whale-code 6.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 (319) hide show
  1. package/README.md +95 -0
  2. package/bin/swag-agent.js +9 -0
  3. package/bin/swagmanager-mcp.js +321 -0
  4. package/dist/cli/app.d.ts +26 -0
  5. package/dist/cli/app.js +64 -0
  6. package/dist/cli/chat/AgentSelector.d.ts +14 -0
  7. package/dist/cli/chat/AgentSelector.js +14 -0
  8. package/dist/cli/chat/ChatApp.d.ts +9 -0
  9. package/dist/cli/chat/ChatApp.js +267 -0
  10. package/dist/cli/chat/ChatInput.d.ts +39 -0
  11. package/dist/cli/chat/ChatInput.js +509 -0
  12. package/dist/cli/chat/MarkdownText.d.ts +10 -0
  13. package/dist/cli/chat/MarkdownText.js +20 -0
  14. package/dist/cli/chat/MessageList.d.ts +37 -0
  15. package/dist/cli/chat/MessageList.js +80 -0
  16. package/dist/cli/chat/ModelSelector.d.ts +20 -0
  17. package/dist/cli/chat/ModelSelector.js +73 -0
  18. package/dist/cli/chat/RewindViewer.d.ts +26 -0
  19. package/dist/cli/chat/RewindViewer.js +185 -0
  20. package/dist/cli/chat/StoreSelector.d.ts +14 -0
  21. package/dist/cli/chat/StoreSelector.js +24 -0
  22. package/dist/cli/chat/StreamingText.d.ts +12 -0
  23. package/dist/cli/chat/StreamingText.js +12 -0
  24. package/dist/cli/chat/SubagentPanel.d.ts +45 -0
  25. package/dist/cli/chat/SubagentPanel.js +110 -0
  26. package/dist/cli/chat/TeamPanel.d.ts +21 -0
  27. package/dist/cli/chat/TeamPanel.js +42 -0
  28. package/dist/cli/chat/ToolIndicator.d.ts +25 -0
  29. package/dist/cli/chat/ToolIndicator.js +436 -0
  30. package/dist/cli/chat/hooks/useAgentLoop.d.ts +39 -0
  31. package/dist/cli/chat/hooks/useAgentLoop.js +382 -0
  32. package/dist/cli/chat/hooks/useSlashCommands.d.ts +37 -0
  33. package/dist/cli/chat/hooks/useSlashCommands.js +387 -0
  34. package/dist/cli/commands/config-cmd.d.ts +10 -0
  35. package/dist/cli/commands/config-cmd.js +99 -0
  36. package/dist/cli/commands/doctor.d.ts +14 -0
  37. package/dist/cli/commands/doctor.js +172 -0
  38. package/dist/cli/commands/init.d.ts +16 -0
  39. package/dist/cli/commands/init.js +278 -0
  40. package/dist/cli/commands/mcp.d.ts +12 -0
  41. package/dist/cli/commands/mcp.js +162 -0
  42. package/dist/cli/login/LoginApp.d.ts +7 -0
  43. package/dist/cli/login/LoginApp.js +157 -0
  44. package/dist/cli/print-mode.d.ts +31 -0
  45. package/dist/cli/print-mode.js +202 -0
  46. package/dist/cli/serve-mode.d.ts +37 -0
  47. package/dist/cli/serve-mode.js +636 -0
  48. package/dist/cli/services/agent-definitions.d.ts +25 -0
  49. package/dist/cli/services/agent-definitions.js +91 -0
  50. package/dist/cli/services/agent-events.d.ts +178 -0
  51. package/dist/cli/services/agent-events.js +175 -0
  52. package/dist/cli/services/agent-loop.d.ts +90 -0
  53. package/dist/cli/services/agent-loop.js +762 -0
  54. package/dist/cli/services/agent-worker-base.d.ts +97 -0
  55. package/dist/cli/services/agent-worker-base.js +220 -0
  56. package/dist/cli/services/auth-service.d.ts +30 -0
  57. package/dist/cli/services/auth-service.js +160 -0
  58. package/dist/cli/services/background-processes.d.ts +126 -0
  59. package/dist/cli/services/background-processes.js +318 -0
  60. package/dist/cli/services/browser-auth.d.ts +24 -0
  61. package/dist/cli/services/browser-auth.js +180 -0
  62. package/dist/cli/services/claude-md-loader.d.ts +16 -0
  63. package/dist/cli/services/claude-md-loader.js +58 -0
  64. package/dist/cli/services/config-store.d.ts +47 -0
  65. package/dist/cli/services/config-store.js +79 -0
  66. package/dist/cli/services/debug-log.d.ts +10 -0
  67. package/dist/cli/services/debug-log.js +52 -0
  68. package/dist/cli/services/error-logger.d.ts +58 -0
  69. package/dist/cli/services/error-logger.js +269 -0
  70. package/dist/cli/services/file-history.d.ts +21 -0
  71. package/dist/cli/services/file-history.js +83 -0
  72. package/dist/cli/services/format-server-response.d.ts +16 -0
  73. package/dist/cli/services/format-server-response.js +440 -0
  74. package/dist/cli/services/git-context.d.ts +11 -0
  75. package/dist/cli/services/git-context.js +66 -0
  76. package/dist/cli/services/hooks.d.ts +85 -0
  77. package/dist/cli/services/hooks.js +258 -0
  78. package/dist/cli/services/interactive-tools.d.ts +125 -0
  79. package/dist/cli/services/interactive-tools.js +260 -0
  80. package/dist/cli/services/keybinding-manager.d.ts +52 -0
  81. package/dist/cli/services/keybinding-manager.js +115 -0
  82. package/dist/cli/services/local-tools.d.ts +22 -0
  83. package/dist/cli/services/local-tools.js +697 -0
  84. package/dist/cli/services/lsp-manager.d.ts +18 -0
  85. package/dist/cli/services/lsp-manager.js +717 -0
  86. package/dist/cli/services/mcp-client.d.ts +48 -0
  87. package/dist/cli/services/mcp-client.js +157 -0
  88. package/dist/cli/services/memory-manager.d.ts +16 -0
  89. package/dist/cli/services/memory-manager.js +57 -0
  90. package/dist/cli/services/model-manager.d.ts +18 -0
  91. package/dist/cli/services/model-manager.js +71 -0
  92. package/dist/cli/services/model-router.d.ts +26 -0
  93. package/dist/cli/services/model-router.js +149 -0
  94. package/dist/cli/services/permission-modes.d.ts +13 -0
  95. package/dist/cli/services/permission-modes.js +43 -0
  96. package/dist/cli/services/rewind.d.ts +84 -0
  97. package/dist/cli/services/rewind.js +194 -0
  98. package/dist/cli/services/ripgrep.d.ts +28 -0
  99. package/dist/cli/services/ripgrep.js +138 -0
  100. package/dist/cli/services/sandbox.d.ts +29 -0
  101. package/dist/cli/services/sandbox.js +97 -0
  102. package/dist/cli/services/server-tools.d.ts +61 -0
  103. package/dist/cli/services/server-tools.js +543 -0
  104. package/dist/cli/services/session-persistence.d.ts +23 -0
  105. package/dist/cli/services/session-persistence.js +99 -0
  106. package/dist/cli/services/subagent-worker.d.ts +19 -0
  107. package/dist/cli/services/subagent-worker.js +41 -0
  108. package/dist/cli/services/subagent.d.ts +47 -0
  109. package/dist/cli/services/subagent.js +647 -0
  110. package/dist/cli/services/system-prompt.d.ts +7 -0
  111. package/dist/cli/services/system-prompt.js +198 -0
  112. package/dist/cli/services/team-lead.d.ts +73 -0
  113. package/dist/cli/services/team-lead.js +512 -0
  114. package/dist/cli/services/team-state.d.ts +77 -0
  115. package/dist/cli/services/team-state.js +398 -0
  116. package/dist/cli/services/teammate.d.ts +31 -0
  117. package/dist/cli/services/teammate.js +689 -0
  118. package/dist/cli/services/telemetry.d.ts +61 -0
  119. package/dist/cli/services/telemetry.js +209 -0
  120. package/dist/cli/services/tools/agent-tools.d.ts +14 -0
  121. package/dist/cli/services/tools/agent-tools.js +347 -0
  122. package/dist/cli/services/tools/file-ops.d.ts +15 -0
  123. package/dist/cli/services/tools/file-ops.js +487 -0
  124. package/dist/cli/services/tools/search-tools.d.ts +8 -0
  125. package/dist/cli/services/tools/search-tools.js +186 -0
  126. package/dist/cli/services/tools/shell-exec.d.ts +10 -0
  127. package/dist/cli/services/tools/shell-exec.js +168 -0
  128. package/dist/cli/services/tools/task-manager.d.ts +28 -0
  129. package/dist/cli/services/tools/task-manager.js +209 -0
  130. package/dist/cli/services/tools/web-tools.d.ts +11 -0
  131. package/dist/cli/services/tools/web-tools.js +395 -0
  132. package/dist/cli/setup/SetupApp.d.ts +9 -0
  133. package/dist/cli/setup/SetupApp.js +191 -0
  134. package/dist/cli/shared/MatrixIntro.d.ts +4 -0
  135. package/dist/cli/shared/MatrixIntro.js +83 -0
  136. package/dist/cli/shared/Theme.d.ts +74 -0
  137. package/dist/cli/shared/Theme.js +127 -0
  138. package/dist/cli/shared/WhaleBanner.d.ts +10 -0
  139. package/dist/cli/shared/WhaleBanner.js +12 -0
  140. package/dist/cli/shared/markdown.d.ts +21 -0
  141. package/dist/cli/shared/markdown.js +756 -0
  142. package/dist/cli/status/StatusApp.d.ts +4 -0
  143. package/dist/cli/status/StatusApp.js +105 -0
  144. package/dist/cli/stores/StoreApp.d.ts +7 -0
  145. package/dist/cli/stores/StoreApp.js +81 -0
  146. package/dist/index.d.ts +15 -0
  147. package/dist/index.js +538 -0
  148. package/dist/local-agent/connection.d.ts +48 -0
  149. package/dist/local-agent/connection.js +332 -0
  150. package/dist/local-agent/discovery.d.ts +18 -0
  151. package/dist/local-agent/discovery.js +146 -0
  152. package/dist/local-agent/executor.d.ts +34 -0
  153. package/dist/local-agent/executor.js +241 -0
  154. package/dist/local-agent/index.d.ts +14 -0
  155. package/dist/local-agent/index.js +198 -0
  156. package/dist/node/adapters/base.d.ts +35 -0
  157. package/dist/node/adapters/base.js +10 -0
  158. package/dist/node/adapters/discord.d.ts +29 -0
  159. package/dist/node/adapters/discord.js +299 -0
  160. package/dist/node/adapters/email.d.ts +23 -0
  161. package/dist/node/adapters/email.js +218 -0
  162. package/dist/node/adapters/imessage.d.ts +17 -0
  163. package/dist/node/adapters/imessage.js +118 -0
  164. package/dist/node/adapters/slack.d.ts +26 -0
  165. package/dist/node/adapters/slack.js +259 -0
  166. package/dist/node/adapters/sms.d.ts +23 -0
  167. package/dist/node/adapters/sms.js +161 -0
  168. package/dist/node/adapters/telegram.d.ts +17 -0
  169. package/dist/node/adapters/telegram.js +101 -0
  170. package/dist/node/adapters/webchat.d.ts +27 -0
  171. package/dist/node/adapters/webchat.js +160 -0
  172. package/dist/node/adapters/whatsapp.d.ts +28 -0
  173. package/dist/node/adapters/whatsapp.js +230 -0
  174. package/dist/node/cli.d.ts +2 -0
  175. package/dist/node/cli.js +325 -0
  176. package/dist/node/config.d.ts +17 -0
  177. package/dist/node/config.js +31 -0
  178. package/dist/node/runtime.d.ts +50 -0
  179. package/dist/node/runtime.js +351 -0
  180. package/dist/server/handlers/__test-utils__/mock-supabase.d.ts +11 -0
  181. package/dist/server/handlers/__test-utils__/mock-supabase.js +393 -0
  182. package/dist/server/handlers/analytics.d.ts +17 -0
  183. package/dist/server/handlers/analytics.js +266 -0
  184. package/dist/server/handlers/api-keys.d.ts +6 -0
  185. package/dist/server/handlers/api-keys.js +221 -0
  186. package/dist/server/handlers/billing.d.ts +33 -0
  187. package/dist/server/handlers/billing.js +272 -0
  188. package/dist/server/handlers/browser.d.ts +10 -0
  189. package/dist/server/handlers/browser.js +517 -0
  190. package/dist/server/handlers/catalog.d.ts +99 -0
  191. package/dist/server/handlers/catalog.js +976 -0
  192. package/dist/server/handlers/comms.d.ts +254 -0
  193. package/dist/server/handlers/comms.js +588 -0
  194. package/dist/server/handlers/creations.d.ts +6 -0
  195. package/dist/server/handlers/creations.js +479 -0
  196. package/dist/server/handlers/crm.d.ts +89 -0
  197. package/dist/server/handlers/crm.js +538 -0
  198. package/dist/server/handlers/discovery.d.ts +6 -0
  199. package/dist/server/handlers/discovery.js +288 -0
  200. package/dist/server/handlers/embeddings.d.ts +92 -0
  201. package/dist/server/handlers/embeddings.js +197 -0
  202. package/dist/server/handlers/enrichment.d.ts +8 -0
  203. package/dist/server/handlers/enrichment.js +768 -0
  204. package/dist/server/handlers/image-gen.d.ts +6 -0
  205. package/dist/server/handlers/image-gen.js +409 -0
  206. package/dist/server/handlers/inventory.d.ts +319 -0
  207. package/dist/server/handlers/inventory.js +447 -0
  208. package/dist/server/handlers/kali.d.ts +10 -0
  209. package/dist/server/handlers/kali.js +210 -0
  210. package/dist/server/handlers/llm-providers.d.ts +6 -0
  211. package/dist/server/handlers/llm-providers.js +673 -0
  212. package/dist/server/handlers/local-agent.d.ts +6 -0
  213. package/dist/server/handlers/local-agent.js +118 -0
  214. package/dist/server/handlers/meta-ads.d.ts +111 -0
  215. package/dist/server/handlers/meta-ads.js +2279 -0
  216. package/dist/server/handlers/nodes.d.ts +33 -0
  217. package/dist/server/handlers/nodes.js +699 -0
  218. package/dist/server/handlers/operations.d.ts +138 -0
  219. package/dist/server/handlers/operations.js +131 -0
  220. package/dist/server/handlers/platform.d.ts +23 -0
  221. package/dist/server/handlers/platform.js +227 -0
  222. package/dist/server/handlers/supply-chain.d.ts +19 -0
  223. package/dist/server/handlers/supply-chain.js +327 -0
  224. package/dist/server/handlers/transcription.d.ts +17 -0
  225. package/dist/server/handlers/transcription.js +121 -0
  226. package/dist/server/handlers/video-gen.d.ts +6 -0
  227. package/dist/server/handlers/video-gen.js +466 -0
  228. package/dist/server/handlers/voice.d.ts +8 -0
  229. package/dist/server/handlers/voice.js +1146 -0
  230. package/dist/server/handlers/workflow-steps.d.ts +86 -0
  231. package/dist/server/handlers/workflow-steps.js +2349 -0
  232. package/dist/server/handlers/workflows.d.ts +7 -0
  233. package/dist/server/handlers/workflows.js +989 -0
  234. package/dist/server/index.d.ts +1 -0
  235. package/dist/server/index.js +2427 -0
  236. package/dist/server/lib/batch-client.d.ts +80 -0
  237. package/dist/server/lib/batch-client.js +467 -0
  238. package/dist/server/lib/code-worker-pool.d.ts +31 -0
  239. package/dist/server/lib/code-worker-pool.js +224 -0
  240. package/dist/server/lib/code-worker.d.ts +1 -0
  241. package/dist/server/lib/code-worker.js +188 -0
  242. package/dist/server/lib/compaction-service.d.ts +32 -0
  243. package/dist/server/lib/compaction-service.js +162 -0
  244. package/dist/server/lib/logger.d.ts +19 -0
  245. package/dist/server/lib/logger.js +46 -0
  246. package/dist/server/lib/otel.d.ts +38 -0
  247. package/dist/server/lib/otel.js +126 -0
  248. package/dist/server/lib/pg-rate-limiter.d.ts +21 -0
  249. package/dist/server/lib/pg-rate-limiter.js +86 -0
  250. package/dist/server/lib/prompt-sanitizer.d.ts +37 -0
  251. package/dist/server/lib/prompt-sanitizer.js +177 -0
  252. package/dist/server/lib/provider-capabilities.d.ts +85 -0
  253. package/dist/server/lib/provider-capabilities.js +190 -0
  254. package/dist/server/lib/provider-failover.d.ts +74 -0
  255. package/dist/server/lib/provider-failover.js +210 -0
  256. package/dist/server/lib/rate-limiter.d.ts +39 -0
  257. package/dist/server/lib/rate-limiter.js +147 -0
  258. package/dist/server/lib/server-agent-loop.d.ts +107 -0
  259. package/dist/server/lib/server-agent-loop.js +667 -0
  260. package/dist/server/lib/server-subagent.d.ts +78 -0
  261. package/dist/server/lib/server-subagent.js +203 -0
  262. package/dist/server/lib/session-checkpoint.d.ts +51 -0
  263. package/dist/server/lib/session-checkpoint.js +145 -0
  264. package/dist/server/lib/ssrf-guard.d.ts +13 -0
  265. package/dist/server/lib/ssrf-guard.js +240 -0
  266. package/dist/server/lib/supabase-client.d.ts +7 -0
  267. package/dist/server/lib/supabase-client.js +78 -0
  268. package/dist/server/lib/template-resolver.d.ts +31 -0
  269. package/dist/server/lib/template-resolver.js +215 -0
  270. package/dist/server/lib/utils.d.ts +16 -0
  271. package/dist/server/lib/utils.js +147 -0
  272. package/dist/server/local-agent-gateway.d.ts +82 -0
  273. package/dist/server/local-agent-gateway.js +426 -0
  274. package/dist/server/providers/anthropic.d.ts +20 -0
  275. package/dist/server/providers/anthropic.js +199 -0
  276. package/dist/server/providers/bedrock.d.ts +20 -0
  277. package/dist/server/providers/bedrock.js +194 -0
  278. package/dist/server/providers/gemini.d.ts +24 -0
  279. package/dist/server/providers/gemini.js +486 -0
  280. package/dist/server/providers/openai.d.ts +24 -0
  281. package/dist/server/providers/openai.js +522 -0
  282. package/dist/server/providers/registry.d.ts +32 -0
  283. package/dist/server/providers/registry.js +58 -0
  284. package/dist/server/providers/shared.d.ts +32 -0
  285. package/dist/server/providers/shared.js +124 -0
  286. package/dist/server/providers/types.d.ts +92 -0
  287. package/dist/server/providers/types.js +12 -0
  288. package/dist/server/proxy-handlers.d.ts +6 -0
  289. package/dist/server/proxy-handlers.js +89 -0
  290. package/dist/server/tool-router.d.ts +149 -0
  291. package/dist/server/tool-router.js +803 -0
  292. package/dist/server/validation.d.ts +24 -0
  293. package/dist/server/validation.js +301 -0
  294. package/dist/server/worker.d.ts +19 -0
  295. package/dist/server/worker.js +201 -0
  296. package/dist/setup.d.ts +8 -0
  297. package/dist/setup.js +181 -0
  298. package/dist/shared/agent-core.d.ts +157 -0
  299. package/dist/shared/agent-core.js +534 -0
  300. package/dist/shared/anthropic-types.d.ts +105 -0
  301. package/dist/shared/anthropic-types.js +7 -0
  302. package/dist/shared/api-client.d.ts +90 -0
  303. package/dist/shared/api-client.js +379 -0
  304. package/dist/shared/constants.d.ts +33 -0
  305. package/dist/shared/constants.js +80 -0
  306. package/dist/shared/sse-parser.d.ts +26 -0
  307. package/dist/shared/sse-parser.js +259 -0
  308. package/dist/shared/tool-dispatch.d.ts +52 -0
  309. package/dist/shared/tool-dispatch.js +191 -0
  310. package/dist/shared/types.d.ts +72 -0
  311. package/dist/shared/types.js +7 -0
  312. package/dist/updater.d.ts +25 -0
  313. package/dist/updater.js +140 -0
  314. package/dist/webchat/widget.d.ts +0 -0
  315. package/dist/webchat/widget.js +397 -0
  316. package/package.json +95 -0
  317. package/src/cli/services/builtin-skills/commit.md +19 -0
  318. package/src/cli/services/builtin-skills/review-pr.md +21 -0
  319. package/src/cli/services/builtin-skills/review.md +18 -0
@@ -0,0 +1,198 @@
1
+ /**
2
+ * System Prompt Builder — assembles the full system prompt for the agent loop
3
+ *
4
+ * Extracted from agent-loop.ts for single-responsibility.
5
+ * All consumers should import from agent-loop.ts (re-export facade).
6
+ */
7
+ import { readdirSync } from "fs";
8
+ import { loadConfig } from "./config-store.js";
9
+ import { loadMemory } from "./memory-manager.js";
10
+ import { loadClaudeMd } from "./claude-md-loader.js";
11
+ import { gatherGitContext } from "./git-context.js";
12
+ import { getPermissionMode } from "./permission-modes.js";
13
+ export async function buildSystemPrompt(hasServerTools, effort) {
14
+ const sections = [];
15
+ // ── Identity ──
16
+ sections.push(`You are whale code, an interactive CLI agent for software engineering and business operations.
17
+ You help users with coding tasks, debugging, refactoring, and managing business data through tools.`);
18
+ // ── Environment ──
19
+ const envLines = [
20
+ `Working directory: ${process.cwd()}`,
21
+ `Platform: ${process.platform}`,
22
+ `Date: ${new Date().toISOString().split("T")[0]}`,
23
+ ];
24
+ // Store context — critical for server tools to operate on the right data
25
+ const storeConfig = loadConfig();
26
+ if (storeConfig.store_name || storeConfig.store_id) {
27
+ envLines.push(`Active store: ${storeConfig.store_name || storeConfig.store_id}`);
28
+ }
29
+ const gitContext = await gatherGitContext();
30
+ if (gitContext)
31
+ envLines.push(`\n${gitContext}`);
32
+ // Directory listing — top-level files/folders for spatial awareness
33
+ try {
34
+ const entries = readdirSync(process.cwd(), { withFileTypes: true });
35
+ const dirs = entries.filter(e => e.isDirectory() && !e.name.startsWith(".")).map(e => e.name + "/").sort();
36
+ const fileNames = entries.filter(e => e.isFile()).map(e => e.name).sort();
37
+ const listing = [...dirs, ...fileNames].slice(0, 30);
38
+ if (listing.length > 0) {
39
+ envLines.push(`\nDirectory contents:\n${listing.join("\n")}`);
40
+ }
41
+ }
42
+ catch { /* cwd not readable */ }
43
+ sections.push(`# Environment\n${envLines.join("\n")}`);
44
+ // ── Doing tasks ──
45
+ sections.push(`# Doing tasks
46
+ - The user will primarily request software engineering tasks: solving bugs, adding features, refactoring, explaining code, and more.
47
+ - You are highly capable and can complete ambitious, multi-step tasks autonomously. Defer to user judgement about scope.
48
+ - ALWAYS read relevant code before proposing changes. Do not modify files you haven't read. Understand existing patterns before editing.
49
+ - Prefer editing existing files over creating new ones. Do not create files unless absolutely necessary.
50
+ - Avoid over-engineering. Only make changes that are directly requested or clearly necessary. Keep solutions simple and focused.
51
+ - Don't add features, refactor code, or make "improvements" beyond what was asked.
52
+ - Don't add error handling or validation for scenarios that can't happen.
53
+ - Don't create abstractions for one-time operations.
54
+ - Be careful not to introduce security vulnerabilities (command injection, XSS, SQL injection, etc.). If you notice insecure code you wrote, fix it immediately.
55
+ - If your approach is blocked, do not brute force. Consider alternative approaches or ask the user.`);
56
+ // ── Coding workflow ──
57
+ sections.push(`# Mandatory coding workflow
58
+ When making code changes, ALWAYS follow this sequence:
59
+
60
+ 1. **Read** — Read the files you intend to modify. Understand the existing code, imports, types, and patterns.
61
+ 2. **Plan** — For non-trivial changes, briefly state what you'll change and why BEFORE editing. For multi-file changes, list the files and the change for each.
62
+ 3. **Edit** — Make targeted, minimal changes. Keep edit batches small (5 or fewer edits before verifying).
63
+ 4. **Verify** — After each batch of edits, run the build or tests (e.g. \`npm run build\`, \`tsc --noEmit\`, \`pytest\`). Read the output. Fix errors before making more edits.
64
+ 5. **Report** — Summarize what you changed and the verification results.
65
+
66
+ CRITICAL RULES:
67
+ - NEVER skip step 1. Do not edit files you haven't read in this session.
68
+ - NEVER make more than 5-8 edits without running a verification step.
69
+ - If a build or test fails, read the error output carefully before attempting a fix. Do not guess.
70
+ - If the same fix approach fails twice, STOP. Re-read the relevant code and try a fundamentally different approach.
71
+ - If you are stuck after 3 failed attempts, explain what you've tried and ask the user for guidance.`);
72
+ // ── Actions with care ──
73
+ sections.push(`# Executing actions with care
74
+ Consider the reversibility and blast radius of your actions:
75
+ - Freely take local, reversible actions like editing files or running tests.
76
+ - For hard-to-reverse or shared-state actions (deleting files, force-pushing, modifying CI, sending messages), check with the user first.
77
+ - Do not use destructive actions as shortcuts. Identify root causes rather than bypassing safety checks.
78
+ - If you encounter unexpected state (unfamiliar files, branches, config), investigate before overwriting — it may be the user's in-progress work.`);
79
+ // ── Tool use ──
80
+ let toolSection = `# Using tools
81
+ - Use the RIGHT tool for the job. Do NOT use run_command when a dedicated tool exists:
82
+ - read_file to read files (not \`cat\` or \`head\`)
83
+ - edit_file or multi_edit to edit files (not \`sed\` or \`awk\`)
84
+ - write_file to create files (not \`echo >\` or heredocs)
85
+ - glob to find files by pattern (not \`find\` or \`ls\`)
86
+ - grep to search content (not \`grep\` or \`rg\` via run_command)
87
+ - run_command ONLY for shell operations: build, test, git, install, etc.
88
+ - Call multiple INDEPENDENT tools in a single response for parallel execution. Do not chain when results are independent.
89
+ - Only chain across turns when a result is needed for the next call.
90
+ - If a tool fails, read the error. If it fails 3 times, try a different tool or approach entirely.
91
+ - All file paths in tool calls should be relative to the working directory when possible (e.g. "src/foo.ts" not "/Users/name/project/src/foo.ts").
92
+ - When the user drops a file path, read it with read_file before responding.
93
+
94
+ ## Subagents (task tool)
95
+ - Subagents run in isolated context — use them freely for parallel work without polluting your main conversation.
96
+ - Use subagents when a task requires 3+ tool calls or touches multiple parts of the codebase.
97
+ - Launch multiple subagents in parallel for independent research (e.g., searching different directories simultaneously).
98
+ - Use task with run_in_background:true for long-running tasks; check with task_output, stop with task_stop.
99
+ - Skip subagents only when a single glob or read_file gives you the answer directly.
100
+ - Prefer "explore" type for quick codebase searches (2-4 turns). Prefer "general-purpose" for autonomous multi-step tasks.
101
+ - Cost-aware model routing:
102
+ - model:"haiku" — file searches, schema lookups, simple reads, pattern matching ($1/$5 per 1M tokens)
103
+ - model:"sonnet" — code analysis, multi-step research, plan design ($3/$15 per 1M tokens)
104
+ - model:"opus" — complex reasoning, judgment calls ($5/$25 per 1M tokens, use sparingly)
105
+
106
+ ## Teams (team_create tool)
107
+ - Do NOT use team_create for bug fixes or single-file changes — work directly. Teams are for large features with 3+ independent workstreams.
108
+ - When creating teams, assign per-task models based on complexity. Most tasks should use haiku or sonnet.`;
109
+ if (hasServerTools) {
110
+ const storeCtx = storeConfig.store_name ? ` All operations are scoped to the active store: **${storeConfig.store_name}**.` : "";
111
+ toolSection += `
112
+
113
+ ## Server tools (business operations)
114
+ - Server tools (analytics, products, inventory, customers, orders, email, workflows, etc.) operate on the active store's data.${storeCtx}
115
+ - These tools require UUIDs for mutations. ALWAYS look up IDs first: use find/list actions to resolve names to UUIDs before calling create/update/delete.
116
+ - The store_id is automatically included in every server tool call — you do NOT need to pass it manually.
117
+ - Use analytics for sales, revenue, and performance data. Use inventory for stock levels. Use products for the catalog.
118
+ - Use audit_trail for store activity history (inventory changes, orders, transfers).
119
+ - Use telemetry for AI system metrics (conversations, tool performance, errors).
120
+ - **Inventory workflow**: (1) Find product with products tool (action=find), (2) Look up location with inventory tool (action=summary or by_location) to get location_id, (3) Use inventory tool with adjust/set and the resolved UUIDs. Always provide a reason for adjustments.
121
+ - **Purchase Order workflow**: (1) Find supplier with supply_chain (action=find_suppliers), (2) Find products with products (action=find), (3) supply_chain action=po_create with supplier_id, location_id, items array, (4) supply_chain action=po_approve, (5) supply_chain action=po_receive to add inventory.
122
+ - **Transfer workflow**: supply_chain action=transfer_create with from_location_id, to_location_id, items → supply_chain action=transfer_receive.
123
+ - The inventory tool has a quick one-step transfer (action=transfer) for simple moves. Use supply_chain transfers for formal tracked transfers with approval flow.
124
+ - Media tools (voice, image_gen, video_gen) auto-download generated files to the current working directory. The result contains a local_file path — report that path to the user. NEVER construct, guess, or curl URLs yourself.
125
+ - **Music generation workflow** (use this for ALL song requests):
126
+ 1. For best vocal clarity, call music_plan first to get a structured composition_plan with proper sections, lyrics per line, and timing
127
+ 2. Review/tweak the plan (edit lyrics, adjust section durations, add style cues)
128
+ 3. Pass the composition_plan to music_compose to generate the final song
129
+ 4. music_compose auto-injects vocal clarity styles (clear vocals, crisp pronunciation) and uses 192kbps quality
130
+ - For quick/simple songs, music_compose with a prompt still works but may have less clear vocals
131
+ - For complex songs with multiple sections, use music_compose_detailed — supports section-by-section control with with_timestamps for precise timing
132
+ - Set force_instrumental:false (default) for vocals. NEVER use speak (TTS) for song vocals — TTS speaks, it doesn't sing
133
+ - Only set force_instrumental:true when the user explicitly wants a karaoke/backing track
134
+ - For clear lyrics: use [Verse], [Chorus], [Bridge] markers, include BPM and key (e.g. "120 BPM, key of C major")
135
+ - For vocal style: add descriptors like "clear female vocals", "male rapper", "a cappella chorus"
136
+ - Exclude bad qualities: composition_plan supports negative_global_styles like "distorted vocals", "mumbled lyrics"
137
+ - **Batch TTS**: For generating multiple audio clips at once (up to 10), use voice tool with action=batch and items=[{text, voice_name?, voice_id?}, ...]. More efficient than sequential speak calls.
138
+ - **Voice cloning** (two tiers):
139
+ - **Instant (IVC)**: action=clone_voice — quick, ~70% accuracy. Good for casual use. Pass file_paths=[...], CLI reads files automatically.
140
+ - **Professional (PVC)**: Near-perfect accuracy, multi-step workflow:
141
+ 1. pvc_create(voice_name="Name") — creates PVC voice slot
142
+ 2. pvc_upload(voice_id=..., file_paths=[...]) — upload 30+ min audio for best results
143
+ 3. pvc_separate_speakers(voice_id=..., sample_id=...) — if audio has multiple speakers
144
+ 4. pvc_status(voice_id=..., sample_id=...) — check separation progress
145
+ 5. pvc_select_speaker(voice_id=..., sample_id=..., speaker_ids=[...]) — pick the right speaker
146
+ 6. pvc_verify(voice_id=...) — submit for manual verification (required by ElevenLabs)
147
+ 7. pvc_train(voice_id=...) — start training (5-30 min). Check with pvc_status(voice_id=...).
148
+ - Use IVC for quick tests, PVC for production-quality voice clones.
149
+ - file_path (single) or file_paths (array) works for clone_voice, pvc_upload, pvc_verify, voice_design, speech_to_text, voice_changer, audio_isolation, stem_separation, forced_alignment — pass file paths directly, NEVER base64-encode via bash.
150
+ - If given a directory of clips, use glob to find all MP3s, then pass all paths at once.
151
+ - **Voice settings**: Cloned voices auto-use optimized settings (higher similarity, lower stability). Override with explicit stability/similarity_boost params if needed.
152
+ - **Voice tool**: Accepts voice names (e.g. "Daniel", "Sarah") — no need to look up voice IDs. Use search_voices to find voices by style/accent/gender.`;
153
+ }
154
+ sections.push(toolSection);
155
+ // ── Permission mode ──
156
+ const permissionMode = getPermissionMode();
157
+ if (permissionMode === "plan") {
158
+ sections.push(`# Mode: Plan (read-only)
159
+ You are in plan mode. Only read and search tools are available. No file writes or commands.`);
160
+ }
161
+ else if (permissionMode === "yolo") {
162
+ sections.push(`# Mode: Yolo
163
+ All tools available without confirmation prompts.`);
164
+ }
165
+ // ── Effort ──
166
+ if (effort === "low") {
167
+ sections.push(`# Effort: Low
168
+ Be concise and direct. Minimize exploration. Give brief answers. Skip verification for trivial changes.`);
169
+ }
170
+ else if (effort === "high") {
171
+ sections.push(`# Effort: High
172
+ Be thorough and exhaustive. Explore deeply. Verify all changes. Consider edge cases.`);
173
+ }
174
+ // ── Tone and style ──
175
+ sections.push(`# Tone and style
176
+ - Be concise. Use tools to do work — don't just explain what you would do.
177
+ - NEVER use emojis — terminal renders them as broken glyphs.
178
+ - Include $ on monetary values, % on percentages.
179
+ - When referencing code, include file_path:line_number for easy navigation.
180
+ - Keep output clean and monospace-aligned.
181
+ - Use markdown tables for multi-column data.
182
+ - Use \`\`\`chart code blocks for bar charts:
183
+ \`\`\`chart
184
+ Title
185
+ Label: $value
186
+ \`\`\``);
187
+ // ── Persistent memory ──
188
+ const memory = loadMemory();
189
+ if (memory) {
190
+ sections.push(`# Memory (persistent across sessions)\n${memory}`);
191
+ }
192
+ // ── Project instructions ──
193
+ const claudeMd = loadClaudeMd();
194
+ if (claudeMd) {
195
+ sections.push(`# Project Instructions (${claudeMd.path})\n${claudeMd.content}`);
196
+ }
197
+ return sections.join("\n\n");
198
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Team Lead — Coordinator for Agent Teams
3
+ *
4
+ * Following Anthropic's official patterns:
5
+ * - Spawns and manages teammates
6
+ * - Creates and assigns tasks
7
+ * - Monitors progress
8
+ * - Synthesizes results
9
+ */
10
+ import { EventEmitter } from "events";
11
+ export interface TeamConfig {
12
+ name: string;
13
+ teammateCount: number;
14
+ model?: "sonnet" | "opus" | "haiku";
15
+ tasks: Array<{
16
+ description: string;
17
+ model?: string;
18
+ files?: string[];
19
+ dependencies?: string[];
20
+ }>;
21
+ teammateNames?: string[];
22
+ }
23
+ export interface TeamResult {
24
+ success: boolean;
25
+ teamId: string;
26
+ summary: string;
27
+ taskResults: Array<{
28
+ description: string;
29
+ result: string;
30
+ status: "completed" | "failed";
31
+ }>;
32
+ tokensUsed: {
33
+ input: number;
34
+ output: number;
35
+ };
36
+ durationMs: number;
37
+ }
38
+ export declare class TeamLead extends EventEmitter {
39
+ private teamId;
40
+ private workers;
41
+ private lastMessageTime;
42
+ private teamTimer;
43
+ private stallInterval;
44
+ private resolveTeam;
45
+ private traceId;
46
+ private spanId;
47
+ private startTime;
48
+ constructor();
49
+ /**
50
+ * Generate meaningful teammate names from task descriptions
51
+ * Extracts key action words to create role-based names
52
+ */
53
+ private generateTeammateNames;
54
+ createTeam(config: TeamConfig): Promise<string>;
55
+ runTeam(): Promise<TeamResult>;
56
+ private handleTeammateMessage;
57
+ private handleTeammateFailure;
58
+ private checkCompletion;
59
+ private buildResult;
60
+ sendToTeammate(teammateId: string, message: string): Promise<boolean>;
61
+ broadcast(message: string): Promise<boolean>;
62
+ getMessages(): Promise<Array<{
63
+ from: string;
64
+ content: string;
65
+ }>>;
66
+ getProgress(): {
67
+ total: number;
68
+ completed: number;
69
+ percentComplete: number;
70
+ } | null;
71
+ stop(): void;
72
+ }
73
+ export declare function runAgentTeam(config: TeamConfig): Promise<TeamResult>;