apibridge.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /**
  2. * 页面通道(API 模式)
  3. * ====================
  4. * 为什么不直接删掉页面通道:`cocorobo` 插件启动时读 `shell-bridge.json`,
  5. * 读不到就整块能力报"通道还没就绪"。所以就算不提供浏览器,也要有人在
  6. * 127.0.0.1 上按同一份契约应答 —— 只是答复内容从"执行结果"变成"这个部署没有页面"。
  7. *
  8. * 四条路由的语义:
  9. * POST /page/eval 没有页面 → 明确失败,并给出两条可走的替代路(老师手动 / cocorobo_api)
  10. * POST /page/dropFile 没有页面 → 文件已在工作区,给下载页地址让老师自己上传
  11. * POST /page/reload 没有页面 → 无副作用的成功(技能链路里有刷新步骤,不该因此中断)
  12. * POST /page/devtools 没有页面 → 成功但说明去看老师自己浏览器的 F12
  13. *
  14. * 为什么错误文案写得这么长:插件的 `cocorobo_page_eval` 会把 `error` 原样拼进
  15. * "页面脚本执行失败:<error>" 交给模型。只有把"为什么不行 + 该怎么办"写进 error,
  16. * 模型才不会以为是偶发故障、反复重试同一次调用。
  17. *
  18. * 与 PageBridge 的差别只有一个:这里不 import 任何浏览器相关模块,
  19. * 单会话常驻内存约 2MB(一个 http.Server + 一份 JSON 解析缓冲)。
  20. */
  21. import http from 'node:http'
  22. import crypto from 'node:crypto'
  23. import fs from 'node:fs'
  24. import path from 'node:path'
  25. const MAX_BODY = 512 * 1024
  26. function safeEqual (a, b) {
  27. const x = Buffer.from(String(a))
  28. const y = Buffer.from(String(b))
  29. if (x.length !== y.length) return false
  30. try { return crypto.timingSafeEqual(x, y) } catch { return false }
  31. }
  32. function readBody (req) {
  33. return new Promise((resolve, reject) => {
  34. let size = 0
  35. const chunks = []
  36. req.on('data', (chunk) => {
  37. size += chunk.length
  38. if (size > MAX_BODY) { reject(new Error('body-too-large')); req.destroy(); return }
  39. chunks.push(chunk)
  40. })
  41. req.on('end', () => {
  42. if (!chunks.length) return resolve({})
  43. try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch (err) {
  44. reject(new Error(`body-invalid: ${err.message}`))
  45. }
  46. })
  47. req.on('error', reject)
  48. })
  49. }
  50. export class ApiBridge {
  51. /**
  52. * @param {object} options
  53. * @param {string} options.tokenFile 插件读的 JSON({port, token}),与 browser 模式同名同格式
  54. * @param {string} options.platformBase 该老师所属区的平台地址(提示里要指路)
  55. * @param {string} options.filesUrl 工作区文件页地址(老师下载自己上传的地方)
  56. * @param {(msg:string)=>void} [options.log]
  57. */
  58. constructor (options) {
  59. this.tokenFile = options.tokenFile
  60. this.platformBase = String(options.platformBase || '').replace(/\/+$/, '')
  61. this.filesUrl = options.filesUrl || ''
  62. this.log = options.log || (() => {})
  63. this.token = crypto.randomBytes(24).toString('hex')
  64. this.server = null
  65. this.info = null
  66. }
  67. async start () {
  68. const server = http.createServer((req, res) => { this.#handle(req, res) })
  69. this.server = server
  70. await new Promise((resolve, reject) => {
  71. server.once('error', reject)
  72. server.listen(0, '127.0.0.1', resolve)
  73. })
  74. const port = server.address().port
  75. this.info = { port, token: this.token }
  76. await fs.promises.mkdir(path.dirname(this.tokenFile), { recursive: true })
  77. await fs.promises.writeFile(this.tokenFile, JSON.stringify(this.info), 'utf8')
  78. this.log(`[bridge] 页面通道 :${port}(API 模式,无服务端页面)`)
  79. return this.info
  80. }
  81. async stop () {
  82. try { await fs.promises.unlink(this.tokenFile) } catch { /* 已经不在了 */ }
  83. if (!this.server) return
  84. await new Promise((resolve) => this.server.close(resolve))
  85. this.server = null
  86. }
  87. async #handle (req, res) {
  88. const reply = (status, body) => {
  89. const text = JSON.stringify(body)
  90. res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
  91. res.end(text)
  92. }
  93. try {
  94. if (req.method !== 'POST') return reply(405, { ok: false, error: 'method-not-allowed' })
  95. const auth = String(req.headers.authorization || '')
  96. if (!auth.startsWith('Bearer ') || !safeEqual(auth.slice(7), this.token)) {
  97. return reply(401, { ok: false, error: 'unauthorized' })
  98. }
  99. const url = new URL(req.url, 'http://127.0.0.1')
  100. const payload = await readBody(req)
  101. let result
  102. if (url.pathname === '/page/eval') result = this.#eval(payload)
  103. else if (url.pathname === '/page/reload') result = this.#reload(payload)
  104. else if (url.pathname === '/page/devtools') result = this.#devtools(payload)
  105. else if (url.pathname === '/page/dropFile') result = this.#dropFile(payload)
  106. else return reply(404, { ok: false, error: 'not-found' })
  107. // 失败也回 200:插件按 body.ok 判断,非 2xx 会被它当成"通道连不上",
  108. // 那样模型看到的是网络故障而不是能力边界,容易反复重试。
  109. reply(200, result)
  110. } catch (err) {
  111. const code = /body-too-large/.test(err.message) ? 'body-too-large'
  112. : /body-invalid/.test(err.message) ? 'body-invalid'
  113. : `bridge-failed: ${err.message}`
  114. reply(200, { ok: false, error: code })
  115. }
  116. }
  117. /** 两条替代路的固定说法:老师手动操作,或改用通用接口通道 */
  118. #instead (what) {
  119. const base = this.platformBase || 'https://cloud.cocorobo.cn'
  120. return (
  121. `no-server-page:本次部署是「API 模式」,服务端不运行浏览器,${what}无法自动完成。` +
  122. `有两条路可以走:① 请老师在浏览器打开 ${base} 自己操作一次(登录态在老师本机,最省事);` +
  123. '② 如果这一步本质只是读写平台数据(班级列表、课件、发布、智能体),改用 cocorobo_api,' +
  124. 'target 填 platform / cocoflow / appstore,它直接调接口,不依赖页面。' +
  125. '不要重复调用本工具,换上面任一条路。'
  126. )
  127. }
  128. #eval (payload) {
  129. const code = String((payload && payload.code) || '').trim()
  130. if (!code) return { ok: false, error: 'empty-code' }
  131. return {
  132. ok: false,
  133. mode: 'api',
  134. error: this.#instead('页面脚本执行'),
  135. hint: '派给 cocorobo_api 或让老师手动,别再试 page_eval'
  136. }
  137. }
  138. #reload () {
  139. // 没有页面可刷。返回成功是刻意的:技能里"改完刷新再看"是一步常规动作,
  140. // 这里报错会把整条链路打断,而它其实没有任何副作用需要保留。
  141. return {
  142. ok: true,
  143. mode: 'api',
  144. url: this.platformBase,
  145. message: 'API 模式没有服务端页面,无需刷新'
  146. }
  147. }
  148. #devtools () {
  149. return {
  150. ok: true,
  151. mode: 'api',
  152. url: this.platformBase,
  153. panel: 'none',
  154. lines: [
  155. '本次部署是 API 模式,服务端没有页面,无法提供它的控制台。',
  156. '要看页面报错:请老师在浏览器按 F12 打开 Console。'
  157. ]
  158. }
  159. }
  160. #dropFile (payload) {
  161. const filePath = String((payload && (payload.path || payload.filePath)) || '').trim()
  162. if (!filePath) return { ok: false, error: 'empty-path' }
  163. const name = String(payload.name || path.basename(filePath))
  164. return {
  165. ok: false,
  166. mode: 'api',
  167. error:
  168. 'no-server-page:本次部署是「API 模式」,文件没法自动投进平台页面。' +
  169. `文件已经在老师的工作区里(${name}),请老师到 ${this.filesUrl || '工作区文件页'} 下载后手动上传;` +
  170. '或者直接让老师把文件拖进平台页面。上传完成后可以用 cocorobo_api 查状态、发布,' +
  171. '这两步不依赖页面。',
  172. manual: {
  173. file: name,
  174. filesUrl: this.filesUrl,
  175. platform: this.platformBase
  176. },
  177. hint: '不要重复投递,交给老师手动上传'
  178. }
  179. }
  180. }