| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194 |
- /**
- * 页面通道(API 模式)
- * ====================
- * 为什么不直接删掉页面通道:`cocorobo` 插件启动时读 `shell-bridge.json`,
- * 读不到就整块能力报"通道还没就绪"。所以就算不提供浏览器,也要有人在
- * 127.0.0.1 上按同一份契约应答 —— 只是答复内容从"执行结果"变成"这个部署没有页面"。
- *
- * 四条路由的语义:
- * POST /page/eval 没有页面 → 明确失败,并给出两条可走的替代路(老师手动 / cocorobo_api)
- * POST /page/dropFile 没有页面 → 文件已在工作区,给下载页地址让老师自己上传
- * POST /page/reload 没有页面 → 无副作用的成功(技能链路里有刷新步骤,不该因此中断)
- * POST /page/devtools 没有页面 → 成功但说明去看老师自己浏览器的 F12
- *
- * 为什么错误文案写得这么长:插件的 `cocorobo_page_eval` 会把 `error` 原样拼进
- * "页面脚本执行失败:<error>" 交给模型。只有把"为什么不行 + 该怎么办"写进 error,
- * 模型才不会以为是偶发故障、反复重试同一次调用。
- *
- * 与 PageBridge 的差别只有一个:这里不 import 任何浏览器相关模块,
- * 单会话常驻内存约 2MB(一个 http.Server + 一份 JSON 解析缓冲)。
- */
- import http from 'node:http'
- import crypto from 'node:crypto'
- import fs from 'node:fs'
- import path from 'node:path'
- const MAX_BODY = 512 * 1024
- function safeEqual (a, b) {
- const x = Buffer.from(String(a))
- const y = Buffer.from(String(b))
- if (x.length !== y.length) return false
- try { return crypto.timingSafeEqual(x, y) } catch { return false }
- }
- function readBody (req) {
- return new Promise((resolve, reject) => {
- let size = 0
- const chunks = []
- req.on('data', (chunk) => {
- size += chunk.length
- if (size > MAX_BODY) { reject(new Error('body-too-large')); req.destroy(); return }
- chunks.push(chunk)
- })
- req.on('end', () => {
- if (!chunks.length) return resolve({})
- try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch (err) {
- reject(new Error(`body-invalid: ${err.message}`))
- }
- })
- req.on('error', reject)
- })
- }
- export class ApiBridge {
- /**
- * @param {object} options
- * @param {string} options.tokenFile 插件读的 JSON({port, token}),与 browser 模式同名同格式
- * @param {string} options.platformBase 该老师所属区的平台地址(提示里要指路)
- * @param {string} options.filesUrl 工作区文件页地址(老师下载自己上传的地方)
- * @param {(msg:string)=>void} [options.log]
- */
- constructor (options) {
- this.tokenFile = options.tokenFile
- this.platformBase = String(options.platformBase || '').replace(/\/+$/, '')
- this.filesUrl = options.filesUrl || ''
- this.log = options.log || (() => {})
- this.token = crypto.randomBytes(24).toString('hex')
- this.server = null
- this.info = null
- }
- async start () {
- const server = http.createServer((req, res) => { this.#handle(req, res) })
- this.server = server
- await new Promise((resolve, reject) => {
- server.once('error', reject)
- server.listen(0, '127.0.0.1', resolve)
- })
- const port = server.address().port
- this.info = { port, token: this.token }
- await fs.promises.mkdir(path.dirname(this.tokenFile), { recursive: true })
- await fs.promises.writeFile(this.tokenFile, JSON.stringify(this.info), 'utf8')
- this.log(`[bridge] 页面通道 :${port}(API 模式,无服务端页面)`)
- return this.info
- }
- async stop () {
- try { await fs.promises.unlink(this.tokenFile) } catch { /* 已经不在了 */ }
- if (!this.server) return
- await new Promise((resolve) => this.server.close(resolve))
- this.server = null
- }
- async #handle (req, res) {
- const reply = (status, body) => {
- const text = JSON.stringify(body)
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
- res.end(text)
- }
- try {
- if (req.method !== 'POST') return reply(405, { ok: false, error: 'method-not-allowed' })
- const auth = String(req.headers.authorization || '')
- if (!auth.startsWith('Bearer ') || !safeEqual(auth.slice(7), this.token)) {
- return reply(401, { ok: false, error: 'unauthorized' })
- }
- const url = new URL(req.url, 'http://127.0.0.1')
- const payload = await readBody(req)
- let result
- if (url.pathname === '/page/eval') result = this.#eval(payload)
- else if (url.pathname === '/page/reload') result = this.#reload(payload)
- else if (url.pathname === '/page/devtools') result = this.#devtools(payload)
- else if (url.pathname === '/page/dropFile') result = this.#dropFile(payload)
- else return reply(404, { ok: false, error: 'not-found' })
- // 失败也回 200:插件按 body.ok 判断,非 2xx 会被它当成"通道连不上",
- // 那样模型看到的是网络故障而不是能力边界,容易反复重试。
- reply(200, result)
- } catch (err) {
- const code = /body-too-large/.test(err.message) ? 'body-too-large'
- : /body-invalid/.test(err.message) ? 'body-invalid'
- : `bridge-failed: ${err.message}`
- reply(200, { ok: false, error: code })
- }
- }
- /** 两条替代路的固定说法:老师手动操作,或改用通用接口通道 */
- #instead (what) {
- const base = this.platformBase || 'https://cloud.cocorobo.cn'
- return (
- `no-server-page:本次部署是「API 模式」,服务端不运行浏览器,${what}无法自动完成。` +
- `有两条路可以走:① 请老师在浏览器打开 ${base} 自己操作一次(登录态在老师本机,最省事);` +
- '② 如果这一步本质只是读写平台数据(班级列表、课件、发布、智能体),改用 cocorobo_api,' +
- 'target 填 platform / cocoflow / appstore,它直接调接口,不依赖页面。' +
- '不要重复调用本工具,换上面任一条路。'
- )
- }
- #eval (payload) {
- const code = String((payload && payload.code) || '').trim()
- if (!code) return { ok: false, error: 'empty-code' }
- return {
- ok: false,
- mode: 'api',
- error: this.#instead('页面脚本执行'),
- hint: '派给 cocorobo_api 或让老师手动,别再试 page_eval'
- }
- }
- #reload () {
- // 没有页面可刷。返回成功是刻意的:技能里"改完刷新再看"是一步常规动作,
- // 这里报错会把整条链路打断,而它其实没有任何副作用需要保留。
- return {
- ok: true,
- mode: 'api',
- url: this.platformBase,
- message: 'API 模式没有服务端页面,无需刷新'
- }
- }
- #devtools () {
- return {
- ok: true,
- mode: 'api',
- url: this.platformBase,
- panel: 'none',
- lines: [
- '本次部署是 API 模式,服务端没有页面,无法提供它的控制台。',
- '要看页面报错:请老师在浏览器按 F12 打开 Console。'
- ]
- }
- }
- #dropFile (payload) {
- const filePath = String((payload && (payload.path || payload.filePath)) || '').trim()
- if (!filePath) return { ok: false, error: 'empty-path' }
- const name = String(payload.name || path.basename(filePath))
- return {
- ok: false,
- mode: 'api',
- error:
- 'no-server-page:本次部署是「API 模式」,文件没法自动投进平台页面。' +
- `文件已经在老师的工作区里(${name}),请老师到 ${this.filesUrl || '工作区文件页'} 下载后手动上传;` +
- '或者直接让老师把文件拖进平台页面。上传完成后可以用 cocorobo_api 查状态、发布,' +
- '这两步不依赖页面。',
- manual: {
- file: name,
- filesUrl: this.filesUrl,
- platform: this.platformBase
- },
- hint: '不要重复投递,交给老师手动上传'
- }
- }
- }
|