jishushell 0.4.24 → 0.5.15

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 (281) hide show
  1. package/INSTALL-NOTICE +11 -0
  2. package/apps/anythingllm-container.yaml +287 -0
  3. package/apps/browserless-chromium-container.yaml +90 -0
  4. package/apps/filebrowser-container.yaml +163 -0
  5. package/apps/hermes-container.yaml +36 -2
  6. package/apps/ollama-binary.yaml +91 -90
  7. package/apps/ollama-cpu-container.yaml +8 -1
  8. package/apps/ollama-with-hollama-binary.yaml +91 -90
  9. package/apps/openclaw-binary.yaml +38 -1
  10. package/apps/openclaw-container.yaml +45 -2
  11. package/apps/openclaw-with-ollama-container.yaml +11 -2
  12. package/apps/openclaw-with-searxng-container.yaml +26 -2
  13. package/apps/openwebui-container.yaml +45 -1
  14. package/apps/playwright-container.yaml +7 -1
  15. package/apps/searxng-container.yaml +58 -7
  16. package/apps/weknora-container.yaml +471 -0
  17. package/dist/cli/app.js +79 -9
  18. package/dist/cli/app.js.map +1 -1
  19. package/dist/cli/doctor.d.ts +12 -12
  20. package/dist/cli/doctor.js +242 -55
  21. package/dist/cli/doctor.js.map +1 -1
  22. package/dist/cli/llm.d.ts +4 -3
  23. package/dist/cli/llm.js +4 -3
  24. package/dist/cli/llm.js.map +1 -1
  25. package/dist/cli/panel.d.ts +6 -5
  26. package/dist/cli/panel.js +10 -9
  27. package/dist/cli/panel.js.map +1 -1
  28. package/dist/config.d.ts +19 -0
  29. package/dist/config.js +99 -1
  30. package/dist/config.js.map +1 -1
  31. package/dist/control.d.ts +7 -6
  32. package/dist/control.js +7 -6
  33. package/dist/control.js.map +1 -1
  34. package/dist/install.js +3 -3
  35. package/dist/install.js.map +1 -1
  36. package/dist/routes/agent-apps.d.ts +1 -1
  37. package/dist/routes/agent-apps.js +1 -1
  38. package/dist/routes/apps.js +44 -11
  39. package/dist/routes/apps.js.map +1 -1
  40. package/dist/routes/auth.js +5 -2
  41. package/dist/routes/auth.js.map +1 -1
  42. package/dist/routes/backup.js +64 -11
  43. package/dist/routes/backup.js.map +1 -1
  44. package/dist/routes/external-mounts.d.ts +17 -0
  45. package/dist/routes/external-mounts.js +73 -0
  46. package/dist/routes/external-mounts.js.map +1 -0
  47. package/dist/routes/file-mounts.d.ts +13 -0
  48. package/dist/routes/file-mounts.js +90 -0
  49. package/dist/routes/file-mounts.js.map +1 -0
  50. package/dist/routes/files-organize.d.ts +28 -0
  51. package/dist/routes/files-organize.js +167 -0
  52. package/dist/routes/files-organize.js.map +1 -0
  53. package/dist/routes/files.d.ts +31 -0
  54. package/dist/routes/files.js +321 -0
  55. package/dist/routes/files.js.map +1 -0
  56. package/dist/routes/instances.js +826 -17
  57. package/dist/routes/instances.js.map +1 -1
  58. package/dist/routes/internal.d.ts +2 -0
  59. package/dist/routes/internal.js +59 -0
  60. package/dist/routes/internal.js.map +1 -0
  61. package/dist/routes/llm.js +24 -35
  62. package/dist/routes/llm.js.map +1 -1
  63. package/dist/routes/setup.js +10 -10
  64. package/dist/routes/setup.js.map +1 -1
  65. package/dist/routes/system.js +1 -1
  66. package/dist/routes/system.js.map +1 -1
  67. package/dist/routes/webdav.d.ts +17 -0
  68. package/dist/routes/webdav.js +114 -0
  69. package/dist/routes/webdav.js.map +1 -0
  70. package/dist/server.d.ts +9 -0
  71. package/dist/server.js +751 -20
  72. package/dist/server.js.map +1 -1
  73. package/dist/services/agent-apps/catalog.js +4 -3
  74. package/dist/services/agent-apps/catalog.js.map +1 -1
  75. package/dist/services/agent-apps/index.d.ts +1 -1
  76. package/dist/services/agent-apps/index.js +1 -1
  77. package/dist/services/agent-apps/installers/adapter.d.ts +1 -1
  78. package/dist/services/agent-apps/installers/adapter.js +1 -1
  79. package/dist/services/agent-apps/installers/shell-script.d.ts +1 -1
  80. package/dist/services/agent-apps/installers/shell-script.js +3 -3
  81. package/dist/services/agent-apps/installers/shell-script.js.map +1 -1
  82. package/dist/services/agent-apps/types.d.ts +2 -2
  83. package/dist/services/agent-apps/types.js +1 -1
  84. package/dist/services/app/app-compiler.d.ts +1 -1
  85. package/dist/services/app/app-compiler.js +5 -5
  86. package/dist/services/app/app-compiler.js.map +1 -1
  87. package/dist/services/app/app-manager.d.ts +25 -1
  88. package/dist/services/app/app-manager.js +829 -150
  89. package/dist/services/app/app-manager.js.map +1 -1
  90. package/dist/services/app/custom-manager.js.map +1 -1
  91. package/dist/services/app/hermes-agent-manager.js +7 -4
  92. package/dist/services/app/hermes-agent-manager.js.map +1 -1
  93. package/dist/services/app/ollama-manager.js +1 -1
  94. package/dist/services/app/ollama-manager.js.map +1 -1
  95. package/dist/services/app/openclaw-manager.js +20 -3
  96. package/dist/services/app/openclaw-manager.js.map +1 -1
  97. package/dist/services/app/platform-transform.d.ts +32 -0
  98. package/dist/services/app/platform-transform.js +65 -0
  99. package/dist/services/app/platform-transform.js.map +1 -0
  100. package/dist/services/app/provide-resolver.d.ts +29 -0
  101. package/dist/services/app/provide-resolver.js +112 -0
  102. package/dist/services/app/provide-resolver.js.map +1 -0
  103. package/dist/services/app-passwords.d.ts +61 -0
  104. package/dist/services/app-passwords.js +173 -0
  105. package/dist/services/app-passwords.js.map +1 -0
  106. package/dist/services/backup-manager.d.ts +11 -0
  107. package/dist/services/backup-manager.js +177 -4
  108. package/dist/services/backup-manager.js.map +1 -1
  109. package/dist/services/capability-endpoint-validator.d.ts +41 -0
  110. package/dist/services/capability-endpoint-validator.js +104 -0
  111. package/dist/services/capability-endpoint-validator.js.map +1 -0
  112. package/dist/services/capability-health.d.ts +16 -0
  113. package/dist/services/capability-health.js +121 -0
  114. package/dist/services/capability-health.js.map +1 -0
  115. package/dist/services/capability-registry.d.ts +106 -0
  116. package/dist/services/capability-registry.js +313 -0
  117. package/dist/services/capability-registry.js.map +1 -0
  118. package/dist/services/connection-apply.d.ts +91 -0
  119. package/dist/services/connection-apply.js +475 -0
  120. package/dist/services/connection-apply.js.map +1 -0
  121. package/dist/services/connection-resolver.d.ts +65 -0
  122. package/dist/services/connection-resolver.js +281 -0
  123. package/dist/services/connection-resolver.js.map +1 -0
  124. package/dist/services/connection-transactor.d.ts +39 -0
  125. package/dist/services/connection-transactor.js +351 -0
  126. package/dist/services/connection-transactor.js.map +1 -0
  127. package/dist/services/external-mounts.d.ts +40 -0
  128. package/dist/services/external-mounts.js +187 -0
  129. package/dist/services/external-mounts.js.map +1 -0
  130. package/dist/services/files-manager.d.ts +252 -0
  131. package/dist/services/files-manager.js +1075 -0
  132. package/dist/services/files-manager.js.map +1 -0
  133. package/dist/services/files-mounts.d.ts +42 -0
  134. package/dist/services/files-mounts.js +207 -0
  135. package/dist/services/files-mounts.js.map +1 -0
  136. package/dist/services/instance-manager.d.ts +13 -0
  137. package/dist/services/instance-manager.js +138 -46
  138. package/dist/services/instance-manager.js.map +1 -1
  139. package/dist/services/llm-proxy/index.d.ts +16 -2
  140. package/dist/services/llm-proxy/index.js +48 -44
  141. package/dist/services/llm-proxy/index.js.map +1 -1
  142. package/dist/services/llm-proxy/probe.d.ts +6 -0
  143. package/dist/services/llm-proxy/probe.js +85 -0
  144. package/dist/services/llm-proxy/probe.js.map +1 -0
  145. package/dist/services/llm-proxy/ssrf.d.ts +1 -0
  146. package/dist/services/llm-proxy/ssrf.js +24 -9
  147. package/dist/services/llm-proxy/ssrf.js.map +1 -1
  148. package/dist/services/nomad-manager.d.ts +4 -0
  149. package/dist/services/nomad-manager.js +428 -35
  150. package/dist/services/nomad-manager.js.map +1 -1
  151. package/dist/services/organize/applier.d.ts +46 -0
  152. package/dist/services/organize/applier.js +218 -0
  153. package/dist/services/organize/applier.js.map +1 -0
  154. package/dist/services/organize/rules.d.ts +57 -0
  155. package/dist/services/organize/rules.js +286 -0
  156. package/dist/services/organize/rules.js.map +1 -0
  157. package/dist/services/organize/scanner.d.ts +50 -0
  158. package/dist/services/organize/scanner.js +366 -0
  159. package/dist/services/organize/scanner.js.map +1 -0
  160. package/dist/services/organize/store.d.ts +14 -0
  161. package/dist/services/organize/store.js +82 -0
  162. package/dist/services/organize/store.js.map +1 -0
  163. package/dist/services/panel-manager.js +20 -1
  164. package/dist/services/panel-manager.js.map +1 -1
  165. package/dist/services/process-manager.js +4 -3
  166. package/dist/services/process-manager.js.map +1 -1
  167. package/dist/services/runtime/adapters/hermes.d.ts +30 -1
  168. package/dist/services/runtime/adapters/hermes.js +219 -6
  169. package/dist/services/runtime/adapters/hermes.js.map +1 -1
  170. package/dist/services/runtime/adapters/openclaw-mcporter.d.ts +45 -0
  171. package/dist/services/runtime/adapters/openclaw-mcporter.js +108 -0
  172. package/dist/services/runtime/adapters/openclaw-mcporter.js.map +1 -0
  173. package/dist/services/runtime/adapters/openclaw-routes.d.ts +8 -2
  174. package/dist/services/runtime/adapters/openclaw-routes.js +68 -0
  175. package/dist/services/runtime/adapters/openclaw-routes.js.map +1 -1
  176. package/dist/services/runtime/adapters/openclaw.d.ts +177 -0
  177. package/dist/services/runtime/adapters/openclaw.js +1171 -11
  178. package/dist/services/runtime/adapters/openclaw.js.map +1 -1
  179. package/dist/services/runtime/instance.d.ts +1 -1
  180. package/dist/services/runtime/instance.js +1 -1
  181. package/dist/services/runtime/instance.js.map +1 -1
  182. package/dist/services/runtime/mcp-shims/anythingllm-shim.d.ts +46 -0
  183. package/dist/services/runtime/mcp-shims/anythingllm-shim.js +281 -0
  184. package/dist/services/runtime/mcp-shims/anythingllm-shim.js.map +1 -0
  185. package/dist/services/runtime/mcp-shims/drive-shim.d.ts +54 -0
  186. package/dist/services/runtime/mcp-shims/drive-shim.js +489 -0
  187. package/dist/services/runtime/mcp-shims/drive-shim.js.map +1 -0
  188. package/dist/services/runtime/mcp-shims/firewall.d.ts +26 -0
  189. package/dist/services/runtime/mcp-shims/firewall.js +129 -0
  190. package/dist/services/runtime/mcp-shims/firewall.js.map +1 -0
  191. package/dist/services/runtime/mcp-shims/searxng-shim.d.ts +27 -0
  192. package/dist/services/runtime/mcp-shims/searxng-shim.js +125 -0
  193. package/dist/services/runtime/mcp-shims/searxng-shim.js.map +1 -0
  194. package/dist/services/runtime/mcp-shims/write-mcp-entry.d.ts +83 -0
  195. package/dist/services/runtime/mcp-shims/write-mcp-entry.js +127 -0
  196. package/dist/services/runtime/mcp-shims/write-mcp-entry.js.map +1 -0
  197. package/dist/services/runtime/migrations.d.ts +8 -0
  198. package/dist/services/runtime/migrations.js +100 -0
  199. package/dist/services/runtime/migrations.js.map +1 -1
  200. package/dist/services/runtime/types.d.ts +46 -0
  201. package/dist/services/setup-manager.js +99 -24
  202. package/dist/services/setup-manager.js.map +1 -1
  203. package/dist/services/suggestions.d.ts +27 -0
  204. package/dist/services/suggestions.js +133 -0
  205. package/dist/services/suggestions.js.map +1 -0
  206. package/dist/services/task-registry.js +4 -2
  207. package/dist/services/task-registry.js.map +1 -1
  208. package/dist/services/telemetry/device-fingerprint.d.ts +1 -1
  209. package/dist/services/telemetry/device-fingerprint.js +1 -1
  210. package/dist/services/types-shim.d.ts +16 -0
  211. package/dist/services/types-shim.js +2 -0
  212. package/dist/services/types-shim.js.map +1 -0
  213. package/dist/services/webdav/server.d.ts +24 -0
  214. package/dist/services/webdav/server.js +420 -0
  215. package/dist/services/webdav/server.js.map +1 -0
  216. package/dist/services/webdav/xml-builder.d.ts +73 -0
  217. package/dist/services/webdav/xml-builder.js +156 -0
  218. package/dist/services/webdav/xml-builder.js.map +1 -0
  219. package/dist/services/workspace-builder.d.ts +29 -0
  220. package/dist/services/workspace-builder.js +188 -0
  221. package/dist/services/workspace-builder.js.map +1 -0
  222. package/dist/types.d.ts +231 -1
  223. package/dist/utils/instance-lock.d.ts +22 -0
  224. package/dist/utils/instance-lock.js +48 -0
  225. package/dist/utils/instance-lock.js.map +1 -0
  226. package/dist/utils/path-locks.d.ts +30 -0
  227. package/dist/utils/path-locks.js +63 -0
  228. package/dist/utils/path-locks.js.map +1 -0
  229. package/dist/utils/path-safety.d.ts +41 -0
  230. package/dist/utils/path-safety.js +119 -0
  231. package/dist/utils/path-safety.js.map +1 -0
  232. package/dist/utils/safe-json.js +55 -22
  233. package/dist/utils/safe-json.js.map +1 -1
  234. package/dist/utils/safe-write.d.ts +24 -0
  235. package/dist/utils/safe-write.js +82 -0
  236. package/dist/utils/safe-write.js.map +1 -0
  237. package/install/jishu-install.sh +323 -27
  238. package/install/jishu-uninstall.sh +353 -20
  239. package/package.json +18 -1
  240. package/public/assets/Dashboard-BdWPtroF.js +1 -0
  241. package/public/assets/{HermesChatPanel-mFSureyc.js → HermesChatPanel-B_2HlVBQ.js} +1 -1
  242. package/public/assets/HermesConfigForm-DVlhg3WV.js +4 -0
  243. package/public/assets/{InitPassword-CVA8wQA6.js → InitPassword-D7glTExX.js} +1 -1
  244. package/public/assets/InstanceDetail-CxSy2cpe.js +92 -0
  245. package/public/assets/{Login-BWsZH2mu.js → Login-Cfr5c2sv.js} +1 -1
  246. package/public/assets/NewInstance-BIYDmJis.js +1 -0
  247. package/public/assets/ProviderRecommendations-BuRnvRcI.js +1 -0
  248. package/public/assets/Settings-Cc-tYBil.js +1 -0
  249. package/public/assets/Setup-lGZEk5jq.js +1 -0
  250. package/public/assets/{WeixinLoginPanel-CnjR8xMu.js → WeixinLoginPanel-CoGqzxeV.js} +2 -2
  251. package/public/assets/index-87IJXG-w.css +1 -0
  252. package/public/assets/index-BZc5zH7u.js +19 -0
  253. package/public/assets/providers-DtNXh9JD.js +1 -0
  254. package/public/assets/registry-BWnkJgZ1.js +2 -0
  255. package/public/assets/{usePolling-Do5Erqm_.js → usePolling-CwwT9KrC.js} +1 -1
  256. package/public/assets/{vendor-i18n-ucpM0OR0.js → vendor-i18n-y9V7Sfuu.js} +1 -1
  257. package/public/assets/{vendor-react-Bk1hRGiY.js → vendor-react-BWrEVJVb.js} +6 -6
  258. package/public/index.html +4 -4
  259. package/scripts/check-app-spec.mjs +457 -0
  260. package/scripts/check-i18n.mjs +154 -0
  261. package/scripts/check-new-file-tests.mjs +230 -0
  262. package/scripts/check-quarantine-expiry.mjs +105 -0
  263. package/scripts/perf/README.md +49 -0
  264. package/scripts/perf/auth.js +99 -0
  265. package/scripts/perf/config.js +63 -0
  266. package/scripts/perf/instances.js +143 -0
  267. package/scripts/perf/proxy.js +96 -0
  268. package/scripts/run.sh +4 -4
  269. package/scripts/smoke/files-w1.sh +142 -0
  270. package/scripts/smoke-backend.mjs +122 -0
  271. package/scripts/smoke-post-publish.mjs +346 -0
  272. package/public/assets/Dashboard-B-JoOjBQ.js +0 -1
  273. package/public/assets/HermesConfigForm-DvR05LK1.js +0 -4
  274. package/public/assets/InstanceDetail-DcZW2QGO.js +0 -91
  275. package/public/assets/NewInstance-BCIrAd86.js +0 -1
  276. package/public/assets/Settings-xkDcduFz.js +0 -1
  277. package/public/assets/Setup-Cfuwj4gV.js +0 -1
  278. package/public/assets/index-CPhVFEsx.css +0 -1
  279. package/public/assets/index-DQsM6Joa.js +0 -19
  280. package/public/assets/providers-V-vwrExZ.js +0 -1
  281. package/public/assets/registry-B4UFJdpA.js +0 -2
@@ -34,10 +34,10 @@
34
34
  * 4. Done. No `instance-manager.ts` / `nomad-manager.ts` / routes edits.
35
35
  */
36
36
  import { execFile, execFileSync } from "child_process";
37
- import { chmodSync, chownSync, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, } from "fs";
37
+ import { accessSync, chmodSync, chownSync, copyFileSync, cpSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from "fs";
38
38
  import { randomBytes } from "crypto";
39
39
  import { homedir, userInfo } from "os";
40
- import { dirname, join, resolve as pathResolve } from "path";
40
+ import { delimiter, dirname, join, resolve as pathResolve } from "path";
41
41
  import { getNomadDriver, getOpenclawDockerImage, JISHUSHELL_HOME, getPanelConfig, } from "../../../config.js";
42
42
  import { LEGACY_PROVIDER_API_ALIASES } from "../../../constants.js";
43
43
  import { ensureDirContainer, ensureDirHost, writeConfigFile } from "../../../utils/fs.js";
@@ -114,6 +114,55 @@ const DEFAULT_CAPABILITIES = {
114
114
  restartlessReload: false,
115
115
  messagingPlatforms: ["feishu", "openclaw-weixin"],
116
116
  };
117
+ import { FILES_ROOT } from "../../../config.js";
118
+ import { defaultMountsForNewInstance, ensureMountTargets, } from "../../files-mounts.js";
119
+ /**
120
+ * Tolerate both `fileMounts` and `file_mounts` in instance.json — some
121
+ * earlier migrations may have written snake_case.
122
+ */
123
+ function readFileMounts(runtime) {
124
+ const raw = runtime.fileMounts ?? runtime.file_mounts;
125
+ return Array.isArray(raw) ? raw : [];
126
+ }
127
+ /**
128
+ * Build the volume list for the docker driver:
129
+ * 1. The existing openclaw-home self-mount (HOME == container HOME)
130
+ * 2. The root FILES_ROOT bind when any mount has empty path
131
+ * ({"path":"","alias":"","mode":"rw"} — the default for new
132
+ * instances). Without this, in-container plugins (Feishu / WeChat
133
+ * send_file) try `fs.open("/home/.../files/...")` and hit ENOENT
134
+ * because the host path isn't bind-mounted. Verified on pi2
135
+ * 2026-05-11: claw1's drive_resolve_local_path returned a valid
136
+ * abs_path; feishu_im_user_message then ENOENT'd on it.
137
+ * 3. One additional bind per non-root FileMount, host==container so
138
+ * the workspace/{alias} symlink (placed by rebuildWorkspace)
139
+ * resolves identically inside the container.
140
+ *
141
+ * Mode "ro" is enforced by the docker bind option; raw_exec / process
142
+ * modes don't go through this path (the agent runs natively on the host
143
+ * and reads files directly).
144
+ */
145
+ function buildVolumes(openclawHome, runtime) {
146
+ const list = [`${openclawHome}:${openclawHome}:rw`];
147
+ let rootBound = false;
148
+ for (const m of readFileMounts(runtime)) {
149
+ if (!m)
150
+ continue;
151
+ const mode = m.mode === "ro" ? "ro" : "rw";
152
+ if (!m.path) {
153
+ if (rootBound)
154
+ continue;
155
+ list.push(`${FILES_ROOT}:${FILES_ROOT}:${mode}`);
156
+ rootBound = true;
157
+ continue;
158
+ }
159
+ if (rootBound)
160
+ continue; // root already covers every subtree
161
+ const abs = join(FILES_ROOT, m.path);
162
+ list.push(`${abs}:${abs}:${mode}`);
163
+ }
164
+ return list;
165
+ }
117
166
  // ── Path helpers (physically migrated from instance-manager.ts) ───────
118
167
  const INSTANCE_OPENCLAW_HOME_DIRNAME = "openclaw-home";
119
168
  const INSTANCE_MODEL_ENV_FILENAME = "model.env";
@@ -176,7 +225,32 @@ function resolveOpenclawBin() {
176
225
  return p;
177
226
  }
178
227
  }
179
- return candidates[0]; // fallback, will fail with clear error at spawn
228
+ // Fallback: scan $PATH for user-installed openclaw (nvm, homebrew, etc.)
229
+ // Uses in-process lookup instead of spawning `which` for security and performance.
230
+ const fromPath = findExecutableOnPath("openclaw");
231
+ if (fromPath)
232
+ return fromPath;
233
+ return candidates[0]; // will fail with clear error at spawn
234
+ }
235
+ /**
236
+ * Search $PATH for an executable by name. Returns the first match or null.
237
+ * Does not chmod the result — PATH-discovered binaries are not managed by JishuShell.
238
+ */
239
+ function findExecutableOnPath(name) {
240
+ const pathEnv = process.env.PATH || "";
241
+ for (const dir of pathEnv.split(delimiter)) {
242
+ if (!dir)
243
+ continue;
244
+ const candidate = join(dir, name);
245
+ try {
246
+ accessSync(candidate, constants.X_OK);
247
+ return candidate;
248
+ }
249
+ catch {
250
+ /* not found or not executable in this dir */
251
+ }
252
+ }
253
+ return null;
180
254
  }
181
255
  function buildDefaultRuntime(instanceId, port, openclawHome) {
182
256
  const home = openclawHome || defaultOpenclawHome(instanceId);
@@ -189,6 +263,12 @@ function buildDefaultRuntime(instanceId, port, openclawHome) {
189
263
  env: {
190
264
  OPENCLAW_GATEWAY_PORT: String(port),
191
265
  NODE_OPTIONS: "--max-old-space-size=2048",
266
+ // Let mcporter find its config regardless of the agent's CWD. The
267
+ // gateway's CWD is openclaw-home (no config/), and `cd workspace`
268
+ // means the user-files symlink (also no config/). Without this env,
269
+ // every `mcporter call drive.*` fails with "Unknown MCP server 'drive'"
270
+ // and the agent reports a generic "network error" to the user.
271
+ MCPORTER_CONFIG: `${home}/.openclaw/workspace/config/mcporter.json`,
192
272
  },
193
273
  resources: { CPU: 1000, MemoryMB: 2048 },
194
274
  };
@@ -265,6 +345,20 @@ function patchJsproxyBaseUrl(configPath) {
265
345
  * container loopback. Normalize default/loopback gateway binds to `lan` so
266
346
  * Nomad's published host port can reach the gateway.
267
347
  */
348
+ // Mirrors hermes.ts:nomadHasExternalHostNetwork. When the host nomad.hcl
349
+ // declares `host_network "external" { ... }`, the legacy openclaw job
350
+ // attaches it to its ReservedPorts so docker publishes the gateway to
351
+ // the LAN address instead of 127.0.0.1. Without this, OpenWebUI in a
352
+ // sibling container can't reach openclaw at all.
353
+ function nomadHasExternalHostNetwork() {
354
+ const path = join(JISHUSHELL_HOME, "nomad", "nomad.hcl");
355
+ try {
356
+ return /host_network\s+"external"\s*\{/.test(readFileSync(path, "utf-8"));
357
+ }
358
+ catch {
359
+ return false;
360
+ }
361
+ }
268
362
  function patchDockerBridgeGatewayBind(configPath) {
269
363
  try {
270
364
  const raw = readFileSync(configPath, "utf-8");
@@ -290,6 +384,560 @@ function patchDockerBridgeGatewayBind(configPath) {
290
384
  console.warn(`[openclaw] Failed to patch gateway.bind in ${configPath}: ${e.message}`);
291
385
  }
292
386
  }
387
+ /**
388
+ * Ensure the `llm-agent` capability advertised by openclaw-*.yaml works for
389
+ * every instance, including ones created before this code shipped: enable
390
+ * OpenClaw's OpenAI-compatible endpoints in `openclaw.json` on every start.
391
+ *
392
+ * Runs idempotently next to `patchDockerBridgeGatewayBind`. The OpenAI
393
+ * routes (`/v1/chat/completions`, `/v1/responses`, `/v1/models`,
394
+ * `/v1/embeddings`) live in openclaw's bundled server.impl and are gated
395
+ * behind `gateway.http.endpoints.{chatCompletions,responses}.enabled` —
396
+ * default false, so a fresh OpenClaw install would 404 those paths even
397
+ * though OpenWebUI binds it through the connections page.
398
+ */
399
+ export function patchOpenAIEndpointsEnabled(configPath) {
400
+ try {
401
+ const raw = readFileSync(configPath, "utf-8");
402
+ const parsed = JSON.parse(raw);
403
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
404
+ return;
405
+ const root = parsed;
406
+ const gateway = root.gateway && typeof root.gateway === "object" && !Array.isArray(root.gateway)
407
+ ? root.gateway
408
+ : (root.gateway = {});
409
+ const http = gateway.http && typeof gateway.http === "object" && !Array.isArray(gateway.http)
410
+ ? gateway.http
411
+ : (gateway.http = {});
412
+ const endpoints = http.endpoints && typeof http.endpoints === "object" && !Array.isArray(http.endpoints)
413
+ ? http.endpoints
414
+ : (http.endpoints = {});
415
+ let changed = false;
416
+ for (const key of ["chatCompletions", "responses"]) {
417
+ const ep = endpoints[key] && typeof endpoints[key] === "object" && !Array.isArray(endpoints[key])
418
+ ? endpoints[key]
419
+ : (endpoints[key] = {});
420
+ if (ep.enabled !== true) {
421
+ ep.enabled = true;
422
+ changed = true;
423
+ }
424
+ }
425
+ if (!changed)
426
+ return;
427
+ const next = JSON.stringify(parsed, null, 2);
428
+ const output = raw.endsWith("\n") ? `${next}\n` : next;
429
+ writeConfigFile(configPath, output);
430
+ console.log(`[openclaw] Enabled gateway.http.endpoints.{chatCompletions,responses} in ${configPath} for llm-agent capability`);
431
+ }
432
+ catch (e) {
433
+ console.warn(`[openclaw] Failed to patch OpenAI endpoints in ${configPath}: ${e.message}`);
434
+ }
435
+ }
436
+ /**
437
+ * Deep-merge a SearXNG connection into an OpenClaw config file at `configPath`.
438
+ *
439
+ * Writes both halves of the wiring required for the `web_search` tool to use
440
+ * the registry-resolved SearXNG instance:
441
+ *
442
+ * plugins.entries.searxng.enabled = true
443
+ * plugins.entries.searxng.config.webSearch.baseUrl = baseUrl
444
+ * tools.web.search.provider = "searxng"
445
+ *
446
+ * The provider selector is required because OpenClaw's built-in default is
447
+ * `"brave"`; without it the tool fails with `missing_brave_api_key` even when
448
+ * the searxng plugin is otherwise correctly configured (verified on Pi
449
+ * 2026-04-29: claw11 had the plugin block right but the selector unset).
450
+ *
451
+ * Why a partial deep-merge instead of `saveNativeConfig`: the latter is
452
+ * destructive — it replaces top-level keys wholesale and only preserves a
453
+ * hardcoded subset (`plugins.installs`, `plugins.entries` per-key, partial
454
+ * `channels` merge). A partial patch through it would wipe `models.providers`
455
+ * / `agents.defaults` / etc., bricking the instance with `No API key found
456
+ * for provider "openai"` on the next chat. So we read, merge, write back.
457
+ *
458
+ * No-op when the config file is absent (instance not yet started).
459
+ */
460
+ export function applySearxngConnectionToConfig(configPath, baseUrl) {
461
+ if (!existsSync(configPath))
462
+ return;
463
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
464
+ existing.plugins = existing.plugins ?? {};
465
+ existing.plugins.entries = existing.plugins.entries ?? {};
466
+ const prior = existing.plugins.entries.searxng ?? {};
467
+ existing.plugins.entries.searxng = {
468
+ ...prior,
469
+ enabled: true,
470
+ config: {
471
+ ...(prior.config ?? {}),
472
+ webSearch: {
473
+ ...((prior.config ?? {}).webSearch ?? {}),
474
+ baseUrl,
475
+ },
476
+ },
477
+ };
478
+ existing.tools = existing.tools ?? {};
479
+ existing.tools.web = existing.tools.web ?? {};
480
+ existing.tools.web.search = existing.tools.web.search ?? {};
481
+ existing.tools.web.search.provider = "searxng";
482
+ safeWriteJson(configPath, existing);
483
+ }
484
+ /**
485
+ * Counterpart to `applySearxngConnectionToConfig` — invoked when the user
486
+ * unbinds the SEARCH slot in the Connections tab. Without this, unbinding
487
+ * left the plugin entry enabled with a baseUrl pointing at the now-gone
488
+ * searxng provider, and `tools.web.search.provider="searxng"` kept routing
489
+ * the agent's `web_search` tool through that dead URL on every chat.
490
+ *
491
+ * Conservative cleanup so a future re-bind (or user-customized plugin
492
+ * settings) survives:
493
+ * - flip the searxng plugin to enabled:false (don't delete the entry —
494
+ * user may have hand-tuned it and we want re-bind to re-enable cheaply)
495
+ * - drop the stale `webSearch.baseUrl` so nothing reads it as still-live
496
+ * - clear `tools.web.search.provider` so the runtime falls back to its
497
+ * built-in default (which today errors out with `missing_brave_api_key`
498
+ * — the right outcome: search was unbound, web_search shouldn't work)
499
+ *
500
+ * No-op when the config file is absent.
501
+ */
502
+ export function clearSearxngConnectionFromConfig(configPath) {
503
+ if (!existsSync(configPath))
504
+ return;
505
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
506
+ const sx = existing?.plugins?.entries?.searxng;
507
+ if (sx && typeof sx === "object") {
508
+ sx.enabled = false;
509
+ if (sx.config?.webSearch && typeof sx.config.webSearch === "object") {
510
+ delete sx.config.webSearch.baseUrl;
511
+ }
512
+ }
513
+ if (existing?.tools?.web?.search && typeof existing.tools.web.search === "object") {
514
+ delete existing.tools.web.search.provider;
515
+ }
516
+ safeWriteJson(configPath, existing);
517
+ }
518
+ /** Profile name used in `browser.profiles` for jishushell-managed Browserless bindings. */
519
+ const BROWSERLESS_PROFILE = "browserless";
520
+ /**
521
+ * Default `color` for the jishushell-managed browserless profile. OpenClaw's
522
+ * profile schema treats `color` as required (the field shows up as the
523
+ * profile chip tint in the UI); omitting it triggers
524
+ * "browser.profiles.browserless.color: Invalid input: expected string,
525
+ * received undefined"
526
+ * on every config reload, which crashloops the gateway. Verified against
527
+ * the runtime image `ghcr.io/x-aijishu/openclaw-runtime:2026.4.15` on Pi 2
528
+ * (2026-05-07). The tone is Browserless brand green; users can override it
529
+ * once and we preserve their override on re-bind via the `prior` spread.
530
+ */
531
+ const BROWSERLESS_DEFAULT_COLOR = "#00AA66";
532
+ /**
533
+ * Deep-merge a Browserless CDP connection into an OpenClaw config file at
534
+ * `configPath`. Mirrors `applySearxngConnectionToConfig` for the browser slot.
535
+ *
536
+ * Writes:
537
+ * browser.profiles.browserless.cdpUrl = cdpUrl // ws:// or wss://
538
+ * browser.profiles.browserless.attachOnly = true // since v2026.3.2
539
+ * browser.profiles.browserless.color = "#00AA66" // required by schema
540
+ * browser.defaultProfile = "browserless" // only if unset
541
+ * browser.enabled = true // only if unset
542
+ * gateway.nodes.browser.mode = "off" // only if unset
543
+ *
544
+ * Why per-profile `attachOnly` and not global `browser.attachOnly`: global
545
+ * attachOnly forces every profile to skip launch — that breaks the user's
546
+ * other manually-configured profiles. Per-profile attachOnly was added in
547
+ * OpenClaw v2026.3.2; older versions silently ignore the extra field and
548
+ * fall back to attach-via-cdpUrl semantics (which `cdpUrl` triggers on its
549
+ * own from v2.0.0-beta5), so the schema is forward-compatible all the way
550
+ * back to the first remote-CDP release.
551
+ *
552
+ * Why `gateway.nodes.browser.mode = "off"`: in OpenClaw 2026.5.6 the
553
+ * gateway only registers the `browser.request` WS method when this config
554
+ * block exists. Without it, `openclaw browser …` CLI and the gateway
555
+ * canvas tool both fail with `unknown method: browser.request` or
556
+ * `node required`. Setting `mode: "off"` forces gateway-local CDP
557
+ * dispatch (use `cdpUrl` directly, never look for paired nodes), which
558
+ * matches jishushell's intent: Browserless is a service-style provider,
559
+ * not a node-style provider. Verified end-to-end on Pi 2 (2026-05-07):
560
+ * Browserless `/sessions` shows `numbConnected: 1` and `openclaw browser
561
+ * navigate <allowed-host>` succeeds + screenshots render correctly.
562
+ *
563
+ * `defaultProfile`, `enabled`, and `gateway.nodes.browser.mode` are all
564
+ * set only when absent so user-customized values survive a re-bind. The
565
+ * `enabled` flag is never flipped off — Browserless binding shouldn't
566
+ * override a user who explicitly disabled the browser tool tree.
567
+ *
568
+ * SSRF policy is intentionally NOT touched here: `browser.ssrfPolicy`
569
+ * (`dangerouslyAllowPrivateNetwork`, `allowedHostnames`) is a user-level
570
+ * security decision (default deny-all is correct for an LLM-driven
571
+ * browser); jishushell would be over-reaching to silently widen it on
572
+ * binding. Users who want the agent to reach a specific host configure
573
+ * the allowlist themselves.
574
+ *
575
+ * No-op when the config file is absent (instance not yet started).
576
+ */
577
+ export function applyBrowserlessConnectionToConfig(configPath, cdpUrl) {
578
+ if (!existsSync(configPath))
579
+ return;
580
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
581
+ const browser = (existing.browser ??= {});
582
+ if (browser.enabled === undefined)
583
+ browser.enabled = true;
584
+ if (!browser.defaultProfile)
585
+ browser.defaultProfile = BROWSERLESS_PROFILE;
586
+ const profiles = (browser.profiles ??= {});
587
+ const prior = profiles[BROWSERLESS_PROFILE] ?? {};
588
+ profiles[BROWSERLESS_PROFILE] = {
589
+ ...prior,
590
+ cdpUrl,
591
+ attachOnly: true,
592
+ color: typeof prior.color === "string" && prior.color ? prior.color : BROWSERLESS_DEFAULT_COLOR,
593
+ };
594
+ const gateway = (existing.gateway ??= {});
595
+ const nodes = (gateway.nodes ??= {});
596
+ const browserPolicy = (nodes.browser ??= {});
597
+ if (browserPolicy.mode === undefined)
598
+ browserPolicy.mode = "off";
599
+ safeWriteJson(configPath, existing);
600
+ }
601
+ /**
602
+ * Counterpart to `applyBrowserlessConnectionToConfig` — invoked when the user
603
+ * unbinds the BROWSER slot in the Connections tab. Removes the
604
+ * jishushell-managed `browserless` profile and clears `defaultProfile` only
605
+ * if it still points at that profile (so user-set defaults pointing at their
606
+ * own profiles survive). Other profiles and `browser.enabled` are left alone.
607
+ *
608
+ * No-op when the config file is absent.
609
+ */
610
+ export function clearBrowserlessConnectionFromConfig(configPath) {
611
+ if (!existsSync(configPath))
612
+ return;
613
+ const existing = JSON.parse(readFileSync(configPath, "utf-8"));
614
+ const browser = existing?.browser;
615
+ if (!browser || typeof browser !== "object")
616
+ return;
617
+ if (browser.profiles && typeof browser.profiles === "object") {
618
+ delete browser.profiles[BROWSERLESS_PROFILE];
619
+ }
620
+ if (browser.defaultProfile === BROWSERLESS_PROFILE) {
621
+ delete browser.defaultProfile;
622
+ }
623
+ safeWriteJson(configPath, existing);
624
+ }
625
+ /**
626
+ * Bump when a panel-side change invalidates the agent's prior reasoning
627
+ * within an existing chat session — e.g., a mount fix that turns prior
628
+ * "I can't read this file" tool failures into stale conclusions. The
629
+ * first onBeforeStart after the bump rotates the instance's session
630
+ * jsonl files (`<file>.jsonl` → `<file>.jsonl.reset.<ts>`), so the next
631
+ * user message lands on a clean context window. Old transcripts are
632
+ * preserved as .reset.* siblings — never deleted, just archived.
633
+ *
634
+ * Concrete history:
635
+ * 2026.5.11.1 — buildVolumes root-mount fix: empty-path FileMount
636
+ * finally binds FILES_ROOT into docker containers. Prior
637
+ * sessions had agent conclude "drive only has metadata,
638
+ * no file content" after ENOENT — that reasoning is
639
+ * poisoned post-fix.
640
+ * 2026.5.11.2 — WeChat target-format rule in TOOLS.md: agent was
641
+ * extrapolating Feishu's `user:` prefix onto WeChat
642
+ * chat_ids that don't carry it, causing WeChat's
643
+ * getuploadurl to return ret:-1. Prior sessions need
644
+ * rotation so the agent re-reads the corrected target
645
+ * rule and stops adding the prefix.
646
+ *
647
+ * Format: YYYY.M.D.N (date + same-day bump counter). Compare as strings;
648
+ * any difference means rotate. Stored per-instance at
649
+ * `<instanceDir>/runtime-contract.txt`
650
+ */
651
+ const RUNTIME_CONTRACT_VERSION = "2026.5.11.2";
652
+ const JISHUSHELL_DRIVE_HINT_BEGIN = "<!-- jishushell-drive: BEGIN auto-generated -->";
653
+ const JISHUSHELL_DRIVE_HINT_END = "<!-- jishushell-drive: END -->";
654
+ const JISHUSHELL_KB_HINT_BEGIN = "<!-- jishushell-kb: BEGIN auto-generated -->";
655
+ const JISHUSHELL_KB_HINT_END = "<!-- jishushell-kb: END -->";
656
+ /**
657
+ * Rotate session jsonl files when the runtime contract version has bumped
658
+ * since this instance last started. Matches OpenClaw's own .reset.<ts>
659
+ * naming convention so its existing UI/cleanup paths still apply.
660
+ *
661
+ * Why this exists: when a panel upgrade fixes a runtime bug (e.g. the
662
+ * 2026-05-11 mount-bind fix), the agent's prior turn-by-turn reasoning
663
+ * inside an existing session is anchored to the broken behaviour. Even
664
+ * after the fix is deployed and the alloc restarted, the LLM keeps
665
+ * citing past tool failures and refusing to retry. Rotating the session
666
+ * jsonl(s) gives the next user message a clean context where the agent
667
+ * sees fresh TOOLS.md + fresh tool outputs.
668
+ *
669
+ * Side effect: the user loses chat scrollback in IM/web. Acceptable
670
+ * because (a) the rotated file is preserved on disk, (b) panel upgrades
671
+ * are infrequent, (c) the alternative — agent stuck in old reasoning —
672
+ * is worse UX.
673
+ */
674
+ function rotateSessionsIfContractChanged(instanceId, openclawHome) {
675
+ try {
676
+ const markerPath = join(framework_instanceDir(instanceId), "runtime-contract.txt");
677
+ let previous = "";
678
+ try {
679
+ previous = readFileSync(markerPath, "utf-8").trim();
680
+ }
681
+ catch (e) {
682
+ if (e?.code !== "ENOENT")
683
+ throw e;
684
+ }
685
+ if (previous === RUNTIME_CONTRACT_VERSION)
686
+ return;
687
+ const sessionsDir = join(openclawHome, ".openclaw", "agents", "main", "sessions");
688
+ if (existsSync(sessionsDir)) {
689
+ const ts = new Date()
690
+ .toISOString()
691
+ .replace(/:/g, "-")
692
+ .replace(/\.\d+Z$/, ".000Z");
693
+ const entries = readdirSync(sessionsDir);
694
+ let rotated = 0;
695
+ for (const name of entries) {
696
+ if (!name.endsWith(".jsonl"))
697
+ continue; // skip already-rotated
698
+ const from = join(sessionsDir, name);
699
+ const to = `${from}.reset.${ts}`;
700
+ try {
701
+ renameSync(from, to);
702
+ rotated++;
703
+ }
704
+ catch (e) {
705
+ console.warn(`[openclaw] session rotate failed for ${from}: ${e?.message ?? e}`);
706
+ }
707
+ }
708
+ if (rotated > 0) {
709
+ console.log(`[openclaw] runtime contract ${previous || "(none)"} → ${RUNTIME_CONTRACT_VERSION}: rotated ${rotated} session(s) under ${sessionsDir}`);
710
+ }
711
+ }
712
+ writeConfigFile(markerPath, RUNTIME_CONTRACT_VERSION + "\n");
713
+ }
714
+ catch (e) {
715
+ console.warn(`[openclaw] rotateSessionsIfContractChanged failed: ${e?.message ?? e}`);
716
+ }
717
+ }
718
+ /**
719
+ * Inject a guarded section into the agent's TOOLS.md telling the LLM that
720
+ * user files live on the local filesystem (host==container bind mount),
721
+ * not on some remote "drive server", and showing the concrete
722
+ * resolve-then-send chain for IM channels (Feishu / WeChat).
723
+ *
724
+ * Why this exists: the LLM defaults to interpreting `drive` as a remote
725
+ * service, then refuses to send NAS files via IM with "I can't access the
726
+ * cloud drive" — even when `drive_list` literally just enumerated them.
727
+ * Verified on pi2 2026-05-11: claw1 saw `文档/宇树G1-D...xlsx` via
728
+ * drive_list, then told the user to "open Feishu cloud space and forward
729
+ * it back" because nothing in TOOLS.md tied drive paths to filesystem
730
+ * paths. This patcher closes that gap by spelling it out.
731
+ *
732
+ * Idempotent: section is bracketed by HTML markers; content between them
733
+ * is rewritten on every call. User edits OUTSIDE the markers are kept.
734
+ *
735
+ * filesRoot is baked in so the example abs path matches the actual install
736
+ * — third-party users on `/home/alice/.jishushell/files/` see their own
737
+ * root, not pi's.
738
+ */
739
+ export function patchToolsMdDriveHint(workspaceDir, filesRoot) {
740
+ try {
741
+ const toolsPath = join(workspaceDir, "TOOLS.md");
742
+ let original = "";
743
+ try {
744
+ original = readFileSync(toolsPath, "utf-8");
745
+ }
746
+ catch (e) {
747
+ if (e?.code !== "ENOENT")
748
+ throw e;
749
+ }
750
+ const section = [
751
+ JISHUSHELL_DRIVE_HINT_BEGIN,
752
+ "",
753
+ "### 📁 用户的 NAS / 文件库",
754
+ "",
755
+ "⚠️ **用户文件操作硬路由 — 必读**",
756
+ "",
757
+ "**单一规则(语言无关)**:用户用任何语言(中文 / English / 日本語 / ...)说「**我的 / 我的 / my / mine / our / the user's / 私の**」+ 任何文件/目录/资料/笔记/文档/代码/data/notes/docs/files → **CRUD 全部走 `drive.*` 工具,禁止用 shell 在 cwd 上操作**。判定按**语义**不按**字面**,本表只是举例。",
758
+ "",
759
+ "动作 ↔ 工具映射表(用户文件场景,中英混排示例):",
760
+ "",
761
+ "| 用户意图(多语言示例) | ✅ 必须用 | ❌ 禁止 |",
762
+ "|---|---|---|",
763
+ "| list / show / 「列一下 / 我有什么 / 看看我的 / what files do I have / show me my docs / list my files」 | `drive_list` | `ls`, `find`, `pwd` |",
764
+ "| read / open / 「打开 / 看看 / 念一下 / 内容是啥 / open my X / read the content of / what's in」 | `drive_read_preview` / `drive_read_full` | `cat`, `head`, `tail` |",
765
+ "| search / find / 「搜 / 找一下 / 哪里提到 / search my docs for / find X in my files / where did I write about」 | `drive_search` | `grep`, `rg` |",
766
+ "| write / save / create / 「写 / 存 / 记一下 / 新建 / save this as / write a note / create a file」 | `drive_write_text` / `drive_write_binary` | `echo >`, `cat <<EOF`, `tee` |",
767
+ "| delete / remove / 「删 / 扔掉 / delete X / remove the file」 | `drive_delete` | `rm` |",
768
+ "| rename / move / 「改名 / 挪到 / 移到 / rename X to Y / move X to」 | `drive_move` | `mv` |",
769
+ "| mkdir / 「建文件夹 / create a folder / make a directory」 | `drive_mkdir` | `mkdir` |",
770
+ "| quota / space / 「配额 / 空间 / how much space / quota / disk usage」 | `drive_quota` | `df`, `du` |",
771
+ "| send / share / 「发给我 / 把 X 发出去 / send me X / share the file with me」 | `drive_resolve_local_path` → IM `send_file` | (拒绝 / refuse) |",
772
+ "",
773
+ "**触发词不完全列表(再次强调:语义优先)**:",
774
+ "- 中文:我的、我那份、我之前的、我刚刚的、用户的、咱们的、文件、文档、资料、笔记、报告、合同、PDF、Excel、附件",
775
+ "- 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)",
776
+ "- 其它语言:私の (ja) / mes (fr) / mein (de) / 我的 (variants) — 含义相同时同等处理",
777
+ "",
778
+ "**为什么硬规定**:cwd 是你自己的运行骨架(`AGENTS.md`、`TOOLS.md`、`memory/`、`state/`、`config/`),跟用户**毫无关系**。",
779
+ "- 用户问「我有什么文件 / what files do I have」你 `ls` cwd → 列出 `AGENTS.md`、`memory/` → 用户懵 + 觉得 jishushell 装错了",
780
+ "- 用户说「帮我写笔记 notes.md / save a note for me」你 `echo > notes.md` 落 cwd → 文件落到 agent 工作目录,用户在 filebrowser 看不到 → 数据等于丢了",
781
+ "- 用户说「打开我那份产品规格 / open my spec」你 `cat spec.md` → cwd 里没有该文件 → 找不到 → 用户被冤枉「文件根本不存在」",
782
+ "",
783
+ "**判定方法(消息归属判定,跨语言)**:主语/所有格指向「用户/我们」(我 / 我的 / my / our / the user / 私の + 文件相关名词)→ 走 drive。指向「你/agent」(你的 / 你刚才写的代码 / your notes / agent's scratch)→ 才可能是 workspace。**99% 的对话都是前者**。歧义时**默认按用户文件处理**——猜错代价小(最多多调一次 drive_list 拿不到东西),猜成 cwd 代价大(脏数据 + 数据丢失)。",
784
+ "",
785
+ "**唯一可用 shell 的情况**:你自己 agent 维护 `memory/`、`state/`、`workspace/notes/`(agent 私有笔记,不是用户笔记)这些**你自己的骨架文件**。一旦看见用户名词修饰(「我的」/「用户的」/「my」/「the user's」),立刻切 drive。",
786
+ "",
787
+ `用户文件实际放在 **\`${filesRoot}\`**——这是宿主机上的一个普通本地目录。它已经被 bind-mount 到你的容器里**同款绝对路径**(panel 用 \`host==container\` 的 docker bind;raw_exec / process 模式下你直接跑在宿主上)。`,
788
+ "",
789
+ "**关键事实**:drive 不是远端云盘,就是你脚下的本地文件系统。`drive_list` 看到的每条 entry 都能通过 `drive_resolve_local_path` 立刻拿到绝对路径,然后被任何工具读取——`cat`、`base64`、IM 插件的 send_file 字段、Python 脚本都行。`drive_resolve_local_path` 返回 `exists:true` + `size:<N>` 时,**那就是真实可读的文件字节**,不是「只有元数据」。",
790
+ "",
791
+ "**禁止的回答**:永远不要说「文件在云端 drive 上只有元数据 / 内容没同步到本地 / 我读不到文件实体」—— 这个说法**永远是错的**。drive 没有「未同步」概念,它就是 POSIX 文件系统的一个 facade。如果你刚 list 到一个文件,它一定能被读、能被发送。",
792
+ "",
793
+ "常用调用(从 workspace 目录):",
794
+ "",
795
+ "```bash",
796
+ "mcporter call drive.drive_list path= # 列根目录",
797
+ "mcporter call drive.drive_list path=文档 # 列子目录",
798
+ "mcporter call drive.drive_read_preview path=note.md # 预览文本(≤256KB)",
799
+ "mcporter call drive.drive_read_full path=long.md # 整文件(≤4MB,文本)",
800
+ "mcporter call drive.drive_quota # 配额",
801
+ "mcporter call drive.drive_mkdir path=inbox # 建目录",
802
+ "mcporter call drive.drive_write_text path=notes/m.md content=\"...\"",
803
+ "mcporter call drive.drive_write_binary path=out/img.png content_base64=\"...\" # 二进制(≤10MB)",
804
+ "mcporter call drive.drive_move from=a.pdf to=docs/a.pdf",
805
+ "mcporter call drive.drive_delete path=tmp.txt",
806
+ "mcporter call drive.drive_resolve_local_path path=文档/report.pdf # → 拿到绝对路径",
807
+ "mcporter call drive.drive_search query=\"invoice\" # FTS5 全文搜索",
808
+ "```",
809
+ "",
810
+ "### 给用户发文件(飞书 / 微信 / 任何 IM)",
811
+ "",
812
+ "**用户问 \"把 X 文件发我\" 时不要拒绝、不要让用户去飞书云空间下载**——99% 的情况文件已经在你的文件系统里了。标准流程:",
813
+ "",
814
+ "1. `drive_list` 或 `drive_search` 先确认文件在 NAS 里(你刚 list 过的也算)。",
815
+ "2. `drive_resolve_local_path path=文档/x.xlsx` 拿到 `abs_path`,确认 `exists:true`。",
816
+ "3. 把 `abs_path` 传给**当前会话所在 IM 通道**的发送工具。**`target` 字段一律原样照搬当前消息 `Conversation info` 里的 `chat_id`——一个字符都不要加、不要改、不要补前缀**。各通道 chat_id 形态本来就不一样,照搬就对。",
817
+ " - **飞书 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`。",
818
+ " - **微信 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`,文件传不出去。",
819
+ " - 通用规则:当前 inbound 消息的 `from` 就是回复 target。打开你刚收到的那条 user message 里 `Conversation info` 的 JSON,把 `chat_id` 整段复制就行。",
820
+ "4. 失败先查 `exists` 字段、文件大小、IM 通道大小上限(飞书典型 30MB、微信 20MB),再决定降级方案。",
821
+ "",
822
+ "**ENOENT / \"no such file or directory\" 处理**:IM 插件返回 ENOENT 但 `drive_resolve_local_path` 刚刚 `exists:true`,**99% 是 panel 刚升级 / mount 刚刷新,但你这个 alloc 用的是旧 spec**。无脑重试一次。还是 ENOENT 才提示用户去 panel 重启实例(stop+start,不是 restart)——但**永远不要**回答 \"文件只是元数据所以读不到\",那是错的。",
823
+ "",
824
+ "要发**新生成**的文件(PDF、图片、报表):先 `drive_write_binary path=agent-data/<instance>/outbox/x.pdf content_base64=...` 落盘,再 resolve → 发送。",
825
+ "",
826
+ "### 用户给你发文件",
827
+ "",
828
+ "目前飞书/微信通道不会自动把附件落盘到 NAS。当用户说\"文件给你了\"但你 `drive_list inbox` 看不到:",
829
+ "- 优先让用户走 panel 的 Filebrowser(`/apps/filebrowser/`)或 WebDAV 把文件上传到 `inbox/`,再告诉你路径。",
830
+ "- 飞书附件流:如果飞书 app 已配 `im:resource` 权限,可以用 `feishu_im_user_fetch_resource` 取 file_key、落到 `inbox/feishu/<date>/`。",
831
+ "",
832
+ "权限:在 panel \"关联 agent\" UI 里给实例授 ro/rw。403 时让用户去 panel 加。",
833
+ "",
834
+ JISHUSHELL_DRIVE_HINT_END,
835
+ "",
836
+ ].join("\n");
837
+ let next;
838
+ const beginIdx = original.indexOf(JISHUSHELL_DRIVE_HINT_BEGIN);
839
+ const endIdx = original.indexOf(JISHUSHELL_DRIVE_HINT_END);
840
+ if (beginIdx >= 0 && endIdx > beginIdx) {
841
+ const tail = endIdx + JISHUSHELL_DRIVE_HINT_END.length;
842
+ const after = original
843
+ .slice(tail)
844
+ .replace(/^\n+/, "\n");
845
+ next = original.slice(0, beginIdx) + section + after;
846
+ }
847
+ else {
848
+ const sep = original && !original.endsWith("\n") ? "\n\n" : "\n";
849
+ next = (original ? original + sep : "") + section;
850
+ }
851
+ if (next === original)
852
+ return;
853
+ writeConfigFile(toolsPath, next);
854
+ console.log(`[openclaw] Patched drive hint into ${toolsPath}`);
855
+ }
856
+ catch (e) {
857
+ console.warn(`[openclaw] Failed to patch TOOLS.md drive hint: ${e.message}`);
858
+ }
859
+ }
860
+ /**
861
+ * Inject a guarded section into TOOLS.md describing the kb_search MCP
862
+ * tool — only when an AnythingLLM-backed knowledge base is wired into
863
+ * this instance. Mirrors patchToolsMdDriveHint's marker model so an
864
+ * uninstall / unbind can cleanly strip the section.
865
+ *
866
+ * `mode === "install"` writes the kb hint between the markers
867
+ * (overwriting any previous content there). `mode === "remove"`
868
+ * deletes the entire bracketed section, leaving the user's
869
+ * surrounding content intact.
870
+ */
871
+ export function patchToolsMdKbHint(workspaceDir, mode) {
872
+ try {
873
+ const toolsPath = join(workspaceDir, "TOOLS.md");
874
+ let original = "";
875
+ try {
876
+ original = readFileSync(toolsPath, "utf-8");
877
+ }
878
+ catch (e) {
879
+ if (e?.code !== "ENOENT")
880
+ throw e;
881
+ if (mode === "remove")
882
+ return; // nothing to strip
883
+ }
884
+ // Strip every existing kb section first — tolerant of legacy variants
885
+ // (e.g. early manual injections that used "END auto-generated -->"
886
+ // instead of the current "END -->" marker). Without this, repeated
887
+ // re-patches would accumulate sections in TOOLS.md.
888
+ const STRIP_RE = /\n*<!-- jishushell-kb: BEGIN[^>]*-->[\s\S]*?<!-- jishushell-kb: END[^>]*-->\n*/g;
889
+ const stripped = original.replace(STRIP_RE, "\n");
890
+ let next;
891
+ if (mode === "remove") {
892
+ if (stripped === original)
893
+ return;
894
+ next = stripped;
895
+ }
896
+ else {
897
+ const section = [
898
+ JISHUSHELL_KB_HINT_BEGIN,
899
+ "",
900
+ "### 📚 知识库(AnythingLLM)",
901
+ "",
902
+ "用户长期投递的文档(手册、PDF、内部笔记、过往会议纪要等)由 **AnythingLLM** 维护索引(本地 LanceDB 向量库 + 内置 Xenova ONNX embedder),通过 `kb.kb_search` 一次调用拿「答案 + 引用来源」。",
903
+ "",
904
+ "**两个工具**:",
905
+ "",
906
+ "- `mcporter call kb.kb_search query=\"<用户原话>\"` — 在已索引文档里检索,返回答案 + 最多 5 条引用源",
907
+ "- `mcporter call kb.kb_ingest path=\"<绝对路径>\"` — 把 drive 里的文件加入知识库并 embed(用户说「加进知识库 / index this / 学习这份」时调)",
908
+ "",
909
+ "**ingest 标准链**(drive 里的文件 → 知识库):",
910
+ "1. `mcporter call drive.drive_resolve_local_path path=inbox/contract.pdf` → 拿 `abs_path`",
911
+ "2. `mcporter call kb.kb_ingest path=<abs_path>` → AnythingLLM 自动 embed",
912
+ "3. 几秒后用户问相关问题,`kb_search` 命中",
913
+ "",
914
+ "**search 什么时候调**:用户问的东西像在已上传文档里能找到——「那个 X 的手册里怎么说」、「我们之前关于 Y 的讨论」、「产品规格」、「合同条款」、「what does the doc say about X」等。",
915
+ "",
916
+ "**什么时候不要调**:寒暄、纯代码生成、数学计算、实时信息(天气/股票/新闻)、**操作 NAS 文件**(那是 `drive.*`,不是 kb)、纯创作类。",
917
+ "",
918
+ "**与 drive 的分工**:",
919
+ "- `drive.*` = 文件系统 facade(列目录、读字节、发文件)—— 要的是**文件本体**用 drive",
920
+ "- `kb.kb_search` / `kb.kb_ingest` = 语义检索 + RAG 入库 —— 要的是**答案/知识**用 kb",
921
+ "",
922
+ "两者数据**不共享**:drive 看到 `manual.pdf` ≠ kb 一定能搜到它。要让 kb 能搜到 → 先 `kb_ingest`。",
923
+ "",
924
+ "**搜不到时的标准回复**:`kb_search` 回答里说「无相关文档」或 sources 为空 → 先确认 drive 里有没有相关文件,如果有,主动建议「要我把它加入知识库吗」(用户同意就 `drive_resolve_local_path` + `kb_ingest`);drive 也没有,告诉用户「我在你的知识库里没找到相关内容」,然后**不要继续幻想答案**。",
925
+ "",
926
+ JISHUSHELL_KB_HINT_END,
927
+ "",
928
+ ].join("\n");
929
+ const sep = stripped && !stripped.endsWith("\n") ? "\n\n" : "\n";
930
+ next = (stripped ? stripped + sep : "") + section;
931
+ }
932
+ if (next === original)
933
+ return;
934
+ writeConfigFile(toolsPath, next);
935
+ console.log(`[openclaw] ${mode === "remove" ? "Removed" : "Patched"} kb hint in ${toolsPath}`);
936
+ }
937
+ catch (e) {
938
+ console.warn(`[openclaw] Failed to ${mode} TOOLS.md kb hint: ${e.message}`);
939
+ }
940
+ }
293
941
  /**
294
942
  * Pre-seed the per-instance npm global prefix with a symlink to the image's
295
943
  * baked openclaw package so OpenClaw's in-gateway "Update now" handler can
@@ -393,7 +1041,7 @@ const PINNED_IMAGE_TAG_RE = /:[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$/;
393
1041
  /**
394
1042
  * Pull DOCKER_BASE_IMAGE from mirrors if not already cached locally.
395
1043
  */
396
- async function ensureDockerBaseImage(invocation, task) {
1044
+ async function _ensureDockerBaseImage(invocation, task) {
397
1045
  try {
398
1046
  execFileSync(invocation.cmd, [...invocation.argsPrefix, "image", "inspect", DOCKER_BASE_IMAGE], {
399
1047
  timeout: 5000,
@@ -513,7 +1161,7 @@ async function pullOrBuildOpenclawImageWithTask(task, tag) {
513
1161
  const invocation = resolveDockerInvocation();
514
1162
  // Always attempt pull — when the image is already local and in sync
515
1163
  // with upstream, docker returns within seconds after a digest check.
516
- // The "skip if image present" early exit was making "重新安装" feel
1164
+ // The "skip if image present" early exit was making "reinstall" feel
517
1165
  // like a no-op; explicit re-pull matches user intent better. On pull
518
1166
  // failure we still fall back to local build below.
519
1167
  emitTask(task, { type: "progress", message: `正在拉取镜像: ${targetTag} ...`, progress: 10 });
@@ -683,6 +1331,11 @@ class OpenClawAdapter {
683
1331
  patchDockerBridgeGatewayBind(configPath);
684
1332
  patchJsproxyBaseUrl(configPath);
685
1333
  }
1334
+ // Driver-agnostic: enable the OpenAI-compatible endpoints on every
1335
+ // start so the `llm-agent` capability advertised by openclaw-*.yaml
1336
+ // works for both fresh installs and instances created before this
1337
+ // patcher shipped. Idempotent — bails out fast if already enabled.
1338
+ patchOpenAIEndpointsEnabled(configPath);
686
1339
  // 4. npm update-seed — use local resolver
687
1340
  try {
688
1341
  const home = openclawAdapter.resolveAgentHome(instanceId);
@@ -692,6 +1345,358 @@ class OpenClawAdapter {
692
1345
  catch {
693
1346
  /* best effort */
694
1347
  }
1348
+ // 4b. Build the workspace symlink layout from this instance's
1349
+ // fileMounts (M1 W2). For docker mode, the corresponding
1350
+ // volume bindings are added in buildNomadTask below; for
1351
+ // raw_exec / process modes, the symlinks are sufficient
1352
+ // (no container layer between agent and host fs).
1353
+ try {
1354
+ const home = openclawAdapter.resolveAgentHome(instanceId);
1355
+ const im = await lazyIm();
1356
+ const runtime = im.getInstanceRuntime(instanceId);
1357
+ const mounts = readFileMounts(runtime);
1358
+ if (home) {
1359
+ const { rebuildWorkspace } = await import("../../workspace-builder.js");
1360
+ rebuildWorkspace({
1361
+ openclawHome: home,
1362
+ filesRoot: FILES_ROOT,
1363
+ mounts,
1364
+ instanceId,
1365
+ });
1366
+ }
1367
+ }
1368
+ catch (e) {
1369
+ // Surface migration-required clearly; otherwise fall back to a
1370
+ // warning so a misconfigured mount cannot prevent instance start.
1371
+ if (e?.reason === "needs-migration") {
1372
+ throw new Error(`instance ${instanceId} workspace contains pre-W2 user data; run legacy migration first (${e.message})`);
1373
+ }
1374
+ console.warn(`[openclaw] workspace rebuild skipped: ${e?.message ?? e}`);
1375
+ }
1376
+ // 4b-bis. Patch TOOLS.md with the drive-shim hint so the agent
1377
+ // understands user files are local (host==container bind) and
1378
+ // knows the resolve→send chain for IM channels. Without this,
1379
+ // the LLM defaults to "drive = remote cloud service" and
1380
+ // refuses to send NAS files via Feishu/WeChat. Runs after the
1381
+ // workspace rebuild because that step creates the workspace
1382
+ // tree if missing.
1383
+ try {
1384
+ const home = openclawAdapter.resolveAgentHome(instanceId);
1385
+ if (home) {
1386
+ patchToolsMdDriveHint(join(home, ".openclaw", "workspace"), FILES_ROOT);
1387
+ }
1388
+ }
1389
+ catch (e) {
1390
+ console.warn(`[openclaw] TOOLS.md drive hint skipped: ${e?.message ?? e}`);
1391
+ }
1392
+ // 4b-ter. Rotate stale session jsonl(s) when the runtime contract
1393
+ // bumps. This is the auto-recovery path for panel upgrades
1394
+ // that fix runtime bugs the agent has already "concluded
1395
+ // around" inside an existing session — without rotation the
1396
+ // LLM keeps citing past failures and refusing to retry even
1397
+ // after the underlying bug is fixed. Idempotent: after the
1398
+ // first onBeforeStart post-upgrade writes the new marker,
1399
+ // subsequent starts are no-ops.
1400
+ try {
1401
+ const home = openclawAdapter.resolveAgentHome(instanceId);
1402
+ if (home)
1403
+ rotateSessionsIfContractChanged(instanceId, home);
1404
+ }
1405
+ catch (e) {
1406
+ console.warn(`[openclaw] session rotation skipped: ${e?.message ?? e}`);
1407
+ }
1408
+ // 4c. Install the drive MCP shim so the agent can call panel
1409
+ // file/organize APIs from chat (M1 W1.6). Idempotent — we
1410
+ // overwrite the shim file every start to pick up fixes, and
1411
+ // mergeMcporterServers marks the entry with __source so user-
1412
+ // managed mcporter entries are preserved untouched.
1413
+ try {
1414
+ const home = openclawAdapter.resolveAgentHome(instanceId);
1415
+ if (home) {
1416
+ const { substituteDriveShimPlaceholders } = await import("../mcp-shims/drive-shim.js");
1417
+ const { mergeMcporterServers } = await import("./openclaw-mcporter.js");
1418
+ const { getInternalMcpToken } = await import("../../../config.js");
1419
+ // Pick the panel URL based on how THIS instance will actually run.
1420
+ // For a containerized instance (raw_exec/docker via Nomad with a
1421
+ // docker image), `host.docker.internal:8090` resolves through the
1422
+ // bridge gateway. For a host-process / binary spec under Nomad
1423
+ // raw_exec, the task gets its own network namespace where
1424
+ // 127.0.0.1 only reaches the task itself — must use the host's
1425
+ // LAN IPv4 so the shim's fetch crosses back into the host netns.
1426
+ // Detected via the instance's resolved runtime: container tasks
1427
+ // carry `runtime.image`, binary tasks carry only `runtime.command`.
1428
+ let drivePanelUrl = "http://host.docker.internal:8090";
1429
+ try {
1430
+ const im2 = await lazyIm();
1431
+ const rt = im2.getInstanceRuntime(instanceId);
1432
+ if (!rt?.image) {
1433
+ const { getPanelLanHost, getPanelPort } = await import("../../../config.js");
1434
+ drivePanelUrl = `http://${getPanelLanHost()}:${getPanelPort()}`;
1435
+ }
1436
+ }
1437
+ catch {
1438
+ // Best effort — fall through to host.docker.internal default
1439
+ }
1440
+ const shimDir = join(home, "__mcp_shims__", "drive");
1441
+ ensureDirContainer(shimDir);
1442
+ const shimPath = join(shimDir, "drive-shim.mjs");
1443
+ // Bake panelUrl/token/instanceId into the shim source so it works
1444
+ // even when OpenClaw scrubs env on MCP subprocess spawn (verified
1445
+ // 2026-05-11 on pi2: env scrub made the shim default to the
1446
+ // unreachable host.docker.internal and surface as "fetch failed").
1447
+ const internalToken = getInternalMcpToken();
1448
+ const shimSource = substituteDriveShimPlaceholders({
1449
+ panelUrl: drivePanelUrl,
1450
+ token: internalToken,
1451
+ instanceId,
1452
+ });
1453
+ writeFileSync(shimPath, shimSource, { mode: 0o755 });
1454
+ mergeMcporterServers(instanceId, {
1455
+ drive: {
1456
+ command: "node",
1457
+ args: [shimPath],
1458
+ env: {
1459
+ // Env still set as a belt-and-suspenders. With baked-in
1460
+ // values in the shim source itself, these become a fallback
1461
+ // for dev/manual testing — production never depends on them.
1462
+ JISHUSHELL_INTERNAL_TOKEN: internalToken,
1463
+ JISHUSHELL_INSTANCE_ID: instanceId,
1464
+ JISHUSHELL_PANEL_URL: drivePanelUrl,
1465
+ },
1466
+ __source: {
1467
+ kind: "connection",
1468
+ slot: "drive",
1469
+ consumerInstanceId: instanceId,
1470
+ },
1471
+ },
1472
+ });
1473
+ }
1474
+ }
1475
+ catch (e) {
1476
+ console.warn(`[openclaw] drive shim install skipped: ${e?.message ?? e}`);
1477
+ }
1478
+ // 4c-quater. Auto-wire AnythingLLM kb shim. The Connections-tab
1479
+ // knowledge slot (declared as `requires: knowledge` on the
1480
+ // OpenClaw spec, persisted under `instance.connections.KNOWLEDGE_BASE_URL`)
1481
+ // is honored here, so unbinding in the UI actually takes effect.
1482
+ // Three states (matching connection-resolver.ts):
1483
+ //
1484
+ // - `null` → user explicitly disconnected → DO NOT
1485
+ // inject (and strip any prior shim).
1486
+ // - explicit binding → inject only if it points at the
1487
+ // anythingllm-container provider; any
1488
+ // other choice means user wants a
1489
+ // different kb provider that we don't
1490
+ // yet ship a shim for.
1491
+ // - undefined → no opinion → fall back to the
1492
+ // historical "auto-on when AnythingLLM
1493
+ // credentials.json exists" UX.
1494
+ //
1495
+ // Secrets handling (defense-in-depth):
1496
+ // - shim source (mode 0o644) carries baseUrl + workspace only;
1497
+ // the API key lives in a sibling `secret.json` (0o600).
1498
+ // - mcporter.json (0o644) env carries only non-secret hints
1499
+ // for hand-running. Production shim reads the secret file.
1500
+ try {
1501
+ const home = openclawAdapter.resolveAgentHome(instanceId);
1502
+ if (home) {
1503
+ const instMeta = getInstance(instanceId);
1504
+ const kbBinding = instMeta?.connections?.KNOWLEDGE_BASE_URL;
1505
+ let bindingAllowsInject = true;
1506
+ if (kbBinding === null) {
1507
+ bindingAllowsInject = false;
1508
+ }
1509
+ else if (kbBinding && typeof kbBinding === "object") {
1510
+ if (kbBinding.kind === "single") {
1511
+ bindingAllowsInject = kbBinding.providerId === "anythingllm-container";
1512
+ }
1513
+ else if (kbBinding.kind === "many") {
1514
+ const providers = Array.isArray(kbBinding.providers) ? kbBinding.providers : [];
1515
+ bindingAllowsInject = providers.some((p) => p?.providerId === "anythingllm-container");
1516
+ }
1517
+ }
1518
+ const credPath = join(JISHUSHELL_HOME, "apps", "anythingllm-container", "credentials.json");
1519
+ let kbCreds = null;
1520
+ if (bindingAllowsInject && existsSync(credPath)) {
1521
+ try {
1522
+ kbCreds = JSON.parse(readFileSync(credPath, "utf-8"));
1523
+ }
1524
+ catch (e) {
1525
+ console.warn(`[openclaw] kb: invalid credentials.json: ${e?.message ?? e}`);
1526
+ }
1527
+ }
1528
+ const wsDir = join(home, ".openclaw", "workspace");
1529
+ const shimDir = join(home, "__mcp_shims__", "anythingllm");
1530
+ const shimPath = join(shimDir, "anythingllm-shim.js");
1531
+ const secretPath = join(shimDir, "secret.json");
1532
+ const { mergeMcporterServers, removeMcporterServers } = await import("./openclaw-mcporter.js");
1533
+ if (kbCreds?.apiKey && kbCreds?.baseUrl) {
1534
+ const { substituteAnythingllmShimPlaceholders } = await import("../mcp-shims/anythingllm-shim.js");
1535
+ ensureDirContainer(shimDir);
1536
+ const shimSource = substituteAnythingllmShimPlaceholders({
1537
+ baseUrl: kbCreds.baseUrl,
1538
+ workspace: kbCreds.workspace || "default",
1539
+ });
1540
+ writeFileSync(shimPath, shimSource, { mode: 0o644 });
1541
+ // chmod after write to dodge umask; secret.json must be 0o600.
1542
+ writeFileSync(secretPath, JSON.stringify({ apiKey: kbCreds.apiKey }), { mode: 0o600 });
1543
+ try {
1544
+ chmodSync(secretPath, 0o600);
1545
+ }
1546
+ catch { /* best effort */ }
1547
+ mergeMcporterServers(instanceId, {
1548
+ kb: {
1549
+ command: "node",
1550
+ args: [shimPath],
1551
+ env: {
1552
+ // Belt-and-suspenders fallback for hand-running. Baked
1553
+ // values in the shim source are the production source
1554
+ // of truth for baseUrl + workspace; the API key is
1555
+ // intentionally NOT placed here — it lives in
1556
+ // `secret.json` (0o600) next to the shim so this 0o644
1557
+ // file stays free of secrets.
1558
+ ANYTHINGLLM_BASE_URL: kbCreds.baseUrl,
1559
+ ANYTHINGLLM_WORKSPACE: kbCreds.workspace || "default",
1560
+ },
1561
+ __source: {
1562
+ kind: "connection",
1563
+ slot: "knowledge",
1564
+ consumerInstanceId: instanceId,
1565
+ },
1566
+ },
1567
+ });
1568
+ patchToolsMdKbHint(wsDir, "install");
1569
+ }
1570
+ else {
1571
+ // Clean removal path (covers "AnythingLLM uninstalled / not
1572
+ // yet ready" AND "user explicitly unbound knowledge in
1573
+ // Connections tab" AND "user bound a different kb provider").
1574
+ removeMcporterServers(instanceId, {
1575
+ source: { kind: "connection", slot: "knowledge", consumerInstanceId: instanceId },
1576
+ });
1577
+ patchToolsMdKbHint(wsDir, "remove");
1578
+ try {
1579
+ if (existsSync(shimPath)) {
1580
+ writeFileSync(shimPath, "// removed: AnythingLLM not installed or knowledge unbound\n", { mode: 0o644 });
1581
+ }
1582
+ }
1583
+ catch { /* best effort */ }
1584
+ try {
1585
+ if (existsSync(secretPath))
1586
+ unlinkSync(secretPath);
1587
+ }
1588
+ catch { /* best effort */ }
1589
+ }
1590
+ }
1591
+ }
1592
+ catch (e) {
1593
+ console.warn(`[openclaw] kb shim wiring skipped: ${e?.message ?? e}`);
1594
+ }
1595
+ // 4c-bis. Self-heal MCPORTER_CONFIG env on existing instances. Without
1596
+ // this, mcporter can't find its config when invoked from the
1597
+ // gateway's CWD (openclaw-home/) or from the workspace symlink
1598
+ // (which points at user files, also no config/), so every drive
1599
+ // tool call fails with "Unknown MCP server 'drive'" and the agent
1600
+ // degrades into reporting a generic "network error". New instances
1601
+ // get this env via the binary/container runtime template; this
1602
+ // block back-fills it for instances created before that template
1603
+ // update so users don't have to recreate them.
1604
+ try {
1605
+ const im2 = await lazyIm();
1606
+ const rt = im2.getInstanceRuntime(instanceId);
1607
+ const home = openclawAdapter.resolveAgentHome(instanceId);
1608
+ if (home && rt && (!rt.env || !rt.env.MCPORTER_CONFIG)) {
1609
+ const desired = `${home}/.openclaw/workspace/config/mcporter.json`;
1610
+ const nextEnv = { ...(rt.env || {}), MCPORTER_CONFIG: desired };
1611
+ im2.updateInstanceMeta(instanceId, { runtime: { ...rt, env: nextEnv } });
1612
+ console.log(`[openclaw] self-healed MCPORTER_CONFIG env for ${instanceId}`);
1613
+ }
1614
+ }
1615
+ catch (e) {
1616
+ console.warn(`[openclaw] MCPORTER_CONFIG self-heal failed: ${e?.message ?? e}`);
1617
+ }
1618
+ // 4d. Self-heal mcporter bin: chmod cli.js + replace the npm-installed
1619
+ // symlink at .npm-global/bin/mcporter with a wrapper that pins
1620
+ // `--config <abs path>`. The wrapper is required because:
1621
+ // (a) npm install on Pi/ARM64 sometimes leaves cli.js as 0644
1622
+ // instead of 0755 (despite a valid shebang). Without +x,
1623
+ // spawning the bin returns "Permission denied".
1624
+ // (b) The OpenClaw bash tool scrubs env when spawning agent tool
1625
+ // subprocesses, so MCPORTER_CONFIG env doesn't reach mcporter,
1626
+ // and mcporter falls back to CWD-relative `config/mcporter.json`.
1627
+ // The agent's CWD is openclaw-home/ (no config/) or the
1628
+ // workspace symlink (also no config/) → "Unknown MCP server
1629
+ // 'drive'" → user sees "drive not configured" / "network
1630
+ // error" in chat.
1631
+ // The wrapper hardcodes both the cli.js path and the config path,
1632
+ // so it works regardless of CWD or env state.
1633
+ // Marker in wrapper body (`# jishushell mcporter wrapper`) lets us
1634
+ // detect when it's already installed and skip the rewrite.
1635
+ try {
1636
+ const home = openclawAdapter.resolveAgentHome(instanceId);
1637
+ if (home) {
1638
+ const mcporterCli = join(home, ".npm-global", "lib", "node_modules", "mcporter", "dist", "cli.js");
1639
+ const mcporterBin = join(home, ".npm-global", "bin", "mcporter");
1640
+ const mcporterConfig = join(home, ".openclaw", "workspace", "config", "mcporter.json");
1641
+ if (existsSync(mcporterCli)) {
1642
+ const st = statSync(mcporterCli);
1643
+ if (!(st.mode & 0o111)) {
1644
+ chmodSync(mcporterCli, 0o755);
1645
+ console.log(`[openclaw] +x ${mcporterCli} (mcporter cli.js self-heal)`);
1646
+ }
1647
+ }
1648
+ // Wrapper install: only proceed when cli.js exists; otherwise
1649
+ // mcporter isn't installed and there's nothing to wrap.
1650
+ if (existsSync(mcporterCli)) {
1651
+ const wrapperMarker = "# jishushell mcporter wrapper";
1652
+ let needsInstall = true;
1653
+ try {
1654
+ if (existsSync(mcporterBin)) {
1655
+ const lst = lstatSync(mcporterBin);
1656
+ if (lst.isFile() && !lst.isSymbolicLink()) {
1657
+ const first200 = readFileSync(mcporterBin, "utf8").slice(0, 200);
1658
+ if (first200.includes(wrapperMarker))
1659
+ needsInstall = false;
1660
+ }
1661
+ }
1662
+ }
1663
+ catch { /* fall through to install */ }
1664
+ if (needsInstall) {
1665
+ const wrapperSrc = `#!/bin/bash\n` +
1666
+ `${wrapperMarker} — pins --config so OpenClaw bash-tool env\n` +
1667
+ `# scrubbing or unexpected CWD cannot detach mcporter from the\n` +
1668
+ `# drive MCP server. Auto-installed by adapter onBeforeStart\n` +
1669
+ `# (src/services/runtime/adapters/openclaw.ts).\n` +
1670
+ `exec node ${JSON.stringify(mcporterCli)} --config ${JSON.stringify(mcporterConfig)} "$@"\n`;
1671
+ // Remove first to handle symlink → regular file transition cleanly.
1672
+ try {
1673
+ unlinkSync(mcporterBin);
1674
+ }
1675
+ catch { /* may not exist */ }
1676
+ writeFileSync(mcporterBin, wrapperSrc, { mode: 0o755 });
1677
+ console.log(`[openclaw] installed mcporter wrapper at ${mcporterBin}`);
1678
+ }
1679
+ // UNCONDITIONAL chmod regardless of whether we just wrote or
1680
+ // detected an existing wrapper. writeFileSync's mode option is
1681
+ // ignored when the file already exists, and a prior run that
1682
+ // hit an umask issue may have left it 0644. Always force 0755
1683
+ // so the agent can exec the wrapper.
1684
+ try {
1685
+ if (existsSync(mcporterBin)) {
1686
+ const wst = statSync(mcporterBin);
1687
+ if (!(wst.mode & 0o111)) {
1688
+ chmodSync(mcporterBin, 0o755);
1689
+ console.log(`[openclaw] +x ${mcporterBin} (wrapper chmod self-heal)`);
1690
+ }
1691
+ }
1692
+ }
1693
+ catch { /* best effort */ }
1694
+ }
1695
+ }
1696
+ }
1697
+ catch (e) {
1698
+ console.warn(`[openclaw] mcporter self-heal failed: ${e?.message ?? e}`);
1699
+ }
695
1700
  // 5. Docker image validation + background pull fallback
696
1701
  if (getNomadDriver() === "docker") {
697
1702
  const image = getOpenclawDockerImage();
@@ -891,6 +1896,21 @@ class OpenClawAdapter {
891
1896
  runtime = { ...baseRuntime, ...compiled };
892
1897
  }
893
1898
  }
1899
+ // W2: every new instance gets a default rw mount on its own
1900
+ // agent-data/{id} subtree (alias _out). Cloned instances inherit
1901
+ // their source's mounts but have agent-data path rewritten to the
1902
+ // new instance id; we keep this simple here and just plant the
1903
+ // default — clone-from semantics for additional mounts can be
1904
+ // tightened in PR-7+ when migration arrives.
1905
+ if (!runtime.fileMounts && !runtime.file_mounts) {
1906
+ runtime.fileMounts = defaultMountsForNewInstance(instanceId);
1907
+ }
1908
+ try {
1909
+ ensureMountTargets(FILES_ROOT, readFileMounts(runtime));
1910
+ }
1911
+ catch (e) {
1912
+ console.warn(`[openclaw] could not pre-create mount targets for ${instanceId}: ${e?.message ?? e}`);
1913
+ }
894
1914
  const allocatedPort = extractGatewayPort(runtime);
895
1915
  try {
896
1916
  const meta = {
@@ -1173,7 +2193,7 @@ class OpenClawAdapter {
1173
2193
  throw new Error(`Invalid runtime user: ${rawRuntime.user}`);
1174
2194
  }
1175
2195
  const image = rawRuntime.image || getOpenclawDockerImage();
1176
- const command = String(rawRuntime.command || DEFAULT_COMMAND);
2196
+ const _command = String(rawRuntime.command || DEFAULT_COMMAND);
1177
2197
  const args = Array.isArray(rawRuntime.args)
1178
2198
  ? rawRuntime.args.map(String)
1179
2199
  : [...DEFAULT_ARGS];
@@ -1220,6 +2240,12 @@ class OpenClawAdapter {
1220
2240
  const safeJobId = `${this.nomadJobPrefix}${instanceId}`;
1221
2241
  assertSafeTemplateId(safeJobId);
1222
2242
  const normalizedResources = normalizeDockerResources(instanceId, rawResources);
2243
+ // Same rationale as hermes.ts:nomadHasExternalHostNetwork — without
2244
+ // HostNetwork, Nomad's docker driver publishes the gateway port to
2245
+ // 127.0.0.1, breaking cross-container consumers (e.g. OpenWebUI
2246
+ // binding openclaw via the llm-agent capability). Bring the legacy
2247
+ // openclaw job in line with the unified app-spec path.
2248
+ const hostNetwork = nomadHasExternalHostNetwork() ? "external" : undefined;
1223
2249
  return {
1224
2250
  Name: "gateway",
1225
2251
  Driver: "docker",
@@ -1227,9 +2253,17 @@ class OpenClawAdapter {
1227
2253
  Config: {
1228
2254
  image,
1229
2255
  force_pull: false,
2256
+ // Match nomad-manager.ts:buildAppTask — default 5-minute pull
2257
+ // timeout is too short for Pi-class networks pulling a 1+ GiB
2258
+ // openclaw runtime image; bump to 15 minutes.
2259
+ image_pull_timeout: "15m",
1230
2260
  args,
1231
2261
  work_dir: openclawHome,
1232
- volumes: [`${openclawHome}:${openclawHome}:rw`],
2262
+ volumes: buildVolumes(openclawHome, im.getInstanceRuntime(instanceId)),
2263
+ // Tell the docker driver to publish the labeled "gateway" port so
2264
+ // it routes via the host_network IP rather than the 127.0.0.1
2265
+ // default.
2266
+ ports: ["gateway"],
1233
2267
  extra_hosts: ["host.docker.internal:host-gateway"],
1234
2268
  cap_drop: ["ALL"],
1235
2269
  security_opt: ["no-new-privileges"],
@@ -1244,7 +2278,18 @@ class OpenClawAdapter {
1244
2278
  Env: containerEnv,
1245
2279
  Resources: {
1246
2280
  ...normalizedResources,
1247
- Networks: [{ ReservedPorts: [{ Label: "gateway", Value: gatewayPort }] }],
2281
+ Networks: [
2282
+ {
2283
+ ReservedPorts: [
2284
+ {
2285
+ Label: "gateway",
2286
+ Value: gatewayPort,
2287
+ To: gatewayPort,
2288
+ ...(hostNetwork ? { HostNetwork: hostNetwork } : {}),
2289
+ },
2290
+ ],
2291
+ },
2292
+ ],
1248
2293
  },
1249
2294
  LogConfig: { MaxFiles: 3, MaxFileSizeMB: 10 },
1250
2295
  Templates: [
@@ -1378,6 +2423,103 @@ class OpenClawAdapter {
1378
2423
  saveNativeConfig(instanceId, config) {
1379
2424
  return saveNativeConfigImpl(instanceId, config);
1380
2425
  }
2426
+ /**
2427
+ * Connection-apply hook (§7 of app-interconnect-design): translate
2428
+ * resolved `inject_as` env vars into OpenClaw-native plugin config and
2429
+ * persist them into `openclaw.json`. Without this, the runtime env
2430
+ * injected by `nomad-manager.injectConnectionsRuntimeEnv` (PR 8) sits
2431
+ * in the container unused — the OpenClaw agent reads tool config from
2432
+ * `openclaw.json`, not from environment variables.
2433
+ *
2434
+ * Currently wired:
2435
+ * SEARCH_API_BASE_URL → plugins.entries.searxng.config.webSearch.baseUrl
2436
+ * SEARCH_API_BASE_URL → tools.web.search.provider = "searxng"
2437
+ *
2438
+ * The provider selector at `tools.web.search.provider` is required: without
2439
+ * it the `web_search` tool defaults to Brave and fails with
2440
+ * `missing_brave_api_key` even when the searxng plugin is fully configured.
2441
+ *
2442
+ * Browser / LLM / MCP wiring lands in PR 9b — they need their own
2443
+ * config-shape mapping (browser → tools.browser, llm → models.providers,
2444
+ * mcp already wired via openclaw-mcporter).
2445
+ *
2446
+ * The write goes through `saveNativeConfig` which deep-merges with the
2447
+ * existing on-disk config, so user-managed plugin entries (e.g.
2448
+ * openclaw-lark) are preserved. Plugin auto-enable then promotes the
2449
+ * searxng entry into `plugins.allow` automatically on next start
2450
+ * because we set `enabled:true` and provide config (the openclaw
2451
+ * runtime treats the presence of `config.webSearch.baseUrl` as a
2452
+ * "configured" signal — see `plugin-auto-enable` in the openclaw
2453
+ * dist bundle).
2454
+ */
2455
+ async applyConnectionEnv(instanceId, env) {
2456
+ const configPath = openclawConfigPath(instanceId);
2457
+ const searchUrl = env.SEARCH_API_BASE_URL;
2458
+ if (typeof searchUrl === "string") {
2459
+ if (searchUrl === "") {
2460
+ // Empty value — connection-transactor's UNPERSIST_HOOKS uses this as
2461
+ // the "unbind" signal. Clear the searxng plugin config so the next
2462
+ // start doesn't keep routing web_search through a now-disconnected
2463
+ // provider.
2464
+ try {
2465
+ clearSearxngConnectionFromConfig(configPath);
2466
+ }
2467
+ catch (e) {
2468
+ console.warn(`[openclaw] applyConnectionEnv search unbind failed for ${instanceId}: ${e.message}`);
2469
+ }
2470
+ }
2471
+ else {
2472
+ // SEARCH_API_BASE_URL points at "<base>/search" (the SearXNG search
2473
+ // endpoint). The plugin's webSearch.baseUrl wants the bare origin —
2474
+ // strip the trailing "/search" path segment if present.
2475
+ // baseUrl stays at the registry-resolved host:port snapshot from
2476
+ // when the user PUT /connections; the framework re-runs this hook
2477
+ // on every instance start (PR 9 phaseRefreshConnections), so host
2478
+ // IP changes propagate automatically on next agent restart.
2479
+ let baseUrl = searchUrl;
2480
+ try {
2481
+ const u = new URL(searchUrl);
2482
+ if (u.pathname === "/search" || u.pathname === "/search/") {
2483
+ u.pathname = "";
2484
+ baseUrl = u.toString().replace(/\/$/, "");
2485
+ }
2486
+ try {
2487
+ applySearxngConnectionToConfig(configPath, baseUrl);
2488
+ }
2489
+ catch (e) {
2490
+ console.warn(`[openclaw] applyConnectionEnv search merge failed for ${instanceId}: ${e.message}`);
2491
+ }
2492
+ }
2493
+ catch {
2494
+ // not a URL — skip silently; the openclaw plugin would break
2495
+ // with a non-URL baseUrl, and start should still proceed.
2496
+ }
2497
+ }
2498
+ }
2499
+ const cdpUrl = env.BROWSER_CDP_URL;
2500
+ if (typeof cdpUrl === "string") {
2501
+ if (cdpUrl === "") {
2502
+ try {
2503
+ clearBrowserlessConnectionFromConfig(configPath);
2504
+ }
2505
+ catch (e) {
2506
+ console.warn(`[openclaw] applyConnectionEnv browser unbind failed for ${instanceId}: ${e.message}`);
2507
+ }
2508
+ }
2509
+ else if (/^wss?:\/\//.test(cdpUrl)) {
2510
+ try {
2511
+ applyBrowserlessConnectionToConfig(configPath, cdpUrl);
2512
+ }
2513
+ catch (e) {
2514
+ console.warn(`[openclaw] applyConnectionEnv browser merge failed for ${instanceId}: ${e.message}`);
2515
+ }
2516
+ }
2517
+ // Non-ws scheme: skip silently. The connection-apply browser hook
2518
+ // already builds ws:// from the capability protocol; an http:// here
2519
+ // would mean a misconfigured provider — better to no-op than to
2520
+ // write a URL OpenClaw can't dial.
2521
+ }
2522
+ }
1381
2523
  // ── Path resolvers (physically migrated) ───────────────────────────
1382
2524
  resolveBin() {
1383
2525
  return resolveOpenclawBin();
@@ -1924,9 +3066,27 @@ function getStockExtensionsDir() {
1924
3066
  function isChannelPluginInstalled(instanceId, channelId) {
1925
3067
  const extDirName = CHANNEL_EXT_DIR_ALIAS[channelId] || channelId;
1926
3068
  const stockExtDir = getStockExtensionsDir();
1927
- return (existsSync(join(getChannelExtensionsDir(instanceId), extDirName)) ||
1928
- existsSync(join(stockExtDir, extDirName)) ||
1929
- (extDirName !== channelId && existsSync(join(stockExtDir, channelId))));
3069
+ if (existsSync(join(getChannelExtensionsDir(instanceId), extDirName)))
3070
+ return true;
3071
+ if (existsSync(join(stockExtDir, extDirName)))
3072
+ return true;
3073
+ if (extDirName !== channelId && existsSync(join(stockExtDir, channelId)))
3074
+ return true;
3075
+ // OpenClaw's npm-backed plugin store lives at
3076
+ // `<home>/.openclaw/npm/node_modules/<pkg>`. The CLI refuses to reinstall
3077
+ // when that path is present ("plugin already exists ... delete it first"),
3078
+ // even if the per-instance extensions/<name> dir is missing (e.g. the
3079
+ // first install was interrupted, or the dir was manually cleaned). Treat
3080
+ // the npm path as authoritative so re-saves stay idempotent.
3081
+ const pkg = CHANNEL_PLUGIN_MAP[channelId];
3082
+ if (pkg) {
3083
+ const home = getInstance(instanceId)?.openclaw_home ||
3084
+ defaultOpenclawHome(instanceId);
3085
+ const npmPath = join(home, OPENCLAW_STATE_DIRNAME, "npm", "node_modules", ...pkg.split("/"));
3086
+ if (existsSync(npmPath))
3087
+ return true;
3088
+ }
3089
+ return false;
1930
3090
  }
1931
3091
  /**
1932
3092
  * Install a single channel plugin. Docker mode → `docker exec` inside the