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
@@ -0,0 +1,4629 @@
1
+ /**
2
+ * OpenClawIntegration — the framework face of OpenClaw business logic.
3
+ *
4
+ * Legacy AppIntegration implementation retained during migration toward the
5
+ * model described in docs/core-app-architecture.md. The
6
+ * short-term goal remains: OpenClaw-specific knowledge should leave generic
7
+ * framework code and live behind this integration boundary.
8
+ *
9
+ * Why not a huge rewrite in a single pass?
10
+ * A full physical migration of ~6500 lines of OpenClaw code out of
11
+ * `instance-manager.ts` / the Nomad driver / `setup-manager.ts` is a
12
+ * multi-PR undertaking. This file lands the **structural** decoupling
13
+ * (contract + dispatch) today, so:
14
+ *
15
+ * 1. Every framework call site now goes through `getIntegration(integrationKind).X()`
16
+ * with zero string-literal branching on "openclaw" / "hermes".
17
+ * 2. OpenClaw-specific imperative logic that was already contained (Nomad
18
+ * task build, on-disk patches, npm update seed, pairing CLI mapping)
19
+ * is physically moved into this file.
20
+ * 3. Larger pieces that are still entangled inside instance-manager.ts
21
+ * (`saveConfig` with channel-plugin auto-install, `createInstance`
22
+ * with `openclaw.json` seeding) are exposed through integration hooks
23
+ * that framework code calls, and the physical code move from
24
+ * instance-manager.ts into a sibling `openclaw-*.ts` file is a
25
+ * straightforward follow-up PR — the `check-integration-isolation.ts`
26
+ * script blocks new integration-specific code from sneaking back into the
27
+ * framework layer.
28
+ *
29
+ * This is legacy AppIntegration compatibility. New app lifecycle work should
30
+ * follow docs/core-app-architecture.md instead of extending this as the
31
+ * primary app model:
32
+ *
33
+ * 1. Create `src/services/integrations/foo/integration.ts` mirroring this file.
34
+ * 2. Add a side-effect registration import to `src/services/integrations/index.ts`.
35
+ * 3. Add one line to `frontend/src/runtimes/registry.ts`.
36
+ * 4. Done. No `instance-manager.ts` / runtime driver / routes edits.
37
+ */
38
+ import { execFile, execFileSync } from "child_process";
39
+ import { accessSync, chmodSync, chownSync, copyFileSync, cpSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from "fs";
40
+ import { createHash, randomBytes } from "crypto";
41
+ import { homedir, userInfo } from "os";
42
+ import { delimiter, dirname, join, resolve as pathResolve } from "path";
43
+ import { getNomadDriver, getOpenclawDockerImage, JISHUSHELL_HOME, getCoreLanHost, getCorePort, getInternalMcpToken, } from "../../../config.js";
44
+ import { ensureDirContainer, ensureDirHost, writeConfigFile } from "../../../utils/fs.js";
45
+ import { safeWriteJson } from "../../../utils/safe-json.js";
46
+ import { chownToServiceUser, getInstance, getRuntimeEnvFiles, listInstances, normalizePath, notifyConfigChange, resolveServiceUser, updateInstanceMeta, updateEnvFile, } from "../../instances/manager.js";
47
+ import { applyTemporaryBrowserAllowlistToConfigObject, browserlessEndpointAllowedHostname, DEFAULT_BROWSER_ALLOWED_HOSTNAMES, mergeBrowserAllowedHostnames, readTemporaryBrowserAllowedHostnames, stripTemporaryBrowserAllowlistFromConfigObject, } from "../../capabilities/browser-policy.js";
48
+ import { getInstanceDir as framework_instanceDir, instanceMetaPath } from "../../../config.js";
49
+ import { createTask, emitTask, spawnWithTask, getDirSizeMB, npmProgressParser, dockerBuildProgressParser, resolveDockerInvocation, } from "../../setup/setup-manager.js";
50
+ import { DEFAULT_OPENCLAW_DOCKER_IMAGE, setOpenclawDockerImage, OPENCLAW_MODULES, OPENCLAW_PKG_DIR, } from "../../../config.js";
51
+ import { fileURLToPath } from "node:url";
52
+ import { inspectDockerImage, toDockerInspectUserError } from "../../../utils/docker-inspect.js";
53
+ import { getDefaultLlmProvider, normalizeProviderApi } from "../../llm-proxy/providers.js";
54
+ import { bootstrapInstanceProxy, getInstanceConfig as getProxyInstanceConfig, } from "../../llm-proxy/instance-proxy.js";
55
+ import { renderStandaloneMcporterSource } from "./mcporter-lite.js";
56
+ import { resolveNomadJobId } from "../../runtime/job-id.js";
57
+ import { DEFINITION_FILENAME, MANIFEST_FILENAME, RESOLVED_SPEC_FILENAME, } from "../../app-common/paths.js";
58
+ import { registerIntegration } from "../registry.js";
59
+ import { isOwnedByInstance, writeOwnershipMarker } from "../../runtime/ownership-marker.js";
60
+ import { mcporterPath, removeMcporterServers } from "./mcporter.js";
61
+ import { removeOpenclawMcpServers, upsertOpenclawMcpServer, } from "./native-mcp.js";
62
+ // ── Constants physically migrated from the Nomad driver ───────────────
63
+ //
64
+ // These used to live as module-scope constants in the Nomad driver and were
65
+ // read by `buildTaskDocker` / `buildRuntime` helpers. They describe how
66
+ // OpenClaw expects to be launched — container image paths, default command,
67
+ // memory ceilings — and therefore belong to the OpenClaw integration, not the
68
+ // Nomad scheduler.
69
+ const DEFAULT_COMMAND = "/usr/bin/openclaw";
70
+ // Default invocation for a fresh OpenClaw container. `--port 18789` is the
71
+ // process's container-internal listener (= `containerPort`), NOT a host port.
72
+ // Host-side publishing is decided by Core's allocator and persisted into
73
+ // `runtime.ports[].hostPort`; the OpenClaw binary itself always speaks on
74
+ // 18789 inside the container regardless of how Core maps it on the outside.
75
+ const DEFAULT_ARGS = ["gateway", "run", "--port", "18789", "--allow-unconfigured"];
76
+ const DEFAULT_USER = userInfo().username;
77
+ const DEFAULT_CWD = homedir();
78
+ const DEFAULT_ENV = {
79
+ HOME: homedir(),
80
+ TMPDIR: "/tmp",
81
+ PATH: `${homedir()}/.local/bin:${homedir()}/.npm-global/bin:${homedir()}/bin:${homedir()}/.volta/bin:` +
82
+ `${homedir()}/.asdf/shims:${homedir()}/.bun/bin:${homedir()}/.nvm/current/bin:${homedir()}/.fnm/current/bin:` +
83
+ `${homedir()}/.local/share/pnpm:/usr/local/bin:/usr/bin:/bin`,
84
+ };
85
+ const DEFAULT_RESOURCES = { CPU: 500, MemoryMB: 512 };
86
+ // Path inside the openclaw-runtime Docker image where the baked-in openclaw
87
+ // npm package lives. Referenced by the entrypoint shim as the fallback and
88
+ // used by the control-UI "Update now" path through a pre-seeded symlink in
89
+ // $HOME/.npm-global (see ensureOpenclawUpdateSeed below).
90
+ const CONTAINER_IMAGE_PKG_ROOT = "/app/node_modules/openclaw";
91
+ const VALID_USER_RE = /^[a-z0-9._-]{1,32}$/;
92
+ const DOCKER_IMAGE_RE = /^[a-zA-Z0-9][a-zA-Z0-9\-_.:/@]*$/;
93
+ const MAX_DOCKER_IMAGE_NAME_LEN = 256;
94
+ export const OPENCLAW_DEFAULT_CONTAINER_PORT = 18789;
95
+ export const OPENCLAW_PREFERRED_HOST_PORT = OPENCLAW_DEFAULT_CONTAINER_PORT;
96
+ /**
97
+ * Resolve the container-internal listening port the OpenClaw process binds.
98
+ *
99
+ * Belongs to the runtime hot path (called from `OpenClawIntegration.buildRuntime`)
100
+ * and must therefore obey the canonical port model: the only allowed sources
101
+ * are `runtime.ports[].containerPort` (Core's persisted desired runtime) or
102
+ * the OpenClaw binary's documented default.
103
+ */
104
+ function resolveOpenclawContainerPort(rawRuntime) {
105
+ const ports = Array.isArray(rawRuntime?.ports) ? rawRuntime.ports : [];
106
+ for (const port of ports) {
107
+ if (port?.name === "gateway" && Number.isInteger(port?.containerPort) && port.containerPort > 0) {
108
+ return port.containerPort;
109
+ }
110
+ }
111
+ for (const port of ports) {
112
+ if (Number.isInteger(port?.containerPort) && port.containerPort > 0) {
113
+ return port.containerPort;
114
+ }
115
+ }
116
+ return OPENCLAW_DEFAULT_CONTAINER_PORT;
117
+ }
118
+ // ── Capability profile (moved from runtime/instance.ts) ──────────────
119
+ //
120
+ // Describes what the framework should expose for OpenClaw instances. The
121
+ // frontend uses this to decide which tabs render and how the Chat tab looks.
122
+ const DEFAULT_CAPABILITIES = {
123
+ ui: {
124
+ http: true,
125
+ websocket: true,
126
+ chatPanel: "iframe",
127
+ },
128
+ pairing: {
129
+ list: true,
130
+ approve: true,
131
+ revoke: false,
132
+ clearPending: false,
133
+ },
134
+ configEditor: "json",
135
+ configSchema: false,
136
+ customProvider: true,
137
+ pluginInstall: true,
138
+ skills: true,
139
+ mcp: true,
140
+ memory: true,
141
+ backupRestore: true,
142
+ usageStats: true,
143
+ restartlessReload: false,
144
+ messagingPlatforms: ["feishu", "openclaw-weixin"],
145
+ };
146
+ export const OPENCLAW_CONTROL_UI_PROXY_RE = /^\/api\/integrations\/openclaw\/instances\/([a-z0-9][a-z0-9-]{0,62})\/control-ui(?:\/(.*))?$/;
147
+ const OPENCLAW_CONTROL_UI_PUBLIC_PROXY = {
148
+ basePathPattern: OPENCLAW_CONTROL_UI_PROXY_RE,
149
+ authBypass: true,
150
+ websocket: true,
151
+ buildHeaders: ({ match }) => {
152
+ try {
153
+ const cfg = loadEffectiveConfig(match.instanceId);
154
+ const token = cfg?.gateway?.auth?.token;
155
+ if (typeof token === "string" && token.trim()) {
156
+ return { authorization: `Bearer ${token.trim()}` };
157
+ }
158
+ }
159
+ catch {
160
+ // Best effort: if config is unavailable, OpenClaw returns its normal auth error.
161
+ }
162
+ return {};
163
+ },
164
+ resolveTarget: async ({ match, query }) => {
165
+ const im = await lazyIm();
166
+ const port = im.getPrimaryHostPort(match.instanceId);
167
+ const host = await im.getPrimaryHostForInstance(match.instanceId);
168
+ const suffix = match.suffix.replace(/^\/+/, "");
169
+ return {
170
+ protocol: "http",
171
+ host,
172
+ port,
173
+ path: `/${suffix}${query}`,
174
+ };
175
+ },
176
+ };
177
+ export async function ensureOpenclawControlUiAllowedOrigin(instanceId, origin) {
178
+ const normalizedOrigin = origin.trim();
179
+ if (!normalizedOrigin)
180
+ return false;
181
+ const im = await lazyIm();
182
+ const config = im.getStoredConfig(instanceId);
183
+ if (!config)
184
+ return false;
185
+ const gateway = config.gateway ??= {};
186
+ const controlUi = gateway.controlUi ??= {};
187
+ const existing = Array.isArray(controlUi.allowedOrigins)
188
+ ? controlUi.allowedOrigins.map((value) => String(value))
189
+ : [];
190
+ const normalized = new Set(existing.map((value) => value.trim().toLowerCase()).filter(Boolean));
191
+ if (normalized.has("*") || normalized.has(normalizedOrigin.toLowerCase()))
192
+ return false;
193
+ controlUi.allowedOrigins = [...existing.filter((value) => value.trim()), normalizedOrigin];
194
+ await im.saveConfig(instanceId, config);
195
+ return true;
196
+ }
197
+ import { FILES_ROOT } from "../../../config.js";
198
+ function readFileMounts(runtime) {
199
+ const raw = runtime.fileMounts;
200
+ return Array.isArray(raw) ? raw : [];
201
+ }
202
+ /**
203
+ * Build the volume list for the docker driver:
204
+ * 1. The existing openclaw-home self-mount (HOME == container HOME)
205
+ * 2. The root FILES_ROOT bind when any mount has empty path
206
+ * ({"path":"","alias":"","mode":"rw"} — the default for new
207
+ * instances). Without this, in-container plugins (Feishu / WeChat
208
+ * send_file) try `fs.open("/home/.../files/...")` and hit ENOENT
209
+ * because the host path isn't bind-mounted. Verified on pi2
210
+ * 2026-05-11: claw1's drive_resolve_local_path returned a valid
211
+ * abs_path; feishu_im_user_message then ENOENT'd on it.
212
+ * 3. One additional bind per non-root FileMount, host==container so
213
+ * the workspace/{alias} symlink (placed by rebuildWorkspace)
214
+ * resolves identically inside the container.
215
+ *
216
+ * Mode "ro" is enforced by the docker bind option; raw_exec / process
217
+ * modes don't go through this path (the agent runs natively on the host
218
+ * and reads files directly).
219
+ */
220
+ function buildVolumes(openclawHome, runtime) {
221
+ const list = [`${openclawHome}:${openclawHome}:rw`];
222
+ for (const abs of listMountedHostPaths(runtime)) {
223
+ const mode = readFileMounts(runtime).find((m) => !m.path || join(FILES_ROOT, m.path) === abs)?.mode === "ro" ? "ro" : "rw";
224
+ list.push(`${abs}:${abs}:${mode}`);
225
+ }
226
+ return list;
227
+ }
228
+ function listMountedHostPaths(runtime) {
229
+ let rootBound = false;
230
+ const list = [];
231
+ for (const m of readFileMounts(runtime)) {
232
+ if (!m)
233
+ continue;
234
+ if (!m.path) {
235
+ if (rootBound)
236
+ continue;
237
+ list.push(FILES_ROOT);
238
+ rootBound = true;
239
+ continue;
240
+ }
241
+ if (rootBound)
242
+ continue; // root already covers every subtree
243
+ list.push(join(FILES_ROOT, m.path));
244
+ }
245
+ return list;
246
+ }
247
+ // ── Path helpers (physically migrated from instance-manager.ts) ───────
248
+ const INSTANCE_OPENCLAW_HOME_DIRNAME = "openclaw-home";
249
+ const INSTANCE_MODEL_ENV_FILENAME = "model.env";
250
+ const OPENCLAW_STATE_DIRNAME = ".openclaw";
251
+ const OPENCLAW_CONFIG_FILENAME = "openclaw.json";
252
+ function defaultOpenclawHome(instanceId) {
253
+ return join(framework_instanceDir(instanceId), INSTANCE_OPENCLAW_HOME_DIRNAME);
254
+ }
255
+ function openclawHomeFromMetadata(meta, instanceId) {
256
+ const integrationHome = meta?.paths?.integrationHome;
257
+ return typeof integrationHome === "string" && integrationHome.trim()
258
+ ? integrationHome
259
+ : defaultOpenclawHome(instanceId);
260
+ }
261
+ function defaultOpenclawModelEnvFile(instanceId) {
262
+ return join(framework_instanceDir(instanceId), INSTANCE_MODEL_ENV_FILENAME);
263
+ }
264
+ function isPrecreatedManagedAppDir(dir) {
265
+ return existsSync(join(dir, DEFINITION_FILENAME))
266
+ && existsSync(join(dir, RESOLVED_SPEC_FILENAME))
267
+ && existsSync(join(dir, MANIFEST_FILENAME));
268
+ }
269
+ function openclawConfigPath(instanceId, home) {
270
+ const h = home ?? defaultOpenclawHome(instanceId);
271
+ return join(h, OPENCLAW_STATE_DIRNAME, OPENCLAW_CONFIG_FILENAME);
272
+ }
273
+ function legacyOpenclawConfigPath(instanceId, home) {
274
+ const h = home ?? defaultOpenclawHome(instanceId);
275
+ return join(h, OPENCLAW_CONFIG_FILENAME);
276
+ }
277
+ /**
278
+ * Resolve the most relevant openclaw.json path for a SOURCE instance used
279
+ * by the clone_from branch. Prefers the .openclaw/ state dir, falls back
280
+ * to the legacy flat path only as a clone/import boundary reader so clones of
281
+ * old instances still work. Normal runtime config reads call
282
+ * `migrateLegacyOuterConfigOnce()` instead of treating this legacy path as a
283
+ * second source of truth.
284
+ */
285
+ function resolveExistingConfigPath(instanceId) {
286
+ const runtimePath = openclawConfigPath(instanceId);
287
+ if (existsSync(runtimePath))
288
+ return runtimePath;
289
+ const legacy = legacyOpenclawConfigPath(instanceId);
290
+ if (existsSync(legacy))
291
+ return legacy;
292
+ return runtimePath;
293
+ }
294
+ function migrateLegacyOuterConfigOnce(instanceId) {
295
+ const runtimePath = openclawConfigPath(instanceId);
296
+ const legacyPath = legacyOpenclawConfigPath(instanceId);
297
+ if (!existsSync(legacyPath))
298
+ return;
299
+ // Step 6 one-shot fallback reader: historical OpenClaw installs stored
300
+ // config at `$OPENCLAW_HOME/openclaw.json`. Normal runtime must now read and
301
+ // write only `$OPENCLAW_HOME/.openclaw/openclaw.json`; this boundary converts
302
+ // old disk state into the canonical path and removes the old mirror so it
303
+ // cannot resurrect fields on a later save.
304
+ if (!existsSync(runtimePath)) {
305
+ ensureDirContainer(dirname(runtimePath));
306
+ copyFileSync(legacyPath, runtimePath);
307
+ chownToServiceUser(runtimePath);
308
+ }
309
+ rmSync(legacyPath, { force: true });
310
+ }
311
+ const OPENCLAW_BROWSER_SESSION_INDEX_RELATIVE_PATH = [
312
+ OPENCLAW_STATE_DIRNAME,
313
+ "agents",
314
+ "main",
315
+ "sessions",
316
+ "sessions.json",
317
+ ];
318
+ const OPENCLAW_BROWSER_SESSION_SUMMARY_MAX_FILE_SIZE = 10 * 1024 * 1024;
319
+ function isBrowserSummaryRecord(value) {
320
+ return !!value && typeof value === "object" && !Array.isArray(value);
321
+ }
322
+ function normalizeBrowserSummaryText(value) {
323
+ return typeof value === "string" && value.trim() ? value.trim() : null;
324
+ }
325
+ function normalizeBrowserSummaryTimestamp(value) {
326
+ const text = normalizeBrowserSummaryText(value);
327
+ if (!text)
328
+ return null;
329
+ const parsed = new Date(text);
330
+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
331
+ }
332
+ function unavailableBrowserConsumerActivitySummary() {
333
+ return {
334
+ recentSession: {
335
+ state: "unavailable",
336
+ sessionKey: null,
337
+ lastMessageAt: null,
338
+ origin: null,
339
+ channel: null,
340
+ },
341
+ lastBrowserAttempt: {
342
+ state: "unavailable",
343
+ action: null,
344
+ profile: null,
345
+ url: null,
346
+ error: null,
347
+ timestamp: null,
348
+ },
349
+ };
350
+ }
351
+ function noSessionsBrowserConsumerActivitySummary() {
352
+ return {
353
+ recentSession: {
354
+ state: "no_sessions",
355
+ sessionKey: null,
356
+ lastMessageAt: null,
357
+ origin: null,
358
+ channel: null,
359
+ },
360
+ lastBrowserAttempt: {
361
+ state: "none",
362
+ action: null,
363
+ profile: null,
364
+ url: null,
365
+ error: null,
366
+ timestamp: null,
367
+ },
368
+ };
369
+ }
370
+ function isInsideResolvedHome(resolvedHome, resolvedPath) {
371
+ return resolvedPath === resolvedHome || resolvedPath.startsWith(`${resolvedHome}/`);
372
+ }
373
+ function resolveSafeOpenclawBrowserSummaryFile(resolvedHome, candidatePath) {
374
+ if (!candidatePath || !existsSync(candidatePath))
375
+ return null;
376
+ try {
377
+ const resolvedPath = realpathSync(candidatePath);
378
+ if (!isInsideResolvedHome(resolvedHome, resolvedPath))
379
+ return null;
380
+ const stats = statSync(resolvedPath);
381
+ if (!stats.isFile() || stats.size > OPENCLAW_BROWSER_SESSION_SUMMARY_MAX_FILE_SIZE)
382
+ return null;
383
+ return resolvedPath;
384
+ }
385
+ catch {
386
+ return null;
387
+ }
388
+ }
389
+ function readOpenclawBrowserSessionIndex(openclawHome) {
390
+ let resolvedHome;
391
+ try {
392
+ resolvedHome = realpathSync(openclawHome);
393
+ }
394
+ catch {
395
+ return "unavailable";
396
+ }
397
+ const sessionsIndex = join(openclawHome, ...OPENCLAW_BROWSER_SESSION_INDEX_RELATIVE_PATH);
398
+ if (!existsSync(sessionsIndex))
399
+ return "no_sessions";
400
+ const resolvedIndex = resolveSafeOpenclawBrowserSummaryFile(resolvedHome, sessionsIndex);
401
+ if (!resolvedIndex)
402
+ return "unavailable";
403
+ let raw;
404
+ try {
405
+ raw = JSON.parse(readFileSync(resolvedIndex, "utf-8"));
406
+ }
407
+ catch {
408
+ return "unavailable";
409
+ }
410
+ if (!isBrowserSummaryRecord(raw))
411
+ return "unavailable";
412
+ return {
413
+ resolvedHome,
414
+ sessions: Object.entries(raw).map(([sessionKey, sessionMeta]) => ({
415
+ sessionKey,
416
+ sessionFile: normalizeBrowserSummaryText(sessionMeta?.sessionFile),
417
+ origin: normalizeBrowserSummaryText(sessionMeta?.origin?.label),
418
+ channel: normalizeBrowserSummaryText(sessionMeta?.origin?.provider),
419
+ })),
420
+ };
421
+ }
422
+ function browserAttemptIsNewer(candidate, current) {
423
+ const candidateTs = candidate.timestamp ? Date.parse(candidate.timestamp) : Number.NaN;
424
+ const currentTs = current.timestamp ? Date.parse(current.timestamp) : Number.NaN;
425
+ const safeCandidateTs = Number.isFinite(candidateTs) ? candidateTs : Number.NEGATIVE_INFINITY;
426
+ const safeCurrentTs = Number.isFinite(currentTs) ? currentTs : Number.NEGATIVE_INFINITY;
427
+ if (safeCandidateTs !== safeCurrentTs)
428
+ return safeCandidateTs > safeCurrentTs;
429
+ if (current.state === "none" && candidate.state !== "none")
430
+ return true;
431
+ return false;
432
+ }
433
+ function summarizeOpenclawBrowserAttemptFromContent(content) {
434
+ const toolCalls = new Map();
435
+ let lastStatusProfile = null;
436
+ let lastAttempt = {
437
+ state: "none",
438
+ action: null,
439
+ profile: null,
440
+ url: null,
441
+ error: null,
442
+ timestamp: null,
443
+ };
444
+ for (const line of content.split("\n")) {
445
+ if (!line.trim())
446
+ continue;
447
+ let entry;
448
+ try {
449
+ entry = JSON.parse(line);
450
+ }
451
+ catch {
452
+ continue;
453
+ }
454
+ if (!isBrowserSummaryRecord(entry) || entry.type !== "message")
455
+ continue;
456
+ const message = isBrowserSummaryRecord(entry.message) ? entry.message : {};
457
+ const timestamp = normalizeBrowserSummaryTimestamp(entry.timestamp);
458
+ const contentBlocks = Array.isArray(message.content) ? message.content : [];
459
+ for (const block of contentBlocks) {
460
+ if (!isBrowserSummaryRecord(block) || block.type !== "toolCall" || block.name !== "browser")
461
+ continue;
462
+ const args = isBrowserSummaryRecord(block.arguments) ? block.arguments : {};
463
+ toolCalls.set(String(block.id ?? ""), {
464
+ action: normalizeBrowserSummaryText(args.action),
465
+ profile: normalizeBrowserSummaryText(args.profile),
466
+ url: normalizeBrowserSummaryText(args.url),
467
+ timestamp,
468
+ });
469
+ }
470
+ if (message.role !== "toolResult" || message.toolName !== "browser")
471
+ continue;
472
+ const call = toolCalls.get(String(message.toolCallId ?? "")) ?? {
473
+ action: null,
474
+ profile: null,
475
+ url: null,
476
+ timestamp,
477
+ };
478
+ const details = isBrowserSummaryRecord(message.details) ? message.details : {};
479
+ const statusProfile = normalizeBrowserSummaryText(details.profile);
480
+ if (call.action === "status" && statusProfile) {
481
+ lastStatusProfile = statusProfile;
482
+ lastAttempt = {
483
+ state: "status_only",
484
+ action: call.action,
485
+ profile: statusProfile,
486
+ url: call.url,
487
+ error: null,
488
+ timestamp: timestamp ?? call.timestamp,
489
+ };
490
+ continue;
491
+ }
492
+ if (call.action !== "open" && call.action !== "navigate")
493
+ continue;
494
+ const error = normalizeBrowserSummaryText(details.error);
495
+ const profile = call.profile ?? statusProfile;
496
+ const ok = typeof details.ok === "boolean" ? details.ok : !error;
497
+ const state = error
498
+ ? (profile === "openclaw"
499
+ && lastStatusProfile === "browserless"
500
+ && error.includes("No supported browser found")
501
+ ? "wrong_profile_selected"
502
+ : "browser_failed_before_session")
503
+ : (ok ? "browser_open_succeeded" : "browser_failed_before_session");
504
+ lastAttempt = {
505
+ state,
506
+ action: call.action,
507
+ profile,
508
+ url: call.url ?? normalizeBrowserSummaryText(details.url),
509
+ error,
510
+ timestamp: timestamp ?? call.timestamp,
511
+ };
512
+ }
513
+ return lastAttempt;
514
+ }
515
+ export function summarizeRecentOpenclawBrowserSession(instanceId) {
516
+ const openclawHome = openclawHomeFromMetadata(getInstance(instanceId), instanceId);
517
+ if (!openclawHome)
518
+ return unavailableBrowserConsumerActivitySummary();
519
+ const index = readOpenclawBrowserSessionIndex(openclawHome);
520
+ if (index === "unavailable")
521
+ return unavailableBrowserConsumerActivitySummary();
522
+ if (index === "no_sessions")
523
+ return noSessionsBrowserConsumerActivitySummary();
524
+ const summary = noSessionsBrowserConsumerActivitySummary();
525
+ for (const session of index.sessions) {
526
+ const resolvedSessionFile = resolveSafeOpenclawBrowserSummaryFile(index.resolvedHome, session.sessionFile);
527
+ if (!resolvedSessionFile)
528
+ continue;
529
+ let content;
530
+ try {
531
+ content = readFileSync(resolvedSessionFile, "utf-8");
532
+ }
533
+ catch {
534
+ continue;
535
+ }
536
+ let lastMessageAt = null;
537
+ for (const line of content.split("\n")) {
538
+ if (!line.trim())
539
+ continue;
540
+ let entry;
541
+ try {
542
+ entry = JSON.parse(line);
543
+ }
544
+ catch {
545
+ continue;
546
+ }
547
+ if (!isBrowserSummaryRecord(entry) || entry.type !== "message")
548
+ continue;
549
+ const timestamp = normalizeBrowserSummaryTimestamp(entry.timestamp);
550
+ if (timestamp)
551
+ lastMessageAt = timestamp;
552
+ }
553
+ if (lastMessageAt && (summary.recentSession.state !== "available"
554
+ || !summary.recentSession.lastMessageAt
555
+ || summary.recentSession.lastMessageAt < lastMessageAt)) {
556
+ summary.recentSession = {
557
+ state: "available",
558
+ sessionKey: session.sessionKey,
559
+ lastMessageAt,
560
+ origin: session.origin,
561
+ channel: session.channel,
562
+ };
563
+ }
564
+ const attempt = summarizeOpenclawBrowserAttemptFromContent(content);
565
+ if (browserAttemptIsNewer(attempt, summary.lastBrowserAttempt)) {
566
+ summary.lastBrowserAttempt = attempt;
567
+ }
568
+ }
569
+ return summary;
570
+ }
571
+ // ── Runtime + config defaults (physically migrated) ───────────────────
572
+ function resolveOpenclawBin() {
573
+ const candidates = [
574
+ join(JISHUSHELL_HOME, "packages", "openclaw", "bin", "openclaw"),
575
+ "/usr/local/bin/openclaw",
576
+ "/usr/bin/openclaw",
577
+ ];
578
+ for (const p of candidates) {
579
+ if (existsSync(p)) {
580
+ try {
581
+ chmodSync(p, 0o755);
582
+ }
583
+ catch {
584
+ /* best effort — may be a symlink */
585
+ }
586
+ try {
587
+ const real = realpathSync(p);
588
+ if (real !== p)
589
+ chmodSync(real, 0o755);
590
+ }
591
+ catch {
592
+ /* best effort */
593
+ }
594
+ return p;
595
+ }
596
+ }
597
+ // Fallback: scan $PATH for user-installed openclaw (nvm, homebrew, etc.)
598
+ // Uses in-process lookup instead of spawning `which` for security and performance.
599
+ const fromPath = findExecutableOnPath("openclaw");
600
+ if (fromPath)
601
+ return fromPath;
602
+ return candidates[0]; // will fail with clear error at spawn
603
+ }
604
+ /**
605
+ * Search $PATH for an executable by name. Returns the first match or null.
606
+ * Does not chmod the result — PATH-discovered binaries are not managed by JishuShell.
607
+ */
608
+ function findExecutableOnPath(name) {
609
+ const pathEnv = process.env.PATH || "";
610
+ for (const dir of pathEnv.split(delimiter)) {
611
+ if (!dir)
612
+ continue;
613
+ const candidate = join(dir, name);
614
+ try {
615
+ accessSync(candidate, constants.X_OK);
616
+ return candidate;
617
+ }
618
+ catch {
619
+ /* not found or not executable in this dir */
620
+ }
621
+ }
622
+ return null;
623
+ }
624
+ function starterConfig() {
625
+ const dp = getDefaultLlmProvider();
626
+ let providerName = "minimax";
627
+ let providerConfig = {
628
+ baseUrl: "https://api.minimaxi.com/v1",
629
+ api: "openai-completions",
630
+ models: [{ id: "MiniMax-M2.7", name: "MiniMax M2.7", contextWindow: 204800 }],
631
+ };
632
+ let defaultModel = "minimax/MiniMax-M2.7";
633
+ if (dp?.id) {
634
+ providerName = dp.id;
635
+ providerConfig = {
636
+ baseUrl: dp.baseUrl,
637
+ api: normalizeProviderApi(dp.api),
638
+ ...(dp.authHeader ? { authHeader: true } : {}),
639
+ models: dp.models || [],
640
+ };
641
+ const modelId = dp.selectedModelId || dp.models?.[0]?.id || "";
642
+ defaultModel = `${providerName}/${modelId}`;
643
+ }
644
+ const config = {
645
+ models: { providers: { [providerName]: providerConfig } },
646
+ agents: { defaults: { model: defaultModel, models: { [defaultModel]: {} } } },
647
+ channels: {},
648
+ gateway: {
649
+ mode: "local",
650
+ auth: { mode: "token", token: randomBytes(24).toString("hex") },
651
+ controlUi: { dangerouslyDisableDeviceAuth: true },
652
+ },
653
+ plugins: { entries: { feishu: { enabled: false } } },
654
+ };
655
+ if (dp?.id) {
656
+ config["x-jishushell"] = {
657
+ proxy: {
658
+ upstream: {
659
+ providerId: dp.id,
660
+ baseUrl: dp.baseUrl,
661
+ api: normalizeProviderApi(dp.api),
662
+ authHeader: dp.authHeader === true || typeof dp.authHeader === "string",
663
+ models: dp.models || [],
664
+ selectedModelId: dp.selectedModelId || dp.models?.[0]?.id || "",
665
+ hasApiKey: !!dp.apiKey,
666
+ },
667
+ },
668
+ };
669
+ }
670
+ return config;
671
+ }
672
+ async function finalizeOpenclawCreatedInstance(instanceId, createArgs) {
673
+ const appSpec = createArgs?.appSpec;
674
+ const cloneFrom = createArgs?.cloneFrom;
675
+ const cloneOptions = createArgs?.cloneOptions;
676
+ const d = framework_instanceDir(instanceId);
677
+ const im = await lazyIm();
678
+ const home = openclawHomeFromMetadata(getInstance(instanceId), instanceId);
679
+ const envFiles = getRuntimeEnvFiles(instanceId);
680
+ const runtime = im.getInstanceRuntime(instanceId);
681
+ const configPath = openclawConfigPath(instanceId, home);
682
+ for (const ef of envFiles) {
683
+ if (!existsSync(ef))
684
+ writeConfigFile(ef, "");
685
+ }
686
+ try {
687
+ const runtimeUser = runtime?.user;
688
+ if (runtimeUser && runtimeUser !== userInfo().username) {
689
+ for (const ef of envFiles) {
690
+ execFileSync("chown", [runtimeUser, ef], { timeout: 5000 });
691
+ }
692
+ }
693
+ }
694
+ catch {
695
+ /* ignore - same user or no permission to chown */
696
+ }
697
+ ensureDirContainer(dirname(configPath));
698
+ if (cloneFrom && !existsSync(configPath)) {
699
+ const srcConfig = resolveExistingConfigPath(cloneFrom);
700
+ if (existsSync(srcConfig)) {
701
+ try {
702
+ const cloned = JSON.parse(readFileSync(srcConfig, "utf-8"));
703
+ const providers = cloned?.models?.providers;
704
+ if (providers) {
705
+ for (const [pid, prov] of Object.entries(providers)) {
706
+ if (typeof prov?.baseUrl === "string" &&
707
+ prov.baseUrl.includes("/proxy/")) {
708
+ delete providers[pid];
709
+ continue;
710
+ }
711
+ if (typeof prov === "object" && prov !== null) {
712
+ delete prov.apiKey;
713
+ }
714
+ }
715
+ }
716
+ const defaultModel = cloned?.agents?.defaults?.model;
717
+ if (typeof defaultModel === "string" &&
718
+ (defaultModel.startsWith("jsproxy/") || defaultModel.startsWith("js-"))) {
719
+ delete cloned.agents.defaults.model;
720
+ }
721
+ stripImBindings(cloned);
722
+ if (!cloned.gateway)
723
+ cloned.gateway = {};
724
+ if (!cloned.gateway.auth)
725
+ cloned.gateway.auth = { mode: "token" };
726
+ cloned.gateway.auth.token = randomBytes(24).toString("hex");
727
+ const subdirs = ["extensions", "workspace"];
728
+ if (cloneOptions?.include_memory !== false) {
729
+ const memDir = join(dirname(srcConfig), "memory");
730
+ if (existsSync(memDir))
731
+ subdirs.push("memory");
732
+ }
733
+ if (cloneOptions?.include_sessions) {
734
+ const sessDir = join(dirname(srcConfig), "agents");
735
+ if (existsSync(sessDir))
736
+ subdirs.push("agents");
737
+ }
738
+ for (const subdir of subdirs) {
739
+ const srcDir = join(dirname(srcConfig), subdir);
740
+ const dstDir = join(dirname(configPath), subdir);
741
+ if (existsSync(srcDir) && !existsSync(dstDir)) {
742
+ try {
743
+ cpSync(srcDir, dstDir, { recursive: true });
744
+ }
745
+ catch {
746
+ /* best effort */
747
+ }
748
+ }
749
+ }
750
+ writeConfigFile(configPath, JSON.stringify(cloned, null, 2));
751
+ const srcMeta = getInstance(cloneFrom);
752
+ const srcXj = srcMeta?.["x-jishushell"];
753
+ if (srcXj?.proxy?.upstream) {
754
+ const dstXj = structuredClone({ proxy: { upstream: srcXj.proxy.upstream } });
755
+ delete dstXj.proxy.upstream.apiKey;
756
+ updateInstanceMeta(instanceId, { "x-jishushell": dstXj });
757
+ }
758
+ }
759
+ catch (error) {
760
+ throw new Error(`Cannot clone OpenClaw config from ${cloneFrom}: ${error?.message ?? error}`);
761
+ }
762
+ }
763
+ }
764
+ if (!existsSync(configPath)) {
765
+ writeConfigFile(configPath, JSON.stringify(starterConfig(), null, 2));
766
+ const dp = getDefaultLlmProvider();
767
+ if (dp?.apiKey && dp?.id && envFiles.length) {
768
+ const providerEnv = join(dirname(envFiles[0]), "provider.env");
769
+ updateEnvFile(providerEnv, { UPSTREAM_API_KEY: dp.apiKey });
770
+ }
771
+ }
772
+ const runtimeOverlay = appSpec?.runtime;
773
+ const overlayDefaults = runtimeOverlay?.defaults
774
+ ?? runtimeOverlay?.config_defaults;
775
+ if (overlayDefaults && existsSync(configPath)) {
776
+ try {
777
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
778
+ const defaults = overlayDefaults;
779
+ for (const [key, value] of Object.entries(defaults)) {
780
+ if (typeof value === "object" &&
781
+ value !== null &&
782
+ !Array.isArray(value) &&
783
+ typeof existing[key] === "object" &&
784
+ existing[key] !== null) {
785
+ existing[key] = { ...existing[key], ...value };
786
+ }
787
+ else {
788
+ existing[key] = value;
789
+ }
790
+ }
791
+ writeConfigFile(configPath, JSON.stringify(existing, null, 2));
792
+ }
793
+ catch {
794
+ /* ignore merge errors */
795
+ }
796
+ }
797
+ const overlaySkills = Array.isArray(runtimeOverlay?.skills)
798
+ ? runtimeOverlay.skills
799
+ : null;
800
+ if (overlaySkills) {
801
+ try {
802
+ const skillsDir = join(dirname(configPath), "skills");
803
+ ensureDirContainer(skillsDir);
804
+ const skillMeta = join(skillsDir, ".app-skills.json");
805
+ safeWriteJson(skillMeta, {
806
+ instanceId,
807
+ definitionId: appSpec?.id ?? instanceId,
808
+ skills: overlaySkills,
809
+ });
810
+ }
811
+ catch {
812
+ /* ignore */
813
+ }
814
+ }
815
+ // Clones intentionally inherit the source instance's Core-managed upstream
816
+ // credential. provider.env contains only the AES-encrypted upstream key and
817
+ // is never exposed to the OpenClaw process; the clone still gets its own
818
+ // JSPROXY_API_KEY in model.env below.
819
+ if (cloneFrom && envFiles.length) {
820
+ const srcEnvFiles = getRuntimeEnvFiles(cloneFrom);
821
+ const srcEnvFile = srcEnvFiles[0];
822
+ const dstEnvFile = envFiles[0];
823
+ if (srcEnvFile) {
824
+ const srcProvider = join(dirname(srcEnvFile), "provider.env");
825
+ const dstProvider = join(dirname(dstEnvFile), "provider.env");
826
+ if (existsSync(srcProvider) && !existsSync(dstProvider)) {
827
+ copyFileSync(srcProvider, dstProvider);
828
+ }
829
+ }
830
+ }
831
+ try {
832
+ await bootstrapInstanceProxy(instanceId);
833
+ }
834
+ catch (e) {
835
+ console.warn(`[openclaw] Proxy bootstrap for ${instanceId} deferred: ${e.message}`);
836
+ }
837
+ const svcUser = resolveServiceUser();
838
+ if (svcUser) {
839
+ try {
840
+ execFileSync("chown", ["-R", `${svcUser.uid}:${svcUser.gid}`, d], {
841
+ timeout: 10_000,
842
+ });
843
+ if (!home.startsWith(d + "/") && existsSync(home)) {
844
+ execFileSync("chown", ["-R", `${svcUser.uid}:${svcUser.gid}`, home], {
845
+ timeout: 10_000,
846
+ });
847
+ }
848
+ }
849
+ catch (e) {
850
+ console.warn(`[openclaw] chown for ${instanceId} failed:`, e.message);
851
+ }
852
+ }
853
+ }
854
+ // ── Nomad-patching helpers (migrated from the runtime driver) ──────────
855
+ /**
856
+ * In docker bridge mode, 127.0.0.1 inside the container resolves to the
857
+ * container's own loopback, not the host. Rewrite the jsproxy provider
858
+ * baseUrl in openclaw.json to use host.docker.internal instead.
859
+ */
860
+ function patchJsproxyBaseUrl(configPath) {
861
+ try {
862
+ const raw = readFileSync(configPath, "utf-8");
863
+ const patched = raw.replace(/http:\/\/127\.0\.0\.1:(\d+)\/proxy/g, `http://host.docker.internal:$1/proxy`);
864
+ if (patched !== raw) {
865
+ writeConfigFile(configPath, patched);
866
+ console.log(`[openclaw] Patched jsproxy baseUrl in ${configPath} (127.0.0.1 → host.docker.internal)`);
867
+ }
868
+ }
869
+ catch (e) {
870
+ console.warn(`[openclaw] Failed to patch jsproxy baseUrl in ${configPath}: ${e.message}`);
871
+ }
872
+ }
873
+ /** Known private/internal hostnames used by JishuShell's local proxy. */
874
+ const PRIVATE_NETWORK_HOSTS = ["host.docker.internal", "127.0.0.1", "localhost", "0.0.0.0"];
875
+ export function isPrivateNetworkBaseUrl(baseUrl) {
876
+ try {
877
+ const url = new URL(baseUrl);
878
+ if (PRIVATE_NETWORK_HOSTS.includes(url.hostname))
879
+ return true;
880
+ if (url.hostname.startsWith("10."))
881
+ return true;
882
+ if (url.hostname.startsWith("192.168."))
883
+ return true;
884
+ // RFC 1918: 172.16.0.0/12 → 172.16.x.x through 172.31.x.x
885
+ const m = url.hostname.match(/^172\.(\d+)\./);
886
+ if (m) {
887
+ const second = parseInt(m[1], 10);
888
+ if (second >= 16 && second <= 31)
889
+ return true;
890
+ }
891
+ return false;
892
+ }
893
+ catch {
894
+ return false;
895
+ }
896
+ }
897
+ /**
898
+ * Ensure `request.allowPrivateNetwork: true` is set on providers whose baseUrl
899
+ * targets a private/internal host (e.g. host.docker.internal). Without this,
900
+ * OpenClaw's SSRF guard blocks requests to the JishuShell local proxy.
901
+ */
902
+ export function patchPrivateNetworkAllowFlag(configPath) {
903
+ try {
904
+ const raw = readFileSync(configPath, "utf-8");
905
+ const config = JSON.parse(raw);
906
+ const providers = config?.models?.providers;
907
+ if (!providers || typeof providers !== "object")
908
+ return;
909
+ let changed = false;
910
+ for (const [, provider] of Object.entries(providers)) {
911
+ if (typeof provider !== "object" || provider === null)
912
+ continue;
913
+ const p = provider;
914
+ if (typeof p.baseUrl !== "string")
915
+ continue;
916
+ if (!isPrivateNetworkBaseUrl(p.baseUrl))
917
+ continue;
918
+ if (p.request?.allowPrivateNetwork === true)
919
+ continue;
920
+ p.request = { ...(p.request || {}), allowPrivateNetwork: true };
921
+ changed = true;
922
+ }
923
+ if (changed) {
924
+ writeConfigFile(configPath, JSON.stringify(config, null, 2));
925
+ console.log(`[openclaw] Patched request.allowPrivateNetwork in ${configPath} for private-network providers`);
926
+ }
927
+ }
928
+ catch (e) {
929
+ console.warn(`[openclaw] Failed to patch allowPrivateNetwork in ${configPath}: ${e.message}`);
930
+ }
931
+ }
932
+ /**
933
+ * Docker bridge port publishing cannot reach a process that only binds the
934
+ * container loopback. Normalize default/loopback gateway binds to `lan` so
935
+ * Nomad's published host port can reach the gateway.
936
+ */
937
+ function patchDockerBridgeGatewayBind(configPath) {
938
+ try {
939
+ const raw = readFileSync(configPath, "utf-8");
940
+ const parsed = JSON.parse(raw);
941
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
942
+ return;
943
+ const gatewayRaw = parsed.gateway;
944
+ const gateway = gatewayRaw && typeof gatewayRaw === "object" && !Array.isArray(gatewayRaw)
945
+ ? gatewayRaw
946
+ : (parsed.gateway = {});
947
+ const bind = typeof gateway.bind === "string" ? gateway.bind.trim() : "";
948
+ if (bind && bind !== "loopback")
949
+ return;
950
+ gateway.bind = "lan";
951
+ const next = JSON.stringify(parsed, null, 2);
952
+ const output = raw.endsWith("\n") ? `${next}\n` : next;
953
+ if (output === raw)
954
+ return;
955
+ writeConfigFile(configPath, output);
956
+ console.log(`[openclaw] Normalized gateway.bind to "lan" in ${configPath} for Docker bridge networking`);
957
+ }
958
+ catch (e) {
959
+ console.warn(`[openclaw] Failed to patch gateway.bind in ${configPath}: ${e.message}`);
960
+ }
961
+ }
962
+ /**
963
+ * Ensure the `llm-agent` capability advertised by openclaw-*.yaml works for
964
+ * every instance, including ones created before this code shipped: enable
965
+ * OpenClaw's OpenAI-compatible endpoints in `openclaw.json` on every start.
966
+ *
967
+ * Runs idempotently next to `patchDockerBridgeGatewayBind`. The OpenAI
968
+ * routes (`/v1/chat/completions`, `/v1/responses`, `/v1/models`,
969
+ * `/v1/embeddings`) live in openclaw's bundled server.impl and are gated
970
+ * behind `gateway.http.endpoints.{chatCompletions,responses}.enabled` —
971
+ * default false, so a fresh OpenClaw install would 404 those paths even
972
+ * though OpenWebUI binds it through the connections page.
973
+ */
974
+ export function patchOpenAIEndpointsEnabled(configPath) {
975
+ try {
976
+ const raw = readFileSync(configPath, "utf-8");
977
+ const parsed = JSON.parse(raw);
978
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
979
+ return;
980
+ const root = parsed;
981
+ const gateway = root.gateway && typeof root.gateway === "object" && !Array.isArray(root.gateway)
982
+ ? root.gateway
983
+ : (root.gateway = {});
984
+ const http = gateway.http && typeof gateway.http === "object" && !Array.isArray(gateway.http)
985
+ ? gateway.http
986
+ : (gateway.http = {});
987
+ const endpoints = http.endpoints && typeof http.endpoints === "object" && !Array.isArray(http.endpoints)
988
+ ? http.endpoints
989
+ : (http.endpoints = {});
990
+ let changed = false;
991
+ for (const key of ["chatCompletions", "responses"]) {
992
+ const ep = endpoints[key] && typeof endpoints[key] === "object" && !Array.isArray(endpoints[key])
993
+ ? endpoints[key]
994
+ : (endpoints[key] = {});
995
+ if (ep.enabled !== true) {
996
+ ep.enabled = true;
997
+ changed = true;
998
+ }
999
+ }
1000
+ if (!changed)
1001
+ return;
1002
+ const next = JSON.stringify(parsed, null, 2);
1003
+ const output = raw.endsWith("\n") ? `${next}\n` : next;
1004
+ writeConfigFile(configPath, output);
1005
+ console.log(`[openclaw] Enabled gateway.http.endpoints.{chatCompletions,responses} in ${configPath} for llm-agent capability`);
1006
+ }
1007
+ catch (e) {
1008
+ console.warn(`[openclaw] Failed to patch OpenAI endpoints in ${configPath}: ${e.message}`);
1009
+ }
1010
+ }
1011
+ /**
1012
+ * Deep-merge a SearXNG connection into an OpenClaw config file at `configPath`.
1013
+ *
1014
+ * Writes both halves of the wiring required for the `web_search` tool to use
1015
+ * the registry-resolved SearXNG instance:
1016
+ *
1017
+ * plugins.entries.searxng.enabled = true
1018
+ * plugins.entries.searxng.config.webSearch.baseUrl = baseUrl
1019
+ * tools.web.search.provider = "searxng"
1020
+ *
1021
+ * The provider selector is required because OpenClaw's built-in default is
1022
+ * `"brave"`; without it the tool fails with `missing_brave_api_key` even when
1023
+ * the searxng plugin is otherwise correctly configured (verified on Pi
1024
+ * 2026-04-29: claw11 had the plugin block right but the selector unset).
1025
+ *
1026
+ * Why a partial deep-merge instead of `saveNativeConfig`: the latter is
1027
+ * destructive — it replaces top-level keys wholesale and only preserves a
1028
+ * hardcoded subset (`plugins.installs`, `plugins.entries` per-key, partial
1029
+ * `channels` merge). A partial patch through it would wipe `models.providers`
1030
+ * / `agents.defaults` / etc., bricking the instance with `No API key found
1031
+ * for provider "openai"` on the next chat. So we read, merge, write back.
1032
+ *
1033
+ * No-op when the config file is absent (instance not yet started).
1034
+ */
1035
+ export function applySearxngConnectionToConfig(configPath, baseUrl) {
1036
+ if (!existsSync(configPath))
1037
+ return;
1038
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
1039
+ existing.plugins = existing.plugins ?? {};
1040
+ existing.plugins.entries = existing.plugins.entries ?? {};
1041
+ const prior = existing.plugins.entries.searxng ?? {};
1042
+ existing.plugins.entries.searxng = {
1043
+ ...prior,
1044
+ enabled: true,
1045
+ config: {
1046
+ ...(prior.config ?? {}),
1047
+ webSearch: {
1048
+ ...((prior.config ?? {}).webSearch ?? {}),
1049
+ baseUrl,
1050
+ },
1051
+ },
1052
+ };
1053
+ existing.tools = existing.tools ?? {};
1054
+ existing.tools.web = existing.tools.web ?? {};
1055
+ existing.tools.web.search = existing.tools.web.search ?? {};
1056
+ existing.tools.web.search.provider = "searxng";
1057
+ safeWriteJson(configPath, existing);
1058
+ }
1059
+ /**
1060
+ * Counterpart to `applySearxngConnectionToConfig` — invoked when the user
1061
+ * unbinds the SEARCH slot in the Connections tab. Without this, unbinding
1062
+ * left the plugin entry enabled with a baseUrl pointing at the now-gone
1063
+ * searxng provider, and `tools.web.search.provider="searxng"` kept routing
1064
+ * the agent's `web_search` tool through that dead URL on every chat.
1065
+ *
1066
+ * Conservative cleanup so a future re-bind (or user-customized plugin
1067
+ * settings) survives:
1068
+ * - flip the searxng plugin to enabled:false (don't delete the entry —
1069
+ * user may have hand-tuned it and we want re-bind to re-enable cheaply)
1070
+ * - drop the stale `webSearch.baseUrl` so nothing reads it as still-live
1071
+ * - clear `tools.web.search.provider` so the runtime falls back to its
1072
+ * built-in default (which today errors out with `missing_brave_api_key`
1073
+ * — the right outcome: search was unbound, web_search shouldn't work)
1074
+ *
1075
+ * No-op when the config file is absent.
1076
+ */
1077
+ export function clearSearxngConnectionFromConfig(configPath) {
1078
+ if (!existsSync(configPath))
1079
+ return;
1080
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
1081
+ const sx = existing?.plugins?.entries?.searxng;
1082
+ if (sx && typeof sx === "object") {
1083
+ sx.enabled = false;
1084
+ if (sx.config?.webSearch && typeof sx.config.webSearch === "object") {
1085
+ delete sx.config.webSearch.baseUrl;
1086
+ }
1087
+ }
1088
+ if (existing?.tools?.web?.search && typeof existing.tools.web.search === "object") {
1089
+ delete existing.tools.web.search.provider;
1090
+ }
1091
+ safeWriteJson(configPath, existing);
1092
+ }
1093
+ /** Profile name used in `browser.profiles` for jishushell-managed Browserless bindings. */
1094
+ const BROWSERLESS_PROFILE = "browserless";
1095
+ /**
1096
+ * Default `color` for the jishushell-managed browserless profile. OpenClaw's
1097
+ * profile schema treats `color` as required (the field shows up as the
1098
+ * profile chip tint in the UI); omitting it triggers
1099
+ * "browser.profiles.browserless.color: Invalid input: expected string,
1100
+ * received undefined"
1101
+ * on every config reload, which crashloops the gateway. Verified against
1102
+ * the runtime image `ghcr.io/x-aijishu/openclaw-runtime:2026.4.15` on Pi 2
1103
+ * (2026-05-07). The tone is Browserless brand green; users can override it
1104
+ * once and we preserve their override on re-bind via the `prior` spread.
1105
+ */
1106
+ const BROWSERLESS_DEFAULT_COLOR = "#00AA66";
1107
+ /**
1108
+ * Deep-merge a Browserless CDP connection into an OpenClaw config file at
1109
+ * `configPath`. Mirrors `applySearxngConnectionToConfig` for the browser slot.
1110
+ *
1111
+ * Writes:
1112
+ * browser.profiles.browserless.cdpUrl = cdpUrl // ws:// or wss://
1113
+ * browser.profiles.browserless.attachOnly = true // since v2026.3.2
1114
+ * browser.profiles.browserless.color = "#00AA66" // required by schema
1115
+ * browser.defaultProfile = "browserless" // only if unset
1116
+ * browser.enabled = true // only if unset
1117
+ * gateway.nodes.browser.mode = "off" // only if unset
1118
+ *
1119
+ * Why per-profile `attachOnly` and not global `browser.attachOnly`: global
1120
+ * attachOnly forces every profile to skip launch — that breaks the user's
1121
+ * other manually-configured profiles. Per-profile attachOnly was added in
1122
+ * OpenClaw v2026.3.2; older versions silently ignore the extra field and
1123
+ * fall back to attach-via-cdpUrl semantics (which `cdpUrl` triggers on its
1124
+ * own from v2.0.0-beta5), so the schema is forward-compatible all the way
1125
+ * back to the first remote-CDP release.
1126
+ *
1127
+ * Why `gateway.nodes.browser.mode = "off"`: in OpenClaw 2026.5.6 the
1128
+ * gateway only registers the `browser.request` WS method when this config
1129
+ * block exists. Without it, `openclaw browser …` CLI and the gateway
1130
+ * canvas tool both fail with `unknown method: browser.request` or
1131
+ * `node required`. Setting `mode: "off"` forces gateway-local CDP
1132
+ * dispatch (use `cdpUrl` directly, never look for paired nodes), which
1133
+ * matches jishushell's intent: Browserless is a service-style provider,
1134
+ * not a node-style provider. Verified end-to-end on Pi 2 (2026-05-07):
1135
+ * Browserless `/sessions` shows `numbConnected: 1` and `openclaw browser
1136
+ * navigate <allowed-host>` succeeds + screenshots render correctly.
1137
+ *
1138
+ * `defaultProfile`, `enabled`, and `gateway.nodes.browser.mode` are all
1139
+ * set only when absent so user-customized values survive a re-bind. The
1140
+ * `enabled` flag is never flipped off — Browserless binding shouldn't
1141
+ * override a user who explicitly disabled the browser tool tree.
1142
+ *
1143
+ * SSRF policy: on every Browserless bind, the bound CDP endpoint hostname is
1144
+ * merged into `allowedHostnames` so OpenClaw can connect to the trusted
1145
+ * Browserless service even when it is advertised on a private LAN address.
1146
+ * On first bind (when the `allowedHostnames` list is empty or absent), a
1147
+ * small set of common public-internet hosts is also pre-populated so users
1148
+ * don't have to whitelist every popular site one by one. The public defaults
1149
+ * are a one-time bootstrap — once the user has any entries, further binds
1150
+ * leave those entries untouched except for refreshing the active endpoint.
1151
+ *
1152
+ * No-op when the config file is absent (instance not yet started).
1153
+ */
1154
+ export function applyBrowserlessConnectionToConfig(configPath, cdpUrl) {
1155
+ if (!existsSync(configPath))
1156
+ return;
1157
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
1158
+ const browser = (existing.browser ??= {});
1159
+ if (browser.enabled === undefined)
1160
+ browser.enabled = true;
1161
+ if (!browser.defaultProfile)
1162
+ browser.defaultProfile = BROWSERLESS_PROFILE;
1163
+ const profiles = (browser.profiles ??= {});
1164
+ const prior = profiles[BROWSERLESS_PROFILE] ?? {};
1165
+ profiles[BROWSERLESS_PROFILE] = {
1166
+ ...prior,
1167
+ cdpUrl,
1168
+ attachOnly: true,
1169
+ color: typeof prior.color === "string" && prior.color ? prior.color : BROWSERLESS_DEFAULT_COLOR,
1170
+ };
1171
+ if (existing.meta?._js_allowAll) {
1172
+ delete browser.ssrfPolicy;
1173
+ }
1174
+ else {
1175
+ const ssrfPolicy = (browser.ssrfPolicy ??= {});
1176
+ const existingAllowedHostnames = Array.isArray(ssrfPolicy.allowedHostnames)
1177
+ ? ssrfPolicy.allowedHostnames.map((entry) => String(entry))
1178
+ : [];
1179
+ const bootstrapHostnames = existingAllowedHostnames.length === 0
1180
+ ? DEFAULT_BROWSER_ALLOWED_HOSTNAMES
1181
+ : existingAllowedHostnames;
1182
+ ssrfPolicy.allowedHostnames = mergeBrowserAllowedHostnames(bootstrapHostnames, browserlessEndpointAllowedHostname(cdpUrl));
1183
+ }
1184
+ const gateway = (existing.gateway ??= {});
1185
+ const nodes = (gateway.nodes ??= {});
1186
+ const browserPolicy = (nodes.browser ??= {});
1187
+ if (browserPolicy.mode === undefined)
1188
+ browserPolicy.mode = "off";
1189
+ safeWriteJson(configPath, existing);
1190
+ }
1191
+ /**
1192
+ * Counterpart to `applyBrowserlessConnectionToConfig` — invoked when the user
1193
+ * unbinds the BROWSER slot in the Connections tab. Removes the
1194
+ * jishushell-managed `browserless` profile and clears `defaultProfile` only
1195
+ * if it still points at that profile (so user-set defaults pointing at their
1196
+ * own profiles survive). Other profiles and `browser.enabled` are left alone.
1197
+ *
1198
+ * No-op when the config file is absent.
1199
+ */
1200
+ export function clearBrowserlessConnectionFromConfig(configPath) {
1201
+ if (!existsSync(configPath))
1202
+ return;
1203
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
1204
+ const browser = existing?.browser;
1205
+ if (!browser || typeof browser !== "object")
1206
+ return;
1207
+ if (browser.profiles && typeof browser.profiles === "object") {
1208
+ delete browser.profiles[BROWSERLESS_PROFILE];
1209
+ }
1210
+ if (browser.defaultProfile === BROWSERLESS_PROFILE) {
1211
+ delete browser.defaultProfile;
1212
+ }
1213
+ safeWriteJson(configPath, existing);
1214
+ }
1215
+ /**
1216
+ * Bump when a panel-side change invalidates the agent's prior reasoning
1217
+ * within an existing chat session — e.g., a mount fix that turns prior
1218
+ * "I can't read this file" tool failures into stale conclusions. The
1219
+ * first onBeforeStart after the bump rotates the instance's session
1220
+ * jsonl files (`<file>.jsonl` → `<file>.jsonl.reset.<ts>`), so the next
1221
+ * user message lands on a clean context window. Old transcripts are
1222
+ * preserved as .reset.* siblings — never deleted, just archived.
1223
+ *
1224
+ * Concrete history:
1225
+ * 2026.5.11.1 — buildVolumes root-mount fix: empty-path FileMount
1226
+ * finally binds FILES_ROOT into docker containers. Prior
1227
+ * sessions had agent conclude "drive only has metadata,
1228
+ * no file content" after ENOENT — that reasoning is
1229
+ * poisoned post-fix.
1230
+ * 2026.5.11.2 — WeChat target-format rule in TOOLS.md: agent was
1231
+ * extrapolating Feishu's `user:` prefix onto WeChat
1232
+ * chat_ids that don't carry it, causing WeChat's
1233
+ * getuploadurl to return ret:-1. Prior sessions need
1234
+ * rotation so the agent re-reads the corrected target
1235
+ * rule and stops adding the prefix.
1236
+ * 2026.6.4.2 — jishu-kb citations response + mcporter fallback shebang:
1237
+ * agent was concluding KB was empty because the shim only
1238
+ * recognized `chunks/results/hits`, while current jishu-kb
1239
+ * returns `citations`. The fallback wrapper also baked a
1240
+ * host-specific node shebang that some OpenClaw runtimes
1241
+ * could not execute directly. Prior sessions need rotation
1242
+ * so the agent retries with the fixed tool behavior.
1243
+ * 2026.6.4.3 — jishu-kb multi-tool surface: KB management/upload/delete
1244
+ * tools and handbook/config reads are now available.
1245
+ * Prior sessions need rotation so the model re-reads the
1246
+ * expanded tool instructions instead of the old search-only
1247
+ * guidance.
1248
+ * 2026.6.10.1 — Browserless profile rule in TOOLS.md: Browserless-bound
1249
+ * instances now spell out that `browser.open` should not
1250
+ * default to `profile: "openclaw"` after status/doctor
1251
+ * already report `browserless via cdp`.
1252
+ * 2026.6.11.1 — Browserless shared-browser handoff rule: Browserless is
1253
+ * now described as a user-takeover-capable shared browser
1254
+ * surface.
1255
+ * 2026.6.12.1 — Browserless site-side anti-bot classification rule:
1256
+ * site WAF/captcha blocks are not Browser Allowlist misses.
1257
+ * 2026.6.24.1 — Immich MCP routing rule in TOOLS.md: photo-library
1258
+ * requests must use the injected immich.* tools instead of
1259
+ * probing docker, ports, or host directories from inside
1260
+ * the OpenClaw container.
1261
+ *
1262
+ * Format: YYYY.M.D.N (date + same-day bump counter). Compare as strings;
1263
+ * any difference means rotate. Stored per-instance at
1264
+ * `<instanceDir>/runtime-contract.txt`
1265
+ */
1266
+ const RUNTIME_CONTRACT_VERSION = "2026.6.24.1";
1267
+ const JISHUSHELL_DRIVE_HINT_BEGIN = "<!-- jishushell-drive: BEGIN auto-generated -->";
1268
+ const JISHUSHELL_DRIVE_HINT_END = "<!-- jishushell-drive: END -->";
1269
+ const JISHUSHELL_KB_HINT_BEGIN = "<!-- jishushell-kb: BEGIN auto-generated -->";
1270
+ const JISHUSHELL_KB_HINT_END = "<!-- jishushell-kb: END -->";
1271
+ const JISHUSHELL_IMMICH_HINT_BEGIN = "<!-- jishushell-immich: BEGIN auto-generated -->";
1272
+ const JISHUSHELL_IMMICH_HINT_END = "<!-- jishushell-immich: END -->";
1273
+ const JISHUSHELL_BROWSERLESS_HINT_BEGIN = "<!-- jishushell-browserless: BEGIN auto-generated -->";
1274
+ const JISHUSHELL_BROWSERLESS_HINT_END = "<!-- jishushell-browserless: END -->";
1275
+ /**
1276
+ * Rotate session jsonl files when the runtime contract version has bumped
1277
+ * since this instance last started. Matches OpenClaw's own .reset.<ts>
1278
+ * naming convention so its existing UI/cleanup paths still apply.
1279
+ *
1280
+ * Why this exists: when a panel upgrade fixes a runtime bug (e.g. the
1281
+ * 2026-05-11 mount-bind fix), the agent's prior turn-by-turn reasoning
1282
+ * inside an existing session is anchored to the broken behaviour. Even
1283
+ * after the fix is deployed and the alloc restarted, the LLM keeps
1284
+ * citing past tool failures and refusing to retry. Rotating the session
1285
+ * jsonl(s) gives the next user message a clean context where the agent
1286
+ * sees fresh TOOLS.md + fresh tool outputs.
1287
+ *
1288
+ * Side effect: the user loses chat scrollback in IM/web. Acceptable
1289
+ * because (a) the rotated file is preserved on disk, (b) panel upgrades
1290
+ * are infrequent, (c) the alternative — agent stuck in old reasoning —
1291
+ * is worse UX.
1292
+ */
1293
+ function rotateSessionsIfContractChanged(instanceId, openclawHome) {
1294
+ try {
1295
+ const markerPath = join(framework_instanceDir(instanceId), "runtime-contract.txt");
1296
+ let previous = "";
1297
+ try {
1298
+ previous = readFileSync(markerPath, "utf-8").trim();
1299
+ }
1300
+ catch (e) {
1301
+ if (e?.code !== "ENOENT")
1302
+ throw e;
1303
+ }
1304
+ if (previous === RUNTIME_CONTRACT_VERSION)
1305
+ return;
1306
+ const sessionsDir = join(openclawHome, ".openclaw", "agents", "main", "sessions");
1307
+ if (existsSync(sessionsDir)) {
1308
+ const ts = new Date()
1309
+ .toISOString()
1310
+ .replace(/:/g, "-")
1311
+ .replace(/\.\d+Z$/, ".000Z");
1312
+ const entries = readdirSync(sessionsDir);
1313
+ let rotated = 0;
1314
+ let rotateFailed = false;
1315
+ for (const name of entries) {
1316
+ if (!name.endsWith(".jsonl"))
1317
+ continue; // skip already-rotated
1318
+ const from = join(sessionsDir, name);
1319
+ const to = `${from}.reset.${ts}`;
1320
+ try {
1321
+ renameSync(from, to);
1322
+ rotated++;
1323
+ }
1324
+ catch (e) {
1325
+ rotateFailed = true;
1326
+ console.warn(`[openclaw] session rotate failed for ${from}: ${e?.message ?? e}`);
1327
+ }
1328
+ }
1329
+ if (rotated > 0) {
1330
+ console.log(`[openclaw] runtime contract ${previous || "(none)"} → ${RUNTIME_CONTRACT_VERSION}: rotated ${rotated} session(s) under ${sessionsDir}`);
1331
+ }
1332
+ if (rotateFailed)
1333
+ return;
1334
+ }
1335
+ writeConfigFile(markerPath, RUNTIME_CONTRACT_VERSION + "\n");
1336
+ }
1337
+ catch (e) {
1338
+ console.warn(`[openclaw] rotateSessionsIfContractChanged failed: ${e?.message ?? e}`);
1339
+ }
1340
+ }
1341
+ /**
1342
+ * Inject a guarded section into the agent's TOOLS.md telling the LLM that
1343
+ * user files live on the local filesystem (host==container bind mount),
1344
+ * not on some remote "drive server", and showing the concrete
1345
+ * resolve-then-send chain for IM channels (Feishu / WeChat).
1346
+ *
1347
+ * Why this exists: the LLM defaults to interpreting `drive` as a remote
1348
+ * service, then refuses to send NAS files via IM with "I can't access the
1349
+ * cloud drive" — even when `drive_list` literally just enumerated them.
1350
+ * Verified on pi2 2026-05-11: claw1 saw `文档/宇树G1-D...xlsx` via
1351
+ * drive_list, then told the user to "open Feishu cloud space and forward
1352
+ * it back" because nothing in TOOLS.md tied drive paths to filesystem
1353
+ * paths. This patcher closes that gap by spelling it out.
1354
+ *
1355
+ * Idempotent: section is bracketed by HTML markers; content between them
1356
+ * is rewritten on every call. User edits OUTSIDE the markers are kept.
1357
+ *
1358
+ * filesRoot is baked in so the example abs path matches the actual install
1359
+ * — third-party users on `/home/alice/.jishushell/files/` see their own
1360
+ * root, not pi's.
1361
+ */
1362
+ export function patchToolsMdDriveHint(workspaceDir, filesRoot, mcporterCommand = "mcporter", instanceId) {
1363
+ try {
1364
+ const toolsPath = join(workspaceDir, "TOOLS.md");
1365
+ let original = "";
1366
+ try {
1367
+ original = readFileSync(toolsPath, "utf-8");
1368
+ }
1369
+ catch (e) {
1370
+ if (e?.code !== "ENOENT")
1371
+ throw e;
1372
+ }
1373
+ const cli = mcporterCommand === "mcporter" ? "mcporter" : JSON.stringify(mcporterCommand);
1374
+ const generatedOutboxPath = instanceId
1375
+ ? `agent-data/${instanceId}/outbox/x.pdf`
1376
+ : "agent-data/<instance>/outbox/x.pdf";
1377
+ const section = [
1378
+ JISHUSHELL_DRIVE_HINT_BEGIN,
1379
+ "",
1380
+ "### 📁 用户的 NAS / 文件库",
1381
+ "",
1382
+ "⚠️ **用户文件操作硬路由 — 必读**",
1383
+ "",
1384
+ "**单一规则(语言无关)**:用户用任何语言(中文 / English / 日本語 / ...)说「**我的 / 我的 / my / mine / our / the user's / 私の**」+ 任何文件/目录/资料/笔记/文档/代码/data/notes/docs/files → **CRUD 全部走 `drive.*` 工具,禁止用 shell 在 cwd 上操作**。判定按**语义**不按**字面**,本表只是举例。",
1385
+ "",
1386
+ "动作 ↔ 工具映射表(用户文件场景,中英混排示例):",
1387
+ "",
1388
+ "| 用户意图(多语言示例) | ✅ 必须用 | ❌ 禁止 |",
1389
+ "|---|---|---|",
1390
+ "| list / show / 「列一下 / 我有什么 / 看看我的 / what files do I have / show me my docs / list my files」 | `drive_list` | `ls`, `find`, `pwd` |",
1391
+ "| read / open / 「打开 / 看看 / 念一下 / 内容是啥 / open my X / read the content of / what's in」 | `drive_read_preview` / `drive_read_full` | `cat`, `head`, `tail` |",
1392
+ "| search / find / 「搜 / 找一下 / 哪里提到 / search my docs for / find X in my files / where did I write about」 | `drive_search` | `grep`, `rg` |",
1393
+ "| write / save / create / 「写 / 存 / 记一下 / 新建 / save this as / write a note / create a file」 | `drive_write_text` / `drive_write_binary` | `echo >`, `cat <<EOF`, `tee` |",
1394
+ "| delete / remove / 「删 / 扔掉 / delete X / remove the file」 | `drive_delete` | `rm` |",
1395
+ "| rename / move / 「改名 / 挪到 / 移到 / rename X to Y / move X to」 | `drive_move` | `mv` |",
1396
+ "| mkdir / 「建文件夹 / create a folder / make a directory」 | `drive_mkdir` | `mkdir` |",
1397
+ "| quota / space / 「配额 / 空间 / how much space / quota / disk usage」 | `drive_quota` | `df`, `du` |",
1398
+ "| send / share / 「发给我 / 把 X 发出去 / send me X / share the file with me」 | `drive_resolve_local_path` → IM `send_file` | (拒绝 / refuse) |",
1399
+ "",
1400
+ "**触发词不完全列表(再次强调:语义优先)**:",
1401
+ "- 中文:我的、我那份、我之前的、我刚刚的、用户的、咱们的、文件、文档、资料、笔记、报告、合同、PDF、Excel、附件",
1402
+ "- 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)",
1403
+ "- 其它语言:私の (ja) / mes (fr) / mein (de) / 我的 (variants) — 含义相同时同等处理",
1404
+ "",
1405
+ "**为什么硬规定**:cwd 是你自己的运行骨架(`AGENTS.md`、`TOOLS.md`、`memory/`、`state/`、`config/`),跟用户**毫无关系**。",
1406
+ "- 用户问「我有什么文件 / what files do I have」你 `ls` cwd → 列出 `AGENTS.md`、`memory/` → 用户懵 + 觉得 jishushell 装错了",
1407
+ "- 用户说「帮我写笔记 notes.md / save a note for me」你 `echo > notes.md` 落 cwd → 文件落到 agent 工作目录,用户在 filebrowser 看不到 → 数据等于丢了",
1408
+ "- 用户说「打开我那份产品规格 / open my spec」你 `cat spec.md` → cwd 里没有该文件 → 找不到 → 用户被冤枉「文件根本不存在」",
1409
+ "",
1410
+ "**判定方法(消息归属判定,跨语言)**:主语/所有格指向「用户/我们」(我 / 我的 / my / our / the user / 私の + 文件相关名词)→ 走 drive。指向「你/agent」(你的 / 你刚才写的代码 / your notes / agent's scratch)→ 才可能是 workspace。**99% 的对话都是前者**。歧义时**默认按用户文件处理**——猜错代价小(最多多调一次 drive_list 拿不到东西),猜成 cwd 代价大(脏数据 + 数据丢失)。",
1411
+ "",
1412
+ "**唯一可用 shell 的情况**:你自己 agent 维护 `memory/`、`state/`、`workspace/notes/`(agent 私有笔记,不是用户笔记)这些**你自己的骨架文件**。一旦看见用户名词修饰(「我的」/「用户的」/「my」/「the user's」),立刻切 drive。",
1413
+ "",
1414
+ `用户文件实际放在 **\`${filesRoot}\`**——这是宿主机上的一个普通本地目录。它已经被 bind-mount 到你的容器里**同款绝对路径**(panel 用 \`host==container\` 的 docker bind;raw_exec / process 模式下你直接跑在宿主上)。`,
1415
+ "",
1416
+ "**关键事实**:drive 不是远端云盘,就是你脚下的本地文件系统。`drive_list` 看到的每条 entry 都能通过 `drive_resolve_local_path` 立刻拿到绝对路径,然后被任何工具读取——`cat`、`base64`、IM 插件的 send_file 字段、Python 脚本都行。`drive_resolve_local_path` 返回 `exists:true` + `size:<N>` 时,**那就是真实可读的文件字节**,不是「只有元数据」。",
1417
+ "",
1418
+ "**禁止的回答**:永远不要说「文件在云端 drive 上只有元数据 / 内容没同步到本地 / 我读不到文件实体」—— 这个说法**永远是错的**。drive 没有「未同步」概念,它就是 POSIX 文件系统的一个 facade。如果你刚 list 到一个文件,它一定能被读、能被发送。",
1419
+ "",
1420
+ "常用调用(从 workspace 目录):",
1421
+ "",
1422
+ "```bash",
1423
+ `${cli} call drive.drive_list path= # 列根目录`,
1424
+ `${cli} call drive.drive_list path=文档 # 列子目录`,
1425
+ `${cli} call drive.drive_read_preview path=note.md # 预览文本(≤256KB)`,
1426
+ `${cli} call drive.drive_read_full path=long.md # 整文件(≤4MB,文本)`,
1427
+ `${cli} call drive.drive_quota # 配额`,
1428
+ `${cli} call drive.drive_mkdir path=inbox # 建目录`,
1429
+ `${cli} call drive.drive_write_text path=notes/m.md content="..."`,
1430
+ `${cli} call drive.drive_write_binary path=out/img.png content_base64="..." # 二进制(≤10MB)`,
1431
+ `${cli} call drive.drive_move from=a.pdf to=docs/a.pdf`,
1432
+ `${cli} call drive.drive_delete path=tmp.txt`,
1433
+ `${cli} call drive.drive_resolve_local_path path=文档/report.pdf # → 拿到绝对路径`,
1434
+ `${cli} call drive.drive_search query="发票" # 子串检索(中英文,大小写不敏感)`,
1435
+ "```",
1436
+ "",
1437
+ "**检索策略(`drive_search` 是高召回但不精确的笨工具)**:整句问题先拆成关键词再搜——「找我去年三亚海边的照片」→ 搜 `三亚`、`海边`、`照片`(或空格分隔 `三亚 海边 照片`,空格 = OR)。它是连续子串匹配、不懂语义;命中后用 `drive_read_full` 读候选、自己判断与精排,召回不够就换同义词多搜几次。",
1438
+ "",
1439
+ "### 给用户发文件(飞书 / 微信 / 任何 IM)",
1440
+ "",
1441
+ "**用户问 \"把 X 文件发我\" 时不要拒绝、不要让用户去飞书云空间下载**——99% 的情况文件已经在你的文件系统里了。标准流程:",
1442
+ "",
1443
+ "1. `drive_list` 或 `drive_search` 先确认文件在 NAS 里(你刚 list 过的也算)。",
1444
+ "2. `drive_resolve_local_path path=文档/x.xlsx` 拿到 `abs_path`,确认 `exists:true`。",
1445
+ "3. 把 `abs_path` 传给**当前会话所在 IM 通道**的发送工具。**`target` 字段一律原样照搬当前消息 `Conversation info` 里的 `chat_id`——一个字符都不要加、不要改、不要补前缀**。各通道 chat_id 形态本来就不一样,照搬就对。",
1446
+ " - **飞书 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`。",
1447
+ " - **微信 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`,文件传不出去。",
1448
+ " - 通用规则:当前 inbound 消息的 `from` 就是回复 target。打开你刚收到的那条 user message 里 `Conversation info` 的 JSON,把 `chat_id` 整段复制就行。",
1449
+ "4. 失败先查 `exists` 字段、文件大小、IM 通道大小上限(飞书典型 30MB、微信 20MB),再决定降级方案。",
1450
+ "",
1451
+ "**ENOENT / \"no such file or directory\" 处理**:IM 插件返回 ENOENT 但 `drive_resolve_local_path` 刚刚 `exists:true`,**99% 是 panel 刚升级 / mount 刚刷新,但你这个 alloc 用的是旧 spec**。无脑重试一次。还是 ENOENT 才提示用户去 panel 重启实例(stop+start,不是 restart)——但**永远不要**回答 \"文件只是元数据所以读不到\",那是错的。",
1452
+ "",
1453
+ `要发**新生成**的文件(PDF、图片、报表):先 \`drive_write_binary path=${generatedOutboxPath} content_base64=...\` 落盘,再 resolve → 发送。`,
1454
+ "",
1455
+ "### 用户给你发文件",
1456
+ "",
1457
+ "目前飞书/微信通道不会自动把附件落盘到 NAS。当用户说\"文件给你了\"但你 `drive_list inbox` 看不到:",
1458
+ "- 优先让用户走 panel 的 Filebrowser(`/apps/filebrowser/`)或 WebDAV 把文件上传到 `inbox/`,再告诉你路径。",
1459
+ "- 飞书附件流:如果飞书 app 已配 `im:resource` 权限,可以用 `feishu_im_user_fetch_resource` 取 file_key、落到 `inbox/feishu/<date>/`。",
1460
+ "",
1461
+ "权限:在 panel \"关联 agent\" UI 里给实例授 ro/rw。403 时让用户去 panel 加。",
1462
+ "",
1463
+ JISHUSHELL_DRIVE_HINT_END,
1464
+ "",
1465
+ ].join("\n");
1466
+ let next;
1467
+ const beginIdx = original.indexOf(JISHUSHELL_DRIVE_HINT_BEGIN);
1468
+ const endIdx = original.indexOf(JISHUSHELL_DRIVE_HINT_END);
1469
+ if (beginIdx >= 0 && endIdx > beginIdx) {
1470
+ const tail = endIdx + JISHUSHELL_DRIVE_HINT_END.length;
1471
+ const after = original
1472
+ .slice(tail)
1473
+ .replace(/^\n+/, "\n");
1474
+ next = original.slice(0, beginIdx) + section + after;
1475
+ }
1476
+ else {
1477
+ const sep = original && !original.endsWith("\n") ? "\n\n" : "\n";
1478
+ next = (original ? original + sep : "") + section;
1479
+ }
1480
+ if (next === original)
1481
+ return;
1482
+ writeConfigFile(toolsPath, next);
1483
+ console.log(`[openclaw] Patched drive hint into ${toolsPath}`);
1484
+ }
1485
+ catch (e) {
1486
+ console.warn(`[openclaw] Failed to patch TOOLS.md drive hint: ${e.message}`);
1487
+ }
1488
+ }
1489
+ export function patchToolsMdBrowserlessHint(workspaceDir, mode) {
1490
+ try {
1491
+ const toolsPath = join(workspaceDir, "TOOLS.md");
1492
+ let original = "";
1493
+ try {
1494
+ original = readFileSync(toolsPath, "utf-8");
1495
+ }
1496
+ catch (e) {
1497
+ if (e?.code !== "ENOENT")
1498
+ throw e;
1499
+ if (mode === "remove")
1500
+ return;
1501
+ }
1502
+ const stripRe = /\n*<!-- jishushell-browserless: BEGIN[^>]*-->[\s\S]*?<!-- jishushell-browserless: END[^>]*-->\n*/g;
1503
+ const stripped = original.replace(stripRe, "\n");
1504
+ let next;
1505
+ if (mode === "remove") {
1506
+ if (stripped === original)
1507
+ return;
1508
+ next = stripped;
1509
+ }
1510
+ else {
1511
+ const section = [
1512
+ JISHUSHELL_BROWSERLESS_HINT_BEGIN,
1513
+ "",
1514
+ "### Browserless shared-browser rule",
1515
+ "",
1516
+ "In JishuShell, Browserless is a shared interactive browser surface:",
1517
+ "- the agent opens and drives pages with the `browser` tool;",
1518
+ "- the user can take over the same Browserless session from the JishuShell panel's Browserless debugger;",
1519
+ "- login forms, captchas, permission prompts, cookie banners, MFA, and similar blockers are handoff points, not terminal failures.",
1520
+ "",
1521
+ "Follow these rules whenever you use the `browser` tool:",
1522
+ "",
1523
+ "1. If `browser status` or `browser doctor` reports `profile = \"browserless\"` / `browserless via cdp`, keep subsequent page-opening actions on Browserless.",
1524
+ "2. For ordinary website opening, prefer omitting `profile` entirely so the configured default can apply.",
1525
+ "3. If you must set a profile explicitly, use `profile: \"browserless\"` unless the user explicitly asked for a different named profile.",
1526
+ "4. Do not switch to `profile: \"openclaw\"` just because the target site may need login. Browserless is the login-capable path in this setup.",
1527
+ "5. If the user explicitly asks to open a browser, says \"I will log in\", \"let me handle it\", or wants to clear a captcha / permission prompt themselves, do not stop at `browser.status`. After the health check, call `browser.open` on the requested site, or `about:blank` if no site was given, so a live Browserless session exists for takeover.",
1528
+ "6. After opening the page, explicitly tell the user to continue in the Browserless debugger / panel and wait for them. The expected workflow is open -> handoff -> user acts -> agent resumes.",
1529
+ "7. Do not claim that `attachOnly`, `headless`, or the lack of a local OS window means the user cannot interact. In this setup the visual surface is the Browserless debugger in JishuShell.",
1530
+ "8. If login, captcha, cookie consent, permissions, MFA, or payment confirmation appears, keep the Browserless session alive and hand control to the user instead of abandoning the task.",
1531
+ "9. If Browserless status is healthy but a later `browser.open` with `profile: \"openclaw\"` would search for a local browser executable, that is the wrong choice for this instance.",
1532
+ "10. If `browser.open` fails with `browser endpoint blocked by policy`, immediately tell the user the blocked hostname, that the block happened before Browserless, where to unblock it in Panel -> this instance -> Browser Allowlist, and ask the user to tell you after whitelisting so you can retry. Do not silently fall back to web_fetch / web_search before delivering that notice.",
1533
+ "11. If `browser.open` succeeds but the page/status/body shows a target-site anti-bot / WAF / verification block, for example `whaleguard block`, `HTTP 432`, `403`, `captcha`, `verify`, or a blank page saying it was blocked, do not tell the user to add the host to the Browser Allowlist. The site was reached and then rejected the browser/session.",
1534
+ "12. For Ctrip / WhaleGuard specifically, do not keep retrying the blocked deep link such as `flights.ctrip.com/online/list/...`. Open `https://www.ctrip.com/` first, keep the Browserless session alive, ask the user to take over in the Browserless debugger to log in / pass verification / perform the search manually, and wait.",
1535
+ "13. Do not claim that a live page/session is ready for takeover unless `browser.open` actually succeeded. A healthy Browserless status alone is not proof that the user already has a visible page to interact with.",
1536
+ "",
1537
+ JISHUSHELL_BROWSERLESS_HINT_END,
1538
+ "",
1539
+ ].join("\n");
1540
+ const sep = stripped && !stripped.endsWith("\n") ? "\n\n" : "\n";
1541
+ next = (stripped ? stripped + sep : "") + section;
1542
+ }
1543
+ if (next === original)
1544
+ return;
1545
+ writeConfigFile(toolsPath, next);
1546
+ console.log(`[openclaw] ${mode === "remove" ? "Removed" : "Patched"} browserless hint in ${toolsPath}`);
1547
+ }
1548
+ catch (e) {
1549
+ console.warn(`[openclaw] Failed to ${mode} TOOLS.md browserless hint: ${e.message}`);
1550
+ }
1551
+ }
1552
+ export function resolveKbProvider(kbBinding) {
1553
+ const LEGACY_PROVIDER_ANYLLM = "anythingllm-container";
1554
+ const LEGACY_PROVIDER_JISHUKB = "jishu-kb-container";
1555
+ const capabilityToTag = (capability) => {
1556
+ if (capability === "knowledge-jishukb")
1557
+ return "jishukb";
1558
+ if (capability === "knowledge-anythingllm")
1559
+ return "anythingllm";
1560
+ return null;
1561
+ };
1562
+ const legacyProviderIdToTag = (providerId) => {
1563
+ if (providerId === LEGACY_PROVIDER_JISHUKB)
1564
+ return "jishukb";
1565
+ if (providerId === LEGACY_PROVIDER_ANYLLM)
1566
+ return "anythingllm";
1567
+ return null;
1568
+ };
1569
+ const entryToTag = (entry) => {
1570
+ if (!entry || typeof entry !== "object")
1571
+ return null;
1572
+ // Canonical connection bindings store the provider instance id in
1573
+ // providerId and the concrete provider kind in capability. The provider
1574
+ // instance id is user-controlled (`jishu-kb`, `my-kb`, ...), so runtime
1575
+ // wiring must key off capability, not template/provider-id strings.
1576
+ return capabilityToTag(entry.capability) ?? legacyProviderIdToTag(entry.providerId);
1577
+ };
1578
+ if (kbBinding === null)
1579
+ return null;
1580
+ if (kbBinding && typeof kbBinding === "object") {
1581
+ const b = kbBinding;
1582
+ if (b.kind === "single") {
1583
+ return entryToTag(b);
1584
+ }
1585
+ if (b.kind === "many") {
1586
+ // User selected the "many" mode but the providers array is malformed
1587
+ // or empty → treat as "no known provider bound", same as a list of
1588
+ // only-unknown providers. Avoids the surprise where a malformed
1589
+ // array silently falls back to legacy auto-anythingllm.
1590
+ if (!Array.isArray(b.providers))
1591
+ return null;
1592
+ // First known match in the user's order wins — the UI lets users
1593
+ // drag to reorder; we honor that order rather than imposing our own.
1594
+ for (const p of b.providers) {
1595
+ const tag = entryToTag(p);
1596
+ if (tag !== null)
1597
+ return tag;
1598
+ }
1599
+ return null;
1600
+ }
1601
+ return null;
1602
+ }
1603
+ return null;
1604
+ }
1605
+ function providerCredentialsPath(providerId) {
1606
+ return join(JISHUSHELL_HOME, "provider-credentials", providerId, "credentials.json");
1607
+ }
1608
+ function legacyProviderCredentialsPath(providerId) {
1609
+ return join(JISHUSHELL_HOME, "apps", providerId, "credentials.json");
1610
+ }
1611
+ function cleanupEmptyLegacyProviderDir(providerId) {
1612
+ const dir = join(JISHUSHELL_HOME, "apps", providerId);
1613
+ try {
1614
+ if (existsSync(dir) && readdirSync(dir).length === 0) {
1615
+ rmSync(dir, { recursive: false, force: true });
1616
+ }
1617
+ }
1618
+ catch {
1619
+ /* best effort */
1620
+ }
1621
+ }
1622
+ function resolveProviderCredentialsPath(providerId) {
1623
+ const nextPath = providerCredentialsPath(providerId);
1624
+ if (existsSync(nextPath))
1625
+ return nextPath;
1626
+ const legacyPath = legacyProviderCredentialsPath(providerId);
1627
+ if (!existsSync(legacyPath))
1628
+ return nextPath;
1629
+ try {
1630
+ ensureDirHost(dirname(nextPath));
1631
+ renameSync(legacyPath, nextPath);
1632
+ cleanupEmptyLegacyProviderDir(providerId);
1633
+ console.log(`[openclaw] migrated ${providerId} credentials to ${nextPath}`);
1634
+ return nextPath;
1635
+ }
1636
+ catch (error) {
1637
+ console.warn(`[openclaw] failed to migrate ${providerId} credentials from legacy apps/ path:`, error?.message ?? error);
1638
+ return legacyPath;
1639
+ }
1640
+ }
1641
+ export async function resolveJishukbDefaultKbIdForOpenClaw(baseUrl, configuredKbId) {
1642
+ const kbId = typeof configuredKbId === "string" ? configuredKbId.trim() : "";
1643
+ if (kbId && kbId !== "default")
1644
+ return kbId;
1645
+ try {
1646
+ const { ensureDefaultKb } = await import("../jishukb/integration.js");
1647
+ await ensureDefaultKb(baseUrl);
1648
+ return "default";
1649
+ }
1650
+ catch (error) {
1651
+ console.warn(`[openclaw] kb: jishu-kb default KB is not usable; wiring without a default kbId: ` +
1652
+ `${error?.message ?? error}`);
1653
+ return "";
1654
+ }
1655
+ }
1656
+ function rewriteJishukbMcpUrlForOpenClawRuntime(url, runtime) {
1657
+ if (!runtime?.image)
1658
+ return url;
1659
+ try {
1660
+ const parsed = new URL(url);
1661
+ if (["127.0.0.1", "localhost", "0.0.0.0", "::1", "[::1]"].includes(parsed.hostname)) {
1662
+ parsed.hostname = "host.docker.internal";
1663
+ return parsed.toString();
1664
+ }
1665
+ }
1666
+ catch {
1667
+ return url;
1668
+ }
1669
+ return url;
1670
+ }
1671
+ /**
1672
+ * Per-provider kb-shim residue cleanup. Wipes the shim source (replacing
1673
+ * the bytes with a removal marker rather than `unlink`-ing — the latter
1674
+ * would race with a concurrent `node <shim>` that already opened it) and
1675
+ * `unlink`s the sibling `secret.json` if any. Idempotent and safe to call
1676
+ * even if no shim was ever installed.
1677
+ *
1678
+ * Called by EVERY branch of the kb auto-wire block so a rebind from
1679
+ * anythingllm ↔ jishukb (or → null) never leaves stale shim files or
1680
+ * 0o600 secrets on disk. The "wipe by overwrite" pattern matches what
1681
+ * the old anythingllm-only branch did before the dispatch refactor.
1682
+ *
1683
+ * integrationHome is the OpenClaw container's `$HOME` (the value returned by
1684
+ * `openclawIntegration.resolveAgentHome(instanceId)`). `which` selects the
1685
+ * provider: each gets its own `__mcp_shims__/<which>/` subtree.
1686
+ *
1687
+ * Exported so the security-critical secret-deletion behavior can be
1688
+ * covered by a focused unit test without standing up the full start hook.
1689
+ */
1690
+ export function wipeKbShimDir(integrationHome, which) {
1691
+ const dir = join(integrationHome, "__mcp_shims__", which);
1692
+ const shimPath = join(dir, `${which}-shim.js`);
1693
+ const removalMarker = which === "anythingllm"
1694
+ ? "// removed: AnythingLLM not bound as knowledge provider\n"
1695
+ : "// removed: jishu-kb not bound as knowledge provider\n";
1696
+ try {
1697
+ if (existsSync(shimPath)) {
1698
+ writeFileSync(shimPath, removalMarker, { mode: 0o644 });
1699
+ }
1700
+ }
1701
+ catch { /* best effort */ }
1702
+ // AnythingLLM's shim has a sibling 0o600 secret.json (API key). v1
1703
+ // jishu-kb ships without auth so no secret to wipe — when jishu-kb
1704
+ // adds JISHU_KB_AUTH_TOKEN_FILE we'll start writing a secret.json
1705
+ // here too and the unlink must be added below.
1706
+ if (which === "anythingllm") {
1707
+ const secretPath = join(dir, "secret.json");
1708
+ try {
1709
+ if (existsSync(secretPath))
1710
+ unlinkSync(secretPath);
1711
+ }
1712
+ catch { /* best effort */ }
1713
+ }
1714
+ }
1715
+ export function patchToolsMdKbHint(workspaceDir, mode, provider, mcporterCommand = "mcporter", instanceId, mediaInboundRoot, unavailableReason) {
1716
+ try {
1717
+ const toolsPath = join(workspaceDir, "TOOLS.md");
1718
+ let original = "";
1719
+ try {
1720
+ original = readFileSync(toolsPath, "utf-8");
1721
+ }
1722
+ catch (e) {
1723
+ if (e?.code !== "ENOENT")
1724
+ throw e;
1725
+ if (mode === "remove")
1726
+ return; // nothing to strip
1727
+ }
1728
+ // Strip every existing kb section first — tolerant of legacy variants
1729
+ // (e.g. early manual injections that used "END auto-generated -->"
1730
+ // instead of the current "END -->" marker). Without this, repeated
1731
+ // re-patches would accumulate sections in TOOLS.md.
1732
+ const STRIP_RE = /\n*<!-- jishushell-kb: BEGIN[^>]*-->[\s\S]*?<!-- jishushell-kb: END[^>]*-->\n*/g;
1733
+ const stripped = original.replace(STRIP_RE, "\n");
1734
+ let next;
1735
+ if (mode === "remove") {
1736
+ if (stripped === original)
1737
+ return;
1738
+ next = stripped;
1739
+ }
1740
+ else if (mode === "unavailable") {
1741
+ const reason = typeof unavailableReason === "string" && unavailableReason.trim()
1742
+ ? unavailableReason.trim().replace(/\s+/g, " ").slice(0, 500)
1743
+ : "native MCP is not registered";
1744
+ const section = [
1745
+ JISHUSHELL_KB_HINT_BEGIN,
1746
+ "",
1747
+ "### 📚 知识库(JishuShell-KB)暂不可用",
1748
+ "",
1749
+ "OpenClaw 已绑定 **JishuShell-KB**,但 JishuShell 当前没有检测到可用的 **native MCP** 服务,所以本轮不能调用 `kb.*` 工具。",
1750
+ "",
1751
+ `**检测原因**:${reason}`,
1752
+ "",
1753
+ "**必须这样处理**:",
1754
+ "- 不要声称已经检索过知识库,也不要尝试使用旧 shim、mcporter 或自己拼 HTTP 请求。",
1755
+ "- 如果用户要查询、上传或管理知识库,直接提醒用户:需要升级 JishuShell-KB 到包含 remote MCP 的版本,并确认 `JISHU_KB_MCP_HTTP` / MCP auth 已配置后重启 OpenClaw。",
1756
+ "- 在 native MCP 恢复前,知识库能力视为不可用。",
1757
+ "",
1758
+ JISHUSHELL_KB_HINT_END,
1759
+ "",
1760
+ ].join("\n");
1761
+ const sep = stripped && !stripped.endsWith("\n") ? "\n\n" : "\n";
1762
+ next = (stripped ? stripped + sep : "") + section;
1763
+ }
1764
+ else {
1765
+ if (!provider) {
1766
+ throw new Error("provider is required when installing KB hint");
1767
+ }
1768
+ const cli = mcporterCommand === "mcporter" ? "mcporter" : JSON.stringify(mcporterCommand);
1769
+ const generatedOutboxPath = instanceId
1770
+ ? `agent-data/${instanceId}/outbox/report.md`
1771
+ : "agent-data/<instance>/outbox/report.md";
1772
+ const attachmentInboxPath = mediaInboundRoot || "<openclawHome>/.openclaw/media/inbound";
1773
+ const nativeKbTool = (name) => `kb__${name}`;
1774
+ const section = provider === "jishukb"
1775
+ ? [
1776
+ JISHUSHELL_KB_HINT_BEGIN,
1777
+ "",
1778
+ "### 📚 知识库(JishuShell-KB)",
1779
+ "",
1780
+ "用户长期投递并已经导入到 **JishuShell-KB** 的文档(手册、PDF、内部笔记、会议纪要等)可以检索;你也可以列知识库、创建知识库、把 drive 文件或 URL 上传入库、查看已索引文档/分块/原文/FAQ、查看 ingest job、查看 handbook、读取**脱敏后的**当前配置,以及在用户明确确认时执行删除/重索引/取消任务。",
1781
+ "",
1782
+ "这些能力由 OpenClaw native MCP 暴露;直接调用 `kb__*` 工具,不要通过 shell、mcporter 或手写 HTTP 请求访问 KB。",
1783
+ "",
1784
+ "**当前 provider 暴露的工具**:",
1785
+ "",
1786
+ `- \`${nativeKbTool("kb_list")}\` — 列出所有知识库(拿 id / name / documents 文件数 / chunks 分块数;用户问“几个文件”时看 documents,不要用 chunks)`,
1787
+ `- \`${nativeKbTool("kb_get_capabilities")}\` — 查看 KB 当前支持的外部控制能力、上传格式和限制(不含密钥)`,
1788
+ `- \`${nativeKbTool("kb_create")}\` — 新建知识库`,
1789
+ `- \`${nativeKbTool("kb_get")}\` — 查看某个知识库的元数据、文件数、分块数、任务数和安全配置摘要`,
1790
+ `- \`${nativeKbTool("kb_search")}\` — 检索指定或默认知识库`,
1791
+ `- \`${nativeKbTool("kb_upload")}\` — 上传并索引文件到指定知识库`,
1792
+ `- \`${nativeKbTool("kb_import_url")}\` — 抓取可读 URL 并入库,默认异步返回 job`,
1793
+ `- \`${nativeKbTool("kb_list_documents")}\` — 列出指定或默认知识库里的已索引文档`,
1794
+ `- \`${nativeKbTool("kb_get_document")}\` — 查看单个文档的元数据和派生计数`,
1795
+ `- \`${nativeKbTool("kb_list_document_chunks")}\` — 查看某个文档的索引分块(文本会截断)`,
1796
+ `- \`${nativeKbTool("kb_read_document_raw")}\` — 读取某个文档的原始存储文本(仅在用户要看原文时用,输出会截断)`,
1797
+ `- \`${nativeKbTool("kb_list_document_faq")}\` — 查看某个文档生成的 FAQ 建议`,
1798
+ `- \`${nativeKbTool("kb_reindex_document")}\` — 重建文档索引(写操作,必须显式确认)`,
1799
+ `- \`${nativeKbTool("kb_list_jobs")}\` — 查看导入/索引任务`,
1800
+ `- \`${nativeKbTool("kb_get_job")}\` — 查看单个任务状态`,
1801
+ `- \`${nativeKbTool("kb_retry_job")}\` — 重试失败/取消的任务(仅在用户要求时用)`,
1802
+ `- \`${nativeKbTool("kb_cancel_job")}\` — 取消任务(必须显式确认)`,
1803
+ `- \`${nativeKbTool("kb_read_handbook")}\` — 读取 handbook 全文或指定章节`,
1804
+ `- \`${nativeKbTool("kb_get_config")}\` — 读取当前**脱敏后的**知识库配置摘要`,
1805
+ `- \`${nativeKbTool("kb_delete_document")}\` — 删除文档(危险操作,必须显式确认)`,
1806
+ `- \`${nativeKbTool("kb_delete_kb")}\` — 删除知识库(危险操作,必须显式确认)`,
1807
+ "",
1808
+ "**推荐调用顺序**:",
1809
+ `1. 用户问“知识库里有几个文件 / 包含哪些文件” → 先 \`${nativeKbTool("kb_list_documents")}\`;如果不知道 kbId,先 \`${nativeKbTool("kb_list")}\`,再对目标库调用 \`${nativeKbTool("kb_list_documents")}\`。文件数按 documents 或 list_documents 返回数组长度计算,不要按 chunks 计算。`,
1810
+ `2. 用户提到“某个指定知识库 / 某个库里”但你不知道 id → 先 \`${nativeKbTool("kb_list")}\`。`,
1811
+ `3. 用户要把 drive 里的文件加入知识库 → 先解析本地路径,再调用 \`${nativeKbTool("kb_upload")}\`,并显式传目标 kbId。`,
1812
+ `4. 用户当前消息已经附了文件,而且消息里给了宿主机绝对路径(通常在 \`${attachmentInboxPath}/...\`)→ 直接把这个绝对路径传给 \`${nativeKbTool("kb_upload")}\`;不要先把内容重写到 \`files/\` 根目录,也不要自己猜 \`agent-data/agent1/...\` 这种路径。`,
1813
+ `5. 用户要把网页/文章 URL 加入知识库 → 先确认目标 kbId,再调用 \`${nativeKbTool("kb_import_url")}\`;返回 job 后用 \`${nativeKbTool("kb_get_job")}\` 或 \`${nativeKbTool("kb_list_jobs")}\` 看进度。`,
1814
+ `6. 用户要上传你**新生成**的文件 → 先写到 \`${generatedOutboxPath}\`,再解析本地路径,最后调用 \`${nativeKbTool("kb_upload")}\`。`,
1815
+ `7. 用户要新建库并马上上传 → \`${nativeKbTool("kb_create")}\` → 记住返回的 id → \`${nativeKbTool("kb_upload")}\` / \`${nativeKbTool("kb_import_url")}\`。`,
1816
+ `8. 用户要查看某个命中文档的细节 → 先 \`${nativeKbTool("kb_list_documents")}\` 找 documentId,再 \`${nativeKbTool("kb_get_document")}\`;需要解释命中原因用 \`${nativeKbTool("kb_list_document_chunks")}\`,只有用户明确要看原文时才用 \`${nativeKbTool("kb_read_document_raw")}\`。`,
1817
+ `9. 用户要修复索引/重跑失败导入 → 先 \`${nativeKbTool("kb_list_jobs")}\` / \`${nativeKbTool("kb_get_job")}\` 看状态;重试用 \`${nativeKbTool("kb_retry_job")}\`,重索引用 \`${nativeKbTool("kb_reindex_document")}\`。`,
1818
+ `10. 用户要解释某个设置项怎么用 → 先 \`${nativeKbTool("kb_read_handbook")}\`,必要时再 \`${nativeKbTool("kb_get_config")}\` 看当前值。`,
1819
+ "",
1820
+ `**安全规则**:写操作、删除操作、重索引、取消任务都不要猜目标知识库;拿不准就先 \`${nativeKbTool("kb_list")}\`。删除/重索引/取消必须是用户明确要求,且把 confirm 字段原样填成同一个 id。 \`${nativeKbTool("kb_get_config")}\` 和 \`${nativeKbTool("kb_get_capabilities")}\` 不会给你密钥。 \`${nativeKbTool("kb_upload")}\` 只接受来自当前实例已挂载文件目录,或当前实例附件 inbox(\`${attachmentInboxPath}/...\`)的绝对路径;如果 remote MCP capabilities 显示 path upload 关闭,就只能使用内容/URL 上传。 \`${nativeKbTool("kb_read_document_raw")}\` 只在用户要看原文时使用。**`,
1821
+ "",
1822
+ "**与 drive 的分工**:",
1823
+ "- `drive.*` = 文件系统 facade(列目录、读字节、拿绝对路径)—— 要的是**文件本体**用 drive",
1824
+ "- `kb__*` = 知识库检索/管理/上传 —— 要的是**知识库里的内容和状态**用 kb",
1825
+ "",
1826
+ "两者数据不共享:drive 里有文件 ≠ 某个知识库已经索引了它。",
1827
+ "",
1828
+ `**搜不到时的标准回复**:如果 \`${nativeKbTool("kb_search")}\` 没结果,就直接说「我在当前知识库里没找到相关内容」。如果用户问的是 drive 里已有文件,可进一步建议「要我把它上传到某个知识库吗?」—— 但上传前先确认目标 kbId,不要自己猜默认库。`,
1829
+ "",
1830
+ JISHUSHELL_KB_HINT_END,
1831
+ "",
1832
+ ].join("\n")
1833
+ : [
1834
+ JISHUSHELL_KB_HINT_BEGIN,
1835
+ "",
1836
+ "### 📚 知识库(AnythingLLM)",
1837
+ "",
1838
+ "用户长期投递的文档(手册、PDF、内部笔记、过往会议纪要等)由 **AnythingLLM** 维护索引(本地 LanceDB 向量库 + 内置 Xenova ONNX embedder),通过 `kb.kb_search` 一次调用拿「答案 + 引用来源」。",
1839
+ "",
1840
+ "**两个工具**:",
1841
+ "",
1842
+ `- \`${cli} call kb.kb_search query="<用户原话>"\` — 在已索引文档里检索,返回答案 + 最多 5 条引用源`,
1843
+ `- \`${cli} call kb.kb_ingest path="<绝对路径>"\` — 把 drive 里的文件加入知识库并 embed(用户说「加进知识库 / index this / 学习这份」时调)`,
1844
+ "",
1845
+ "**ingest 标准链**(drive 里的文件 → 知识库):",
1846
+ `1. \`${cli} call drive.drive_resolve_local_path path=inbox/contract.pdf\` → 拿 \`abs_path\``,
1847
+ `2. \`${cli} call kb.kb_ingest path=<abs_path>\` → AnythingLLM 自动 embed`,
1848
+ "3. 几秒后用户问相关问题,`kb_search` 命中",
1849
+ "",
1850
+ "**search 什么时候调**:用户问的东西像在已上传文档里能找到——「那个 X 的手册里怎么说」、「我们之前关于 Y 的讨论」、「产品规格」、「合同条款」、「what does the doc say about X」等。",
1851
+ "",
1852
+ "**什么时候不要调**:寒暄、纯代码生成、数学计算、实时信息(天气/股票/新闻)、**操作 NAS 文件**(那是 `drive.*`,不是 kb)、纯创作类。",
1853
+ "",
1854
+ "**与 drive 的分工**:",
1855
+ "- `drive.*` = 文件系统 facade(列目录、读字节、发文件)—— 要的是**文件本体**用 drive",
1856
+ "- `kb.kb_search` / `kb.kb_ingest` = 语义检索 + RAG 入库 —— 要的是**答案/知识**用 kb",
1857
+ "",
1858
+ "两者数据**不共享**:drive 看到 `manual.pdf` ≠ kb 一定能搜到它。要让 kb 能搜到 → 先 `kb_ingest`。",
1859
+ "",
1860
+ "**搜不到时的标准回复**:`kb_search` 回答里说「无相关文档」或 sources 为空 → 先确认 drive 里有没有相关文件,如果有,主动建议「要我把它加入知识库吗」(用户同意就 `drive_resolve_local_path` + `kb_ingest`);drive 也没有,告诉用户「我在你的知识库里没找到相关内容」,然后**不要继续幻想答案**。",
1861
+ "",
1862
+ JISHUSHELL_KB_HINT_END,
1863
+ "",
1864
+ ].join("\n");
1865
+ const sep = stripped && !stripped.endsWith("\n") ? "\n\n" : "\n";
1866
+ next = (stripped ? stripped + sep : "") + section;
1867
+ }
1868
+ if (next === original)
1869
+ return;
1870
+ writeConfigFile(toolsPath, next);
1871
+ console.log(`[openclaw] ${mode === "remove" ? "Removed" : "Patched"} kb hint in ${toolsPath}`);
1872
+ }
1873
+ catch (e) {
1874
+ console.warn(`[openclaw] Failed to ${mode} TOOLS.md kb hint: ${e.message}`);
1875
+ }
1876
+ }
1877
+ export function patchToolsMdKbUnavailableHint(workspaceDir, reason) {
1878
+ patchToolsMdKbHint(workspaceDir, "unavailable", undefined, "mcporter", undefined, undefined, reason);
1879
+ }
1880
+ /**
1881
+ * Inject or remove the Immich MCP usage contract in TOOLS.md.
1882
+ *
1883
+ * Immich is registered through OpenClaw's native `mcp.servers` config, so the
1884
+ * model receives standard tool schemas and calls them directly. This section
1885
+ * only supplies product behavior and safety guidance; it must not teach the
1886
+ * model to shell out through mcporter.
1887
+ */
1888
+ export function patchToolsMdImmichHint(workspaceDir, mode, serverName = "immich") {
1889
+ try {
1890
+ const toolsPath = join(workspaceDir, "TOOLS.md");
1891
+ let original = "";
1892
+ try {
1893
+ original = readFileSync(toolsPath, "utf-8");
1894
+ }
1895
+ catch (e) {
1896
+ if (e?.code !== "ENOENT")
1897
+ throw e;
1898
+ if (mode === "remove")
1899
+ return;
1900
+ }
1901
+ const stripRe = /\n*<!-- jishushell-immich: BEGIN[^>]*-->[\s\S]*?<!-- jishushell-immich: END[^>]*-->\n*/g;
1902
+ const stripped = original.replace(stripRe, "\n");
1903
+ let next;
1904
+ if (mode === "remove") {
1905
+ if (stripped === original)
1906
+ return;
1907
+ next = stripped;
1908
+ }
1909
+ else {
1910
+ const tool = (name) => `${serverName}__${name}`;
1911
+ const section = [
1912
+ JISHUSHELL_IMMICH_HINT_BEGIN,
1913
+ "",
1914
+ "### 🖼️ Immich 照片库",
1915
+ "",
1916
+ `Immich 已通过 OpenClaw 原生 MCP 接入。用户询问照片、视频、图库状态、相册、标签、人物、人脸、地图位置或重复照片时,必须调用 \`${serverName}__*\` 工具,并严格按照工具提供的参数 Schema 传参。`,
1917
+ "",
1918
+ `⚠️ **不要用 shell 探测 Immich 是否安装**:OpenClaw 运行在自己的容器里;容器内没有 \`docker\` 命令、没有宿主机监听端口或 Immich 数据目录,并不代表宿主机没有运行 Immich。禁止用 \`docker ps\`、\`ss\`、\`find /\`、\`ls /opt\` 等结果判断 Immich 状态。连接状态只以 \`${tool("get_library_summary")}\` / \`${tool("ping")}\` 的结果为准。`,
1919
+ "",
1920
+ "**主要工具**:",
1921
+ "",
1922
+ `- \`${tool("get_library_summary")}\` — 首选健康检查;返回连接、版本和图库统计`,
1923
+ `- \`${tool("get_photo_library_status")}\` — 查看 AI Box 默认照片目录是否已接入及已扫描数量`,
1924
+ `- \`${tool("scan_photo_library")}\` — 扫描 AI Box 默认照片目录;首次调用会自动创建 External Library`,
1925
+ `- \`${tool("create_photo_upload_session")}\` — 创建短期网页上传链接;照片和视频由浏览器直接传到 AI Box;同一页面在过期前可完成并扫描多个上传批次`,
1926
+ `- \`${tool("list_assets")}\` — 列出照片/视频`,
1927
+ `- \`${tool("search_metadata")}\` — 按结构化元数据搜索`,
1928
+ `- \`${tool("search_smart")}\` — 用自然语言或相似图片获取 Immich Smart Search / CLIP 相似候选排序`,
1929
+ `- \`${tool("get_asset_info")}\` — 查看单个资源`,
1930
+ `- \`${tool("list_albums")}\` / \`${tool("get_album")}\` / \`${tool("delete_album")}\` — 相册`,
1931
+ `- \`${tool("list_tags")}\` / \`${tool("get_tag")}\` / \`${tool("delete_tag")}\` — 标签`,
1932
+ `- \`${tool("list_people")}\` / \`${tool("search_people")}\` — 人物`,
1933
+ `- \`${tool("get_duplicates")}\` — 重复项`,
1934
+ `- \`${tool("generate_review_gallery")}\` — 创建用户自选照片的 review 页面;确认后 Core 直接执行`,
1935
+ "",
1936
+ "**标准工具策略**:",
1937
+ `1. 先按用户意图选择工具,不要用 shell、mcporter 或 memory_search 代替 Immich MCP。健康检查用 \`${tool("get_library_summary")}\` / \`${tool("ping")}\`;扫描用 \`${tool("scan_photo_library")}\`,返回 \`scan_queued\` 时只说明扫描已开始,不要声称所有照片已经导入完成;上传用 \`${tool("create_photo_upload_session")}\`,上传页面可在过期前连续完成多个批次。`,
1938
+ `2. 读取和搜索只负责收集候选资源:普通列表用 \`${tool("list_assets")}\`,结构化条件搜索用 \`${tool("search_metadata")}\`,自然语言视觉语义或“找相似照片”用 \`${tool("search_smart")}\`,相册内容用 \`${tool("get_album")}\`,重复项用 \`${tool("get_duplicates")}\`。工具返回短 JSON 和 asset id;不要把 thumbnail base64、文件内容或大量 asset id 展示给用户。`,
1939
+ ` \`${tool("search_smart")}\` 的实际语义是 Immich 返回一页按语义相似度排序的候选,默认 \`size=50\`、最大 \`100\`;它不是二分类器,也不保证返回“所有符合条件”的照片。小图库里可能几乎所有照片都会出现在第一页。向用户表述时使用“相似候选 / 候选结果 / 排序结果”,不要说“已经找到了所有 X 照片”或“这些全都是 X”。`,
1940
+ `3. 相册和标签是目标容器。用户要求把照片加入某个新相册或新标签时,先用 \`${tool("create_album")}\` 或 \`${tool("create_tag")}\` 创建目标;如果目标是否存在或应复用不明确,先查列表或向用户确认。`,
1941
+ `4. 删除相册或标签前,必须先用 \`${tool("get_album")}\` / \`${tool("get_tag")}\` 或列表结果核对资源名称和 id,并在对话里明确询问用户确认。调用 \`${tool("delete_album")}\` 不会删除照片;调用 \`${tool("delete_tag")}\` 不会删除照片,但会把该标签从所有关联照片上移除。`,
1942
+ `5. 所有需要用户从候选照片中确认子集、确认批量修改、或决定哪些重复项应处理的操作,都必须通过 \`${tool("generate_review_gallery")}\` 创建 review interaction。适用动作包括加入/移出相册、打标签/取消标签、移入回收站、处理重复项。`,
1943
+ `6. 对搜索驱动的批量操作采用通用的 human-in-the-loop 候选审核流程:先用读取/搜索工具得到候选集,把需要用户可见审核的候选放入 \`asset_ids\`;只有能解释清楚依据的高置信项才放入 \`preselected_asset_ids\`,让 review UI 默认勾选。最终执行仍以用户在页面中的确认和修改为准。`,
1944
+ `7. 不要把所有 CLIP 命中无条件当作推荐项。Smart Search 结果只能直接作为候选,推荐项应基于多信号判断:分数 score(如果工具返回)、搜索排名、文件名、相册/标签/人物、地点、日期、资源类型等。精确结构化条件、明确 asset id、或用户给出的确定集合可以默认全选;纯视觉搜索且缺少可靠阈值或存在歧义时,只预选高置信项,不能判断的保持未选,必要时先请用户缩小条件。`,
1945
+ `8. 用户表达“所有/全部/帮我找并加入/自动整理”时,不要把筛选工作完全丢给用户;应创建 review 页面给出候选,并在有高置信推荐项时默认选中。若候选只来自 Smart Search 且无法可靠区分,应明确说明这是相似候选排序,需要用户在页面中最终确认,而不是假装已经自动识别全部。用户表达“我来选、从图库挑、让我自己选择、选择几张”时,省略 \`preselected_asset_ids\`,让用户手动选择。`,
1946
+ `9. 调用 \`${tool("generate_review_gallery")}\` 时,\`action\` 必须使用工具 schema 中的枚举原值:\`add_assets_to_album\`、\`remove_assets_from_album\`、\`tag_assets\`、\`untag_assets\`、\`delete_assets_to_trash\`、\`resolve_duplicates\`。不要自造 \`add-to-album\`、\`select-assets\`、\`manage-album\` 等动作名。`,
1947
+ `10. 创建 review interaction 后,只把返回的 \`urls.web\` 和简短说明发给用户。如果提供了 \`preselected_asset_ids\`,说明“已默认选中推荐项,可直接确认或取消误选”;如果没有预选项,说明“这是候选页面,需要你确认哪些要处理”。用户在页面点击确认后,Core 会直接执行;不要要求用户回到对话框继续确认,也不要自行声称已经执行,除非工具返回的执行状态明确表示完成。`,
1948
+ "11. 如果候选集过大或用户意图不足以确定候选范围,先请用户用时间、地点、收藏、文件名、相册、标签、人物或其他结构化条件缩小范围;不要为了避免使用 review UI 而先列编号让用户在对话里挑。",
1949
+ "12. 删除照片只表示移入 Immich 回收站。永久删除和清空回收站不可用,不要声称已经永久删除。",
1950
+ "13. MCP 调用失败时,原样说明工具错误;不要改用 shell 猜测工具参数,也不要据此断言 Immich 未安装。",
1951
+ "",
1952
+ JISHUSHELL_IMMICH_HINT_END,
1953
+ "",
1954
+ ].join("\n");
1955
+ const sep = stripped && !stripped.endsWith("\n") ? "\n\n" : "\n";
1956
+ next = (stripped ? stripped + sep : "") + section;
1957
+ }
1958
+ if (next === original)
1959
+ return;
1960
+ writeConfigFile(toolsPath, next);
1961
+ console.log(`[openclaw] ${mode === "remove" ? "Removed" : "Patched"} immich hint in ${toolsPath}`);
1962
+ }
1963
+ catch (e) {
1964
+ console.warn(`[openclaw] Failed to ${mode} TOOLS.md immich hint: ${e.message}`);
1965
+ }
1966
+ }
1967
+ /**
1968
+ * Pre-seed the per-instance npm global prefix with a symlink to the image's
1969
+ * baked openclaw package so OpenClaw's in-gateway "Update now" handler can
1970
+ * detect the install as an npm global install. Idempotent; docker driver only.
1971
+ */
1972
+ function ensureOpenclawUpdateSeed(openclawHome, instanceId) {
1973
+ if (getNomadDriver() !== "docker")
1974
+ return;
1975
+ if (!openclawHome)
1976
+ return;
1977
+ const linkDir = join(openclawHome, ".npm-global", "lib", "node_modules");
1978
+ const linkPath = join(linkDir, "openclaw");
1979
+ try {
1980
+ lstatSync(linkPath);
1981
+ return;
1982
+ }
1983
+ catch (err) {
1984
+ if (err?.code !== "ENOENT") {
1985
+ console.warn(`[openclaw] update-seed: lstat failed for ${linkPath}: ${err?.message ?? err}`);
1986
+ return;
1987
+ }
1988
+ }
1989
+ try {
1990
+ mkdirSync(linkDir, { recursive: true });
1991
+ symlinkSync(CONTAINER_IMAGE_PKG_ROOT, linkPath);
1992
+ console.log(`[openclaw] update-seed ${instanceId}: seeded ${linkPath} -> ${CONTAINER_IMAGE_PKG_ROOT}`);
1993
+ }
1994
+ catch (err) {
1995
+ console.warn(`[openclaw] update-seed ${instanceId}: failed to create seed: ${err?.message ?? err}`);
1996
+ }
1997
+ }
1998
+ // ── Session fence patch (OpenClaw >= 5.19 regression) ─────────────────
1999
+ /**
2000
+ * The minimum OpenClaw version where the session fence bug exists.
2001
+ * The bug was introduced in v2026.5.19 — `eventMayReachTranscriptWriters()`
2002
+ * doesn't recognize `"message"` / `"custom_message"` event types, causing
2003
+ * session writes to bypass `withSessionWriteLock`, which in turn leaves
2004
+ * the file fingerprint stale and triggers `EmbeddedAttemptSessionTakeoverError`
2005
+ * on the next prompt.
2006
+ *
2007
+ * Additionally, on virtiofs mounts (macOS → Colima VM → Docker), file
2008
+ * metadata (mtime/ctime) can drift between `releaseForPrompt()` and
2009
+ * `assertSessionFileFence()` even without actual writes, due to the
2010
+ * multi-layer filesystem stack timing. Patching `assertSessionFileFence`
2011
+ * to a no-op fully disables the flawed fence check.
2012
+ */
2013
+ const SESSION_FENCE_BUG_MIN_VERSION = [2026, 5, 19];
2014
+ /**
2015
+ * Maximum version (exclusive) to apply the patch. Once OpenClaw ships a fix
2016
+ * upstream, set a concrete version here to stop patching newer releases.
2017
+ * For now, no upper bound — patch all versions >= MIN.
2018
+ */
2019
+ /**
2020
+ * Safety limit: if the extracted function body exceeds this many characters,
2021
+ * skip the patch to avoid corrupting the bundle (e.g. brace-depth counter
2022
+ * fooled by string literals containing braces in a future refactored version).
2023
+ */
2024
+ const MAX_PATCH_TARGET_BODY_LENGTH = 5000;
2025
+ /**
2026
+ * Patch targets: each entry defines a function to replace.
2027
+ * - `eventMayReachTranscriptWriters`: broad return prevents events from
2028
+ * bypassing the write lock (necessary but not sufficient on virtiofs).
2029
+ * - `assertSessionFileFence`: no-op disables the fingerprint comparison
2030
+ * that false-triggers due to virtiofs stat drift.
2031
+ */
2032
+ const SESSION_FENCE_PATCH_TARGETS = [
2033
+ {
2034
+ fnName: "function assertSessionFileFence()",
2035
+ litNeedle: "sameSessionFileFingerprint",
2036
+ replacement: "function assertSessionFileFence() { return; }",
2037
+ },
2038
+ {
2039
+ fnName: "function eventMayReachTranscriptWriters",
2040
+ litNeedle: '"message_update"',
2041
+ replacement: 'function eventMayReachTranscriptWriters(session, event) { return typeof event?.type === "string"; }',
2042
+ },
2043
+ ];
2044
+ /**
2045
+ * Patch the session fence bug in OpenClaw >= 5.19 by replacing the
2046
+ * `eventMayReachTranscriptWriters` function in the minified bundle.
2047
+ *
2048
+ * Idempotent: uses a marker file containing the SHA-256 of the patched
2049
+ * file. Skips if already patched or if the pattern is not found (future
2050
+ * fixed version or different bundle layout).
2051
+ *
2052
+ * Docker-only: the bug manifests through the virtiofs mount timing
2053
+ * discrepancy between container and host — raw_exec/process modes are
2054
+ * unaffected in practice.
2055
+ */
2056
+ export function patchSessionFenceBug(openclawHome, instanceId) {
2057
+ if (getNomadDriver() !== "docker")
2058
+ return;
2059
+ // 1. Read installed version from npm-global package.json
2060
+ const pkgPath = join(openclawHome, ".npm-global", "lib", "node_modules", "openclaw", "package.json");
2061
+ let versionStr;
2062
+ try {
2063
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
2064
+ versionStr = pkg.version || "";
2065
+ }
2066
+ catch {
2067
+ return; // no npm-global install or unreadable — skip
2068
+ }
2069
+ // 2. Parse version and check minimum threshold
2070
+ const parts = versionStr.split(".").map(Number);
2071
+ if (parts.length < 3 || parts.some(Number.isNaN))
2072
+ return;
2073
+ const [major, minor, patch] = parts;
2074
+ const [minMajor, minMinor, minPatch] = SESSION_FENCE_BUG_MIN_VERSION;
2075
+ if (major < minMajor ||
2076
+ (major === minMajor && minor < minMinor) ||
2077
+ (major === minMajor && minor === minMinor && patch < minPatch)) {
2078
+ return; // version predates the bug
2079
+ }
2080
+ // 3. Find the selection-*.js bundle that contains the target function.
2081
+ // There may be multiple selection-*.js files in dist/; only one holds
2082
+ // the session management code.
2083
+ const distDir = join(openclawHome, ".npm-global", "lib", "node_modules", "openclaw", "dist");
2084
+ let bundleFiles;
2085
+ try {
2086
+ const entries = readdirSync(distDir);
2087
+ bundleFiles = entries.filter((f) => f.startsWith("selection-") && f.endsWith(".js"));
2088
+ }
2089
+ catch {
2090
+ return; // dist dir missing or unreadable
2091
+ }
2092
+ if (bundleFiles.length === 0)
2093
+ return;
2094
+ // Scan each candidate for any of the patch target signatures
2095
+ let bundlePath;
2096
+ let bundleContent;
2097
+ for (const file of bundleFiles) {
2098
+ const candidatePath = join(distDir, file);
2099
+ let content;
2100
+ try {
2101
+ content = readFileSync(candidatePath, "utf-8");
2102
+ }
2103
+ catch {
2104
+ continue;
2105
+ }
2106
+ // Match if any target's fnName or litNeedle is present
2107
+ const hasTarget = SESSION_FENCE_PATCH_TARGETS.some((t) => content.includes(t.fnName) || content.includes(t.litNeedle));
2108
+ if (hasTarget) {
2109
+ bundlePath = candidatePath;
2110
+ bundleContent = content;
2111
+ break;
2112
+ }
2113
+ }
2114
+ if (!bundlePath || !bundleContent)
2115
+ return;
2116
+ // 4. Check marker file for idempotency
2117
+ const markerPath = join(distDir, `.session-fence-patched`);
2118
+ const currentHash = createHash("sha256").update(bundleContent).digest("hex");
2119
+ try {
2120
+ const marker = readFileSync(markerPath, "utf-8").trim();
2121
+ if (marker === currentHash)
2122
+ return; // already patched, hash matches
2123
+ }
2124
+ catch {
2125
+ // marker missing — proceed
2126
+ }
2127
+ // 5. Apply each patch target using brace-depth counting to extract and
2128
+ // replace function bodies. Process targets in order; earlier patches
2129
+ // shift offsets so we re-search after each replacement.
2130
+ let patched = bundleContent;
2131
+ let patchCount = 0;
2132
+ for (const target of SESSION_FENCE_PATCH_TARGETS) {
2133
+ let fnStart = patched.indexOf(target.fnName);
2134
+ // Fallback for eventMayReachTranscriptWriters: locate by unique literal
2135
+ // combination ("message_update" near "message_end" and "agent_end")
2136
+ if (fnStart === -1 && target.litNeedle === '"message_update"') {
2137
+ let scanPos = 0;
2138
+ while (scanPos < patched.length) {
2139
+ const litIdx = patched.indexOf(target.litNeedle, scanPos);
2140
+ if (litIdx === -1)
2141
+ break;
2142
+ const window = patched.slice(litIdx, litIdx + 200);
2143
+ if (window.includes('"message_end"') && window.includes('"agent_end"')) {
2144
+ const searchStart = Math.max(0, litIdx - 300);
2145
+ const prefix = patched.slice(searchStart, litIdx);
2146
+ const fnKeywordIdx = prefix.lastIndexOf("function ");
2147
+ if (fnKeywordIdx !== -1) {
2148
+ fnStart = searchStart + fnKeywordIdx;
2149
+ break;
2150
+ }
2151
+ }
2152
+ scanPos = litIdx + 1;
2153
+ }
2154
+ }
2155
+ if (fnStart === -1)
2156
+ continue; // target not found (already patched or fixed version)
2157
+ // Check if already patched (replacement is short and contains `return;`)
2158
+ const peekEnd = Math.min(fnStart + target.replacement.length + 10, patched.length);
2159
+ const peek = patched.slice(fnStart, peekEnd);
2160
+ if (peek.startsWith(target.replacement))
2161
+ continue;
2162
+ // Extract function body with brace-depth counting
2163
+ const braceStart = patched.indexOf("{", fnStart);
2164
+ if (braceStart === -1)
2165
+ continue;
2166
+ let depth = 0;
2167
+ let fnEnd = -1;
2168
+ for (let i = braceStart; i < patched.length; i++) {
2169
+ if (patched[i] === "{")
2170
+ depth++;
2171
+ else if (patched[i] === "}") {
2172
+ depth--;
2173
+ if (depth === 0) {
2174
+ fnEnd = i + 1;
2175
+ break;
2176
+ }
2177
+ }
2178
+ }
2179
+ if (fnEnd === -1)
2180
+ continue;
2181
+ // Safety: if extracted body is suspiciously large, skip to avoid corrupting
2182
+ // the bundle (brace counter may have been fooled by string contents).
2183
+ if (fnEnd - fnStart > MAX_PATCH_TARGET_BODY_LENGTH) {
2184
+ console.warn(`[openclaw] session-fence-patch ${instanceId}: skipping ${target.fnName} — body too large (${fnEnd - fnStart} chars)`);
2185
+ continue;
2186
+ }
2187
+ patched = patched.slice(0, fnStart) + target.replacement + patched.slice(fnEnd);
2188
+ patchCount++;
2189
+ }
2190
+ if (patchCount === 0) {
2191
+ // No targets needed patching — write marker for current state
2192
+ try {
2193
+ writeFileSync(markerPath, currentHash + "\n", "utf-8");
2194
+ }
2195
+ catch {
2196
+ /* best effort */
2197
+ }
2198
+ return;
2199
+ }
2200
+ // 7. Atomic write: temp file → rename
2201
+ const tmpPath = bundlePath + `.tmp.${randomBytes(4).toString("hex")}`;
2202
+ try {
2203
+ writeFileSync(tmpPath, patched, "utf-8");
2204
+ renameSync(tmpPath, bundlePath);
2205
+ }
2206
+ catch (err) {
2207
+ // Clean up temp file on failure
2208
+ try {
2209
+ unlinkSync(tmpPath);
2210
+ }
2211
+ catch {
2212
+ /* ignore */
2213
+ }
2214
+ console.warn(`[openclaw] session-fence-patch ${instanceId}: atomic write failed: ${err?.message ?? err}`);
2215
+ return;
2216
+ }
2217
+ // 8. Write marker with hash of the PATCHED file
2218
+ const patchedHash = createHash("sha256").update(patched).digest("hex");
2219
+ try {
2220
+ writeFileSync(markerPath, patchedHash + "\n", "utf-8");
2221
+ }
2222
+ catch {
2223
+ // Non-fatal — patch was applied, marker just helps idempotency
2224
+ }
2225
+ console.log(`[openclaw] session-fence-patch ${instanceId}: patched ${bundlePath.split("/").pop()} (v${versionStr})`);
2226
+ }
2227
+ // ── Container-side patch script ───────────────────────────────────────────
2228
+ /**
2229
+ * Self-contained Node.js script that patches the session fence bug from
2230
+ * INSIDE the container. Written to `$OPENCLAW_HOME/.jishushell/session-fence-patch.mjs`
2231
+ * by onBeforeStart and executed by the inline Docker entrypoint before the
2232
+ * OpenClaw gateway starts.
2233
+ *
2234
+ * This covers the case where an in-container `npm install openclaw@latest`
2235
+ * upgrades to a buggy version (>= 5.19) after the container was created
2236
+ * with a clean image (5.7). The host-side `patchSessionFenceBug` cannot
2237
+ * patch at onBeforeStart time because the npm-global directory may not yet
2238
+ * contain the upgraded bundle (it's a dangling symlink to a container-only path).
2239
+ */
2240
+ const CONTAINER_PATCH_SCRIPT = `#!/usr/bin/env node
2241
+ // Session fence patch — auto-generated by JishuShell.
2242
+ // Patches assertSessionFileFence + eventMayReachTranscriptWriters
2243
+ // in OpenClaw >= 2026.5.19 to work around virtiofs stat drift.
2244
+ import { readFileSync, writeFileSync, readdirSync, renameSync, existsSync } from "fs";
2245
+ import { join } from "path";
2246
+ import { createHash } from "crypto";
2247
+
2248
+ const home = process.env.HOME || process.env.OPENCLAW_HOME || "/home/openclaw";
2249
+ const distDir = join(home, ".npm-global", "lib", "node_modules", "openclaw", "dist");
2250
+ const pkgPath = join(home, ".npm-global", "lib", "node_modules", "openclaw", "package.json");
2251
+
2252
+ try {
2253
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
2254
+ const parts = (pkg.version || "").split(".").map(Number);
2255
+ if (parts.length < 3 || parts[0] < 2026 || (parts[0] === 2026 && parts[1] < 5) ||
2256
+ (parts[0] === 2026 && parts[1] === 5 && parts[2] < 19)) process.exit(0);
2257
+ // No upper version cap for now — patch all versions >= 5.19
2258
+ } catch { process.exit(0); }
2259
+
2260
+ const markerPath = join(distDir, ".session-fence-patched");
2261
+ let files;
2262
+ try { files = readdirSync(distDir).filter(f => f.startsWith("selection-") && f.endsWith(".js")); }
2263
+ catch { process.exit(0); }
2264
+
2265
+ const targets = [
2266
+ { fn: "function assertSessionFileFence()", repl: "function assertSessionFileFence() { return; }" },
2267
+ { fn: "function eventMayReachTranscriptWriters", repl: 'function eventMayReachTranscriptWriters(session, event) { return typeof event?.type === "string"; }' },
2268
+ ];
2269
+
2270
+ for (const file of files) {
2271
+ const p = join(distDir, file);
2272
+ let src;
2273
+ try { src = readFileSync(p, "utf-8"); } catch { continue; }
2274
+ if (!targets.some(t => src.includes(t.fn) || src.includes("sameSessionFileFingerprint"))) continue;
2275
+
2276
+ const hash = createHash("sha256").update(src).digest("hex");
2277
+ try { if (readFileSync(markerPath, "utf-8").trim() === hash) process.exit(0); } catch {}
2278
+
2279
+ let modified = src;
2280
+ let count = 0;
2281
+ for (const t of targets) {
2282
+ const idx = modified.indexOf(t.fn);
2283
+ if (idx === -1) continue;
2284
+ if (modified.slice(idx, idx + t.repl.length + 5).startsWith(t.repl)) continue;
2285
+ const braceStart = modified.indexOf("{", idx);
2286
+ if (braceStart === -1) continue;
2287
+ let d = 0, end = -1;
2288
+ for (let i = braceStart; i < modified.length; i++) {
2289
+ if (modified[i] === "{") d++;
2290
+ else if (modified[i] === "}") { d--; if (d === 0) { end = i + 1; break; } }
2291
+ }
2292
+ if (end === -1) continue;
2293
+ if (end - idx > 5000) continue; // safety: skip if body suspiciously large
2294
+ modified = modified.slice(0, idx) + t.repl + modified.slice(end);
2295
+ count++;
2296
+ }
2297
+ if (count === 0) {
2298
+ try { writeFileSync(markerPath, hash + "\\n"); } catch {}
2299
+ process.exit(0);
2300
+ }
2301
+ const tmp = p + ".tmp." + Math.random().toString(36).slice(2, 8);
2302
+ writeFileSync(tmp, modified);
2303
+ renameSync(tmp, p);
2304
+ const newHash = createHash("sha256").update(modified).digest("hex");
2305
+ try { writeFileSync(markerPath, newHash + "\\n"); } catch {}
2306
+ console.log("[session-fence-patch] patched " + file);
2307
+ break;
2308
+ }
2309
+ `;
2310
+ const CONTAINER_PATCH_ENTRYPOINT_COMMAND = 'node "$HOME/.jishushell/session-fence-patch.mjs" 2>/dev/null || true; exec /usr/local/bin/openclaw-entry.sh "$@"';
2311
+ /**
2312
+ * Write the container-side patch script to the openclaw-home directory so it
2313
+ * is available inside the container via the bind mount.
2314
+ *
2315
+ * Called from onBeforeStart. Idempotent — only rewrites if content changed.
2316
+ */
2317
+ export function writeContainerPatchScript(openclawHome) {
2318
+ const scriptDir = join(openclawHome, ".jishushell");
2319
+ try {
2320
+ ensureDirContainer(scriptDir);
2321
+ }
2322
+ catch (err) {
2323
+ console.warn(`[openclaw] Failed to prepare container patch directory ${scriptDir}: ${err?.message ?? err}`);
2324
+ return;
2325
+ }
2326
+ const scriptPath = join(scriptDir, "session-fence-patch.mjs");
2327
+ ensureReadableContent(scriptPath, CONTAINER_PATCH_SCRIPT);
2328
+ }
2329
+ function ensureReadableContent(path, content) {
2330
+ try {
2331
+ if (existsSync(path) && readFileSync(path, "utf-8") === content) {
2332
+ chmodSync(path, 0o644);
2333
+ return;
2334
+ }
2335
+ writeConfigFile(path, content);
2336
+ }
2337
+ catch (err) {
2338
+ console.warn(`[openclaw] Failed to write patch script ${path}: ${err?.message ?? err}`);
2339
+ }
2340
+ }
2341
+ function resolveUidGid(username) {
2342
+ try {
2343
+ if (!VALID_USER_RE.test(username)) {
2344
+ console.warn(`[openclaw] Invalid username for UID lookup: ${username}`);
2345
+ return `${process.getuid()}:${process.getgid()}`;
2346
+ }
2347
+ const passwd = readFileSync("/etc/passwd", "utf-8");
2348
+ const line = passwd.split("\n").find((l) => l.startsWith(username + ":"));
2349
+ if (line) {
2350
+ const parts = line.split(":");
2351
+ const uid = parseInt(parts[2], 10);
2352
+ const gid = parseInt(parts[3], 10);
2353
+ if (!isNaN(uid) && !isNaN(gid))
2354
+ return `${uid}:${gid}`;
2355
+ }
2356
+ }
2357
+ catch {
2358
+ /* ignore */
2359
+ }
2360
+ return `${process.getuid()}:${process.getgid()}`;
2361
+ }
2362
+ // Host peripheral device nodes worth passing into a privileged OpenClaw
2363
+ // container so the agent reaches cameras / GPU / audio like a native install.
2364
+ // Directory roots are fully expanded; the prefixes match numbered top-level
2365
+ // nodes (e.g. /dev/video0, /dev/media1, /dev/mali0).
2366
+ const PERIPHERAL_DEV_ROOTS = ["/dev/dri", "/dev/snd"];
2367
+ const PERIPHERAL_DEV_PREFIXES = ["/dev/video", "/dev/media", "/dev/v4l-subdev", "/dev/mali", "/dev/dma_heap"];
2368
+ // Raw-disk / kernel-memory / device-mapper nodes that must NEVER be passed
2369
+ // into a container, even if a hand-edited `runtime.devices` entry — or a
2370
+ // symlink sitting under a peripheral prefix (e.g. /dev/videoX -> /dev/sda) —
2371
+ // resolves to one. Peripheral passthrough must not silently become raw host
2372
+ // disk or physical-memory access. Prefix match (anchored at /dev/) so
2373
+ // partitions like /dev/sda1 and /dev/nvme0n1p2 are covered too.
2374
+ const FORBIDDEN_DEVICE_RE = /^\/dev\/(mem|kmem|kmsg|port|sd[a-z]|hd[a-z]|vd[a-z]|nvme\d|mmcblk\d|sr\d|md\d|loop\d|dm-\d|mapper\/|disk\/|block\/)/;
2375
+ /**
2376
+ * Enumerate the host's media/accelerator device nodes (plus any explicit
2377
+ * extras from `runtime.devices`) so a privileged container can open them.
2378
+ * Returns docker `devices` entries (real, symlink-resolved paths, deduped)
2379
+ * and the set of owning group gids — the (non-root) container user is added
2380
+ * to those gids via `group_add` so the 0660 root:video / root:render /
2381
+ * root:audio nodes are actually accessible inside the container. Missing
2382
+ * nodes are skipped, so this is a no-op on hosts without such hardware.
2383
+ */
2384
+ function collectPrivilegedDevices(extraPaths = []) {
2385
+ const candidates = new Set(extraPaths);
2386
+ for (const root of PERIPHERAL_DEV_ROOTS) {
2387
+ try {
2388
+ for (const name of readdirSync(root))
2389
+ candidates.add(`${root}/${name}`);
2390
+ }
2391
+ catch { /* root absent on this host */ }
2392
+ }
2393
+ try {
2394
+ for (const name of readdirSync("/dev")) {
2395
+ const full = `/dev/${name}`;
2396
+ if (PERIPHERAL_DEV_PREFIXES.some((p) => full.startsWith(p)))
2397
+ candidates.add(full);
2398
+ }
2399
+ }
2400
+ catch { /* /dev unreadable (non-Linux) */ }
2401
+ const devices = [];
2402
+ const gids = new Set();
2403
+ const seen = new Set();
2404
+ for (const path of candidates) {
2405
+ let real;
2406
+ try {
2407
+ real = realpathSync(path);
2408
+ }
2409
+ catch {
2410
+ continue;
2411
+ }
2412
+ if (seen.has(real))
2413
+ continue;
2414
+ seen.add(real);
2415
+ // Defense-in-depth: only ever expose real /dev nodes, and never raw
2416
+ // disk / memory / device-mapper targets — applies to auto-discovered
2417
+ // nodes (catches a malicious symlink under a peripheral prefix) and to
2418
+ // explicit runtime.devices entries alike.
2419
+ if (!real.startsWith("/dev/") || FORBIDDEN_DEVICE_RE.test(real)) {
2420
+ console.warn(`[openclaw] refusing device passthrough "${path}" -> "${real}" (outside /dev or on denylist)`);
2421
+ continue;
2422
+ }
2423
+ let st;
2424
+ try {
2425
+ st = statSync(real);
2426
+ }
2427
+ catch {
2428
+ continue;
2429
+ }
2430
+ if (!st.isCharacterDevice() && !st.isBlockDevice())
2431
+ continue;
2432
+ devices.push({ host_path: real, container_path: real, cgroup_permissions: "rw" });
2433
+ if (typeof st.gid === "number" && st.gid > 0)
2434
+ gids.add(st.gid);
2435
+ }
2436
+ return { devices, groupAdd: [...gids].map(String) };
2437
+ }
2438
+ // ── Nomad template safety (migrated from the runtime driver) ──────────
2439
+ const NOMAD_TEMPLATE_UNSAFE_RE = /[{}"\\]/;
2440
+ function assertSafeTemplateId(id) {
2441
+ if (NOMAD_TEMPLATE_UNSAFE_RE.test(id)) {
2442
+ throw new Error(`Job ID "${id}" contains characters unsafe for Nomad Template interpolation`);
2443
+ }
2444
+ }
2445
+ // ── Lazy-imported framework helpers (avoid circular deps) ─────────────
2446
+ //
2447
+ // The integration reaches back into instance-manager.ts for helpers that still
2448
+ // live there. Using lazy `await import()` keeps the static import graph
2449
+ // acyclic, so integrations/index.ts -> integrations/openclaw/integration.ts loads cleanly before
2450
+ // instance-manager.ts needs it.
2451
+ async function lazyIm() {
2452
+ return await import("../../instances/manager.js");
2453
+ }
2454
+ async function resolveCoreConnectionForOpenclaw(instanceId) {
2455
+ const corePort = getCorePort();
2456
+ let coreHost = "host.docker.internal";
2457
+ try {
2458
+ const im = await lazyIm();
2459
+ const runtime = im.getInstanceRuntime(instanceId);
2460
+ if (!runtime?.image)
2461
+ coreHost = getCoreLanHost();
2462
+ }
2463
+ catch (error) {
2464
+ console.warn(`[openclaw] core URL runtime detection failed for ${instanceId}; using container-reachable host:`, error);
2465
+ }
2466
+ return {
2467
+ coreUrl: `http://${coreHost}:${corePort}`,
2468
+ internalToken: getInternalMcpToken(),
2469
+ };
2470
+ }
2471
+ async function syncImmichMcpForOpenclawInstance(instanceId) {
2472
+ const home = openclawIntegration.resolveAgentHome(instanceId);
2473
+ const configPath = openclawConfigPath(instanceId, home);
2474
+ const { resolveImmichConfig, } = await import("../immich/config.js");
2475
+ const config = await resolveImmichConfig();
2476
+ const source = {
2477
+ kind: "connection",
2478
+ slot: "photos",
2479
+ consumerInstanceId: instanceId,
2480
+ };
2481
+ const shimDir = join(home, "__mcp_shims__", "immich");
2482
+ const shimPath = join(shimDir, "immich-shim.js");
2483
+ const secretPath = join(shimDir, "secret.json");
2484
+ const wsDir = join(home, ".openclaw", "workspace");
2485
+ if (config?.baseUrl && config.apiKey) {
2486
+ const { IMMICH_SHIM_SECRET_FILENAME, substituteImmichShimPlaceholders, } = await import("../immich/immich-shim.js");
2487
+ ensureDirContainer(shimDir);
2488
+ const { coreUrl, internalToken, } = await resolveCoreConnectionForOpenclaw(instanceId);
2489
+ writeFileSync(shimPath, substituteImmichShimPlaceholders({
2490
+ baseUrl: config.baseUrl,
2491
+ photoLibraryEnabled: config.mode === "managed",
2492
+ coreUrl,
2493
+ instanceId,
2494
+ }), { mode: 0o644 });
2495
+ writeFileSync(join(shimDir, IMMICH_SHIM_SECRET_FILENAME), JSON.stringify({ apiKey: config.apiKey, internalToken }) + "\n", { mode: 0o600 });
2496
+ try {
2497
+ chmodSync(secretPath, 0o600);
2498
+ }
2499
+ catch { /* best effort */ }
2500
+ const nativeServerName = upsertOpenclawMcpServer(configPath, "immich", {
2501
+ command: "node",
2502
+ args: [shimPath],
2503
+ __source: source,
2504
+ });
2505
+ if (!nativeServerName)
2506
+ return "missing-config";
2507
+ removeMcporterServers(instanceId, { source });
2508
+ patchToolsMdImmichHint(wsDir, "install", nativeServerName);
2509
+ notifyConfigChange(instanceId);
2510
+ return "installed";
2511
+ }
2512
+ removeOpenclawMcpServers(configPath, { source });
2513
+ removeMcporterServers(instanceId, { source });
2514
+ rmSync(shimDir, { recursive: true, force: true });
2515
+ patchToolsMdImmichHint(wsDir, "remove");
2516
+ notifyConfigChange(instanceId);
2517
+ return "removed";
2518
+ }
2519
+ function isOpenclawInstanceMetadata(instance) {
2520
+ return Array.isArray(instance.integrations)
2521
+ && instance.integrations.some((entry) => entry?.kind === "openclaw");
2522
+ }
2523
+ // ── Docker image build helpers (physically migrated from setup-manager) ─
2524
+ //
2525
+ // All OpenClaw-specific docker image build knowledge lives here. setup-manager
2526
+ // only retains a thin dispatch wrapper so the public
2527
+ // `buildSlimOpenclawImage()` / `startBuildSlimOpenclawImage()` API remains
2528
+ // back-compatible for routes/setup.ts and the CLI installer.
2529
+ /** Matches a semver-ish tag suffix, e.g. "...:2026.4.9" or "...:v1.2.3-beta". */
2530
+ const PINNED_IMAGE_TAG_RE = /:[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$/;
2531
+ /**
2532
+ * Query the npm registry for the current OpenClaw version. Used to bust the
2533
+ * Docker layer cache for `RUN npm install openclaw@${ver}` during local build.
2534
+ */
2535
+ function resolveOpenclawNpmVersion() {
2536
+ try {
2537
+ const out = execFileSync("npm", ["view", "openclaw", "version"], {
2538
+ timeout: 15000,
2539
+ encoding: "utf-8",
2540
+ stdio: ["ignore", "pipe", "ignore"],
2541
+ }).trim();
2542
+ if (/^\d+\.\d+\.\d+/.test(out))
2543
+ return out;
2544
+ }
2545
+ catch {
2546
+ /* npm not reachable */
2547
+ }
2548
+ return "latest";
2549
+ }
2550
+ /**
2551
+ * Read the OpenClaw version bundled at /app/ inside a Docker image.
2552
+ */
2553
+ function readBundledOpenclawVersion(invocation, image) {
2554
+ try {
2555
+ const out = execFileSync(invocation.cmd, [
2556
+ ...invocation.argsPrefix,
2557
+ "run",
2558
+ "--rm",
2559
+ "--entrypoint",
2560
+ "node",
2561
+ image,
2562
+ "-p",
2563
+ "require('/app/node_modules/openclaw/package.json').version",
2564
+ ], { timeout: 20000, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim();
2565
+ if (/^\d+\.\d+\.\d+/.test(out))
2566
+ return out;
2567
+ }
2568
+ catch {
2569
+ /* docker unavailable, image missing, or path not present */
2570
+ }
2571
+ return "";
2572
+ }
2573
+ /**
2574
+ * Add a pinned version alias for an image, then drop the mutable :latest /
2575
+ * :slim tag. See original setup-manager commentary for details.
2576
+ */
2577
+ function capturePinnedImageTag(invocation, targetTag, explicitVersion) {
2578
+ if (PINNED_IMAGE_TAG_RE.test(targetTag))
2579
+ return targetTag;
2580
+ let version = explicitVersion && /^\d+\.\d+\.\d+/.test(explicitVersion) ? explicitVersion : "";
2581
+ if (!version) {
2582
+ version = readBundledOpenclawVersion(invocation, targetTag);
2583
+ }
2584
+ if (!version || !/^\d+\.\d+\.\d+/.test(version))
2585
+ return targetTag;
2586
+ const colonIdx = targetTag.lastIndexOf(":");
2587
+ const slashIdx = targetTag.lastIndexOf("/");
2588
+ const hasTag = colonIdx > slashIdx;
2589
+ const repo = hasTag ? targetTag.slice(0, colonIdx) : targetTag;
2590
+ const pinnedTag = `${repo}:${version}`;
2591
+ if (pinnedTag === targetTag)
2592
+ return targetTag;
2593
+ try {
2594
+ execFileSync(invocation.cmd, [...invocation.argsPrefix, "tag", targetTag, pinnedTag], { timeout: 10000, stdio: "ignore" });
2595
+ }
2596
+ catch {
2597
+ return targetTag;
2598
+ }
2599
+ if (/:(latest|slim)$/.test(targetTag)) {
2600
+ try {
2601
+ execFileSync(invocation.cmd, [...invocation.argsPrefix, "rmi", targetTag], { timeout: 10000, stdio: "ignore" });
2602
+ }
2603
+ catch {
2604
+ /* best-effort cleanup */
2605
+ }
2606
+ }
2607
+ return pinnedTag;
2608
+ }
2609
+ /**
2610
+ * Try docker pull, fall back to local `Dockerfile.openclaw-slim` build. This
2611
+ * is the primary image-prep path used by every setup flow. Called from the
2612
+ * integration's `buildRuntimeImage()` method.
2613
+ */
2614
+ async function pullOrBuildOpenclawImageWithTask(task, tag) {
2615
+ const targetTag = tag || DEFAULT_OPENCLAW_DOCKER_IMAGE;
2616
+ try {
2617
+ const invocation = resolveDockerInvocation();
2618
+ // Always attempt pull — when the image is already local and in sync
2619
+ // with upstream, docker returns within seconds after a digest check.
2620
+ // The "skip if image present" early exit was making "reinstall" feel
2621
+ // like a no-op; explicit re-pull matches user intent better. On pull
2622
+ // failure we still fall back to local build below.
2623
+ emitTask(task, { type: "progress", message: `正在拉取镜像: ${targetTag} ...`, progress: 10 });
2624
+ const pullResult = await spawnWithTask(task, invocation.cmd, [...invocation.argsPrefix, "pull", targetTag], { timeout: 600000 });
2625
+ if (pullResult.ok) {
2626
+ const pinned = capturePinnedImageTag(invocation, targetTag);
2627
+ setOpenclawDockerImage(pinned);
2628
+ emitTask(task, { type: "done", message: `镜像拉取成功: ${pinned}`, progress: 100 });
2629
+ task.status = "done";
2630
+ return { ok: true, message: `Docker image ${pinned} pulled`, taskId: task.id };
2631
+ }
2632
+ console.log(`[openclaw] docker pull failed for ${targetTag}, falling back to local build...`);
2633
+ emitTask(task, {
2634
+ type: "progress",
2635
+ message: `拉取失败,正在本地构建镜像: ${targetTag} ...`,
2636
+ progress: 20,
2637
+ });
2638
+ const projectRoot = join(dirname(fileURLToPath(import.meta.url)), "../../../..");
2639
+ const dockerfilePath = join(projectRoot, "Dockerfile.openclaw-slim");
2640
+ if (!existsSync(dockerfilePath)) {
2641
+ emitTask(task, {
2642
+ type: "error",
2643
+ message: "Dockerfile.openclaw-slim not found, cannot fallback to local build",
2644
+ });
2645
+ task.status = "error";
2646
+ return {
2647
+ ok: false,
2648
+ message: "Docker pull failed and Dockerfile.openclaw-slim not found",
2649
+ taskId: task.id,
2650
+ };
2651
+ }
2652
+ const openclawVersion = resolveOpenclawNpmVersion();
2653
+ console.log(`[openclaw] building image with OPENCLAW_VERSION=${openclawVersion}`);
2654
+ const buildResult = await spawnWithTask(task, invocation.cmd, [
2655
+ ...invocation.argsPrefix,
2656
+ "build",
2657
+ "--network=host",
2658
+ "--build-arg",
2659
+ `OPENCLAW_VERSION=${openclawVersion}`,
2660
+ "-f",
2661
+ dockerfilePath,
2662
+ "-t",
2663
+ targetTag,
2664
+ projectRoot,
2665
+ ], { timeout: 1800000, progressParser: dockerBuildProgressParser });
2666
+ if (!buildResult.ok) {
2667
+ try {
2668
+ execFileSync(invocation.cmd, [...invocation.argsPrefix, "image", "prune", "-f"], { timeout: 15000, stdio: "ignore" });
2669
+ }
2670
+ catch {
2671
+ /* best-effort */
2672
+ }
2673
+ emitTask(task, { type: "error", message: "Docker 镜像构建失败" });
2674
+ task.status = "error";
2675
+ return {
2676
+ ok: false,
2677
+ message: "Docker image build failed",
2678
+ error: buildResult.output,
2679
+ taskId: task.id,
2680
+ };
2681
+ }
2682
+ const pinned = capturePinnedImageTag(invocation, targetTag, openclawVersion);
2683
+ setOpenclawDockerImage(pinned);
2684
+ emitTask(task, {
2685
+ type: "done",
2686
+ message: `OpenClaw 镜像就绪 (本地构建): ${pinned}`,
2687
+ progress: 100,
2688
+ });
2689
+ task.status = "done";
2690
+ return { ok: true, message: `Docker image ${pinned} built locally`, taskId: task.id };
2691
+ }
2692
+ catch (e) {
2693
+ emitTask(task, { type: "error", message: `镜像获取失败: ${e.message}` });
2694
+ task.status = "error";
2695
+ return {
2696
+ ok: false,
2697
+ message: "Docker image pull/build failed",
2698
+ error: e.message,
2699
+ taskId: task.id,
2700
+ };
2701
+ }
2702
+ }
2703
+ // ── OpenClawIntegration class ─────────────────────────────────────────────
2704
+ class OpenClawIntegration {
2705
+ kind = "openclaw";
2706
+ displayName = "OpenClaw";
2707
+ defaultCapabilities = DEFAULT_CAPABILITIES;
2708
+ publicProxy = OPENCLAW_CONTROL_UI_PUBLIC_PROXY;
2709
+ preferredHostPort = OPENCLAW_PREFERRED_HOST_PORT;
2710
+ manifest = {
2711
+ kind: "openclaw",
2712
+ displayName: "OpenClaw",
2713
+ description: "默认 runtime,支持克隆、飞书 / 企业微信插件",
2714
+ defaultCapabilities: DEFAULT_CAPABILITIES,
2715
+ requiresNomadDocker: false,
2716
+ diskSpaceMB: 2048,
2717
+ catalogGroup: "agents",
2718
+ catalogIcon: "openclaw",
2719
+ defaultTab: "chat",
2720
+ supportsClone: true,
2721
+ connectionRole: "agent",
2722
+ defaultConnectionApplyMode: "proxy-upstream",
2723
+ requiredForSetupReady: true,
2724
+ defaultCreateAppSpecId: "openclaw-container",
2725
+ createAppSpecAliases: ["openclaw", "openclaw-container.yaml"],
2726
+ autoStartRequiresDefaultLlmProvider: true,
2727
+ embeddedUiSurface: "integration-control-ui",
2728
+ };
2729
+ async registerRoutes(app) {
2730
+ const { registerOpenclawRoutes } = await import("./routes.js");
2731
+ registerOpenclawRoutes(app);
2732
+ }
2733
+ hooks = {
2734
+ onCreatePrepare: async (ctx) => this.prepareInitialLayout(ctx),
2735
+ onPrepareControlUiOrigin: async ({ instanceId, origin, action }) => {
2736
+ const added = await ensureOpenclawControlUiAllowedOrigin(instanceId, origin);
2737
+ if (added) {
2738
+ console.log(`[openclaw-control-ui] prepared allowed origin for ${instanceId} action=${action} origin=${origin}`);
2739
+ }
2740
+ return added;
2741
+ },
2742
+ /**
2743
+ * Full OpenClaw pre-start prelude — used to live inline in
2744
+ * the Nomad driver's start path as an `if (!hermes) { ... }` branch
2745
+ * (~80 lines). Framework code now calls this hook uniformly for every
2746
+ * kind; Hermes provides a no-op and OpenClaw owns the full sequence:
2747
+ *
2748
+ * 1. Ensure `openclaw.json` exists + fix state-dir permissions
2749
+ * 2. Docker-bridge: patch gateway.bind + jsproxy baseUrl
2750
+ * 3. Seed `$HOME/.npm-global` for in-gateway "Update now"
2751
+ * 4. Validate + image-inspect the Docker image; background-pull on miss
2752
+ * 5. Write JSPROXY_API_KEY into Nomad Variables
2753
+ *
2754
+ * Throws on fatal errors. Framework catches and returns the structured
2755
+ * result; a `taskId` property on the thrown error signals an async
2756
+ * image pull in progress.
2757
+ *
2758
+ * Step 13 (2026-06-09): the historical "stop legacy host-mode
2759
+ * subprocess" step has been removed. Host-mode / process-manager
2760
+ * driven instances are no longer supported on the runtime path;
2761
+ * `jishushell migrate legacy` must convert them to canonical
2762
+ * `apps/<id>` layout before they can be started under Nomad.
2763
+ */
2764
+ onBeforeStart: async ({ instanceId }) => {
2765
+ // 1. Config path existence check + permissions — use local resolvers
2766
+ // instead of lazy importing back into instance-manager.
2767
+ let configPath;
2768
+ try {
2769
+ configPath = openclawIntegration.resolveConfigPath(instanceId);
2770
+ }
2771
+ catch {
2772
+ return; // bail gracefully for non-OpenClaw instances
2773
+ }
2774
+ if (!existsSync(configPath)) {
2775
+ throw new Error("Config file not found");
2776
+ }
2777
+ if (getNomadDriver() === "docker") {
2778
+ const stateDir = dirname(configPath);
2779
+ ensureDirContainer(stateDir);
2780
+ try {
2781
+ for (const entry of readdirSync(stateDir, { withFileTypes: true })) {
2782
+ if (entry.isDirectory()) {
2783
+ const sub = join(stateDir, entry.name);
2784
+ ensureDirContainer(sub);
2785
+ try {
2786
+ for (const child of readdirSync(sub, { withFileTypes: true })) {
2787
+ if (child.isDirectory())
2788
+ ensureDirContainer(join(sub, child.name));
2789
+ }
2790
+ }
2791
+ catch {
2792
+ /* ignore */
2793
+ }
2794
+ }
2795
+ }
2796
+ }
2797
+ catch {
2798
+ /* ignore */
2799
+ }
2800
+ if (existsSync(configPath))
2801
+ chmodSync(configPath, 0o644);
2802
+ // 3. Docker bridge patches
2803
+ patchDockerBridgeGatewayBind(configPath);
2804
+ patchJsproxyBaseUrl(configPath);
2805
+ patchPrivateNetworkAllowFlag(configPath);
2806
+ }
2807
+ // Driver-agnostic: enable the OpenAI-compatible endpoints on every
2808
+ // start so the `llm-agent` capability advertised by openclaw-*.yaml
2809
+ // works for both fresh installs and instances created before this
2810
+ // patcher shipped. Idempotent — bails out fast if already enabled.
2811
+ patchOpenAIEndpointsEnabled(configPath);
2812
+ // 4. npm update-seed — use local resolver
2813
+ try {
2814
+ const home = openclawIntegration.resolveAgentHome(instanceId);
2815
+ if (home)
2816
+ ensureOpenclawUpdateSeed(home, instanceId);
2817
+ }
2818
+ catch {
2819
+ /* best effort */
2820
+ }
2821
+ // 4a. Patch session fence bug in OpenClaw >= 5.19
2822
+ try {
2823
+ const home = openclawIntegration.resolveAgentHome(instanceId);
2824
+ if (home) {
2825
+ patchSessionFenceBug(home, instanceId);
2826
+ // Also write the container-side patch script so that even if
2827
+ // the host-side patch couldn't apply (e.g. symlink to container
2828
+ // path), the container will self-patch on startup.
2829
+ if (getNomadDriver() === "docker") {
2830
+ writeContainerPatchScript(home);
2831
+ }
2832
+ }
2833
+ }
2834
+ catch {
2835
+ /* best effort — patch failure must not prevent start */
2836
+ }
2837
+ // 4b. Build the workspace symlink layout from this instance's
2838
+ // fileMounts (M1 W2). For docker mode, the corresponding
2839
+ // volume bindings are added in buildNomadTask below; for
2840
+ // raw_exec / process modes, the symlinks are sufficient
2841
+ // (no container layer between agent and host fs).
2842
+ try {
2843
+ const home = openclawIntegration.resolveAgentHome(instanceId);
2844
+ const im = await lazyIm();
2845
+ const runtime = im.getInstanceRuntime(instanceId);
2846
+ const mounts = readFileMounts(runtime);
2847
+ if (home) {
2848
+ const { rebuildWorkspace } = await import("../../workspaces/builder.js");
2849
+ rebuildWorkspace({
2850
+ integrationHome: home,
2851
+ filesRoot: FILES_ROOT,
2852
+ mounts,
2853
+ instanceId,
2854
+ });
2855
+ }
2856
+ }
2857
+ catch (e) {
2858
+ // Surface migration-required clearly; otherwise fall back to a
2859
+ // warning so a misconfigured mount cannot prevent instance start.
2860
+ if (e?.reason === "needs-migration") {
2861
+ throw new Error(`instance ${instanceId} workspace contains pre-W2 user data; run legacy migration first (${e.message})`);
2862
+ }
2863
+ console.warn(`[openclaw] workspace rebuild skipped: ${e?.message ?? e}`);
2864
+ }
2865
+ // 4b-bis. Patch TOOLS.md with the drive-shim hint so the agent
2866
+ // understands user files are local (host==container bind) and
2867
+ // knows the resolve→send chain for IM channels. Without this,
2868
+ // the LLM defaults to "drive = remote cloud service" and
2869
+ // refuses to send NAS files via Feishu/WeChat. Runs after the
2870
+ // workspace rebuild because that step creates the workspace
2871
+ // tree if missing.
2872
+ try {
2873
+ const home = openclawIntegration.resolveAgentHome(instanceId);
2874
+ if (home) {
2875
+ patchToolsMdDriveHint(join(home, ".openclaw", "workspace"), FILES_ROOT, join(home, ".npm-global", "bin", "jishushell-mcporter"), instanceId);
2876
+ }
2877
+ }
2878
+ catch (e) {
2879
+ console.warn(`[openclaw] TOOLS.md drive hint skipped: ${e?.message ?? e}`);
2880
+ }
2881
+ try {
2882
+ const home = openclawIntegration.resolveAgentHome(instanceId);
2883
+ if (home) {
2884
+ const configPath = openclawConfigPath(instanceId, home);
2885
+ const runtimeConfig = existsSync(configPath)
2886
+ ? JSON.parse(readFileSync(configPath, "utf-8"))
2887
+ : {};
2888
+ const shouldInstallBrowserlessHint = runtimeConfig?.browser?.defaultProfile === BROWSERLESS_PROFILE;
2889
+ patchToolsMdBrowserlessHint(join(home, ".openclaw", "workspace"), shouldInstallBrowserlessHint ? "install" : "remove");
2890
+ }
2891
+ }
2892
+ catch (e) {
2893
+ console.warn(`[openclaw] TOOLS.md browserless hint skipped: ${e?.message ?? e}`);
2894
+ }
2895
+ // 4b-ter. Rotate stale session jsonl(s) when the runtime contract
2896
+ // bumps. This is the auto-recovery path for panel upgrades
2897
+ // that fix runtime bugs the agent has already "concluded
2898
+ // around" inside an existing session — without rotation the
2899
+ // LLM keeps citing past failures and refusing to retry even
2900
+ // after the underlying bug is fixed. Idempotent: after the
2901
+ // first onBeforeStart post-upgrade writes the new marker,
2902
+ // subsequent starts are no-ops.
2903
+ try {
2904
+ const home = openclawIntegration.resolveAgentHome(instanceId);
2905
+ if (home)
2906
+ rotateSessionsIfContractChanged(instanceId, home);
2907
+ }
2908
+ catch (e) {
2909
+ console.warn(`[openclaw] session rotation skipped: ${e?.message ?? e}`);
2910
+ }
2911
+ // 4c. Install the drive MCP shim so the agent can call panel
2912
+ // file/organize APIs from chat (M1 W1.6). Idempotent — we
2913
+ // overwrite the shim file every start to pick up fixes, and
2914
+ // mergeMcporterServers marks the entry with __source so user-
2915
+ // managed mcporter entries are preserved untouched.
2916
+ try {
2917
+ const home = openclawIntegration.resolveAgentHome(instanceId);
2918
+ if (home) {
2919
+ const { substituteDriveShimPlaceholders } = await import("./drive-shim.js");
2920
+ const { mergeMcporterServers } = await import("./mcporter.js");
2921
+ // Pick the core URL based on how THIS instance will actually run.
2922
+ // For a containerized instance (raw_exec/docker via Nomad with a
2923
+ // docker image), `host.docker.internal:<corePort>` resolves through
2924
+ // the bridge gateway. For a host-process / binary spec under Nomad
2925
+ // raw_exec, the task gets its own network namespace where
2926
+ // 127.0.0.1 only reaches the task itself — must use the host's
2927
+ // LAN IPv4 so the shim's fetch crosses back into the host netns.
2928
+ // Detected via the instance's resolved runtime: container tasks
2929
+ // carry `runtime.image`, binary tasks carry only `runtime.command`.
2930
+ const corePort = getCorePort();
2931
+ const { coreUrl: driveCoreUrl, internalToken, } = await resolveCoreConnectionForOpenclaw(instanceId);
2932
+ const shimDir = join(home, "__mcp_shims__", "drive");
2933
+ ensureDirContainer(shimDir);
2934
+ const shimPath = join(shimDir, "drive-shim.mjs");
2935
+ // Bake coreUrl/token/instanceId into the shim source so it works
2936
+ // even when OpenClaw scrubs env on MCP subprocess spawn (verified
2937
+ // 2026-05-11 on pi2: env scrub made the shim default to the
2938
+ // unreachable host.docker.internal and surface as "fetch failed").
2939
+ const shimSource = substituteDriveShimPlaceholders({
2940
+ coreUrl: driveCoreUrl,
2941
+ token: internalToken,
2942
+ instanceId,
2943
+ });
2944
+ writeFileSync(shimPath, shimSource, { mode: 0o755 });
2945
+ mergeMcporterServers(instanceId, {
2946
+ drive: {
2947
+ command: "node",
2948
+ args: [shimPath],
2949
+ env: {
2950
+ // Env still set as a belt-and-suspenders. With baked-in
2951
+ // values in the shim source itself, these become a fallback
2952
+ // for dev/manual testing — production never depends on them.
2953
+ JISHUSHELL_INTERNAL_TOKEN: internalToken,
2954
+ JISHUSHELL_INSTANCE_ID: instanceId,
2955
+ JISHUSHELL_CORE_URL: driveCoreUrl,
2956
+ JISHUSHELL_CORE_PORT: String(corePort),
2957
+ },
2958
+ __source: {
2959
+ kind: "connection",
2960
+ slot: "drive",
2961
+ consumerInstanceId: instanceId,
2962
+ },
2963
+ },
2964
+ });
2965
+ }
2966
+ }
2967
+ catch (e) {
2968
+ console.warn(`[openclaw] drive shim install skipped: ${e?.message ?? e}`);
2969
+ }
2970
+ // 4c-quater. Auto-wire knowledge MCP shim. The Connections-tab
2971
+ // knowledge slot (declared as `requires: knowledge` on the
2972
+ // OpenClaw spec, persisted under `instance.connections.KNOWLEDGE_BASE_URL`)
2973
+ // is honored here, so unbinding in the UI actually takes effect.
2974
+ // Provider resolution (matching connection-resolver.ts):
2975
+ //
2976
+ // - `null` → user explicitly disconnected →
2977
+ // DO NOT inject (and strip any prior shim).
2978
+ // - kind=single + providerId → use that provider's shim.
2979
+ // - kind=many → first known match in user order wins.
2980
+ // - undefined/unknown → no provider; migration/repair may
2981
+ // materialize old defaults into an
2982
+ // explicit binding, but runtime never
2983
+ // guesses from credentials.json.
2984
+ //
2985
+ // Mutual cleanup: rebinding from anythingllm → jishukb (or
2986
+ // vice versa, or → null) wipes the OTHER provider's shim dir
2987
+ // in EVERY branch. Leaving a 0o600 secret.json + bearer-
2988
+ // prefilled shim source on disk after unbind would be a
2989
+ // lingering security smell.
2990
+ //
2991
+ // Secrets handling (defense-in-depth, anythingllm only):
2992
+ // - shim source (mode 0o644) carries baseUrl + workspace only;
2993
+ // the API key lives in a sibling `secret.json` (0o600).
2994
+ // - mcporter.json (0o644) env carries only non-secret hints
2995
+ // for hand-running. Production shim reads the secret file.
2996
+ // JishuKB remote MCP auth is stored on the managed KB runtime and
2997
+ // provider credentials, not in the legacy shim directory.
2998
+ try {
2999
+ const home = openclawIntegration.resolveAgentHome(instanceId);
3000
+ if (home) {
3001
+ const instMeta = getInstance(instanceId);
3002
+ const provider = resolveKbProvider(instMeta?.connections?.KNOWLEDGE_BASE_URL);
3003
+ const mcporterCommand = join(home, ".npm-global", "bin", "jishushell-mcporter");
3004
+ const wsDir = join(home, ".openclaw", "workspace");
3005
+ const anyllmShimDir = join(home, "__mcp_shims__", "anythingllm");
3006
+ const anyllmShimPath = join(anyllmShimDir, "anythingllm-shim.js");
3007
+ const anyllmSecretPath = join(anyllmShimDir, "secret.json");
3008
+ const { mergeMcporterServers, removeMcporterServers } = await import("./mcporter.js");
3009
+ const { removeOpenclawMcpServers, upsertFixedOpenclawMcpServer } = await import("./native-mcp.js");
3010
+ const kbSource = { kind: "connection", slot: "knowledge", consumerInstanceId: instanceId };
3011
+ const openclawCfgPath = openclawConfigPath(instanceId, home);
3012
+ const cleanupManagedKb = (unavailableReason) => {
3013
+ removeMcporterServers(instanceId, { source: kbSource });
3014
+ removeOpenclawMcpServers(openclawCfgPath, { source: kbSource });
3015
+ notifyConfigChange(instanceId);
3016
+ if (unavailableReason) {
3017
+ patchToolsMdKbUnavailableHint(wsDir, unavailableReason);
3018
+ }
3019
+ else {
3020
+ patchToolsMdKbHint(wsDir, "remove");
3021
+ }
3022
+ wipeKbShimDir(home, "jishukb");
3023
+ };
3024
+ if (provider === "jishukb") {
3025
+ // Wipe the OTHER provider's residue first (including its
3026
+ // 0o600 secret.json). Security smell to leave it on disk.
3027
+ wipeKbShimDir(home, "anythingllm");
3028
+ const credPath = resolveProviderCredentialsPath("jishu-kb-container");
3029
+ let creds = null;
3030
+ if (existsSync(credPath)) {
3031
+ try {
3032
+ creds = JSON.parse(readFileSync(credPath, "utf-8"));
3033
+ }
3034
+ catch (e) {
3035
+ console.warn(`[openclaw] kb: invalid jishu-kb credentials.json: ${e?.message ?? e}`);
3036
+ }
3037
+ }
3038
+ if (creds?.baseUrl) {
3039
+ const mediaInbound = join(home, ".openclaw", "media", "inbound");
3040
+ ensureDirContainer(mediaInbound);
3041
+ const authToken = typeof creds.mcpAuthToken === "string" ? creds.mcpAuthToken.trim() : "";
3042
+ const { discoverJishukbRemoteMcp, preflightJishukbRemoteMcp } = await import("./jishukb-native-mcp.js");
3043
+ const discovery = await discoverJishukbRemoteMcp({
3044
+ baseUrl: creds.baseUrl,
3045
+ authToken,
3046
+ expectedProfile: "openclaw",
3047
+ });
3048
+ if (!discovery.ok || !discovery.url) {
3049
+ const reason = `remote jishu-kb MCP discovery failed: ${discovery.reason || "no endpoint"}`;
3050
+ console.warn(`[openclaw] kb: ${reason}`);
3051
+ cleanupManagedKb(reason);
3052
+ }
3053
+ else {
3054
+ if (discovery.authRequired && !authToken) {
3055
+ const reason = "remote jishu-kb MCP requires bearer auth but credentials are missing mcpAuthToken";
3056
+ console.warn(`[openclaw] kb: ${reason}`);
3057
+ cleanupManagedKb(reason);
3058
+ }
3059
+ else {
3060
+ const preflight = await preflightJishukbRemoteMcp({
3061
+ url: discovery.url,
3062
+ authToken,
3063
+ expectedProfile: "openclaw",
3064
+ });
3065
+ if (!preflight.ok) {
3066
+ const reason = `remote jishu-kb MCP preflight failed: ${preflight.reason}`;
3067
+ console.warn(`[openclaw] kb: ${reason}`);
3068
+ cleanupManagedKb(reason);
3069
+ }
3070
+ else {
3071
+ const registeredUrl = rewriteJishukbMcpUrlForOpenClawRuntime(discovery.url, instMeta?.runtime ?? {});
3072
+ const entry = {
3073
+ url: registeredUrl,
3074
+ transport: "streamable-http",
3075
+ connectionTimeoutMs: 8_000,
3076
+ __source: kbSource,
3077
+ };
3078
+ if (authToken) {
3079
+ entry.headers = { Authorization: `Bearer ${authToken}` };
3080
+ }
3081
+ wipeKbShimDir(home, "jishukb");
3082
+ removeMcporterServers(instanceId, { source: kbSource });
3083
+ const result = upsertFixedOpenclawMcpServer(openclawCfgPath, "kb", entry);
3084
+ if (!result.ok) {
3085
+ const reason = result.reason === "name-conflict"
3086
+ ? "user-managed native MCP server 'kb' blocks managed JishuKB registration"
3087
+ : "OpenClaw native config is missing; managed JishuKB registration skipped";
3088
+ console.warn(`[openclaw] kb: ${reason}`);
3089
+ cleanupManagedKb(reason);
3090
+ }
3091
+ else {
3092
+ notifyConfigChange(instanceId);
3093
+ patchToolsMdKbHint(wsDir, "install", "jishukb", "native", instanceId, mediaInbound);
3094
+ }
3095
+ }
3096
+ }
3097
+ }
3098
+ }
3099
+ else {
3100
+ // jishu-kb bound but baseUrl not yet ready / credentials missing.
3101
+ // Remove any prior kb registration so the agent doesn't
3102
+ // call a stale shim, and wipe our own shim dir for hygiene.
3103
+ const reason = `jishu-kb bound but baseUrl missing at ${credPath}; native MCP registration skipped`;
3104
+ console.warn(`[openclaw] kb: ${reason}`);
3105
+ cleanupManagedKb(reason);
3106
+ }
3107
+ }
3108
+ else if (provider === "anythingllm") {
3109
+ // Wipe the OTHER provider's residue first.
3110
+ wipeKbShimDir(home, "jishukb");
3111
+ removeOpenclawMcpServers(openclawCfgPath, { source: kbSource });
3112
+ notifyConfigChange(instanceId);
3113
+ const credPath = resolveProviderCredentialsPath("anythingllm-container");
3114
+ let kbCreds = null;
3115
+ if (existsSync(credPath)) {
3116
+ try {
3117
+ kbCreds = JSON.parse(readFileSync(credPath, "utf-8"));
3118
+ }
3119
+ catch (e) {
3120
+ console.warn(`[openclaw] kb: invalid credentials.json: ${e?.message ?? e}`);
3121
+ }
3122
+ }
3123
+ if (kbCreds?.apiKey && kbCreds?.baseUrl) {
3124
+ const { substituteAnythingllmShimPlaceholders } = await import("./anythingllm-shim.js");
3125
+ ensureDirContainer(anyllmShimDir);
3126
+ const shimSource = substituteAnythingllmShimPlaceholders({
3127
+ baseUrl: kbCreds.baseUrl,
3128
+ workspace: kbCreds.workspace || "default",
3129
+ });
3130
+ writeFileSync(anyllmShimPath, shimSource, { mode: 0o644 });
3131
+ // chmod after write to dodge umask; secret.json must be 0o600.
3132
+ writeFileSync(anyllmSecretPath, JSON.stringify({ apiKey: kbCreds.apiKey }), { mode: 0o600 });
3133
+ try {
3134
+ chmodSync(anyllmSecretPath, 0o600);
3135
+ }
3136
+ catch { /* best effort */ }
3137
+ mergeMcporterServers(instanceId, {
3138
+ kb: {
3139
+ command: "node",
3140
+ args: [anyllmShimPath],
3141
+ env: {
3142
+ // Belt-and-suspenders fallback for hand-running. Baked
3143
+ // values in the shim source are the production source
3144
+ // of truth for baseUrl + workspace; the API key is
3145
+ // intentionally NOT placed here — it lives in
3146
+ // `secret.json` (0o600) next to the shim so this 0o644
3147
+ // file stays free of secrets.
3148
+ ANYTHINGLLM_BASE_URL: kbCreds.baseUrl,
3149
+ ANYTHINGLLM_WORKSPACE: kbCreds.workspace || "default",
3150
+ },
3151
+ __source: {
3152
+ kind: "connection",
3153
+ slot: "knowledge",
3154
+ consumerInstanceId: instanceId,
3155
+ },
3156
+ },
3157
+ });
3158
+ patchToolsMdKbHint(wsDir, "install", "anythingllm", mcporterCommand);
3159
+ }
3160
+ else {
3161
+ // AnythingLLM bound but creds missing → strip and clean.
3162
+ removeMcporterServers(instanceId, {
3163
+ source: { kind: "connection", slot: "knowledge", consumerInstanceId: instanceId },
3164
+ });
3165
+ patchToolsMdKbHint(wsDir, "remove");
3166
+ wipeKbShimDir(home, "anythingllm");
3167
+ }
3168
+ }
3169
+ else {
3170
+ // provider === null → user explicitly unbound, or bound to
3171
+ // an unknown/unsupported provider. Strip kb server and wipe
3172
+ // both shim dirs.
3173
+ cleanupManagedKb();
3174
+ wipeKbShimDir(home, "anythingllm");
3175
+ }
3176
+ }
3177
+ }
3178
+ catch (e) {
3179
+ console.warn(`[openclaw] kb shim wiring skipped: ${e?.message ?? e}`);
3180
+ }
3181
+ // 4c-quinquies. Auto-wire Immich MCP when the Immich integration has
3182
+ // endpoint credentials. The endpoint can be external or a managed
3183
+ // immich-container instance. OpenClaw receives the stdio shim through
3184
+ // its native `mcp.servers` config, the API key and Core internal token
3185
+ // stay in a 0o600 sibling secret file, and user review interactions are
3186
+ // created through Core-owned Immich routes.
3187
+ try {
3188
+ await syncImmichMcpForOpenclawInstance(instanceId);
3189
+ }
3190
+ catch (e) {
3191
+ console.warn(`[openclaw] immich shim wiring skipped: ${e?.message ?? e}`);
3192
+ }
3193
+ // 4c-bis. Self-heal MCPORTER_CONFIG env on existing instances. Without
3194
+ // this, mcporter can't find its config when invoked from the
3195
+ // gateway's CWD (openclaw-home/) or from the workspace symlink
3196
+ // (which points at user files, also no config/), so every drive
3197
+ // tool call fails with "Unknown MCP server 'drive'" and the agent
3198
+ // degrades into reporting a generic "network error". New instances
3199
+ // get this env via the binary/container runtime template; this
3200
+ // block back-fills it for instances created before that template
3201
+ // update so users don't have to recreate them.
3202
+ try {
3203
+ const im2 = await lazyIm();
3204
+ const rt = im2.getInstanceRuntime(instanceId);
3205
+ const home = openclawIntegration.resolveAgentHome(instanceId);
3206
+ if (home && rt && (!rt.env || !rt.env.MCPORTER_CONFIG)) {
3207
+ const desired = `${home}/.openclaw/workspace/config/mcporter.json`;
3208
+ const nextEnv = { ...(rt.env || {}), MCPORTER_CONFIG: desired };
3209
+ im2.updateInstanceMeta(instanceId, { runtime: { ...rt, env: nextEnv } });
3210
+ console.log(`[openclaw] self-healed MCPORTER_CONFIG env for ${instanceId}`);
3211
+ }
3212
+ }
3213
+ catch (e) {
3214
+ console.warn(`[openclaw] MCPORTER_CONFIG self-heal failed: ${e?.message ?? e}`);
3215
+ }
3216
+ // 4d. Install a standalone mcporter-compatible FALLBACK wrapper at
3217
+ // `$OPENCLAW_HOME/.npm-global/bin/jishushell-mcporter`. Fresh
3218
+ // instances often do not carry an actual mcporter npm install, yet
3219
+ // TOOLS.md asks the model to shell out for drive/kb access. Keep
3220
+ // the fallback on a distinct path so we do NOT clobber a real
3221
+ // mcporter install that may support transports/features beyond this
3222
+ // wrapper's narrow built-in scope.
3223
+ try {
3224
+ const home = openclawIntegration.resolveAgentHome(instanceId);
3225
+ if (home) {
3226
+ const mcporterBin = join(home, ".npm-global", "bin", "jishushell-mcporter");
3227
+ ensureDirContainer(join(home, ".npm-global", "bin"));
3228
+ writeFileSync(mcporterBin, renderStandaloneMcporterSource(), { mode: 0o755 });
3229
+ try {
3230
+ chmodSync(mcporterBin, 0o755);
3231
+ }
3232
+ catch { /* best effort */ }
3233
+ console.log(`[openclaw] installed standalone mcporter fallback at ${mcporterBin}`);
3234
+ }
3235
+ }
3236
+ catch (e) {
3237
+ console.warn(`[openclaw] mcporter self-heal failed: ${e?.message ?? e}`);
3238
+ }
3239
+ // 5. Docker image validation + background pull fallback
3240
+ if (getNomadDriver() === "docker") {
3241
+ const image = getOpenclawDockerImage();
3242
+ if (!DOCKER_IMAGE_RE.test(image) || image.length > MAX_DOCKER_IMAGE_NAME_LEN) {
3243
+ throw new Error(`Invalid Docker image name: "${image}"`);
3244
+ }
3245
+ const imageCheck = inspectDockerImage(image, { timeout: 10000 });
3246
+ if (!imageCheck.ok) {
3247
+ const inspectError = toDockerInspectUserError(image, imageCheck);
3248
+ if (imageCheck.reason !== "not_found") {
3249
+ const err = new Error(inspectError.message);
3250
+ err.code = inspectError.code;
3251
+ err.statusCode = inspectError.statusCode;
3252
+ throw err;
3253
+ }
3254
+ console.log(`[openclaw] Docker image ${image} not found, starting background pull`);
3255
+ try {
3256
+ const result = openclawIntegration.startBuildRuntimeImage({ tag: image });
3257
+ const err = new Error(`${inspectError.message} Pull started in background.`);
3258
+ err.building = true;
3259
+ err.taskId = result.taskId;
3260
+ err.code = inspectError.code;
3261
+ err.statusCode = 202;
3262
+ throw err;
3263
+ }
3264
+ catch (e) {
3265
+ if (e?.building)
3266
+ throw e;
3267
+ throw new Error(`Docker image ${image} not available: ${e?.message ?? e}`);
3268
+ }
3269
+ }
3270
+ }
3271
+ // 6. Write instance secrets to Nomad Variables
3272
+ try {
3273
+ const nomad = await import("../../runtime/drivers/nomad.js");
3274
+ if (typeof nomad.writeInstanceVariables === "function") {
3275
+ await nomad.writeInstanceVariables(instanceId);
3276
+ }
3277
+ }
3278
+ catch (e) {
3279
+ throw new Error(`Failed to store instance secrets in Nomad Variables: ${e?.message ?? e}`);
3280
+ }
3281
+ },
3282
+ /**
3283
+ * OpenClaw auto-installs IM channel plugins (feishu, weixin, etc.) when
3284
+ * they're enabled in `openclaw.json`. That logic currently lives in
3285
+ * `instance-manager.saveConfig()`; wiring it through this hook is a
3286
+ * no-op during MVP because saveConfig still runs inline. The hook
3287
+ * exists so the physical-migration follow-up PR can move the code into
3288
+ * this file without touching framework code.
3289
+ */
3290
+ onConfigSaved: async (_args) => {
3291
+ /* reserved — channel plugin install hook, filled by follow-up PR */
3292
+ },
3293
+ onCreate: async ({ instanceId, createArgs }) => {
3294
+ await finalizeOpenclawCreatedInstance(instanceId, createArgs);
3295
+ },
3296
+ /**
3297
+ * Surface an orphan-directory warning when the canonical integration home
3298
+ * points outside the instance dir. The framework's deleteInstance
3299
+ * only rm's the instance dir itself, so custom-home layouts leave a
3300
+ * tree that the operator must clean up manually — UNLESS the Step 5
3301
+ * ownership marker proves Core created the tree as part of THIS
3302
+ * instance, in which case it is safe to remove.
3303
+ */
3304
+ onDelete: async ({ instanceId, meta }) => {
3305
+ const home = openclawHomeFromMetadata(meta, instanceId);
3306
+ const instDir = framework_instanceDir(instanceId);
3307
+ if (home.startsWith(instDir))
3308
+ return; // inside the instance dir — rm already caught it
3309
+ if (!existsSync(home))
3310
+ return;
3311
+ // Step 5: marker match is the canonical proof of Core ownership.
3312
+ // Without it we MUST NOT delete — the directory might be user data
3313
+ // (e.g. a hand-curated `~/.openclaw-data`) that happened to be
3314
+ // selected as the integration home for read-only reuse.
3315
+ if (isOwnedByInstance(home, instanceId)) {
3316
+ try {
3317
+ rmSync(home, { recursive: true, force: true });
3318
+ return;
3319
+ }
3320
+ catch (e) {
3321
+ return {
3322
+ warnings: [
3323
+ `Failed to remove Core-owned OpenClaw integration home '${home}': ${e?.message ?? e}. Delete manually.`,
3324
+ ],
3325
+ };
3326
+ }
3327
+ }
3328
+ return {
3329
+ warnings: [
3330
+ `Custom OpenClaw integration home '${home}' was preserved (no Core ownership marker found). Delete manually if no longer needed.`,
3331
+ ],
3332
+ };
3333
+ },
3334
+ /**
3335
+ * Rewrite `openclaw.json` x-jishushell.proxy.upstream when the panel
3336
+ * default provider changes. Delegates to instance-manager's existing
3337
+ * helper so the transition stays stepwise.
3338
+ */
3339
+ onUpstreamProviderChange: async ({ instanceId, upstream }) => {
3340
+ try {
3341
+ const im = await lazyIm();
3342
+ if (typeof im.pushUpstreamToInstance === "function") {
3343
+ await im.pushUpstreamToInstance(instanceId, upstream);
3344
+ }
3345
+ }
3346
+ catch (e) {
3347
+ console.warn(`[openclaw] onUpstreamProviderChange failed for ${instanceId}: ${e.message}`);
3348
+ }
3349
+ },
3350
+ };
3351
+ async prepareInitialLayout(ctx) {
3352
+ const instDir = framework_instanceDir(ctx.instanceId);
3353
+ const metaPath = instanceMetaPath(ctx.instanceId);
3354
+ if (existsSync(metaPath))
3355
+ throw new Error(`Instance '${ctx.instanceId}' already exists`);
3356
+ if (existsSync(instDir) && !isPrecreatedManagedAppDir(instDir)) {
3357
+ throw new Error(`Instance '${ctx.instanceId}' already exists`);
3358
+ }
3359
+ const integrationHome = ctx.integrationHome
3360
+ ? normalizePath(ctx.integrationHome)
3361
+ : defaultOpenclawHome(ctx.instanceId);
3362
+ if (ctx.integrationHome) {
3363
+ const resolved = pathResolve(integrationHome);
3364
+ if (!resolved.startsWith(JISHUSHELL_HOME) && !resolved.startsWith("/home/")) {
3365
+ throw new Error(`OpenClaw integration home must be under ${JISHUSHELL_HOME} or /home/`);
3366
+ }
3367
+ const parentDir = dirname(resolved);
3368
+ if (existsSync(parentDir)) {
3369
+ const realParent = realpathSync(parentDir);
3370
+ if (!realParent.startsWith(JISHUSHELL_HOME) && !realParent.startsWith("/home/")) {
3371
+ throw new Error(`OpenClaw integration home parent resolves outside allowed paths (symlink detected)`);
3372
+ }
3373
+ }
3374
+ const shared = listInstances().filter((inst) => normalizePath(openclawHomeFromMetadata(inst, inst.id)) ===
3375
+ normalizePath(integrationHome));
3376
+ if (shared.length) {
3377
+ throw new Error(`OpenClaw home '${integrationHome}' is already used by instance(s): ${shared
3378
+ .map((i) => i.id)
3379
+ .join(", ")}`);
3380
+ }
3381
+ }
3382
+ if (existsSync(integrationHome)) {
3383
+ try {
3384
+ const entries = readdirSync(integrationHome);
3385
+ if (entries.length > 0) {
3386
+ // Step 5 (bootstrap ownership marker): non-empty directories are
3387
+ // disambiguated via the ownership marker rather than treated as
3388
+ // "already installed".
3389
+ // - Marker present AND `instanceId` matches → this is debris
3390
+ // from a previous failed install of THE SAME instance id.
3391
+ // Safe to wipe the contents and retry from scratch (preserve
3392
+ // the directory itself so chown/permissions stay stable).
3393
+ // - Marker present but a different `instanceId` → another
3394
+ // instance owns this tree (catches the case where the path
3395
+ // conflict check above missed because the other instance
3396
+ // was already deleted but the home was left behind).
3397
+ // - Marker absent → user data (e.g. a hand-curated
3398
+ // `~/.openclaw-data` populated before installing JishuShell).
3399
+ // Refuse to touch it.
3400
+ if (isOwnedByInstance(integrationHome, ctx.instanceId)) {
3401
+ for (const entry of entries) {
3402
+ rmSync(join(integrationHome, entry), { recursive: true, force: true });
3403
+ }
3404
+ }
3405
+ else {
3406
+ throw new Error(`OpenClaw home directory '${integrationHome}' already exists and is not empty. ` +
3407
+ `Remove it manually or choose a different path.`);
3408
+ }
3409
+ }
3410
+ }
3411
+ catch (e) {
3412
+ if (e.message.includes("not empty"))
3413
+ throw e;
3414
+ }
3415
+ }
3416
+ ensureDirContainer(instDir);
3417
+ try {
3418
+ const parentGid = statSync(dirname(instDir)).gid;
3419
+ chownSync(instDir, -1, parentGid);
3420
+ }
3421
+ catch {
3422
+ /* non-root without CAP_CHOWN */
3423
+ }
3424
+ ensureDirContainer(integrationHome);
3425
+ // Step 5: write the ownership marker as soon as the home directory
3426
+ // exists. Doing this BEFORE any other subdir creation makes the
3427
+ // marker the earliest persisted signal of Core ownership — if any
3428
+ // subsequent setup step throws, the next install retry's pre-check
3429
+ // will see the matching marker and proceed via the "wipe and retry"
3430
+ // branch above. The marker is consulted only by install pre-check,
3431
+ // install rollback, and uninstall — never by start/status/proxy
3432
+ // paths (presence MUST NOT be interpreted as "instance running").
3433
+ writeOwnershipMarker(integrationHome, {
3434
+ instanceId: ctx.instanceId,
3435
+ integrationKind: "openclaw",
3436
+ });
3437
+ ensureDirContainer(join(integrationHome, OPENCLAW_STATE_DIRNAME));
3438
+ return {
3439
+ instanceDir: instDir,
3440
+ integrationHome,
3441
+ primaryConfig: join(integrationHome, OPENCLAW_STATE_DIRNAME, OPENCLAW_CONFIG_FILENAME),
3442
+ secretEnv: defaultOpenclawModelEnvFile(ctx.instanceId),
3443
+ };
3444
+ }
3445
+ async buildRuntime(instanceId) {
3446
+ // OpenClaw persists its runtime in legacy snake_case shape
3447
+ // ({env_files, resources, ...}). Translate at read time into the
3448
+ // engine-neutral RuntimeSpec contract.
3449
+ const im = await lazyIm();
3450
+ const raw = im.getInstanceRuntime(instanceId);
3451
+ const home = openclawHomeFromMetadata(getInstance(instanceId), instanceId);
3452
+ const env = { ...DEFAULT_ENV, ...(raw?.env || {}) };
3453
+ if (home && !env.MCPORTER_CONFIG) {
3454
+ env.MCPORTER_CONFIG = `${home}/.openclaw/workspace/config/mcporter.json`;
3455
+ }
3456
+ return {
3457
+ image: raw?.image ?? getOpenclawDockerImage(),
3458
+ command: String(raw?.command || DEFAULT_COMMAND),
3459
+ args: Array.isArray(raw?.args) ? raw.args.map(String) : [...DEFAULT_ARGS],
3460
+ cwd: String(raw?.cwd || home || DEFAULT_CWD),
3461
+ user: String(raw?.user || DEFAULT_USER),
3462
+ env,
3463
+ envFiles: Array.isArray(raw?.env_files)
3464
+ ? raw.env_files
3465
+ : Array.isArray(raw?.envFiles)
3466
+ ? raw.envFiles
3467
+ : [],
3468
+ resources: {
3469
+ CPU: Number(raw?.resources?.CPU ?? DEFAULT_RESOURCES.CPU),
3470
+ MemoryMB: Number(raw?.resources?.MemoryMB ?? DEFAULT_RESOURCES.MemoryMB),
3471
+ MemoryMaxMB: raw?.resources?.MemoryMaxMB != null ? Number(raw.resources.MemoryMaxMB) : undefined,
3472
+ },
3473
+ ports: [
3474
+ {
3475
+ name: "gateway",
3476
+ containerPort: resolveOpenclawContainerPort(raw),
3477
+ hostPort: im.getPrimaryHostPort(instanceId),
3478
+ visibility: "external",
3479
+ },
3480
+ ],
3481
+ volumes: [{ hostPath: home, containerPath: home, mode: "rw" }],
3482
+ health: null,
3483
+ };
3484
+ }
3485
+ async getPersistedRuntimeSpec(instanceId) {
3486
+ const im = await lazyIm();
3487
+ const rawRuntime = im.getInstanceRuntime(instanceId);
3488
+ const openclawHome = openclawHomeFromMetadata(getInstance(instanceId), instanceId);
3489
+ const runtime = await this.buildRuntime(instanceId);
3490
+ const env = { ...(runtime.env ?? {}) };
3491
+ injectProviderHostEnv(env, instanceId);
3492
+ delete env.JSPROXY_API_KEY;
3493
+ return {
3494
+ ...runtime,
3495
+ // WorkloadCompiler contributes the compatibility entrypoint, so keep the
3496
+ // persisted command empty here to avoid emitting both `command` and
3497
+ // `entrypoint` in the docker config.
3498
+ command: "",
3499
+ user: resolveUidGid(String(rawRuntime.user || DEFAULT_USER)),
3500
+ env,
3501
+ volumes: buildVolumes(openclawHome, rawRuntime).map((entry) => {
3502
+ const [hostPath, containerPath, mode = "rw"] = entry.split(":");
3503
+ return {
3504
+ hostPath,
3505
+ containerPath,
3506
+ mode: mode === "ro" ? "ro" : "rw",
3507
+ };
3508
+ }),
3509
+ };
3510
+ }
3511
+ async buildRuntimeContribution(instanceId) {
3512
+ const im = await lazyIm();
3513
+ const openclawHome = openclawHomeFromMetadata(getInstance(instanceId), instanceId);
3514
+ const safeJobId = resolveNomadJobId(instanceId, this.nomadJobPrefix);
3515
+ assertSafeTemplateId(safeJobId);
3516
+ // Opt-in privilege relaxation (per-instance runtime.privileged). Default
3517
+ // keeps the hardened container (read-only rootfs + the base cap_drop=ALL /
3518
+ // no-new-privileges applied by the workload compiler). When enabled, the
3519
+ // driverConfig deep-merges over that base to relax it to native-install-
3520
+ // like permissions — writable rootfs, docker default caps (cap_drop=[]),
3521
+ // no-new-privileges off — and passes through host peripheral devices +
3522
+ // group_add of their owning gids. Toggle via `jishushell job privileged`.
3523
+ const rawRuntime = im.getInstanceRuntime(instanceId);
3524
+ const privileged = rawRuntime.privileged === true;
3525
+ const peripherals = privileged
3526
+ ? collectPrivilegedDevices(Array.isArray(rawRuntime.devices) ? rawRuntime.devices.map(String) : [])
3527
+ : { devices: [], groupAdd: [] };
3528
+ if (privileged) {
3529
+ console.warn(`[openclaw] instance ${instanceId} running with privileged=true — hardening relaxed (writable rootfs, default caps, no-new-privileges off); ${peripherals.devices.length} host device(s) passed through, group_add=[${peripherals.groupAdd.join(",")}]`);
3530
+ }
3531
+ const driverConfig = {
3532
+ entrypoint: ["/bin/sh", "-c", CONTAINER_PATCH_ENTRYPOINT_COMMAND, "--"],
3533
+ readonly_rootfs: !privileged,
3534
+ mounts: [
3535
+ { type: "tmpfs", target: "/tmp", tmpfs_options: { size: 536870912 } },
3536
+ { type: "tmpfs", target: "/var/tmp", tmpfs_options: { size: 67108864 } },
3537
+ { type: "tmpfs", target: "/run", tmpfs_options: { size: 52428800 } },
3538
+ ],
3539
+ ...(privileged
3540
+ ? {
3541
+ cap_drop: [],
3542
+ security_opt: [],
3543
+ ...(peripherals.devices.length > 0 ? { devices: peripherals.devices } : {}),
3544
+ ...(peripherals.groupAdd.length > 0 ? { group_add: peripherals.groupAdd } : {}),
3545
+ }
3546
+ : {}),
3547
+ };
3548
+ return {
3549
+ tasks: {
3550
+ gateway: {
3551
+ env: {
3552
+ HOME: openclawHome,
3553
+ OPENCLAW_HOME: openclawHome,
3554
+ OPENCLAW_INSTANCE_ID: instanceId,
3555
+ OPENCLAW_STATE_DIR: `${openclawHome}/.openclaw`,
3556
+ OPENCLAW_SYSTEMD_UNIT: `nomad-${safeJobId}.service`,
3557
+ npm_config_prefix: `${openclawHome}/.npm-global`,
3558
+ PIP_USER: "1",
3559
+ PYTHONUSERBASE: `${openclawHome}/.local`,
3560
+ NODE_ENV: "production",
3561
+ NODE_PATH: [
3562
+ `${openclawHome}/.npm-global/lib/node_modules`,
3563
+ "/app/node_modules",
3564
+ ].join(":"),
3565
+ PATH: [
3566
+ `${openclawHome}/.npm-global/bin`,
3567
+ `${openclawHome}/.local/bin`,
3568
+ `${openclawHome}/go/bin`,
3569
+ `${openclawHome}/.cargo/bin`,
3570
+ "/usr/local/sbin",
3571
+ "/usr/local/bin",
3572
+ "/usr/sbin",
3573
+ "/usr/bin",
3574
+ "/sbin",
3575
+ "/bin",
3576
+ ].join(":"),
3577
+ },
3578
+ driverConfig,
3579
+ templates: [
3580
+ {
3581
+ DestPath: "secrets/instance.env",
3582
+ Envvars: true,
3583
+ EmbeddedTmpl: [
3584
+ `{{ if nomadVarExists "nomad/jobs/${safeJobId}/openclaw/gateway" }}`,
3585
+ `JSPROXY_API_KEY={{ with nomadVar "nomad/jobs/${safeJobId}/openclaw/gateway" }}{{ .JSPROXY_API_KEY }}{{ end }}`,
3586
+ `{{ end }}`,
3587
+ ].join("\n"),
3588
+ ChangeMode: "restart",
3589
+ },
3590
+ ],
3591
+ },
3592
+ },
3593
+ };
3594
+ }
3595
+ async getRuntimeVersion(_instanceId) {
3596
+ // Parse the image reference (digest > tag) for the baseline image.
3597
+ const image = getOpenclawDockerImage() || "";
3598
+ let ref;
3599
+ let digest;
3600
+ if (image) {
3601
+ if (image.includes("@")) {
3602
+ digest = image.split("@", 2)[1];
3603
+ }
3604
+ else {
3605
+ const lastColon = image.lastIndexOf(":");
3606
+ const lastSlash = image.lastIndexOf("/");
3607
+ if (lastColon > lastSlash)
3608
+ ref = image.slice(lastColon + 1);
3609
+ }
3610
+ }
3611
+ return { integrationKind: "openclaw", ref, digest, mode: "baseline" };
3612
+ }
3613
+ async getConfigMeta(instanceId) {
3614
+ return {
3615
+ integrationKind: "openclaw",
3616
+ format: "json",
3617
+ schemaId: "openclaw/v1",
3618
+ capabilities: DEFAULT_CAPABILITIES,
3619
+ secretFields: ["content.x-jishushell.proxy.upstream.apiKey"],
3620
+ runtimeVersion: await this.getRuntimeVersion(instanceId),
3621
+ };
3622
+ }
3623
+ async readConfig(instanceId) {
3624
+ const im = await lazyIm();
3625
+ const content = im.getStoredConfig
3626
+ ? im.getStoredConfig(instanceId)
3627
+ : null;
3628
+ return {
3629
+ format: "json",
3630
+ content: (content && typeof content === "object") ? content : {},
3631
+ };
3632
+ }
3633
+ async writeConfig(instanceId, doc) {
3634
+ if (doc.format !== "json") {
3635
+ throw new Error(`OpenClaw config requires format="json", got "${doc.format}"`);
3636
+ }
3637
+ // Route through llmProxy.saveInstanceConfig so x-jishushell.proxy
3638
+ // metadata is stripped, the upstream apiKey is AES-encrypted to
3639
+ // provider.env, and models.providers is rewritten to the local
3640
+ // proxy — same contract HermesIntegration.writeConfig uses. That
3641
+ // function internally calls instanceManager.saveConfig, which
3642
+ // dispatches back to this integration's saveNativeConfig() for the
3643
+ // raw disk write (distinct method, no recursion).
3644
+ const { saveInstanceConfig } = await import("../../llm-proxy/instance-proxy.js");
3645
+ await saveInstanceConfig(instanceId, doc.content);
3646
+ return this.readConfig(instanceId);
3647
+ }
3648
+ async buildPairingListCommand(_instanceId) {
3649
+ return ["openclaw", "pairing", "list"];
3650
+ }
3651
+ async buildPairingApproveCommand(_instanceId, input) {
3652
+ return ["openclaw", "pairing", "approve", input.channel, input.code];
3653
+ }
3654
+ // ── Native config I/O (physically migrated from instance-manager) ───
3655
+ channelPluginMap = CHANNEL_PLUGIN_MAP;
3656
+ /**
3657
+ * Get the stored raw OpenClaw config (from `.openclaw/openclaw.json`
3658
+ * or the legacy `openclaw.json`), merged with the x-jishushell
3659
+ * metadata pulled from `instance.json`. Returns null when the instance
3660
+ * has no persisted config yet.
3661
+ */
3662
+ getNativeConfig(instanceId) {
3663
+ const config = loadEffectiveConfig(instanceId);
3664
+ if (!config)
3665
+ return null;
3666
+ const tempHosts = readTemporaryBrowserAllowedHostnames(instanceId);
3667
+ const stripped = stripTemporaryBrowserAllowlistFromConfigObject(config, tempHosts);
3668
+ // Always merge the latest upstream proxy config from instance.json
3669
+ const meta = getInstance(instanceId);
3670
+ if (meta?.["x-jishushell"]) {
3671
+ stripped["x-jishushell"] = meta["x-jishushell"];
3672
+ }
3673
+ return stripped;
3674
+ }
3675
+ /**
3676
+ * Get the stored raw config WITHOUT provider key injection. Used by
3677
+ * callers that round-trip the config back to disk (e.g. credential
3678
+ * writers) — injecting the provider key would re-persist it to the
3679
+ * config file, which is exactly what `saveConfig` takes pains to avoid.
3680
+ */
3681
+ getStoredNativeConfig(instanceId) {
3682
+ const config = loadEffectiveConfig(instanceId);
3683
+ if (!config)
3684
+ return null;
3685
+ const tempHosts = readTemporaryBrowserAllowedHostnames(instanceId);
3686
+ const stripped = stripTemporaryBrowserAllowlistFromConfigObject(config, tempHosts);
3687
+ const meta = getInstance(instanceId);
3688
+ if (meta?.["x-jishushell"]) {
3689
+ stripped["x-jishushell"] = meta["x-jishushell"];
3690
+ }
3691
+ return stripped;
3692
+ }
3693
+ isChannelPluginInstalled(instanceId, channelId) {
3694
+ return isChannelPluginInstalled(instanceId, channelId);
3695
+ }
3696
+ async installChannelPlugin(instanceId, channelId) {
3697
+ return installChannelPlugin(instanceId, channelId);
3698
+ }
3699
+ saveNativeConfig(instanceId, config) {
3700
+ return saveNativeConfigImpl(instanceId, config);
3701
+ }
3702
+ /**
3703
+ * Connection-apply hook: translate resolved `inject_as` env vars into
3704
+ * OpenClaw-native plugin config and
3705
+ * persist them into `openclaw.json`. Without this, the runtime env
3706
+ * injected by the Nomad driver's connection env phase sits
3707
+ * in the container unused — the OpenClaw agent reads tool config from
3708
+ * `openclaw.json`, not from environment variables.
3709
+ *
3710
+ * Currently wired:
3711
+ * SEARCH_API_BASE_URL → plugins.entries.searxng.config.webSearch.baseUrl
3712
+ * SEARCH_API_BASE_URL → tools.web.search.provider = "searxng"
3713
+ *
3714
+ * The provider selector at `tools.web.search.provider` is required: without
3715
+ * it the `web_search` tool defaults to Brave and fails with
3716
+ * `missing_brave_api_key` even when the searxng plugin is fully configured.
3717
+ *
3718
+ * Browser / LLM wiring needs its own config-shape mapping
3719
+ * (browser → tools.browser, llm → models.providers).
3720
+ *
3721
+ * The write goes through `saveNativeConfig` which preserves relevant fields
3722
+ * from the existing canonical on-disk config, so user-managed plugin entries (e.g.
3723
+ * openclaw-lark) are preserved. Plugin auto-enable then promotes the
3724
+ * searxng entry into `plugins.allow` automatically on next start
3725
+ * because we set `enabled:true` and provide config (the openclaw
3726
+ * runtime treats the presence of `config.webSearch.baseUrl` as a
3727
+ * "configured" signal — see `plugin-auto-enable` in the openclaw
3728
+ * dist bundle).
3729
+ */
3730
+ async applyConnectionEnv(instanceId, env) {
3731
+ const configPath = openclawConfigPath(instanceId);
3732
+ const searchUrl = env.SEARCH_API_BASE_URL;
3733
+ if (typeof searchUrl === "string") {
3734
+ if (searchUrl === "") {
3735
+ // Empty value — connection-transactor's UNPERSIST_HOOKS uses this as
3736
+ // the "unbind" signal. Clear the searxng plugin config so the next
3737
+ // start doesn't keep routing web_search through a now-disconnected
3738
+ // provider.
3739
+ try {
3740
+ clearSearxngConnectionFromConfig(configPath);
3741
+ }
3742
+ catch (e) {
3743
+ console.warn(`[openclaw] applyConnectionEnv search unbind failed for ${instanceId}: ${e.message}`);
3744
+ }
3745
+ }
3746
+ else {
3747
+ // SEARCH_API_BASE_URL points at "<base>/search" (the SearXNG search
3748
+ // endpoint). The plugin's webSearch.baseUrl wants the bare origin —
3749
+ // strip the trailing "/search" path segment if present.
3750
+ // baseUrl stays at the registry-resolved host:port snapshot from
3751
+ // when the user PUT /connections; the framework re-runs this hook
3752
+ // on every instance start (lifecycle connection refresh), so host
3753
+ // IP changes propagate automatically on next agent restart.
3754
+ let baseUrl = searchUrl;
3755
+ try {
3756
+ const u = new URL(searchUrl);
3757
+ if (u.pathname === "/search" || u.pathname === "/search/") {
3758
+ u.pathname = "";
3759
+ baseUrl = u.toString().replace(/\/$/, "");
3760
+ }
3761
+ try {
3762
+ applySearxngConnectionToConfig(configPath, baseUrl);
3763
+ }
3764
+ catch (e) {
3765
+ console.warn(`[openclaw] applyConnectionEnv search merge failed for ${instanceId}: ${e.message}`);
3766
+ }
3767
+ }
3768
+ catch {
3769
+ // not a URL — skip silently; the openclaw plugin would break
3770
+ // with a non-URL baseUrl, and start should still proceed.
3771
+ }
3772
+ }
3773
+ }
3774
+ const cdpUrl = env.BROWSER_CDP_URL;
3775
+ if (typeof cdpUrl === "string") {
3776
+ if (cdpUrl === "") {
3777
+ try {
3778
+ clearBrowserlessConnectionFromConfig(configPath);
3779
+ }
3780
+ catch (e) {
3781
+ console.warn(`[openclaw] applyConnectionEnv browser unbind failed for ${instanceId}: ${e.message}`);
3782
+ }
3783
+ }
3784
+ else if (/^wss?:\/\//.test(cdpUrl)) {
3785
+ try {
3786
+ applyBrowserlessConnectionToConfig(configPath, cdpUrl);
3787
+ }
3788
+ catch (e) {
3789
+ console.warn(`[openclaw] applyConnectionEnv browser merge failed for ${instanceId}: ${e.message}`);
3790
+ }
3791
+ }
3792
+ // Non-ws scheme: skip silently. The connection-apply browser hook
3793
+ // already builds ws:// from the capability protocol; an http:// here
3794
+ // would mean a misconfigured provider — better to no-op than to
3795
+ // write a URL OpenClaw can't dial.
3796
+ }
3797
+ }
3798
+ listConnectionSideEffectFiles(args) {
3799
+ const home = openclawHomeFromMetadata(getInstance(args.instanceId), args.instanceId);
3800
+ const envFile = getRuntimeEnvFiles(args.instanceId)[0] ?? defaultOpenclawModelEnvFile(args.instanceId);
3801
+ return [
3802
+ join(dirname(envFile), "provider.env"),
3803
+ openclawConfigPath(args.instanceId, home),
3804
+ mcporterPath(args.instanceId),
3805
+ ];
3806
+ }
3807
+ // ── Path resolvers (physically migrated) ───────────────────────────
3808
+ resolveBin() {
3809
+ return resolveOpenclawBin();
3810
+ }
3811
+ getSystemVersion() {
3812
+ try {
3813
+ return execFileSync(resolveOpenclawBin(), ["--version"], { encoding: "utf-8", timeout: 5_000 }).trim() || "unknown";
3814
+ }
3815
+ catch {
3816
+ return "unknown";
3817
+ }
3818
+ }
3819
+ resolveAgentHome(instanceId) {
3820
+ const meta = getInstance(instanceId);
3821
+ return openclawHomeFromMetadata(meta, instanceId);
3822
+ }
3823
+ summarizeRecentBrowserSession(instanceId) {
3824
+ return summarizeRecentOpenclawBrowserSession(instanceId);
3825
+ }
3826
+ async syncImmichMcpForAllInstances() {
3827
+ const updated = [];
3828
+ const skipped = [];
3829
+ for (const instance of listInstances()) {
3830
+ const instanceId = typeof instance.id === "string" ? instance.id : "";
3831
+ if (!instanceId)
3832
+ continue;
3833
+ try {
3834
+ if (!isOpenclawInstanceMetadata(instance))
3835
+ continue;
3836
+ await syncImmichMcpForOpenclawInstance(instanceId);
3837
+ updated.push(instanceId);
3838
+ }
3839
+ catch (error) {
3840
+ skipped.push({ instanceId, error: error?.message ?? String(error) });
3841
+ }
3842
+ }
3843
+ return { updated, skipped };
3844
+ }
3845
+ /** Env vars OpenClaw's CLI needs when backup-manager runs it as a subprocess. */
3846
+ buildCliEnv(instanceId) {
3847
+ return { OPENCLAW_HOME: this.resolveAgentHome(instanceId) };
3848
+ }
3849
+ /**
3850
+ * Rewrite only the host-side published gateway port (canonical Step 2
3851
+ * integration contract).
3852
+ *
3853
+ * Domain semantics:
3854
+ * - `hostPort` is Core-allocated and may be rewritten freely.
3855
+ * - `containerPort` is the in-container OpenClaw listener and MUST stay
3856
+ * stable across host-port reallocations.
3857
+ *
3858
+ * Missing canonical `runtime.ports[]` is a migration error for ordinary
3859
+ * lifecycle paths; this method must not synthesize runtime facts.
3860
+ */
3861
+ reallocateRuntimePort(runtime, newPort) {
3862
+ if (Array.isArray(runtime.ports) && runtime.ports.length > 0) {
3863
+ runtime.ports = runtime.ports.map((port, index) => {
3864
+ const isGateway = port?.name === "gateway" || index === 0;
3865
+ return isGateway
3866
+ ? { ...port, hostPort: newPort }
3867
+ : port;
3868
+ });
3869
+ return;
3870
+ }
3871
+ throw new Error("[openclaw-integration] reallocateRuntimePort: instance is missing canonical "
3872
+ + "runtime.ports[]; run migration or repair before reallocating.");
3873
+ }
3874
+ nomadJobPrefix = "openclaw-";
3875
+ // Must match the path referenced by this integration's buildNomadTask Templates
3876
+ // (see `nomadVar "nomad/jobs/<jid>/openclaw/gateway"` in the template body).
3877
+ nomadVariablePath = "openclaw/gateway";
3878
+ resolveConfigPath(instanceId) {
3879
+ return openclawConfigPath(instanceId, this.resolveAgentHome(instanceId));
3880
+ }
3881
+ resolveLegacyConfigPath(instanceId) {
3882
+ return legacyOpenclawConfigPath(instanceId, this.resolveAgentHome(instanceId));
3883
+ }
3884
+ /**
3885
+ * Return other OpenClaw instance IDs that share this one's
3886
+ * canonical integration-home path. Used by the start-time conflict check.
3887
+ */
3888
+ findInstancesSharingHome(instanceId) {
3889
+ const target = normalizePath(this.resolveAgentHome(instanceId));
3890
+ return listInstances()
3891
+ .filter((inst) => inst.id !== instanceId)
3892
+ .filter((inst) => {
3893
+ const meta = inst;
3894
+ const otherHome = openclawHomeFromMetadata(meta, inst.id);
3895
+ return normalizePath(otherHome) === target;
3896
+ })
3897
+ .map((inst) => inst.id);
3898
+ }
3899
+ // ── Feishu / WeChat credential writers (physically migrated) ───────
3900
+ saveFeishuCredentials(instanceId, creds) {
3901
+ if (!FEISHU_APP_ID_RE.test(creds.appId)) {
3902
+ throw new Error(`Invalid Feishu appId format: expected cli_<alnum> (got "${creds.appId}")`);
3903
+ }
3904
+ if (!creds.appSecret || typeof creds.appSecret !== "string" || creds.appSecret.length < 4) {
3905
+ throw new Error("Invalid Feishu appSecret: must be a non-empty string");
3906
+ }
3907
+ const configPath = this.resolveConfigPath(instanceId);
3908
+ let config = {};
3909
+ try {
3910
+ if (existsSync(configPath)) {
3911
+ config = JSON.parse(readFileSync(configPath, "utf-8"));
3912
+ }
3913
+ }
3914
+ catch {
3915
+ /* best effort */
3916
+ }
3917
+ config.plugins ??= {};
3918
+ config.plugins.entries ??= {};
3919
+ config.plugins.entries.feishu = { enabled: false };
3920
+ config.plugins.entries["openclaw-lark"] = { enabled: true };
3921
+ config.channels ??= {};
3922
+ config.channels.feishu = {
3923
+ ...config.channels.feishu,
3924
+ enabled: true,
3925
+ appId: creds.appId,
3926
+ appSecret: creds.appSecret,
3927
+ domain: creds.domain,
3928
+ dmPolicy: "open",
3929
+ allowFrom: ["*"],
3930
+ };
3931
+ safeWriteJson(configPath, config);
3932
+ chownToServiceUser(configPath);
3933
+ console.log(`[openclaw] Feishu credentials saved for ${instanceId}, domain=${creds.domain}`);
3934
+ }
3935
+ saveWeixinCredentials(instanceId, creds) {
3936
+ if (!creds.accountId || !SAFE_ACCOUNT_ID_RE.test(creds.accountId) || creds.accountId.includes("..")) {
3937
+ throw new Error(`Invalid accountId: must be 1-128 chars of [a-zA-Z0-9@._-] without '..'`);
3938
+ }
3939
+ const home = this.resolveAgentHome(instanceId);
3940
+ const stateDir = join(home, OPENCLAW_STATE_DIRNAME, "openclaw-weixin");
3941
+ const accountsDir = join(stateDir, "accounts");
3942
+ ensureDirContainer(accountsDir);
3943
+ const credObj = {
3944
+ token: creds.token,
3945
+ baseUrl: creds.baseUrl,
3946
+ userId: creds.userId,
3947
+ savedAt: new Date().toISOString(),
3948
+ };
3949
+ safeWriteJson(join(accountsDir, `${creds.accountId}.json`), credObj);
3950
+ safeWriteJson(join(accountsDir, "default.json"), credObj);
3951
+ chownToServiceUser(join(accountsDir, `${creds.accountId}.json`), join(accountsDir, "default.json"));
3952
+ // Update accounts.json index
3953
+ const indexPath = join(stateDir, "accounts.json");
3954
+ let index = [];
3955
+ try {
3956
+ const raw = readFileSync(indexPath, "utf-8");
3957
+ index = JSON.parse(raw);
3958
+ }
3959
+ catch {
3960
+ /* start fresh */
3961
+ }
3962
+ if (!Array.isArray(index))
3963
+ index = [];
3964
+ if (!index.includes(creds.accountId))
3965
+ index.push(creds.accountId);
3966
+ safeWriteJson(indexPath, index);
3967
+ const configPath = this.resolveConfigPath(instanceId);
3968
+ let config = {};
3969
+ try {
3970
+ if (existsSync(configPath))
3971
+ config = JSON.parse(readFileSync(configPath, "utf-8"));
3972
+ }
3973
+ catch {
3974
+ /* best effort */
3975
+ }
3976
+ config.plugins ??= {};
3977
+ config.plugins.entries ??= {};
3978
+ config.plugins.entries["openclaw-weixin"] ??= {};
3979
+ config.plugins.entries["openclaw-weixin"].enabled = true;
3980
+ config.channels ??= {};
3981
+ config.channels["openclaw-weixin"] ??= {};
3982
+ config.channels["openclaw-weixin"].enabled = true;
3983
+ const normalizedId = creds.accountId.replace(/[@.]/g, "-");
3984
+ const accounts = config.channels["openclaw-weixin"].accounts ??= {};
3985
+ accounts[creds.accountId] = { enabled: true };
3986
+ if (normalizedId !== creds.accountId)
3987
+ accounts[normalizedId] = { enabled: true };
3988
+ accounts["default"] = { enabled: true };
3989
+ if (!config.channels["openclaw-weixin"].defaultAccount) {
3990
+ config.channels["openclaw-weixin"].defaultAccount = "default";
3991
+ }
3992
+ safeWriteJson(configPath, config);
3993
+ chownToServiceUser(configPath);
3994
+ console.log(`[openclaw] WeChat credentials saved for ${instanceId}, account=${creds.accountId}`);
3995
+ }
3996
+ getWeixinAccounts(instanceId) {
3997
+ const home = this.resolveAgentHome(instanceId);
3998
+ const stateDir = join(home, OPENCLAW_STATE_DIRNAME, "openclaw-weixin");
3999
+ const accountsDir = join(stateDir, "accounts");
4000
+ if (!existsSync(accountsDir))
4001
+ return [];
4002
+ let indexedIds = [];
4003
+ try {
4004
+ indexedIds = JSON.parse(readFileSync(join(stateDir, "accounts.json"), "utf-8"));
4005
+ }
4006
+ catch {
4007
+ /* fallback to scanning */
4008
+ }
4009
+ const results = [];
4010
+ for (const f of readdirSync(accountsDir)) {
4011
+ if (!f.endsWith(".json"))
4012
+ continue;
4013
+ const id = f.replace(/\.json$/, "");
4014
+ if (indexedIds.length > 0 && !indexedIds.includes(id))
4015
+ continue;
4016
+ if (id === "default")
4017
+ continue;
4018
+ try {
4019
+ const data = JSON.parse(readFileSync(join(accountsDir, f), "utf-8"));
4020
+ results.push({
4021
+ accountId: id,
4022
+ userId: data.userId,
4023
+ savedAt: data.savedAt,
4024
+ });
4025
+ }
4026
+ catch {
4027
+ /* skip */
4028
+ }
4029
+ }
4030
+ return results;
4031
+ }
4032
+ // ── Legacy runtime install ────────────────────────────────────────────
4033
+ //
4034
+ // Installs the OpenClaw npm package via `npm install -g --prefix` so that
4035
+ // postinstall scripts run naturally. Emits SSE progress through the task
4036
+ // machinery exported by setup-manager.
4037
+ async installRuntime(opts) {
4038
+ const version = opts?.version ?? "latest";
4039
+ try {
4040
+ const openclawPkgDir = join(OPENCLAW_MODULES, "openclaw");
4041
+ if (existsSync(openclawPkgDir)) {
4042
+ const ver = readInstalledOpenclawVersion() || "unknown";
4043
+ return { ok: true, message: `OpenClaw already installed: ${ver}` };
4044
+ }
4045
+ const task = createTask("openclaw");
4046
+ ensureDirHost(OPENCLAW_PKG_DIR);
4047
+ emitTask(task, { type: "progress", message: "开始安装 OpenClaw...", progress: 0 });
4048
+ const sizeTracker = setInterval(() => {
4049
+ const sizeMB = getDirSizeMB(OPENCLAW_PKG_DIR);
4050
+ const pct = Math.min(95, Math.round((sizeMB / OPENCLAW_EXPECTED_SIZE_MB) * 95));
4051
+ if (pct > 0) {
4052
+ emitTask(task, {
4053
+ type: "progress",
4054
+ message: `下载安装中... ${sizeMB}MB / ~${OPENCLAW_EXPECTED_SIZE_MB}MB`,
4055
+ progress: pct,
4056
+ });
4057
+ }
4058
+ }, 3000);
4059
+ const result = await spawnWithTask(task, "npm", ["install", "-g", "--prefix", OPENCLAW_PKG_DIR, `openclaw@${version}`], { timeout: 600000, progressParser: npmProgressParser });
4060
+ clearInterval(sizeTracker);
4061
+ if (!result.ok) {
4062
+ emitTask(task, { type: "error", message: "OpenClaw 安装失败" });
4063
+ task.status = "error";
4064
+ return {
4065
+ ok: false,
4066
+ message: "OpenClaw installation failed",
4067
+ error: result.output,
4068
+ taskId: task.id,
4069
+ };
4070
+ }
4071
+ const ver = readInstalledOpenclawVersion() || "installed";
4072
+ emitTask(task, { type: "done", message: `OpenClaw 安装完成: ${ver}`, progress: 100 });
4073
+ task.status = "done";
4074
+ return { ok: true, message: `OpenClaw installed: ${ver}`, taskId: task.id };
4075
+ }
4076
+ catch (e) {
4077
+ return { ok: false, message: "OpenClaw installation failed", error: e.message };
4078
+ }
4079
+ }
4080
+ /**
4081
+ * Build / pull the OpenClaw Docker image. Blocking — useful for CLI
4082
+ * installer and `runFullSetup()`. Non-blocking variant below is used by
4083
+ * the REST API and the integration's own `onBeforeStart` self-heal path.
4084
+ */
4085
+ async buildRuntimeImage(opts) {
4086
+ const task = createTask("openclaw-docker-pull");
4087
+ return pullOrBuildOpenclawImageWithTask(task, opts?.tag);
4088
+ }
4089
+ /**
4090
+ * Non-blocking variant of `buildRuntimeImage` — returns a task id
4091
+ * immediately so the caller can poll SSE progress.
4092
+ */
4093
+ startBuildRuntimeImage(opts) {
4094
+ const task = createTask("openclaw-docker-pull");
4095
+ void pullOrBuildOpenclawImageWithTask(task, opts?.tag).catch((err) => {
4096
+ emitTask(task, {
4097
+ type: "error",
4098
+ message: `镜像获取失败: ${err?.message || err}`,
4099
+ });
4100
+ task.status = "error";
4101
+ });
4102
+ return { ok: true, message: "Docker image pull started", taskId: task.id };
4103
+ }
4104
+ /**
4105
+ * Return OpenClaw's readiness for spawning instances. Docker image
4106
+ * presence is the gating factor in the default docker-mode deployment;
4107
+ * the legacy `npm install` path is still reported as `installed` but is
4108
+ * not required for the docker-driver stack.
4109
+ */
4110
+ getInstallStatus() {
4111
+ // OPENCLAW_MODULES may be undefined when config is partially mocked in tests.
4112
+ const pkgInstalled = OPENCLAW_MODULES ? existsSync(join(OPENCLAW_MODULES, "openclaw")) : false;
4113
+ const imageTag = getOpenclawDockerImage?.() ?? "";
4114
+ let imageReady = false;
4115
+ try {
4116
+ const invocation = resolveDockerInvocation();
4117
+ if (invocation?.cmd) {
4118
+ execFileSync(invocation.cmd, [...invocation.argsPrefix, "image", "inspect", imageTag], {
4119
+ timeout: 5000,
4120
+ stdio: "ignore",
4121
+ });
4122
+ imageReady = true;
4123
+ }
4124
+ }
4125
+ catch { /* image absent */ }
4126
+ // Prefer the version pinned into the docker image tag — that is what
4127
+ // instances actually run in the default docker deployment. The host-npm
4128
+ // package.json (readInstalledOpenclawVersion) is unrelated to the running
4129
+ // container, so reporting it made the UI show "latest" while the container
4130
+ // still ran the old build after an update. Fall back to host-npm only when
4131
+ // no image is ready (legacy npm path).
4132
+ const imageVersion = imageReady ? versionFromImageTag(imageTag) : "";
4133
+ const version = imageVersion || (pkgInstalled ? readInstalledOpenclawVersion() : "");
4134
+ return {
4135
+ installed: imageReady || pkgInstalled,
4136
+ imageReady,
4137
+ version: version || undefined,
4138
+ };
4139
+ }
4140
+ }
4141
+ // ── Install-time helpers (used by installRuntime) ─────────────────────
4142
+ const OPENCLAW_EXPECTED_SIZE_MB = 700;
4143
+ function readInstalledOpenclawVersion() {
4144
+ try {
4145
+ const pkg = join(OPENCLAW_MODULES, "openclaw", "package.json");
4146
+ if (existsSync(pkg))
4147
+ return JSON.parse(readFileSync(pkg, "utf-8")).version || "";
4148
+ }
4149
+ catch {
4150
+ /* best effort */
4151
+ }
4152
+ return "";
4153
+ }
4154
+ /**
4155
+ * Extract a semver-ish version from a pinned image tag, e.g.
4156
+ * `ghcr.io/x-aijishu/openclaw-runtime:2026.6.10` -> `2026.6.10`. Returns "" when
4157
+ * the tag carries no version (mutable `:latest`/`:slim`, or the only colon is a
4158
+ * registry port).
4159
+ */
4160
+ function versionFromImageTag(imageTag) {
4161
+ if (!imageTag)
4162
+ return "";
4163
+ const colonIdx = imageTag.lastIndexOf(":");
4164
+ const slashIdx = imageTag.lastIndexOf("/");
4165
+ if (colonIdx <= slashIdx)
4166
+ return "";
4167
+ const tag = imageTag.slice(colonIdx + 1);
4168
+ return /^\d+\.\d+\.\d+/.test(tag) ? tag : "";
4169
+ }
4170
+ // Feishu app IDs issued by the open platform follow `cli_<hex/alnum>`.
4171
+ const FEISHU_APP_ID_RE = /^cli_[a-zA-Z0-9]{8,64}$/;
4172
+ const SAFE_ACCOUNT_ID_RE = /^[a-zA-Z0-9@._-]{1,128}$/;
4173
+ // ── Channel plugin constants (physically migrated) ───────────────────
4174
+ const CHANNEL_EXT_DIR_ALIAS = {
4175
+ feishu: "openclaw-lark",
4176
+ lark: "openclaw-lark",
4177
+ };
4178
+ const CHANNEL_PLUGIN_MAP = {
4179
+ feishu: "@larksuite/openclaw-lark",
4180
+ lark: "@larksuite/openclaw-lark",
4181
+ telegram: "@openclaw/telegram",
4182
+ discord: "@openclaw/discord",
4183
+ slack: "@openclaw/slack",
4184
+ whatsapp: "@openclaw/whatsapp",
4185
+ signal: "@openclaw/signal",
4186
+ line: "@openclaw/line",
4187
+ msteams: "@openclaw/msteams",
4188
+ "openclaw-weixin": "@tencent-weixin/openclaw-weixin",
4189
+ };
4190
+ const IM_PLUGIN_ENTRY_IDS = new Set([
4191
+ ...Object.keys(CHANNEL_PLUGIN_MAP),
4192
+ ...Object.values(CHANNEL_EXT_DIR_ALIAS),
4193
+ ]);
4194
+ // ── Config I/O helpers (physically migrated) ─────────────────────────
4195
+ function hasConfiguredValue(value) {
4196
+ if (typeof value !== "string")
4197
+ return !!value;
4198
+ return value.trim().length > 0;
4199
+ }
4200
+ function loadJsonSafe(path) {
4201
+ try {
4202
+ return JSON.parse(readFileSync(path, "utf-8"));
4203
+ }
4204
+ catch (e) {
4205
+ console.warn(`[openclaw] Failed to parse ${path}: ${e.message}`);
4206
+ return null;
4207
+ }
4208
+ }
4209
+ function loadEffectiveConfig(instanceId) {
4210
+ migrateLegacyOuterConfigOnce(instanceId);
4211
+ const runtimePath = openclawConfigPath(instanceId);
4212
+ if (existsSync(runtimePath))
4213
+ return loadJsonSafe(runtimePath);
4214
+ return null;
4215
+ }
4216
+ function applyFeishuDebugAccessDefaults(channel) {
4217
+ if (channel.enabled === false)
4218
+ return;
4219
+ if (!hasConfiguredValue(channel.appId))
4220
+ return;
4221
+ if (!hasConfiguredValue(channel.appSecret))
4222
+ return;
4223
+ let dmPolicy = channel.dmPolicy;
4224
+ if (typeof dmPolicy !== "string" || !dmPolicy.trim()) {
4225
+ channel.dmPolicy = "open";
4226
+ dmPolicy = "open";
4227
+ }
4228
+ if (dmPolicy !== "open")
4229
+ return;
4230
+ if (!("resolveSenderNames" in channel))
4231
+ channel.resolveSenderNames = false;
4232
+ let accounts = channel.accounts;
4233
+ if (typeof accounts !== "object" || accounts === null) {
4234
+ accounts = {};
4235
+ channel.accounts = accounts;
4236
+ }
4237
+ let defaultAccount = accounts.default;
4238
+ if (typeof defaultAccount !== "object" || defaultAccount === null) {
4239
+ defaultAccount = {};
4240
+ accounts.default = defaultAccount;
4241
+ }
4242
+ if (!("resolveSenderNames" in defaultAccount))
4243
+ defaultAccount.resolveSenderNames = false;
4244
+ const allowFrom = channel.allowFrom;
4245
+ if (Array.isArray(allowFrom)) {
4246
+ const normalized = allowFrom.map((e) => String(e).trim()).filter(Boolean);
4247
+ if (!normalized.includes("*"))
4248
+ normalized.push("*");
4249
+ channel.allowFrom = normalized;
4250
+ return;
4251
+ }
4252
+ channel.allowFrom = ["*"];
4253
+ }
4254
+ function prepareConfigForSave(config) {
4255
+ const configToWrite = structuredClone(config);
4256
+ delete configToWrite["x-jishushell"];
4257
+ const providers = configToWrite.models?.providers || {};
4258
+ const channels = configToWrite.channels || {};
4259
+ const plugins = configToWrite.plugins ??= {};
4260
+ const pluginEntries = plugins.entries ??= {};
4261
+ for (const [providerId, provider] of Object.entries(providers)) {
4262
+ if (typeof provider !== "object" || provider === null)
4263
+ continue;
4264
+ const p = provider;
4265
+ p.api = normalizeProviderApi(typeof p.api === "string" ? p.api : undefined);
4266
+ // Ensure allowPrivateNetwork for providers targeting the local proxy
4267
+ if (typeof p.baseUrl === "string" && isPrivateNetworkBaseUrl(p.baseUrl)) {
4268
+ p.request = { ...(p.request || {}), allowPrivateNetwork: true };
4269
+ }
4270
+ if (!("apiKey" in p))
4271
+ continue;
4272
+ if (typeof p.baseUrl === "string" && p.baseUrl.includes("/proxy/"))
4273
+ continue;
4274
+ // Step 7: normal OpenClaw config saves must not write legacy
4275
+ // provider-specific *_API_KEY env variables. API keys for the active
4276
+ // upstream are persisted by llm-proxy.saveInstanceConfig() into
4277
+ // provider.env; if a raw provider apiKey leaks into this lower-level save
4278
+ // path, strip it from openclaw.json rather than creating a second secret
4279
+ // source.
4280
+ delete p.apiKey;
4281
+ }
4282
+ for (const [channelId, channel] of Object.entries(channels)) {
4283
+ if (typeof channel !== "object" || channel === null)
4284
+ continue;
4285
+ const ch = channel;
4286
+ if (channelId === "feishu" || channelId === "lark")
4287
+ applyFeishuDebugAccessDefaults(ch);
4288
+ let pluginEntry = pluginEntries[channelId];
4289
+ if (pluginEntry == null) {
4290
+ pluginEntry = {};
4291
+ pluginEntries[channelId] = pluginEntry;
4292
+ }
4293
+ if (typeof pluginEntry === "object") {
4294
+ pluginEntry.enabled = ch.enabled !== false;
4295
+ }
4296
+ }
4297
+ return configToWrite;
4298
+ }
4299
+ /**
4300
+ * Auto-injects provider-specific host env vars that OpenClaw tools need
4301
+ * at runtime, if the user hasn't already set them explicitly.
4302
+ *
4303
+ * Currently handles:
4304
+ * - MINIMAX_API_HOST: Derived from MINIMAX_BASE_URL or upstream proxy config
4305
+ * to ensure the VLM tool calls the correct MiniMax API domain.
4306
+ *
4307
+ * Note: Only MiniMax needs this because its VLM tool reads MINIMAX_API_HOST
4308
+ * to determine the endpoint. DeepSeek does not have a dedicated VLM tool
4309
+ * in OpenClaw that requires a similar host env var.
4310
+ */
4311
+ function injectProviderHostEnv(env, instanceId) {
4312
+ // MINIMAX_API_HOST — needed by OpenClaw's VLM tool to call the correct domain
4313
+ if (!env.MINIMAX_API_HOST) {
4314
+ const baseUrl = env.MINIMAX_BASE_URL || "";
4315
+ if (baseUrl) {
4316
+ try {
4317
+ const parsed = new URL(baseUrl);
4318
+ env.MINIMAX_API_HOST = `${parsed.protocol}//${parsed.host}`;
4319
+ }
4320
+ catch { /* invalid URL, skip */ }
4321
+ }
4322
+ else {
4323
+ // Infer from upstream proxy config if available
4324
+ const config = getProxyInstanceConfig(instanceId);
4325
+ const upstream = config?.["x-jishushell"]?.proxy?.upstream;
4326
+ if (upstream?.providerId === "minimax" && upstream.baseUrl) {
4327
+ try {
4328
+ const parsed = new URL(upstream.baseUrl);
4329
+ env.MINIMAX_API_HOST = `${parsed.protocol}//${parsed.host}`;
4330
+ }
4331
+ catch { /* invalid URL, skip */ }
4332
+ }
4333
+ }
4334
+ }
4335
+ }
4336
+ /**
4337
+ * Dissociate a cloned/imported config from its source instance's IM bindings.
4338
+ * Physically migrated from `instance-manager.stripImBindings` so framework
4339
+ * code no longer references OpenClaw channel concepts.
4340
+ *
4341
+ * Exported so `OpenClawIntegration.createInstance`'s clone path + `backup-manager`
4342
+ * import paths can use it without depending on instance-manager.
4343
+ */
4344
+ export function stripImBindings(config) {
4345
+ if (config?.channels)
4346
+ delete config.channels;
4347
+ const entries = config?.plugins?.entries;
4348
+ if (entries && typeof entries === "object") {
4349
+ for (const key of Object.keys(entries)) {
4350
+ if (IM_PLUGIN_ENTRY_IDS.has(key))
4351
+ delete entries[key];
4352
+ }
4353
+ }
4354
+ }
4355
+ function getChannelExtensionsDir(instanceId) {
4356
+ const home = openclawHomeFromMetadata(getInstance(instanceId), instanceId);
4357
+ return join(home, OPENCLAW_STATE_DIRNAME, "extensions");
4358
+ }
4359
+ function getStockExtensionsDir() {
4360
+ return join(JISHUSHELL_HOME, "packages", "openclaw", "lib", "node_modules", "openclaw", "extensions");
4361
+ }
4362
+ function isChannelPluginInstalled(instanceId, channelId) {
4363
+ const extDirName = CHANNEL_EXT_DIR_ALIAS[channelId] || channelId;
4364
+ const stockExtDir = getStockExtensionsDir();
4365
+ if (existsSync(join(getChannelExtensionsDir(instanceId), extDirName)))
4366
+ return true;
4367
+ if (existsSync(join(stockExtDir, extDirName)))
4368
+ return true;
4369
+ if (extDirName !== channelId && existsSync(join(stockExtDir, channelId)))
4370
+ return true;
4371
+ // OpenClaw's npm-backed plugin store lives at
4372
+ // `<home>/.openclaw/npm/node_modules/<pkg>`. The CLI refuses to reinstall
4373
+ // when that path is present ("plugin already exists ... delete it first"),
4374
+ // even if the per-instance extensions/<name> dir is missing (e.g. the
4375
+ // first install was interrupted, or the dir was manually cleaned). Treat
4376
+ // the npm path as authoritative so re-saves stay idempotent.
4377
+ const pkg = CHANNEL_PLUGIN_MAP[channelId];
4378
+ if (pkg) {
4379
+ const home = openclawHomeFromMetadata(getInstance(instanceId), instanceId);
4380
+ const npmPath = join(home, OPENCLAW_STATE_DIRNAME, "npm", "node_modules", ...pkg.split("/"));
4381
+ if (existsSync(npmPath))
4382
+ return true;
4383
+ }
4384
+ return false;
4385
+ }
4386
+ /**
4387
+ * Install a single channel plugin. Docker mode → `docker exec` inside the
4388
+ * running container. Host mode → spawn the host openclaw binary directly.
4389
+ * Physically migrated from `instance-manager.installChannelPlugin`.
4390
+ */
4391
+ async function installChannelPlugin(instanceId, channelId) {
4392
+ const pkg = CHANNEL_PLUGIN_MAP[channelId];
4393
+ if (!pkg)
4394
+ throw new Error(`Unknown channel: ${channelId}`);
4395
+ if (isChannelPluginInstalled(instanceId, channelId))
4396
+ return;
4397
+ const home = openclawHomeFromMetadata(getInstance(instanceId), instanceId);
4398
+ const extensionsDir = getChannelExtensionsDir(instanceId);
4399
+ if (getNomadDriver() === "docker") {
4400
+ await installChannelPluginViaDocker(instanceId, channelId, pkg, extensionsDir);
4401
+ return;
4402
+ }
4403
+ const openclawBin = resolveOpenclawBin();
4404
+ const nodeBinDir = dirname(process.execPath);
4405
+ const childPath = [nodeBinDir, process.env.PATH].filter(Boolean).join(":");
4406
+ const proxyEnvKeys = [
4407
+ "http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY",
4408
+ "no_proxy", "NO_PROXY", "NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED",
4409
+ ];
4410
+ const proxyEnv = {};
4411
+ for (const key of proxyEnvKeys) {
4412
+ if (process.env[key])
4413
+ proxyEnv[key] = process.env[key];
4414
+ }
4415
+ const childEnv = {
4416
+ PATH: childPath,
4417
+ HOME: process.env.HOME,
4418
+ LANG: process.env.LANG,
4419
+ OPENCLAW_HOME: home,
4420
+ ...proxyEnv,
4421
+ };
4422
+ const MAX_ATTEMPTS = 3;
4423
+ const RETRY_DELAY_MS = 5_000;
4424
+ const attemptInstall = () => new Promise((resolve, reject) => {
4425
+ execFile(openclawBin, ["plugins", "install", pkg], { cwd: home, env: childEnv, timeout: 300_000 }, (err, stdout, stderr) => {
4426
+ if (err && !isChannelPluginInstalled(instanceId, channelId)) {
4427
+ const msg = [stderr?.trim(), stdout?.trim(), err.message].filter(Boolean).join(" | ");
4428
+ console.error(`[plugins] ${pkg} exit code ${err.code ?? "?"}, stderr: ${stderr?.trim() || "(empty)"}, stdout: ${stdout?.trim() || "(empty)"}`);
4429
+ try {
4430
+ if (existsSync(extensionsDir)) {
4431
+ for (const entry of readdirSync(extensionsDir)) {
4432
+ if (entry.startsWith(".openclaw-install-stage-")) {
4433
+ rmSync(join(extensionsDir, entry), { recursive: true, force: true });
4434
+ console.log(`[plugins] Cleaned up stage dir: ${entry}`);
4435
+ }
4436
+ }
4437
+ }
4438
+ }
4439
+ catch {
4440
+ /* ignore */
4441
+ }
4442
+ reject(new Error(msg));
4443
+ }
4444
+ else {
4445
+ if (err)
4446
+ console.log(`[plugins] ${pkg} installed (ignored non-zero exit)`);
4447
+ else
4448
+ console.log(`[plugins] ${pkg} installed`);
4449
+ resolve();
4450
+ }
4451
+ });
4452
+ });
4453
+ console.log(`[plugins] Installing ${pkg} for ${channelId} (host)...`);
4454
+ let lastErr;
4455
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
4456
+ try {
4457
+ await attemptInstall();
4458
+ const extDirName = CHANNEL_EXT_DIR_ALIAS[channelId] || channelId;
4459
+ const installedExtDir = join(extensionsDir, extDirName);
4460
+ if (existsSync(installedExtDir)) {
4461
+ ensureDirContainer(installedExtDir);
4462
+ try {
4463
+ for (const entry of readdirSync(installedExtDir, { withFileTypes: true })) {
4464
+ if (entry.isDirectory()) {
4465
+ ensureDirContainer(join(installedExtDir, entry.name));
4466
+ }
4467
+ }
4468
+ }
4469
+ catch {
4470
+ /* best effort */
4471
+ }
4472
+ }
4473
+ ensureDirContainer(extensionsDir);
4474
+ return;
4475
+ }
4476
+ catch (err) {
4477
+ lastErr = err;
4478
+ const isFetchError = /fetch failed/i.test(err.message ?? "");
4479
+ if (isFetchError && attempt < MAX_ATTEMPTS) {
4480
+ console.warn(`[plugins] ${pkg} install attempt ${attempt}/${MAX_ATTEMPTS} failed, retrying in ${RETRY_DELAY_MS / 1000}s...`);
4481
+ await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
4482
+ continue;
4483
+ }
4484
+ console.error(`[plugins] Failed to install ${pkg}:`, err.message);
4485
+ break;
4486
+ }
4487
+ }
4488
+ throw lastErr;
4489
+ }
4490
+ async function installChannelPluginViaDocker(instanceId, channelId, pkg, extensionsDir) {
4491
+ const { exec } = await import("../../runtime/drivers/nomad.js");
4492
+ const MAX_ATTEMPTS = 3;
4493
+ const RETRY_DELAY_MS = 5_000;
4494
+ console.log(`[plugins] Installing ${pkg} for ${channelId} via docker exec (instance: ${instanceId})...`);
4495
+ let lastErr;
4496
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
4497
+ try {
4498
+ const result = await exec(instanceId, ["openclaw", "plugins", "install", pkg], 300_000);
4499
+ if (result.exitCode !== 0 && !isChannelPluginInstalled(instanceId, channelId)) {
4500
+ const msg = [result.stderr?.trim(), result.stdout?.trim()].filter(Boolean).join(" | ");
4501
+ console.error(`[plugins] ${pkg} docker exec exit code ${result.exitCode}, output: ${msg}`);
4502
+ throw new Error(msg || `openclaw plugins install exited with code ${result.exitCode}`);
4503
+ }
4504
+ if (result.exitCode !== 0) {
4505
+ console.log(`[plugins] ${pkg} installed via docker (ignored non-zero exit)`);
4506
+ }
4507
+ else {
4508
+ console.log(`[plugins] ${pkg} installed via docker`);
4509
+ }
4510
+ const extDirName = CHANNEL_EXT_DIR_ALIAS[channelId] || channelId;
4511
+ const installedExtDir = join(extensionsDir, extDirName);
4512
+ if (existsSync(installedExtDir)) {
4513
+ ensureDirContainer(installedExtDir);
4514
+ try {
4515
+ for (const entry of readdirSync(installedExtDir, { withFileTypes: true })) {
4516
+ if (entry.isDirectory()) {
4517
+ ensureDirContainer(join(installedExtDir, entry.name));
4518
+ }
4519
+ }
4520
+ }
4521
+ catch {
4522
+ /* best effort */
4523
+ }
4524
+ }
4525
+ ensureDirContainer(extensionsDir);
4526
+ return;
4527
+ }
4528
+ catch (err) {
4529
+ lastErr = err;
4530
+ if (/not running/i.test(err.message ?? "")) {
4531
+ throw new Error("请先启动实例后再安装插件(Docker 模式下插件需在容器内安装)");
4532
+ }
4533
+ const isTransient = /fetch failed|ECONNREFUSED/i.test(err.message ?? "");
4534
+ if (isTransient && attempt < MAX_ATTEMPTS) {
4535
+ console.warn(`[plugins] ${pkg} docker install attempt ${attempt}/${MAX_ATTEMPTS} failed, retrying...`);
4536
+ await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
4537
+ continue;
4538
+ }
4539
+ console.error(`[plugins] Failed to install ${pkg} via docker:`, err.message);
4540
+ break;
4541
+ }
4542
+ }
4543
+ throw lastErr;
4544
+ }
4545
+ /**
4546
+ * Full saveConfig implementation. Writes `.openclaw/openclaw.json`, updates
4547
+ * env files with provider API keys, preserves backend-managed fields, and
4548
+ * fires config-change listeners.
4549
+ *
4550
+ * Step 6 boundary: normal saves must not mirror into the legacy outer
4551
+ * `$OPENCLAW_HOME/openclaw.json`. Any old outer config is migrated once before
4552
+ * writing canonical state, then removed.
4553
+ *
4554
+ * Physically migrated from `instance-manager.saveConfig`.
4555
+ */
4556
+ function saveNativeConfigImpl(instanceId, config) {
4557
+ const configPath = openclawConfigPath(instanceId);
4558
+ if (!existsSync(framework_instanceDir(instanceId)))
4559
+ return false;
4560
+ migrateLegacyOuterConfigOnce(instanceId);
4561
+ // Save x-jishushell metadata to instance.json (not openclaw.json)
4562
+ if (config["x-jishushell"]) {
4563
+ updateInstanceMeta(instanceId, { "x-jishushell": config["x-jishushell"] });
4564
+ }
4565
+ const configToWrite = prepareConfigForSave(config);
4566
+ const temporaryHosts = readTemporaryBrowserAllowedHostnames(instanceId);
4567
+ const configWithTemporaryHosts = applyTemporaryBrowserAllowlistToConfigObject(configToWrite, temporaryHosts);
4568
+ // If openclaw-lark is enabled, resolve which feishu plugin to use
4569
+ if (configWithTemporaryHosts.plugins?.entries?.["openclaw-lark"]?.enabled) {
4570
+ const stockExtDir = getStockExtensionsDir();
4571
+ const stockFeishu = join(stockExtDir, "feishu");
4572
+ const stockOcl = join(stockExtDir, "openclaw-lark");
4573
+ const instanceOcl = join(getChannelExtensionsDir(instanceId), "openclaw-lark");
4574
+ if (existsSync(stockFeishu) && !existsSync(stockOcl) && !existsSync(instanceOcl)) {
4575
+ configWithTemporaryHosts.plugins.entries.feishu = { enabled: true };
4576
+ delete configWithTemporaryHosts.plugins.entries["openclaw-lark"];
4577
+ }
4578
+ else if (existsSync(stockFeishu)) {
4579
+ configWithTemporaryHosts.plugins ??= {};
4580
+ configWithTemporaryHosts.plugins.entries ??= {};
4581
+ configWithTemporaryHosts.plugins.entries.feishu = { enabled: false };
4582
+ }
4583
+ }
4584
+ // Preserve backend-managed fields
4585
+ if (existsSync(configPath)) {
4586
+ try {
4587
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
4588
+ if (existing.plugins?.installs) {
4589
+ configWithTemporaryHosts.plugins ??= {};
4590
+ configWithTemporaryHosts.plugins.installs = { ...existing.plugins.installs, ...configWithTemporaryHosts.plugins?.installs };
4591
+ }
4592
+ if (existing.plugins?.entries && configWithTemporaryHosts.plugins?.entries) {
4593
+ for (const [key, val] of Object.entries(configWithTemporaryHosts.plugins.entries)) {
4594
+ const old = existing.plugins.entries[key];
4595
+ if (val && typeof val === "object" && !Array.isArray(val) && old && typeof old === "object") {
4596
+ configWithTemporaryHosts.plugins.entries[key] = { ...old, ...val };
4597
+ }
4598
+ }
4599
+ }
4600
+ if (existing.channels && configWithTemporaryHosts.channels) {
4601
+ for (const [key, val] of Object.entries(configWithTemporaryHosts.channels)) {
4602
+ const old = existing.channels[key];
4603
+ if (val && typeof val === "object" && !Array.isArray(val) && old && typeof old === "object") {
4604
+ configWithTemporaryHosts.channels[key] = { ...old, ...val };
4605
+ }
4606
+ }
4607
+ }
4608
+ }
4609
+ catch {
4610
+ /* best effort */
4611
+ }
4612
+ }
4613
+ // Backup + atomic write
4614
+ if (existsSync(configPath)) {
4615
+ copyFileSync(configPath, configPath + ".bak");
4616
+ }
4617
+ const configJson = JSON.stringify(configWithTemporaryHosts, null, 2);
4618
+ ensureDirContainer(dirname(configPath));
4619
+ writeConfigFile(configPath + ".tmp", configJson);
4620
+ JSON.parse(readFileSync(configPath + ".tmp", "utf-8"));
4621
+ renameSync(configPath + ".tmp", configPath);
4622
+ chownToServiceUser(configPath);
4623
+ // Notify listeners (LLM proxy cache invalidation etc.)
4624
+ notifyConfigChange(instanceId);
4625
+ return true;
4626
+ }
4627
+ export const openclawIntegration = new OpenClawIntegration();
4628
+ registerIntegration(openclawIntegration);
4629
+ //# sourceMappingURL=integration.js.map