prompt.ts 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  1. import path from "path"
  2. import os from "os"
  3. import fs from "fs/promises"
  4. import z from "zod"
  5. import { Identifier } from "../id/id"
  6. import { MessageV2 } from "./message-v2"
  7. import { Log } from "../util/log"
  8. import { SessionRevert } from "./revert"
  9. import { Session } from "."
  10. import { Agent } from "../agent/agent"
  11. import { Provider } from "../provider/provider"
  12. import { type Tool as AITool, tool, jsonSchema, type ToolCallOptions } from "ai"
  13. import { SessionCompaction } from "./compaction"
  14. import { Instance } from "../project/instance"
  15. import { Bus } from "../bus"
  16. import { ProviderTransform } from "../provider/transform"
  17. import { SystemPrompt } from "./system"
  18. import { InstructionPrompt } from "./instruction"
  19. import { Plugin } from "../plugin"
  20. import PROMPT_PLAN from "../session/prompt/plan.txt"
  21. import BUILD_SWITCH from "../session/prompt/build-switch.txt"
  22. import MAX_STEPS from "../session/prompt/max-steps.txt"
  23. import { defer } from "../util/defer"
  24. import { clone } from "remeda"
  25. import { ToolRegistry } from "../tool/registry"
  26. import { MCP } from "../mcp"
  27. import { LSP } from "../lsp"
  28. import { ReadTool } from "../tool/read"
  29. import { ListTool } from "../tool/ls"
  30. import { FileTime } from "../file/time"
  31. import { Flag } from "../flag/flag"
  32. import { ulid } from "ulid"
  33. import { spawn } from "child_process"
  34. import { Command } from "../command"
  35. import { $, fileURLToPath } from "bun"
  36. import { ConfigMarkdown } from "../config/markdown"
  37. import { SessionSummary } from "./summary"
  38. import { NamedError } from "@opencode-ai/util/error"
  39. import { fn } from "@/util/fn"
  40. import { SessionProcessor } from "./processor"
  41. import { TaskTool } from "@/tool/task"
  42. import { Tool } from "@/tool/tool"
  43. import { PermissionNext } from "@/permission/next"
  44. import { SessionStatus } from "./status"
  45. import { LLM } from "./llm"
  46. import { iife } from "@/util/iife"
  47. import { Shell } from "@/shell/shell"
  48. import { Truncate } from "@/tool/truncation"
  49. // @ts-ignore
  50. globalThis.AI_SDK_LOG_WARNINGS = false
  51. export namespace SessionPrompt {
  52. const log = Log.create({ service: "session.prompt" })
  53. export const OUTPUT_TOKEN_MAX = Flag.OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX || 32_000
  54. const state = Instance.state(
  55. () => {
  56. const data: Record<
  57. string,
  58. {
  59. abort: AbortController
  60. callbacks: {
  61. resolve(input: MessageV2.WithParts): void
  62. reject(): void
  63. }[]
  64. }
  65. > = {}
  66. return data
  67. },
  68. async (current) => {
  69. for (const item of Object.values(current)) {
  70. item.abort.abort()
  71. for (const callback of item.callbacks) {
  72. callback.reject()
  73. }
  74. }
  75. },
  76. )
  77. export function assertNotBusy(sessionID: string) {
  78. const match = state()[sessionID]
  79. if (match) throw new Session.BusyError(sessionID)
  80. }
  81. export const PromptInput = z.object({
  82. sessionID: Identifier.schema("session"),
  83. messageID: Identifier.schema("message").optional(),
  84. model: z
  85. .object({
  86. providerID: z.string(),
  87. modelID: z.string(),
  88. })
  89. .optional(),
  90. agent: z.string().optional(),
  91. noReply: z.boolean().optional(),
  92. tools: z
  93. .record(z.string(), z.boolean())
  94. .optional()
  95. .describe(
  96. "@deprecated tools and permissions have been merged, you can set permissions on the session itself now",
  97. ),
  98. system: z.string().optional(),
  99. variant: z.string().optional(),
  100. parts: z.array(
  101. z.discriminatedUnion("type", [
  102. MessageV2.TextPart.omit({
  103. messageID: true,
  104. sessionID: true,
  105. })
  106. .partial({
  107. id: true,
  108. })
  109. .meta({
  110. ref: "TextPartInput",
  111. }),
  112. MessageV2.FilePart.omit({
  113. messageID: true,
  114. sessionID: true,
  115. })
  116. .partial({
  117. id: true,
  118. })
  119. .meta({
  120. ref: "FilePartInput",
  121. }),
  122. MessageV2.AgentPart.omit({
  123. messageID: true,
  124. sessionID: true,
  125. })
  126. .partial({
  127. id: true,
  128. })
  129. .meta({
  130. ref: "AgentPartInput",
  131. }),
  132. MessageV2.SubtaskPart.omit({
  133. messageID: true,
  134. sessionID: true,
  135. })
  136. .partial({
  137. id: true,
  138. })
  139. .meta({
  140. ref: "SubtaskPartInput",
  141. }),
  142. ]),
  143. ),
  144. })
  145. export type PromptInput = z.infer<typeof PromptInput>
  146. export const prompt = fn(PromptInput, async (input) => {
  147. const session = await Session.get(input.sessionID)
  148. await SessionRevert.cleanup(session)
  149. const message = await createUserMessage(input)
  150. await Session.touch(input.sessionID)
  151. // this is backwards compatibility for allowing `tools` to be specified when
  152. // prompting
  153. const permissions: PermissionNext.Ruleset = []
  154. for (const [tool, enabled] of Object.entries(input.tools ?? {})) {
  155. permissions.push({
  156. permission: tool,
  157. action: enabled ? "allow" : "deny",
  158. pattern: "*",
  159. })
  160. }
  161. if (permissions.length > 0) {
  162. session.permission = permissions
  163. await Session.update(session.id, (draft) => {
  164. draft.permission = permissions
  165. })
  166. }
  167. if (input.noReply === true) {
  168. return message
  169. }
  170. return loop(input.sessionID)
  171. })
  172. export async function resolvePromptParts(template: string): Promise<PromptInput["parts"]> {
  173. const parts: PromptInput["parts"] = [
  174. {
  175. type: "text",
  176. text: template,
  177. },
  178. ]
  179. const matches = ConfigMarkdown.files(template)
  180. const seen = new Set<string>()
  181. const names = matches
  182. .map((match) => match[1])
  183. .filter((name) => {
  184. if (seen.has(name)) return false
  185. seen.add(name)
  186. return true
  187. })
  188. const resolved = await Promise.all(
  189. names.map(async (name) => {
  190. const filepath = name.startsWith("~/")
  191. ? path.join(os.homedir(), name.slice(2))
  192. : path.resolve(Instance.worktree, name)
  193. const stats = await fs.stat(filepath).catch(() => undefined)
  194. if (!stats) {
  195. const agent = await Agent.get(name)
  196. if (!agent) return undefined
  197. return {
  198. type: "agent",
  199. name: agent.name,
  200. } satisfies PromptInput["parts"][number]
  201. }
  202. if (stats.isDirectory()) {
  203. return {
  204. type: "file",
  205. url: `file://${filepath}`,
  206. filename: name,
  207. mime: "application/x-directory",
  208. } satisfies PromptInput["parts"][number]
  209. }
  210. return {
  211. type: "file",
  212. url: `file://${filepath}`,
  213. filename: name,
  214. mime: "text/plain",
  215. } satisfies PromptInput["parts"][number]
  216. }),
  217. )
  218. for (const item of resolved) {
  219. if (!item) continue
  220. parts.push(item)
  221. }
  222. return parts
  223. }
  224. function start(sessionID: string) {
  225. const s = state()
  226. if (s[sessionID]) return
  227. const controller = new AbortController()
  228. s[sessionID] = {
  229. abort: controller,
  230. callbacks: [],
  231. }
  232. return controller.signal
  233. }
  234. export function cancel(sessionID: string) {
  235. log.info("cancel", { sessionID })
  236. const s = state()
  237. const match = s[sessionID]
  238. if (!match) return
  239. match.abort.abort()
  240. for (const item of match.callbacks) {
  241. item.reject()
  242. }
  243. delete s[sessionID]
  244. SessionStatus.set(sessionID, { type: "idle" })
  245. return
  246. }
  247. export const loop = fn(Identifier.schema("session"), async (sessionID) => {
  248. const abort = start(sessionID)
  249. if (!abort) {
  250. return new Promise<MessageV2.WithParts>((resolve, reject) => {
  251. const callbacks = state()[sessionID].callbacks
  252. callbacks.push({ resolve, reject })
  253. })
  254. }
  255. using _ = defer(() => cancel(sessionID))
  256. let step = 0
  257. const session = await Session.get(sessionID)
  258. while (true) {
  259. SessionStatus.set(sessionID, { type: "busy" })
  260. log.info("loop", { step, sessionID })
  261. if (abort.aborted) break
  262. let msgs = await MessageV2.filterCompacted(MessageV2.stream(sessionID))
  263. let lastUser: MessageV2.User | undefined
  264. let lastAssistant: MessageV2.Assistant | undefined
  265. let lastFinished: MessageV2.Assistant | undefined
  266. let tasks: (MessageV2.CompactionPart | MessageV2.SubtaskPart)[] = []
  267. for (let i = msgs.length - 1; i >= 0; i--) {
  268. const msg = msgs[i]
  269. if (!lastUser && msg.info.role === "user") lastUser = msg.info as MessageV2.User
  270. if (!lastAssistant && msg.info.role === "assistant") lastAssistant = msg.info as MessageV2.Assistant
  271. if (!lastFinished && msg.info.role === "assistant" && msg.info.finish)
  272. lastFinished = msg.info as MessageV2.Assistant
  273. if (lastUser && lastFinished) break
  274. const task = msg.parts.filter((part) => part.type === "compaction" || part.type === "subtask")
  275. if (task && !lastFinished) {
  276. tasks.push(...task)
  277. }
  278. }
  279. if (!lastUser) throw new Error("No user message found in stream. This should never happen.")
  280. if (
  281. lastAssistant?.finish &&
  282. !["tool-calls", "unknown"].includes(lastAssistant.finish) &&
  283. lastUser.id < lastAssistant.id
  284. ) {
  285. log.info("exiting loop", { sessionID })
  286. break
  287. }
  288. step++
  289. if (step === 1)
  290. ensureTitle({
  291. session,
  292. modelID: lastUser.model.modelID,
  293. providerID: lastUser.model.providerID,
  294. history: msgs,
  295. })
  296. const model = await Provider.getModel(lastUser.model.providerID, lastUser.model.modelID)
  297. const task = tasks.pop()
  298. // pending subtask
  299. // TODO: centralize "invoke tool" logic
  300. if (task?.type === "subtask") {
  301. const taskTool = await TaskTool.init()
  302. const taskModel = task.model ? await Provider.getModel(task.model.providerID, task.model.modelID) : model
  303. const assistantMessage = (await Session.updateMessage({
  304. id: Identifier.ascending("message"),
  305. role: "assistant",
  306. parentID: lastUser.id,
  307. sessionID,
  308. mode: task.agent,
  309. agent: task.agent,
  310. path: {
  311. cwd: Instance.directory,
  312. root: Instance.worktree,
  313. },
  314. cost: 0,
  315. tokens: {
  316. input: 0,
  317. output: 0,
  318. reasoning: 0,
  319. cache: { read: 0, write: 0 },
  320. },
  321. modelID: taskModel.id,
  322. providerID: taskModel.providerID,
  323. time: {
  324. created: Date.now(),
  325. },
  326. })) as MessageV2.Assistant
  327. let part = (await Session.updatePart({
  328. id: Identifier.ascending("part"),
  329. messageID: assistantMessage.id,
  330. sessionID: assistantMessage.sessionID,
  331. type: "tool",
  332. callID: ulid(),
  333. tool: TaskTool.id,
  334. state: {
  335. status: "running",
  336. input: {
  337. prompt: task.prompt,
  338. description: task.description,
  339. subagent_type: task.agent,
  340. command: task.command,
  341. },
  342. time: {
  343. start: Date.now(),
  344. },
  345. },
  346. })) as MessageV2.ToolPart
  347. const taskArgs = {
  348. prompt: task.prompt,
  349. description: task.description,
  350. subagent_type: task.agent,
  351. command: task.command,
  352. }
  353. await Plugin.trigger(
  354. "tool.execute.before",
  355. {
  356. tool: "task",
  357. sessionID,
  358. callID: part.id,
  359. },
  360. { args: taskArgs },
  361. )
  362. let executionError: Error | undefined
  363. const taskAgent = await Agent.get(task.agent)
  364. const taskCtx: Tool.Context = {
  365. agent: task.agent,
  366. messageID: assistantMessage.id,
  367. sessionID: sessionID,
  368. abort,
  369. callID: part.callID,
  370. extra: { bypassAgentCheck: true },
  371. messages: msgs,
  372. async metadata(input) {
  373. await Session.updatePart({
  374. ...part,
  375. type: "tool",
  376. state: {
  377. ...part.state,
  378. ...input,
  379. },
  380. } satisfies MessageV2.ToolPart)
  381. },
  382. async ask(req) {
  383. await PermissionNext.ask({
  384. ...req,
  385. sessionID: sessionID,
  386. ruleset: PermissionNext.merge(taskAgent.permission, session.permission ?? []),
  387. })
  388. },
  389. }
  390. const result = await taskTool.execute(taskArgs, taskCtx).catch((error) => {
  391. executionError = error
  392. log.error("subtask execution failed", { error, agent: task.agent, description: task.description })
  393. return undefined
  394. })
  395. await Plugin.trigger(
  396. "tool.execute.after",
  397. {
  398. tool: "task",
  399. sessionID,
  400. callID: part.id,
  401. },
  402. result,
  403. )
  404. assistantMessage.finish = "tool-calls"
  405. assistantMessage.time.completed = Date.now()
  406. await Session.updateMessage(assistantMessage)
  407. if (result && part.state.status === "running") {
  408. const attachments = result.attachments?.map((attachment) => ({
  409. ...attachment,
  410. id: Identifier.ascending("part"),
  411. messageID: assistantMessage.id,
  412. sessionID: assistantMessage.sessionID,
  413. }))
  414. await Session.updatePart({
  415. ...part,
  416. state: {
  417. status: "completed",
  418. input: part.state.input,
  419. title: result.title,
  420. metadata: result.metadata,
  421. output: result.output,
  422. attachments,
  423. time: {
  424. ...part.state.time,
  425. end: Date.now(),
  426. },
  427. },
  428. } satisfies MessageV2.ToolPart)
  429. }
  430. if (!result) {
  431. await Session.updatePart({
  432. ...part,
  433. state: {
  434. status: "error",
  435. error: executionError ? `Tool execution failed: ${executionError.message}` : "Tool execution failed",
  436. time: {
  437. start: part.state.status === "running" ? part.state.time.start : Date.now(),
  438. end: Date.now(),
  439. },
  440. metadata: part.metadata,
  441. input: part.state.input,
  442. },
  443. } satisfies MessageV2.ToolPart)
  444. }
  445. if (task.command) {
  446. // Add synthetic user message to prevent certain reasoning models from erroring
  447. // If we create assistant messages w/ out user ones following mid loop thinking signatures
  448. // will be missing and it can cause errors for models like gemini for example
  449. const summaryUserMsg: MessageV2.User = {
  450. id: Identifier.ascending("message"),
  451. sessionID,
  452. role: "user",
  453. time: {
  454. created: Date.now(),
  455. },
  456. agent: lastUser.agent,
  457. model: lastUser.model,
  458. }
  459. await Session.updateMessage(summaryUserMsg)
  460. await Session.updatePart({
  461. id: Identifier.ascending("part"),
  462. messageID: summaryUserMsg.id,
  463. sessionID,
  464. type: "text",
  465. text: "Summarize the task tool output above and continue with your task.",
  466. synthetic: true,
  467. } satisfies MessageV2.TextPart)
  468. }
  469. continue
  470. }
  471. // pending compaction
  472. if (task?.type === "compaction") {
  473. const result = await SessionCompaction.process({
  474. messages: msgs,
  475. parentID: lastUser.id,
  476. abort,
  477. sessionID,
  478. auto: task.auto,
  479. })
  480. if (result === "stop") break
  481. continue
  482. }
  483. // context overflow, needs compaction
  484. if (
  485. lastFinished &&
  486. lastFinished.summary !== true &&
  487. (await SessionCompaction.isOverflow({ tokens: lastFinished.tokens, model }))
  488. ) {
  489. await SessionCompaction.create({
  490. sessionID,
  491. agent: lastUser.agent,
  492. model: lastUser.model,
  493. auto: true,
  494. })
  495. continue
  496. }
  497. // normal processing
  498. const agent = await Agent.get(lastUser.agent)
  499. const maxSteps = agent.steps ?? Infinity
  500. const isLastStep = step >= maxSteps
  501. msgs = await insertReminders({
  502. messages: msgs,
  503. agent,
  504. session,
  505. })
  506. const processor = SessionProcessor.create({
  507. assistantMessage: (await Session.updateMessage({
  508. id: Identifier.ascending("message"),
  509. parentID: lastUser.id,
  510. role: "assistant",
  511. mode: agent.name,
  512. agent: agent.name,
  513. path: {
  514. cwd: Instance.directory,
  515. root: Instance.worktree,
  516. },
  517. cost: 0,
  518. tokens: {
  519. input: 0,
  520. output: 0,
  521. reasoning: 0,
  522. cache: { read: 0, write: 0 },
  523. },
  524. modelID: model.id,
  525. providerID: model.providerID,
  526. time: {
  527. created: Date.now(),
  528. },
  529. sessionID,
  530. })) as MessageV2.Assistant,
  531. sessionID: sessionID,
  532. model,
  533. abort,
  534. })
  535. using _ = defer(() => InstructionPrompt.clear(processor.message.id))
  536. // Check if user explicitly invoked an agent via @ in this turn
  537. const lastUserMsg = msgs.findLast((m) => m.info.role === "user")
  538. const bypassAgentCheck = lastUserMsg?.parts.some((p) => p.type === "agent") ?? false
  539. const tools = await resolveTools({
  540. agent,
  541. session,
  542. model,
  543. tools: lastUser.tools,
  544. processor,
  545. bypassAgentCheck,
  546. messages: msgs,
  547. })
  548. if (step === 1) {
  549. SessionSummary.summarize({
  550. sessionID: sessionID,
  551. messageID: lastUser.id,
  552. })
  553. }
  554. const sessionMessages = clone(msgs)
  555. // Ephemerally wrap queued user messages with a reminder to stay on track
  556. if (step > 1 && lastFinished) {
  557. for (const msg of sessionMessages) {
  558. if (msg.info.role !== "user" || msg.info.id <= lastFinished.id) continue
  559. for (const part of msg.parts) {
  560. if (part.type !== "text" || part.ignored || part.synthetic) continue
  561. if (!part.text.trim()) continue
  562. part.text = [
  563. "<system-reminder>",
  564. "The user sent the following message:",
  565. part.text,
  566. "",
  567. "Please address this message and continue with your tasks.",
  568. "</system-reminder>",
  569. ].join("\n")
  570. }
  571. }
  572. }
  573. await Plugin.trigger("experimental.chat.messages.transform", {}, { messages: sessionMessages })
  574. const result = await processor.process({
  575. user: lastUser,
  576. agent,
  577. abort,
  578. sessionID,
  579. system: [...(await SystemPrompt.environment(model)), ...(await InstructionPrompt.system())],
  580. messages: [
  581. ...MessageV2.toModelMessages(sessionMessages, model),
  582. ...(isLastStep
  583. ? [
  584. {
  585. role: "assistant" as const,
  586. content: MAX_STEPS,
  587. },
  588. ]
  589. : []),
  590. ],
  591. tools,
  592. model,
  593. })
  594. if (result === "stop") break
  595. if (result === "compact") {
  596. await SessionCompaction.create({
  597. sessionID,
  598. agent: lastUser.agent,
  599. model: lastUser.model,
  600. auto: true,
  601. })
  602. }
  603. continue
  604. }
  605. SessionCompaction.prune({ sessionID })
  606. for await (const item of MessageV2.stream(sessionID)) {
  607. if (item.info.role === "user") continue
  608. const queued = state()[sessionID]?.callbacks ?? []
  609. for (const q of queued) {
  610. q.resolve(item)
  611. }
  612. return item
  613. }
  614. throw new Error("Impossible")
  615. })
  616. async function lastModel(sessionID: string) {
  617. for await (const item of MessageV2.stream(sessionID)) {
  618. if (item.info.role === "user" && item.info.model) return item.info.model
  619. }
  620. return Provider.defaultModel()
  621. }
  622. async function resolveTools(input: {
  623. agent: Agent.Info
  624. model: Provider.Model
  625. session: Session.Info
  626. tools?: Record<string, boolean>
  627. processor: SessionProcessor.Info
  628. bypassAgentCheck: boolean
  629. messages: MessageV2.WithParts[]
  630. }) {
  631. using _ = log.time("resolveTools")
  632. const tools: Record<string, AITool> = {}
  633. const context = (args: any, options: ToolCallOptions): Tool.Context => ({
  634. sessionID: input.session.id,
  635. abort: options.abortSignal!,
  636. messageID: input.processor.message.id,
  637. callID: options.toolCallId,
  638. extra: { model: input.model, bypassAgentCheck: input.bypassAgentCheck },
  639. agent: input.agent.name,
  640. messages: input.messages,
  641. metadata: async (val: { title?: string; metadata?: any }) => {
  642. const match = input.processor.partFromToolCall(options.toolCallId)
  643. if (match && match.state.status === "running") {
  644. await Session.updatePart({
  645. ...match,
  646. state: {
  647. title: val.title,
  648. metadata: val.metadata,
  649. status: "running",
  650. input: args,
  651. time: {
  652. start: Date.now(),
  653. },
  654. },
  655. })
  656. }
  657. },
  658. async ask(req) {
  659. await PermissionNext.ask({
  660. ...req,
  661. sessionID: input.session.id,
  662. tool: { messageID: input.processor.message.id, callID: options.toolCallId },
  663. ruleset: PermissionNext.merge(input.agent.permission, input.session.permission ?? []),
  664. })
  665. },
  666. })
  667. for (const item of await ToolRegistry.tools(
  668. { modelID: input.model.api.id, providerID: input.model.providerID },
  669. input.agent,
  670. )) {
  671. const schema = ProviderTransform.schema(input.model, z.toJSONSchema(item.parameters))
  672. tools[item.id] = tool({
  673. id: item.id as any,
  674. description: item.description,
  675. inputSchema: jsonSchema(schema as any),
  676. async execute(args, options) {
  677. const ctx = context(args, options)
  678. await Plugin.trigger(
  679. "tool.execute.before",
  680. {
  681. tool: item.id,
  682. sessionID: ctx.sessionID,
  683. callID: ctx.callID,
  684. },
  685. {
  686. args,
  687. },
  688. )
  689. const result = await item.execute(args, ctx)
  690. await Plugin.trigger(
  691. "tool.execute.after",
  692. {
  693. tool: item.id,
  694. sessionID: ctx.sessionID,
  695. callID: ctx.callID,
  696. },
  697. result,
  698. )
  699. return result
  700. },
  701. })
  702. }
  703. for (const [key, item] of Object.entries(await MCP.tools())) {
  704. const execute = item.execute
  705. if (!execute) continue
  706. // Wrap execute to add plugin hooks and format output
  707. item.execute = async (args, opts) => {
  708. const ctx = context(args, opts)
  709. await Plugin.trigger(
  710. "tool.execute.before",
  711. {
  712. tool: key,
  713. sessionID: ctx.sessionID,
  714. callID: opts.toolCallId,
  715. },
  716. {
  717. args,
  718. },
  719. )
  720. await ctx.ask({
  721. permission: key,
  722. metadata: {},
  723. patterns: ["*"],
  724. always: ["*"],
  725. })
  726. const result = await execute(args, opts)
  727. await Plugin.trigger(
  728. "tool.execute.after",
  729. {
  730. tool: key,
  731. sessionID: ctx.sessionID,
  732. callID: opts.toolCallId,
  733. },
  734. result,
  735. )
  736. const textParts: string[] = []
  737. const attachments: Omit<MessageV2.FilePart, "id" | "messageID" | "sessionID">[] = []
  738. for (const contentItem of result.content) {
  739. if (contentItem.type === "text") {
  740. textParts.push(contentItem.text)
  741. } else if (contentItem.type === "image") {
  742. attachments.push({
  743. type: "file",
  744. mime: contentItem.mimeType,
  745. url: `data:${contentItem.mimeType};base64,${contentItem.data}`,
  746. })
  747. } else if (contentItem.type === "resource") {
  748. const { resource } = contentItem
  749. if (resource.text) {
  750. textParts.push(resource.text)
  751. }
  752. if (resource.blob) {
  753. attachments.push({
  754. type: "file",
  755. mime: resource.mimeType ?? "application/octet-stream",
  756. url: `data:${resource.mimeType ?? "application/octet-stream"};base64,${resource.blob}`,
  757. filename: resource.uri,
  758. })
  759. }
  760. }
  761. }
  762. const truncated = await Truncate.output(textParts.join("\n\n"), {}, input.agent)
  763. const metadata = {
  764. ...(result.metadata ?? {}),
  765. truncated: truncated.truncated,
  766. ...(truncated.truncated && { outputPath: truncated.outputPath }),
  767. }
  768. return {
  769. title: "",
  770. metadata,
  771. output: truncated.content,
  772. attachments,
  773. content: result.content, // directly return content to preserve ordering when outputting to model
  774. }
  775. }
  776. tools[key] = item
  777. }
  778. return tools
  779. }
  780. async function createUserMessage(input: PromptInput) {
  781. const agent = await Agent.get(input.agent ?? (await Agent.defaultAgent()))
  782. const model = input.model ?? agent.model ?? (await lastModel(input.sessionID))
  783. const variant =
  784. input.variant ??
  785. (agent.variant &&
  786. agent.model &&
  787. model.providerID === agent.model.providerID &&
  788. model.modelID === agent.model.modelID
  789. ? agent.variant
  790. : undefined)
  791. const info: MessageV2.Info = {
  792. id: input.messageID ?? Identifier.ascending("message"),
  793. role: "user",
  794. sessionID: input.sessionID,
  795. time: {
  796. created: Date.now(),
  797. },
  798. tools: input.tools,
  799. agent: agent.name,
  800. model,
  801. system: input.system,
  802. variant,
  803. }
  804. using _ = defer(() => InstructionPrompt.clear(info.id))
  805. const parts = await Promise.all(
  806. input.parts.map(async (part): Promise<MessageV2.Part[]> => {
  807. if (part.type === "file") {
  808. // before checking the protocol we check if this is an mcp resource because it needs special handling
  809. if (part.source?.type === "resource") {
  810. const { clientName, uri } = part.source
  811. log.info("mcp resource", { clientName, uri, mime: part.mime })
  812. const pieces: MessageV2.Part[] = [
  813. {
  814. id: Identifier.ascending("part"),
  815. messageID: info.id,
  816. sessionID: input.sessionID,
  817. type: "text",
  818. synthetic: true,
  819. text: `Reading MCP resource: ${part.filename} (${uri})`,
  820. },
  821. ]
  822. try {
  823. const resourceContent = await MCP.readResource(clientName, uri)
  824. if (!resourceContent) {
  825. throw new Error(`Resource not found: ${clientName}/${uri}`)
  826. }
  827. // Handle different content types
  828. const contents = Array.isArray(resourceContent.contents)
  829. ? resourceContent.contents
  830. : [resourceContent.contents]
  831. for (const content of contents) {
  832. if ("text" in content && content.text) {
  833. pieces.push({
  834. id: Identifier.ascending("part"),
  835. messageID: info.id,
  836. sessionID: input.sessionID,
  837. type: "text",
  838. synthetic: true,
  839. text: content.text as string,
  840. })
  841. } else if ("blob" in content && content.blob) {
  842. // Handle binary content if needed
  843. const mimeType = "mimeType" in content ? content.mimeType : part.mime
  844. pieces.push({
  845. id: Identifier.ascending("part"),
  846. messageID: info.id,
  847. sessionID: input.sessionID,
  848. type: "text",
  849. synthetic: true,
  850. text: `[Binary content: ${mimeType}]`,
  851. })
  852. }
  853. }
  854. pieces.push({
  855. ...part,
  856. id: part.id ?? Identifier.ascending("part"),
  857. messageID: info.id,
  858. sessionID: input.sessionID,
  859. })
  860. } catch (error: unknown) {
  861. log.error("failed to read MCP resource", { error, clientName, uri })
  862. const message = error instanceof Error ? error.message : String(error)
  863. pieces.push({
  864. id: Identifier.ascending("part"),
  865. messageID: info.id,
  866. sessionID: input.sessionID,
  867. type: "text",
  868. synthetic: true,
  869. text: `Failed to read MCP resource ${part.filename}: ${message}`,
  870. })
  871. }
  872. return pieces
  873. }
  874. const url = new URL(part.url)
  875. switch (url.protocol) {
  876. case "data:":
  877. if (part.mime === "text/plain") {
  878. return [
  879. {
  880. id: Identifier.ascending("part"),
  881. messageID: info.id,
  882. sessionID: input.sessionID,
  883. type: "text",
  884. synthetic: true,
  885. text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`,
  886. },
  887. {
  888. id: Identifier.ascending("part"),
  889. messageID: info.id,
  890. sessionID: input.sessionID,
  891. type: "text",
  892. synthetic: true,
  893. text: Buffer.from(part.url, "base64url").toString(),
  894. },
  895. {
  896. ...part,
  897. id: part.id ?? Identifier.ascending("part"),
  898. messageID: info.id,
  899. sessionID: input.sessionID,
  900. },
  901. ]
  902. }
  903. break
  904. case "file:":
  905. log.info("file", { mime: part.mime })
  906. // have to normalize, symbol search returns absolute paths
  907. // Decode the pathname since URL constructor doesn't automatically decode it
  908. const filepath = fileURLToPath(part.url)
  909. const stat = await Bun.file(filepath).stat()
  910. if (stat.isDirectory()) {
  911. part.mime = "application/x-directory"
  912. }
  913. if (part.mime === "text/plain") {
  914. let offset: number | undefined = undefined
  915. let limit: number | undefined = undefined
  916. const range = {
  917. start: url.searchParams.get("start"),
  918. end: url.searchParams.get("end"),
  919. }
  920. if (range.start != null) {
  921. const filePathURI = part.url.split("?")[0]
  922. let start = parseInt(range.start)
  923. let end = range.end ? parseInt(range.end) : undefined
  924. // some LSP servers (eg, gopls) don't give full range in
  925. // workspace/symbol searches, so we'll try to find the
  926. // symbol in the document to get the full range
  927. if (start === end) {
  928. const symbols = await LSP.documentSymbol(filePathURI)
  929. for (const symbol of symbols) {
  930. let range: LSP.Range | undefined
  931. if ("range" in symbol) {
  932. range = symbol.range
  933. } else if ("location" in symbol) {
  934. range = symbol.location.range
  935. }
  936. if (range?.start?.line && range?.start?.line === start) {
  937. start = range.start.line
  938. end = range?.end?.line ?? start
  939. break
  940. }
  941. }
  942. }
  943. offset = Math.max(start - 1, 0)
  944. if (end) {
  945. limit = end - offset
  946. }
  947. }
  948. const args = { filePath: filepath, offset, limit }
  949. const pieces: MessageV2.Part[] = [
  950. {
  951. id: Identifier.ascending("part"),
  952. messageID: info.id,
  953. sessionID: input.sessionID,
  954. type: "text",
  955. synthetic: true,
  956. text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
  957. },
  958. ]
  959. await ReadTool.init()
  960. .then(async (t) => {
  961. const model = await Provider.getModel(info.model.providerID, info.model.modelID)
  962. const readCtx: Tool.Context = {
  963. sessionID: input.sessionID,
  964. abort: new AbortController().signal,
  965. agent: input.agent!,
  966. messageID: info.id,
  967. extra: { bypassCwdCheck: true, model },
  968. messages: [],
  969. metadata: async () => {},
  970. ask: async () => {},
  971. }
  972. const result = await t.execute(args, readCtx)
  973. pieces.push({
  974. id: Identifier.ascending("part"),
  975. messageID: info.id,
  976. sessionID: input.sessionID,
  977. type: "text",
  978. synthetic: true,
  979. text: result.output,
  980. })
  981. if (result.attachments?.length) {
  982. pieces.push(
  983. ...result.attachments.map((attachment) => ({
  984. ...attachment,
  985. id: Identifier.ascending("part"),
  986. synthetic: true,
  987. filename: attachment.filename ?? part.filename,
  988. messageID: info.id,
  989. sessionID: input.sessionID,
  990. })),
  991. )
  992. } else {
  993. pieces.push({
  994. ...part,
  995. id: part.id ?? Identifier.ascending("part"),
  996. messageID: info.id,
  997. sessionID: input.sessionID,
  998. })
  999. }
  1000. })
  1001. .catch((error) => {
  1002. log.error("failed to read file", { error })
  1003. const message = error instanceof Error ? error.message : error.toString()
  1004. Bus.publish(Session.Event.Error, {
  1005. sessionID: input.sessionID,
  1006. error: new NamedError.Unknown({
  1007. message,
  1008. }).toObject(),
  1009. })
  1010. pieces.push({
  1011. id: Identifier.ascending("part"),
  1012. messageID: info.id,
  1013. sessionID: input.sessionID,
  1014. type: "text",
  1015. synthetic: true,
  1016. text: `Read tool failed to read ${filepath} with the following error: ${message}`,
  1017. })
  1018. })
  1019. return pieces
  1020. }
  1021. if (part.mime === "application/x-directory") {
  1022. const args = { path: filepath }
  1023. const listCtx: Tool.Context = {
  1024. sessionID: input.sessionID,
  1025. abort: new AbortController().signal,
  1026. agent: input.agent!,
  1027. messageID: info.id,
  1028. extra: { bypassCwdCheck: true },
  1029. messages: [],
  1030. metadata: async () => {},
  1031. ask: async () => {},
  1032. }
  1033. const result = await ListTool.init().then((t) => t.execute(args, listCtx))
  1034. return [
  1035. {
  1036. id: Identifier.ascending("part"),
  1037. messageID: info.id,
  1038. sessionID: input.sessionID,
  1039. type: "text",
  1040. synthetic: true,
  1041. text: `Called the list tool with the following input: ${JSON.stringify(args)}`,
  1042. },
  1043. {
  1044. id: Identifier.ascending("part"),
  1045. messageID: info.id,
  1046. sessionID: input.sessionID,
  1047. type: "text",
  1048. synthetic: true,
  1049. text: result.output,
  1050. },
  1051. {
  1052. ...part,
  1053. id: part.id ?? Identifier.ascending("part"),
  1054. messageID: info.id,
  1055. sessionID: input.sessionID,
  1056. },
  1057. ]
  1058. }
  1059. const file = Bun.file(filepath)
  1060. FileTime.read(input.sessionID, filepath)
  1061. return [
  1062. {
  1063. id: Identifier.ascending("part"),
  1064. messageID: info.id,
  1065. sessionID: input.sessionID,
  1066. type: "text",
  1067. text: `Called the Read tool with the following input: {\"filePath\":\"${filepath}\"}`,
  1068. synthetic: true,
  1069. },
  1070. {
  1071. id: part.id ?? Identifier.ascending("part"),
  1072. messageID: info.id,
  1073. sessionID: input.sessionID,
  1074. type: "file",
  1075. url: `data:${part.mime};base64,` + Buffer.from(await file.bytes()).toString("base64"),
  1076. mime: part.mime,
  1077. filename: part.filename!,
  1078. source: part.source,
  1079. },
  1080. ]
  1081. }
  1082. }
  1083. if (part.type === "agent") {
  1084. // Check if this agent would be denied by task permission
  1085. const perm = PermissionNext.evaluate("task", part.name, agent.permission)
  1086. const hint = perm.action === "deny" ? " . Invoked by user; guaranteed to exist." : ""
  1087. return [
  1088. {
  1089. id: Identifier.ascending("part"),
  1090. ...part,
  1091. messageID: info.id,
  1092. sessionID: input.sessionID,
  1093. },
  1094. {
  1095. id: Identifier.ascending("part"),
  1096. messageID: info.id,
  1097. sessionID: input.sessionID,
  1098. type: "text",
  1099. synthetic: true,
  1100. // An extra space is added here. Otherwise the 'Use' gets appended
  1101. // to user's last word; making a combined word
  1102. text:
  1103. " Use the above message and context to generate a prompt and call the task tool with subagent: " +
  1104. part.name +
  1105. hint,
  1106. },
  1107. ]
  1108. }
  1109. return [
  1110. {
  1111. id: Identifier.ascending("part"),
  1112. ...part,
  1113. messageID: info.id,
  1114. sessionID: input.sessionID,
  1115. },
  1116. ]
  1117. }),
  1118. )
  1119. .then((x) => x.flat())
  1120. .then((drafts) =>
  1121. drafts.map(
  1122. (part): MessageV2.Part => ({
  1123. ...part,
  1124. id: Identifier.ascending("part"),
  1125. messageID: info.id,
  1126. sessionID: input.sessionID,
  1127. }),
  1128. ),
  1129. )
  1130. await Plugin.trigger(
  1131. "chat.message",
  1132. {
  1133. sessionID: input.sessionID,
  1134. agent: input.agent,
  1135. model: input.model,
  1136. messageID: input.messageID,
  1137. variant: input.variant,
  1138. },
  1139. {
  1140. message: info,
  1141. parts,
  1142. },
  1143. )
  1144. await Session.updateMessage(info)
  1145. for (const part of parts) {
  1146. await Session.updatePart(part)
  1147. }
  1148. return {
  1149. info,
  1150. parts,
  1151. }
  1152. }
  1153. async function insertReminders(input: { messages: MessageV2.WithParts[]; agent: Agent.Info; session: Session.Info }) {
  1154. const userMessage = input.messages.findLast((msg) => msg.info.role === "user")
  1155. if (!userMessage) return input.messages
  1156. // Original logic when experimental plan mode is disabled
  1157. if (!Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE) {
  1158. if (input.agent.name === "plan") {
  1159. userMessage.parts.push({
  1160. id: Identifier.ascending("part"),
  1161. messageID: userMessage.info.id,
  1162. sessionID: userMessage.info.sessionID,
  1163. type: "text",
  1164. text: PROMPT_PLAN,
  1165. synthetic: true,
  1166. })
  1167. }
  1168. const wasPlan = input.messages.some((msg) => msg.info.role === "assistant" && msg.info.agent === "plan")
  1169. if (wasPlan && input.agent.name === "build") {
  1170. userMessage.parts.push({
  1171. id: Identifier.ascending("part"),
  1172. messageID: userMessage.info.id,
  1173. sessionID: userMessage.info.sessionID,
  1174. type: "text",
  1175. text: BUILD_SWITCH,
  1176. synthetic: true,
  1177. })
  1178. }
  1179. return input.messages
  1180. }
  1181. // New plan mode logic when flag is enabled
  1182. const assistantMessage = input.messages.findLast((msg) => msg.info.role === "assistant")
  1183. // Switching from plan mode to build mode
  1184. if (input.agent.name !== "plan" && assistantMessage?.info.agent === "plan") {
  1185. const plan = Session.plan(input.session)
  1186. const exists = await Bun.file(plan).exists()
  1187. if (exists) {
  1188. const part = await Session.updatePart({
  1189. id: Identifier.ascending("part"),
  1190. messageID: userMessage.info.id,
  1191. sessionID: userMessage.info.sessionID,
  1192. type: "text",
  1193. text:
  1194. BUILD_SWITCH + "\n\n" + `A plan file exists at ${plan}. You should execute on the plan defined within it`,
  1195. synthetic: true,
  1196. })
  1197. userMessage.parts.push(part)
  1198. }
  1199. return input.messages
  1200. }
  1201. // Entering plan mode
  1202. if (input.agent.name === "plan" && assistantMessage?.info.agent !== "plan") {
  1203. const plan = Session.plan(input.session)
  1204. const exists = await Bun.file(plan).exists()
  1205. if (!exists) await fs.mkdir(path.dirname(plan), { recursive: true })
  1206. const part = await Session.updatePart({
  1207. id: Identifier.ascending("part"),
  1208. messageID: userMessage.info.id,
  1209. sessionID: userMessage.info.sessionID,
  1210. type: "text",
  1211. text: `<system-reminder>
  1212. Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
  1213. ## Plan File Info:
  1214. ${exists ? `A plan file already exists at ${plan}. You can read it and make incremental edits using the edit tool.` : `No plan file exists yet. You should create your plan at ${plan} using the write tool.`}
  1215. You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
  1216. ## Plan Workflow
  1217. ### Phase 1: Initial Understanding
  1218. Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should only use the explore subagent type.
  1219. 1. Focus on understanding the user's request and the code associated with their request
  1220. 2. **Launch up to 3 explore agents IN PARALLEL** (single message, multiple tool calls) to efficiently explore the codebase.
  1221. - Use 1 agent when the task is isolated to known files, the user provided specific file paths, or you're making a small targeted change.
  1222. - Use multiple agents when: the scope is uncertain, multiple areas of the codebase are involved, or you need to understand existing patterns before planning.
  1223. - Quality over quantity - 3 agents maximum, but you should try to use the minimum number of agents necessary (usually just 1)
  1224. - If using multiple agents: Provide each agent with a specific search focus or area to explore. Example: One agent searches for existing implementations, another explores related components, a third investigates testing patterns
  1225. 3. After exploring the code, use the question tool to clarify ambiguities in the user request up front.
  1226. ### Phase 2: Design
  1227. Goal: Design an implementation approach.
  1228. Launch general agent(s) to design the implementation based on the user's intent and your exploration results from Phase 1.
  1229. You can launch up to 1 agent(s) in parallel.
  1230. **Guidelines:**
  1231. - **Default**: Launch at least 1 Plan agent for most tasks - it helps validate your understanding and consider alternatives
  1232. - **Skip agents**: Only for truly trivial tasks (typo fixes, single-line changes, simple renames)
  1233. Examples of when to use multiple agents:
  1234. - The task touches multiple parts of the codebase
  1235. - It's a large refactor or architectural change
  1236. - There are many edge cases to consider
  1237. - You'd benefit from exploring different approaches
  1238. Example perspectives by task type:
  1239. - New feature: simplicity vs performance vs maintainability
  1240. - Bug fix: root cause vs workaround vs prevention
  1241. - Refactoring: minimal change vs clean architecture
  1242. In the agent prompt:
  1243. - Provide comprehensive background context from Phase 1 exploration including filenames and code path traces
  1244. - Describe requirements and constraints
  1245. - Request a detailed implementation plan
  1246. ### Phase 3: Review
  1247. Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
  1248. 1. Read the critical files identified by agents to deepen your understanding
  1249. 2. Ensure that the plans align with the user's original request
  1250. 3. Use question tool to clarify any remaining questions with the user
  1251. ### Phase 4: Final Plan
  1252. Goal: Write your final plan to the plan file (the only file you can edit).
  1253. - Include only your recommended approach, not all alternatives
  1254. - Ensure that the plan file is concise enough to scan quickly, but detailed enough to execute effectively
  1255. - Include the paths of critical files to be modified
  1256. - Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
  1257. ### Phase 5: Call plan_exit tool
  1258. At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call plan_exit to indicate to the user that you are done planning.
  1259. This is critical - your turn should only end with either asking the user a question or calling plan_exit. Do not stop unless it's for these 2 reasons.
  1260. **Important:** Use question tool to clarify requirements/approach, use plan_exit to request plan approval. Do NOT use question tool to ask "Is this plan okay?" - that's what plan_exit does.
  1261. NOTE: At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
  1262. </system-reminder>`,
  1263. synthetic: true,
  1264. })
  1265. userMessage.parts.push(part)
  1266. return input.messages
  1267. }
  1268. return input.messages
  1269. }
  1270. export const ShellInput = z.object({
  1271. sessionID: Identifier.schema("session"),
  1272. agent: z.string(),
  1273. model: z
  1274. .object({
  1275. providerID: z.string(),
  1276. modelID: z.string(),
  1277. })
  1278. .optional(),
  1279. command: z.string(),
  1280. })
  1281. export type ShellInput = z.infer<typeof ShellInput>
  1282. export async function shell(input: ShellInput) {
  1283. const abort = start(input.sessionID)
  1284. if (!abort) {
  1285. throw new Session.BusyError(input.sessionID)
  1286. }
  1287. using _ = defer(() => cancel(input.sessionID))
  1288. const session = await Session.get(input.sessionID)
  1289. if (session.revert) {
  1290. await SessionRevert.cleanup(session)
  1291. }
  1292. const agent = await Agent.get(input.agent)
  1293. const model = input.model ?? agent.model ?? (await lastModel(input.sessionID))
  1294. const userMsg: MessageV2.User = {
  1295. id: Identifier.ascending("message"),
  1296. sessionID: input.sessionID,
  1297. time: {
  1298. created: Date.now(),
  1299. },
  1300. role: "user",
  1301. agent: input.agent,
  1302. model: {
  1303. providerID: model.providerID,
  1304. modelID: model.modelID,
  1305. },
  1306. }
  1307. await Session.updateMessage(userMsg)
  1308. const userPart: MessageV2.Part = {
  1309. type: "text",
  1310. id: Identifier.ascending("part"),
  1311. messageID: userMsg.id,
  1312. sessionID: input.sessionID,
  1313. text: "The following tool was executed by the user",
  1314. synthetic: true,
  1315. }
  1316. await Session.updatePart(userPart)
  1317. const msg: MessageV2.Assistant = {
  1318. id: Identifier.ascending("message"),
  1319. sessionID: input.sessionID,
  1320. parentID: userMsg.id,
  1321. mode: input.agent,
  1322. agent: input.agent,
  1323. cost: 0,
  1324. path: {
  1325. cwd: Instance.directory,
  1326. root: Instance.worktree,
  1327. },
  1328. time: {
  1329. created: Date.now(),
  1330. },
  1331. role: "assistant",
  1332. tokens: {
  1333. input: 0,
  1334. output: 0,
  1335. reasoning: 0,
  1336. cache: { read: 0, write: 0 },
  1337. },
  1338. modelID: model.modelID,
  1339. providerID: model.providerID,
  1340. }
  1341. await Session.updateMessage(msg)
  1342. const part: MessageV2.Part = {
  1343. type: "tool",
  1344. id: Identifier.ascending("part"),
  1345. messageID: msg.id,
  1346. sessionID: input.sessionID,
  1347. tool: "bash",
  1348. callID: ulid(),
  1349. state: {
  1350. status: "running",
  1351. time: {
  1352. start: Date.now(),
  1353. },
  1354. input: {
  1355. command: input.command,
  1356. },
  1357. },
  1358. }
  1359. await Session.updatePart(part)
  1360. const shell = Shell.preferred()
  1361. const shellName = (
  1362. process.platform === "win32" ? path.win32.basename(shell, ".exe") : path.basename(shell)
  1363. ).toLowerCase()
  1364. const invocations: Record<string, { args: string[] }> = {
  1365. nu: {
  1366. args: ["-c", input.command],
  1367. },
  1368. fish: {
  1369. args: ["-c", input.command],
  1370. },
  1371. zsh: {
  1372. args: [
  1373. "-c",
  1374. "-l",
  1375. `
  1376. [[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
  1377. [[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
  1378. eval ${JSON.stringify(input.command)}
  1379. `,
  1380. ],
  1381. },
  1382. bash: {
  1383. args: [
  1384. "-c",
  1385. "-l",
  1386. `
  1387. shopt -s expand_aliases
  1388. [[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
  1389. eval ${JSON.stringify(input.command)}
  1390. `,
  1391. ],
  1392. },
  1393. // Windows cmd
  1394. cmd: {
  1395. args: ["/c", input.command],
  1396. },
  1397. // Windows PowerShell
  1398. powershell: {
  1399. args: ["-NoProfile", "-Command", input.command],
  1400. },
  1401. pwsh: {
  1402. args: ["-NoProfile", "-Command", input.command],
  1403. },
  1404. // Fallback: any shell that doesn't match those above
  1405. // - No -l, for max compatibility
  1406. "": {
  1407. args: ["-c", `${input.command}`],
  1408. },
  1409. }
  1410. const matchingInvocation = invocations[shellName] ?? invocations[""]
  1411. const args = matchingInvocation?.args
  1412. const proc = spawn(shell, args, {
  1413. cwd: Instance.directory,
  1414. detached: process.platform !== "win32",
  1415. stdio: ["ignore", "pipe", "pipe"],
  1416. env: {
  1417. ...process.env,
  1418. TERM: "dumb",
  1419. },
  1420. })
  1421. let output = ""
  1422. proc.stdout?.on("data", (chunk) => {
  1423. output += chunk.toString()
  1424. if (part.state.status === "running") {
  1425. part.state.metadata = {
  1426. output: output,
  1427. description: "",
  1428. }
  1429. Session.updatePart(part)
  1430. }
  1431. })
  1432. proc.stderr?.on("data", (chunk) => {
  1433. output += chunk.toString()
  1434. if (part.state.status === "running") {
  1435. part.state.metadata = {
  1436. output: output,
  1437. description: "",
  1438. }
  1439. Session.updatePart(part)
  1440. }
  1441. })
  1442. let aborted = false
  1443. let exited = false
  1444. const kill = () => Shell.killTree(proc, { exited: () => exited })
  1445. if (abort.aborted) {
  1446. aborted = true
  1447. await kill()
  1448. }
  1449. const abortHandler = () => {
  1450. aborted = true
  1451. void kill()
  1452. }
  1453. abort.addEventListener("abort", abortHandler, { once: true })
  1454. await new Promise<void>((resolve) => {
  1455. proc.on("close", () => {
  1456. exited = true
  1457. abort.removeEventListener("abort", abortHandler)
  1458. resolve()
  1459. })
  1460. })
  1461. if (aborted) {
  1462. output += "\n\n" + ["<metadata>", "User aborted the command", "</metadata>"].join("\n")
  1463. }
  1464. msg.time.completed = Date.now()
  1465. await Session.updateMessage(msg)
  1466. if (part.state.status === "running") {
  1467. part.state = {
  1468. status: "completed",
  1469. time: {
  1470. ...part.state.time,
  1471. end: Date.now(),
  1472. },
  1473. input: part.state.input,
  1474. title: "",
  1475. metadata: {
  1476. output,
  1477. description: "",
  1478. },
  1479. output,
  1480. }
  1481. await Session.updatePart(part)
  1482. }
  1483. return { info: msg, parts: [part] }
  1484. }
  1485. export const CommandInput = z.object({
  1486. messageID: Identifier.schema("message").optional(),
  1487. sessionID: Identifier.schema("session"),
  1488. agent: z.string().optional(),
  1489. model: z.string().optional(),
  1490. arguments: z.string(),
  1491. command: z.string(),
  1492. variant: z.string().optional(),
  1493. parts: z
  1494. .array(
  1495. z.discriminatedUnion("type", [
  1496. MessageV2.FilePart.omit({
  1497. messageID: true,
  1498. sessionID: true,
  1499. }).partial({
  1500. id: true,
  1501. }),
  1502. ]),
  1503. )
  1504. .optional(),
  1505. })
  1506. export type CommandInput = z.infer<typeof CommandInput>
  1507. const bashRegex = /!`([^`]+)`/g
  1508. // Match [Image N] as single token, quoted strings, or non-space sequences
  1509. const argsRegex = /(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi
  1510. const placeholderRegex = /\$(\d+)/g
  1511. const quoteTrimRegex = /^["']|["']$/g
  1512. /**
  1513. * Regular expression to match @ file references in text
  1514. * Matches @ followed by file paths, excluding commas, periods at end of sentences, and backticks
  1515. * Does not match when preceded by word characters or backticks (to avoid email addresses and quoted references)
  1516. */
  1517. export async function command(input: CommandInput) {
  1518. log.info("command", input)
  1519. const command = await Command.get(input.command)
  1520. const agentName = command.agent ?? input.agent ?? (await Agent.defaultAgent())
  1521. const raw = input.arguments.match(argsRegex) ?? []
  1522. const args = raw.map((arg) => arg.replace(quoteTrimRegex, ""))
  1523. const templateCommand = await command.template
  1524. const placeholders = templateCommand.match(placeholderRegex) ?? []
  1525. let last = 0
  1526. for (const item of placeholders) {
  1527. const value = Number(item.slice(1))
  1528. if (value > last) last = value
  1529. }
  1530. // Let the final placeholder swallow any extra arguments so prompts read naturally
  1531. const withArgs = templateCommand.replaceAll(placeholderRegex, (_, index) => {
  1532. const position = Number(index)
  1533. const argIndex = position - 1
  1534. if (argIndex >= args.length) return ""
  1535. if (position === last) return args.slice(argIndex).join(" ")
  1536. return args[argIndex]
  1537. })
  1538. const usesArgumentsPlaceholder = templateCommand.includes("$ARGUMENTS")
  1539. let template = withArgs.replaceAll("$ARGUMENTS", input.arguments)
  1540. // If command doesn't explicitly handle arguments (no $N or $ARGUMENTS placeholders)
  1541. // but user provided arguments, append them to the template
  1542. if (placeholders.length === 0 && !usesArgumentsPlaceholder && input.arguments.trim()) {
  1543. template = template + "\n\n" + input.arguments
  1544. }
  1545. const shell = ConfigMarkdown.shell(template)
  1546. if (shell.length > 0) {
  1547. const results = await Promise.all(
  1548. shell.map(async ([, cmd]) => {
  1549. try {
  1550. return await $`${{ raw: cmd }}`.quiet().nothrow().text()
  1551. } catch (error) {
  1552. return `Error executing command: ${error instanceof Error ? error.message : String(error)}`
  1553. }
  1554. }),
  1555. )
  1556. let index = 0
  1557. template = template.replace(bashRegex, () => results[index++])
  1558. }
  1559. template = template.trim()
  1560. const taskModel = await (async () => {
  1561. if (command.model) {
  1562. return Provider.parseModel(command.model)
  1563. }
  1564. if (command.agent) {
  1565. const cmdAgent = await Agent.get(command.agent)
  1566. if (cmdAgent?.model) {
  1567. return cmdAgent.model
  1568. }
  1569. }
  1570. if (input.model) return Provider.parseModel(input.model)
  1571. return await lastModel(input.sessionID)
  1572. })()
  1573. try {
  1574. await Provider.getModel(taskModel.providerID, taskModel.modelID)
  1575. } catch (e) {
  1576. if (Provider.ModelNotFoundError.isInstance(e)) {
  1577. const { providerID, modelID, suggestions } = e.data
  1578. const hint = suggestions?.length ? ` Did you mean: ${suggestions.join(", ")}?` : ""
  1579. Bus.publish(Session.Event.Error, {
  1580. sessionID: input.sessionID,
  1581. error: new NamedError.Unknown({ message: `Model not found: ${providerID}/${modelID}.${hint}` }).toObject(),
  1582. })
  1583. }
  1584. throw e
  1585. }
  1586. const agent = await Agent.get(agentName)
  1587. if (!agent) {
  1588. const available = await Agent.list().then((agents) => agents.filter((a) => !a.hidden).map((a) => a.name))
  1589. const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
  1590. const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` })
  1591. Bus.publish(Session.Event.Error, {
  1592. sessionID: input.sessionID,
  1593. error: error.toObject(),
  1594. })
  1595. throw error
  1596. }
  1597. const templateParts = await resolvePromptParts(template)
  1598. const isSubtask = (agent.mode === "subagent" && command.subtask !== false) || command.subtask === true
  1599. const parts = isSubtask
  1600. ? [
  1601. {
  1602. type: "subtask" as const,
  1603. agent: agent.name,
  1604. description: command.description ?? "",
  1605. command: input.command,
  1606. model: {
  1607. providerID: taskModel.providerID,
  1608. modelID: taskModel.modelID,
  1609. },
  1610. // TODO: how can we make task tool accept a more complex input?
  1611. prompt: templateParts.find((y) => y.type === "text")?.text ?? "",
  1612. },
  1613. ]
  1614. : [...templateParts, ...(input.parts ?? [])]
  1615. const userAgent = isSubtask ? (input.agent ?? (await Agent.defaultAgent())) : agentName
  1616. const userModel = isSubtask
  1617. ? input.model
  1618. ? Provider.parseModel(input.model)
  1619. : await lastModel(input.sessionID)
  1620. : taskModel
  1621. await Plugin.trigger(
  1622. "command.execute.before",
  1623. {
  1624. command: input.command,
  1625. sessionID: input.sessionID,
  1626. arguments: input.arguments,
  1627. },
  1628. { parts },
  1629. )
  1630. const result = (await prompt({
  1631. sessionID: input.sessionID,
  1632. messageID: input.messageID,
  1633. model: userModel,
  1634. agent: userAgent,
  1635. parts,
  1636. variant: input.variant,
  1637. })) as MessageV2.WithParts
  1638. Bus.publish(Command.Event.Executed, {
  1639. name: input.command,
  1640. sessionID: input.sessionID,
  1641. arguments: input.arguments,
  1642. messageID: result.info.id,
  1643. })
  1644. return result
  1645. }
  1646. async function ensureTitle(input: {
  1647. session: Session.Info
  1648. history: MessageV2.WithParts[]
  1649. providerID: string
  1650. modelID: string
  1651. }) {
  1652. if (input.session.parentID) return
  1653. if (!Session.isDefaultTitle(input.session.title)) return
  1654. // Find first non-synthetic user message
  1655. const firstRealUserIdx = input.history.findIndex(
  1656. (m) => m.info.role === "user" && !m.parts.every((p) => "synthetic" in p && p.synthetic),
  1657. )
  1658. if (firstRealUserIdx === -1) return
  1659. const isFirst =
  1660. input.history.filter((m) => m.info.role === "user" && !m.parts.every((p) => "synthetic" in p && p.synthetic))
  1661. .length === 1
  1662. if (!isFirst) return
  1663. // Gather all messages up to and including the first real user message for context
  1664. // This includes any shell/subtask executions that preceded the user's first prompt
  1665. const contextMessages = input.history.slice(0, firstRealUserIdx + 1)
  1666. const firstRealUser = contextMessages[firstRealUserIdx]
  1667. // For subtask-only messages (from command invocations), extract the prompt directly
  1668. // since toModelMessage converts subtask parts to generic "The following tool was executed by the user"
  1669. const subtaskParts = firstRealUser.parts.filter((p) => p.type === "subtask") as MessageV2.SubtaskPart[]
  1670. const hasOnlySubtaskParts = subtaskParts.length > 0 && firstRealUser.parts.every((p) => p.type === "subtask")
  1671. const agent = await Agent.get("title")
  1672. if (!agent) return
  1673. const model = await iife(async () => {
  1674. if (agent.model) return await Provider.getModel(agent.model.providerID, agent.model.modelID)
  1675. return (
  1676. (await Provider.getSmallModel(input.providerID)) ?? (await Provider.getModel(input.providerID, input.modelID))
  1677. )
  1678. })
  1679. const result = await LLM.stream({
  1680. agent,
  1681. user: firstRealUser.info as MessageV2.User,
  1682. system: [],
  1683. small: true,
  1684. tools: {},
  1685. model,
  1686. abort: new AbortController().signal,
  1687. sessionID: input.session.id,
  1688. retries: 2,
  1689. messages: [
  1690. {
  1691. role: "user",
  1692. content: "Generate a title for this conversation:\n",
  1693. },
  1694. ...(hasOnlySubtaskParts
  1695. ? [{ role: "user" as const, content: subtaskParts.map((p) => p.prompt).join("\n") }]
  1696. : MessageV2.toModelMessages(contextMessages, model)),
  1697. ],
  1698. })
  1699. const text = await result.text.catch((err) => log.error("failed to generate title", { error: err }))
  1700. if (text)
  1701. return Session.update(
  1702. input.session.id,
  1703. (draft) => {
  1704. const cleaned = text
  1705. .replace(/<think>[\s\S]*?<\/think>\s*/g, "")
  1706. .split("\n")
  1707. .map((line) => line.trim())
  1708. .find((line) => line.length > 0)
  1709. if (!cleaned) return
  1710. const title = cleaned.length > 100 ? cleaned.substring(0, 97) + "..." : cleaned
  1711. draft.title = title
  1712. },
  1713. { touch: false },
  1714. )
  1715. }
  1716. }