prompt.ts 60 KB

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