agent.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import { Config } from "../config/config"
  2. import z from "zod"
  3. import { Provider } from "../provider/provider"
  4. import { generateObject, type ModelMessage } from "ai"
  5. import { SystemPrompt } from "../session/system"
  6. import { Instance } from "../project/instance"
  7. import { mergeDeep } from "remeda"
  8. import { Log } from "../util/log"
  9. const log = Log.create({ service: "agent" })
  10. import PROMPT_GENERATE from "./generate.txt"
  11. import PROMPT_COMPACTION from "./prompt/compaction.txt"
  12. import PROMPT_EXPLORE from "./prompt/explore.txt"
  13. import PROMPT_SUMMARY from "./prompt/summary.txt"
  14. import PROMPT_TITLE from "./prompt/title.txt"
  15. export namespace Agent {
  16. export const Info = z
  17. .object({
  18. name: z.string(),
  19. description: z.string().optional(),
  20. mode: z.enum(["subagent", "primary", "all"]),
  21. native: z.boolean().optional(),
  22. hidden: z.boolean().optional(),
  23. default: z.boolean().optional(),
  24. topP: z.number().optional(),
  25. temperature: z.number().optional(),
  26. color: z.string().optional(),
  27. permission: z.object({
  28. edit: Config.Permission,
  29. bash: z.record(z.string(), Config.Permission),
  30. skill: z.record(z.string(), Config.Permission),
  31. webfetch: Config.Permission.optional(),
  32. doom_loop: Config.Permission.optional(),
  33. external_directory: Config.Permission.optional(),
  34. }),
  35. model: z
  36. .object({
  37. modelID: z.string(),
  38. providerID: z.string(),
  39. })
  40. .optional(),
  41. prompt: z.string().optional(),
  42. tools: z.record(z.string(), z.boolean()),
  43. options: z.record(z.string(), z.any()),
  44. maxSteps: z.number().int().positive().optional(),
  45. })
  46. .meta({
  47. ref: "Agent",
  48. })
  49. export type Info = z.infer<typeof Info>
  50. const state = Instance.state(async () => {
  51. const cfg = await Config.get()
  52. const defaultTools = cfg.tools ?? {}
  53. const defaultPermission: Info["permission"] = {
  54. edit: "allow",
  55. bash: {
  56. "*": "allow",
  57. },
  58. skill: {
  59. "*": "allow",
  60. },
  61. webfetch: "allow",
  62. doom_loop: "ask",
  63. external_directory: "ask",
  64. }
  65. const agentPermission = mergeAgentPermissions(defaultPermission, cfg.permission ?? {})
  66. const planPermission = mergeAgentPermissions(
  67. {
  68. edit: "deny",
  69. bash: {
  70. "cut*": "allow",
  71. "diff*": "allow",
  72. "du*": "allow",
  73. "file *": "allow",
  74. "find * -delete*": "ask",
  75. "find * -exec*": "ask",
  76. "find * -fprint*": "ask",
  77. "find * -fls*": "ask",
  78. "find * -fprintf*": "ask",
  79. "find * -ok*": "ask",
  80. "find *": "allow",
  81. "git diff*": "allow",
  82. "git log*": "allow",
  83. "git show*": "allow",
  84. "git status*": "allow",
  85. "git branch": "allow",
  86. "git branch -v": "allow",
  87. "grep*": "allow",
  88. "head*": "allow",
  89. "less*": "allow",
  90. "ls*": "allow",
  91. "more*": "allow",
  92. "pwd*": "allow",
  93. "rg*": "allow",
  94. "sort --output=*": "ask",
  95. "sort -o *": "ask",
  96. "sort*": "allow",
  97. "stat*": "allow",
  98. "tail*": "allow",
  99. "tree -o *": "ask",
  100. "tree*": "allow",
  101. "uniq*": "allow",
  102. "wc*": "allow",
  103. "whereis*": "allow",
  104. "which*": "allow",
  105. "*": "ask",
  106. },
  107. webfetch: "allow",
  108. },
  109. cfg.permission ?? {},
  110. )
  111. const result: Record<string, Info> = {
  112. build: {
  113. name: "build",
  114. tools: { ...defaultTools },
  115. options: {},
  116. permission: agentPermission,
  117. mode: "primary",
  118. native: true,
  119. },
  120. plan: {
  121. name: "plan",
  122. options: {},
  123. permission: planPermission,
  124. tools: {
  125. ...defaultTools,
  126. },
  127. mode: "primary",
  128. native: true,
  129. },
  130. general: {
  131. name: "general",
  132. description: `General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.`,
  133. tools: {
  134. todoread: false,
  135. todowrite: false,
  136. ...defaultTools,
  137. },
  138. options: {},
  139. permission: agentPermission,
  140. mode: "subagent",
  141. native: true,
  142. hidden: true,
  143. },
  144. explore: {
  145. name: "explore",
  146. tools: {
  147. todoread: false,
  148. todowrite: false,
  149. edit: false,
  150. write: false,
  151. ...defaultTools,
  152. },
  153. description: `Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.`,
  154. prompt: PROMPT_EXPLORE,
  155. options: {},
  156. permission: agentPermission,
  157. mode: "subagent",
  158. native: true,
  159. },
  160. compaction: {
  161. name: "compaction",
  162. mode: "primary",
  163. native: true,
  164. hidden: true,
  165. prompt: PROMPT_COMPACTION,
  166. tools: {
  167. "*": false,
  168. },
  169. options: {},
  170. permission: agentPermission,
  171. },
  172. title: {
  173. name: "title",
  174. mode: "primary",
  175. options: {},
  176. native: true,
  177. hidden: true,
  178. permission: agentPermission,
  179. prompt: PROMPT_TITLE,
  180. tools: {},
  181. },
  182. summary: {
  183. name: "summary",
  184. mode: "primary",
  185. options: {},
  186. native: true,
  187. hidden: true,
  188. permission: agentPermission,
  189. prompt: PROMPT_SUMMARY,
  190. tools: {},
  191. },
  192. }
  193. for (const [key, value] of Object.entries(cfg.agent ?? {})) {
  194. if (value.disable) {
  195. delete result[key]
  196. continue
  197. }
  198. let item = result[key]
  199. if (!item)
  200. item = result[key] = {
  201. name: key,
  202. mode: "all",
  203. permission: agentPermission,
  204. options: {},
  205. tools: {},
  206. native: false,
  207. }
  208. const {
  209. name,
  210. model,
  211. prompt,
  212. tools,
  213. description,
  214. temperature,
  215. top_p,
  216. mode,
  217. permission,
  218. color,
  219. maxSteps,
  220. ...extra
  221. } = value
  222. item.options = {
  223. ...item.options,
  224. ...extra,
  225. }
  226. if (model) item.model = Provider.parseModel(model)
  227. if (prompt) item.prompt = prompt
  228. if (tools)
  229. item.tools = {
  230. ...item.tools,
  231. ...tools,
  232. }
  233. item.tools = {
  234. ...defaultTools,
  235. ...item.tools,
  236. }
  237. if (description) item.description = description
  238. if (temperature != undefined) item.temperature = temperature
  239. if (top_p != undefined) item.topP = top_p
  240. if (mode) item.mode = mode
  241. if (color) item.color = color
  242. // just here for consistency & to prevent it from being added as an option
  243. if (name) item.name = name
  244. if (maxSteps != undefined) item.maxSteps = maxSteps
  245. if (permission ?? cfg.permission) {
  246. item.permission = mergeAgentPermissions(cfg.permission ?? {}, permission ?? {})
  247. }
  248. }
  249. // Mark the default agent
  250. const defaultName = cfg.default_agent ?? "build"
  251. const defaultCandidate = result[defaultName]
  252. if (defaultCandidate && defaultCandidate.mode !== "subagent") {
  253. defaultCandidate.default = true
  254. } else {
  255. // Fall back to "build" if configured default is invalid
  256. if (result["build"]) {
  257. result["build"].default = true
  258. }
  259. }
  260. const hasPrimaryAgents = Object.values(result).filter((a) => a.mode !== "subagent" && !a.hidden).length > 0
  261. if (!hasPrimaryAgents) {
  262. throw new Config.InvalidError({
  263. path: "config",
  264. message: "No primary agents are available. Please configure at least one agent with mode 'primary' or 'all'.",
  265. })
  266. }
  267. return result
  268. })
  269. export async function get(agent: string) {
  270. return state().then((x) => x[agent])
  271. }
  272. export async function list() {
  273. return state().then((x) => Object.values(x))
  274. }
  275. export async function defaultAgent(): Promise<string> {
  276. const agents = await state()
  277. const defaultCandidate = Object.values(agents).find((a) => a.default)
  278. return defaultCandidate?.name ?? "build"
  279. }
  280. export async function generate(input: { description: string; model?: { providerID: string; modelID: string } }) {
  281. const cfg = await Config.get()
  282. const defaultModel = input.model ?? (await Provider.defaultModel())
  283. const model = await Provider.getModel(defaultModel.providerID, defaultModel.modelID)
  284. const language = await Provider.getLanguage(model)
  285. const system = SystemPrompt.header(defaultModel.providerID)
  286. system.push(PROMPT_GENERATE)
  287. const existing = await list()
  288. const result = await generateObject({
  289. experimental_telemetry: {
  290. isEnabled: cfg.experimental?.openTelemetry,
  291. metadata: {
  292. userId: cfg.username ?? "unknown",
  293. },
  294. },
  295. temperature: 0.3,
  296. messages: [
  297. ...system.map(
  298. (item): ModelMessage => ({
  299. role: "system",
  300. content: item,
  301. }),
  302. ),
  303. {
  304. role: "user",
  305. content: `Create an agent configuration based on this request: \"${input.description}\".\n\nIMPORTANT: The following identifiers already exist and must NOT be used: ${existing.map((i) => i.name).join(", ")}\n Return ONLY the JSON object, no other text, do not wrap in backticks`,
  306. },
  307. ],
  308. model: language,
  309. schema: z.object({
  310. identifier: z.string(),
  311. whenToUse: z.string(),
  312. systemPrompt: z.string(),
  313. }),
  314. })
  315. return result.object
  316. }
  317. }
  318. function mergeAgentPermissions(basePermission: any, overridePermission: any): Agent.Info["permission"] {
  319. if (typeof basePermission.bash === "string") {
  320. basePermission.bash = {
  321. "*": basePermission.bash,
  322. }
  323. }
  324. if (typeof overridePermission.bash === "string") {
  325. overridePermission.bash = {
  326. "*": overridePermission.bash,
  327. }
  328. }
  329. if (typeof basePermission.skill === "string") {
  330. basePermission.skill = {
  331. "*": basePermission.skill,
  332. }
  333. }
  334. if (typeof overridePermission.skill === "string") {
  335. overridePermission.skill = {
  336. "*": overridePermission.skill,
  337. }
  338. }
  339. const merged = mergeDeep(basePermission ?? {}, overridePermission ?? {}) as any
  340. let mergedBash
  341. if (merged.bash) {
  342. if (typeof merged.bash === "string") {
  343. mergedBash = {
  344. "*": merged.bash,
  345. }
  346. } else if (typeof merged.bash === "object") {
  347. mergedBash = mergeDeep(
  348. {
  349. "*": "allow",
  350. },
  351. merged.bash,
  352. )
  353. }
  354. }
  355. let mergedSkill
  356. if (merged.skill) {
  357. if (typeof merged.skill === "string") {
  358. mergedSkill = {
  359. "*": merged.skill,
  360. }
  361. } else if (typeof merged.skill === "object") {
  362. mergedSkill = mergeDeep(
  363. {
  364. "*": "allow",
  365. },
  366. merged.skill,
  367. )
  368. }
  369. }
  370. const result: Agent.Info["permission"] = {
  371. edit: merged.edit ?? "allow",
  372. webfetch: merged.webfetch ?? "allow",
  373. bash: mergedBash ?? { "*": "allow" },
  374. skill: mergedSkill ?? { "*": "allow" },
  375. doom_loop: merged.doom_loop,
  376. external_directory: merged.external_directory,
  377. }
  378. return result
  379. }