@humain/terminal 0.0.2 → 0.0.3-beta.0

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 (680) hide show
  1. package/CHANGELOG.md +241 -24
  2. package/README.md +143 -119
  3. package/dist/cli/args.d.ts +4 -2
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +37 -39
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/auth-check.d.ts +19 -0
  8. package/dist/cli/auth-check.d.ts.map +1 -0
  9. package/dist/cli/auth-check.js +50 -0
  10. package/dist/cli/auth-check.js.map +1 -0
  11. package/dist/cli/auth-command.d.ts +24 -0
  12. package/dist/cli/auth-command.d.ts.map +1 -0
  13. package/dist/cli/auth-command.js +103 -0
  14. package/dist/cli/auth-command.js.map +1 -0
  15. package/dist/cli/config-selector.d.ts.map +1 -1
  16. package/dist/cli/config-selector.js +2 -2
  17. package/dist/cli/config-selector.js.map +1 -1
  18. package/dist/cli/credential-print.d.ts +5 -15
  19. package/dist/cli/credential-print.d.ts.map +1 -1
  20. package/dist/cli/credential-print.js +42 -83
  21. package/dist/cli/credential-print.js.map +1 -1
  22. package/dist/cli/experimental/auth.d.ts +16 -0
  23. package/dist/cli/experimental/auth.d.ts.map +1 -0
  24. package/dist/cli/experimental/auth.js +13 -0
  25. package/dist/cli/experimental/auth.js.map +1 -0
  26. package/dist/cli/experimental/cli.d.ts +6 -0
  27. package/dist/cli/experimental/cli.d.ts.map +1 -0
  28. package/dist/cli/experimental/cli.js +5 -0
  29. package/dist/cli/experimental/cli.js.map +1 -0
  30. package/dist/cli/experimental/command-options.d.ts +17 -0
  31. package/dist/cli/experimental/command-options.d.ts.map +1 -0
  32. package/dist/cli/experimental/command-options.js +35 -0
  33. package/dist/cli/experimental/command-options.js.map +1 -0
  34. package/dist/cli/experimental/command.d.ts +63 -0
  35. package/dist/cli/experimental/command.d.ts.map +1 -0
  36. package/dist/cli/experimental/command.js +130 -0
  37. package/dist/cli/experimental/command.js.map +1 -0
  38. package/dist/cli/experimental/commands/client.d.ts +13 -0
  39. package/dist/cli/experimental/commands/client.d.ts.map +1 -0
  40. package/dist/cli/experimental/commands/client.js +25 -0
  41. package/dist/cli/experimental/commands/client.js.map +1 -0
  42. package/dist/cli/experimental/commands/pi.d.ts +15 -0
  43. package/dist/cli/experimental/commands/pi.d.ts.map +1 -0
  44. package/dist/cli/experimental/commands/pi.js +28 -0
  45. package/dist/cli/experimental/commands/pi.js.map +1 -0
  46. package/dist/cli/experimental/commands/server.d.ts +13 -0
  47. package/dist/cli/experimental/commands/server.d.ts.map +1 -0
  48. package/dist/cli/experimental/commands/server.js +25 -0
  49. package/dist/cli/experimental/commands/server.js.map +1 -0
  50. package/dist/cli/experimental/transport-address.d.ts +10 -0
  51. package/dist/cli/experimental/transport-address.d.ts.map +1 -0
  52. package/dist/cli/experimental/transport-address.js +38 -0
  53. package/dist/cli/experimental/transport-address.js.map +1 -0
  54. package/dist/cli/list-models.d.ts +1 -1
  55. package/dist/cli/list-models.d.ts.map +1 -1
  56. package/dist/cli/list-models.js +2 -2
  57. package/dist/cli/list-models.js.map +1 -1
  58. package/dist/cli/startup-ui.d.ts +1 -1
  59. package/dist/cli/startup-ui.d.ts.map +1 -1
  60. package/dist/cli/startup-ui.js +2 -2
  61. package/dist/cli/startup-ui.js.map +1 -1
  62. package/dist/client/index.d.ts +3 -0
  63. package/dist/client/index.d.ts.map +1 -0
  64. package/dist/client/index.js +3 -0
  65. package/dist/client/index.js.map +1 -0
  66. package/dist/client/remote-session.d.ts +53 -0
  67. package/dist/client/remote-session.d.ts.map +1 -0
  68. package/dist/client/remote-session.js +340 -0
  69. package/dist/client/remote-session.js.map +1 -0
  70. package/dist/client/transcript.d.ts +12 -0
  71. package/dist/client/transcript.d.ts.map +1 -0
  72. package/dist/client/transcript.js +98 -0
  73. package/dist/client/transcript.js.map +1 -0
  74. package/dist/core/agent-session-services.d.ts +1 -0
  75. package/dist/core/agent-session-services.d.ts.map +1 -1
  76. package/dist/core/agent-session-services.js +1 -0
  77. package/dist/core/agent-session-services.js.map +1 -1
  78. package/dist/core/agent-session.d.ts +1 -10
  79. package/dist/core/agent-session.d.ts.map +1 -1
  80. package/dist/core/agent-session.js +72 -70
  81. package/dist/core/agent-session.js.map +1 -1
  82. package/dist/core/auth-storage.d.ts +25 -9
  83. package/dist/core/auth-storage.d.ts.map +1 -1
  84. package/dist/core/auth-storage.js +237 -39
  85. package/dist/core/auth-storage.js.map +1 -1
  86. package/dist/core/extensions/index.d.ts +1 -1
  87. package/dist/core/extensions/index.d.ts.map +1 -1
  88. package/dist/core/extensions/index.js.map +1 -1
  89. package/dist/core/extensions/loader.d.ts.map +1 -1
  90. package/dist/core/extensions/loader.js +60 -41
  91. package/dist/core/extensions/loader.js.map +1 -1
  92. package/dist/core/extensions/runner.d.ts +2 -1
  93. package/dist/core/extensions/runner.d.ts.map +1 -1
  94. package/dist/core/extensions/runner.js +3 -0
  95. package/dist/core/extensions/runner.js.map +1 -1
  96. package/dist/core/extensions/types.d.ts +27 -4
  97. package/dist/core/extensions/types.d.ts.map +1 -1
  98. package/dist/core/extensions/types.js.map +1 -1
  99. package/dist/core/http-dispatcher.d.ts.map +1 -1
  100. package/dist/core/http-dispatcher.js +5 -0
  101. package/dist/core/http-dispatcher.js.map +1 -1
  102. package/dist/core/keybindings.d.ts +45 -5
  103. package/dist/core/keybindings.d.ts.map +1 -1
  104. package/dist/core/keybindings.js.map +1 -1
  105. package/dist/core/model-config.d.ts +29 -5
  106. package/dist/core/model-config.d.ts.map +1 -1
  107. package/dist/core/model-config.js +4 -0
  108. package/dist/core/model-config.js.map +1 -1
  109. package/dist/core/model-registry.d.ts +5 -3
  110. package/dist/core/model-registry.d.ts.map +1 -1
  111. package/dist/core/model-registry.js +13 -10
  112. package/dist/core/model-registry.js.map +1 -1
  113. package/dist/core/model-resolver.d.ts +4 -3
  114. package/dist/core/model-resolver.d.ts.map +1 -1
  115. package/dist/core/model-resolver.js +42 -10
  116. package/dist/core/model-resolver.js.map +1 -1
  117. package/dist/core/model-runtime.d.ts +30 -13
  118. package/dist/core/model-runtime.d.ts.map +1 -1
  119. package/dist/core/model-runtime.js +233 -73
  120. package/dist/core/model-runtime.js.map +1 -1
  121. package/dist/core/models-store.d.ts +12 -7
  122. package/dist/core/models-store.d.ts.map +1 -1
  123. package/dist/core/models-store.js +83 -14
  124. package/dist/core/models-store.js.map +1 -1
  125. package/dist/core/package-manager.d.ts +6 -3
  126. package/dist/core/package-manager.d.ts.map +1 -1
  127. package/dist/core/package-manager.js +80 -61
  128. package/dist/core/package-manager.js.map +1 -1
  129. package/dist/core/pi-manifest.d.ts +8 -0
  130. package/dist/core/pi-manifest.d.ts.map +1 -0
  131. package/dist/core/pi-manifest.js +28 -0
  132. package/dist/core/pi-manifest.js.map +1 -0
  133. package/dist/core/provider-composer.d.ts +4 -1
  134. package/dist/core/provider-composer.d.ts.map +1 -1
  135. package/dist/core/provider-composer.js +36 -15
  136. package/dist/core/provider-composer.js.map +1 -1
  137. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  138. package/dist/core/remote-catalog-provider.js +73 -67
  139. package/dist/core/remote-catalog-provider.js.map +1 -1
  140. package/dist/core/resource-loader.d.ts.map +1 -1
  141. package/dist/core/resource-loader.js +2 -2
  142. package/dist/core/resource-loader.js.map +1 -1
  143. package/dist/core/runtime-credentials.d.ts +5 -5
  144. package/dist/core/runtime-credentials.d.ts.map +1 -1
  145. package/dist/core/runtime-credentials.js +11 -8
  146. package/dist/core/runtime-credentials.js.map +1 -1
  147. package/dist/core/sdk.d.ts +1 -1
  148. package/dist/core/sdk.d.ts.map +1 -1
  149. package/dist/core/sdk.js +2 -2
  150. package/dist/core/sdk.js.map +1 -1
  151. package/dist/core/session-manager.d.ts.map +1 -1
  152. package/dist/core/session-manager.js +3 -1
  153. package/dist/core/session-manager.js.map +1 -1
  154. package/dist/core/settings-manager.d.ts +12 -0
  155. package/dist/core/settings-manager.d.ts.map +1 -1
  156. package/dist/core/settings-manager.js +40 -16
  157. package/dist/core/settings-manager.js.map +1 -1
  158. package/dist/core/system-prompt.d.ts.map +1 -1
  159. package/dist/core/system-prompt.js +8 -0
  160. package/dist/core/system-prompt.js.map +1 -1
  161. package/dist/core/tools/bash.d.ts +5 -1
  162. package/dist/core/tools/bash.d.ts.map +1 -1
  163. package/dist/core/tools/bash.js +16 -15
  164. package/dist/core/tools/bash.js.map +1 -1
  165. package/dist/core/tools/edit.d.ts +4 -0
  166. package/dist/core/tools/edit.d.ts.map +1 -1
  167. package/dist/core/tools/edit.js +11 -7
  168. package/dist/core/tools/edit.js.map +1 -1
  169. package/dist/core/tools/find.d.ts +7 -0
  170. package/dist/core/tools/find.d.ts.map +1 -1
  171. package/dist/core/tools/find.js +16 -19
  172. package/dist/core/tools/find.js.map +1 -1
  173. package/dist/core/tools/grep.d.ts +4 -0
  174. package/dist/core/tools/grep.d.ts.map +1 -1
  175. package/dist/core/tools/grep.js +5 -1
  176. package/dist/core/tools/grep.js.map +1 -1
  177. package/dist/core/tools/ls.d.ts +4 -0
  178. package/dist/core/tools/ls.d.ts.map +1 -1
  179. package/dist/core/tools/ls.js +5 -1
  180. package/dist/core/tools/ls.js.map +1 -1
  181. package/dist/core/tools/read.d.ts +4 -0
  182. package/dist/core/tools/read.d.ts.map +1 -1
  183. package/dist/core/tools/read.js +7 -3
  184. package/dist/core/tools/read.js.map +1 -1
  185. package/dist/core/tools/write.d.ts +4 -0
  186. package/dist/core/tools/write.d.ts.map +1 -1
  187. package/dist/core/tools/write.js +6 -2
  188. package/dist/core/tools/write.js.map +1 -1
  189. package/dist/extensions/llama/index.d.ts.map +1 -1
  190. package/dist/extensions/llama/index.js +11 -2
  191. package/dist/extensions/llama/index.js.map +1 -1
  192. package/dist/extensions/llama/provider.d.ts.map +1 -1
  193. package/dist/extensions/llama/provider.js +21 -7
  194. package/dist/extensions/llama/provider.js.map +1 -1
  195. package/dist/humain/agent-execution-protocol.d.ts +218 -0
  196. package/dist/humain/agent-execution-protocol.d.ts.map +1 -0
  197. package/dist/humain/agent-execution-protocol.js +204 -0
  198. package/dist/humain/agent-execution-protocol.js.map +1 -0
  199. package/dist/humain/agent-execution-runtime.d.ts +35 -0
  200. package/dist/humain/agent-execution-runtime.d.ts.map +1 -0
  201. package/dist/humain/agent-execution-runtime.js +170 -0
  202. package/dist/humain/agent-execution-runtime.js.map +1 -0
  203. package/dist/humain/index.d.ts.map +1 -1
  204. package/dist/humain/index.js +8 -7
  205. package/dist/humain/index.js.map +1 -1
  206. package/dist/humain/mcp-adapter/vendor/CHANGELOG.md +660 -0
  207. package/dist/humain/mcp-adapter/vendor/LICENSE +21 -0
  208. package/dist/humain/mcp-adapter/vendor/README.md +733 -0
  209. package/dist/humain/mcp-adapter/vendor/abort.ts +34 -0
  210. package/dist/humain/mcp-adapter/vendor/agent-dir.ts +60 -0
  211. package/dist/humain/mcp-adapter/vendor/agent-plugin-loader.ts +377 -0
  212. package/dist/humain/mcp-adapter/vendor/app-bridge.bundle.js +67 -0
  213. package/dist/humain/mcp-adapter/vendor/banner.png +0 -0
  214. package/dist/humain/mcp-adapter/vendor/cli.js +209 -0
  215. package/dist/humain/mcp-adapter/vendor/commands.ts +627 -0
  216. package/dist/humain/mcp-adapter/vendor/config.ts +1226 -0
  217. package/dist/humain/mcp-adapter/vendor/consent-manager.ts +64 -0
  218. package/dist/humain/mcp-adapter/vendor/direct-tools.ts +604 -0
  219. package/dist/humain/mcp-adapter/vendor/elicitation-handler.ts +348 -0
  220. package/dist/humain/mcp-adapter/vendor/error-signal.ts +21 -0
  221. package/dist/humain/mcp-adapter/vendor/errors.ts +223 -0
  222. package/dist/humain/mcp-adapter/vendor/glimpse-ui.ts +80 -0
  223. package/dist/humain/mcp-adapter/vendor/host-html-template.ts +461 -0
  224. package/dist/humain/mcp-adapter/vendor/index.bundle.d.mts +4 -0
  225. package/dist/humain/mcp-adapter/vendor/index.bundle.mjs +15923 -0
  226. package/dist/humain/mcp-adapter/vendor/index.ts +898 -0
  227. package/dist/humain/mcp-adapter/vendor/init.ts +649 -0
  228. package/dist/humain/mcp-adapter/vendor/json-schema-validator.ts +69 -0
  229. package/dist/humain/mcp-adapter/vendor/lifecycle.ts +147 -0
  230. package/dist/humain/mcp-adapter/vendor/logger.ts +169 -0
  231. package/dist/humain/mcp-adapter/vendor/mcp-auth-flow.ts +993 -0
  232. package/dist/humain/mcp-adapter/vendor/mcp-auth.ts +1000 -0
  233. package/dist/humain/mcp-adapter/vendor/mcp-callback-server.ts +510 -0
  234. package/dist/humain/mcp-adapter/vendor/mcp-code.ts +354 -0
  235. package/dist/humain/mcp-adapter/vendor/mcp-keyring-helper.cjs +89 -0
  236. package/dist/humain/mcp-adapter/vendor/mcp-oauth-provider.ts +616 -0
  237. package/dist/humain/mcp-adapter/vendor/mcp-output-guard.ts +408 -0
  238. package/dist/humain/mcp-adapter/vendor/mcp-panel.ts +1015 -0
  239. package/dist/humain/mcp-adapter/vendor/mcp-probe.ts +187 -0
  240. package/dist/humain/mcp-adapter/vendor/mcp-script-worker.mjs +130 -0
  241. package/dist/humain/mcp-adapter/vendor/mcp-setup-panel.ts +666 -0
  242. package/dist/humain/mcp-adapter/vendor/mcp-status.ts +109 -0
  243. package/dist/humain/mcp-adapter/vendor/mcp-trace.ts +306 -0
  244. package/dist/humain/mcp-adapter/vendor/metadata-cache.ts +353 -0
  245. package/dist/humain/mcp-adapter/vendor/npx-resolver.ts +543 -0
  246. package/dist/humain/mcp-adapter/vendor/oauth-handler.ts +30 -0
  247. package/dist/humain/mcp-adapter/vendor/oauth.ts +48 -0
  248. package/dist/humain/mcp-adapter/vendor/onboarding-state.ts +76 -0
  249. package/dist/humain/mcp-adapter/vendor/package.json +178 -0
  250. package/dist/humain/mcp-adapter/vendor/panel-keys.ts +53 -0
  251. package/dist/humain/mcp-adapter/vendor/prompts.ts +353 -0
  252. package/dist/humain/mcp-adapter/vendor/proxy-modes.ts +1331 -0
  253. package/dist/humain/mcp-adapter/vendor/resource-tools.ts +17 -0
  254. package/dist/humain/mcp-adapter/vendor/runtime-owner.ts +91 -0
  255. package/dist/humain/mcp-adapter/vendor/sampling-handler.ts +284 -0
  256. package/dist/humain/mcp-adapter/vendor/search-ranking.ts +206 -0
  257. package/dist/humain/mcp-adapter/vendor/server-manager.ts +1124 -0
  258. package/dist/humain/mcp-adapter/vendor/session-recovery.ts +151 -0
  259. package/dist/humain/mcp-adapter/vendor/skills/mcp-scripting/SKILL.md +38 -0
  260. package/dist/humain/mcp-adapter/vendor/state.ts +62 -0
  261. package/dist/humain/mcp-adapter/vendor/tool-approval.ts +182 -0
  262. package/dist/humain/mcp-adapter/vendor/tool-metadata.ts +276 -0
  263. package/dist/humain/mcp-adapter/vendor/tool-registrar.ts +253 -0
  264. package/dist/humain/mcp-adapter/vendor/tool-result-renderer.ts +423 -0
  265. package/dist/humain/mcp-adapter/vendor/ts-shape.ts +149 -0
  266. package/dist/humain/mcp-adapter/vendor/types.ts +859 -0
  267. package/dist/humain/mcp-adapter/vendor/ui-app-bridge-helpers.ts +40 -0
  268. package/dist/humain/mcp-adapter/vendor/ui-resource-handler.ts +250 -0
  269. package/dist/humain/mcp-adapter/vendor/ui-server.ts +866 -0
  270. package/dist/humain/mcp-adapter/vendor/ui-session.ts +570 -0
  271. package/dist/humain/mcp-adapter/vendor/ui-stream-types.ts +89 -0
  272. package/dist/humain/mcp-adapter/vendor/ui-tool-visibility.ts +25 -0
  273. package/dist/humain/mcp-adapter/vendor/unix-socket-transport.ts +85 -0
  274. package/dist/humain/mcp-adapter/vendor/utils.ts +310 -0
  275. package/dist/humain/mcp-adapter.d.ts +3 -0
  276. package/dist/humain/mcp-adapter.d.ts.map +1 -0
  277. package/dist/humain/mcp-adapter.js +5 -0
  278. package/dist/humain/mcp-adapter.js.map +1 -0
  279. package/dist/humain/pi-agent-execution-host.d.ts +34 -0
  280. package/dist/humain/pi-agent-execution-host.d.ts.map +1 -0
  281. package/dist/humain/pi-agent-execution-host.js +77 -0
  282. package/dist/humain/pi-agent-execution-host.js.map +1 -0
  283. package/dist/humain/web-access/host.d.ts +4 -0
  284. package/dist/humain/web-access/host.d.ts.map +1 -0
  285. package/dist/humain/web-access/host.js +3 -0
  286. package/dist/humain/web-access/host.js.map +1 -0
  287. package/dist/humain/web-access/index.d.ts +3 -0
  288. package/dist/humain/web-access/index.d.ts.map +1 -0
  289. package/dist/humain/web-access/index.js +5 -0
  290. package/dist/humain/web-access/index.js.map +1 -0
  291. package/dist/humain/web-access/vendor/activity.d.ts +34 -0
  292. package/dist/humain/web-access/vendor/activity.d.ts.map +1 -0
  293. package/dist/humain/web-access/vendor/activity.js +68 -0
  294. package/dist/humain/web-access/vendor/activity.js.map +1 -0
  295. package/dist/humain/web-access/vendor/anysearch.d.ts +8 -0
  296. package/dist/humain/web-access/vendor/anysearch.d.ts.map +1 -0
  297. package/dist/humain/web-access/vendor/anysearch.js +167 -0
  298. package/dist/humain/web-access/vendor/anysearch.js.map +1 -0
  299. package/dist/humain/web-access/vendor/bocha.d.ts +4 -0
  300. package/dist/humain/web-access/vendor/bocha.d.ts.map +1 -0
  301. package/dist/humain/web-access/vendor/bocha.js +219 -0
  302. package/dist/humain/web-access/vendor/bocha.js.map +1 -0
  303. package/dist/humain/web-access/vendor/brave.d.ts +4 -0
  304. package/dist/humain/web-access/vendor/brave.d.ts.map +1 -0
  305. package/dist/humain/web-access/vendor/brave.js +194 -0
  306. package/dist/humain/web-access/vendor/brave.js.map +1 -0
  307. package/dist/humain/web-access/vendor/brightdata-unlocker.d.ts +12 -0
  308. package/dist/humain/web-access/vendor/brightdata-unlocker.d.ts.map +1 -0
  309. package/dist/humain/web-access/vendor/brightdata-unlocker.js +230 -0
  310. package/dist/humain/web-access/vendor/brightdata-unlocker.js.map +1 -0
  311. package/dist/humain/web-access/vendor/brightdata.d.ts +8 -0
  312. package/dist/humain/web-access/vendor/brightdata.d.ts.map +1 -0
  313. package/dist/humain/web-access/vendor/brightdata.js +519 -0
  314. package/dist/humain/web-access/vendor/brightdata.js.map +1 -0
  315. package/dist/humain/web-access/vendor/chrome-cookies.d.ts +10 -0
  316. package/dist/humain/web-access/vendor/chrome-cookies.d.ts.map +1 -0
  317. package/dist/humain/web-access/vendor/chrome-cookies.js +438 -0
  318. package/dist/humain/web-access/vendor/chrome-cookies.js.map +1 -0
  319. package/dist/humain/web-access/vendor/content-find.d.ts +11 -0
  320. package/dist/humain/web-access/vendor/content-find.d.ts.map +1 -0
  321. package/dist/humain/web-access/vendor/content-find.js +117 -0
  322. package/dist/humain/web-access/vendor/content-find.js.map +1 -0
  323. package/dist/humain/web-access/vendor/credential-source.d.ts +28 -0
  324. package/dist/humain/web-access/vendor/credential-source.d.ts.map +1 -0
  325. package/dist/humain/web-access/vendor/credential-source.js +151 -0
  326. package/dist/humain/web-access/vendor/credential-source.js.map +1 -0
  327. package/dist/humain/web-access/vendor/curator-page.d.ts +29 -0
  328. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -0
  329. package/dist/humain/web-access/vendor/curator-page.js +3554 -0
  330. package/dist/humain/web-access/vendor/curator-page.js.map +1 -0
  331. package/dist/humain/web-access/vendor/curator-server.d.ts +93 -0
  332. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -0
  333. package/dist/humain/web-access/vendor/curator-server.js +688 -0
  334. package/dist/humain/web-access/vendor/curator-server.js.map +1 -0
  335. package/dist/humain/web-access/vendor/datalab-pdf-extract.d.ts +60 -0
  336. package/dist/humain/web-access/vendor/datalab-pdf-extract.d.ts.map +1 -0
  337. package/dist/humain/web-access/vendor/datalab-pdf-extract.js +416 -0
  338. package/dist/humain/web-access/vendor/datalab-pdf-extract.js.map +1 -0
  339. package/dist/humain/web-access/vendor/declared-web-links.d.ts +16 -0
  340. package/dist/humain/web-access/vendor/declared-web-links.d.ts.map +1 -0
  341. package/dist/humain/web-access/vendor/declared-web-links.js +168 -0
  342. package/dist/humain/web-access/vendor/declared-web-links.js.map +1 -0
  343. package/dist/humain/web-access/vendor/duckduckgo.d.ts +4 -0
  344. package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -0
  345. package/dist/humain/web-access/vendor/duckduckgo.js +123 -0
  346. package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -0
  347. package/dist/humain/web-access/vendor/exa.d.ts +10 -0
  348. package/dist/humain/web-access/vendor/exa.d.ts.map +1 -0
  349. package/dist/humain/web-access/vendor/exa.js +426 -0
  350. package/dist/humain/web-access/vendor/exa.js.map +1 -0
  351. package/dist/humain/web-access/vendor/extract.d.ts +46 -0
  352. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -0
  353. package/dist/humain/web-access/vendor/extract.js +1064 -0
  354. package/dist/humain/web-access/vendor/extract.js.map +1 -0
  355. package/dist/humain/web-access/vendor/feature-config.d.ts +3 -0
  356. package/dist/humain/web-access/vendor/feature-config.d.ts.map +1 -0
  357. package/dist/humain/web-access/vendor/feature-config.js +27 -0
  358. package/dist/humain/web-access/vendor/feature-config.js.map +1 -0
  359. package/dist/humain/web-access/vendor/fetch-params.d.ts +25 -0
  360. package/dist/humain/web-access/vendor/fetch-params.d.ts.map +1 -0
  361. package/dist/humain/web-access/vendor/fetch-params.js +57 -0
  362. package/dist/humain/web-access/vendor/fetch-params.js.map +1 -0
  363. package/dist/humain/web-access/vendor/firecrawl.d.ts +12 -0
  364. package/dist/humain/web-access/vendor/firecrawl.d.ts.map +1 -0
  365. package/dist/humain/web-access/vendor/firecrawl.js +239 -0
  366. package/dist/humain/web-access/vendor/firecrawl.js.map +1 -0
  367. package/dist/humain/web-access/vendor/gemini-api.d.ts +27 -0
  368. package/dist/humain/web-access/vendor/gemini-api.d.ts.map +1 -0
  369. package/dist/humain/web-access/vendor/gemini-api.js +230 -0
  370. package/dist/humain/web-access/vendor/gemini-api.js.map +1 -0
  371. package/dist/humain/web-access/vendor/gemini-pdf-extract.d.ts +9 -0
  372. package/dist/humain/web-access/vendor/gemini-pdf-extract.d.ts.map +1 -0
  373. package/dist/humain/web-access/vendor/gemini-pdf-extract.js +85 -0
  374. package/dist/humain/web-access/vendor/gemini-pdf-extract.js.map +1 -0
  375. package/dist/humain/web-access/vendor/gemini-search.d.ts +40 -0
  376. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -0
  377. package/dist/humain/web-access/vendor/gemini-search.js +814 -0
  378. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -0
  379. package/dist/humain/web-access/vendor/gemini-url-context.d.ts +4 -0
  380. package/dist/humain/web-access/vendor/gemini-url-context.d.ts.map +1 -0
  381. package/dist/humain/web-access/vendor/gemini-url-context.js +101 -0
  382. package/dist/humain/web-access/vendor/gemini-url-context.js.map +1 -0
  383. package/dist/humain/web-access/vendor/gemini-web-config.d.ts +4 -0
  384. package/dist/humain/web-access/vendor/gemini-web-config.d.ts.map +1 -0
  385. package/dist/humain/web-access/vendor/gemini-web-config.js +42 -0
  386. package/dist/humain/web-access/vendor/gemini-web-config.js.map +1 -0
  387. package/dist/humain/web-access/vendor/gemini-web.d.ts +18 -0
  388. package/dist/humain/web-access/vendor/gemini-web.d.ts.map +1 -0
  389. package/dist/humain/web-access/vendor/gemini-web.js +385 -0
  390. package/dist/humain/web-access/vendor/gemini-web.js.map +1 -0
  391. package/dist/humain/web-access/vendor/github-api.d.ts +7 -0
  392. package/dist/humain/web-access/vendor/github-api.d.ts.map +1 -0
  393. package/dist/humain/web-access/vendor/github-api.js +160 -0
  394. package/dist/humain/web-access/vendor/github-api.js.map +1 -0
  395. package/dist/humain/web-access/vendor/github-extract.d.ts +13 -0
  396. package/dist/humain/web-access/vendor/github-extract.d.ts.map +1 -0
  397. package/dist/humain/web-access/vendor/github-extract.js +635 -0
  398. package/dist/humain/web-access/vendor/github-extract.js.map +1 -0
  399. package/dist/humain/web-access/vendor/index.d.ts +4 -0
  400. package/dist/humain/web-access/vendor/index.d.ts.map +1 -0
  401. package/dist/humain/web-access/vendor/index.js +3002 -0
  402. package/dist/humain/web-access/vendor/index.js.map +1 -0
  403. package/dist/humain/web-access/vendor/jina-search.d.ts +8 -0
  404. package/dist/humain/web-access/vendor/jina-search.d.ts.map +1 -0
  405. package/dist/humain/web-access/vendor/jina-search.js +255 -0
  406. package/dist/humain/web-access/vendor/jina-search.js.map +1 -0
  407. package/dist/humain/web-access/vendor/kagi.d.ts +15 -0
  408. package/dist/humain/web-access/vendor/kagi.d.ts.map +1 -0
  409. package/dist/humain/web-access/vendor/kagi.js +262 -0
  410. package/dist/humain/web-access/vendor/kagi.js.map +1 -0
  411. package/dist/humain/web-access/vendor/ollama.d.ts +15 -0
  412. package/dist/humain/web-access/vendor/ollama.d.ts.map +1 -0
  413. package/dist/humain/web-access/vendor/ollama.js +216 -0
  414. package/dist/humain/web-access/vendor/ollama.js.map +1 -0
  415. package/dist/humain/web-access/vendor/openai-search.d.ts +15 -0
  416. package/dist/humain/web-access/vendor/openai-search.d.ts.map +1 -0
  417. package/dist/humain/web-access/vendor/openai-search.js +459 -0
  418. package/dist/humain/web-access/vendor/openai-search.js.map +1 -0
  419. package/dist/humain/web-access/vendor/page-query.d.ts +16 -0
  420. package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -0
  421. package/dist/humain/web-access/vendor/page-query.js +79 -0
  422. package/dist/humain/web-access/vendor/page-query.js.map +1 -0
  423. package/dist/humain/web-access/vendor/parallel.d.ts +12 -0
  424. package/dist/humain/web-access/vendor/parallel.d.ts.map +1 -0
  425. package/dist/humain/web-access/vendor/parallel.js +343 -0
  426. package/dist/humain/web-access/vendor/parallel.js.map +1 -0
  427. package/dist/humain/web-access/vendor/pdf-extract.d.ts +44 -0
  428. package/dist/humain/web-access/vendor/pdf-extract.d.ts.map +1 -0
  429. package/dist/humain/web-access/vendor/pdf-extract.js +298 -0
  430. package/dist/humain/web-access/vendor/pdf-extract.js.map +1 -0
  431. package/dist/humain/web-access/vendor/perplexity.d.ts +20 -0
  432. package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -0
  433. package/dist/humain/web-access/vendor/perplexity.js +159 -0
  434. package/dist/humain/web-access/vendor/perplexity.js.map +1 -0
  435. package/dist/humain/web-access/vendor/querit.d.ts +10 -0
  436. package/dist/humain/web-access/vendor/querit.d.ts.map +1 -0
  437. package/dist/humain/web-access/vendor/querit.js +335 -0
  438. package/dist/humain/web-access/vendor/querit.js.map +1 -0
  439. package/dist/humain/web-access/vendor/render-search-error.d.ts +57 -0
  440. package/dist/humain/web-access/vendor/render-search-error.d.ts.map +1 -0
  441. package/dist/humain/web-access/vendor/render-search-error.js +130 -0
  442. package/dist/humain/web-access/vendor/render-search-error.js.map +1 -0
  443. package/dist/humain/web-access/vendor/rsc-extract.d.ts +12 -0
  444. package/dist/humain/web-access/vendor/rsc-extract.d.ts.map +1 -0
  445. package/dist/humain/web-access/vendor/rsc-extract.js +329 -0
  446. package/dist/humain/web-access/vendor/rsc-extract.js.map +1 -0
  447. package/dist/humain/web-access/vendor/search1api.d.ts +10 -0
  448. package/dist/humain/web-access/vendor/search1api.d.ts.map +1 -0
  449. package/dist/humain/web-access/vendor/search1api.js +251 -0
  450. package/dist/humain/web-access/vendor/search1api.js.map +1 -0
  451. package/dist/humain/web-access/vendor/searchinfinity.d.ts +8 -0
  452. package/dist/humain/web-access/vendor/searchinfinity.d.ts.map +1 -0
  453. package/dist/humain/web-access/vendor/searchinfinity.js +229 -0
  454. package/dist/humain/web-access/vendor/searchinfinity.js.map +1 -0
  455. package/dist/humain/web-access/vendor/searxng.d.ts +4 -0
  456. package/dist/humain/web-access/vendor/searxng.d.ts.map +1 -0
  457. package/dist/humain/web-access/vendor/searxng.js +238 -0
  458. package/dist/humain/web-access/vendor/searxng.js.map +1 -0
  459. package/dist/humain/web-access/vendor/serpbase.d.ts +4 -0
  460. package/dist/humain/web-access/vendor/serpbase.d.ts.map +1 -0
  461. package/dist/humain/web-access/vendor/serpbase.js +211 -0
  462. package/dist/humain/web-access/vendor/serpbase.js.map +1 -0
  463. package/dist/humain/web-access/vendor/serpdive.d.ts +8 -0
  464. package/dist/humain/web-access/vendor/serpdive.d.ts.map +1 -0
  465. package/dist/humain/web-access/vendor/serpdive.js +267 -0
  466. package/dist/humain/web-access/vendor/serpdive.js.map +1 -0
  467. package/dist/humain/web-access/vendor/source-check.d.ts +99 -0
  468. package/dist/humain/web-access/vendor/source-check.d.ts.map +1 -0
  469. package/dist/humain/web-access/vendor/source-check.js +205 -0
  470. package/dist/humain/web-access/vendor/source-check.js.map +1 -0
  471. package/dist/humain/web-access/vendor/ssrf-protection.d.ts +50 -0
  472. package/dist/humain/web-access/vendor/ssrf-protection.d.ts.map +1 -0
  473. package/dist/humain/web-access/vendor/ssrf-protection.js +466 -0
  474. package/dist/humain/web-access/vendor/ssrf-protection.js.map +1 -0
  475. package/dist/humain/web-access/vendor/storage.d.ts +55 -0
  476. package/dist/humain/web-access/vendor/storage.d.ts.map +1 -0
  477. package/dist/humain/web-access/vendor/storage.js +485 -0
  478. package/dist/humain/web-access/vendor/storage.js.map +1 -0
  479. package/dist/humain/web-access/vendor/summary-model-scope.d.ts +25 -0
  480. package/dist/humain/web-access/vendor/summary-model-scope.d.ts.map +1 -0
  481. package/dist/humain/web-access/vendor/summary-model-scope.js +98 -0
  482. package/dist/humain/web-access/vendor/summary-model-scope.js.map +1 -0
  483. package/dist/humain/web-access/vendor/summary-review.d.ts +24 -0
  484. package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -0
  485. package/dist/humain/web-access/vendor/summary-review.js +341 -0
  486. package/dist/humain/web-access/vendor/summary-review.js.map +1 -0
  487. package/dist/humain/web-access/vendor/tavily.d.ts +8 -0
  488. package/dist/humain/web-access/vendor/tavily.d.ts.map +1 -0
  489. package/dist/humain/web-access/vendor/tavily.js +194 -0
  490. package/dist/humain/web-access/vendor/tavily.js.map +1 -0
  491. package/dist/humain/web-access/vendor/tinyfish.d.ts +11 -0
  492. package/dist/humain/web-access/vendor/tinyfish.d.ts.map +1 -0
  493. package/dist/humain/web-access/vendor/tinyfish.js +331 -0
  494. package/dist/humain/web-access/vendor/tinyfish.js.map +1 -0
  495. package/dist/humain/web-access/vendor/utils.d.ts +20 -0
  496. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -0
  497. package/dist/humain/web-access/vendor/utils.js +91 -0
  498. package/dist/humain/web-access/vendor/utils.js.map +1 -0
  499. package/dist/humain/web-access/vendor/video-extract.d.ts +16 -0
  500. package/dist/humain/web-access/vendor/video-extract.d.ts.map +1 -0
  501. package/dist/humain/web-access/vendor/video-extract.js +335 -0
  502. package/dist/humain/web-access/vendor/video-extract.js.map +1 -0
  503. package/dist/humain/web-access/vendor/xai-search.d.ts +13 -0
  504. package/dist/humain/web-access/vendor/xai-search.d.ts.map +1 -0
  505. package/dist/humain/web-access/vendor/xai-search.js +331 -0
  506. package/dist/humain/web-access/vendor/xai-search.js.map +1 -0
  507. package/dist/humain/web-access/vendor/youtube-extract.d.ts +27 -0
  508. package/dist/humain/web-access/vendor/youtube-extract.d.ts.map +1 -0
  509. package/dist/humain/web-access/vendor/youtube-extract.js +282 -0
  510. package/dist/humain/web-access/vendor/youtube-extract.js.map +1 -0
  511. package/dist/index.d.ts +7 -4
  512. package/dist/index.d.ts.map +1 -1
  513. package/dist/index.js +5 -2
  514. package/dist/index.js.map +1 -1
  515. package/dist/main.d.ts +2 -2
  516. package/dist/main.d.ts.map +1 -1
  517. package/dist/main.js +169 -102
  518. package/dist/main.js.map +1 -1
  519. package/dist/modes/agent-exec-mode.d.ts +14 -0
  520. package/dist/modes/agent-exec-mode.d.ts.map +1 -0
  521. package/dist/modes/agent-exec-mode.js +92 -0
  522. package/dist/modes/agent-exec-mode.js.map +1 -0
  523. package/dist/modes/index.d.ts +4 -2
  524. package/dist/modes/index.d.ts.map +1 -1
  525. package/dist/modes/index.js +2 -1
  526. package/dist/modes/index.js.map +1 -1
  527. package/dist/modes/interactive/components/assistant-message.d.ts +5 -2
  528. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  529. package/dist/modes/interactive/components/assistant-message.js +13 -4
  530. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  531. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  532. package/dist/modes/interactive/components/custom-editor.js +7 -0
  533. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  534. package/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
  535. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
  536. package/dist/modes/interactive/components/earendil-announcement.js +40 -0
  537. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -0
  538. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  539. package/dist/modes/interactive/components/footer.js +1 -1
  540. package/dist/modes/interactive/components/footer.js.map +1 -1
  541. package/dist/modes/interactive/components/markdown-transform.d.ts +3 -0
  542. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
  543. package/dist/modes/interactive/components/markdown-transform.js +19 -0
  544. package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
  545. package/dist/modes/interactive/components/mermaid.d.ts +11 -0
  546. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
  547. package/dist/modes/interactive/components/mermaid.js +75 -0
  548. package/dist/modes/interactive/components/mermaid.js.map +1 -0
  549. package/dist/modes/interactive/components/model-selector.d.ts +1 -1
  550. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  551. package/dist/modes/interactive/components/model-selector.js +16 -4
  552. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  553. package/dist/modes/interactive/components/scoped-models-selector.d.ts +4 -0
  554. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  555. package/dist/modes/interactive/components/scoped-models-selector.js +26 -0
  556. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  557. package/dist/modes/interactive/components/settings-selector.d.ts +8 -2
  558. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  559. package/dist/modes/interactive/components/settings-selector.js +30 -0
  560. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  561. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  562. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  563. package/dist/modes/interactive/components/user-message.js +9 -2
  564. package/dist/modes/interactive/components/user-message.js.map +1 -1
  565. package/dist/modes/interactive/interactive-mode.d.ts +45 -9
  566. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  567. package/dist/modes/interactive/interactive-mode.js +581 -211
  568. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  569. package/dist/modes/interactive/theme/dark.json +1 -0
  570. package/dist/modes/interactive/theme/light.json +1 -0
  571. package/dist/modes/interactive/theme/theme-controller.d.ts +3 -0
  572. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  573. package/dist/modes/interactive/theme/theme-controller.js +10 -1
  574. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  575. package/dist/modes/interactive/theme/theme-schema.json +5 -1
  576. package/dist/modes/interactive/theme/theme.d.ts +2 -2
  577. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  578. package/dist/modes/interactive/theme/theme.js +24 -6
  579. package/dist/modes/interactive/theme/theme.js.map +1 -1
  580. package/dist/modes/json-event.d.ts +28 -0
  581. package/dist/modes/json-event.d.ts.map +1 -0
  582. package/dist/modes/json-event.js +12 -0
  583. package/dist/modes/json-event.js.map +1 -0
  584. package/dist/modes/print-mode.d.ts.map +1 -1
  585. package/dist/modes/print-mode.js +12 -2
  586. package/dist/modes/print-mode.js.map +1 -1
  587. package/dist/modes/rpc/rpc-client.d.ts +12 -5
  588. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  589. package/dist/modes/rpc/rpc-client.js +55 -1
  590. package/dist/modes/rpc/rpc-client.js.map +1 -1
  591. package/dist/modes/rpc/rpc-mode.d.ts +1 -1
  592. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  593. package/dist/modes/rpc/rpc-mode.js +13 -3
  594. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  595. package/dist/modes/rpc/rpc-types.d.ts +15 -0
  596. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  597. package/dist/modes/rpc/rpc-types.js.map +1 -1
  598. package/dist/package-manager-cli.d.ts.map +1 -1
  599. package/dist/package-manager-cli.js +11 -9
  600. package/dist/package-manager-cli.js.map +1 -1
  601. package/dist/rpc-entry.d.ts.map +1 -1
  602. package/dist/rpc-entry.js +3 -2
  603. package/dist/rpc-entry.js.map +1 -1
  604. package/dist/server/create-harness.d.ts +26 -0
  605. package/dist/server/create-harness.d.ts.map +1 -0
  606. package/dist/server/create-harness.js +104 -0
  607. package/dist/server/create-harness.js.map +1 -0
  608. package/dist/utils/abort.d.ts +5 -0
  609. package/dist/utils/abort.d.ts.map +1 -0
  610. package/dist/utils/abort.js +48 -0
  611. package/dist/utils/abort.js.map +1 -0
  612. package/dist/utils/clipboard.d.ts +1 -1
  613. package/dist/utils/clipboard.d.ts.map +1 -1
  614. package/dist/utils/clipboard.js +22 -2
  615. package/dist/utils/clipboard.js.map +1 -1
  616. package/dist/utils/management-http.d.ts +23 -0
  617. package/dist/utils/management-http.d.ts.map +1 -0
  618. package/dist/utils/management-http.js +50 -0
  619. package/dist/utils/management-http.js.map +1 -0
  620. package/dist/utils/paths.d.ts +3 -0
  621. package/dist/utils/paths.d.ts.map +1 -1
  622. package/dist/utils/paths.js +23 -1
  623. package/dist/utils/paths.js.map +1 -1
  624. package/dist/utils/tool-result-images.d.ts +19 -0
  625. package/dist/utils/tool-result-images.d.ts.map +1 -0
  626. package/dist/utils/tool-result-images.js +45 -0
  627. package/dist/utils/tool-result-images.js.map +1 -0
  628. package/dist/utils/tools-manager.d.ts.map +1 -1
  629. package/dist/utils/tools-manager.js +13 -25
  630. package/dist/utils/tools-manager.js.map +1 -1
  631. package/dist/utils/version-check.d.ts +4 -0
  632. package/dist/utils/version-check.d.ts.map +1 -1
  633. package/dist/utils/version-check.js +23 -5
  634. package/dist/utils/version-check.js.map +1 -1
  635. package/docs/compaction.md +2 -2
  636. package/docs/custom-provider.md +7 -5
  637. package/docs/extensions.md +30 -5
  638. package/docs/humain-terminal.md +21 -1
  639. package/docs/json.md +24 -19
  640. package/docs/keybindings.md +46 -14
  641. package/docs/models.md +32 -11
  642. package/docs/providers.md +9 -1
  643. package/docs/quickstart.md +39 -37
  644. package/docs/rpc.md +31 -11
  645. package/docs/sdk.md +21 -2
  646. package/docs/security.md +21 -21
  647. package/docs/session-format.md +14 -14
  648. package/docs/settings.md +4 -1
  649. package/docs/themes.md +5 -3
  650. package/docs/usage.md +7 -0
  651. package/examples/extensions/custom-compaction.ts +3 -18
  652. package/examples/extensions/custom-provider-anthropic/index.ts +5 -1
  653. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  654. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  655. package/examples/extensions/custom-provider-gitlab-duo/index.ts +5 -1
  656. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  657. package/examples/extensions/doom-overlay/wad-finder.ts +7 -3
  658. package/examples/extensions/gondolin/package-lock.json +2 -2
  659. package/examples/extensions/gondolin/package.json +1 -1
  660. package/examples/extensions/handoff.ts +4 -13
  661. package/examples/extensions/qna.ts +5 -9
  662. package/examples/extensions/sandbox/package-lock.json +2 -2
  663. package/examples/extensions/sandbox/package.json +1 -1
  664. package/examples/extensions/summarize.ts +9 -20
  665. package/examples/extensions/with-deps/package-lock.json +2 -2
  666. package/examples/extensions/with-deps/package.json +1 -1
  667. package/examples/rpc-extension-ui.ts +11 -2
  668. package/examples/sdk/02-custom-model.ts +2 -3
  669. package/examples/sdk/09-api-keys-and-oauth.ts +1 -1
  670. package/examples/sdk/12-full-control.ts +1 -1
  671. package/examples/sdk/README.md +1 -1
  672. package/npm-shrinkwrap.json +2771 -535
  673. package/package.json +40 -11
  674. package/src/humain/mcp-adapter/UPSTREAM.md +15 -0
  675. package/src/humain/mcp-adapter/upstream.json +7 -0
  676. package/src/humain/mcp-adapter/vendor/CHANGELOG.md +660 -0
  677. package/src/humain/mcp-adapter/vendor/LICENSE +21 -0
  678. package/src/humain/web-access/UPSTREAM.md +17 -0
  679. package/src/humain/web-access/upstream.json +23 -0
  680. package/src/humain/web-access/vendor/LICENSE +21 -0
@@ -5,6 +5,10 @@ declare const writeSchema: Type.TObject<{
5
5
  path: Type.TString;
6
6
  content: Type.TString;
7
7
  }>;
8
+ export declare const writeToolSystemPromptContribution: {
9
+ readonly snippet: "Create or overwrite files";
10
+ readonly guidelines: readonly ["Use write only for new files or complete rewrites."];
11
+ };
8
12
  export type WriteToolInput = Static<typeof writeSchema>;
9
13
  /**
10
14
  * Pluggable operations for the write tool.
@@ -1 +1 @@
1
- {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAMtF,QAAA,MAAM,WAAW;;;EAGf,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC/B,8BAA8B;IAC9B,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,mCAAmC;IACnC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AAOD,MAAM,WAAW,gBAAgB;IAChC,oEAAoE;IACpE,UAAU,CAAC,EAAE,eAAe,CAAC;CAC7B;AA6ID,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gBAAgB,GACxB,cAAc,CAAC,OAAO,WAAW,EAAE,SAAS,CAAC,CA+E/C;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,SAAS,CAAC,OAAO,WAAW,CAAC,CAEtG","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ToolDefinition<typeof writeSchema, undefined> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: \"Create or overwrite files\",\n\t\tpromptGuidelines: [\"Use write only for new files or complete rewrites.\"],\n\t\tparameters: writeSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, content }: { path: string; content: string },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\t// Create parent directories if needed.\n\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Write the file contents.\n\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully wrote ${content.length} bytes to ${path}` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAMtF,QAAA,MAAM,WAAW;;;EAGf,CAAC;AAEH,eAAO,MAAM,iCAAiC;;;CAGpC,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC/B,8BAA8B;IAC9B,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,mCAAmC;IACnC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AAOD,MAAM,WAAW,gBAAgB;IAChC,oEAAoE;IACpE,UAAU,CAAC,EAAE,eAAe,CAAC;CAC7B;AA6ID,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gBAAgB,GACxB,cAAc,CAAC,OAAO,WAAW,EAAE,SAAS,CAAC,CA+E/C;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,SAAS,CAAC,OAAO,WAAW,CAAC,CAEtG","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport const writeToolSystemPromptContribution = {\n\tsnippet: \"Create or overwrite files\",\n\tguidelines: [\"Use write only for new files or complete rewrites.\"],\n} as const;\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ToolDefinition<typeof writeSchema, undefined> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: writeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...writeToolSystemPromptContribution.guidelines],\n\t\tparameters: writeSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, content }: { path: string; content: string },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\t// Create parent directories if needed.\n\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Write the file contents.\n\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully wrote ${content.length} bytes to ${path}` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
@@ -12,6 +12,10 @@ const writeSchema = Type.Object({
12
12
  path: Type.String({ description: "Path to the file to write (relative or absolute)" }),
13
13
  content: Type.String({ description: "Content to write to the file" }),
14
14
  });
15
+ export const writeToolSystemPromptContribution = {
16
+ snippet: "Create or overwrite files",
17
+ guidelines: ["Use write only for new files or complete rewrites."],
18
+ };
15
19
  const defaultWriteOperations = {
16
20
  writeFile: (path, content) => fsWriteFile(path, content, "utf-8"),
17
21
  mkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => { }),
@@ -134,8 +138,8 @@ export function createWriteToolDefinition(cwd, options) {
134
138
  name: "write",
135
139
  label: "write",
136
140
  description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
137
- promptSnippet: "Create or overwrite files",
138
- promptGuidelines: ["Use write only for new files or complete rewrites."],
141
+ promptSnippet: writeToolSystemPromptContribution.snippet,
142
+ promptGuidelines: [...writeToolSystemPromptContribution.guidelines],
139
143
  parameters: writeSchema,
140
144
  async execute(_toolCallId, { path, content }, signal, _onUpdate, _ctx) {
141
145
  const absolutePath = resolveToCwd(path, cwd);
@@ -1 +1 @@
1
- {"version":3,"file":"write.js","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AACA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AAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,eAAe,CAAC,GAAW,EAAE,OAA0B,EAAiC;IACvG,OAAO,kBAAkB,CAAC,yBAAyB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACnE","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ToolDefinition<typeof writeSchema, undefined> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: \"Create or overwrite files\",\n\t\tpromptGuidelines: [\"Use write only for new files or complete rewrites.\"],\n\t\tparameters: writeSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, content }: { path: string; content: string },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\t// Create parent directories if needed.\n\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Write the file contents.\n\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully wrote ${content.length} bytes to ${path}` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"write.js","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,KAAK,IAAI,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAc,MAAM,wCAAwC,CAAC;AAExG,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,W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C;YAChF,CAAC;iBAAM,CAAC;gBACP,SAAS,CAAC,KAAK,GAAG,SAAS,CAAC;YAC7B,CAAC;YACD,SAAS,CAAC,OAAO,CAChB,eAAe,CACd,UAAU,EACV,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,EAC5D,KAAK,EACL,SAAS,CAAC,KAAK,EACf,OAAO,CAAC,GAAG,CACX,CACD,CAAC;YACF,OAAO,SAAS,CAAC;QAAA,CACjB;QACD,YAAY,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE;YAC9C,MAAM,MAAM,GAAG,iBAAiB,CAAC,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;YACjF,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,MAAM,SAAS,GAAI,OAAO,CAAC,aAAuC,IAAI,IAAI,SAAS,EAAE,CAAC;gBACtF,SAAS,CAAC,KAAK,EAAE,CAAC;gBAClB,OAAO,SAAS,CAAC;YAClB,CAAC;YACD,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,eAAe,CAAC,GAAW,EAAE,OAA0B,EAAiC;IACvG,OAAO,kBAAkB,CAAC,yBAAyB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACnE","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport const writeToolSystemPromptContribution = {\n\tsnippet: \"Create or overwrite files\",\n\tguidelines: [\"Use write only for new files or complete rewrites.\"],\n} as const;\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ToolDefinition<typeof writeSchema, undefined> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: writeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...writeToolSystemPromptContribution.guidelines],\n\t\tparameters: writeSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, content }: { path: string; content: string },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\t// Create parent directories if needed.\n\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Write the file contents.\n\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully wrote ${content.length} bytes to ${path}` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA2B,MAAM,gCAAgC,CAAC;AAyC5F,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAmL7D","sourcesContent":["import type { ExtensionAPI, ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport { formatBytes, LlamaClient, type LlamaModelInfo, normalizeLlamaServerUrl } from \"./client.ts\";\nimport { findHuggingFaceToken, HuggingFaceClient } from \"./huggingface.ts\";\nimport { createLlamaProvider, LLAMA_PROVIDER_ID } from \"./provider.ts\";\nimport { type LlamaUi, runWithProgress, showLlamaUi } from \"./ui.ts\";\n\nfunction modelIsLoaded(model: LlamaModelInfo): boolean {\n\treturn model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n}\n\nfunction isConnectionError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst message = `${error.name} ${error.message}`.toLowerCase();\n\treturn message.includes(\"fetch failed\") || message.includes(\"timeout\") || message.includes(\"network\");\n}\n\nfunction connectionErrorMessage(error: unknown): string {\n\tif (isConnectionError(error)) return \"Could not connect to the server.\";\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction parseHuggingFaceModel(value: string): { repository: string; quantization?: string } {\n\tconst colon = value.indexOf(\":\", value.indexOf(\"/\") + 1);\n\treturn colon < 0\n\t\t? { repository: value }\n\t\t: { repository: value.slice(0, colon), quantization: value.slice(colon + 1) };\n}\n\nasync function configuredClient(ctx: ExtensionCommandContext): Promise<LlamaClient | undefined> {\n\tconst result = await ctx.modelRegistry.getProviderAuth(LLAMA_PROVIDER_ID);\n\tif (!result) {\n\t\tctx.ui.notify(`Configure llama.cpp with /login ${LLAMA_PROVIDER_ID}`, \"warning\");\n\t\treturn undefined;\n\t}\n\tconst configuredUrl = result.env?.LLAMA_BASE_URL;\n\tconst serverUrl = normalizeLlamaServerUrl(\n\t\ttypeof configuredUrl === \"string\" && configuredUrl ? configuredUrl : (result.auth.baseUrl ?? \"\"),\n\t);\n\treturn new LlamaClient(serverUrl, result.auth.apiKey);\n}\n\nexport default function llamaExtension(pi: ExtensionAPI): void {\n\tconst provider = createLlamaProvider();\n\tpi.registerProvider(provider.provider);\n\n\tconst syncCatalog = async (\n\t\tctx: ExtensionCommandContext,\n\t\tclient: LlamaClient,\n\t\tcatalog?: LlamaModelInfo[],\n\t): Promise<LlamaModelInfo[]> => {\n\t\tconst current = catalog ?? (await client.list());\n\t\tprovider.setCatalog(current, client.serverUrl);\n\t\tawait ctx.modelRegistry.refresh();\n\t\treturn current;\n\t};\n\n\tconst loadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tcatalog: LlamaModelInfo[],\n\t\ttarget: LlamaModelInfo,\n\t): Promise<void> => {\n\t\tconst loaded = catalog.filter((model) => model.id !== target.id && modelIsLoaded(model));\n\t\tlet replace = false;\n\t\tif (loaded.length > 0) {\n\t\t\tconst choice = await ui.select(`${loaded.length} model${loaded.length === 1 ? \" is\" : \"s are\"} loaded`, [\n\t\t\t\t\"Unload all and load\",\n\t\t\t\t\"Keep loaded and load\",\n\t\t\t\t\"Cancel\",\n\t\t\t]);\n\t\t\tif (!choice || choice === \"Cancel\") return;\n\t\t\treplace = choice === \"Unload all and load\";\n\t\t}\n\n\t\tconst restoreLoaded = async (): Promise<void> => {\n\t\t\tctx.ui.notify(\"Restoring previously loaded models\");\n\t\t\tfor (const model of loaded) await client.loadAndWait(model.id, () => {});\n\t\t\tawait syncCatalog(ctx, client);\n\t\t};\n\t\tif (replace) {\n\t\t\tfor (const model of loaded) await client.unloadAndWait(model.id);\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await runWithProgress(ui, {\n\t\t\t\ttitle: \"Loading model\",\n\t\t\t\tmodel: target.id,\n\t\t\t\tinitialMessage: \"Starting…\",\n\t\t\t\tcancelTitle: \"Stop loading?\",\n\t\t\t\tcancelMessage: target.id,\n\t\t\t\trun: (signal, update) => client.loadAndWait(target.id, update, signal),\n\t\t\t\tcancel: () => client.unload(target.id),\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\tif (replace) await restoreLoaded();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst refreshed = await syncCatalog(ctx, client);\n\t\t\tconst loadedModel = refreshed.find((model) => model.id === target.id);\n\t\t\tctx.ui.notify(\n\t\t\t\tloadedModel?.status.value === \"loaded\" ? `Loaded ${target.id}` : `Load started for ${target.id}`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (replace) {\n\t\t\t\ttry {\n\t\t\t\t\tawait restoreLoaded();\n\t\t\t\t} catch {\n\t\t\t\t\t// Preserve the original load error.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst unloadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tmodel: LlamaModelInfo,\n\t): Promise<void> => {\n\t\tif (!(await ui.confirm(\"Unload model?\", model.id))) return;\n\t\tawait client.unloadAndWait(model.id);\n\t\tawait syncCatalog(ctx, client);\n\t\tctx.ui.notify(`Unloaded ${model.id}`);\n\t};\n\n\tconst downloadModel = async (ctx: ExtensionCommandContext, ui: LlamaUi, client: LlamaClient): Promise<void> => {\n\t\tconst huggingFace = new HuggingFaceClient(await findHuggingFaceToken());\n\t\tconst selected = await ui.searchModels((query, signal) => huggingFace.search(query, signal));\n\t\tif (!selected) return;\n\t\tconst parsed = parseHuggingFaceModel(selected);\n\t\tui.showStatus(\"Loading model details\", parsed.repository);\n\t\tconst details = await huggingFace.details(parsed.repository);\n\t\tif (details.gated) {\n\t\t\tconst approval = details.gated === \"manual\" ? \"Manual approval is required\" : \"Accept the access terms\";\n\t\t\tconst choice = await ui.select(\n\t\t\t\t`Hugging Face access required\\n${details.id}\\n\\n${approval} at:\\nhttps://huggingface.co/${details.id}\\n\\nThe llama.cpp server needs HF_TOKEN with access.`,\n\t\t\t\t[\"Continue\", \"Back\"],\n\t\t\t);\n\t\t\tif (choice !== \"Continue\") return;\n\t\t}\n\t\tlet quantization = parsed.quantization;\n\t\tif (!quantization && details.quantizations.length > 0) {\n\t\t\tconst options = details.quantizations.map((entry) => {\n\t\t\t\tconst detail = [\n\t\t\t\t\tentry.size === undefined ? undefined : formatBytes(entry.size),\n\t\t\t\t\tentry.name === \"Q4_K_M\" ? \"recommended\" : undefined,\n\t\t\t\t]\n\t\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t\t.join(\" · \");\n\t\t\t\treturn detail ? `${entry.name} · ${detail}` : entry.name;\n\t\t\t});\n\t\t\tconst choice = await ui.select(`Select quantization\\n${details.id}`, options);\n\t\t\tif (!choice) return;\n\t\t\tquantization = details.quantizations[options.indexOf(choice)]?.name;\n\t\t\tif (!quantization) return;\n\t\t}\n\t\tconst model = quantization ? `${details.id}:${quantization}` : details.id;\n\t\tconst result = await runWithProgress(ui, {\n\t\t\ttitle: \"Downloading model\",\n\t\t\tmodel,\n\t\t\tinitialMessage: \"Starting…\",\n\t\t\tcancelTitle: \"Stop download?\",\n\t\t\tcancelMessage: model,\n\t\t\trun: (signal, update) => client.downloadAndWait(model, update, signal),\n\t\t\tcancel: () => client.unload(model),\n\t\t});\n\t\tif (result.cancelled) return;\n\t\tawait syncCatalog(ctx, client, result.value);\n\t\tctx.ui.notify(`Downloaded ${model}`);\n\t};\n\n\tpi.registerCommand(\"llama\", {\n\t\tdescription: \"Manage llama.cpp router models\",\n\t\thandler: async (_args, ctx) => {\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/llama is available in interactive mode\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst client = await configuredClient(ctx);\n\t\t\tif (!client) return;\n\t\t\tawait showLlamaUi(ctx, async (ui) => {\n\t\t\t\tconst readCatalog = async (): Promise<LlamaModelInfo[] | undefined> => {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await syncCatalog(ctx, client);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif ((await ui.connectionError(client.serverUrl, connectionErrorMessage(error))) === \"close\") {\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tlet catalog = await readCatalog();\n\t\t\t\tif (!catalog) return;\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst action = await ui.showModels(client.serverUrl, catalog);\n\t\t\t\t\tif (action.type === \"close\") return;\n\t\t\t\t\tlet actionError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (action.type === \"download\") await downloadModel(ctx, ui, client);\n\t\t\t\t\t\telse if (modelIsLoaded(action.model)) await unloadModel(ctx, ui, client, action.model);\n\t\t\t\t\t\telse if (action.model.status.value === \"unloaded\")\n\t\t\t\t\t\t\tawait loadModel(ctx, ui, client, catalog, action.model);\n\t\t\t\t\t\telse ctx.ui.notify(`${action.model.id} is ${action.model.status.value}`, \"warning\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tactionError = error;\n\t\t\t\t\t}\n\t\t\t\t\tconst refreshed = await readCatalog();\n\t\t\t\t\tif (!refreshed) return;\n\t\t\t\t\tcatalog = refreshed;\n\t\t\t\t\tif (actionError && !isConnectionError(actionError)) {\n\t\t\t\t\t\tctx.ui.notify(actionError instanceof Error ? actionError.message : String(actionError), \"error\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA2B,MAAM,gCAAgC,CAAC;AAyC5F,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CA0L7D","sourcesContent":["import type { ExtensionAPI, ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport { formatBytes, LlamaClient, type LlamaModelInfo, normalizeLlamaServerUrl } from \"./client.ts\";\nimport { findHuggingFaceToken, HuggingFaceClient } from \"./huggingface.ts\";\nimport { createLlamaProvider, LLAMA_PROVIDER_ID } from \"./provider.ts\";\nimport { type LlamaUi, runWithProgress, showLlamaUi } from \"./ui.ts\";\n\nfunction modelIsLoaded(model: LlamaModelInfo): boolean {\n\treturn model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n}\n\nfunction isConnectionError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst message = `${error.name} ${error.message}`.toLowerCase();\n\treturn message.includes(\"fetch failed\") || message.includes(\"timeout\") || message.includes(\"network\");\n}\n\nfunction connectionErrorMessage(error: unknown): string {\n\tif (isConnectionError(error)) return \"Could not connect to the server.\";\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction parseHuggingFaceModel(value: string): { repository: string; quantization?: string } {\n\tconst colon = value.indexOf(\":\", value.indexOf(\"/\") + 1);\n\treturn colon < 0\n\t\t? { repository: value }\n\t\t: { repository: value.slice(0, colon), quantization: value.slice(colon + 1) };\n}\n\nasync function configuredClient(ctx: ExtensionCommandContext): Promise<LlamaClient | undefined> {\n\tconst result = await ctx.modelRegistry.getProviderAuth(LLAMA_PROVIDER_ID);\n\tif (!result) {\n\t\tctx.ui.notify(`Configure llama.cpp with /login ${LLAMA_PROVIDER_ID}`, \"warning\");\n\t\treturn undefined;\n\t}\n\tconst configuredUrl = result.env?.LLAMA_BASE_URL;\n\tconst serverUrl = normalizeLlamaServerUrl(\n\t\ttypeof configuredUrl === \"string\" && configuredUrl ? configuredUrl : (result.auth.baseUrl ?? \"\"),\n\t);\n\treturn new LlamaClient(serverUrl, result.auth.apiKey);\n}\n\nexport default function llamaExtension(pi: ExtensionAPI): void {\n\tconst provider = createLlamaProvider();\n\tpi.registerProvider(provider.provider);\n\n\tconst syncCatalog = async (\n\t\tctx: ExtensionCommandContext,\n\t\tclient: LlamaClient,\n\t\tcatalog?: LlamaModelInfo[],\n\t): Promise<LlamaModelInfo[]> => {\n\t\tconst signal = AbortSignal.timeout(15_000);\n\t\tconst current = catalog ?? (await client.list({ signal }));\n\t\tprovider.setCatalog(current, client.serverUrl);\n\t\tconst result = await ctx.modelRegistry.refresh({\n\t\t\tproviders: [LLAMA_PROVIDER_ID],\n\t\t\tsignal,\n\t\t});\n\t\tif (result.aborted) throw new Error(\"Model catalog refresh timed out.\");\n\t\tconst refreshError = result.errors.get(LLAMA_PROVIDER_ID);\n\t\tif (refreshError) throw refreshError;\n\t\treturn current;\n\t};\n\n\tconst loadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tcatalog: LlamaModelInfo[],\n\t\ttarget: LlamaModelInfo,\n\t): Promise<void> => {\n\t\tconst loaded = catalog.filter((model) => model.id !== target.id && modelIsLoaded(model));\n\t\tlet replace = false;\n\t\tif (loaded.length > 0) {\n\t\t\tconst choice = await ui.select(`${loaded.length} model${loaded.length === 1 ? \" is\" : \"s are\"} loaded`, [\n\t\t\t\t\"Unload all and load\",\n\t\t\t\t\"Keep loaded and load\",\n\t\t\t\t\"Cancel\",\n\t\t\t]);\n\t\t\tif (!choice || choice === \"Cancel\") return;\n\t\t\treplace = choice === \"Unload all and load\";\n\t\t}\n\n\t\tconst restoreLoaded = async (): Promise<void> => {\n\t\t\tctx.ui.notify(\"Restoring previously loaded models\");\n\t\t\tfor (const model of loaded) await client.loadAndWait(model.id, () => {});\n\t\t\tawait syncCatalog(ctx, client);\n\t\t};\n\t\tif (replace) {\n\t\t\tfor (const model of loaded) await client.unloadAndWait(model.id);\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await runWithProgress(ui, {\n\t\t\t\ttitle: \"Loading model\",\n\t\t\t\tmodel: target.id,\n\t\t\t\tinitialMessage: \"Starting…\",\n\t\t\t\tcancelTitle: \"Stop loading?\",\n\t\t\t\tcancelMessage: target.id,\n\t\t\t\trun: (signal, update) => client.loadAndWait(target.id, update, signal),\n\t\t\t\tcancel: () => client.unload(target.id),\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\tif (replace) await restoreLoaded();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst refreshed = await syncCatalog(ctx, client);\n\t\t\tconst loadedModel = refreshed.find((model) => model.id === target.id);\n\t\t\tctx.ui.notify(\n\t\t\t\tloadedModel?.status.value === \"loaded\" ? `Loaded ${target.id}` : `Load started for ${target.id}`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (replace) {\n\t\t\t\ttry {\n\t\t\t\t\tawait restoreLoaded();\n\t\t\t\t} catch {\n\t\t\t\t\t// Preserve the original load error.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst unloadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tmodel: LlamaModelInfo,\n\t): Promise<void> => {\n\t\tif (!(await ui.confirm(\"Unload model?\", model.id))) return;\n\t\tawait client.unloadAndWait(model.id);\n\t\tawait syncCatalog(ctx, client);\n\t\tctx.ui.notify(`Unloaded ${model.id}`);\n\t};\n\n\tconst downloadModel = async (ctx: ExtensionCommandContext, ui: LlamaUi, client: LlamaClient): Promise<void> => {\n\t\tconst huggingFace = new HuggingFaceClient(await findHuggingFaceToken());\n\t\tconst selected = await ui.searchModels((query, signal) => huggingFace.search(query, signal));\n\t\tif (!selected) return;\n\t\tconst parsed = parseHuggingFaceModel(selected);\n\t\tui.showStatus(\"Loading model details\", parsed.repository);\n\t\tconst details = await huggingFace.details(parsed.repository);\n\t\tif (details.gated) {\n\t\t\tconst approval = details.gated === \"manual\" ? \"Manual approval is required\" : \"Accept the access terms\";\n\t\t\tconst choice = await ui.select(\n\t\t\t\t`Hugging Face access required\\n${details.id}\\n\\n${approval} at:\\nhttps://huggingface.co/${details.id}\\n\\nThe llama.cpp server needs HF_TOKEN with access.`,\n\t\t\t\t[\"Continue\", \"Back\"],\n\t\t\t);\n\t\t\tif (choice !== \"Continue\") return;\n\t\t}\n\t\tlet quantization = parsed.quantization;\n\t\tif (!quantization && details.quantizations.length > 0) {\n\t\t\tconst options = details.quantizations.map((entry) => {\n\t\t\t\tconst detail = [\n\t\t\t\t\tentry.size === undefined ? undefined : formatBytes(entry.size),\n\t\t\t\t\tentry.name === \"Q4_K_M\" ? \"recommended\" : undefined,\n\t\t\t\t]\n\t\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t\t.join(\" · \");\n\t\t\t\treturn detail ? `${entry.name} · ${detail}` : entry.name;\n\t\t\t});\n\t\t\tconst choice = await ui.select(`Select quantization\\n${details.id}`, options);\n\t\t\tif (!choice) return;\n\t\t\tquantization = details.quantizations[options.indexOf(choice)]?.name;\n\t\t\tif (!quantization) return;\n\t\t}\n\t\tconst model = quantization ? `${details.id}:${quantization}` : details.id;\n\t\tconst result = await runWithProgress(ui, {\n\t\t\ttitle: \"Downloading model\",\n\t\t\tmodel,\n\t\t\tinitialMessage: \"Starting…\",\n\t\t\tcancelTitle: \"Stop download?\",\n\t\t\tcancelMessage: model,\n\t\t\trun: (signal, update) => client.downloadAndWait(model, update, signal),\n\t\t\tcancel: () => client.unload(model),\n\t\t});\n\t\tif (result.cancelled) return;\n\t\tawait syncCatalog(ctx, client, result.value);\n\t\tctx.ui.notify(`Downloaded ${model}`);\n\t};\n\n\tpi.registerCommand(\"llama\", {\n\t\tdescription: \"Manage llama.cpp router models\",\n\t\thandler: async (_args, ctx) => {\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/llama is available in interactive mode\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst client = await configuredClient(ctx);\n\t\t\tif (!client) return;\n\t\t\tawait showLlamaUi(ctx, async (ui) => {\n\t\t\t\tconst readCatalog = async (): Promise<LlamaModelInfo[] | undefined> => {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await syncCatalog(ctx, client);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif ((await ui.connectionError(client.serverUrl, connectionErrorMessage(error))) === \"close\") {\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tlet catalog = await readCatalog();\n\t\t\t\tif (!catalog) return;\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst action = await ui.showModels(client.serverUrl, catalog);\n\t\t\t\t\tif (action.type === \"close\") return;\n\t\t\t\t\tlet actionError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (action.type === \"download\") await downloadModel(ctx, ui, client);\n\t\t\t\t\t\telse if (modelIsLoaded(action.model)) await unloadModel(ctx, ui, client, action.model);\n\t\t\t\t\t\telse if (action.model.status.value === \"unloaded\")\n\t\t\t\t\t\t\tawait loadModel(ctx, ui, client, catalog, action.model);\n\t\t\t\t\t\telse ctx.ui.notify(`${action.model.id} is ${action.model.status.value}`, \"warning\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tactionError = error;\n\t\t\t\t\t}\n\t\t\t\t\tconst refreshed = await readCatalog();\n\t\t\t\t\tif (!refreshed) return;\n\t\t\t\t\tcatalog = refreshed;\n\t\t\t\t\tif (actionError && !isConnectionError(actionError)) {\n\t\t\t\t\t\tctx.ui.notify(actionError instanceof Error ? actionError.message : String(actionError), \"error\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t});\n}\n"]}
@@ -36,9 +36,18 @@ export default function llamaExtension(pi) {
36
36
  const provider = createLlamaProvider();
37
37
  pi.registerProvider(provider.provider);
38
38
  const syncCatalog = async (ctx, client, catalog) => {
39
- const current = catalog ?? (await client.list());
39
+ const signal = AbortSignal.timeout(15_000);
40
+ const current = catalog ?? (await client.list({ signal }));
40
41
  provider.setCatalog(current, client.serverUrl);
41
- await ctx.modelRegistry.refresh();
42
+ const result = await ctx.modelRegistry.refresh({
43
+ providers: [LLAMA_PROVIDER_ID],
44
+ signal,
45
+ });
46
+ if (result.aborted)
47
+ throw new Error("Model catalog refresh timed out.");
48
+ const refreshError = result.errors.get(LLAMA_PROVIDER_ID);
49
+ if (refreshError)
50
+ throw refreshError;
42
51
  return current;
43
52
  };
44
53
  const loadModel = async (ctx, ui, client, catalog, target) => {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/extensions/llama/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,WAAW,EAAuB,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACrG,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,EAAgB,eAAe,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAErE,SAAS,aAAa,CAAC,KAAqB,EAAW;IACtD,OAAO,KAAK,CAAC,MAAM,CAAC,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,KAAK,UAAU,CAAC;AAAA,CAC5E;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAW;IACnD,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5C,MAAM,OAAO,GAAG,GAAG,KAAK,CAAC,IAAI,IAAI,K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","sourcesContent":["import type { ExtensionAPI, ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport { formatBytes, LlamaClient, type LlamaModelInfo, normalizeLlamaServerUrl } from \"./client.ts\";\nimport { findHuggingFaceToken, HuggingFaceClient } from \"./huggingface.ts\";\nimport { createLlamaProvider, LLAMA_PROVIDER_ID } from \"./provider.ts\";\nimport { type LlamaUi, runWithProgress, showLlamaUi } from \"./ui.ts\";\n\nfunction modelIsLoaded(model: LlamaModelInfo): boolean {\n\treturn model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n}\n\nfunction isConnectionError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst message = `${error.name} ${error.message}`.toLowerCase();\n\treturn message.includes(\"fetch failed\") || message.includes(\"timeout\") || message.includes(\"network\");\n}\n\nfunction connectionErrorMessage(error: unknown): string {\n\tif (isConnectionError(error)) return \"Could not connect to the server.\";\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction parseHuggingFaceModel(value: string): { repository: string; quantization?: string } {\n\tconst colon = value.indexOf(\":\", value.indexOf(\"/\") + 1);\n\treturn colon < 0\n\t\t? { repository: value }\n\t\t: { repository: value.slice(0, colon), quantization: value.slice(colon + 1) };\n}\n\nasync function configuredClient(ctx: ExtensionCommandContext): Promise<LlamaClient | undefined> {\n\tconst result = await ctx.modelRegistry.getProviderAuth(LLAMA_PROVIDER_ID);\n\tif (!result) {\n\t\tctx.ui.notify(`Configure llama.cpp with /login ${LLAMA_PROVIDER_ID}`, \"warning\");\n\t\treturn undefined;\n\t}\n\tconst configuredUrl = result.env?.LLAMA_BASE_URL;\n\tconst serverUrl = normalizeLlamaServerUrl(\n\t\ttypeof configuredUrl === \"string\" && configuredUrl ? configuredUrl : (result.auth.baseUrl ?? \"\"),\n\t);\n\treturn new LlamaClient(serverUrl, result.auth.apiKey);\n}\n\nexport default function llamaExtension(pi: ExtensionAPI): void {\n\tconst provider = createLlamaProvider();\n\tpi.registerProvider(provider.provider);\n\n\tconst syncCatalog = async (\n\t\tctx: ExtensionCommandContext,\n\t\tclient: LlamaClient,\n\t\tcatalog?: LlamaModelInfo[],\n\t): Promise<LlamaModelInfo[]> => {\n\t\tconst current = catalog ?? (await client.list());\n\t\tprovider.setCatalog(current, client.serverUrl);\n\t\tawait ctx.modelRegistry.refresh();\n\t\treturn current;\n\t};\n\n\tconst loadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tcatalog: LlamaModelInfo[],\n\t\ttarget: LlamaModelInfo,\n\t): Promise<void> => {\n\t\tconst loaded = catalog.filter((model) => model.id !== target.id && modelIsLoaded(model));\n\t\tlet replace = false;\n\t\tif (loaded.length > 0) {\n\t\t\tconst choice = await ui.select(`${loaded.length} model${loaded.length === 1 ? \" is\" : \"s are\"} loaded`, [\n\t\t\t\t\"Unload all and load\",\n\t\t\t\t\"Keep loaded and load\",\n\t\t\t\t\"Cancel\",\n\t\t\t]);\n\t\t\tif (!choice || choice === \"Cancel\") return;\n\t\t\treplace = choice === \"Unload all and load\";\n\t\t}\n\n\t\tconst restoreLoaded = async (): Promise<void> => {\n\t\t\tctx.ui.notify(\"Restoring previously loaded models\");\n\t\t\tfor (const model of loaded) await client.loadAndWait(model.id, () => {});\n\t\t\tawait syncCatalog(ctx, client);\n\t\t};\n\t\tif (replace) {\n\t\t\tfor (const model of loaded) await client.unloadAndWait(model.id);\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await runWithProgress(ui, {\n\t\t\t\ttitle: \"Loading model\",\n\t\t\t\tmodel: target.id,\n\t\t\t\tinitialMessage: \"Starting…\",\n\t\t\t\tcancelTitle: \"Stop loading?\",\n\t\t\t\tcancelMessage: target.id,\n\t\t\t\trun: (signal, update) => client.loadAndWait(target.id, update, signal),\n\t\t\t\tcancel: () => client.unload(target.id),\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\tif (replace) await restoreLoaded();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst refreshed = await syncCatalog(ctx, client);\n\t\t\tconst loadedModel = refreshed.find((model) => model.id === target.id);\n\t\t\tctx.ui.notify(\n\t\t\t\tloadedModel?.status.value === \"loaded\" ? `Loaded ${target.id}` : `Load started for ${target.id}`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (replace) {\n\t\t\t\ttry {\n\t\t\t\t\tawait restoreLoaded();\n\t\t\t\t} catch {\n\t\t\t\t\t// Preserve the original load error.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst unloadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tmodel: LlamaModelInfo,\n\t): Promise<void> => {\n\t\tif (!(await ui.confirm(\"Unload model?\", model.id))) return;\n\t\tawait client.unloadAndWait(model.id);\n\t\tawait syncCatalog(ctx, client);\n\t\tctx.ui.notify(`Unloaded ${model.id}`);\n\t};\n\n\tconst downloadModel = async (ctx: ExtensionCommandContext, ui: LlamaUi, client: LlamaClient): Promise<void> => {\n\t\tconst huggingFace = new HuggingFaceClient(await findHuggingFaceToken());\n\t\tconst selected = await ui.searchModels((query, signal) => huggingFace.search(query, signal));\n\t\tif (!selected) return;\n\t\tconst parsed = parseHuggingFaceModel(selected);\n\t\tui.showStatus(\"Loading model details\", parsed.repository);\n\t\tconst details = await huggingFace.details(parsed.repository);\n\t\tif (details.gated) {\n\t\t\tconst approval = details.gated === \"manual\" ? \"Manual approval is required\" : \"Accept the access terms\";\n\t\t\tconst choice = await ui.select(\n\t\t\t\t`Hugging Face access required\\n${details.id}\\n\\n${approval} at:\\nhttps://huggingface.co/${details.id}\\n\\nThe llama.cpp server needs HF_TOKEN with access.`,\n\t\t\t\t[\"Continue\", \"Back\"],\n\t\t\t);\n\t\t\tif (choice !== \"Continue\") return;\n\t\t}\n\t\tlet quantization = parsed.quantization;\n\t\tif (!quantization && details.quantizations.length > 0) {\n\t\t\tconst options = details.quantizations.map((entry) => {\n\t\t\t\tconst detail = [\n\t\t\t\t\tentry.size === undefined ? undefined : formatBytes(entry.size),\n\t\t\t\t\tentry.name === \"Q4_K_M\" ? \"recommended\" : undefined,\n\t\t\t\t]\n\t\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t\t.join(\" · \");\n\t\t\t\treturn detail ? `${entry.name} · ${detail}` : entry.name;\n\t\t\t});\n\t\t\tconst choice = await ui.select(`Select quantization\\n${details.id}`, options);\n\t\t\tif (!choice) return;\n\t\t\tquantization = details.quantizations[options.indexOf(choice)]?.name;\n\t\t\tif (!quantization) return;\n\t\t}\n\t\tconst model = quantization ? `${details.id}:${quantization}` : details.id;\n\t\tconst result = await runWithProgress(ui, {\n\t\t\ttitle: \"Downloading model\",\n\t\t\tmodel,\n\t\t\tinitialMessage: \"Starting…\",\n\t\t\tcancelTitle: \"Stop download?\",\n\t\t\tcancelMessage: model,\n\t\t\trun: (signal, update) => client.downloadAndWait(model, update, signal),\n\t\t\tcancel: () => client.unload(model),\n\t\t});\n\t\tif (result.cancelled) return;\n\t\tawait syncCatalog(ctx, client, result.value);\n\t\tctx.ui.notify(`Downloaded ${model}`);\n\t};\n\n\tpi.registerCommand(\"llama\", {\n\t\tdescription: \"Manage llama.cpp router models\",\n\t\thandler: async (_args, ctx) => {\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/llama is available in interactive mode\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst client = await configuredClient(ctx);\n\t\t\tif (!client) return;\n\t\t\tawait showLlamaUi(ctx, async (ui) => {\n\t\t\t\tconst readCatalog = async (): Promise<LlamaModelInfo[] | undefined> => {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await syncCatalog(ctx, client);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif ((await ui.connectionError(client.serverUrl, connectionErrorMessage(error))) === \"close\") {\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tlet catalog = await readCatalog();\n\t\t\t\tif (!catalog) return;\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst action = await ui.showModels(client.serverUrl, catalog);\n\t\t\t\t\tif (action.type === \"close\") return;\n\t\t\t\t\tlet actionError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (action.type === \"download\") await downloadModel(ctx, ui, client);\n\t\t\t\t\t\telse if (modelIsLoaded(action.model)) await unloadModel(ctx, ui, client, action.model);\n\t\t\t\t\t\telse if (action.model.status.value === \"unloaded\")\n\t\t\t\t\t\t\tawait loadModel(ctx, ui, client, catalog, action.model);\n\t\t\t\t\t\telse ctx.ui.notify(`${action.model.id} is ${action.model.status.value}`, \"warning\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tactionError = error;\n\t\t\t\t\t}\n\t\t\t\t\tconst refreshed = await readCatalog();\n\t\t\t\t\tif (!refreshed) return;\n\t\t\t\t\tcatalog = refreshed;\n\t\t\t\t\tif (actionError && !isConnectionError(actionError)) {\n\t\t\t\t\t\tctx.ui.notify(actionError instanceof Error ? actionError.message : String(actionError), \"error\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/extensions/llama/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,WAAW,EAAuB,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACrG,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,EAAgB,eAAe,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAErE,SAAS,aAAa,CAAC,KAAqB,EAAW;IACtD,OA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CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,OAAO,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,SAAS,CAAC,CAAC;oBACrF,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBAChB,WAAW,GAAG,KAAK,CAAC;oBACrB,CAAC;oBACD,MAAM,SAAS,GAAG,MAAM,WAAW,EAAE,CAAC;oBACtC,IAAI,CAAC,SAAS;wBAAE,OAAO;oBACvB,OAAO,GAAG,SAAS,CAAC;oBACpB,IAAI,WAAW,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,EAAE,CAAC;wBACpD,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,WAAW,YAAY,KAAK,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC,CAAC;oBAClG,CAAC;gBACF,CAAC;YAAA,CACD,CAAC,CAAC;QAAA,CACH;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["import type { ExtensionAPI, ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport { formatBytes, LlamaClient, type LlamaModelInfo, normalizeLlamaServerUrl } from \"./client.ts\";\nimport { findHuggingFaceToken, HuggingFaceClient } from \"./huggingface.ts\";\nimport { createLlamaProvider, LLAMA_PROVIDER_ID } from \"./provider.ts\";\nimport { type LlamaUi, runWithProgress, showLlamaUi } from \"./ui.ts\";\n\nfunction modelIsLoaded(model: LlamaModelInfo): boolean {\n\treturn model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n}\n\nfunction isConnectionError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst message = `${error.name} ${error.message}`.toLowerCase();\n\treturn message.includes(\"fetch failed\") || message.includes(\"timeout\") || message.includes(\"network\");\n}\n\nfunction connectionErrorMessage(error: unknown): string {\n\tif (isConnectionError(error)) return \"Could not connect to the server.\";\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction parseHuggingFaceModel(value: string): { repository: string; quantization?: string } {\n\tconst colon = value.indexOf(\":\", value.indexOf(\"/\") + 1);\n\treturn colon < 0\n\t\t? { repository: value }\n\t\t: { repository: value.slice(0, colon), quantization: value.slice(colon + 1) };\n}\n\nasync function configuredClient(ctx: ExtensionCommandContext): Promise<LlamaClient | undefined> {\n\tconst result = await ctx.modelRegistry.getProviderAuth(LLAMA_PROVIDER_ID);\n\tif (!result) {\n\t\tctx.ui.notify(`Configure llama.cpp with /login ${LLAMA_PROVIDER_ID}`, \"warning\");\n\t\treturn undefined;\n\t}\n\tconst configuredUrl = result.env?.LLAMA_BASE_URL;\n\tconst serverUrl = normalizeLlamaServerUrl(\n\t\ttypeof configuredUrl === \"string\" && configuredUrl ? configuredUrl : (result.auth.baseUrl ?? \"\"),\n\t);\n\treturn new LlamaClient(serverUrl, result.auth.apiKey);\n}\n\nexport default function llamaExtension(pi: ExtensionAPI): void {\n\tconst provider = createLlamaProvider();\n\tpi.registerProvider(provider.provider);\n\n\tconst syncCatalog = async (\n\t\tctx: ExtensionCommandContext,\n\t\tclient: LlamaClient,\n\t\tcatalog?: LlamaModelInfo[],\n\t): Promise<LlamaModelInfo[]> => {\n\t\tconst signal = AbortSignal.timeout(15_000);\n\t\tconst current = catalog ?? (await client.list({ signal }));\n\t\tprovider.setCatalog(current, client.serverUrl);\n\t\tconst result = await ctx.modelRegistry.refresh({\n\t\t\tproviders: [LLAMA_PROVIDER_ID],\n\t\t\tsignal,\n\t\t});\n\t\tif (result.aborted) throw new Error(\"Model catalog refresh timed out.\");\n\t\tconst refreshError = result.errors.get(LLAMA_PROVIDER_ID);\n\t\tif (refreshError) throw refreshError;\n\t\treturn current;\n\t};\n\n\tconst loadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tcatalog: LlamaModelInfo[],\n\t\ttarget: LlamaModelInfo,\n\t): Promise<void> => {\n\t\tconst loaded = catalog.filter((model) => model.id !== target.id && modelIsLoaded(model));\n\t\tlet replace = false;\n\t\tif (loaded.length > 0) {\n\t\t\tconst choice = await ui.select(`${loaded.length} model${loaded.length === 1 ? \" is\" : \"s are\"} loaded`, [\n\t\t\t\t\"Unload all and load\",\n\t\t\t\t\"Keep loaded and load\",\n\t\t\t\t\"Cancel\",\n\t\t\t]);\n\t\t\tif (!choice || choice === \"Cancel\") return;\n\t\t\treplace = choice === \"Unload all and load\";\n\t\t}\n\n\t\tconst restoreLoaded = async (): Promise<void> => {\n\t\t\tctx.ui.notify(\"Restoring previously loaded models\");\n\t\t\tfor (const model of loaded) await client.loadAndWait(model.id, () => {});\n\t\t\tawait syncCatalog(ctx, client);\n\t\t};\n\t\tif (replace) {\n\t\t\tfor (const model of loaded) await client.unloadAndWait(model.id);\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await runWithProgress(ui, {\n\t\t\t\ttitle: \"Loading model\",\n\t\t\t\tmodel: target.id,\n\t\t\t\tinitialMessage: \"Starting…\",\n\t\t\t\tcancelTitle: \"Stop loading?\",\n\t\t\t\tcancelMessage: target.id,\n\t\t\t\trun: (signal, update) => client.loadAndWait(target.id, update, signal),\n\t\t\t\tcancel: () => client.unload(target.id),\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\tif (replace) await restoreLoaded();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst refreshed = await syncCatalog(ctx, client);\n\t\t\tconst loadedModel = refreshed.find((model) => model.id === target.id);\n\t\t\tctx.ui.notify(\n\t\t\t\tloadedModel?.status.value === \"loaded\" ? `Loaded ${target.id}` : `Load started for ${target.id}`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (replace) {\n\t\t\t\ttry {\n\t\t\t\t\tawait restoreLoaded();\n\t\t\t\t} catch {\n\t\t\t\t\t// Preserve the original load error.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst unloadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tmodel: LlamaModelInfo,\n\t): Promise<void> => {\n\t\tif (!(await ui.confirm(\"Unload model?\", model.id))) return;\n\t\tawait client.unloadAndWait(model.id);\n\t\tawait syncCatalog(ctx, client);\n\t\tctx.ui.notify(`Unloaded ${model.id}`);\n\t};\n\n\tconst downloadModel = async (ctx: ExtensionCommandContext, ui: LlamaUi, client: LlamaClient): Promise<void> => {\n\t\tconst huggingFace = new HuggingFaceClient(await findHuggingFaceToken());\n\t\tconst selected = await ui.searchModels((query, signal) => huggingFace.search(query, signal));\n\t\tif (!selected) return;\n\t\tconst parsed = parseHuggingFaceModel(selected);\n\t\tui.showStatus(\"Loading model details\", parsed.repository);\n\t\tconst details = await huggingFace.details(parsed.repository);\n\t\tif (details.gated) {\n\t\t\tconst approval = details.gated === \"manual\" ? \"Manual approval is required\" : \"Accept the access terms\";\n\t\t\tconst choice = await ui.select(\n\t\t\t\t`Hugging Face access required\\n${details.id}\\n\\n${approval} at:\\nhttps://huggingface.co/${details.id}\\n\\nThe llama.cpp server needs HF_TOKEN with access.`,\n\t\t\t\t[\"Continue\", \"Back\"],\n\t\t\t);\n\t\t\tif (choice !== \"Continue\") return;\n\t\t}\n\t\tlet quantization = parsed.quantization;\n\t\tif (!quantization && details.quantizations.length > 0) {\n\t\t\tconst options = details.quantizations.map((entry) => {\n\t\t\t\tconst detail = [\n\t\t\t\t\tentry.size === undefined ? undefined : formatBytes(entry.size),\n\t\t\t\t\tentry.name === \"Q4_K_M\" ? \"recommended\" : undefined,\n\t\t\t\t]\n\t\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t\t.join(\" · \");\n\t\t\t\treturn detail ? `${entry.name} · ${detail}` : entry.name;\n\t\t\t});\n\t\t\tconst choice = await ui.select(`Select quantization\\n${details.id}`, options);\n\t\t\tif (!choice) return;\n\t\t\tquantization = details.quantizations[options.indexOf(choice)]?.name;\n\t\t\tif (!quantization) return;\n\t\t}\n\t\tconst model = quantization ? `${details.id}:${quantization}` : details.id;\n\t\tconst result = await runWithProgress(ui, {\n\t\t\ttitle: \"Downloading model\",\n\t\t\tmodel,\n\t\t\tinitialMessage: \"Starting…\",\n\t\t\tcancelTitle: \"Stop download?\",\n\t\t\tcancelMessage: model,\n\t\t\trun: (signal, update) => client.downloadAndWait(model, update, signal),\n\t\t\tcancel: () => client.unload(model),\n\t\t});\n\t\tif (result.cancelled) return;\n\t\tawait syncCatalog(ctx, client, result.value);\n\t\tctx.ui.notify(`Downloaded ${model}`);\n\t};\n\n\tpi.registerCommand(\"llama\", {\n\t\tdescription: \"Manage llama.cpp router models\",\n\t\thandler: async (_args, ctx) => {\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/llama is available in interactive mode\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst client = await configuredClient(ctx);\n\t\t\tif (!client) return;\n\t\t\tawait showLlamaUi(ctx, async (ui) => {\n\t\t\t\tconst readCatalog = async (): Promise<LlamaModelInfo[] | undefined> => {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await syncCatalog(ctx, client);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif ((await ui.connectionError(client.serverUrl, connectionErrorMessage(error))) === \"close\") {\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tlet catalog = await readCatalog();\n\t\t\t\tif (!catalog) return;\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst action = await ui.showModels(client.serverUrl, catalog);\n\t\t\t\t\tif (action.type === \"close\") return;\n\t\t\t\t\tlet actionError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (action.type === \"download\") await downloadModel(ctx, ui, client);\n\t\t\t\t\t\telse if (modelIsLoaded(action.model)) await unloadModel(ctx, ui, client, action.model);\n\t\t\t\t\t\telse if (action.model.status.value === \"unloaded\")\n\t\t\t\t\t\t\tawait loadModel(ctx, ui, client, catalog, action.model);\n\t\t\t\t\t\telse ctx.ui.notify(`${action.model.id} is ${action.model.status.value}`, \"warning\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tactionError = error;\n\t\t\t\t\t}\n\t\t\t\t\tconst refreshed = await readCatalog();\n\t\t\t\t\tif (!refreshed) return;\n\t\t\t\t\tcatalog = refreshed;\n\t\t\t\t\tif (actionError && !isConnectionError(actionError)) {\n\t\t\t\t\t\tctx.ui.notify(actionError instanceof Error ? actionError.message : String(actionError), \"error\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAKX,QAAQ,EAGR,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAe,KAAK,cAAc,EAA8C,MAAM,aAAa,CAAC;AAE3G,eAAO,MAAM,iBAAiB,cAAc,CAAC;AAC7C,eAAO,MAAM,wBAAwB,0BAA0B,CAAC;AAuChE,MAAM,WAAW,uBAAuB;IACvC,QAAQ,EAAE,QAAQ,CAAC,oBAAoB,CAAC,CAAC;IACzC,UAAU,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CACvE;AAED,wBAAgB,mBAAmB,IAAI,uBAAuB,CA4E7D","sourcesContent":["import type {\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tModel,\n\tProvider,\n\tProviderStreamOptions,\n\tRefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { stream, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { LlamaClient, type LlamaModelInfo, llamaInferenceUrl, normalizeLlamaServerUrl } from \"./client.ts\";\n\nexport const LLAMA_PROVIDER_ID = \"llama.cpp\";\nexport const DEFAULT_LLAMA_SERVER_URL = \"http://127.0.0.1:8080\";\nfunction credentialServerUrl(credential: ApiKeyCredential | undefined): string | undefined {\n\tconst value = credential?.env?.LLAMA_BASE_URL;\n\treturn typeof value === \"string\" && value.trim() ? normalizeLlamaServerUrl(value) : undefined;\n}\n\nasync function resolveServerUrl(\n\tctx: AuthContext,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<string | undefined> {\n\tconst configured = credentialServerUrl(credential) ?? (await ctx.env(\"LLAMA_BASE_URL\"))?.trim();\n\treturn configured ? normalizeLlamaServerUrl(configured) : undefined;\n}\n\nfunction toPiModel(model: LlamaModelInfo, serverUrl: string): Model<\"openai-completions\"> {\n\tconst reportedContextWindow = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tconst contextWindow = reportedContextWindow && reportedContextWindow > 0 ? reportedContextWindow : 128000;\n\treturn {\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"openai-completions\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: llamaInferenceUrl(serverUrl),\n\t\treasoning: false,\n\t\tinput: model.architecture?.input_modalities?.includes(\"image\") ? [\"text\", \"image\"] : [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow,\n\t\tmaxTokens: contextWindow,\n\t\tcompat: {\n\t\t\tsupportsStore: false,\n\t\t\tsupportsDeveloperRole: false,\n\t\t\tsupportsReasoningEffort: false,\n\t\t\tsupportsUsageInStreaming: true,\n\t\t\tsupportsStrictMode: false,\n\t\t\tmaxTokensField: \"max_tokens\",\n\t\t},\n\t};\n}\n\nexport interface LlamaProviderController {\n\tprovider: Provider<\"openai-completions\">;\n\tsetCatalog(models: readonly LlamaModelInfo[], serverUrl: string): void;\n}\n\nexport function createLlamaProvider(): LlamaProviderController {\n\tlet models: readonly Model<\"openai-completions\">[] = [];\n\n\tconst setCatalog = (catalog: readonly LlamaModelInfo[], serverUrl: string): void => {\n\t\tmodels = catalog.filter((model) => model.status.value === \"loaded\").map((model) => toPiModel(model, serverUrl));\n\t};\n\n\tconst provider: Provider<\"openai-completions\"> = {\n\t\tid: LLAMA_PROVIDER_ID,\n\t\tname: \"llama.cpp\",\n\t\tbaseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname: \"llama.cpp server\",\n\t\t\t\tlogin: async (interaction): Promise<ApiKeyCredential> => {\n\t\t\t\t\tconst enteredUrl = await interaction.prompt({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tmessage: \"llama.cpp server URL\",\n\t\t\t\t\t\tplaceholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t});\n\t\t\t\t\tconst serverUrl = normalizeLlamaServerUrl(\n\t\t\t\t\t\tenteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t);\n\t\t\t\t\tconst apiKey = (\n\t\t\t\t\t\tawait interaction.prompt({\n\t\t\t\t\t\t\ttype: \"secret\",\n\t\t\t\t\t\t\tmessage: \"API key (optional)\",\n\t\t\t\t\t\t})\n\t\t\t\t\t).trim();\n\t\t\t\t\tawait new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal });\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"api_key\",\n\t\t\t\t\t\tkey: apiKey || undefined,\n\t\t\t\t\t\tenv: { LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcheck: async ({ ctx, credential }) => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\treturn serverUrl\n\t\t\t\t\t\t? { type: \"api_key\", source: credential ? \"stored credential\" : \"LLAMA_BASE_URL\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ ctx, credential }): Promise<AuthResult | undefined> => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\tif (!serverUrl) return undefined;\n\t\t\t\t\tconst apiKey = credential?.key ?? (await ctx.env(\"LLAMA_API_KEY\")) ?? \"local\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tauth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) },\n\t\t\t\t\t\tenv: { ...credential?.env, LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t\tsource: credential ? \"stored credential\" : \"LLAMA_BASE_URL\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext): Promise<void> => {\n\t\t\tconst stored = await context.store.read();\n\t\t\tif (stored) {\n\t\t\t\tmodels = stored.models.filter(\n\t\t\t\t\t(model): model is Model<\"openai-completions\"> =>\n\t\t\t\t\t\tmodel.provider === LLAMA_PROVIDER_ID && model.api === \"openai-completions\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!context.allowNetwork || context.signal?.aborted || context.credential?.type !== \"api_key\") return;\n\t\t\tconst serverUrl = credentialServerUrl(context.credential);\n\t\t\tif (!serverUrl) return;\n\t\t\tconst catalog = await new LlamaClient(serverUrl, context.credential.key).list({ signal: context.signal });\n\t\t\tsetCatalog(catalog, serverUrl);\n\t\t\tif (!context.signal?.aborted) await context.store.write({ models, checkedAt: Date.now() });\n\t\t},\n\t\tstream: (model, context, options) => stream(model, context, options as ProviderStreamOptions | undefined),\n\t\tstreamSimple: (model, context, options) => streamSimple(model, context, options),\n\t};\n\n\treturn { provider, setCatalog };\n}\n"]}
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAKX,QAAQ,EAGR,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAe,KAAK,cAAc,EAA8C,MAAM,aAAa,CAAC;AAE3G,eAAO,MAAM,iBAAiB,cAAc,CAAC;AAC7C,eAAO,MAAM,wBAAwB,0BAA0B,CAAC;AAuChE,MAAM,WAAW,uBAAuB;IACvC,QAAQ,EAAE,QAAQ,CAAC,oBAAoB,CAAC,CAAC;IACzC,UAAU,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CACvE;AAED,wBAAgB,mBAAmB,IAAI,uBAAuB,CA4F7D","sourcesContent":["import type {\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tModel,\n\tProvider,\n\tProviderStreamOptions,\n\tRefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { stream, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { LlamaClient, type LlamaModelInfo, llamaInferenceUrl, normalizeLlamaServerUrl } from \"./client.ts\";\n\nexport const LLAMA_PROVIDER_ID = \"llama.cpp\";\nexport const DEFAULT_LLAMA_SERVER_URL = \"http://127.0.0.1:8080\";\nfunction credentialServerUrl(credential: ApiKeyCredential | undefined): string | undefined {\n\tconst value = credential?.env?.LLAMA_BASE_URL;\n\treturn typeof value === \"string\" && value.trim() ? normalizeLlamaServerUrl(value) : undefined;\n}\n\nasync function resolveServerUrl(\n\tctx: AuthContext,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<string | undefined> {\n\tconst configured = credentialServerUrl(credential) ?? (await ctx.env(\"LLAMA_BASE_URL\"))?.trim();\n\treturn configured ? normalizeLlamaServerUrl(configured) : undefined;\n}\n\nfunction toPiModel(model: LlamaModelInfo, serverUrl: string): Model<\"openai-completions\"> {\n\tconst reportedContextWindow = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tconst contextWindow = reportedContextWindow && reportedContextWindow > 0 ? reportedContextWindow : 128000;\n\treturn {\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"openai-completions\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: llamaInferenceUrl(serverUrl),\n\t\treasoning: false,\n\t\tinput: model.architecture?.input_modalities?.includes(\"image\") ? [\"text\", \"image\"] : [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow,\n\t\tmaxTokens: contextWindow,\n\t\tcompat: {\n\t\t\tsupportsStore: false,\n\t\t\tsupportsDeveloperRole: false,\n\t\t\tsupportsReasoningEffort: false,\n\t\t\tsupportsUsageInStreaming: true,\n\t\t\tsupportsStrictMode: false,\n\t\t\tmaxTokensField: \"max_tokens\",\n\t\t},\n\t};\n}\n\nexport interface LlamaProviderController {\n\tprovider: Provider<\"openai-completions\">;\n\tsetCatalog(models: readonly LlamaModelInfo[], serverUrl: string): void;\n}\n\nexport function createLlamaProvider(): LlamaProviderController {\n\tlet models: readonly Model<\"openai-completions\">[] = [];\n\n\tconst setCatalog = (catalog: readonly LlamaModelInfo[], serverUrl: string): void => {\n\t\tmodels = catalog.filter((model) => model.status.value === \"loaded\").map((model) => toPiModel(model, serverUrl));\n\t};\n\n\tconst provider: Provider<\"openai-completions\"> = {\n\t\tid: LLAMA_PROVIDER_ID,\n\t\tname: \"llama.cpp\",\n\t\tbaseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname: \"llama.cpp server\",\n\t\t\t\tlogin: async (interaction): Promise<ApiKeyCredential> => {\n\t\t\t\t\tconst enteredUrl = await interaction.prompt({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tmessage: \"llama.cpp server URL\",\n\t\t\t\t\t\tplaceholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t});\n\t\t\t\t\tconst serverUrl = normalizeLlamaServerUrl(\n\t\t\t\t\t\tenteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t);\n\t\t\t\t\tconst apiKey = (\n\t\t\t\t\t\tawait interaction.prompt({\n\t\t\t\t\t\t\ttype: \"secret\",\n\t\t\t\t\t\t\tmessage: \"API key (optional)\",\n\t\t\t\t\t\t})\n\t\t\t\t\t).trim();\n\t\t\t\t\tawait new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal });\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"api_key\",\n\t\t\t\t\t\tkey: apiKey || undefined,\n\t\t\t\t\t\tenv: { LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcheck: async ({ ctx, credential }) => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\treturn serverUrl\n\t\t\t\t\t\t? { type: \"api_key\", source: credential ? \"stored credential\" : \"LLAMA_BASE_URL\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ ctx, credential }): Promise<AuthResult | undefined> => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\tif (!serverUrl) return undefined;\n\t\t\t\t\tconst apiKey = credential?.key ?? (await ctx.env(\"LLAMA_API_KEY\")) ?? \"local\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tauth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) },\n\t\t\t\t\t\tenv: { ...credential?.env, LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t\tsource: credential ? \"stored credential\" : \"LLAMA_BASE_URL\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext): Promise<void> => {\n\t\t\tif (context.stored) {\n\t\t\t\tconst restored = context.stored.models.filter(\n\t\t\t\t\t(model): model is Model<\"openai-completions\"> =>\n\t\t\t\t\t\tmodel.provider === LLAMA_PROVIDER_ID && model.api === \"openai-completions\",\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\t!(await context.publish({\n\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\tmodels = restored;\n\t\t\t\t\t\t},\n\t\t\t\t\t}))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!context.allowNetwork || context.signal.aborted || context.credential?.type !== \"api_key\") return;\n\t\t\tconst serverUrl = credentialServerUrl(context.credential);\n\t\t\tif (!serverUrl) return;\n\t\t\tconst catalog = await new LlamaClient(serverUrl, context.credential.key).list({ signal: context.signal });\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst refreshed = catalog\n\t\t\t\t.filter((model) => model.status.value === \"loaded\")\n\t\t\t\t.map((model) => toPiModel(model, serverUrl));\n\t\t\tawait context.publish({\n\t\t\t\tpersist: { models: refreshed, checkedAt: Date.now() },\n\t\t\t\tupdate: () => {\n\t\t\t\t\tmodels = refreshed;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tstream: (model, context, options) => stream(model, context, options as ProviderStreamOptions | undefined),\n\t\tstreamSimple: (model, context, options) => streamSimple(model, context, options),\n\t};\n\n\treturn { provider, setCatalog };\n}\n"]}
@@ -85,19 +85,33 @@ export function createLlamaProvider() {
85
85
  },
86
86
  getModels: () => models,
87
87
  refreshModels: async (context) => {
88
- const stored = await context.store.read();
89
- if (stored) {
90
- models = stored.models.filter((model) => model.provider === LLAMA_PROVIDER_ID && model.api === "openai-completions");
88
+ if (context.stored) {
89
+ const restored = context.stored.models.filter((model) => model.provider === LLAMA_PROVIDER_ID && model.api === "openai-completions");
90
+ if (!(await context.publish({
91
+ update: () => {
92
+ models = restored;
93
+ },
94
+ }))) {
95
+ return;
96
+ }
91
97
  }
92
- if (!context.allowNetwork || context.signal?.aborted || context.credential?.type !== "api_key")
98
+ if (!context.allowNetwork || context.signal.aborted || context.credential?.type !== "api_key")
93
99
  return;
94
100
  const serverUrl = credentialServerUrl(context.credential);
95
101
  if (!serverUrl)
96
102
  return;
97
103
  const catalog = await new LlamaClient(serverUrl, context.credential.key).list({ signal: context.signal });
98
- setCatalog(catalog, serverUrl);
99
- if (!context.signal?.aborted)
100
- await context.store.write({ models, checkedAt: Date.now() });
104
+ if (context.signal.aborted)
105
+ return;
106
+ const refreshed = catalog
107
+ .filter((model) => model.status.value === "loaded")
108
+ .map((model) => toPiModel(model, serverUrl));
109
+ await context.publish({
110
+ persist: { models: refreshed, checkedAt: Date.now() },
111
+ update: () => {
112
+ models = refreshed;
113
+ },
114
+ });
101
115
  },
102
116
  stream: (model, context, options) => stream(model, context, options),
103
117
  streamSimple: (model, context, options) => streamSimple(model, context, options),
@@ -1 +1 @@
1
- {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,WAAW,EAAuB,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAE3G,MAAM,CAAC,MAAM,iBAAiB,GAAG,WAAW,CAAC;AAC7C,MAAM,CAAC,MAAM,wBAAwB,GAAG,uBAAuB,CAAC;AAChE,SAAS,mBAAmB,CAAC,UAAwC,EAAsB;IAC1F,MAAM,KAAK,GAAG,UAAU,EAAE,GAAG,EAAE,cAAc,CAAC;IAC9C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,uBAAuB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC9F;AAED,KAAK,UAAU,gBAAgB,CAC9B,GAAgB,EAChB,UAAwC,EACV;IAC9B,MAAM,UAAU,GAAG,mBAAmB,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC;IAChG,OAAO,UAAU,CAAC,CAAC,CAAC,uBA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,KAAK,CAAC,QAAQ,KAAK,iBAAiB,IAAI,KAAK,CAAC,GAAG,KAAK,oBAAoB,CAC3E,CAAC;YACH,CAAC;YAED,IAAI,CAAC,OAAO,CAAC,YAAY,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,IAAI,OAAO,CAAC,UAAU,EAAE,IAAI,KAAK,SAAS;gBAAE,OAAO;YACvG,MAAM,SAAS,GAAG,mBAAmB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;YAC1D,IAAI,CAAC,SAAS;gBAAE,OAAO;YACvB,MAAM,OAAO,GAAG,MAAM,IAAI,WAAW,CAAC,SAAS,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YAC1G,UAAU,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;YAC/B,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO;gBAAE,MAAM,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAAA,CAC3F;QACD,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAA4C,CAAC;QACzG,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KAChF,CAAC;IAEF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;AAAA,CAChC","sourcesContent":["import type {\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tModel,\n\tProvider,\n\tProviderStreamOptions,\n\tRefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { stream, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { LlamaClient, type LlamaModelInfo, llamaInferenceUrl, normalizeLlamaServerUrl } from \"./client.ts\";\n\nexport const LLAMA_PROVIDER_ID = \"llama.cpp\";\nexport const DEFAULT_LLAMA_SERVER_URL = \"http://127.0.0.1:8080\";\nfunction credentialServerUrl(credential: ApiKeyCredential | undefined): string | undefined {\n\tconst value = credential?.env?.LLAMA_BASE_URL;\n\treturn typeof value === \"string\" && value.trim() ? normalizeLlamaServerUrl(value) : undefined;\n}\n\nasync function resolveServerUrl(\n\tctx: AuthContext,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<string | undefined> {\n\tconst configured = credentialServerUrl(credential) ?? (await ctx.env(\"LLAMA_BASE_URL\"))?.trim();\n\treturn configured ? normalizeLlamaServerUrl(configured) : undefined;\n}\n\nfunction toPiModel(model: LlamaModelInfo, serverUrl: string): Model<\"openai-completions\"> {\n\tconst reportedContextWindow = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tconst contextWindow = reportedContextWindow && reportedContextWindow > 0 ? reportedContextWindow : 128000;\n\treturn {\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"openai-completions\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: llamaInferenceUrl(serverUrl),\n\t\treasoning: false,\n\t\tinput: model.architecture?.input_modalities?.includes(\"image\") ? [\"text\", \"image\"] : [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow,\n\t\tmaxTokens: contextWindow,\n\t\tcompat: {\n\t\t\tsupportsStore: false,\n\t\t\tsupportsDeveloperRole: false,\n\t\t\tsupportsReasoningEffort: false,\n\t\t\tsupportsUsageInStreaming: true,\n\t\t\tsupportsStrictMode: false,\n\t\t\tmaxTokensField: \"max_tokens\",\n\t\t},\n\t};\n}\n\nexport interface LlamaProviderController {\n\tprovider: Provider<\"openai-completions\">;\n\tsetCatalog(models: readonly LlamaModelInfo[], serverUrl: string): void;\n}\n\nexport function createLlamaProvider(): LlamaProviderController {\n\tlet models: readonly Model<\"openai-completions\">[] = [];\n\n\tconst setCatalog = (catalog: readonly LlamaModelInfo[], serverUrl: string): void => {\n\t\tmodels = catalog.filter((model) => model.status.value === \"loaded\").map((model) => toPiModel(model, serverUrl));\n\t};\n\n\tconst provider: Provider<\"openai-completions\"> = {\n\t\tid: LLAMA_PROVIDER_ID,\n\t\tname: \"llama.cpp\",\n\t\tbaseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname: \"llama.cpp server\",\n\t\t\t\tlogin: async (interaction): Promise<ApiKeyCredential> => {\n\t\t\t\t\tconst enteredUrl = await interaction.prompt({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tmessage: \"llama.cpp server URL\",\n\t\t\t\t\t\tplaceholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t});\n\t\t\t\t\tconst serverUrl = normalizeLlamaServerUrl(\n\t\t\t\t\t\tenteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t);\n\t\t\t\t\tconst apiKey = (\n\t\t\t\t\t\tawait interaction.prompt({\n\t\t\t\t\t\t\ttype: \"secret\",\n\t\t\t\t\t\t\tmessage: \"API key (optional)\",\n\t\t\t\t\t\t})\n\t\t\t\t\t).trim();\n\t\t\t\t\tawait new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal });\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"api_key\",\n\t\t\t\t\t\tkey: apiKey || undefined,\n\t\t\t\t\t\tenv: { LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcheck: async ({ ctx, credential }) => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\treturn serverUrl\n\t\t\t\t\t\t? { type: \"api_key\", source: credential ? \"stored credential\" : \"LLAMA_BASE_URL\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ ctx, credential }): Promise<AuthResult | undefined> => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\tif (!serverUrl) return undefined;\n\t\t\t\t\tconst apiKey = credential?.key ?? (await ctx.env(\"LLAMA_API_KEY\")) ?? \"local\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tauth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) },\n\t\t\t\t\t\tenv: { ...credential?.env, LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t\tsource: credential ? \"stored credential\" : \"LLAMA_BASE_URL\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext): Promise<void> => {\n\t\t\tconst stored = await context.store.read();\n\t\t\tif (stored) {\n\t\t\t\tmodels = stored.models.filter(\n\t\t\t\t\t(model): model is Model<\"openai-completions\"> =>\n\t\t\t\t\t\tmodel.provider === LLAMA_PROVIDER_ID && model.api === \"openai-completions\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!context.allowNetwork || context.signal?.aborted || context.credential?.type !== \"api_key\") return;\n\t\t\tconst serverUrl = credentialServerUrl(context.credential);\n\t\t\tif (!serverUrl) return;\n\t\t\tconst catalog = await new LlamaClient(serverUrl, context.credential.key).list({ signal: context.signal });\n\t\t\tsetCatalog(catalog, serverUrl);\n\t\t\tif (!context.signal?.aborted) await context.store.write({ models, checkedAt: Date.now() });\n\t\t},\n\t\tstream: (model, context, options) => stream(model, context, options as ProviderStreamOptions | undefined),\n\t\tstreamSimple: (model, context, options) => streamSimple(model, context, options),\n\t};\n\n\treturn { provider, setCatalog };\n}\n"]}
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,MAAM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AAI,WAAW,CAAC,SAAS,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YAC1G,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO;YACnC,MAAM,SAAS,GAAG,OAAO;iBACvB,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC;iBAClD,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;YAC9C,MAAM,OAAO,CAAC,OAAO,CAAC;gBACrB,OAAO,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE;gBACrD,MAAM,EAAE,GAAG,EAAE,CAAC;oBACb,MAAM,GAAG,SAAS,CAAC;gBAAA,CACnB;aACD,CAAC,CAAC;QAAA,CACH;QACD,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAA4C,CAAC;QACzG,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KAChF,CAAC;IAEF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;AAAA,CAChC","sourcesContent":["import type {\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tModel,\n\tProvider,\n\tProviderStreamOptions,\n\tRefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { stream, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { LlamaClient, type LlamaModelInfo, llamaInferenceUrl, normalizeLlamaServerUrl } from \"./client.ts\";\n\nexport const LLAMA_PROVIDER_ID = \"llama.cpp\";\nexport const DEFAULT_LLAMA_SERVER_URL = \"http://127.0.0.1:8080\";\nfunction credentialServerUrl(credential: ApiKeyCredential | undefined): string | undefined {\n\tconst value = credential?.env?.LLAMA_BASE_URL;\n\treturn typeof value === \"string\" && value.trim() ? normalizeLlamaServerUrl(value) : undefined;\n}\n\nasync function resolveServerUrl(\n\tctx: AuthContext,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<string | undefined> {\n\tconst configured = credentialServerUrl(credential) ?? (await ctx.env(\"LLAMA_BASE_URL\"))?.trim();\n\treturn configured ? normalizeLlamaServerUrl(configured) : undefined;\n}\n\nfunction toPiModel(model: LlamaModelInfo, serverUrl: string): Model<\"openai-completions\"> {\n\tconst reportedContextWindow = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tconst contextWindow = reportedContextWindow && reportedContextWindow > 0 ? reportedContextWindow : 128000;\n\treturn {\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"openai-completions\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: llamaInferenceUrl(serverUrl),\n\t\treasoning: false,\n\t\tinput: model.architecture?.input_modalities?.includes(\"image\") ? [\"text\", \"image\"] : [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow,\n\t\tmaxTokens: contextWindow,\n\t\tcompat: {\n\t\t\tsupportsStore: false,\n\t\t\tsupportsDeveloperRole: false,\n\t\t\tsupportsReasoningEffort: false,\n\t\t\tsupportsUsageInStreaming: true,\n\t\t\tsupportsStrictMode: false,\n\t\t\tmaxTokensField: \"max_tokens\",\n\t\t},\n\t};\n}\n\nexport interface LlamaProviderController {\n\tprovider: Provider<\"openai-completions\">;\n\tsetCatalog(models: readonly LlamaModelInfo[], serverUrl: string): void;\n}\n\nexport function createLlamaProvider(): LlamaProviderController {\n\tlet models: readonly Model<\"openai-completions\">[] = [];\n\n\tconst setCatalog = (catalog: readonly LlamaModelInfo[], serverUrl: string): void => {\n\t\tmodels = catalog.filter((model) => model.status.value === \"loaded\").map((model) => toPiModel(model, serverUrl));\n\t};\n\n\tconst provider: Provider<\"openai-completions\"> = {\n\t\tid: LLAMA_PROVIDER_ID,\n\t\tname: \"llama.cpp\",\n\t\tbaseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname: \"llama.cpp server\",\n\t\t\t\tlogin: async (interaction): Promise<ApiKeyCredential> => {\n\t\t\t\t\tconst enteredUrl = await interaction.prompt({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tmessage: \"llama.cpp server URL\",\n\t\t\t\t\t\tplaceholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t});\n\t\t\t\t\tconst serverUrl = normalizeLlamaServerUrl(\n\t\t\t\t\t\tenteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t);\n\t\t\t\t\tconst apiKey = (\n\t\t\t\t\t\tawait interaction.prompt({\n\t\t\t\t\t\t\ttype: \"secret\",\n\t\t\t\t\t\t\tmessage: \"API key (optional)\",\n\t\t\t\t\t\t})\n\t\t\t\t\t).trim();\n\t\t\t\t\tawait new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal });\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"api_key\",\n\t\t\t\t\t\tkey: apiKey || undefined,\n\t\t\t\t\t\tenv: { LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcheck: async ({ ctx, credential }) => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\treturn serverUrl\n\t\t\t\t\t\t? { type: \"api_key\", source: credential ? \"stored credential\" : \"LLAMA_BASE_URL\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ ctx, credential }): Promise<AuthResult | undefined> => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\tif (!serverUrl) return undefined;\n\t\t\t\t\tconst apiKey = credential?.key ?? (await ctx.env(\"LLAMA_API_KEY\")) ?? \"local\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tauth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) },\n\t\t\t\t\t\tenv: { ...credential?.env, LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t\tsource: credential ? \"stored credential\" : \"LLAMA_BASE_URL\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext): Promise<void> => {\n\t\t\tif (context.stored) {\n\t\t\t\tconst restored = context.stored.models.filter(\n\t\t\t\t\t(model): model is Model<\"openai-completions\"> =>\n\t\t\t\t\t\tmodel.provider === LLAMA_PROVIDER_ID && model.api === \"openai-completions\",\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\t!(await context.publish({\n\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\tmodels = restored;\n\t\t\t\t\t\t},\n\t\t\t\t\t}))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!context.allowNetwork || context.signal.aborted || context.credential?.type !== \"api_key\") return;\n\t\t\tconst serverUrl = credentialServerUrl(context.credential);\n\t\t\tif (!serverUrl) return;\n\t\t\tconst catalog = await new LlamaClient(serverUrl, context.credential.key).list({ signal: context.signal });\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst refreshed = catalog\n\t\t\t\t.filter((model) => model.status.value === \"loaded\")\n\t\t\t\t.map((model) => toPiModel(model, serverUrl));\n\t\t\tawait context.publish({\n\t\t\t\tpersist: { models: refreshed, checkedAt: Date.now() },\n\t\t\t\tupdate: () => {\n\t\t\t\t\tmodels = refreshed;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tstream: (model, context, options) => stream(model, context, options as ProviderStreamOptions | undefined),\n\t\tstreamSimple: (model, context, options) => streamSimple(model, context, options),\n\t};\n\n\treturn { provider, setCatalog };\n}\n"]}