prompt.ts 62 KB

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