@build-astron-co/nimbus 0.2.0 → 0.4.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 (469) hide show
  1. package/bin/nimbus +26 -10
  2. package/bin/nimbus.cmd +41 -0
  3. package/bin/nimbus.mjs +70 -0
  4. package/completions/nimbus.bash +38 -0
  5. package/completions/nimbus.fish +48 -0
  6. package/completions/nimbus.zsh +81 -0
  7. package/dist/src/agent/compaction-agent.js +215 -0
  8. package/dist/src/agent/context-manager.js +385 -0
  9. package/dist/src/agent/context.js +322 -0
  10. package/dist/src/agent/deploy-preview.js +395 -0
  11. package/dist/src/agent/expand-files.js +95 -0
  12. package/dist/src/agent/index.js +18 -0
  13. package/dist/src/agent/loop.js +1535 -0
  14. package/dist/src/agent/modes.js +347 -0
  15. package/dist/src/agent/permissions.js +396 -0
  16. package/dist/src/agent/subagents/base.js +67 -0
  17. package/dist/src/agent/subagents/cost.js +45 -0
  18. package/dist/src/agent/subagents/explore.js +36 -0
  19. package/dist/src/agent/subagents/general.js +41 -0
  20. package/dist/src/agent/subagents/index.js +88 -0
  21. package/dist/src/agent/subagents/infra.js +52 -0
  22. package/dist/src/agent/subagents/security.js +60 -0
  23. package/dist/src/agent/system-prompt.js +860 -0
  24. package/dist/src/app.js +152 -0
  25. package/dist/src/audit/activity-log.js +209 -0
  26. package/dist/src/audit/compliance-checker.js +419 -0
  27. package/dist/src/audit/cost-tracker.js +231 -0
  28. package/dist/src/audit/index.js +10 -0
  29. package/dist/src/audit/security-scanner.js +490 -0
  30. package/dist/src/auth/guard.js +64 -0
  31. package/dist/src/auth/index.js +19 -0
  32. package/dist/src/auth/keychain.js +79 -0
  33. package/dist/src/auth/oauth.js +389 -0
  34. package/dist/src/auth/providers.js +415 -0
  35. package/dist/src/auth/sso.js +87 -0
  36. package/dist/src/auth/store.js +424 -0
  37. package/dist/src/auth/types.js +5 -0
  38. package/dist/src/cli/index.js +8 -0
  39. package/dist/src/cli/init.js +1048 -0
  40. package/dist/src/cli/openapi-spec.js +346 -0
  41. package/dist/src/cli/run.js +505 -0
  42. package/dist/src/cli/serve-auth.js +56 -0
  43. package/dist/src/cli/serve.js +432 -0
  44. package/dist/src/cli/web.js +50 -0
  45. package/dist/src/cli.js +1574 -0
  46. package/dist/src/clients/core-engine-client.js +156 -0
  47. package/dist/src/clients/enterprise-client.js +246 -0
  48. package/dist/src/clients/generator-client.js +219 -0
  49. package/dist/src/clients/git-client.js +367 -0
  50. package/dist/src/clients/github-client.js +229 -0
  51. package/dist/src/clients/helm-client.js +299 -0
  52. package/dist/src/clients/index.js +18 -0
  53. package/dist/src/clients/k8s-client.js +270 -0
  54. package/dist/src/clients/llm-client.js +119 -0
  55. package/dist/src/clients/rest-client.js +104 -0
  56. package/dist/src/clients/service-discovery.js +35 -0
  57. package/dist/src/clients/terraform-client.js +302 -0
  58. package/dist/src/clients/tools-client.js +1227 -0
  59. package/dist/src/clients/ws-client.js +93 -0
  60. package/dist/src/commands/alias.js +91 -0
  61. package/dist/src/commands/analyze/index.js +313 -0
  62. package/dist/src/commands/apply/helm.js +375 -0
  63. package/dist/src/commands/apply/index.js +176 -0
  64. package/dist/src/commands/apply/k8s.js +350 -0
  65. package/dist/src/commands/apply/terraform.js +465 -0
  66. package/dist/src/commands/ask.js +137 -0
  67. package/dist/src/commands/audit/index.js +322 -0
  68. package/dist/src/commands/auth-cloud.js +345 -0
  69. package/dist/src/commands/auth-list.js +112 -0
  70. package/dist/src/commands/auth-profile.js +104 -0
  71. package/dist/src/commands/auth-refresh.js +161 -0
  72. package/dist/src/commands/auth-status.js +122 -0
  73. package/dist/src/commands/aws/ec2.js +402 -0
  74. package/dist/src/commands/aws/iam.js +304 -0
  75. package/dist/src/commands/aws/index.js +108 -0
  76. package/dist/src/commands/aws/lambda.js +317 -0
  77. package/dist/src/commands/aws/rds.js +345 -0
  78. package/dist/src/commands/aws/s3.js +346 -0
  79. package/dist/src/commands/aws/vpc.js +302 -0
  80. package/dist/src/commands/aws-discover.js +413 -0
  81. package/dist/src/commands/aws-terraform.js +618 -0
  82. package/dist/src/commands/azure/aks.js +305 -0
  83. package/dist/src/commands/azure/functions.js +200 -0
  84. package/dist/src/commands/azure/index.js +93 -0
  85. package/dist/src/commands/azure/storage.js +378 -0
  86. package/dist/src/commands/azure/vm.js +291 -0
  87. package/dist/src/commands/billing/index.js +224 -0
  88. package/dist/src/commands/chat.js +259 -0
  89. package/dist/src/commands/completions.js +255 -0
  90. package/dist/src/commands/config.js +291 -0
  91. package/dist/src/commands/cost/cloud-cost-estimator.js +211 -0
  92. package/dist/src/commands/cost/estimator.js +73 -0
  93. package/dist/src/commands/cost/index.js +625 -0
  94. package/dist/src/commands/cost/parsers/terraform.js +234 -0
  95. package/dist/src/commands/cost/parsers/types.js +4 -0
  96. package/dist/src/commands/cost/pricing/aws.js +501 -0
  97. package/dist/src/commands/cost/pricing/azure.js +462 -0
  98. package/dist/src/commands/cost/pricing/gcp.js +359 -0
  99. package/dist/src/commands/cost/pricing/index.js +24 -0
  100. package/dist/src/commands/demo.js +196 -0
  101. package/dist/src/commands/deploy.js +215 -0
  102. package/dist/src/commands/doctor.js +1291 -0
  103. package/dist/src/commands/drift/index.js +674 -0
  104. package/dist/src/commands/explain.js +235 -0
  105. package/dist/src/commands/export.js +120 -0
  106. package/dist/src/commands/feedback.js +319 -0
  107. package/dist/src/commands/fix.js +263 -0
  108. package/dist/src/commands/fs/index.js +338 -0
  109. package/dist/src/commands/gcp/compute.js +266 -0
  110. package/dist/src/commands/gcp/functions.js +221 -0
  111. package/dist/src/commands/gcp/gke.js +357 -0
  112. package/dist/src/commands/gcp/iam.js +295 -0
  113. package/dist/src/commands/gcp/index.js +105 -0
  114. package/dist/src/commands/gcp/storage.js +232 -0
  115. package/dist/src/commands/generate-helm.js +1026 -0
  116. package/dist/src/commands/generate-k8s.js +1263 -0
  117. package/dist/src/commands/generate-terraform.js +1058 -0
  118. package/dist/src/commands/gh/index.js +663 -0
  119. package/dist/src/commands/git/index.js +1208 -0
  120. package/dist/src/commands/helm/index.js +985 -0
  121. package/dist/src/commands/help.js +639 -0
  122. package/dist/src/commands/history.js +120 -0
  123. package/dist/src/commands/import.js +782 -0
  124. package/dist/src/commands/incident.js +144 -0
  125. package/dist/src/commands/index.js +109 -0
  126. package/dist/src/commands/init.js +955 -0
  127. package/dist/src/commands/k8s/index.js +979 -0
  128. package/dist/src/commands/login.js +588 -0
  129. package/dist/src/commands/logout.js +61 -0
  130. package/dist/src/commands/logs.js +160 -0
  131. package/dist/src/commands/onboarding.js +382 -0
  132. package/dist/src/commands/pipeline.js +153 -0
  133. package/dist/src/commands/plan/display.js +216 -0
  134. package/dist/src/commands/plan/index.js +525 -0
  135. package/dist/src/commands/plugin.js +325 -0
  136. package/dist/src/commands/preview.js +356 -0
  137. package/dist/src/commands/profile.js +297 -0
  138. package/dist/src/commands/questionnaire.js +1021 -0
  139. package/dist/src/commands/resume.js +35 -0
  140. package/dist/src/commands/rollback.js +259 -0
  141. package/dist/src/commands/rollout.js +74 -0
  142. package/dist/src/commands/runbook.js +307 -0
  143. package/dist/src/commands/schedule.js +202 -0
  144. package/dist/src/commands/status.js +213 -0
  145. package/dist/src/commands/team/index.js +309 -0
  146. package/dist/src/commands/team-context.js +200 -0
  147. package/dist/src/commands/template.js +204 -0
  148. package/dist/src/commands/tf/index.js +989 -0
  149. package/dist/src/commands/upgrade.js +515 -0
  150. package/dist/src/commands/usage/index.js +118 -0
  151. package/dist/src/commands/version.js +145 -0
  152. package/dist/src/commands/watch.js +127 -0
  153. package/dist/src/compat/index.js +2 -0
  154. package/dist/src/compat/runtime.js +10 -0
  155. package/dist/src/compat/sqlite.js +144 -0
  156. package/dist/src/config/index.js +6 -0
  157. package/dist/src/config/manager.js +469 -0
  158. package/dist/src/config/mode-store.js +57 -0
  159. package/dist/src/config/profiles.js +66 -0
  160. package/dist/src/config/safety-policy.js +251 -0
  161. package/dist/src/config/schema.js +107 -0
  162. package/dist/src/config/types.js +311 -0
  163. package/dist/src/config/workspace-state.js +38 -0
  164. package/dist/src/context/context-db.js +138 -0
  165. package/dist/src/demo/index.js +295 -0
  166. package/dist/src/demo/scenarios/full-journey.js +226 -0
  167. package/dist/src/demo/scenarios/getting-started.js +124 -0
  168. package/dist/src/demo/scenarios/helm-release.js +334 -0
  169. package/dist/src/demo/scenarios/k8s-deployment.js +190 -0
  170. package/dist/src/demo/scenarios/terraform-vpc.js +167 -0
  171. package/dist/src/demo/types.js +6 -0
  172. package/dist/src/engine/cost-estimator.js +334 -0
  173. package/dist/src/engine/diagram-generator.js +192 -0
  174. package/dist/src/engine/drift-detector.js +688 -0
  175. package/dist/src/engine/executor.js +832 -0
  176. package/dist/src/engine/index.js +39 -0
  177. package/dist/src/engine/orchestrator.js +436 -0
  178. package/dist/src/engine/planner.js +616 -0
  179. package/dist/src/engine/safety.js +609 -0
  180. package/dist/src/engine/verifier.js +664 -0
  181. package/dist/src/enterprise/audit.js +241 -0
  182. package/dist/src/enterprise/auth.js +189 -0
  183. package/dist/src/enterprise/billing.js +512 -0
  184. package/dist/src/enterprise/index.js +16 -0
  185. package/dist/src/enterprise/teams.js +315 -0
  186. package/dist/src/generator/best-practices.js +1375 -0
  187. package/dist/src/generator/helm.js +495 -0
  188. package/dist/src/generator/index.js +11 -0
  189. package/dist/src/generator/intent-parser.js +420 -0
  190. package/dist/src/generator/kubernetes.js +773 -0
  191. package/dist/src/generator/terraform.js +1472 -0
  192. package/dist/src/history/index.js +6 -0
  193. package/dist/src/history/manager.js +199 -0
  194. package/dist/src/history/types.js +6 -0
  195. package/dist/src/hooks/config.js +318 -0
  196. package/dist/src/hooks/engine.js +317 -0
  197. package/dist/src/hooks/index.js +2 -0
  198. package/dist/src/llm/auth-bridge.js +157 -0
  199. package/dist/src/llm/circuit-breaker.js +116 -0
  200. package/dist/src/llm/config-loader.js +172 -0
  201. package/dist/src/llm/cost-calculator.js +137 -0
  202. package/dist/src/llm/index.js +7 -0
  203. package/dist/src/llm/model-aliases.js +99 -0
  204. package/dist/src/llm/provider-registry.js +57 -0
  205. package/dist/src/llm/providers/anthropic.js +430 -0
  206. package/dist/src/llm/providers/bedrock.js +409 -0
  207. package/dist/src/llm/providers/google.js +344 -0
  208. package/dist/src/llm/providers/ollama.js +661 -0
  209. package/dist/src/llm/providers/openai-compatible.js +289 -0
  210. package/dist/src/llm/providers/openai.js +284 -0
  211. package/dist/src/llm/providers/openrouter.js +293 -0
  212. package/dist/src/llm/router.js +844 -0
  213. package/dist/src/llm/types.js +69 -0
  214. package/dist/src/lsp/client.js +239 -0
  215. package/dist/src/lsp/languages.js +95 -0
  216. package/dist/src/lsp/manager.js +243 -0
  217. package/dist/src/mcp/client.js +289 -0
  218. package/dist/src/mcp/index.js +5 -0
  219. package/dist/src/mcp/manager.js +113 -0
  220. package/dist/src/nimbus.js +212 -0
  221. package/dist/src/plugins/index.js +13 -0
  222. package/dist/src/plugins/loader.js +280 -0
  223. package/dist/src/plugins/manager.js +282 -0
  224. package/dist/src/plugins/types.js +23 -0
  225. package/dist/src/scanners/cicd-scanner.js +230 -0
  226. package/dist/src/scanners/cloud-scanner.js +415 -0
  227. package/dist/src/scanners/framework-scanner.js +430 -0
  228. package/dist/src/scanners/iac-scanner.js +350 -0
  229. package/dist/src/scanners/index.js +454 -0
  230. package/dist/src/scanners/language-scanner.js +258 -0
  231. package/dist/src/scanners/package-manager-scanner.js +252 -0
  232. package/dist/src/scanners/types.js +6 -0
  233. package/dist/src/sessions/manager.js +395 -0
  234. package/dist/src/sessions/types.js +4 -0
  235. package/dist/src/sharing/sync.js +238 -0
  236. package/dist/src/sharing/viewer.js +131 -0
  237. package/dist/src/snapshots/index.js +1 -0
  238. package/dist/src/snapshots/manager.js +432 -0
  239. package/dist/src/state/artifacts.js +94 -0
  240. package/dist/src/state/audit.js +73 -0
  241. package/dist/src/state/billing.js +126 -0
  242. package/dist/src/state/checkpoints.js +81 -0
  243. package/dist/src/state/config.js +58 -0
  244. package/dist/src/state/conversations.js +7 -0
  245. package/dist/src/state/credentials.js +96 -0
  246. package/dist/src/state/db.js +53 -0
  247. package/dist/src/state/index.js +23 -0
  248. package/dist/src/state/messages.js +76 -0
  249. package/dist/src/state/projects.js +92 -0
  250. package/dist/src/state/schema.js +233 -0
  251. package/dist/src/state/sessions.js +79 -0
  252. package/dist/src/state/teams.js +131 -0
  253. package/dist/src/telemetry.js +91 -0
  254. package/dist/src/tools/aws-ops.js +747 -0
  255. package/dist/src/tools/azure-ops.js +491 -0
  256. package/dist/src/tools/file-ops.js +451 -0
  257. package/dist/src/tools/gcp-ops.js +559 -0
  258. package/dist/src/tools/git-ops.js +557 -0
  259. package/dist/src/tools/github-ops.js +460 -0
  260. package/dist/src/tools/helm-ops.js +634 -0
  261. package/dist/src/tools/index.js +16 -0
  262. package/dist/src/tools/k8s-ops.js +579 -0
  263. package/dist/src/tools/schemas/converter.js +129 -0
  264. package/dist/src/tools/schemas/devops.js +3319 -0
  265. package/dist/src/tools/schemas/index.js +19 -0
  266. package/dist/src/tools/schemas/standard.js +966 -0
  267. package/dist/src/tools/schemas/types.js +409 -0
  268. package/dist/src/tools/spawn-exec.js +109 -0
  269. package/dist/src/tools/terraform-ops.js +627 -0
  270. package/dist/src/types/config.js +1 -0
  271. package/dist/src/types/drift.js +4 -0
  272. package/dist/src/types/enterprise.js +5 -0
  273. package/dist/src/types/index.js +14 -0
  274. package/dist/src/types/plan.js +1 -0
  275. package/dist/src/types/request.js +1 -0
  276. package/dist/src/types/response.js +1 -0
  277. package/dist/src/types/service.js +1 -0
  278. package/dist/src/ui/App.js +1672 -0
  279. package/dist/src/ui/DeployPreview.js +60 -0
  280. package/dist/src/ui/FileDiffModal.js +108 -0
  281. package/dist/src/ui/Header.js +46 -0
  282. package/dist/src/ui/HelpModal.js +9 -0
  283. package/dist/src/ui/InputBox.js +408 -0
  284. package/dist/src/ui/MessageList.js +795 -0
  285. package/dist/src/ui/PermissionPrompt.js +72 -0
  286. package/dist/src/ui/StatusBar.js +109 -0
  287. package/dist/src/ui/TerminalPane.js +31 -0
  288. package/dist/src/ui/ToolCallDisplay.js +303 -0
  289. package/dist/src/ui/TreePane.js +83 -0
  290. package/dist/src/ui/chat-ui.js +721 -0
  291. package/dist/src/ui/index.js +11 -0
  292. package/dist/src/ui/ink/index.js +1325 -0
  293. package/dist/src/ui/streaming.js +137 -0
  294. package/dist/src/ui/theme.js +78 -0
  295. package/dist/src/ui/types.js +7 -0
  296. package/dist/src/utils/analytics.js +61 -0
  297. package/dist/src/utils/cost-warning.js +25 -0
  298. package/dist/src/utils/env.js +42 -0
  299. package/dist/src/utils/errors.js +54 -0
  300. package/dist/src/utils/event-bus.js +22 -0
  301. package/dist/src/utils/index.js +16 -0
  302. package/dist/src/utils/logger.js +150 -0
  303. package/dist/src/utils/rate-limiter.js +90 -0
  304. package/dist/src/utils/service-auth.js +36 -0
  305. package/dist/src/utils/validation.js +39 -0
  306. package/dist/src/version.js +3 -0
  307. package/dist/src/watcher/index.js +192 -0
  308. package/dist/src/wizard/approval.js +275 -0
  309. package/dist/src/wizard/index.js +13 -0
  310. package/dist/src/wizard/prompts.js +273 -0
  311. package/dist/src/wizard/types.js +4 -0
  312. package/dist/src/wizard/ui.js +453 -0
  313. package/dist/src/wizard/wizard.js +227 -0
  314. package/package.json +31 -23
  315. package/src/__tests__/alias.test.ts +133 -0
  316. package/src/__tests__/app.test.ts +1 -1
  317. package/src/__tests__/audit.test.ts +1 -1
  318. package/src/__tests__/circuit-breaker.test.ts +1 -1
  319. package/src/__tests__/cli-run.test.ts +237 -1
  320. package/src/__tests__/compat-sqlite.test.ts +68 -0
  321. package/src/__tests__/context-manager.test.ts +131 -1
  322. package/src/__tests__/context.test.ts +1 -1
  323. package/src/__tests__/devops-terminal-gaps.test.ts +718 -0
  324. package/src/__tests__/doctor.test.ts +48 -0
  325. package/src/__tests__/enterprise.test.ts +1 -1
  326. package/src/__tests__/export.test.ts +236 -0
  327. package/src/__tests__/gap-11-18-20.test.ts +958 -0
  328. package/src/__tests__/generator.test.ts +1 -1
  329. package/src/__tests__/helm-streaming.test.ts +127 -0
  330. package/src/__tests__/hooks.test.ts +1 -1
  331. package/src/__tests__/incident.test.ts +179 -0
  332. package/src/__tests__/init.test.ts +55 -4
  333. package/src/__tests__/intent-parser.test.ts +1 -1
  334. package/src/__tests__/llm-router.test.ts +1 -1
  335. package/src/__tests__/logs.test.ts +107 -0
  336. package/src/__tests__/loop-errors.test.ts +244 -0
  337. package/src/__tests__/lsp.test.ts +1 -1
  338. package/src/__tests__/modes.test.ts +1 -1
  339. package/src/__tests__/perf-optimizations.test.ts +847 -0
  340. package/src/__tests__/permissions.test.ts +1 -1
  341. package/src/__tests__/pipeline.test.ts +50 -0
  342. package/src/__tests__/polish-phase3.test.ts +340 -0
  343. package/src/__tests__/profile.test.ts +237 -0
  344. package/src/__tests__/rollback.test.ts +83 -0
  345. package/src/__tests__/runbook.test.ts +219 -0
  346. package/src/__tests__/schedule.test.ts +206 -0
  347. package/src/__tests__/serve.test.ts +1 -1
  348. package/src/__tests__/sessions.test.ts +96 -1
  349. package/src/__tests__/sharing.test.ts +53 -1
  350. package/src/__tests__/snapshots.test.ts +1 -1
  351. package/src/__tests__/standalone-migration.test.ts +199 -0
  352. package/src/__tests__/state-db.test.ts +1 -1
  353. package/src/__tests__/status.test.ts +158 -0
  354. package/src/__tests__/stream-with-tools.test.ts +71 -25
  355. package/src/__tests__/subagents.test.ts +1 -1
  356. package/src/__tests__/system-prompt.test.ts +82 -3
  357. package/src/__tests__/terminal-gap-v2.test.ts +395 -0
  358. package/src/__tests__/terminal-parity.test.ts +393 -0
  359. package/src/__tests__/tf-apply.test.ts +187 -0
  360. package/src/__tests__/tool-converter.test.ts +1 -1
  361. package/src/__tests__/tool-schemas.test.ts +209 -4
  362. package/src/__tests__/tools.test.ts +4 -3
  363. package/src/__tests__/version-json.test.ts +184 -0
  364. package/src/__tests__/version.test.ts +1 -1
  365. package/src/__tests__/watch.test.ts +129 -0
  366. package/src/agent/compaction-agent.ts +40 -1
  367. package/src/agent/context-manager.ts +67 -3
  368. package/src/agent/deploy-preview.ts +62 -1
  369. package/src/agent/expand-files.ts +108 -0
  370. package/src/agent/loop.ts +1312 -31
  371. package/src/agent/permissions.ts +51 -4
  372. package/src/agent/system-prompt.ts +573 -19
  373. package/src/app.ts +58 -0
  374. package/src/audit/security-scanner.ts +45 -0
  375. package/src/auth/keychain.ts +82 -0
  376. package/src/auth/oauth.ts +15 -5
  377. package/src/cli/init.ts +378 -5
  378. package/src/cli/run.ts +407 -16
  379. package/src/cli/serve.ts +78 -1
  380. package/src/cli/web.ts +10 -6
  381. package/src/cli.ts +312 -1
  382. package/src/clients/service-discovery.ts +30 -25
  383. package/src/commands/alias.ts +100 -0
  384. package/src/commands/audit/index.ts +121 -2
  385. package/src/commands/auth-cloud.ts +113 -0
  386. package/src/commands/auth-refresh.ts +187 -0
  387. package/src/commands/aws-discover.ts +144 -251
  388. package/src/commands/aws-terraform.ts +68 -118
  389. package/src/commands/chat.ts +9 -3
  390. package/src/commands/completions.ts +268 -0
  391. package/src/commands/config.ts +26 -0
  392. package/src/commands/cost/index.ts +218 -2
  393. package/src/commands/deploy.ts +260 -0
  394. package/src/commands/doctor.ts +744 -152
  395. package/src/commands/drift/index.ts +371 -23
  396. package/src/commands/export.ts +146 -0
  397. package/src/commands/generate-k8s.ts +9 -61
  398. package/src/commands/generate-terraform.ts +191 -449
  399. package/src/commands/help.ts +212 -36
  400. package/src/commands/history.ts +8 -1
  401. package/src/commands/incident.ts +166 -0
  402. package/src/commands/init.ts +5 -0
  403. package/src/commands/login.ts +86 -1
  404. package/src/commands/logs.ts +167 -0
  405. package/src/commands/onboarding.ts +211 -34
  406. package/src/commands/pipeline.ts +186 -0
  407. package/src/commands/plugin.ts +398 -0
  408. package/src/commands/profile.ts +342 -0
  409. package/src/commands/questionnaire.ts +0 -98
  410. package/src/commands/resume.ts +26 -34
  411. package/src/commands/rollback.ts +315 -0
  412. package/src/commands/rollout.ts +88 -0
  413. package/src/commands/runbook.ts +346 -0
  414. package/src/commands/schedule.ts +236 -0
  415. package/src/commands/status.ts +252 -0
  416. package/src/commands/team-context.ts +220 -0
  417. package/src/commands/template.ts +58 -57
  418. package/src/commands/tf/index.ts +70 -11
  419. package/src/commands/upgrade.ts +57 -0
  420. package/src/commands/version.ts +54 -50
  421. package/src/commands/watch.ts +153 -0
  422. package/src/compat/runtime.ts +1 -1
  423. package/src/compat/sqlite.ts +75 -5
  424. package/src/config/mode-store.ts +62 -0
  425. package/src/config/profiles.ts +84 -0
  426. package/src/config/types.ts +83 -1
  427. package/src/config/workspace-state.ts +53 -0
  428. package/src/engine/cost-estimator.ts +52 -10
  429. package/src/engine/executor.ts +33 -2
  430. package/src/engine/planner.ts +68 -1
  431. package/src/generator/terraform.ts +8 -0
  432. package/src/history/manager.ts +2 -74
  433. package/src/hooks/engine.ts +5 -4
  434. package/src/llm/cost-calculator.ts +2 -2
  435. package/src/llm/providers/anthropic.ts +50 -21
  436. package/src/llm/router.ts +76 -7
  437. package/src/lsp/languages.ts +3 -0
  438. package/src/lsp/manager.ts +21 -5
  439. package/src/nimbus.ts +37 -18
  440. package/src/sessions/manager.ts +108 -1
  441. package/src/sharing/sync.ts +4 -0
  442. package/src/sharing/viewer.ts +66 -0
  443. package/src/tools/file-ops.ts +22 -0
  444. package/src/tools/schemas/devops.ts +3007 -117
  445. package/src/tools/schemas/standard.ts +5 -1
  446. package/src/tools/schemas/types.ts +31 -1
  447. package/src/tools/spawn-exec.ts +148 -0
  448. package/src/ui/App.tsx +1183 -66
  449. package/src/ui/DeployPreview.tsx +62 -57
  450. package/src/ui/FileDiffModal.tsx +162 -0
  451. package/src/ui/Header.tsx +87 -24
  452. package/src/ui/HelpModal.tsx +57 -0
  453. package/src/ui/InputBox.tsx +163 -10
  454. package/src/ui/MessageList.tsx +487 -40
  455. package/src/ui/PermissionPrompt.tsx +17 -5
  456. package/src/ui/StatusBar.tsx +122 -3
  457. package/src/ui/TerminalPane.tsx +84 -0
  458. package/src/ui/ToolCallDisplay.tsx +252 -18
  459. package/src/ui/TreePane.tsx +132 -0
  460. package/src/ui/chat-ui.ts +41 -44
  461. package/src/ui/ink/index.ts +771 -38
  462. package/src/ui/streaming.ts +1 -1
  463. package/src/ui/theme.ts +104 -0
  464. package/src/ui/types.ts +18 -0
  465. package/src/version.ts +1 -1
  466. package/src/watcher/index.ts +66 -15
  467. package/src/wizard/types.ts +1 -0
  468. package/src/wizard/ui.ts +1 -1
  469. package/tsconfig.json +2 -2
@@ -0,0 +1,966 @@
1
+ /**
2
+ * Standard Tool Definitions
3
+ *
4
+ * Defines the 11 standard coding tools available to the Nimbus agentic loop.
5
+ * Each tool wraps existing filesystem operations (src/tools/file-ops.ts) or
6
+ * uses child_process for shell commands.
7
+ *
8
+ * Tools:
9
+ * read_file, edit_file, multi_edit, write_file, bash,
10
+ * glob, grep, list_dir, webfetch, todo_read, todo_write
11
+ */
12
+ import { z } from 'zod';
13
+ import * as fs from 'node:fs/promises';
14
+ import * as path from 'node:path';
15
+ import { spawn, exec } from 'node:child_process';
16
+ import { promisify } from 'node:util';
17
+ import { glob as fastGlob } from 'fast-glob';
18
+ const execAsync = promisify(exec);
19
+ /**
20
+ * Execute a shell command using spawn with process group management.
21
+ * On timeout, kills the entire process group to avoid orphaned children.
22
+ */
23
+ function spawnAsync(command, options) {
24
+ return new Promise((resolve, reject) => {
25
+ const maxBuffer = options.maxBuffer ?? 10 * 1024 * 1024;
26
+ const child = spawn('sh', ['-c', command], {
27
+ cwd: options.cwd,
28
+ stdio: ['ignore', 'pipe', 'pipe'],
29
+ // Create a new process group so we can kill the whole tree
30
+ detached: true,
31
+ });
32
+ let stdout = '';
33
+ let stderr = '';
34
+ let killed = false;
35
+ let stdoutOverflow = false;
36
+ let stderrOverflow = false;
37
+ // Kill process group helper
38
+ const killProcessGroup = () => {
39
+ killed = true;
40
+ try {
41
+ if (child.pid) {
42
+ process.kill(-child.pid, 'SIGTERM');
43
+ setTimeout(() => {
44
+ try {
45
+ if (child.pid) {
46
+ process.kill(-child.pid, 'SIGKILL');
47
+ }
48
+ }
49
+ catch {
50
+ /* already dead */
51
+ }
52
+ }, 2000);
53
+ }
54
+ }
55
+ catch {
56
+ /* Process already exited */
57
+ }
58
+ };
59
+ // Wire AbortSignal (Ctrl+C) to kill the child process group
60
+ if (options.signal) {
61
+ if (options.signal.aborted) {
62
+ killProcessGroup();
63
+ }
64
+ else {
65
+ options.signal.addEventListener('abort', killProcessGroup, { once: true });
66
+ }
67
+ }
68
+ child.stdout?.on('data', (data) => {
69
+ options.onChunk?.(data.toString());
70
+ if (stdout.length + data.length > maxBuffer) {
71
+ stdoutOverflow = true;
72
+ return;
73
+ }
74
+ stdout += data.toString();
75
+ });
76
+ child.stderr?.on('data', (data) => {
77
+ options.onChunk?.(data.toString());
78
+ if (stderr.length + data.length > maxBuffer) {
79
+ stderrOverflow = true;
80
+ return;
81
+ }
82
+ stderr += data.toString();
83
+ });
84
+ const timer = options.timeout
85
+ ? setTimeout(() => {
86
+ killProcessGroup();
87
+ }, options.timeout)
88
+ : null;
89
+ child.on('close', code => {
90
+ if (timer) {
91
+ clearTimeout(timer);
92
+ }
93
+ // Clean up abort listener
94
+ if (options.signal) {
95
+ options.signal.removeEventListener('abort', killProcessGroup);
96
+ }
97
+ if (killed) {
98
+ const err = new Error(options.signal?.aborted
99
+ ? 'Command aborted by user'
100
+ : `Command timed out after ${options.timeout}ms`);
101
+ err.stdout = stdout;
102
+ err.stderr = stderr;
103
+ reject(err);
104
+ return;
105
+ }
106
+ if (stdoutOverflow || stderrOverflow) {
107
+ stdout += '\n[Output truncated: exceeded buffer limit]';
108
+ }
109
+ if (code !== 0) {
110
+ const err = new Error(`Command exited with code ${code}`);
111
+ err.stdout = stdout;
112
+ err.stderr = stderr;
113
+ err.code = code;
114
+ reject(err);
115
+ return;
116
+ }
117
+ resolve({ stdout, stderr });
118
+ });
119
+ child.on('error', error => {
120
+ if (timer) {
121
+ clearTimeout(timer);
122
+ }
123
+ reject(error);
124
+ });
125
+ });
126
+ }
127
+ // ---------------------------------------------------------------------------
128
+ // Helpers
129
+ // ---------------------------------------------------------------------------
130
+ /** Build a successful ToolResult. */
131
+ function ok(output) {
132
+ return { output, isError: false };
133
+ }
134
+ /** Build an error ToolResult. */
135
+ function err(message) {
136
+ return { output: '', error: message, isError: true };
137
+ }
138
+ // ---------------------------------------------------------------------------
139
+ // 1. read_file
140
+ // ---------------------------------------------------------------------------
141
+ const readFileSchema = z.object({
142
+ path: z.string().describe('Absolute or relative path to the file to read'),
143
+ offset: z.number().optional().describe('1-based line number to start reading from'),
144
+ limit: z.number().optional().describe('Maximum number of lines to return'),
145
+ });
146
+ /** Patterns for sensitive files that should be blocked from read_file. */
147
+ const SENSITIVE_FILE_PATTERNS = [
148
+ /\.env($|\.)/i, // .env, .env.local, .env.production, etc.
149
+ /credentials\.json$/i, // GCP credentials
150
+ /\.aws\/credentials$/i, // AWS credentials
151
+ /\.ssh\/(id_|known_hosts|config)/i, // SSH keys and config
152
+ /\.gnupg\//i, // GPG keys
153
+ /\.netrc$/i, // Network credentials
154
+ /secret[s]?\.ya?ml$/i, // Kubernetes secrets
155
+ /\.pem$/i, // SSL certificates
156
+ /\.key$/i, // Private keys
157
+ /\.p12$/i, // PKCS#12 certificates
158
+ /\.keystore$/i, // Java keystores
159
+ /\/\.git\/config$/i, // Git config (may contain tokens)
160
+ /token[s]?\.json$/i, // OAuth tokens
161
+ ];
162
+ function isSensitivePath(filePath) {
163
+ const normalized = filePath.replace(/\\/g, '/');
164
+ return SENSITIVE_FILE_PATTERNS.some(pattern => pattern.test(normalized));
165
+ }
166
+ export const readFileTool = {
167
+ name: 'read_file',
168
+ description: 'Read file contents. Returns the text content of a file at the given path.',
169
+ inputSchema: readFileSchema,
170
+ permissionTier: 'auto_allow',
171
+ category: 'standard',
172
+ async execute(raw) {
173
+ try {
174
+ const input = readFileSchema.parse(raw);
175
+ const resolved = path.resolve(input.path);
176
+ // Block reading of sensitive files (credentials, keys, secrets)
177
+ if (isSensitivePath(resolved)) {
178
+ return err(`Blocked: ${path.basename(resolved)} appears to be a sensitive file (credentials, secrets, or keys). ` +
179
+ `Reading it could expose secrets in the conversation history.`);
180
+ }
181
+ // Detect image files — return base64-encoded data for multimodal LLM support
182
+ const ext = path.extname(resolved).toLowerCase();
183
+ const imageExts = new Set([
184
+ '.png',
185
+ '.jpg',
186
+ '.jpeg',
187
+ '.gif',
188
+ '.bmp',
189
+ '.webp',
190
+ '.svg',
191
+ '.ico',
192
+ '.tiff',
193
+ '.tif',
194
+ ]);
195
+ // Subset that LLMs can actually process as vision input
196
+ const MULTIMODAL_EXTS = {
197
+ '.png': 'image/png',
198
+ '.jpg': 'image/jpeg',
199
+ '.jpeg': 'image/jpeg',
200
+ '.gif': 'image/gif',
201
+ '.webp': 'image/webp',
202
+ };
203
+ if (imageExts.has(ext)) {
204
+ try {
205
+ const stats = await fs.stat(resolved);
206
+ const sizeStr = stats.size < 1024
207
+ ? `${stats.size} B`
208
+ : stats.size < 1024 * 1024
209
+ ? `${(stats.size / 1024).toFixed(1)} KB`
210
+ : `${(stats.size / (1024 * 1024)).toFixed(1)} MB`;
211
+ const mediaType = MULTIMODAL_EXTS[ext];
212
+ // If the image is a supported multimodal format and under 20MB, include base64
213
+ if (mediaType && stats.size < 20 * 1024 * 1024) {
214
+ const buffer = await fs.readFile(resolved);
215
+ const base64 = buffer.toString('base64');
216
+ return ok(`[Image file: ${path.basename(resolved)}]\nType: ${ext.slice(1).toUpperCase()}\nSize: ${sizeStr}\nPath: ${resolved}\n\n` +
217
+ `<image_data media_type="${mediaType}" encoding="base64">${base64}</image_data>`);
218
+ }
219
+ return ok(`[Image file: ${path.basename(resolved)}]\nType: ${ext.slice(1).toUpperCase()}\nSize: ${sizeStr}\nPath: ${resolved}\n\nNote: Image content cannot be displayed in text mode. Use an image viewer or IDE to see the contents.`);
220
+ }
221
+ catch {
222
+ return ok(`[Image file: ${path.basename(resolved)}]\nPath: ${resolved}\n\nNote: Image content cannot be displayed in text mode.`);
223
+ }
224
+ }
225
+ // Detect Jupyter notebooks
226
+ if (ext === '.ipynb') {
227
+ try {
228
+ const nbRaw = await fs.readFile(resolved, 'utf-8');
229
+ const notebook = JSON.parse(nbRaw);
230
+ if (!notebook.cells || !Array.isArray(notebook.cells)) {
231
+ return ok(nbRaw); // Malformed notebook, return raw JSON
232
+ }
233
+ const parts = [`# Jupyter Notebook: ${path.basename(resolved)}\n`];
234
+ for (let i = 0; i < notebook.cells.length; i++) {
235
+ const cell = notebook.cells[i];
236
+ const source = Array.isArray(cell.source)
237
+ ? cell.source.join('')
238
+ : String(cell.source || '');
239
+ if (cell.cell_type === 'markdown') {
240
+ parts.push(`## Cell ${i + 1} [Markdown]\n${source}\n`);
241
+ }
242
+ else if (cell.cell_type === 'code') {
243
+ parts.push(`## Cell ${i + 1} [Code]\n\`\`\`python\n${source}\n\`\`\`\n`);
244
+ // Show outputs
245
+ if (cell.outputs && Array.isArray(cell.outputs)) {
246
+ for (const output of cell.outputs) {
247
+ if (output.text) {
248
+ const text = Array.isArray(output.text)
249
+ ? output.text.join('')
250
+ : String(output.text);
251
+ parts.push(`Output:\n\`\`\`\n${text}\n\`\`\`\n`);
252
+ }
253
+ else if (output.data?.['text/plain']) {
254
+ const text = Array.isArray(output.data['text/plain'])
255
+ ? output.data['text/plain'].join('')
256
+ : String(output.data['text/plain']);
257
+ parts.push(`Output:\n\`\`\`\n${text}\n\`\`\`\n`);
258
+ }
259
+ else if (output.data?.['image/png'] || output.data?.['image/jpeg']) {
260
+ parts.push(`Output: [Image output — cannot display in text mode]\n`);
261
+ }
262
+ }
263
+ }
264
+ }
265
+ else if (cell.cell_type === 'raw') {
266
+ parts.push(`## Cell ${i + 1} [Raw]\n${source}\n`);
267
+ }
268
+ }
269
+ return ok(parts.join('\n'));
270
+ }
271
+ catch {
272
+ // If notebook parsing fails, fall through to normal file read
273
+ }
274
+ }
275
+ const content = await fs.readFile(resolved, 'utf-8');
276
+ if (input.offset !== undefined || input.limit !== undefined) {
277
+ const lines = content.split('\n');
278
+ const start = (input.offset ?? 1) - 1; // convert to 0-based
279
+ const end = input.limit !== undefined ? start + input.limit : lines.length;
280
+ return ok(lines.slice(start, end).join('\n'));
281
+ }
282
+ return ok(content);
283
+ }
284
+ catch (error) {
285
+ const message = error instanceof Error ? error.message : String(error);
286
+ return err(`Failed to read file: ${message}`);
287
+ }
288
+ },
289
+ };
290
+ // ---------------------------------------------------------------------------
291
+ // 2. edit_file
292
+ // ---------------------------------------------------------------------------
293
+ const editFileSchema = z.object({
294
+ path: z.string().describe('Path to the file to edit'),
295
+ old_string: z.string().describe('Exact text to find'),
296
+ new_string: z.string().describe('Replacement text'),
297
+ replace_all: z
298
+ .boolean()
299
+ .optional()
300
+ .default(false)
301
+ .describe('Replace all occurrences instead of just the first'),
302
+ });
303
+ export const editFileTool = {
304
+ name: 'edit_file',
305
+ description: 'Make a precise text replacement in a file. By default replaces the first occurrence of old_string with new_string. Set replace_all to true to replace every occurrence.',
306
+ inputSchema: editFileSchema,
307
+ permissionTier: 'ask_once',
308
+ category: 'standard',
309
+ isDestructive: true,
310
+ async execute(raw) {
311
+ try {
312
+ const input = editFileSchema.parse(raw);
313
+ const content = await fs.readFile(input.path, 'utf-8');
314
+ if (!content.includes(input.old_string)) {
315
+ return err(`old_string not found in ${input.path}. Make sure the string matches exactly, including whitespace and indentation.`);
316
+ }
317
+ let updated;
318
+ if (input.replace_all) {
319
+ // Count occurrences for the success message
320
+ let count = 0;
321
+ let searchPos = 0;
322
+ for (;;) {
323
+ const idx = content.indexOf(input.old_string, searchPos);
324
+ if (idx === -1) {
325
+ break;
326
+ }
327
+ count++;
328
+ searchPos = idx + input.old_string.length;
329
+ }
330
+ updated = content.replaceAll(input.old_string, input.new_string);
331
+ await fs.writeFile(input.path, updated, 'utf-8');
332
+ return ok(`Successfully replaced ${count} occurrence${count !== 1 ? 's' : ''} in ${input.path}`);
333
+ }
334
+ // Replace only the first occurrence
335
+ const idx = content.indexOf(input.old_string);
336
+ updated =
337
+ content.slice(0, idx) + input.new_string + content.slice(idx + input.old_string.length);
338
+ await fs.writeFile(input.path, updated, 'utf-8');
339
+ return ok(`Successfully edited ${input.path}`);
340
+ }
341
+ catch (error) {
342
+ const message = error instanceof Error ? error.message : String(error);
343
+ return err(`Failed to edit file: ${message}`);
344
+ }
345
+ },
346
+ };
347
+ // ---------------------------------------------------------------------------
348
+ // 3. multi_edit
349
+ // ---------------------------------------------------------------------------
350
+ const multiEditSchema = z.object({
351
+ path: z.string().describe('Path to the file to edit'),
352
+ edits: z
353
+ .array(z.object({
354
+ old_string: z.string().describe('Exact text to find'),
355
+ new_string: z.string().describe('Replacement text'),
356
+ }))
357
+ .describe('Array of edits to apply sequentially'),
358
+ });
359
+ export const multiEditTool = {
360
+ name: 'multi_edit',
361
+ description: 'Make multiple text replacements in a single file atomically.',
362
+ inputSchema: multiEditSchema,
363
+ permissionTier: 'ask_once',
364
+ category: 'standard',
365
+ isDestructive: true,
366
+ async execute(raw) {
367
+ try {
368
+ const input = multiEditSchema.parse(raw);
369
+ const content = await fs.readFile(input.path, 'utf-8');
370
+ // Pre-compute all edit positions on the original content to detect
371
+ // overlap issues and enable bottom-up application.
372
+ const positioned = [];
373
+ const usedPositions = new Set();
374
+ for (let i = 0; i < input.edits.length; i++) {
375
+ const edit = input.edits[i];
376
+ // Search for the next occurrence that hasn't already been claimed
377
+ let searchFrom = 0;
378
+ let idx = -1;
379
+ for (;;) {
380
+ idx = content.indexOf(edit.old_string, searchFrom);
381
+ if (idx === -1) {
382
+ break;
383
+ }
384
+ if (!usedPositions.has(idx)) {
385
+ break;
386
+ }
387
+ searchFrom = idx + 1;
388
+ }
389
+ if (idx === -1) {
390
+ return err(`Edit ${i + 1}: old_string not found in ${input.path}. Aborting — no changes were written.`);
391
+ }
392
+ usedPositions.add(idx);
393
+ positioned.push({
394
+ index: idx,
395
+ editIndex: i,
396
+ old_string: edit.old_string,
397
+ new_string: edit.new_string,
398
+ });
399
+ }
400
+ // Sort by position descending (bottom-up) so earlier edits don't
401
+ // shift the positions of later ones.
402
+ positioned.sort((a, b) => b.index - a.index);
403
+ let result = content;
404
+ for (const edit of positioned) {
405
+ result =
406
+ result.slice(0, edit.index) +
407
+ edit.new_string +
408
+ result.slice(edit.index + edit.old_string.length);
409
+ }
410
+ await fs.writeFile(input.path, result, 'utf-8');
411
+ return ok(`Successfully applied ${input.edits.length} edit(s) to ${input.path}`);
412
+ }
413
+ catch (error) {
414
+ const message = error instanceof Error ? error.message : String(error);
415
+ return err(`Failed to apply multi-edit: ${message}`);
416
+ }
417
+ },
418
+ };
419
+ // ---------------------------------------------------------------------------
420
+ // 4. write_file
421
+ // ---------------------------------------------------------------------------
422
+ const writeFileSchema = z.object({
423
+ path: z.string().describe('Path to the file to create or overwrite'),
424
+ content: z.string().describe('Full file content to write'),
425
+ });
426
+ export const writeFileTool = {
427
+ name: 'write_file',
428
+ description: 'Create or overwrite a file with the given content.',
429
+ inputSchema: writeFileSchema,
430
+ permissionTier: 'ask_once',
431
+ category: 'standard',
432
+ isDestructive: true,
433
+ async execute(raw) {
434
+ try {
435
+ const input = writeFileSchema.parse(raw);
436
+ await fs.mkdir(path.dirname(input.path), { recursive: true });
437
+ await fs.writeFile(input.path, input.content, 'utf-8');
438
+ return ok(`Successfully wrote ${input.path}`);
439
+ }
440
+ catch (error) {
441
+ const message = error instanceof Error ? error.message : String(error);
442
+ return err(`Failed to write file: ${message}`);
443
+ }
444
+ },
445
+ };
446
+ // ---------------------------------------------------------------------------
447
+ // 5. bash
448
+ // ---------------------------------------------------------------------------
449
+ const bashSchema = z.object({
450
+ command: z.string().describe('Shell command to execute'),
451
+ timeout: z
452
+ .number()
453
+ .optional()
454
+ .default(120_000)
455
+ .describe('Timeout in milliseconds (default: 120000)'),
456
+ workdir: z.string().optional().describe('Working directory for the command'),
457
+ });
458
+ export const bashTool = {
459
+ name: 'bash',
460
+ description: 'Execute a shell command and return its output. Use for running tests, installing packages, or other terminal operations.',
461
+ inputSchema: bashSchema,
462
+ permissionTier: 'ask_once',
463
+ category: 'standard',
464
+ isDestructive: true,
465
+ async execute(raw) {
466
+ try {
467
+ const input = bashSchema.parse(raw);
468
+ const signal = raw?._signal;
469
+ const onChunk = raw?._onChunk;
470
+ const { stdout, stderr } = await spawnAsync(input.command, {
471
+ timeout: input.timeout,
472
+ cwd: input.workdir,
473
+ maxBuffer: 10 * 1024 * 1024, // 10 MB
474
+ signal,
475
+ onChunk,
476
+ });
477
+ const combined = [stdout, stderr].filter(Boolean).join('\n');
478
+ return ok(combined || '(no output)');
479
+ }
480
+ catch (error) {
481
+ if (error !== null && typeof error === 'object' && 'stdout' in error) {
482
+ // Process errors still carry partial output
483
+ const execErr = error;
484
+ const combined = [execErr.stdout, execErr.stderr].filter(Boolean).join('\n');
485
+ return err(combined || execErr.message || 'Command failed');
486
+ }
487
+ const message = error instanceof Error ? error.message : String(error);
488
+ return err(`Command failed: ${message}`);
489
+ }
490
+ },
491
+ };
492
+ // ---------------------------------------------------------------------------
493
+ // 6. glob
494
+ // ---------------------------------------------------------------------------
495
+ const globSchema = z.object({
496
+ pattern: z.string().describe('Glob pattern to match files (e.g., "**/*.ts")'),
497
+ path: z.string().optional().describe('Base directory to search in (defaults to cwd)'),
498
+ });
499
+ export const globTool = {
500
+ name: 'glob',
501
+ description: 'Find files matching a glob pattern. Returns matching file paths.',
502
+ inputSchema: globSchema,
503
+ permissionTier: 'auto_allow',
504
+ category: 'standard',
505
+ async execute(raw) {
506
+ try {
507
+ const input = globSchema.parse(raw);
508
+ const matches = await fastGlob(input.pattern, {
509
+ cwd: input.path ?? process.cwd(),
510
+ absolute: true,
511
+ dot: false,
512
+ });
513
+ if (matches.length === 0) {
514
+ return ok('No files matched the pattern.');
515
+ }
516
+ return ok(matches.join('\n'));
517
+ }
518
+ catch (error) {
519
+ const message = error instanceof Error ? error.message : String(error);
520
+ return err(`Glob search failed: ${message}`);
521
+ }
522
+ },
523
+ };
524
+ // ---------------------------------------------------------------------------
525
+ // 7. grep
526
+ // ---------------------------------------------------------------------------
527
+ const grepSchema = z.object({
528
+ pattern: z.string().describe('Regex pattern to search for'),
529
+ path: z.string().optional().describe('Directory or file to search in (defaults to cwd)'),
530
+ include: z.string().optional().describe('Glob filter for file types (e.g., "*.ts")'),
531
+ });
532
+ export const grepTool = {
533
+ name: 'grep',
534
+ description: 'Search file contents using a regex pattern. Returns matching lines with file paths and line numbers.',
535
+ inputSchema: grepSchema,
536
+ permissionTier: 'auto_allow',
537
+ category: 'standard',
538
+ async execute(raw) {
539
+ try {
540
+ const input = grepSchema.parse(raw);
541
+ const searchPath = input.path ?? process.cwd();
542
+ // Try ripgrep first (faster, respects .gitignore), fall back to grep
543
+ let command;
544
+ try {
545
+ await execAsync('rg --version', { timeout: 2000 });
546
+ const globFlag = input.include ? ` --glob ${JSON.stringify(input.include)}` : '';
547
+ command = `rg -n${globFlag} ${JSON.stringify(input.pattern)} ${JSON.stringify(searchPath)}`;
548
+ }
549
+ catch {
550
+ const includeFlag = input.include ? ` --include=${JSON.stringify(input.include)}` : '';
551
+ command = `grep -rn${includeFlag} ${JSON.stringify(input.pattern)} ${JSON.stringify(searchPath)}`;
552
+ }
553
+ const { stdout } = await execAsync(command, {
554
+ maxBuffer: 10 * 1024 * 1024,
555
+ });
556
+ return ok(stdout || 'No matches found.');
557
+ }
558
+ catch (error) {
559
+ if (error !== null &&
560
+ typeof error === 'object' &&
561
+ 'code' in error &&
562
+ error.code === 1) {
563
+ // grep/rg exit code 1 = no matches (not a real error)
564
+ return ok('No matches found.');
565
+ }
566
+ const message = error instanceof Error ? error.message : String(error);
567
+ return err(`Grep failed: ${message}`);
568
+ }
569
+ },
570
+ };
571
+ // ---------------------------------------------------------------------------
572
+ // 8. list_dir
573
+ // ---------------------------------------------------------------------------
574
+ const listDirSchema = z.object({
575
+ path: z.string().describe('Absolute or relative path to the directory'),
576
+ });
577
+ export const listDirTool = {
578
+ name: 'list_dir',
579
+ description: 'List the contents of a directory. Returns file and directory names with type indicators.',
580
+ inputSchema: listDirSchema,
581
+ permissionTier: 'auto_allow',
582
+ category: 'standard',
583
+ async execute(raw) {
584
+ try {
585
+ const input = listDirSchema.parse(raw);
586
+ const entries = await fs.readdir(input.path, {
587
+ withFileTypes: true,
588
+ });
589
+ if (entries.length === 0) {
590
+ return ok('(empty directory)');
591
+ }
592
+ const lines = entries.map(entry => {
593
+ if (entry.isDirectory()) {
594
+ return `[DIR] ${entry.name}/`;
595
+ }
596
+ return `[FILE] ${entry.name}`;
597
+ });
598
+ return ok(lines.join('\n'));
599
+ }
600
+ catch (error) {
601
+ const message = error instanceof Error ? error.message : String(error);
602
+ return err(`Failed to list directory: ${message}`);
603
+ }
604
+ },
605
+ };
606
+ // ---------------------------------------------------------------------------
607
+ // 9. webfetch
608
+ // ---------------------------------------------------------------------------
609
+ const webfetchSchema = z.object({
610
+ url: z.string().url().describe('URL to fetch content from'),
611
+ prompt: z.string().optional().describe('Optional prompt describing what information to extract'),
612
+ });
613
+ /** Maximum characters returned from a fetched page. */
614
+ const WEBFETCH_MAX_CHARS = 50_000;
615
+ export const webfetchTool = {
616
+ name: 'webfetch',
617
+ description: 'Fetch content from a URL and optionally process it with a prompt.',
618
+ inputSchema: webfetchSchema,
619
+ permissionTier: 'ask_once',
620
+ category: 'standard',
621
+ async execute(raw) {
622
+ try {
623
+ const input = webfetchSchema.parse(raw);
624
+ const response = await fetch(input.url);
625
+ if (!response.ok) {
626
+ return err(`HTTP ${response.status} ${response.statusText} fetching ${input.url}`);
627
+ }
628
+ let text = await response.text();
629
+ if (text.length > WEBFETCH_MAX_CHARS) {
630
+ text = `${text.slice(0, WEBFETCH_MAX_CHARS)}\n\n... (truncated, ${text.length} total characters)`;
631
+ }
632
+ if (input.prompt) {
633
+ // Attempt to process the fetched content through a fast LLM model.
634
+ // Falls back to returning raw text if the router is unavailable or
635
+ // the LLM call fails for any reason.
636
+ try {
637
+ const { getAppContext } = await import('../../app');
638
+ const ctx = getAppContext();
639
+ if (ctx?.router) {
640
+ const stream = ctx.router.routeStream({
641
+ messages: [
642
+ {
643
+ role: 'system',
644
+ content: 'You are a content extraction assistant. The user will provide web page content and a question or instruction. Extract the requested information concisely from the content. Do not add information that is not present in the content.',
645
+ },
646
+ {
647
+ role: 'user',
648
+ content: `${input.prompt}\n\n---\n\nWeb page content from ${input.url}:\n\n${text}`,
649
+ },
650
+ ],
651
+ model: 'haiku',
652
+ maxTokens: 4096,
653
+ }, 'summarization');
654
+ let result = '';
655
+ for await (const chunk of stream) {
656
+ if (chunk.content) {
657
+ result += chunk.content;
658
+ }
659
+ }
660
+ if (result.length > 0) {
661
+ return ok(result);
662
+ }
663
+ }
664
+ }
665
+ catch {
666
+ // LLM processing failed — fall through to raw text response.
667
+ }
668
+ return ok(`[Prompt: ${input.prompt}]\n\n${text}`);
669
+ }
670
+ return ok(text);
671
+ }
672
+ catch (error) {
673
+ const message = error instanceof Error ? error.message : String(error);
674
+ return err(`Fetch failed: ${message}`);
675
+ }
676
+ },
677
+ };
678
+ // ---------------------------------------------------------------------------
679
+ // 10. todo_read
680
+ // ---------------------------------------------------------------------------
681
+ const todoReadSchema = z.object({}).describe('No input required');
682
+ export const todoReadTool = {
683
+ name: 'todo_read',
684
+ description: "Read the current session's task list.",
685
+ inputSchema: todoReadSchema,
686
+ permissionTier: 'auto_allow',
687
+ category: 'standard',
688
+ async execute(_raw) {
689
+ try {
690
+ const { getDb } = await import('../../state/db');
691
+ const db = getDb();
692
+ db.exec(`
693
+ CREATE TABLE IF NOT EXISTS todos (
694
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
695
+ subject TEXT NOT NULL,
696
+ status TEXT NOT NULL DEFAULT 'pending',
697
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
698
+ )
699
+ `);
700
+ const rows = db.query('SELECT id, subject, status FROM todos ORDER BY id').all();
701
+ if (rows.length === 0) {
702
+ return ok('No tasks yet.');
703
+ }
704
+ const lines = rows.map(r => {
705
+ const indicator = r.status === 'completed' ? '[x]' : r.status === 'in_progress' ? '[~]' : '[ ]';
706
+ return `${r.id}. ${indicator} ${r.subject}`;
707
+ });
708
+ return ok(lines.join('\n'));
709
+ }
710
+ catch (error) {
711
+ // Fallback to original placeholder behavior on DB failure.
712
+ return ok('No tasks yet.');
713
+ }
714
+ },
715
+ };
716
+ // ---------------------------------------------------------------------------
717
+ // 11. todo_write
718
+ // ---------------------------------------------------------------------------
719
+ const todoWriteSchema = z.object({
720
+ tasks: z
721
+ .array(z.object({
722
+ subject: z.string().describe('Brief task title'),
723
+ status: z
724
+ .enum(['pending', 'in_progress', 'completed'])
725
+ .describe('Current status of the task'),
726
+ }))
727
+ .describe('Array of tasks to write to the session'),
728
+ });
729
+ export const todoWriteTool = {
730
+ name: 'todo_write',
731
+ description: "Update the session's task list.",
732
+ inputSchema: todoWriteSchema,
733
+ permissionTier: 'auto_allow',
734
+ category: 'standard',
735
+ async execute(raw) {
736
+ try {
737
+ const input = todoWriteSchema.parse(raw);
738
+ const { getDb } = await import('../../state/db');
739
+ const db = getDb();
740
+ db.exec(`
741
+ CREATE TABLE IF NOT EXISTS todos (
742
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
743
+ subject TEXT NOT NULL,
744
+ status TEXT NOT NULL DEFAULT 'pending',
745
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
746
+ )
747
+ `);
748
+ // Replace strategy: clear existing rows and insert the new set.
749
+ db.exec('DELETE FROM todos');
750
+ const insert = db.prepare('INSERT INTO todos (subject, status) VALUES (?, ?)');
751
+ const insertAll = db.transaction((tasks) => {
752
+ for (const t of tasks) {
753
+ insert.run(t.subject, t.status);
754
+ }
755
+ });
756
+ insertAll(input.tasks);
757
+ const summary = input.tasks.map(t => {
758
+ const indicator = t.status === 'completed' ? '[x]' : t.status === 'in_progress' ? '[~]' : '[ ]';
759
+ return `${indicator} ${t.subject}`;
760
+ });
761
+ return ok(`Task list updated (${input.tasks.length} task${input.tasks.length === 1 ? '' : 's'}):\n${summary.join('\n')}`);
762
+ }
763
+ catch (error) {
764
+ // Fallback to original placeholder behavior on DB failure.
765
+ const message = error instanceof Error ? error.message : String(error);
766
+ return err(`Failed to update tasks: ${message}`);
767
+ }
768
+ },
769
+ };
770
+ // ---------------------------------------------------------------------------
771
+ // 12. web_search — Multi-engine search helpers
772
+ // ---------------------------------------------------------------------------
773
+ /**
774
+ * Search using the Brave Search API. Returns formatted markdown results
775
+ * or null if the request fails (allowing fallback to DuckDuckGo).
776
+ */
777
+ async function searchBrave(query, maxResults, apiKey) {
778
+ try {
779
+ const encodedQuery = encodeURIComponent(query);
780
+ const response = await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodedQuery}&count=${maxResults}`, {
781
+ headers: {
782
+ Accept: 'application/json',
783
+ 'Accept-Encoding': 'gzip',
784
+ 'X-Subscription-Token': apiKey,
785
+ },
786
+ });
787
+ if (!response.ok) {
788
+ return null;
789
+ }
790
+ const data = (await response.json());
791
+ const results = [];
792
+ // Featured snippet
793
+ if (data.mixed?.main?.[0]?.type === 'faq') {
794
+ const faq = data.mixed.main[0];
795
+ if (faq.results?.[0]?.answer) {
796
+ results.push(`## Featured Answer\n${faq.results[0].answer}\n`);
797
+ }
798
+ }
799
+ // Web results
800
+ if (data.web?.results) {
801
+ results.push('## Results');
802
+ for (const r of data.web.results.slice(0, maxResults)) {
803
+ results.push(`### ${r.title}\n${r.description || ''}\nURL: ${r.url}\n`);
804
+ }
805
+ }
806
+ // Knowledge graph
807
+ if (data.infobox?.results?.[0]) {
808
+ const info = data.infobox.results[0];
809
+ results.push(`## ${info.title || 'Info'}\n${info.description || ''}`);
810
+ }
811
+ return results.length > 0 ? results.join('\n') : null;
812
+ }
813
+ catch {
814
+ return null;
815
+ }
816
+ }
817
+ /**
818
+ * Search using DuckDuckGo Instant Answer API. Returns formatted markdown
819
+ * results. This is the fallback engine that requires no API key.
820
+ */
821
+ async function searchDuckDuckGo(query, maxResults) {
822
+ const encodedQuery = encodeURIComponent(query);
823
+ // Try the Instant Answer API first for direct answers
824
+ const iaResponse = await fetch(`https://api.duckduckgo.com/?q=${encodedQuery}&format=json&no_html=1&skip_disambig=1`);
825
+ const results = [];
826
+ if (iaResponse.ok) {
827
+ const data = (await iaResponse.json());
828
+ // Abstract (direct answer)
829
+ if (data.Abstract) {
830
+ results.push(`## Direct Answer\n${data.Abstract}\nSource: ${data.AbstractURL}\n`);
831
+ }
832
+ // Definition
833
+ if (data.Definition) {
834
+ results.push(`## Definition\n${data.Definition}\nSource: ${data.DefinitionURL}\n`);
835
+ }
836
+ // Answer (calculations, conversions, etc.)
837
+ if (data.Answer) {
838
+ results.push(`## Answer\n${data.Answer}\n`);
839
+ }
840
+ // Related topics
841
+ if (data.RelatedTopics && Array.isArray(data.RelatedTopics)) {
842
+ const topics = data.RelatedTopics.filter((t) => t.Text && t.FirstURL).slice(0, maxResults);
843
+ if (topics.length > 0) {
844
+ results.push('## Results');
845
+ for (const topic of topics) {
846
+ results.push(`- ${topic.Text}\n URL: ${topic.FirstURL}`);
847
+ }
848
+ }
849
+ }
850
+ // Infobox
851
+ if (data.Infobox?.content?.length > 0) {
852
+ results.push('## Info');
853
+ for (const item of data.Infobox.content.slice(0, 5)) {
854
+ if (item.label && item.value) {
855
+ results.push(`- ${item.label}: ${item.value}`);
856
+ }
857
+ }
858
+ }
859
+ // Redirect (if DDG suggests a better page)
860
+ if (data.Redirect) {
861
+ results.push(`\nSuggested page: ${data.Redirect}`);
862
+ }
863
+ }
864
+ // If Instant Answer API returned nothing, try the HTML lite endpoint
865
+ if (results.length === 0) {
866
+ try {
867
+ const htmlResponse = await fetch(`https://html.duckduckgo.com/html/?q=${encodedQuery}`, {
868
+ headers: { 'User-Agent': 'Mozilla/5.0 (compatible; Nimbus-CLI/1.0)' },
869
+ });
870
+ if (htmlResponse.ok) {
871
+ const html = await htmlResponse.text();
872
+ // Parse result snippets from the lite HTML page
873
+ const resultPattern = /<a rel="nofollow" class="result__a" href="([^"]+)"[^>]*>([^<]+)<\/a>[\s\S]*?<a class="result__snippet"[^>]*>([^<]*)<\/a>/g;
874
+ let match;
875
+ let count = 0;
876
+ results.push('## Results');
877
+ while ((match = resultPattern.exec(html)) !== null && count < maxResults) {
878
+ const url = match[1].startsWith('//') ? `https:${match[1]}` : match[1];
879
+ const title = match[2]
880
+ .replace(/&#x27;/g, "'")
881
+ .replace(/&amp;/g, '&')
882
+ .replace(/&quot;/g, '"');
883
+ const snippet = match[3]
884
+ .replace(/<\/?b>/g, '**')
885
+ .replace(/&#x27;/g, "'")
886
+ .replace(/&amp;/g, '&');
887
+ results.push(`### ${title}\n${snippet}\nURL: ${url}\n`);
888
+ count++;
889
+ }
890
+ }
891
+ }
892
+ catch {
893
+ // HTML fallback failed — fall through to "no results" message
894
+ }
895
+ }
896
+ if (results.length === 0) {
897
+ return `No results found for: "${query}". Try rephrasing the query or using more specific terms.\n\nTip: Set BRAVE_SEARCH_API_KEY env var for significantly better web search results.`;
898
+ }
899
+ return results.join('\n');
900
+ }
901
+ // ---------------------------------------------------------------------------
902
+ // 12. web_search
903
+ // ---------------------------------------------------------------------------
904
+ const webSearchSchema = z.object({
905
+ query: z.string().describe('The search query string'),
906
+ maxResults: z
907
+ .number()
908
+ .optional()
909
+ .default(5)
910
+ .describe('Maximum number of results to return (default: 5)'),
911
+ engine: z
912
+ .enum(['auto', 'duckduckgo', 'brave'])
913
+ .optional()
914
+ .default('auto')
915
+ .describe('Search engine to use (default: auto)'),
916
+ });
917
+ export const webSearchTool = {
918
+ name: 'web_search',
919
+ description: 'Search the web using a query string. Returns titles, URLs, and snippets. ' +
920
+ 'Supports Brave Search (set BRAVE_SEARCH_API_KEY) and DuckDuckGo. ' +
921
+ 'Useful for finding documentation, looking up error messages, or researching technologies.',
922
+ inputSchema: webSearchSchema,
923
+ permissionTier: 'ask_once',
924
+ category: 'standard',
925
+ async execute(raw) {
926
+ try {
927
+ const input = webSearchSchema.parse(raw);
928
+ // Try Brave Search API first if key is available, then DuckDuckGo as fallback
929
+ const braveKey = process.env.BRAVE_SEARCH_API_KEY;
930
+ if ((input.engine === 'brave' || input.engine === 'auto') && braveKey) {
931
+ const result = await searchBrave(input.query, input.maxResults, braveKey);
932
+ if (result) {
933
+ return ok(result);
934
+ }
935
+ if (input.engine === 'brave') {
936
+ return err('Brave Search failed and no fallback allowed');
937
+ }
938
+ }
939
+ // DuckDuckGo HTML search (better results than Instant Answer API)
940
+ const result = await searchDuckDuckGo(input.query, input.maxResults);
941
+ return ok(result);
942
+ }
943
+ catch (error) {
944
+ const msg = error instanceof Error ? error.message : String(error);
945
+ return err(`Web search failed: ${msg}`);
946
+ }
947
+ },
948
+ };
949
+ // ---------------------------------------------------------------------------
950
+ // Aggregate export
951
+ // ---------------------------------------------------------------------------
952
+ /** All 12 standard tools as an ordered array. */
953
+ export const standardTools = [
954
+ readFileTool,
955
+ editFileTool,
956
+ multiEditTool,
957
+ writeFileTool,
958
+ bashTool,
959
+ globTool,
960
+ grepTool,
961
+ listDirTool,
962
+ webfetchTool,
963
+ todoReadTool,
964
+ todoWriteTool,
965
+ webSearchTool,
966
+ ];