prompt.ts 60 KB

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