mock-server.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. import type { Page, Route } from "@playwright/test"
  2. import type {
  3. JsonValue,
  4. PromptAgentAttachment,
  5. PromptFileAttachment,
  6. SessionMessageAssistant,
  7. SessionMessageInfo,
  8. SessionStructuredError,
  9. } from "@opencode-ai/client/promise"
  10. const emptyList = new Set(["/skill", "/command", "/lsp", "/formatter", "/vcs/status", "/vcs/diff"])
  11. const emptyObject = new Set(["/global/config", "/config", "/provider/auth", "/mcp", "/experimental/resource"])
  12. export interface MockServerConfig {
  13. protocol?: "v1" | "v2"
  14. provider: unknown | (() => unknown)
  15. integrationMethods?: Record<string, unknown[]>
  16. onConnectKey?: (input: { integrationID: string; body: unknown }) => void
  17. onInstanceDispose?: () => void
  18. directory: string
  19. project: unknown
  20. sessions: ({ id: string } & Record<string, unknown>)[]
  21. pageMessages: (sessionId: string, limit: number, before?: string) => { items: unknown[]; cursor?: string }
  22. vcsDiff?: unknown[]
  23. messageDelay?: number
  24. beforeMessagesResponse?: (input: { sessionID: string; before?: string }) => Promise<void>
  25. onMessages?: (input: { sessionID: string; before?: string; phase: "start" | "end" }) => void
  26. message?: (sessionID: string, messageID: string) => unknown
  27. onMessage?: (input: { sessionID: string; messageID: string }) => void
  28. events?: () => unknown[]
  29. eventRetry?: number
  30. todos?: (sessionID: string) => unknown[]
  31. permissions?: unknown[] | (() => unknown[])
  32. questions?: unknown[] | (() => unknown[])
  33. fileList?: (path: string) => unknown | Promise<unknown>
  34. fileContent?: (path: string) => unknown | Promise<unknown>
  35. findFiles?: (input: { query: string; dirs?: string; limit?: number }) => unknown
  36. sessionStatus?: Record<string, unknown> | (() => Record<string, unknown>)
  37. }
  38. export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
  39. const cursors = new Map<string, string>()
  40. let nextCursor = 0
  41. const staticRoutes: Record<string, unknown> = {
  42. "/path": {
  43. state: config.directory,
  44. config: config.directory,
  45. worktree: config.directory,
  46. directory: config.directory,
  47. home: "C:/OpenCode",
  48. },
  49. "/project": [config.project],
  50. "/project/current": config.project,
  51. "/agent": [{ name: "build", mode: "primary" }],
  52. "/vcs": { branch: "main", default_branch: "main" },
  53. "/session": config.sessions,
  54. }
  55. await page.route("**/*", async (route) => {
  56. const url = new URL(route.request().url())
  57. const targetPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
  58. const appPort = new URL(
  59. process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:${process.env.PLAYWRIGHT_PORT ?? "3000"}`,
  60. ).port
  61. if (url.port !== targetPort && url.port !== appPort) return route.fallback()
  62. const path = url.pathname
  63. if (path === "/global/event" || path === "/event" || path === "/api/event") {
  64. const events = config.events?.()
  65. return sse(
  66. route,
  67. path === "/api/event"
  68. ? [{ id: "evt_mock_connected", type: "server.connected", data: {} }, ...(events?.map(currentEvent) ?? [])]
  69. : [
  70. ...(path === "/global/event"
  71. ? [{ payload: { id: "evt_mock_connected", type: "server.connected", properties: {} } }]
  72. : []),
  73. ...(events ?? []),
  74. ],
  75. config.eventRetry,
  76. )
  77. }
  78. if (path === "/global/health")
  79. return config.protocol === "v2" ? json(route, {}) : json(route, { healthy: true })
  80. if (path === "/api/health" && config.protocol === "v2")
  81. return json(route, { healthy: true, version: "2.0.0", pid: 1 })
  82. if (path === "/experimental/capabilities") return json(route, { backgroundSubagents: true })
  83. if (path === "/provider") return json(route, providerConfig(config))
  84. if (path === "/provider/auth") return json(route, config.integrationMethods ?? {})
  85. const legacyAuth = path.match(/^\/auth\/([^/]+)$/)?.[1]
  86. if (legacyAuth && route.request().method() === "PUT") {
  87. config.onConnectKey?.({ integrationID: legacyAuth, body: route.request().postDataJSON() })
  88. return json(route, true)
  89. }
  90. if (path === "/instance/dispose" && route.request().method() === "POST") {
  91. config.onInstanceDispose?.()
  92. return json(route, true)
  93. }
  94. if (path === "/permission")
  95. return json(route, typeof config.permissions === "function" ? config.permissions() : (config.permissions ?? []))
  96. if (path === "/question")
  97. return json(route, typeof config.questions === "function" ? config.questions() : (config.questions ?? []))
  98. if (path === "/session/status")
  99. return json(
  100. route,
  101. typeof config.sessionStatus === "function" ? config.sessionStatus() : (config.sessionStatus ?? {}),
  102. )
  103. if (path === "/vcs/diff" && config.vcsDiff) return json(route, config.vcsDiff)
  104. if (path === "/file" && config.fileList)
  105. return json(route, await config.fileList(url.searchParams.get("path") ?? ""))
  106. if (path === "/file/content" && config.fileContent)
  107. return json(route, await config.fileContent(url.searchParams.get("path") ?? ""))
  108. if (path === "/find/file" && config.findFiles)
  109. return json(
  110. route,
  111. await config.findFiles({
  112. query: url.searchParams.get("query") ?? "",
  113. dirs: url.searchParams.get("dirs") ?? undefined,
  114. limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined,
  115. }),
  116. )
  117. if (path === "/api/reference")
  118. return json(route, {
  119. location: {
  120. directory: config.directory,
  121. project: { id: (config.project as { id?: string }).id, directory: config.directory },
  122. },
  123. data: [],
  124. })
  125. if (path === "/api/agent")
  126. return json(route, {
  127. location: location(config),
  128. data: [
  129. {
  130. id: "build",
  131. name: "Build",
  132. mode: "primary",
  133. hidden: false,
  134. request: { settings: {}, headers: {}, body: {} },
  135. permissions: [],
  136. },
  137. ],
  138. })
  139. if (path === "/api/provider")
  140. return json(route, {
  141. location: location(config),
  142. data: currentProviders(providerConfig(config)),
  143. })
  144. if (path === "/api/model") return json(route, { location: location(config), data: currentModels(providerConfig(config)) })
  145. if (path === "/api/model/default")
  146. return json(route, { location: location(config), data: currentDefaultModel(providerConfig(config)) })
  147. if (path === "/api/integration") return json(route, { location: location(config), data: [] })
  148. if (path === "/api/command") return json(route, { location: location(config), data: [] })
  149. if (path === "/api/plugin") return json(route, { location: location(config), data: [] })
  150. if (path === "/api/mcp") return json(route, { location: location(config), data: [] })
  151. if (path === "/api/mcp/resource")
  152. return json(route, { location: location(config), data: { resources: [], templates: [] } })
  153. const integration = path.match(/^\/api\/integration\/([^/]+)$/)?.[1]
  154. if (integration && route.request().method() === "GET")
  155. return json(route, {
  156. location: location(config),
  157. data: {
  158. id: integration,
  159. name: integration,
  160. methods: config.integrationMethods?.[integration] ?? [{ type: "key", label: "API key" }],
  161. connections: [],
  162. },
  163. })
  164. const integrationConnect = path.match(/^\/api\/integration\/([^/]+)\/connect\/key$/)?.[1]
  165. if (integrationConnect && route.request().method() === "POST") {
  166. config.onConnectKey?.({ integrationID: integrationConnect, body: route.request().postDataJSON() })
  167. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  168. }
  169. if (/^\/api\/credential\/[^/]+$/.test(path) && route.request().method() === "DELETE")
  170. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  171. if (path === "/api/project") return json(route, [config.project])
  172. if (path === "/api/project/current")
  173. return json(route, { id: (config.project as { id?: string }).id, directory: config.directory })
  174. if (path === "/api/location") return json(route, location(config))
  175. const projectCopy = path.match(/^\/experimental\/project\/([^/]+)\/copy$/)?.[1]
  176. if (projectCopy && route.request().method() === "POST") {
  177. const input = route.request().postDataJSON() as { directory: string; name?: string }
  178. return json(route, { directory: `${input.directory}/${input.name ?? "copy"}` })
  179. }
  180. if (projectCopy && route.request().method() === "DELETE")
  181. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  182. if (path === "/api/permission/request")
  183. return json(route, {
  184. location: location(config),
  185. data: (typeof config.permissions === "function" ? config.permissions() : (config.permissions ?? [])).map(
  186. currentPermission,
  187. ),
  188. })
  189. if (path === "/api/question/request")
  190. return json(route, {
  191. location: location(config),
  192. data: typeof config.questions === "function" ? config.questions() : (config.questions ?? []),
  193. })
  194. if (path === "/api/vcs")
  195. return json(route, { location: location(config), data: { branch: "main", defaultBranch: "main" } })
  196. if (path === "/api/vcs/status") return json(route, { location: location(config), data: [] })
  197. if (path === "/api/vcs/diff") return json(route, { location: location(config), data: config.vcsDiff ?? [] })
  198. if (path === "/api/fs/list" && config.fileList)
  199. return json(route, {
  200. location: location(config),
  201. data: await config.fileList(url.searchParams.get("path") ?? ""),
  202. })
  203. const fileRead = path.match(/^\/api\/fs\/read\/(.+)$/)?.[1]
  204. if (fileRead && config.fileContent) {
  205. const value = await config.fileContent(decodeURIComponent(fileRead))
  206. const content = value && typeof value === "object" && "content" in value ? String(value.content) : String(value ?? "")
  207. return route.fulfill({ status: 200, body: content, headers: { "content-type": "application/octet-stream" } })
  208. }
  209. if (path === "/api/fs/find" && config.findFiles) {
  210. const entries = await config.findFiles({
  211. query: url.searchParams.get("query") ?? "",
  212. dirs: url.searchParams.get("type") ?? undefined,
  213. limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined,
  214. })
  215. return json(route, {
  216. location: location(config),
  217. data: Array.isArray(entries)
  218. ? entries.map((entry) =>
  219. typeof entry === "string"
  220. ? {
  221. name: entry.split(/[\\/]/).at(-1) ?? entry,
  222. path: entry,
  223. absolute: `${config.directory}/${entry}`,
  224. type: "directory",
  225. ignored: false,
  226. }
  227. : entry,
  228. )
  229. : entries,
  230. })
  231. }
  232. if (path === "/api/pty/shells") return json(route, { location: location(config), data: [] })
  233. if (/^\/api\/pty\/[^/]+\/connect-token$/.test(path))
  234. return json(route, { location: location(config), data: { ticket: "e2e-ticket", expires_in: 60 } })
  235. if (path === "/api/session") {
  236. const directory = url.searchParams.get("directory")
  237. const parentID = url.searchParams.get("parentID")
  238. const limit = Number(url.searchParams.get("limit") ?? 50)
  239. const offset = Number(url.searchParams.get("cursor") ?? 0)
  240. const sessions = config.sessions
  241. .filter((session) => !directory || session.directory === directory)
  242. .filter((session) => parentID !== "null" || session.parentID === undefined)
  243. .filter((session) => {
  244. const search = url.searchParams.get("search")?.toLowerCase()
  245. return (
  246. !search ||
  247. String(session.title ?? "")
  248. .toLowerCase()
  249. .includes(search)
  250. )
  251. })
  252. const ordered = url.searchParams.get("order") === "asc" ? sessions.toReversed() : sessions
  253. const data = ordered.slice(offset, offset + limit)
  254. const next = offset + limit < ordered.length ? String(offset + limit) : undefined
  255. return json(route, {
  256. data: data.map((session) => currentSession(session, config.directory)),
  257. cursor: { next },
  258. })
  259. }
  260. if (path === "/api/session/active") {
  261. const statuses = (
  262. typeof config.sessionStatus === "function" ? config.sessionStatus() : (config.sessionStatus ?? {})
  263. ) as Record<string, { type?: string }>
  264. return json(route, {
  265. data: Object.fromEntries(
  266. Object.entries(statuses).flatMap(([id, status]) =>
  267. status.type === "idle" ? [] : [[id, { type: "running" }]],
  268. ),
  269. ),
  270. })
  271. }
  272. if (/^\/api\/session\/[^/]+\/shell$/.test(path) && route.request().method() === "POST") {
  273. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  274. }
  275. if (/^\/api\/session\/[^/]+\/question\/[^/]+\/(reply|reject)$/.test(path) && route.request().method() === "POST") {
  276. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  277. }
  278. if (/^\/api\/session\/[^/]+\/permission\/[^/]+\/reply$/.test(path) && route.request().method() === "POST") {
  279. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  280. }
  281. if (/^\/question\/[^/]+\/(reply|reject)$/.test(path) && route.request().method() === "POST") return json(route, true)
  282. if (/^\/session\/[^/]+\/permissions\/[^/]+$/.test(path) && route.request().method() === "POST")
  283. return json(route, true)
  284. if (
  285. /^\/api\/session\/[^/]+\/(archive|rename|interrupt|revert\/clear|revert\/commit)$/.test(path) &&
  286. route.request().method() === "POST"
  287. ) {
  288. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  289. }
  290. if (/^\/api\/session\/[^/]+$/.test(path) && route.request().method() === "DELETE") {
  291. return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
  292. }
  293. if (emptyObject.has(path)) return json(route, {})
  294. if (emptyList.has(path)) return json(route, [])
  295. if (path in staticRoutes) return json(route, staticRoutes[path])
  296. const currentSessionMatch = path.match(/^\/api\/session\/([^/]+)$/)
  297. if (currentSessionMatch) {
  298. const session = config.sessions.find((item) => item.id === currentSessionMatch[1])
  299. if (!session) return json(route, { error: "Session not found" }, undefined, 404)
  300. return json(route, {
  301. data: currentSession(session, config.directory),
  302. })
  303. }
  304. const currentMessageMatch = path.match(/^\/api\/session\/([^/]+)\/message\/([^/]+)$/)
  305. if (currentMessageMatch) {
  306. config.onMessage?.({ sessionID: currentMessageMatch[1]!, messageID: currentMessageMatch[2]! })
  307. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  308. const message = config.message?.(currentMessageMatch[1]!, currentMessageMatch[2]!)
  309. if (message === undefined) return json(route, { error: "Message not found" }, undefined, 404)
  310. return json(route, { data: currentMessage(message) })
  311. }
  312. const sessionMatch = path.match(/^\/session\/([^/]+)$/)
  313. if (sessionMatch) return json(route, config.sessions.find((session) => session.id === sessionMatch[1]) ?? {})
  314. const projectMatch = path.match(/^\/project\/([^/]+)$/)
  315. if (projectMatch) return json(route, config.project)
  316. const messageMatch = path.match(/^\/session\/([^/]+)\/message\/([^/]+)$/)
  317. if (messageMatch) {
  318. config.onMessage?.({ sessionID: messageMatch[1]!, messageID: messageMatch[2]! })
  319. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  320. const message = config.message?.(messageMatch[1]!, messageMatch[2]!)
  321. if (message === undefined) return json(route, { error: "Message not found" }, undefined, 404)
  322. return json(route, message)
  323. }
  324. const todoMatch = path.match(/^\/session\/([^/]+)\/todo$/)
  325. if (todoMatch) return json(route, config.todos?.(todoMatch[1]!) ?? [])
  326. if (/^\/session\/[^/]+\/(children|diff)$/.test(path)) return json(route, [])
  327. const currentMessagesMatch = path.match(/^\/api\/session\/([^/]+)\/message$/)
  328. if (currentMessagesMatch) {
  329. const token = url.searchParams.get("cursor") ?? undefined
  330. const before = token ? cursors.get(token) : undefined
  331. if (token && !before) return json(route, { error: "Invalid cursor" }, undefined, 400)
  332. config.onMessages?.({ sessionID: currentMessagesMatch[1], before, phase: "start" })
  333. await config.beforeMessagesResponse?.({ sessionID: currentMessagesMatch[1]!, before })
  334. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  335. const pageData = config.pageMessages(currentMessagesMatch[1], Number(url.searchParams.get("limit") ?? 50), before)
  336. config.onMessages?.({ sessionID: currentMessagesMatch[1], before, phase: "end" })
  337. const cursor = pageData.cursor ? `cursor_${++nextCursor}` : undefined
  338. if (cursor) cursors.set(cursor, pageData.cursor!)
  339. return json(route, {
  340. data: pageData.items.map(currentMessage).reverse(),
  341. cursor: { next: cursor },
  342. })
  343. }
  344. const messagesMatch = path.match(/^\/session\/([^/]+)\/message$/)
  345. if (messagesMatch) {
  346. const token = url.searchParams.get("before") ?? undefined
  347. const before = token ? cursors.get(token) : undefined
  348. if (token && !before) return json(route, { error: "Invalid cursor" }, undefined, 400)
  349. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "start" })
  350. await config.beforeMessagesResponse?.({ sessionID: messagesMatch[1]!, before })
  351. if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  352. const pageData = config.pageMessages(messagesMatch[1], Number(url.searchParams.get("limit") ?? 80), before)
  353. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "end" })
  354. if (!pageData.cursor) return json(route, pageData.items)
  355. const cursor = `cursor_${++nextCursor}`
  356. cursors.set(cursor, pageData.cursor)
  357. return json(route, pageData.items, { "x-next-cursor": cursor })
  358. }
  359. if (url.port === targetPort && targetPort !== appPort) return json(route, {})
  360. return route.fallback()
  361. })
  362. }
  363. function location(config: MockServerConfig) {
  364. return {
  365. directory: config.directory,
  366. project: { id: (config.project as { id?: string }).id, directory: config.directory, canonical: config.directory },
  367. }
  368. }
  369. function providerConfig(config: MockServerConfig) {
  370. return typeof config.provider === "function" ? config.provider() : config.provider
  371. }
  372. function currentProviders(value: unknown) {
  373. if (!record(value) || !Array.isArray(value.all)) return Array.isArray(value) ? value : []
  374. return value.all.filter(record).flatMap((provider) =>
  375. typeof provider.id === "string" && typeof provider.name === "string"
  376. ? [{ id: provider.id, name: provider.name, package: provider.id }]
  377. : [],
  378. )
  379. }
  380. function currentModels(value: unknown) {
  381. if (!record(value) || !Array.isArray(value.all)) return []
  382. return value.all.filter(record).flatMap((provider) => {
  383. if (typeof provider.id !== "string" || !record(provider.models)) return []
  384. return Object.values(provider.models)
  385. .filter(record)
  386. .flatMap((model) => {
  387. if (typeof model.id !== "string" || typeof model.name !== "string") return []
  388. const limit = record(model.limit) ? model.limit : {}
  389. const cost = record(model.cost) ? model.cost : {}
  390. return [
  391. {
  392. id: model.id,
  393. modelID: model.id,
  394. providerID: provider.id,
  395. name: model.name,
  396. capabilities: { tools: true, input: ["text"], output: ["text"] },
  397. variants: record(model.variants)
  398. ? Object.entries(model.variants).map(([id, settings]) => ({
  399. id,
  400. ...(jsonRecord(settings) ? { settings: jsonRecord(settings) } : {}),
  401. }))
  402. : [],
  403. time: { released: Date.now() },
  404. cost: [
  405. {
  406. input: typeof cost.input === "number" ? cost.input : 0,
  407. output: typeof cost.output === "number" ? cost.output : 0,
  408. cache: { read: 0, write: 0 },
  409. },
  410. ],
  411. status: "active",
  412. enabled: true,
  413. limit: {
  414. context: typeof limit.context === "number" ? limit.context : 200_000,
  415. output: typeof limit.output === "number" ? limit.output : 32_000,
  416. },
  417. },
  418. ]
  419. })
  420. })
  421. }
  422. function currentDefaultModel(value: unknown) {
  423. if (!record(value) || !record(value.default)) return null
  424. const selected = value.default
  425. const models = currentModels(value)
  426. return models.find(
  427. (model) => model.providerID === selected.providerID && model.id === selected.modelID,
  428. ) ?? null
  429. }
  430. function currentPermission(value: unknown) {
  431. const permission = value as Record<string, unknown>
  432. if (permission.action) return permission
  433. const tool = permission.tool as { messageID?: string; callID?: string } | undefined
  434. return {
  435. id: permission.id,
  436. sessionID: permission.sessionID,
  437. action: permission.permission,
  438. resources: permission.patterns ?? [],
  439. save: permission.always,
  440. metadata: permission.metadata,
  441. source:
  442. tool?.messageID && tool.callID ? { type: "tool", messageID: tool.messageID, callID: tool.callID } : undefined,
  443. }
  444. }
  445. export function currentSession(session: { id: string } & Record<string, unknown>, fallbackDirectory?: string) {
  446. const time = session.time && typeof session.time === "object" ? session.time : {}
  447. return {
  448. id: session.id,
  449. parentID: session.parentID,
  450. projectID: session.projectID ?? "project",
  451. agent: session.agent ?? "build",
  452. model: session.model ?? { id: "mock-model", providerID: "mock-provider" },
  453. cost: session.cost ?? 0,
  454. tokens: session.tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  455. time: {
  456. created: "created" in time && typeof time.created === "number" ? time.created : 0,
  457. updated: "updated" in time && typeof time.updated === "number" ? time.updated : 0,
  458. ...(session.time && typeof session.time === "object" && "archived" in session.time
  459. ? { archived: session.time.archived }
  460. : {}),
  461. },
  462. title: session.title ?? session.id,
  463. location: {
  464. directory: typeof session.directory === "string" ? session.directory : fallbackDirectory,
  465. ...(typeof session.workspaceID === "string" ? { workspaceID: session.workspaceID } : {}),
  466. },
  467. subpath: session.path,
  468. revert: session.revert,
  469. }
  470. }
  471. export function currentMessage(value: unknown): SessionMessageInfo {
  472. if (isCurrentMessage(value)) return value
  473. if (!record(value) || !record(value.info) || !Array.isArray(value.parts)) throw new Error("Invalid message fixture")
  474. const info = value.info
  475. const parts = value.parts.filter(record)
  476. if (typeof info.id !== "string" || !record(info.time) || typeof info.time.created !== "number")
  477. throw new Error("Invalid legacy message fixture")
  478. const time = {
  479. created: info.time.created,
  480. ...(typeof info.time.completed === "number" ? { completed: info.time.completed } : {}),
  481. }
  482. if (info.role === "user") {
  483. return {
  484. id: info.id,
  485. type: "user",
  486. time: { created: time.created },
  487. text: parts
  488. .flatMap((part) => (part.type === "text" && typeof part.text === "string" ? [part.text] : []))
  489. .join("\n"),
  490. files: parts.flatMap((part) => (part.type === "file" ? legacyFile(part) : [])),
  491. agents: parts.flatMap((part) => (part.type === "agent" ? legacyAgent(part) : [])),
  492. }
  493. }
  494. if (info.role !== "assistant") throw new Error("Invalid legacy message role")
  495. return {
  496. id: info.id,
  497. type: "assistant",
  498. time,
  499. agent: typeof info.agent === "string" ? info.agent : typeof info.mode === "string" ? info.mode : "build",
  500. model: {
  501. id: typeof info.modelID === "string" ? info.modelID : "model",
  502. providerID: typeof info.providerID === "string" ? info.providerID : "provider",
  503. ...(typeof info.variant === "string" ? { variant: info.variant } : {}),
  504. },
  505. content: parts.flatMap((part) => legacyAssistantContent(part, time.created)),
  506. ...(typeof info.cost === "number" ? { cost: info.cost } : {}),
  507. ...(tokens(info.tokens) ? { tokens: tokens(info.tokens) } : {}),
  508. ...(structuredError(info.error) ? { error: structuredError(info.error) } : {}),
  509. ...(finish(info.finish) ? { finish: finish(info.finish) } : {}),
  510. }
  511. }
  512. function isCurrentMessage(value: unknown): value is SessionMessageInfo {
  513. return record(value) && typeof value.id === "string" && typeof value.type === "string" && !record(value.info)
  514. }
  515. function legacyFile(part: Record<string, unknown>): PromptFileAttachment[] {
  516. if (typeof part.mime !== "string" || typeof part.url !== "string") return []
  517. const data = part.url.match(/^data:[^,]*;base64,(.*)$/)?.[1] ?? ""
  518. const source = record(part.source) ? part.source : undefined
  519. const sourceText = source && record(source.text) ? source.text : undefined
  520. const mention = mentionFrom(sourceText)
  521. const uri = source?.type === "resource" && typeof source.uri === "string" ? source.uri : part.url
  522. return [
  523. {
  524. data,
  525. mime: part.mime,
  526. source: part.url.startsWith("data:") ? { type: "inline" } : { type: "uri", uri },
  527. ...(typeof part.filename === "string" ? { name: part.filename } : {}),
  528. ...(mention ? { mention } : {}),
  529. },
  530. ]
  531. }
  532. function legacyAgent(part: Record<string, unknown>): PromptAgentAttachment[] {
  533. if (typeof part.name !== "string") return []
  534. const mention = mentionFrom(record(part.source) ? part.source : undefined)
  535. return [{ name: part.name, ...(mention ? { mention } : {}) }]
  536. }
  537. function mentionFrom(value: Record<string, unknown> | undefined) {
  538. if (
  539. !value ||
  540. typeof value.value !== "string" ||
  541. typeof value.start !== "number" ||
  542. typeof value.end !== "number"
  543. )
  544. return
  545. return { text: value.value, start: value.start, end: value.end }
  546. }
  547. function legacyAssistantContent(
  548. part: Record<string, unknown>,
  549. created: number,
  550. ): SessionMessageAssistant["content"] {
  551. if (part.type === "text" && typeof part.text === "string")
  552. return [{ type: "text", text: part.text, ...(jsonRecord(part.metadata) ? { state: jsonRecord(part.metadata) } : {}) }]
  553. if (part.type === "reasoning" && typeof part.text === "string") {
  554. const time = record(part.time) ? part.time : undefined
  555. return [
  556. {
  557. type: "reasoning",
  558. text: part.text,
  559. ...(jsonRecord(part.metadata) ? { state: jsonRecord(part.metadata) } : {}),
  560. ...(time && typeof time.start === "number"
  561. ? {
  562. time: {
  563. created: time.start,
  564. ...(typeof time.end === "number" ? { completed: time.end } : {}),
  565. },
  566. }
  567. : {}),
  568. },
  569. ]
  570. }
  571. if (part.type !== "tool" || typeof part.id !== "string" || typeof part.tool !== "string" || !record(part.state))
  572. return []
  573. const state = part.state
  574. const time = record(state.time) ? state.time : undefined
  575. const toolTime = {
  576. created: time && typeof time.start === "number" ? time.start : created,
  577. ...(time && typeof time.start === "number" ? { ran: time.start } : {}),
  578. ...(time && typeof time.end === "number" ? { completed: time.end } : {}),
  579. }
  580. const input = jsonRecord(state.input) ?? {}
  581. const metadata = jsonRecord(state.metadata)
  582. const base = {
  583. type: "tool" as const,
  584. id: typeof part.callID === "string" ? part.callID : part.id,
  585. name: part.tool,
  586. time: toolTime,
  587. ...(typeof part.executed === "boolean" ? { executed: part.executed } : {}),
  588. ...(jsonRecord(part.providerState) ? { providerState: jsonRecord(part.providerState) } : {}),
  589. ...(jsonRecord(part.providerResultState) ? { providerResultState: jsonRecord(part.providerResultState) } : {}),
  590. }
  591. if (state.status === "pending")
  592. return [{ ...base, state: { status: "streaming", input: typeof state.raw === "string" ? state.raw : JSON.stringify(input) } }]
  593. if (state.status === "completed")
  594. return [
  595. {
  596. ...base,
  597. state: {
  598. status: "completed",
  599. input,
  600. content: [{ type: "text", text: typeof state.output === "string" ? state.output : "" }],
  601. ...(metadata ? { metadata } : {}),
  602. },
  603. },
  604. ]
  605. if (state.status === "error")
  606. return [
  607. {
  608. ...base,
  609. state: {
  610. status: "error",
  611. input,
  612. error: structuredError(state.error) ?? { type: "ToolError", message: "Tool failed" },
  613. ...(metadata ? { metadata } : {}),
  614. },
  615. },
  616. ]
  617. return [{ ...base, state: { status: "running", input, metadata: metadata ?? {} } }]
  618. }
  619. function structuredError(value: unknown): SessionStructuredError | undefined {
  620. if (typeof value === "string") return { type: "Error", message: value }
  621. if (!record(value)) return
  622. if (typeof value.type === "string" && typeof value.message === "string")
  623. return { type: value.type, message: value.message }
  624. if (typeof value.name !== "string" || !record(value.data) || typeof value.data.message !== "string") return
  625. return { type: value.name, message: value.data.message }
  626. }
  627. function tokens(value: unknown): SessionMessageAssistant["tokens"] | undefined {
  628. if (!record(value) || !record(value.cache)) return
  629. if (
  630. typeof value.input !== "number" ||
  631. typeof value.output !== "number" ||
  632. typeof value.reasoning !== "number" ||
  633. typeof value.cache.read !== "number" ||
  634. typeof value.cache.write !== "number"
  635. )
  636. return
  637. return {
  638. input: value.input,
  639. output: value.output,
  640. reasoning: value.reasoning,
  641. cache: { read: value.cache.read, write: value.cache.write },
  642. }
  643. }
  644. function finish(value: unknown): SessionMessageAssistant["finish"] | undefined {
  645. if (
  646. value === "stop" ||
  647. value === "length" ||
  648. value === "tool-calls" ||
  649. value === "content-filter" ||
  650. value === "error" ||
  651. value === "unknown"
  652. )
  653. return value
  654. }
  655. function jsonRecord(value: unknown): Record<string, JsonValue> | undefined {
  656. if (!record(value)) return
  657. return Object.fromEntries(
  658. Object.entries(value).flatMap(([key, item]) => {
  659. const next = jsonValue(item)
  660. return next === undefined ? [] : [[key, next]]
  661. }),
  662. )
  663. }
  664. function jsonValue(value: unknown): JsonValue | undefined {
  665. if (value === null || typeof value === "string" || typeof value === "boolean") return value
  666. if (typeof value === "number") return Number.isFinite(value) ? value : null
  667. if (Array.isArray(value)) return value.map((item) => jsonValue(item) ?? null)
  668. return jsonRecord(value)
  669. }
  670. function record(value: unknown): value is Record<string, unknown> {
  671. return !!value && typeof value === "object" && !Array.isArray(value)
  672. }
  673. function json(route: Route, body: unknown, headers?: Record<string, string>, status = 200) {
  674. return route.fulfill({
  675. status,
  676. contentType: "application/json",
  677. headers: {
  678. "access-control-allow-origin": "*",
  679. "access-control-expose-headers": "x-next-cursor",
  680. ...headers,
  681. },
  682. body: JSON.stringify(body ?? null),
  683. })
  684. }
  685. function sse(route: Route, events?: unknown[], retry?: number) {
  686. return route.fulfill({
  687. status: 200,
  688. contentType: "text/event-stream",
  689. body: `${retry === undefined ? "" : `retry: ${retry}\n\n`}${events?.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("") || ": ok\n\n"}`,
  690. })
  691. }
  692. function currentEvent(input: unknown) {
  693. if (!input || typeof input !== "object" || !("payload" in input)) return input
  694. const envelope = input as { directory?: string; payload?: unknown }
  695. if (!envelope.payload || typeof envelope.payload !== "object") return input
  696. const payload = envelope.payload as { id?: string; type?: string; properties?: unknown }
  697. if (!payload.type) return input
  698. return {
  699. id: payload.id ?? `evt_mock_${Date.now()}`,
  700. created: Date.now(),
  701. type: payload.type,
  702. data: payload.properties ?? {},
  703. location: envelope.directory && envelope.directory !== "global" ? { directory: envelope.directory } : undefined,
  704. }
  705. }