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