realtimeProtocol.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import type { RawData } from 'ws'
  2. import { HttpError } from './errors.js'
  3. export const CHAT_MAX_PAYLOAD = 36 * 1_024 * 1_024
  4. const CHAT_METHODS = new Set([
  5. 'approval.respond',
  6. 'clarify.respond',
  7. 'config.set',
  8. 'file.attach',
  9. 'image.attach_bytes',
  10. 'pdf.attach',
  11. 'profiles.configure',
  12. 'profiles.get_asset',
  13. 'profiles.list',
  14. 'profiles.set_asset',
  15. 'prompt.submit',
  16. 'session.branch',
  17. 'session.close',
  18. 'session.context_breakdown',
  19. 'session.create',
  20. 'session.interrupt',
  21. 'session.resume',
  22. 'session.steer',
  23. 'session.usage',
  24. ])
  25. const SESSION_ID_REQUIRED_METHODS = new Set([
  26. 'config.set',
  27. 'file.attach',
  28. 'image.attach_bytes',
  29. 'pdf.attach',
  30. 'prompt.submit',
  31. 'session.branch',
  32. 'session.close',
  33. 'session.context_breakdown',
  34. 'session.interrupt',
  35. 'session.resume',
  36. 'session.steer',
  37. 'session.usage',
  38. ])
  39. function safeString(value: unknown, label: string, required = false): string | undefined {
  40. if (value === undefined && !required) return undefined
  41. if (typeof value !== 'string') throw new HttpError(400, `${label} must be a string`)
  42. const normalized = value.trim()
  43. if ((!normalized && required) || normalized.length > 256 || /[\u0000-\u001f\u007f]/.test(normalized)) {
  44. throw new HttpError(400, `${label} is invalid`)
  45. }
  46. return normalized
  47. }
  48. function normalizedConfigParams(params: Record<string, unknown>): Record<string, unknown> {
  49. const sessionID = safeString(params.session_id, 'session_id', true)!
  50. const key = safeString(params.key, 'config key', true)
  51. if (key === 'model') {
  52. const value = typeof params.value === 'string' ? params.value.trim() : ''
  53. if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,511} --provider [A-Za-z0-9][A-Za-z0-9._:-]{0,127}( --session)?$/.test(value)) {
  54. throw new HttpError(400, 'Model selection is invalid')
  55. }
  56. return {
  57. session_id: sessionID,
  58. key,
  59. value,
  60. ...(params.confirm_expensive_model === true ? { confirm_expensive_model: true } : {}),
  61. }
  62. }
  63. if (key === 'reasoning') {
  64. const value = safeString(params.value, 'reasoning value', true)!
  65. if (!new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']).has(value)) {
  66. throw new HttpError(400, 'Reasoning value is invalid')
  67. }
  68. return { session_id: sessionID, key, value, scope: 'session' }
  69. }
  70. if (key === 'fast') {
  71. const value = safeString(params.value, 'fast value', true)!
  72. if (value !== 'fast' && value !== 'normal') throw new HttpError(400, 'Fast value is invalid')
  73. return { session_id: sessionID, key, value, scope: 'session' }
  74. }
  75. throw new HttpError(403, 'Config key is not allowed')
  76. }
  77. function normalizedSessionOpenParams(
  78. method: 'session.create' | 'session.resume',
  79. params: Record<string, unknown>,
  80. ): Record<string, unknown> {
  81. const profile = safeString(params.profile, 'profile', true)!
  82. const columns = typeof params.cols === 'number' && Number.isInteger(params.cols)
  83. ? Math.min(500, Math.max(20, params.cols))
  84. : 80
  85. if (method === 'session.resume') {
  86. return {
  87. session_id: safeString(params.session_id, 'session_id', true)!,
  88. profile,
  89. source: 'web',
  90. close_on_disconnect: false,
  91. omit_messages: params.omit_messages === true,
  92. cols: columns,
  93. }
  94. }
  95. const title = safeString(params.title, 'title')
  96. const reasoning = safeString(params.reasoning_effort, 'reasoning effort')
  97. const allowedReasoning = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
  98. if (reasoning && !allowedReasoning.has(reasoning)) throw new HttpError(400, 'Reasoning effort is invalid')
  99. return {
  100. profile,
  101. source: 'web',
  102. close_on_disconnect: false,
  103. cols: columns,
  104. ...(title ? { title } : {}),
  105. ...(reasoning ? { reasoning_effort: reasoning } : {}),
  106. ...(typeof params.fast === 'boolean' ? { fast: params.fast } : {}),
  107. }
  108. }
  109. function normalizedPairedSessionOpenParams(
  110. method: 'session.create' | 'session.resume',
  111. params: Record<string, unknown>,
  112. ): Record<string, unknown> {
  113. const profile = safeString(params.profile, 'profile', true)!
  114. const source = safeString(params.source, 'source') ?? 'mobile'
  115. const columns = typeof params.cols === 'number' && Number.isInteger(params.cols)
  116. ? Math.min(500, Math.max(20, params.cols))
  117. : 80
  118. if (method === 'session.resume') {
  119. return {
  120. session_id: safeString(params.session_id, 'session_id', true)!,
  121. profile,
  122. source,
  123. close_on_disconnect: false,
  124. omit_messages: params.omit_messages === true,
  125. cols: columns,
  126. }
  127. }
  128. const title = safeString(params.title, 'title')
  129. const cwd = typeof params.cwd === 'string' && params.cwd.length <= 4_096 ? params.cwd : ''
  130. const reasoning = safeString(params.reasoning_effort, 'reasoning effort')
  131. const allowedReasoning = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])
  132. if (reasoning && !allowedReasoning.has(reasoning)) throw new HttpError(400, 'Reasoning effort is invalid')
  133. const model = safeString(params.model, 'model')
  134. const provider = safeString(params.provider, 'provider')
  135. if ((model === undefined) !== (provider === undefined)) {
  136. throw new HttpError(400, 'Model and provider must be set together')
  137. }
  138. const messages = params.messages
  139. if (messages !== undefined && (!Array.isArray(messages) || messages.length > 256)) {
  140. throw new HttpError(400, 'Seed messages are invalid')
  141. }
  142. return {
  143. profile,
  144. source,
  145. close_on_disconnect: false,
  146. cols: columns,
  147. cwd,
  148. hidden: params.hidden === true,
  149. ...(title ? { title } : {}),
  150. ...(reasoning ? { reasoning_effort: reasoning } : {}),
  151. ...(model && provider ? { model, provider } : {}),
  152. ...(typeof params.fast === 'boolean' ? { fast: params.fast } : {}),
  153. ...(messages !== undefined ? { messages } : {}),
  154. }
  155. }
  156. export function checkedChatFrame(data: RawData, isBinary: boolean, paired = false): string {
  157. if (isBinary) throw new HttpError(400, 'Binary chat frames are not accepted')
  158. const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data as ArrayBuffer)
  159. if (bytes.byteLength > CHAT_MAX_PAYLOAD) throw new HttpError(413, 'Chat frame is too large')
  160. let value: unknown
  161. try {
  162. value = JSON.parse(bytes.toString('utf8'))
  163. } catch {
  164. throw new HttpError(400, 'Chat frame must be JSON')
  165. }
  166. if (!value || typeof value !== 'object' || Array.isArray(value)) {
  167. throw new HttpError(400, 'Chat frame must be a JSON-RPC object')
  168. }
  169. const request = value as Record<string, unknown>
  170. if (typeof request.method !== 'string' || !CHAT_METHODS.has(request.method)) {
  171. throw new HttpError(403, 'Chat RPC method is not allowed')
  172. }
  173. if (request.id !== undefined && typeof request.id !== 'string' && typeof request.id !== 'number') {
  174. throw new HttpError(400, 'Chat RPC id is invalid')
  175. }
  176. if (!request.params || typeof request.params !== 'object' || Array.isArray(request.params)) {
  177. throw new HttpError(400, 'Chat RPC params must be an object')
  178. }
  179. let params = { ...(request.params as Record<string, unknown>) }
  180. safeString(params.session_id, 'session_id', SESSION_ID_REQUIRED_METHODS.has(request.method))
  181. const profileRequired = request.method === 'session.create' || request.method === 'session.resume'
  182. safeString(params.profile, 'profile', profileRequired)
  183. if (request.method === 'session.create' || request.method === 'session.resume') {
  184. params = paired
  185. ? normalizedPairedSessionOpenParams(request.method, params)
  186. : normalizedSessionOpenParams(request.method, params)
  187. }
  188. if (request.method === 'profiles.list') {
  189. const preferred = params.preferred_session_ids
  190. if (preferred !== undefined && (!preferred || typeof preferred !== 'object' || Array.isArray(preferred))) {
  191. throw new HttpError(400, 'preferred_session_ids must be an object')
  192. }
  193. params = {
  194. ...(typeof params.include_sessions === 'boolean' ? { include_sessions: params.include_sessions } : {}),
  195. ...(preferred !== undefined ? { preferred_session_ids: preferred } : {}),
  196. }
  197. }
  198. if (request.method === 'profiles.get_asset') {
  199. params = {
  200. name: safeString(params.name, 'profile name', true)!,
  201. asset: safeString(params.asset, 'profile asset', true)!,
  202. }
  203. }
  204. if (request.method === 'profiles.set_asset') {
  205. const clear = params.clear === true
  206. const data = typeof params.data === 'string' ? params.data.trim() : ''
  207. if (!clear && !data) throw new HttpError(400, 'profile asset data is required')
  208. if (data.length > 2_800_000) throw new HttpError(413, 'profile asset exceeds 2 MiB')
  209. params = {
  210. name: safeString(params.name, 'profile name', true)!,
  211. asset: safeString(params.asset, 'profile asset', true)!,
  212. ...(clear ? { clear: true } : { data }),
  213. }
  214. }
  215. if (request.method === 'profiles.configure') {
  216. if (!params.ui_meta || typeof params.ui_meta !== 'object' || Array.isArray(params.ui_meta)) {
  217. throw new HttpError(400, 'ui_meta must be an object')
  218. }
  219. if (params.ui_meta_expected_revisions !== undefined
  220. && (!params.ui_meta_expected_revisions
  221. || typeof params.ui_meta_expected_revisions !== 'object'
  222. || Array.isArray(params.ui_meta_expected_revisions))) {
  223. throw new HttpError(400, 'ui_meta_expected_revisions must be an object')
  224. }
  225. params = {
  226. name: safeString(params.name, 'profile name', true)!,
  227. ui_meta: params.ui_meta,
  228. ...(params.ui_meta_expected_revisions !== undefined
  229. ? { ui_meta_expected_revisions: params.ui_meta_expected_revisions }
  230. : {}),
  231. }
  232. }
  233. if (request.method === 'config.set') params = normalizedConfigParams(params)
  234. if (request.method === 'prompt.submit' || request.method === 'session.steer') {
  235. const text = typeof params.text === 'string' ? params.text.trim() : ''
  236. if (!text || text.length > 200_000) throw new HttpError(400, 'Prompt text is invalid')
  237. params = {
  238. session_id: safeString(params.session_id, 'session_id', true)!,
  239. text,
  240. ...(request.method === 'prompt.submit' && params.queued === true ? { queued: true } : {}),
  241. }
  242. }
  243. if (request.method === 'image.attach_bytes' || request.method === 'pdf.attach') {
  244. const encoded = typeof params.content_base64 === 'string' ? params.content_base64 : ''
  245. const estimated = Math.floor(encoded.length * 0.75)
  246. if (!encoded || estimated > 25 * 1_024 * 1_024) {
  247. throw new HttpError(413, 'Attachment exceeds 25 MiB')
  248. }
  249. }
  250. if (request.method === 'file.attach') {
  251. const dataURL = typeof params.data_url === 'string' ? params.data_url : ''
  252. const marker = dataURL.indexOf(',')
  253. if (marker < 0 || Math.floor((dataURL.length - marker - 1) * 0.75) > 25 * 1_024 * 1_024) {
  254. throw new HttpError(413, 'Attachment exceeds 25 MiB')
  255. }
  256. }
  257. return JSON.stringify({ ...request, params })
  258. }
  259. export class GroupFrameValidator {
  260. #ready = false
  261. #cursor: number
  262. constructor(readonly epoch: string, cursor: number) {
  263. this.#cursor = cursor
  264. }
  265. accept(data: RawData, isBinary: boolean): boolean {
  266. if (isBinary) throw new HttpError(400, 'Binary group frames are not accepted')
  267. let envelope: Record<string, unknown>
  268. try {
  269. const value = JSON.parse(Buffer.from(data as Uint8Array).toString('utf8')) as unknown
  270. if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object')
  271. envelope = value as Record<string, unknown>
  272. } catch {
  273. throw new HttpError(400, 'Malformed group event frame')
  274. }
  275. const type = envelope.type
  276. const cursor = Number(envelope.cursor)
  277. if (type === 'group.ready') {
  278. const heartbeat = Number(envelope.heartbeatSeconds)
  279. if (this.#ready || envelope.epoch !== this.epoch || !Number.isSafeInteger(cursor)
  280. || cursor !== this.#cursor || !Number.isFinite(heartbeat) || heartbeat <= 0) {
  281. throw new HttpError(409, 'Invalid group.ready frame')
  282. }
  283. this.#ready = true
  284. return true
  285. }
  286. if (type === 'group.reset_required') {
  287. if (typeof envelope.epoch !== 'string' || !Number.isSafeInteger(cursor)
  288. || typeof envelope.reason !== 'string') {
  289. throw new HttpError(400, 'Invalid group.reset_required frame')
  290. }
  291. return true
  292. }
  293. if (!this.#ready) throw new HttpError(409, 'Group event arrived before group.ready')
  294. if (type === 'group.event') {
  295. if (envelope.epoch !== this.epoch || !Number.isSafeInteger(cursor) || cursor < 0) {
  296. throw new HttpError(409, 'Group event epoch or cursor is invalid')
  297. }
  298. if (cursor <= this.#cursor) return false
  299. if (cursor !== this.#cursor + 1) throw new HttpError(409, 'Group event cursor gap')
  300. this.#cursor = cursor
  301. return true
  302. }
  303. if (type === 'group.heartbeat') {
  304. if ((envelope.epoch !== undefined && envelope.epoch !== this.epoch)
  305. || !Number.isSafeInteger(cursor) || cursor !== this.#cursor) {
  306. throw new HttpError(409, 'Group heartbeat cursor mismatch')
  307. }
  308. return true
  309. }
  310. throw new HttpError(400, 'Unknown group event frame')
  311. }
  312. resetFrame(reason: string): string {
  313. return JSON.stringify({
  314. type: 'group.reset_required',
  315. epoch: this.epoch,
  316. cursor: this.#cursor,
  317. reason,
  318. })
  319. }
  320. }
  321. export function canonicalEpoch(value: unknown): string {
  322. if (typeof value !== 'string'
  323. || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
  324. throw new HttpError(400, 'epoch must be a canonical lowercase UUID', 'invalid_epoch')
  325. }
  326. return value
  327. }
  328. export function groupCursor(value: unknown): number {
  329. const cursor = typeof value === 'number' ? value : Number(value ?? 0)
  330. if (!Number.isSafeInteger(cursor) || cursor < 0) {
  331. throw new HttpError(400, 'cursor must be a non-negative integer', 'invalid_cursor')
  332. }
  333. return cursor
  334. }