mock-server.ts 32 KB

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