index.mjs 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  1. /**
  2. * CocoBuddy 教师端 dsh 插件
  3. * ------------------------
  4. * 第一阶段只开放两个"创建"能力,越少越好用:
  5. * cococlass_courseware_create —— 一句话 → cococlass 课件
  6. * cococlass_course_from_pptx —— 本地 PPTX 交给平台前端解析建课
  7. * cocoflow_agent_create —— 一句话 → cocoflow 工作流智能体
  8. *
  9. * 设计约束(改代码前先读):
  10. * 1. 工具名带业务域前缀(cococlass_ / cocoflow_),模型看名字就知道选哪个。
  11. * 2. 粒度对齐老师的一句自然语言,不暴露 CRUD,也不让模型自己拼多步。
  12. * 3. 建课件是分钟级长任务:工具内部自己等,等不到就把 taskId 和链接交出去,
  13. * 绝不要求模型连续轮询(那会把对话刷成一堆工具气泡)。
  14. * 4. 登录态每次从 authFile 读取,换账号/续期不需要重启进程。
  15. * 5. 其余能力(班级列表/发布/我的课件)由 config.extras 控制,默认不开。
  16. */
  17. import fs from 'node:fs'
  18. import path from 'node:path'
  19. import { createUserCenter } from './user.mjs'
  20. import { createBrowserController } from './browser.mjs'
  21. import { readOfficeFile, writeDocx, writeXlsx, writePptx, htmlToPdf, htmlToPng } from './office.mjs'
  22. import { buildWorkflowFile, WorkflowError, WorkflowIOError } from './workflow-build.mjs'
  23. const DEFAULT_API_BASE = 'https://cloud.cocorobo.cn'
  24. const API_PREFIX = '/agent/v1'
  25. // 建课件默认最多在工具里等 45 秒,剩下的交给"续查"链接,避免工具调用超时
  26. const DEFAULT_WAIT_MS = 45_000
  27. export const name = 'cocorobo'
  28. export const inject = ['tools']
  29. export function apply (ctx, config = {}) {
  30. const apiBase = (config.apiBase || DEFAULT_API_BASE).replace(/\/+$/, '')
  31. // 门户页面基址:创建完成后要在客户端右侧打开的那个网页。和接口同域,
  32. // 随语言/区域切换(cloud.cocorobo.cn / .hk / .com),所以默认跟着 apiBase 走。
  33. const portalBase = String(config.portalBase || apiBase).replace(/\/+$/, '')
  34. /**
  35. * 平台页面的 hash 路由:
  36. * 智能体 {portal}/#!/agent/<agentId>
  37. * 课件/课程 {portal}/#!/cococlass/<coursewareId>
  38. * 工具结果里带 openUrl,客户端插件会据此在右侧打开浏览器页
  39. * (见 resources/plugin/cocorobo-brand/client.js)。
  40. */
  41. const pageUrl = (kind, id) => (id ? `${portalBase}/#!/${kind}/${encodeURIComponent(id)}` : '')
  42. // 课件编辑器(PPT 解析 + 保存都在这个前端里跑)
  43. const pptBase = String(config.cococlassPptBase || 'https://ppt.cocorobo.cn').replace(/\/+$/, '')
  44. /**
  45. * 应用中心(/api/pbl/*):第三个后端,独立域名 pbl.cocorobo.cn。
  46. * 智能体"发布成应用"之后的分类、权限、详情、列表都在这里,不在 appapi,
  47. * 也不在 cloud 的 /agent/v1。实测只带平台 apiKey(Bearer)就够,不需要网页 cookie。
  48. */
  49. const appStoreBase = String(config.appStoreApiBase || 'https://pbl.cocorobo.cn').replace(/\/+$/, '')
  50. // 统一模型网关(openai 兼容):图片走它,key 与业务 apiKey 同一把(见 electron/llm.js)
  51. const llmBase = String(config.llmBaseURL || '').trim().replace(/\/+$/, '')
  52. // 图像网关默认与文本同一个;服务端若把图片单独挂在别的地址,用 imageBaseURL 覆盖,不用发版
  53. const imageBase = String(config.imageBaseURL || '').trim().replace(/\/+$/, '') || llmBase
  54. /**
  55. * 图片作品统一落在老师的数据目录里,不是当前 cwd:
  56. * 引擎的 cwd 会随会话变化,换个会话老师就找不到刚生成的图了。
  57. */
  58. const workspaceDir = String(
  59. config.workspaceDir ||
  60. (config.authFile ? path.join(path.dirname(path.dirname(config.authFile)), 'workspace') : '')
  61. )
  62. const authFile = config.authFile
  63. const forceMock = config.mock !== false
  64. const extras = config.extras === true
  65. const waitMs = Number(config.waitMs) || DEFAULT_WAIT_MS
  66. const readAuth = () => {
  67. try {
  68. return JSON.parse(fs.readFileSync(authFile, 'utf8'))
  69. } catch {
  70. return { apiBase, token: '', mock: forceMock }
  71. }
  72. }
  73. const isMock = () => forceMock || !!readAuth().mock
  74. const token = () => (readAuth().token || '').trim()
  75. /**
  76. * 当前登录老师(cococlass / cocoflow 共用同一份)。
  77. * 身份先读 authFile;缺 organizeid / apiKey 时按缓存的 userid 去平台补全,
  78. * 补全结果写回 authFile —— "登录回调没带 organizeid" 只影响第一次调用。
  79. */
  80. const user = createUserCenter({
  81. authFile,
  82. apiBase,
  83. pblBase: config.pblBase || config.cocoroboPblBase || '',
  84. mock: forceMock,
  85. // 默认只走判 cookie 的 selectUser;selectUser2 是无鉴权测试接口,只有本机调试才显式打开
  86. allowTestApi: config.pblTestApi === true
  87. })
  88. function fail (message, hint) {
  89. throw new Error(hint ? `${message}。${hint}` : message)
  90. }
  91. function idempotencyKey (prefix) {
  92. const uuid = globalThis.crypto && globalThis.crypto.randomUUID
  93. ? globalThis.crypto.randomUUID()
  94. : `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
  95. return `${prefix}-${uuid}`
  96. }
  97. /** 平台可能返回 {code,data} 包装,统一拆一层,工具里就不用到处判断。 */
  98. function unwrap (json) {
  99. if (json && typeof json === 'object' && json.data && typeof json.data === 'object' && !Array.isArray(json.data)) {
  100. return json.data
  101. }
  102. return json || {}
  103. }
  104. async function api (pathname, init = {}) {
  105. const url = `${apiBase}${API_PREFIX}${pathname}`
  106. // 身份与凭据都走用户中心:key 可能是刚按 userid 补全回来的那一把
  107. const me = await user.resolve()
  108. const tk = me.apiKey || token()
  109. if (!tk) fail('还没有登录账号', '请在客户端里完成登录后重试')
  110. let res
  111. try {
  112. res = await fetch(url, {
  113. ...init,
  114. headers: {
  115. 'content-type': 'application/json',
  116. authorization: `Bearer ${tk}`,
  117. // 平台侧可直接用这几个头定位老师/学校;没有就省略,平台自己按 apiKey 反查
  118. ...(me.userid ? { 'x-user-id': me.userid } : {}),
  119. ...(me.schoolName ? { 'x-school-name': encodeURIComponent(me.schoolName) } : {}),
  120. ...(me.organizeId ? { 'x-org-id': me.organizeId } : {}),
  121. ...(init.headers || {})
  122. },
  123. signal: init.signal
  124. })
  125. } catch (err) {
  126. if (err && err.name === 'AbortError') throw err
  127. fail(`连不上平台接口 ${pathname}`, `${err.message};请检查网络或平台地址`)
  128. }
  129. const text = await res.text()
  130. if (res.status === 401 || res.status === 403) fail('登录已过期或没有权限', '请重新登录客户端')
  131. let json = null
  132. try { json = text ? JSON.parse(text) : null } catch { /* 非 JSON */ }
  133. if (!res.ok) {
  134. const msg = json && (json.message || json.msg || json.error)
  135. fail(`平台接口 ${pathname} 返回 ${res.status}`, msg || text.slice(0, 200))
  136. }
  137. if (json === null) fail(`平台接口 ${pathname} 返回的不是 JSON`, '请确认接口已按契约实现')
  138. if (typeof json.code === 'number' && json.code !== 0) {
  139. fail(json.message || json.msg || `平台返回错误码 ${json.code}`)
  140. }
  141. return unwrap(json)
  142. }
  143. const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
  144. // ------------------------------------------------------------------ 进度
  145. const RUNNING = new Set(['queued', 'pending', 'running', 'processing', 'generating', 'in_progress'])
  146. const DONE = new Set(['done', 'success', 'succeeded', 'completed', 'finished', 'ready'])
  147. const FAILED = new Set(['failed', 'error', 'canceled', 'cancelled', 'timeout'])
  148. function stateOf (task) {
  149. const raw = String(task.status || task.state || '').toLowerCase()
  150. if (DONE.has(raw)) return 'done'
  151. if (FAILED.has(raw)) return 'failed'
  152. if (RUNNING.has(raw)) return 'running'
  153. // 有结果地址基本就等于做完了,兼容只回 previewUrl 不回收敛状态的平台
  154. if (task.previewUrl || task.coursewareId || task.resultUrl) return 'done'
  155. return 'running'
  156. }
  157. /**
  158. * 在工具内部等异步任务收敛。
  159. * 收敛了返回结果;超时返回 running 快照(带链接);失败抛出可读原因。
  160. */
  161. async function waitTask (taskId, { timeoutMs, signal, initial }) {
  162. const deadline = Date.now() + timeoutMs
  163. let snap = initial || { taskId, status: 'queued' }
  164. let delay = 1200
  165. while (Date.now() < deadline) {
  166. if (signal && signal.aborted) throw new Error('已取消')
  167. if (stateOf(snap) === 'done') return snap
  168. if (stateOf(snap) === 'failed') {
  169. fail(snap.message || snap.error || '平台生成失败', '可以调整要求后重新生成一次')
  170. }
  171. await sleep(delay)
  172. delay = Math.min(Math.round(delay * 1.4), 6000)
  173. // mock 模式下没有平台接口可问:直接用本地假任务推进,否则会拿空 token 去请求
  174. // /tasks 并被判成"还没有登录账号",整条链路连试都试不了。
  175. snap = isMock()
  176. ? { ...mockTaskState(taskId), taskId }
  177. : { ...(await api(`/tasks/${encodeURIComponent(taskId)}`, { signal })), taskId }
  178. }
  179. return { ...snap, taskId, status: snap.status || 'running', timedOut: true }
  180. }
  181. // ---------------------------------------------------------------- mock 实现
  182. // 平台接口还没上线时,让整条链路(对话 → 工具 → 结果卡片)先跑起来。
  183. const mockTasks = new Map()
  184. const mockAgents = []
  185. let mockSeq = 0
  186. const MOCK_CLASSES = [
  187. { id: 'cls-1001', name: '三年级 2 班', grade: '三年级', students: 38 },
  188. { id: 'cls-1002', name: '四年级 1 班', grade: '四年级', students: 41 },
  189. { id: 'cls-1003', name: '八年级 2 班', grade: '八年级', students: 42 }
  190. ]
  191. function mockCreateTask (kind, input) {
  192. mockSeq += 1
  193. const id = `mock-${Date.now().toString(36)}-${mockSeq}`
  194. mockTasks.set(id, { id, kind, input, createdAt: Date.now() })
  195. return { taskId: id, status: 'queued' }
  196. }
  197. function mockTaskState (id) {
  198. const t = mockTasks.get(id)
  199. if (!t) fail(`找不到任务 ${id}`, '任务可能已过期,请重新创建')
  200. const elapsed = Date.now() - t.createdAt
  201. if (elapsed < 2000) return { taskId: id, status: 'running', progress: 30, stage: '正在生成课程大纲' }
  202. if (elapsed < 4500) return { taskId: id, status: 'running', progress: 72, stage: '正在生成页面与配图' }
  203. return {
  204. taskId: id,
  205. status: 'done',
  206. progress: 100,
  207. stage: '已完成',
  208. title: t.input.title,
  209. coursewareId: `cw-${id.slice(-6)}`,
  210. pageCount: 12,
  211. previewUrl: `${apiBase}/cococlass/courseware/${id}/preview`,
  212. editUrl: `${apiBase}/cococlass/courseware/${id}/edit`
  213. }
  214. }
  215. const textOut = (value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
  216. const jsonOut = { schema: { type: 'object', additionalProperties: true }, render: (_a, v) => textOut(v) }
  217. /**
  218. * ctx.tools.register 的 parameters 要的是**完整 JSON Schema**
  219. * ({type:'object', properties, required}),不是 defineTool 那套「属性表 + required:true」的简写。
  220. * 简写原样发给模型会直接 400:
  221. * Provider API error: tools[n].function.parameters must be a JSON Schema of type object
  222. * 所以这里统一把手写属性表编译成模型要的形状。
  223. */
  224. function params (props = {}) {
  225. const properties = {}
  226. const required = []
  227. for (const [key, spec] of Object.entries(props)) {
  228. const { required: isRequired, ...rest } = spec || {}
  229. properties[key] = rest
  230. if (isRequired) required.push(key)
  231. }
  232. return { type: 'object', properties, ...(required.length ? { required } : {}) }
  233. }
  234. // ============================================== 用户中心:我是谁
  235. // cococlass / cocoflow 的业务工具内部都会调 user.resolve(),所以这把工具不是"必经步骤",
  236. // 而是给两种情况用:老师直接问"我现在是哪个账号",以及业务工具报缺 userid / organizeId 时排查。
  237. ctx.tools.register({
  238. name: 'cocorobo_user_profile',
  239. description:
  240. '读取当前登录老师的平台账号信息(userid、姓名、学校、机构 id、账号名)。' +
  241. 'cococlass 与 cocoflow 的工具会自动使用这份身份,通常不必手动调用;' +
  242. '老师问"我现在登录的是谁/用的哪个账号",或工具报缺身份信息时再调用它。' +
  243. '返回里不含密钥明文。',
  244. parameters: params({
  245. refresh: { type: 'boolean', description: 'true 表示忽略缓存、重新向平台读一次(换账号或怀疑信息不对时用)' }
  246. }),
  247. output: jsonOut,
  248. timeoutMs: 20_000,
  249. async execute (args) {
  250. const profile = await user.describe({ force: !!(args && args.refresh) })
  251. return {
  252. ...profile,
  253. hint: profile.missing.length
  254. ? `缺少 ${profile.missing.join(' / ')}:请老师在客户端退出后重新登录一次;仍然缺就是登录回调没把这些参数带回来`
  255. : ''
  256. }
  257. }
  258. })
  259. // ========================================== 把平台页面放到客户端右侧
  260. // 老师说"在右边打开/打开看看/把它调出来"时,模型需要一把能真的开页面的工具,
  261. // 否则只会回"我没有打开网页的能力"。这里只做一件事:返回 openUrl,
  262. // 客户端品牌插件收到结果就在右侧栏开页签(与建课件/建智能体同一套机制)。
  263. ctx.tools.register({
  264. name: 'cocorobo_open_page',
  265. description:
  266. '在客户端右侧栏打开一个可可乐博平台的页面,老师不用离开对话。' +
  267. '老师说"在右边打开/打开看看/把某个课件、智能体、课程页面调出来"时调用;' +
  268. '已知智能体或课件的 id 时可以直接拼链接。' +
  269. 'url 必须是 cocorobo 平台地址(cloud.cocorobo.cn / ppt.cocorobo.cn / beta.cloud.cocorobo.cn 等)。',
  270. parameters: params({
  271. url: { type: 'string', required: true, description: '要打开的完整地址(https:// 开头),也接受 /#!/agent/<id> 这种站内路径' },
  272. title: { type: 'string', description: '页面名称,仅用于对话说明' }
  273. }),
  274. output: jsonOut,
  275. timeoutMs: 10_000,
  276. async execute (args) {
  277. let url = String(args.url || '').trim()
  278. if (!url) fail('缺少 url', '给出要打开的完整地址')
  279. // 站内路径补成完整地址:模型常直接把路由写出来,不该因此失败
  280. if (url.startsWith('#')) url = `${portalBase}/${url}`
  281. else if (url.startsWith('/')) url = `${portalBase}${url}`
  282. if (!/^https?:\/\//i.test(url)) fail('url 需要是 http(s) 地址', `收到的是 ${url}`)
  283. // 只放行平台域名:右边栏是登录态上下文,随便开外站等于把老师带走
  284. if (!/^https?:\/\/([a-z0-9-]+\.)*cocorobo\.(cn|hk|com)(\/|$)/i.test(url)) {
  285. fail('只支持可可乐博平台页面', `这个地址不属于平台域名:${url}`)
  286. }
  287. return {
  288. ok: true,
  289. openUrl: url,
  290. title: String(args.title || '').trim(),
  291. message: '已在客户端右侧打开,简单说一句"右边可以看了"就行'
  292. }
  293. }
  294. })
  295. // ====================================== 在右侧页面里执行一段脚本
  296. // 技能要"在右边那个页面上做一件事"(调用模块暴露的 window.__cocorobo 函数、
  297. // 读页面上的状态),是各产品组最常见的诉求。工具跑在引擎进程、页面在外壳进程,
  298. // 以前没有回路;现在外壳开了一条只走 127.0.0.1 的通道(electron/page-bridge.js),
  299. // 这里只是它的入口。凭据每次启动重新生成,插件调用时才读。
  300. const bridgeFile = String(config.bridgeFile || '').trim()
  301. function bridgeInfo () {
  302. if (!bridgeFile) return null
  303. try {
  304. const raw = JSON.parse(fs.readFileSync(bridgeFile, 'utf8'))
  305. if (!raw || !raw.port || !raw.token) return null
  306. return raw
  307. } catch {
  308. return null
  309. }
  310. }
  311. ctx.tools.register({
  312. name: 'cocorobo_page_eval',
  313. description:
  314. '在客户端右侧已经打开的可可乐博平台页面上执行一段 JavaScript,并把结果拿回来。' +
  315. '页面模块暴露了 window.__cocorobo.<模块>.<方法>(题库筛选、课件定位、白板载入等)时用它调用;' +
  316. '也可以读页面状态(当前课件 id、列表条数)。' +
  317. '右侧没有平台页面时返回 no-guest —— 先用 cocorobo_open_page 打开,再调用。' +
  318. '只对平台域名生效,不能开新页、不能导航、不能读本地文件、不能操作老师的账号设置。',
  319. parameters: params({
  320. code: {
  321. type: 'string',
  322. required: true,
  323. description: '要执行的 JS:表达式或 async IIFE,返回值必须可 JSON 序列化。' +
  324. '例:window.__cocorobo.questionBank.filter({ kw: "分数" })'
  325. },
  326. urlMatch: { type: 'string', description: '按地址挑页面,如 cloud.cocorobo.cn;不填就用当前可见的平台页面' },
  327. timeoutMs: { type: 'number', description: '超时毫秒,默认 8000,上限 20000' }
  328. }),
  329. output: jsonOut,
  330. timeoutMs: 25_000,
  331. async execute (args) {
  332. const code = String(args.code || '').trim()
  333. if (!code) fail('缺少 code', '给出要执行的 JS,例如 window.__cocorobo.cococlass.currentLesson()')
  334. const info = bridgeInfo()
  335. if (!info) {
  336. fail(
  337. '页面执行通道还没就绪',
  338. '让老师重启客户端后再试;如果只是想打开页面,用 cocorobo_open_page(它不需要这条通道)'
  339. )
  340. }
  341. let data = null
  342. try {
  343. const res = await fetch(`http://127.0.0.1:${info.port}/page/eval`, {
  344. method: 'POST',
  345. headers: {
  346. 'content-type': 'application/json',
  347. authorization: `Bearer ${info.token}`
  348. },
  349. body: JSON.stringify({
  350. code,
  351. urlMatch: String(args.urlMatch || '').trim(),
  352. timeoutMs: Number(args.timeoutMs) || 0
  353. })
  354. })
  355. data = await res.json()
  356. } catch (err) {
  357. fail('页面执行通道连不上', `客户端可能已退出或换了通道端口:${err.message}`)
  358. }
  359. if (!data || data.ok !== true) {
  360. const reason = String((data && data.error) || 'unknown')
  361. if (reason === 'no-guest') {
  362. fail('右侧还没有打开平台页面', '先用 cocorobo_open_page 打开对应页面,再执行脚本')
  363. }
  364. if (reason === 'timeout') {
  365. fail('页面脚本超时', '把动作拆小;页面可能还在加载,先确认已经打开完成')
  366. }
  367. fail(
  368. `页面脚本执行失败:${reason}`,
  369. '确认页面里确实有这段代码(例如 window.__cocorobo.<模块>.<方法>),不要凭空调用不存在的函数'
  370. )
  371. }
  372. return {
  373. ok: true,
  374. url: data.url || '',
  375. value: data.value,
  376. truncated: data.truncated === true,
  377. message: '结果已经拿到:按结果回答老师,不要把 JS 代码念出来'
  378. }
  379. }
  380. })
  381. // ====================================== 把本地文件投进右侧页面
  382. // 老师在对话里给了 PPT、或文件已经在技能工作区时,页面侧脚本投不进去:
  383. // executeJavaScript 只能跑文本,浏览器也不允许脚本凭空造 File 塞进 input.files
  384. // (需要用户手势)。字节在外壳进程里,所以走 /page/dropFile —— 和 page_eval
  385. // 同一条 127.0.0.1 通道、同一份凭据。没有这把工具时,模型只能答
  386. // "我在页面里造不出 File,你自己拖一下"(2026-11-20 用户现场)。
  387. ctx.tools.register({
  388. name: 'cocorobo_page_drop_file',
  389. description:
  390. '把老师放进对话的文件直接交给右侧平台页面:可以是上传控件,也可以是页面自己暴露的函数(pageFn)。' +
  391. '等同于老师自己点「选择文件」或把文件拖进页面。支持任意类型(pptx/ppt/pdf/docx/xlsx/图片/音视频…),单文件上限 512MB。' +
  392. '给了 pageFn 就把真 File 交给那个函数,函数返回值原样带回;不给 pageFn 就塞进页面的 input[type=file] 并派发 change。' +
  393. '页面钩子收数组的(如建课页 window.handleFileUpload(File[]))传 pageFnArgs:"array"。' +
  394. '禁止为搬运文件编写任何本地 HTTP 服务 / serve_pptx.js / 127.0.0.1 临时端口:字节已由本工具读入并还原成真 File,起服务是过期写法。' +
  395. '投递只负责"把文件交到页面手上",页面处理完再用 cocorobo_page_eval 回读状态核对。',
  396. parameters: params({
  397. path: { type: 'string', required: true, description: '本地文件的绝对路径(技能工作区里的那份)' },
  398. pageFn: {
  399. type: 'string',
  400. description: '页面函数路径,例如建课页 window.handleFileUpload(最里层 ppt iframe,收 File[],须配 pageFnArgs:"array")。' +
  401. '给了就优先调它,页面没有这个函数才退回 input。函数发在哪一层 frame 都行,会自动找。'
  402. },
  403. pageFnArgs: {
  404. type: 'string',
  405. enum: ['single', 'array'],
  406. description: '页面函数入参形态:默认 single = fn(file, meta);array = fn([file], meta),用于 handleFileUpload(File[]) 这类收数组的钩子。'
  407. },
  408. name: { type: 'string', description: '页面上显示的文件名;不填就用 path 的文件名' },
  409. urlMatch: { type: 'string', description: '按地址挑页签,如 ppt.cocorobo.cn;不填就取最新打开的平台页签' },
  410. clickText: {
  411. type: 'array',
  412. items: { type: 'string' },
  413. description: '上传入口的按钮文字,页面需要先点一下才露出控件时用,如 ["上传本地文件"]'
  414. },
  415. pageFnTimeoutMs: { type: 'number', description: '等页面函数返回的毫秒数,默认 120000(页面可能要传完 S3 才返回)' }
  416. }),
  417. output: jsonOut,
  418. timeoutMs: 300_000,
  419. async execute (args) {
  420. const file = String(args.path || '').trim()
  421. if (!file) fail('缺少 path', '给出技能工作区里那份文件的绝对路径')
  422. const info = bridgeInfo()
  423. if (!info) {
  424. fail('页面执行通道还没就绪', '让老师重启客户端后再试')
  425. }
  426. let data = null
  427. try {
  428. const res = await fetch(`http://127.0.0.1:${info.port}/page/dropFile`, {
  429. method: 'POST',
  430. headers: {
  431. 'content-type': 'application/json',
  432. authorization: `Bearer ${info.token}`
  433. },
  434. body: JSON.stringify({
  435. path: file,
  436. name: String(args.name || ''),
  437. urlMatch: String(args.urlMatch || ''),
  438. clickText: Array.isArray(args.clickText) ? args.clickText.map(String) : [],
  439. pageFn: String(args.pageFn || ''),
  440. pageFnArgs: String(args.pageFnArgs || '') === 'array' ? 'array' : 'single',
  441. pageFnTimeoutMs: Number(args.pageFnTimeoutMs) || 0
  442. })
  443. })
  444. data = await res.json()
  445. } catch (err) {
  446. fail('页面执行通道连不上', `客户端可能已退出或换了通道端口:${err.message}`)
  447. }
  448. if (!data || data.ok !== true) {
  449. const reason = String((data && data.error) || 'unknown')
  450. if (reason === 'no-guest') {
  451. fail('右侧还没有打开平台页面', '先用 cocorobo_open_page 打开对应页面,再投递文件')
  452. }
  453. if (reason === 'path-not-allowed') {
  454. fail('文件不在技能工作区里', '通道只读应用数据目录,先把文件复制进工作区再投递')
  455. }
  456. if (reason === 'too-large') {
  457. fail('文件太大', `上限 512MB,收到 ${data && data.size ? Math.round(data.size / 1048576) + 'MB' : '未知大小'}`)
  458. }
  459. if (reason === 'file-missing') {
  460. fail('文件不存在', `检查路径:${file}`)
  461. }
  462. if (reason === 'no-fn') {
  463. fail(
  464. '页面里没有这个函数',
  465. `${data.fn || args.pageFn} 不存在。确认页面已挂到 window(层级、拼写),或直接不传 pageFn 走上传控件`
  466. )
  467. }
  468. if (reason === 'fn-threw' || reason === 'fn-timeout') {
  469. fail(
  470. reason === 'fn-timeout' ? '页面函数没有按时返回' : '页面函数执行报错',
  471. String((data && data.hint) || (data && data.message) || '文件已经交到页面手里,问题在页面内部;不要重复投递')
  472. )
  473. }
  474. if (reason === 'no-target') {
  475. fail(
  476. '页面上没找到上传控件',
  477. '确认建课弹窗已经停在「上传本地文件」那一步;必要时用 clickText 指一下入口按钮,或传 pageFn 直接调页面函数'
  478. )
  479. }
  480. fail(`投递失败:${reason}`, String((data && data.hint) || ''))
  481. }
  482. return {
  483. ok: true,
  484. url: data.url || '',
  485. name: data.name || '',
  486. via: data.via || 'change',
  487. fn: data.fn || '',
  488. value: data.value,
  489. size: data.size || 0,
  490. message: data.via === 'fn'
  491. ? '文件已经交给页面函数,返回值见 value;页面处理完再用 cocorobo_page_eval 回读核对'
  492. : '文件已经投进页面,等页面解析完再用 cocorobo_page_eval 回读核对(看页数,不看返回值)'
  493. }
  494. }
  495. })
  496. // ====================================== 右侧页面的开发者工具
  497. // 老师排查"右边点了没反应"要看控制台。右侧栏是 Electron <webview>,外壳菜单里的
  498. // 开发者工具只作用于工作台自己,够不到它;以前模型只能说"我没有这个接口"。
  499. // 客户端补了一条 127.0.0.1 的路由(electron/page-bridge.js 的 /page/devtools),
  500. // 这里只是入口 —— 和 page_eval 共用同一份凭据与"只认平台页面"的挑选规则。
  501. ctx.tools.register({
  502. name: 'cocorobo_page_devtools',
  503. description:
  504. '打开或关闭客户端右侧内嵌浏览器的开发者工具(DevTools / F12 面板),默认弹成独立窗口。' +
  505. '老师说「打开右侧调试工具」「打开 F12」「开开发者工具」「看看右边页面的控制台/报错」时用它。' +
  506. '只对右侧已经打开的可可乐博平台页面生效;右侧没开页面时返回 no-guest,先用 cocorobo_open_page 打开。' +
  507. '不要用 cocorobo_page_eval 去模拟,也不要说"没有这个接口"。',
  508. parameters: params({
  509. action: {
  510. type: 'string',
  511. enum: ['open', 'close', 'toggle'],
  512. description: 'open(默认,已开则不重复开)/ close / toggle'
  513. },
  514. urlMatch: { type: 'string', description: '按地址挑页面,如 cloud.cocorobo.cn;不填就用当前可见的平台页面' }
  515. }),
  516. output: jsonOut,
  517. timeoutMs: 15_000,
  518. async execute (args) {
  519. const info = bridgeInfo()
  520. if (!info) {
  521. fail('页面执行通道还没就绪', '让老师重启客户端后再试')
  522. }
  523. let data = null
  524. try {
  525. const res = await fetch(`http://127.0.0.1:${info.port}/page/devtools`, {
  526. method: 'POST',
  527. headers: {
  528. 'content-type': 'application/json',
  529. authorization: `Bearer ${info.token}`
  530. },
  531. body: JSON.stringify({
  532. action: String(args.action || 'open').trim().toLowerCase(),
  533. urlMatch: String(args.urlMatch || '').trim()
  534. })
  535. })
  536. data = await res.json()
  537. } catch (err) {
  538. fail('页面执行通道连不上', `客户端可能已退出或换了通道端口:${err.message}`)
  539. }
  540. if (!data || data.ok !== true) {
  541. const reason = String((data && data.error) || 'unknown')
  542. if (reason === 'no-guest') {
  543. fail('右侧还没有打开平台页面', '先用 cocorobo_open_page 打开对应页面,再开调试工具')
  544. }
  545. fail(`调试工具没开起来:${reason}`, (data && data.hint) || '让老师确认右侧页面还在,再试一次')
  546. }
  547. return {
  548. ok: true,
  549. url: data.url || '',
  550. opened: data.opened === true,
  551. action: data.action || 'open',
  552. message: data.message || (data.opened ? '调试工具已打开(独立窗口)' : '调试工具已关闭')
  553. }
  554. }
  555. })
  556. // ====================================== 右侧页面的刷新 / 清缓存
  557. // "服务端更新了,客户端里还是旧页面"这条反馈反复出现。原因有两层:
  558. // 1. 右栏页签打开后一直活着,点同一个入口只把页签顶到前面,不会重新请求;
  559. // 2. 平台不少响应没带 Cache-Control,Chromium 会按"最近改动时间的 10%"启发式缓存,
  560. // 页面能旧几个小时;js/css 是固定文件名,同样是旧文件。
  561. // 客户端已经在请求/响应头上做了协商缓存(electron/cache-policy.js),这里再给
  562. // 模型一个显式出口:普通刷新 / 硬刷新(等于 Chrome 的 Ctrl+Shift+R)。
  563. ctx.tools.register({
  564. name: 'cocorobo_page_reload',
  565. description:
  566. '刷新客户端右侧内嵌浏览器里的页面,可选硬刷新(清 HTTP 缓存 + 该站点的 Service Worker)。' +
  567. '老师说「刷新一下右边」「页面还是旧的」「服务器更新了没同步」「强制刷新」「清一下缓存再打开」时用它。' +
  568. 'hard=true 等于在 Chrome 里按 Ctrl+Shift+R,服务端发新版后一定拿得到新文件;' +
  569. '只是页面卡住、想重新加载时用 hard=false。' +
  570. '只对右侧已经打开的可可乐博平台页面生效;返回 no-guest 时先用 cocorobo_open_page 打开。',
  571. parameters: params({
  572. hard: {
  573. type: 'boolean',
  574. description: 'true=硬刷新(清缓存和 Service Worker,版本更新后用);false=普通刷新(默认)'
  575. },
  576. urlMatch: { type: 'string', description: '按地址挑页面,如 ppt.cocorobo.cn;不填就用当前可见的平台页面' }
  577. }),
  578. output: jsonOut,
  579. timeoutMs: 30_000,
  580. async execute (args) {
  581. const info = bridgeInfo()
  582. if (!info) {
  583. fail('页面执行通道还没就绪', '让老师重启客户端后再试')
  584. }
  585. const hard = args.hard === true || String(args.hard).toLowerCase() === 'true'
  586. let data = null
  587. try {
  588. const res = await fetch(`http://127.0.0.1:${info.port}/page/reload`, {
  589. method: 'POST',
  590. headers: {
  591. 'content-type': 'application/json',
  592. authorization: `Bearer ${info.token}`
  593. },
  594. body: JSON.stringify({
  595. hard,
  596. urlMatch: String(args.urlMatch || '').trim()
  597. })
  598. })
  599. data = await res.json()
  600. } catch (err) {
  601. fail('页面执行通道连不上', `客户端可能已退出或换了通道端口:${err.message}`)
  602. }
  603. if (!data || data.ok !== true) {
  604. const reason = String((data && data.error) || 'unknown')
  605. if (reason === 'no-guest') {
  606. fail('右侧还没有打开平台页面', '先用 cocorobo_open_page 打开对应页面,再刷新')
  607. }
  608. fail(`刷新失败:${reason}`, (data && data.hint) || '让老师确认右侧页面还在,再试一次')
  609. }
  610. return {
  611. ok: true,
  612. url: data.url || '',
  613. hard: data.hard === true,
  614. message: data.message || (hard ? '已硬刷新(清缓存后重新加载)' : '已刷新')
  615. }
  616. }
  617. })
  618. // ======================================== 通用接口调用(技能作者不用写函数)
  619. // 为什么要有这把工具:业务接口由各模块组自己加,每加一个就让客户端发一版是不现实的。
  620. // 有了它,新增接口 = 改 SKILL.md 里一行 {target, method, path},插件与客户端都不用动。
  621. //
  622. // 边界(有意收窄,别当成"任意 HTTP 代理"):
  623. // · 只能打两个后端:platform(config.apiBase + /agent/v1)、cocoflow(config.cocoflowApiBase)
  624. // · 不接受自定义 header / 任意 URL,凭据一律由客户端注入,技能拿不到 key
  625. // · 写操作(非 GET)必须 confirmed=true,避免技能自作主张改老师账号里的数据
  626. const API_TARGETS = {
  627. platform: {
  628. label: '教学平台',
  629. base: () => `${apiBase}${API_PREFIX}`,
  630. // 平台认 apiKey;x-user-id / x-org-id 是给人看的定位信息,缺了不影响鉴权
  631. auth: async () => {
  632. const me = await user.resolve()
  633. const tk = me.apiKey || token()
  634. if (!tk) fail('还没有登录账号', '请在客户端里完成登录后重试')
  635. return {
  636. authorization: `Bearer ${tk}`,
  637. ...(me.userid ? { 'x-user-id': me.userid } : {}),
  638. ...(me.organizeId ? { 'x-org-id': me.organizeId } : {}),
  639. ...(me.schoolName ? { 'x-school-name': encodeURIComponent(me.schoolName) } : {})
  640. }
  641. }
  642. },
  643. cocoflow: {
  644. label: 'cocoflow',
  645. base: () => cocoflow.apiBase,
  646. // appapi 与主站同一套登录态:cookie 或 Bearer 有一份就能读
  647. auth: async () => {
  648. const tk = cocoflow.token || token()
  649. return {
  650. ...(tk ? { authorization: `Bearer ${tk}` } : {}),
  651. ...(cocoflow.cookie ? { cookie: cocoflow.cookie } : {})
  652. }
  653. }
  654. },
  655. appstore: {
  656. label: '应用中心',
  657. base: () => appStoreBase,
  658. // /api/pbl/* 认平台 apiKey(Bearer)。实测 cookie、Bearer、甚至不带凭据
  659. // 都能读分类这类公共数据,但写操作(发布)必须带上真身份,所以统一按平台
  660. // 那把 key 走,和 platform 一致。
  661. auth: async () => {
  662. const me = await user.resolve()
  663. const tk = me.apiKey || token()
  664. if (!tk) fail('还没有登录账号', '请在客户端里完成登录后重试')
  665. return {
  666. authorization: `Bearer ${tk}`,
  667. ...(me.userid ? { 'x-user-id': me.userid } : {}),
  668. ...(me.organizeId ? { 'x-org-id': me.organizeId } : {})
  669. }
  670. }
  671. }
  672. }
  673. async function callBackend (args, exec) {
  674. const targetKey = String(args.target || '').trim()
  675. const target = API_TARGETS[targetKey]
  676. if (!target) fail(`不支持的 target:${targetKey || '空'}`, '只能是 platform、cocoflow 或 appstore')
  677. const method = String(args.method || 'GET').toUpperCase()
  678. if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
  679. fail(`不支持的 method:${method}`, '只能是 GET / POST / PUT / PATCH / DELETE')
  680. }
  681. if (method !== 'GET' && args.confirmed !== true) {
  682. fail(
  683. `${method} 会改动老师账号里的数据,需要老师明确同意`,
  684. '先把要做什么、影响什么讲给老师听,老师回复"可以/确认"后再带 confirmed: true 调用'
  685. )
  686. }
  687. const pathname = String(args.path || '').trim()
  688. if (!pathname.startsWith('/')) fail('path 必须以 / 开头', '例如 /courseware 或 /api/agents/agent')
  689. if (pathname.includes('://')) fail('path 只能写路径,不能写完整网址', '域名由 target 决定,不能自己指定')
  690. if (pathname.includes('?')) fail('path 里不要带查询串', '把参数放进 query 字段,客户端会拼好')
  691. if (pathname.split('/').includes('..')) fail('path 里不能有 ..', '只写真实的接口路径')
  692. let url
  693. try {
  694. url = new URL(target.base() + pathname)
  695. } catch {
  696. fail('拼出来的接口地址不合法', `target=${targetKey} path=${pathname}`)
  697. }
  698. const query = args.query && typeof args.query === 'object' ? args.query : {}
  699. for (const [k, v] of Object.entries(query)) {
  700. if (v === undefined || v === null || v === '') continue
  701. if (Array.isArray(v)) v.forEach((item) => url.searchParams.append(k, String(item)))
  702. else url.searchParams.set(k, String(v))
  703. }
  704. let payload
  705. if (method !== 'GET' && args.body !== undefined && args.body !== null) {
  706. payload = JSON.stringify(args.body)
  707. // 图片 base64 之类很容易把对话撑爆,超过就明确拒绝而不是静默截断
  708. if (payload.length > 6 * 1024 * 1024) {
  709. fail('请求体超过 6MB', '不要用这把工具传大文件;文件请走课件/资源上传那条链路')
  710. }
  711. }
  712. const headers = { 'content-type': 'application/json', ...(await target.auth()) }
  713. const startedAt = Date.now()
  714. console.log(`[api] → ${method} ${targetKey} ${pathname}`)
  715. const ac = new AbortController()
  716. const timer = setTimeout(() => ac.abort(), 30_000)
  717. if (exec && exec.signal) {
  718. if (exec.signal.aborted) ac.abort()
  719. else exec.signal.addEventListener('abort', () => ac.abort(), { once: true })
  720. }
  721. let res, text
  722. try {
  723. res = await fetch(url.toString(), { method, headers, body: payload, signal: ac.signal })
  724. text = await res.text()
  725. console.log(`[api] ← ${method} ${targetKey} ${pathname} ${res.status} ${Date.now() - startedAt}ms`)
  726. } catch (err) {
  727. const aborted = err && (err.name === 'AbortError' || err.name === 'TimeoutError')
  728. fail(
  729. aborted ? `${target.label}接口超时(30s)` : `连不上${target.label}接口 ${pathname}`,
  730. aborted ? '接口可能在做耗时任务;能异步的话改成先提交再查状态' : `${err.message};请检查网络`
  731. )
  732. } finally {
  733. clearTimeout(timer)
  734. }
  735. let json = null
  736. try { json = text ? JSON.parse(text) : null } catch { /* 可能不是 JSON */ }
  737. if (res.status === 401 || res.status === 403) {
  738. fail('登录已过期或没有权限', '让老师退出后重新登录一次再试;不要重试同一把凭据')
  739. }
  740. const payloadOut = json === null ? String(text || '').slice(0, 200_000) : json
  741. // 平台对不存在的路径不返回 404,而是回 200 + SPA 兜底网页(实测)。不识别的话,
  742. // 技能会把一整页 HTML 当成接口数据,最后对老师编出一个"查到了"的结论。
  743. const ctype = String(res.headers.get('content-type') || '')
  744. const htmlFallback = json === null && (ctype.includes('text/html') || /^\s*<!DOCTYPE html/i.test(String(text || '')))
  745. if (htmlFallback) {
  746. console.log(`[api] ⚠ ${targetKey} ${pathname} 返回网页而不是 JSON(路径错了或后端未部署)`)
  747. return {
  748. ok: false,
  749. status: res.status,
  750. ms: Date.now() - startedAt,
  751. target: targetKey,
  752. method,
  753. path: pathname,
  754. code: 'html-fallback',
  755. error: '接口返回的是网页,不是 JSON:这个路径不存在,或后端还没部署',
  756. hint: '不要把这页 HTML 当数据用,也不要告诉老师"查到了"。核对 path 是否与接口文档一致,或改走 cocorobo_page_eval'
  757. }
  758. }
  759. return {
  760. ok: res.ok,
  761. status: res.status,
  762. ms: Date.now() - startedAt,
  763. target: targetKey,
  764. method,
  765. path: pathname,
  766. ...(res.ok
  767. ? { data: payloadOut }
  768. : { error: payloadOut, hint: '接口返回了非 2xx:先把 status 与 error 里的 message 讲清楚,不要自己编数据' }),
  769. ...(json === null ? { raw: true } : {})
  770. }
  771. }
  772. ctx.tools.register({
  773. name: 'cocorobo_api',
  774. description:
  775. '调用可可乐博平台接口(通用通道)。各模块组新增业务接口时,**不需要客户端加工具**:' +
  776. '在 SKILL.md 里写好 target / method / path / query / body 即可,凭据由客户端注入。' +
  777. 'target=cocoflow 打 appapi(智能体、知识库等),target=platform 打教学平台 /agent/v1(课件、题库等),' +
  778. 'target=appstore 打应用中心 /api/pbl(智能体发布、应用分类、应用详情)。' +
  779. '只能打这三个后端,不能填任意网址、不能自定义 header、不能上传大文件。' +
  780. 'GET 直接调;POST/PUT/PATCH/DELETE 属于写操作,必须老师明确同意后带 confirmed=true。',
  781. parameters: params({
  782. target: {
  783. type: 'string',
  784. enum: ['platform', 'cocoflow', 'appstore'],
  785. required: true,
  786. description: 'platform=教学平台(/agent/v1),cocoflow=appapi 智能体平台,appstore=应用中心(/api/pbl)'
  787. },
  788. method: {
  789. type: 'string',
  790. enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  791. description: 'HTTP 方法,默认 GET'
  792. },
  793. path: {
  794. type: 'string',
  795. required: true,
  796. description: '以 / 开头的接口路径,例如 /api/agents/agent(不要带域名,不要带 ? 查询串)'
  797. },
  798. query: { type: 'object', description: '查询参数对象;数组会展开成重复参数' },
  799. body: { type: 'object', description: 'JSON 请求体(POST/PUT/PATCH 用),上限 6MB' },
  800. confirmed: {
  801. type: 'boolean',
  802. description: '写操作必填:仅当老师明确同意后才为 true;GET 不需要'
  803. }
  804. }),
  805. output: jsonOut,
  806. timeoutMs: 40_000,
  807. async execute (args, exec) {
  808. return callBackend(args, exec)
  809. }
  810. })
  811. // ============================================== 工作流:方案 → 可导入的 JSON
  812. // 原来靠技能里的 build_workflow.py,但老师电脑没有 Python(Windows 基本都没有),
  813. // 这条命令会直接失败。编译器是纯 JSON 变换,放进客户端就没有外部依赖了。
  814. ctx.tools.register({
  815. name: 'cocorobo_workflow_build',
  816. description:
  817. '把 CocoFlow 工作流方案(plan)编译成可直接导入的工作流 JSON 文件。' +
  818. '只做本地校验和格式转换,不联网、不碰老师账号里的数据。' +
  819. '方案不合法时会把具体原因返回,按提示改完再调一次即可。',
  820. parameters: params({
  821. plan: {
  822. type: 'object',
  823. required: true,
  824. description: '工作流方案:schemaVersion:1、name、model,以及 steps 或 routes(二选一),可选 description/opening/form'
  825. },
  826. outputPath: {
  827. type: 'string',
  828. required: true,
  829. description: '输出文件的绝对路径。文件必须不存在(不覆盖已有文件),建议放在老师的桌面或文档目录'
  830. }
  831. }),
  832. output: jsonOut,
  833. timeoutMs: 20_000,
  834. async execute (args) {
  835. try {
  836. const result = buildWorkflowFile(args.plan, args.outputPath)
  837. const nodes = result.workflow.content.nodes
  838. const steps = nodes.filter((n) => n.type === 'UserTask')
  839. return {
  840. ok: true,
  841. path: result.path,
  842. bytes: result.bytes,
  843. nodes: nodes.length,
  844. edges: result.workflow.content.edges.length,
  845. // 给模型做汇报用:节点顺序 + 每个智能体的名字,避免它凭空描述
  846. steps: steps.map((n) => n.properties.item.assistantName),
  847. hasForm: nodes.some((n) => n.type === 'form_card'),
  848. hasBranch: nodes.some((n) => n.type === 'boss_card')
  849. }
  850. } catch (err) {
  851. if (err instanceof WorkflowError) {
  852. fail(`方案没通过校验:${err.message}`, '按上面这条改方案,改完再调一次;不要自己拼 JSON 文件')
  853. }
  854. if (err instanceof WorkflowIOError) {
  855. fail(err.message, '换一个输出路径再试;不要删老师已有的文件')
  856. }
  857. throw err
  858. }
  859. }
  860. })
  861. // ================================================ 图片处理(doubao seedream)
  862. // 老师要"画一张图/给课件配图/把这张图改成…"时,模型需要真的能出图,
  863. // 否则只会回"我没有画图的能力"。平台网关(onehub)是 openai 兼容的
  864. // /images/generations,key 与业务 apiKey 同一把。
  865. //
  866. // 模型策略:优先 seedream 5.0 flash,平台分组没开这个渠道时网关回 503,
  867. // 就立刻退回已开通的 3.0(实测唯一稳定可用的),并在结果里如实标注。
  868. // 这样平台哪天补开 5.0,客户端不用改代码就自动切过去。
  869. const IMAGE_MODEL_PREFERRED = String(config.imageModel || 'doubao-seedream-5-0-flash-260915').trim()
  870. const IMAGE_MODEL_READY = String(config.imageModelReady || 'doubao-seedream-3-0-t2i-250415').trim()
  871. // 记住"某个模型刚被网关拒过",5 分钟内不再白试一次(否则每张图都要多等一轮)
  872. const imageModelBlocked = new Map()
  873. const IMAGE_BLOCK_TTL = 5 * 60_000
  874. const imageModelUsable = (model) => {
  875. const at = imageModelBlocked.get(model)
  876. return !at || Date.now() - at > IMAGE_BLOCK_TTL
  877. }
  878. /** 按文件头判定真实格式:接口回的常是 JPEG,扩展名必须跟着字节走 */
  879. const imageExtOf = (buf) => {
  880. if (buf.length > 4 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return '.png'
  881. if (buf.length > 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return '.jpg'
  882. if (buf.length > 12 && buf.slice(8, 12).toString('ascii') === 'WEBP') return '.webp'
  883. return '.png'
  884. }
  885. ctx.tools.register({
  886. name: 'cocorobo_image_generate',
  887. description:
  888. '生成图片——老师要的任何一张图都必须走这里,不要用写 HTML 截屏、PowerShell/System.Drawing 或 Python 自己画。' +
  889. '只给 prompt 是文生图;同时给 image 是图生图(按参考图改风格/改背景/换配色/做成海报,保留原构图与原图里的数字文字)。' +
  890. '老师说"画一张…/生成一张配图/给这节课配个插图/做个封面/做成战报图"时调用;' +
  891. '老师说"改这张图/换成水彩风/去掉背景/把字改成…/按这张截图做一张夸张的"时,把那张图的本地路径放进 image 再调用。' +
  892. '返回本地文件路径,可以交给后续的课件步骤或告诉老师在哪儿看。',
  893. parameters: params({
  894. prompt: { type: 'string', required: true, description: '画面描述,越具体越好:主体、场景、风格、文字标注、画面比例' },
  895. image: { type: 'string', description: '参考图:本地文件路径或 http(s) 链接。传了就是图生图,保持构图只改 prompt 里说的部分;不传就是文生图' },
  896. size: { type: 'string', description: '输出尺寸,格式 宽x高:方图 1024x1024,横图 1536x1024,竖图 1024x1536' },
  897. model: { type: 'string', description: '一般不用填;平台未开通首选模型时会自动换用可用模型' },
  898. savePath: { type: 'string', description: '保存路径;不填自动存到工作区 images/ 下' }
  899. }),
  900. output: jsonOut,
  901. // 图像模型排队 + 出图通常 20~60 秒,给足时间,避免模型以为失败了重复调用
  902. timeoutMs: 240_000,
  903. async execute (args, exec) {
  904. void exec
  905. const prompt = String(args.prompt || '').trim()
  906. if (!prompt) fail('缺少画面描述', '把老师要的画面写成一句话放进 prompt,例如「三年级科学:水循环示意图,扁平插画」')
  907. let requested = String(args.model || '').trim() || IMAGE_MODEL_PREFERRED
  908. // 只放行图像模型:模型偶尔会把手边的文本模型填进来,那种请求必然 400
  909. if (!/image|seedream|flux|dall-?e|t2i|wanx?/i.test(requested)) {
  910. fail(`“${requested}”不是图像模型`, '图片处理不需要传文本模型,去掉 model 参数即可')
  911. }
  912. // 网关侧已开启「请求体完整透传」(DoneHub 的 pass_through_body),image 会原样到上游。
  913. // 只有显式配了 imageReference:false 的老环境才拒绝,避免又把"改图"答成"重画"。
  914. if (String(args.image || '').trim() && config.imageReference === false) {
  915. fail(
  916. '当前出图通道没有开启参考图透传,改不了已有图片',
  917. '只能按文字描述重新画一张;不要声称会保留原图细节'
  918. )
  919. }
  920. // seedream 3.0 只吃「宽x高」,2K/4K 这类关键字留给以后开通的版本,先归一化
  921. const wantSize = String(args.size || '').trim()
  922. const size = /^\d{2,4}x\d{2,4}$/.test(wantSize) ? wantSize : '1024x1024'
  923. // 参考图:本地文件转 data URL,http(s) 原样传(两种都实测透传成功)
  924. let imageRef = String(args.image || '').trim()
  925. if (imageRef && !/^https?:\/\//i.test(imageRef)) {
  926. const refPath = path.resolve(imageRef)
  927. let stat
  928. try { stat = fs.statSync(refPath) } catch { fail('参考图不存在', `读不到 ${refPath}`) }
  929. if (!stat.isFile()) fail('参考图不是文件', refPath)
  930. if (stat.size > 10 * 1048576) fail('参考图太大', `${(stat.size / 1048576).toFixed(1)}MB,请压缩到 10MB 以内`)
  931. const ext = path.extname(refPath).toLowerCase().replace('.', '') || 'png'
  932. const mime = ext === 'jpg' ? 'jpeg' : ext
  933. imageRef = `data:image/${mime};base64,${fs.readFileSync(refPath).toString('base64')}`
  934. }
  935. if (isMock()) {
  936. return {
  937. ok: true,
  938. mock: true,
  939. model: requested,
  940. prompt,
  941. message: '当前是演示模式,没有真的出图;接入平台账号后会返回图片文件'
  942. }
  943. }
  944. // 演示模式不碰网络;真出图才要求网关地址(老版本 patch 没写这一项)
  945. if (!imageBase) fail('缺少模型网关地址', '客户端启动时没有写入 llmBaseURL,请重启客户端;仍然失败请反馈')
  946. const me = await user.resolve()
  947. // 网关 key 优先:服务端单独下发的那把才可能带图像渠道。
  948. const key = readAuth().llmKey || me.apiKey || token()
  949. if (!key) fail('还没有登录账号', '请先在客户端完成登录')
  950. // 参考图要求模型本身吃图像输入:t2i(text-to-image)型号会静默忽略 image,
  951. // 出图跟参考图毫无关系却不报错,是最坏的情况,所以带参考图时直接把它换掉。
  952. const canUseReference = (m) => !/t2i/i.test(m)
  953. if (imageRef && !canUseReference(requested)) requested = IMAGE_MODEL_PREFERRED
  954. // 候选链:老师/调用方指定的 → 首选 → 已开通的兜底,去重后按顺序试
  955. const chain = [...new Set([requested, IMAGE_MODEL_PREFERRED, IMAGE_MODEL_READY])].filter(Boolean)
  956. const usable = chain.filter(imageModelUsable)
  957. const attempts = (usable.length ? usable : [IMAGE_MODEL_READY])
  958. .filter((m) => !imageRef || canUseReference(m))
  959. if (!attempts.length) {
  960. fail('没有可用于图生图的模型', '当前只开通了纯文生图(t2i)模型,需要平台开通支持参考图的 seedream 4.0+ 或 seededit i2i')
  961. }
  962. let lastError = ''
  963. for (const model of attempts) {
  964. const body = { model, prompt, n: 1, size, response_format: 'b64_json' }
  965. if (imageRef) body.image = imageRef
  966. let res
  967. try {
  968. res = await fetch(`${imageBase}/images/generations`, {
  969. method: 'POST',
  970. headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
  971. body: JSON.stringify(body)
  972. })
  973. } catch (err) {
  974. fail('连不上模型网关', `${err.message};请检查网络后重试`)
  975. }
  976. const text = await res.text()
  977. let json = null
  978. try { json = text ? JSON.parse(text) : null } catch { /* 网关偶发返回 html */ }
  979. if (!res.ok) {
  980. const detail = (json && json.error && (json.error.message || json.error.code)) || text.slice(0, 200)
  981. // 503=分组没有可用上游、404=没这个模型:都说明该模型现在用不了,换下一个
  982. if (res.status === 503 || res.status === 404) {
  983. imageModelBlocked.set(model, Date.now())
  984. lastError = `${model}:${detail}`
  985. continue
  986. }
  987. // 内容审核:换描述重试才有效,重试同一条只会再被拦一次
  988. if (/Sensitive|sensitive/i.test(text)) {
  989. fail('这个画面被内容审核拦下了', '换一种说法:去掉"解剖""人体"这类词,改成具体的教学场景描述再试')
  990. }
  991. fail(`图像接口返回 ${res.status}`, String(detail).slice(0, 200))
  992. }
  993. const list = json && (json.data || json.images || json.output)
  994. const first = Array.isArray(list) ? list[0] : list
  995. const url = first && (first.url || first.image_url || (typeof first === 'string' ? first : ''))
  996. const b64 = first && (first.b64_json || first.b64)
  997. if (!url && !b64) fail('图像接口没有返回图片', `返回内容:${text.slice(0, 200)}`)
  998. // 先把字节拿到手:seedream 回的是 JPEG,文件名写 .png 会让一些软件打不开
  999. let data = null
  1000. if (b64) {
  1001. data = Buffer.from(b64, 'base64')
  1002. } else {
  1003. const imgRes = await fetch(url)
  1004. if (!imgRes.ok) fail(`下载生成的图片失败(${imgRes.status})`, '生成成功了但没能存到本地,请重试一次')
  1005. data = Buffer.from(await imgRes.arrayBuffer())
  1006. }
  1007. if (!data || !data.length) fail('生成的图片是空文件', '请重试一次;连续失败请反馈')
  1008. // 落盘:网关给的 url 有有效期,老师过几天再点就看不到了
  1009. const target = String(args.savePath || '').trim()
  1010. ? path.resolve(String(args.savePath).trim())
  1011. : path.join(workspaceDir || '.', 'images', `image-${Date.now()}${imageExtOf(data)}`)
  1012. fs.mkdirSync(path.dirname(target), { recursive: true })
  1013. fs.writeFileSync(target, data)
  1014. const bytes = fs.statSync(target).size
  1015. if (!bytes) fail('生成的图片是空文件', '请重试一次;连续失败请反馈')
  1016. return {
  1017. ok: true,
  1018. model,
  1019. requestedModel: requested,
  1020. fallback: model !== requested,
  1021. file: target,
  1022. size,
  1023. bytes,
  1024. prompt,
  1025. // true = 这张是按参考图改的;老师问"跟原来像不像"时据此回答
  1026. usedReference: Boolean(imageRef),
  1027. // 平台出图强制带右下角「AI生成」标识,watermark:false 实测无效,别向老师承诺能去掉
  1028. watermarked: true,
  1029. message: `图片已生成:${target}。告诉老师"图好了,存在这个位置"即可;右下角带平台的 AI 生成标识,不要说模型名或接口细节`
  1030. }
  1031. }
  1032. fail('图像服务当前不可用', `${lastError || '网关没有可用的图像模型'}。请平台侧确认 seedream 图像渠道已开通`)
  1033. }
  1034. })
  1035. // ===================================================== cococlass:建课件
  1036. ctx.tools.register({
  1037. name: 'cococlass_courseware_create',
  1038. description:
  1039. '在 cococlass 里创建一份课件(备课/一节课/课件/讲义)。' +
  1040. '老师说"帮我做一节课/把这节课备了/生成课件"时调用。' +
  1041. '工具自己会等生成结果:返回 done 时客户端右侧已经打开课件页面,跟老师说一声就好;' +
  1042. '返回 running 时右侧打开的是进度页,告诉老师还在生成,不要连续调用本工具。',
  1043. parameters: params({
  1044. title: { type: 'string', required: true, description: '课件标题,例如"认识三角形"' },
  1045. subject: { type: 'string', description: '学科,例如 数学 / 物理 / 语文' },
  1046. grade: { type: 'string', description: '学段年级,例如 三年级 / 八年级' },
  1047. duration: { type: 'number', description: '课时长度(分钟),默认 40' },
  1048. requirements: { type: 'string', description: '老师的额外要求,例如"多举生活例子,结尾带课堂练习"' },
  1049. outline: {
  1050. type: 'array',
  1051. items: { type: 'string' },
  1052. description: '已和老师确认过的页面大纲;有就传,避免模型重新发挥'
  1053. }
  1054. }),
  1055. output: jsonOut,
  1056. timeoutMs: 120_000,
  1057. async execute (args, exec) {
  1058. if (!args.title) fail('缺少课件标题', '先问老师这节课讲什么')
  1059. const payload = {
  1060. title: String(args.title).trim(),
  1061. subject: args.subject || '',
  1062. grade: args.grade || '',
  1063. duration: Number(args.duration) || 40,
  1064. requirements: args.requirements || '',
  1065. outline: Array.isArray(args.outline) ? args.outline : [],
  1066. source: 'cocorobo-workspace'
  1067. }
  1068. if (isMock()) {
  1069. const created = mockCreateTask('courseware', payload)
  1070. const final = await waitTask(created.taskId, { timeoutMs: 20_000, signal: exec.signal, initial: created })
  1071. return { ok: true, ...final, openUrl: pageUrl('cococlass', final.coursewareId || final.id || '') }
  1072. }
  1073. const created = await api('/cococlass/courseware/drafts', {
  1074. method: 'POST',
  1075. body: JSON.stringify(payload),
  1076. headers: { 'idempotency-key': idempotencyKey('cw') },
  1077. signal: exec.signal
  1078. })
  1079. const taskId = created.taskId || created.id
  1080. if (!taskId) {
  1081. // 同步返回(小课件直接生成完):原样交回给模型,只补一个能直接打开的页面地址
  1082. return { ok: true, status: 'done', ...created, openUrl: pageUrl('cococlass', created.coursewareId || created.id || '') }
  1083. }
  1084. const final = await waitTask(taskId, { timeoutMs: waitMs, signal: exec.signal, initial: created })
  1085. const done = stateOf(final) === 'done'
  1086. const coursewareId = final.coursewareId || final.id || ''
  1087. return {
  1088. ok: true,
  1089. status: done ? 'done' : 'running',
  1090. taskId,
  1091. title: final.title || payload.title,
  1092. coursewareId,
  1093. pageCount: final.pageCount || final.pages || null,
  1094. previewUrl: final.previewUrl || final.resultUrl || '',
  1095. editUrl: final.editUrl || '',
  1096. // 客户端右侧会自动打开这个地址(老师不用再复制链接到浏览器)
  1097. openUrl: pageUrl('cococlass', coursewareId),
  1098. progress: final.progress || null,
  1099. stage: final.stage || '',
  1100. progressUrl: final.previewUrl || `${apiBase}/agent/v1/tasks/${taskId}`,
  1101. message: done
  1102. ? '课件已生成,客户端右侧已打开课件页面;简单说一句"做好了,右边可以看",再问是否要发布到班级'
  1103. : '平台还在生成,客户端右侧已打开进度页;告诉老师可以继续等,不要连续重复调用本工具'
  1104. }
  1105. }
  1106. })
  1107. // ======================================= cococlass:本地 PPTX 直接建课
  1108. // 平台的 PPT 解析完全在前端(ppt.cocorobo.cn 的 importPPTXFile:FileReader
  1109. // 读 ArrayBuffer → JSZip 拆 pptx → 转成 slides JSON → 图片传 S3 → 保存)。
  1110. // 这条链路没有对外接口,解析函数也没挂到 window 上,唯一入口是页面里的
  1111. // 上传控件(`.file-input` + `input[name=upload][accept=".pptx,.ppt,.pdf"]`)。
  1112. // 所以这里不重写解析,只把文件交给页面:工具结果带 uploadFile,
  1113. // 客户端右侧打开编辑器后构造 File 走该控件的 drop / change,
  1114. // 等于老师手选文件,后面全由平台自己的代码跑完。
  1115. ctx.tools.register({
  1116. name: 'cococlass_course_from_pptx',
  1117. description:
  1118. '把本地已生成的 PPTX 交给 cococlass 平台解析成课程。' +
  1119. '老师说"把这份 PPT 建成课程/传到 cococlass"且文件已存在时调用;' +
  1120. '还没有文件就先用 PPT 生成技能把 .pptx 做出来。' +
  1121. '有课程 id 就传 courseid(导进已有课程),没有就打开建课页新建。' +
  1122. '调用后右侧会自动填文件并开始解析,告诉老师看右侧即可。',
  1123. parameters: params({
  1124. pptxPath: { type: 'string', required: true, description: 'PPTX 文件绝对路径(技能生成后的输出路径)' },
  1125. courseid: { type: 'string', description: '已有课程 id;不传则走新建课程' },
  1126. title: { type: 'string', description: '课程名,仅用于对话说明' }
  1127. }),
  1128. output: jsonOut,
  1129. timeoutMs: 20_000,
  1130. async execute (args, exec) {
  1131. void exec
  1132. const file = String(args.pptxPath || '').trim()
  1133. if (!file) fail('缺少 pptxPath', '先确认 PPT 文件的实际路径')
  1134. if (!/\.pptx$/i.test(file)) fail('只支持 .pptx 文件', `收到的是 ${file};请先用 PPT 技能导出 .pptx`)
  1135. let size = 0
  1136. try {
  1137. size = fs.statSync(file).size
  1138. if (size <= 0) throw new Error('empty')
  1139. } catch {
  1140. fail('PPTX 文件不存在或为空', `路径 ${file} 读不到;确认生成步骤是否真的完成了`)
  1141. }
  1142. const id = await user.resolve({ needKey: false })
  1143. const courseid = String(args.courseid || '').trim()
  1144. const q = new URLSearchParams()
  1145. q.set('mode', 'editor3')
  1146. if (id.userid) q.set('userid', id.userid)
  1147. if (courseid) q.set('courseid', courseid)
  1148. // 有课程 id → 直接进编辑器;没课程 id → 开门户页,让它进教学中心并弹出
  1149. //「创建新课程」(弹窗里的上传控件一渲染就有,文件用 drop 投进去,不点它,
  1150. // 点它会拉起系统文件框)。
  1151. const openUrl = courseid
  1152. ? `${pptBase}/?${q.toString()}`
  1153. : String(config.cococlassUrl || '').trim() || `${portalBase}/`
  1154. return {
  1155. ok: true,
  1156. status: 'uploading',
  1157. title: String(args.title || '').trim(),
  1158. courseid,
  1159. file,
  1160. size,
  1161. openUrl,
  1162. uploadFile: {
  1163. path: file,
  1164. name: file.split(/[\\/]/).pop(),
  1165. clickText: courseid ? [] : ['教学中心', '创建课程', '创建新课程', '新建课程'],
  1166. urlMatch: 'cocorobo'
  1167. },
  1168. message: '已在右侧打开页面并把文件交给平台解析;解析完会自己跳转,不要重复调用本工具'
  1169. }
  1170. }
  1171. })
  1172. // ==================================================== cocoflow:建智能体
  1173. // 真实接口(appapi.cocorobo.cn,浏览器抓包对齐):
  1174. // POST /api/agents/agent 建智能体骨架,返回 id / assistant_id / thread_id
  1175. // PUT /api/agents/agent/{id} 写入提示词等完整配置
  1176. // 创建会在老师账号里留下真智能体,所以拆成两把工具:
  1177. // cocoflow_agent_plan 只出方案,不落库
  1178. // cocoflow_agent_create 必须等老师明确说"创建"才允许调(confirmed 门禁)
  1179. const COCOFLOW_DEFAULT_HEAD_URL =
  1180. 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/default%2F%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F11741770951146.png'
  1181. const COCOFLOW_DEFAULT_JSON_DATA = JSON.stringify({
  1182. voiceInteractionMode: false, syncTranscriptionText: false, autoPlay: false, sttLanguage: 'zh-CN', cyid: ''
  1183. })
  1184. const cocoflow = {
  1185. apiBase: String(config.cocoflowApiBase || 'https://appapi.cocorobo.cn').replace(/\/+$/, ''),
  1186. modelType: String(config.cocoflowModelType || 'open-doubao'),
  1187. headUrl: String(config.cocoflowHeadUrl || COCOFLOW_DEFAULT_HEAD_URL),
  1188. userId: String(config.cocoflowUserId || '').trim(),
  1189. username: String(config.cocoflowUsername || '').trim(),
  1190. organizeId: String(config.cocoflowOrganizeId || '').trim(),
  1191. token: String(config.cocoflowToken || '').trim(),
  1192. cookie: String(config.cocoflowCookie || '').trim(),
  1193. // cocoflow 自己的 mock 开关:没单独配就跟随全局 mock。
  1194. // 想只测 cocoflow 真实接口,把 config.json 里 cocoflowMock 设 false 即可。
  1195. mock: typeof config.cocoflowMock === 'boolean' ? config.cocoflowMock : null
  1196. }
  1197. const cfMock = () => (cocoflow.mock !== null ? cocoflow.mock : isMock())
  1198. /**
  1199. * cocoflow 的身份:**登录授权带回的为准**(authFile 的 userid/username/organizeId,
  1200. * 与 cocorobo://auth/callback 里的 userid/organizeid 同源)。
  1201. * 授权没带 organizeid 时由用户中心按 userid 去平台补全,config 里的
  1202. * cocoflowUserId / cocoflowOrganizeId 只在没登录或 mock 登录时兜底。
  1203. * mock 登录的 mock-teacher 绝不能当成真 userId 传给平台。
  1204. */
  1205. async function cfIdentity () {
  1206. // cocoflow 走 cookie/Bearer,不强制要求 apiKey;这里只关心"人是谁、属于哪个机构"
  1207. const id = await user.resolve({ needKey: false })
  1208. const authorized = !id.mock && !String(id.userid || '').startsWith('mock')
  1209. return {
  1210. userId: (authorized && id.userid) || cocoflow.userId || '',
  1211. username: (authorized && id.username) || cocoflow.username || '老师',
  1212. organizeId: (authorized && id.organizeId) || cocoflow.organizeId || '',
  1213. source: id.source
  1214. }
  1215. }
  1216. /** appapi 没有 /agent/v1 前缀,凭据形态也不同(浏览器抓的是 cookie),单独一个请求函数。 */
  1217. async function cfApi (pathname, init = {}) {
  1218. const headers = { 'content-type': 'application/json', ...(init.headers || {}) }
  1219. const tk = cocoflow.token || token()
  1220. if (tk) headers.authorization = `Bearer ${tk}`
  1221. if (cocoflow.cookie) headers.cookie = cocoflow.cookie
  1222. // 排查用:SKILL.md 里看不到任何接口地址,真正打 appapi 的是这里。
  1223. // 只记方法/路径/状态码,不记 body(body 里有老师的提示词全文)。
  1224. const method = String(init.method || 'GET').toUpperCase()
  1225. const startedAt = Date.now()
  1226. const authUsed = cocoflow.cookie && tk ? 'cookie+bearer' : (cocoflow.cookie ? 'cookie' : (tk ? 'bearer' : '无凭据'))
  1227. console.log(`[cocoflow] → ${method} ${pathname}(鉴权 ${authUsed})`)
  1228. let res
  1229. try {
  1230. res = await fetch(`${cocoflow.apiBase}${pathname}`, { ...init, headers, signal: init.signal })
  1231. console.log(`[cocoflow] ← ${method} ${pathname} ${res.status} ${Date.now() - startedAt}ms`)
  1232. } catch (err) {
  1233. console.log(`[cocoflow] ✗ ${method} ${pathname} ${err && err.message} ${Date.now() - startedAt}ms`)
  1234. if (err && err.name === 'AbortError') throw err
  1235. fail(`连不上 cocoflow 接口 ${pathname}`, `${err.message};请检查网络`)
  1236. }
  1237. const text = await res.text()
  1238. let json = null
  1239. try { json = text ? JSON.parse(text) : null } catch { /* 非 JSON */ }
  1240. if (!res.ok) {
  1241. const msg = json && (json.message || json.msg || json.error)
  1242. fail(`cocoflow 接口 ${pathname} 返回 ${res.status}`, msg || text.slice(0, 200))
  1243. }
  1244. if (json === null) fail(`cocoflow 接口 ${pathname} 返回的不是 JSON`, text.slice(0, 200))
  1245. return json
  1246. }
  1247. /** 从需求里起个默认名,老师不满意会改,所以只求"像个名字"。 */
  1248. function suggestName (args) {
  1249. if (args.name) return String(args.name).trim().slice(0, 20)
  1250. const grade = args.grade || ''
  1251. const subject = args.subject || ''
  1252. if (subject) return `${grade}${subject}助手`.slice(0, 20)
  1253. return '我的智能体'
  1254. }
  1255. /** 提示词初稿:结构化模板比让模型自由发挥稳定,老师后续会改。 */
  1256. function draftInstructions (name, args) {
  1257. const out = []
  1258. out.push('# 角色')
  1259. out.push(`你是「${name}」,服务对象是${args.grade || '中小学'}的${args.subject || ''}学生与老师。`)
  1260. if (args.tone) out.push(`说话风格:${args.tone}。`)
  1261. out.push('', '# 职责')
  1262. out.push(String(args.need || '').trim())
  1263. const steps = Array.isArray(args.steps) ? args.steps.filter(Boolean) : []
  1264. if (steps.length) {
  1265. out.push('', '# 工作流程')
  1266. steps.forEach((s, i) => out.push(`${i + 1}. ${s}`))
  1267. }
  1268. out.push('', '# 输出要求')
  1269. out.push('- 用中文回答,结论清晰、可直接使用。')
  1270. if (args.boundaries) out.push(`- ${args.boundaries}`)
  1271. out.push('- 超出职责范围的问题,礼貌说明并建议向老师求助。')
  1272. return out.join('\n')
  1273. }
  1274. ctx.tools.register({
  1275. name: 'cocoflow_agent_plan',
  1276. description:
  1277. '老师想做一个 cocoflow 智能体时的第一步:把需求整理成「名称 + 简介 + 提示词」方案。' +
  1278. '本工具不创建任何东西、不碰平台接口。' +
  1279. '拿到方案后必须把名称/简介/提示词完整展示给老师,并问"就按这个在 cocoflow 创建吗?"——' +
  1280. '老师明确回复"创建/确认/可以"之前,禁止调用 cocoflow_agent_create。',
  1281. parameters: params({
  1282. need: { type: 'string', required: true, description: '老师的原话需求,例如"想要一个帮学生改作文的助手"' },
  1283. subject: { type: 'string', description: '学科' },
  1284. grade: { type: 'string', description: '学段年级' },
  1285. tone: { type: 'string', description: '说话风格,例如"像耐心的老师,多用提问引导"' },
  1286. steps: { type: 'array', items: { type: 'string' }, description: '做事顺序(3–6 步),老师没说就按学科常识补并列出来让老师过目' },
  1287. boundaries: { type: 'string', description: '边界规则,例如"不要直接给答案,先给提示"' },
  1288. name: { type: 'string', description: '老师已经定好的名字;没定就省略,用工具起的默认名' },
  1289. instructions: { type: 'string', description: '老师自己写好了完整提示词时填这里,原样采用、不再改写' }
  1290. }),
  1291. output: jsonOut,
  1292. timeoutMs: 20_000,
  1293. async execute (args) {
  1294. if (!args.need && !args.instructions) fail('缺少需求描述', '先问老师想要一个什么样的助手')
  1295. const name = suggestName(args)
  1296. const instructions = String(args.instructions || '').trim() || draftInstructions(name, args)
  1297. const description = String(args.need || '').trim().slice(0, 60)
  1298. return {
  1299. plan: { assistantName: name, description, instructions },
  1300. message:
  1301. '这是准备在 cocoflow 创建的方案(还未创建)。把 plan 里的名称/简介/提示词完整展示给老师,' +
  1302. '问"就按这个创建吗?要改哪里直接说"。老师明确同意后,把确认过的 assistantName/description/' +
  1303. 'instructions 原样传给 cocoflow_agent_create 并把 confirmed 设为 true;老师没同意前不要调。'
  1304. }
  1305. }
  1306. })
  1307. ctx.tools.register({
  1308. name: 'cocoflow_agent_create',
  1309. description:
  1310. '在 cocoflow 里真正创建智能体并写入提示词(POST 建骨架 + PUT 写提示词,两步都做完才算成功)。' +
  1311. '硬性规则:必须先用 cocoflow_agent_plan 出方案并给老师确认,老师明确回复"创建/确认/可以"后才能调用;' +
  1312. '老师还在讨论、修改、犹豫时禁止调用。assistantName/description/instructions 要传老师确认过的版本,不要自己改写。' +
  1313. '创建成功后客户端右侧会自动打开智能体页面,不要自己拼链接发给老师。',
  1314. parameters: params({
  1315. assistantName: { type: 'string', required: true, description: '老师确认过的智能体名称' },
  1316. description: { type: 'string', required: true, description: '老师确认过的一句话简介' },
  1317. instructions: { type: 'string', required: true, description: '老师确认过的提示词全文,原样传入' },
  1318. confirmed: {
  1319. type: 'boolean',
  1320. required: true,
  1321. description: '仅当老师在对话里明确同意创建后才能为 true;false 时本工具直接拒绝执行'
  1322. },
  1323. modelType: { type: 'string', description: '模型类型,默认 open-doubao,老师没提就不要传' }
  1324. }),
  1325. output: jsonOut,
  1326. timeoutMs: 60_000,
  1327. async execute (args, exec) {
  1328. // 门禁:宁可多问一句,也不能在老师账号里留下没确认过的智能体
  1329. if (!args.confirmed) {
  1330. fail('老师还没有明确同意创建', '先用 cocoflow_agent_plan 出方案给老师确认,老师回复"创建"后再来')
  1331. }
  1332. const assistantName = String(args.assistantName || '').trim()
  1333. const description = String(args.description || '').trim()
  1334. const instructions = String(args.instructions || '').trim()
  1335. if (!assistantName) fail('缺少智能体名称', '回上一步让老师定个名字')
  1336. if (!instructions) fail('缺少提示词', '回上一步把提示词跟老师确认好')
  1337. if (cfMock()) {
  1338. const agentId = `ag-${Date.now().toString(36)}`
  1339. mockAgents.push({ agentId, assistantName, description, instructions, createdAt: new Date().toISOString() })
  1340. return {
  1341. ok: true,
  1342. status: 'done',
  1343. mock: true,
  1344. agentId,
  1345. name: assistantName,
  1346. openUrl: pageUrl('agent', agentId),
  1347. message: `智能体「${assistantName}」已创建(mock),提示词 ${instructions.length} 字;客户端右侧已打开智能体页面`
  1348. }
  1349. }
  1350. const me = await cfIdentity()
  1351. if (!me.userId) {
  1352. fail('读不到老师账号(userid)',
  1353. '客户端里重新登录一次即可;仍在登录态的话,说明登录回调没有带回 userid,让平台侧确认回调参数')
  1354. }
  1355. if (!me.organizeId) {
  1356. fail('读不到老师所属机构(organizeId)',
  1357. '已按当前 userid 向平台补全过但仍为空:请确认登录回调带上 organizeid,或在 config.json 里配置 cocoflowOrganizeId')
  1358. }
  1359. const modelType = String(args.modelType || cocoflow.modelType)
  1360. // 第一步:建骨架
  1361. const created = await cfApi('/api/agents/agent', {
  1362. method: 'POST',
  1363. body: JSON.stringify({
  1364. userId: me.userId,
  1365. username: me.username,
  1366. assistantName,
  1367. isRetrieval: 0,
  1368. isCode: 0,
  1369. isGoogle: 0,
  1370. isDalleImage: 0,
  1371. organize_id: me.organizeId,
  1372. vector_store_id: '',
  1373. modelType,
  1374. inputMode: 'text',
  1375. outputMode: 'text',
  1376. headUrl: cocoflow.headUrl,
  1377. description,
  1378. jsonData: ''
  1379. }),
  1380. signal: exec.signal
  1381. })
  1382. const agentId = created.id || created.agentId || ''
  1383. if (!agentId) fail('平台没有返回智能体 id', JSON.stringify(created).slice(0, 200))
  1384. // 第二步:写提示词。失败不吞掉 —— 智能体已经建出来,老师必须知道提示词没写进去
  1385. let promptWritten = true
  1386. let promptError = ''
  1387. try {
  1388. await cfApi(`/api/agents/agent/${encodeURIComponent(agentId)}`, {
  1389. method: 'PUT',
  1390. body: JSON.stringify({
  1391. prologue: null,
  1392. description,
  1393. instructions,
  1394. isAutoReply: 0,
  1395. file_ids: '',
  1396. file_names: '',
  1397. folder_ids: '',
  1398. folder_names: '',
  1399. modelType,
  1400. functionNames: '',
  1401. functionContents: '[]',
  1402. tools: [{ type: 'file_search' }],
  1403. inputMode: 'text',
  1404. outputMode: 'text',
  1405. vector_store_id: created.vector_store_id || '',
  1406. assistantName,
  1407. jsonData: cocoflow.jsonData || COCOFLOW_DEFAULT_JSON_DATA
  1408. }),
  1409. signal: exec.signal
  1410. })
  1411. } catch (err) {
  1412. promptWritten = false
  1413. promptError = err.message
  1414. }
  1415. return {
  1416. ok: promptWritten,
  1417. status: 'done',
  1418. agentId,
  1419. assistantId: created.assistant_id || '',
  1420. threadId: created.thread_id || '',
  1421. name: created.assistantName || assistantName,
  1422. // 客户端右侧会自动打开这个地址(智能体详情页)
  1423. openUrl: pageUrl('agent', agentId),
  1424. promptWritten,
  1425. ...(promptWritten ? {} : { promptError }),
  1426. message: promptWritten
  1427. ? `智能体「${assistantName}」已创建,提示词已写入,客户端右侧已打开。告诉老师知识库与发布还要在网页端操作即可`
  1428. : `智能体「${assistantName}」已创建,但提示词写入失败:${promptError}。让老师到右侧页面手动补,或调整后重试`
  1429. }
  1430. }
  1431. })
  1432. // ================================================== 可选能力(默认关闭)
  1433. if (extras) {
  1434. // 原来这里有个 cocorobo_whoami(打平台 /me 取账号+班级)。账号信息已由常驻的
  1435. // cocorobo_user_profile 提供(且不依赖 /me 是否上线),班级由下面的 class_list 负责,
  1436. // 所以合并掉,避免两把工具对"我是谁"给出不同答案。
  1437. ctx.tools.register({
  1438. name: 'cococlass_class_list',
  1439. description: '列出可发布的班级(含 classId),发布课件前用它取 id。',
  1440. parameters: params({ keyword: { type: 'string', description: '按班级名筛选' } }),
  1441. output: jsonOut,
  1442. timeoutMs: 20_000,
  1443. async execute ({ keyword }, exec) {
  1444. if (isMock()) {
  1445. return { classes: keyword ? MOCK_CLASSES.filter((c) => c.name.includes(keyword)) : MOCK_CLASSES }
  1446. }
  1447. const q = keyword ? `?keyword=${encodeURIComponent(keyword)}` : ''
  1448. return api(`/cococlass/classes${q}`, { signal: exec.signal })
  1449. }
  1450. })
  1451. ctx.tools.register({
  1452. name: 'cococlass_courseware_status',
  1453. description: '查询课件生成任务进度(创建时已自动等待,只有在需要追问进度时才用)。',
  1454. parameters: params({ taskId: { type: 'string', required: true } }),
  1455. output: jsonOut,
  1456. timeoutMs: 20_000,
  1457. async execute ({ taskId }, exec) {
  1458. if (isMock()) return mockTaskState(taskId)
  1459. return api(`/tasks/${encodeURIComponent(taskId)}`, { signal: exec.signal })
  1460. }
  1461. })
  1462. ctx.tools.register({
  1463. name: 'cococlass_courseware_publish',
  1464. description: '把课件发布到班级(写操作,必须老师明确同意后再调用)。',
  1465. parameters: params({
  1466. coursewareId: { type: 'string', required: true },
  1467. classId: { type: 'string', required: true },
  1468. publishAt: { type: 'string', description: '预约时间 ISO8601,留空立即发布' }
  1469. }),
  1470. output: jsonOut,
  1471. timeoutMs: 30_000,
  1472. async execute ({ coursewareId, classId, publishAt }, exec) {
  1473. if (isMock()) {
  1474. const cls = MOCK_CLASSES.find((c) => c.id === classId)
  1475. if (!cls) fail(`找不到班级 ${classId}`)
  1476. return {
  1477. published: true,
  1478. coursewareId,
  1479. classId,
  1480. className: cls.name,
  1481. publishAt: publishAt || new Date().toISOString(),
  1482. shareUrl: `${apiBase}/cococlass/class/${classId}?cw=${coursewareId}`
  1483. }
  1484. }
  1485. return api(`/cococlass/courseware/${encodeURIComponent(coursewareId)}/publish`, {
  1486. method: 'POST',
  1487. body: JSON.stringify({ classId, publishAt: publishAt || null }),
  1488. signal: exec.signal
  1489. })
  1490. }
  1491. })
  1492. }
  1493. // ============================================ 浏览器:真的上网干活
  1494. // 引擎自身没有"操作网页"的工具(右侧栏只是展示),老师要查资料/盯竞品/填表单时
  1495. // 模型只能说"我没有联网能力"。这里用 Chrome/Edge 的 DevTools 协议自己开一个
  1496. // 独立浏览器实例(独立 profile,不碰老师日常浏览器),把常用动作暴露成一把工具。
  1497. const browser = createBrowserController({
  1498. userDataDir: workspaceDir ? path.join(workspaceDir, '.browser-profile') : '',
  1499. browserExe: config.browserExe,
  1500. headless: config.browserHeadless !== false
  1501. })
  1502. ctx.tools.register({
  1503. name: 'cocorobo_browser',
  1504. description:
  1505. '用真实浏览器打开网页并操作它:读取正文、点按钮、填输入框、截图、跑一段页面脚本。' +
  1506. '老师要"上网查一下 / 打开这个链接看看 / 搜一下… / 把这个网页的内容整理出来 / 在网站上填个表"时用。' +
  1507. '典型顺序:action=open 拿 tabId → action=text 读内容(需要时 click/type)→ 再 text 确认结果。' +
  1508. '只支持 http/https;不能读本地文件,也不要用它登录老师的平台账号(平台页面走 cocorobo_open_page 在右侧打开)。',
  1509. parameters: params({
  1510. action: {
  1511. type: 'string',
  1512. required: true,
  1513. enum: ['open', 'goto', 'text', 'click', 'type', 'screenshot', 'eval', 'tabs', 'close', 'quit'],
  1514. description: 'open=新开页面;goto=当前页跳转;text=取正文;click=点击;type=输入;screenshot=截图;eval=执行脚本;tabs=列出页签;close/quit=关页签/关浏览器'
  1515. },
  1516. url: { type: 'string', description: 'open / goto 时必填,http(s) 完整地址' },
  1517. tabId: { type: 'string', description: '页签 id(open 的返回里有);不填就用最近打开的那个' },
  1518. selector: { type: 'string', description: 'CSS 选择器。click 时可只给 text;type 时必填(如 input[name=q])' },
  1519. text: { type: 'string', description: 'click 时=按钮上的文字;type 时=要输入的内容' },
  1520. submit: { type: 'boolean', description: 'type 时是否提交(回车/提交表单)' },
  1521. index: { type: 'number', description: 'click 命中多个时点第几个,默认 0(第一个)' },
  1522. expression: { type: 'string', description: 'eval 时执行的 JS 表达式,返回可序列化值' },
  1523. file: { type: 'string', description: 'screenshot 保存路径,不填存到工作区 screenshots/' }
  1524. }),
  1525. output: jsonOut,
  1526. timeoutMs: 90_000,
  1527. async execute (args) {
  1528. const action = String(args.action || '').trim()
  1529. const tabId = String(args.tabId || '').trim() || undefined
  1530. try {
  1531. if (action === 'open') return await browser.open(args.url)
  1532. if (action === 'goto') return await browser.goto(args.url, tabId)
  1533. if (action === 'text') return await browser.pageText(tabId, { selector: String(args.selector || 'body') })
  1534. if (action === 'click') {
  1535. return await browser.click(tabId, {
  1536. selector: String(args.selector || ''),
  1537. text: String(args.text || ''),
  1538. index: Number(args.index) || 0
  1539. })
  1540. }
  1541. if (action === 'type') {
  1542. if (!String(args.selector || '').trim()) fail('缺少 selector', '输入框要给出 CSS 选择器,例如 input[name=q];不确定就先取一次页面文字')
  1543. return await browser.type(tabId, {
  1544. selector: String(args.selector),
  1545. text: String(args.text ?? ''),
  1546. submit: args.submit === true
  1547. })
  1548. }
  1549. if (action === 'screenshot') {
  1550. const dir = workspaceDir || '.'
  1551. const file = String(args.file || '').trim() || path.join(dir, 'screenshots', `page-${Date.now()}.png`)
  1552. return await browser.screenshot(tabId, file)
  1553. }
  1554. if (action === 'eval') {
  1555. if (!String(args.expression || '').trim()) fail('缺少 expression', 'eval 需要一段 JS 表达式')
  1556. return { value: await browser.evaluate(tabId, args.expression) }
  1557. }
  1558. if (action === 'tabs') {
  1559. const list = await browser.listTabs()
  1560. return { tabs: list.map((t) => ({ id: t.id, title: t.title, url: t.url })) }
  1561. }
  1562. if (action === 'close') {
  1563. if (!tabId) fail('缺少 tabId', '先 action=tabs 看有哪些页签')
  1564. return await browser.closeTab(tabId)
  1565. }
  1566. if (action === 'quit') return await browser.quit()
  1567. fail(`不认识的 action:${action}`, '可选 open / goto / text / click / type / screenshot / eval / tabs / close / quit')
  1568. } catch (err) {
  1569. fail(err.message || '浏览器操作失败', '可以先用 action=tabs 看当前页面状态,或换一个网址重试')
  1570. }
  1571. }
  1572. })
  1573. // ============================================ 本地 Office / PDF 文件
  1574. // 老师的工作常常落在 Word/Excel/PDF 上:读一份成绩表、把大纲写成文档、
  1575. // 把网页或讲义打成 PDF。这里直接读写文件,不依赖 WPS 界面(COM 会被安全策略拦)。
  1576. const writeRoots = [
  1577. workspaceDir,
  1578. path.join(process.env.USERPROFILE || process.env.HOME || '', 'Desktop'),
  1579. path.join(process.env.USERPROFILE || process.env.HOME || '', 'Documents'),
  1580. path.join(process.env.USERPROFILE || process.env.HOME || '', 'Downloads')
  1581. ].filter(Boolean).map((p) => path.resolve(p))
  1582. function checkWritePath (file) {
  1583. const target = path.resolve(String(file || ''))
  1584. const ok = writeRoots.some((root) => target === root || target.startsWith(root + path.sep))
  1585. if (!ok) fail('只能在 工作区 / 桌面 / 文档 / 下载 里创建文件', `收到的是 ${target}`)
  1586. return target
  1587. }
  1588. ctx.tools.register({
  1589. name: 'cocorobo_office',
  1590. description:
  1591. '读写老师电脑上的 Office 文件:读 docx/xlsx/pptx/pdf 的内容,生成 docx/xlsx/pptx,把 HTML 导成 PDF 或 PNG。' +
  1592. '老师说"看看这份文档/表格里写了什么""把这些内容整理成 Word/Excel""做一份 PPT 课件/说课稿""把这份讲义转成 PDF"时用。' +
  1593. 'read 支持 .docx/.xlsx/.pptx/.pdf;.doc/.xls/.ppt 老格式会报错,需要先另存为新格式。' +
  1594. 'write_pptx 生成 16:9 可编辑课件(标题/要点/配图),老师在 WPS 和 PowerPoint 里都能直接改。' +
  1595. 'html_to_pdf / html_to_png 把自写的 HTML(思维导图、板书、海报)导出成 PDF 或 PNG。' +
  1596. '中文 PDF 常见字体未内嵌,读出来是乱码——遇到会直接报"读不了",不要猜内容。',
  1597. parameters: params({
  1598. action: { type: 'string', required: true, enum: ['read', 'write_docx', 'write_xlsx', 'write_pptx', 'html_to_pdf', 'html_to_png'], description: '要做的操作' },
  1599. file: { type: 'string', required: true, description: '文件绝对路径。read 时是源文件;write_* 时是要生成的文件;html_to_pdf 时是 HTML 路径或网址' },
  1600. title: { type: 'string', description: 'write_docx 的文档标题;write_pptx 的封面主标题' },
  1601. blocks: {
  1602. type: 'array',
  1603. description: 'write_docx 的正文块:[{type:"heading",level:1,text:"…"} | {type:"paragraph",text:"…"} | {type:"bullet",text:"…"} | {type:"table",rows:[["列1","列2"],…]}]',
  1604. items: { type: 'object', additionalProperties: true }
  1605. },
  1606. sheets: {
  1607. type: 'array',
  1608. description: 'write_xlsx 的工作表:[{name:"成绩",rows:[["姓名","分数"],["张三",92]]}]',
  1609. items: { type: 'object', additionalProperties: true }
  1610. },
  1611. slides: {
  1612. type: 'array',
  1613. description: 'write_pptx 的页面(封面自动加):[{layout:"section"|"bullets"|"image"|"closing", title:"…", subtitle:"…", bullets:["…"], image:"配图绝对路径", note:"小字备注"}]',
  1614. items: { type: 'object', additionalProperties: true }
  1615. },
  1616. subtitle: { type: 'string', description: 'write_pptx 封面副标题,如"五年级数学 · 第 3 单元"' },
  1617. meta: { type: 'string', description: 'write_pptx 封面的署名行,如"授课教师:李老师"' },
  1618. footer: { type: 'string', description: 'write_pptx 每页左下角页脚,可不填' },
  1619. accent: { type: 'string', description: 'write_pptx 主色,十六进制如 #2563EB;不填用蓝色' },
  1620. closing: { type: 'string', description: 'write_pptx 结尾页文字,不填则不加结尾页' },
  1621. out: { type: 'string', description: 'html_to_pdf / html_to_png 的输出路径,不填则与 HTML 同名' },
  1622. width: { type: 'number', description: 'html_to_png 的画布宽度(像素),不填 1400' },
  1623. height: { type: 'number', description: 'html_to_png 的画布高度(像素),不填 900' }
  1624. }),
  1625. output: jsonOut,
  1626. timeoutMs: 120_000,
  1627. async execute (args) {
  1628. const action = String(args.action || '').trim()
  1629. const file = String(args.file || '').trim()
  1630. if (!file) fail('缺少 file', '给出文件的绝对路径')
  1631. if (action === 'read') {
  1632. const target = path.resolve(file)
  1633. let stat
  1634. try { stat = fs.statSync(target) } catch { fail('文件不存在', `读不到 ${target}`) }
  1635. if (stat.size > 60 * 1048576) fail('文件太大', `${(stat.size / 1048576).toFixed(0)}MB,超过 60MB 请先拆分`)
  1636. const result = readOfficeFile(target)
  1637. if (result.kind === 'pdf' && !result.readable) {
  1638. fail('这个 PDF 读不出文字', result.hint)
  1639. }
  1640. return { ...result, file: target, size: stat.size }
  1641. }
  1642. if (action === 'write_docx') {
  1643. const target = checkWritePath(file)
  1644. return writeDocx(target, { title: String(args.title || ''), blocks: Array.isArray(args.blocks) ? args.blocks : [] })
  1645. }
  1646. if (action === 'write_xlsx') {
  1647. const target = checkWritePath(file)
  1648. return writeXlsx(target, { sheets: Array.isArray(args.sheets) ? args.sheets : [] })
  1649. }
  1650. if (action === 'write_pptx') {
  1651. const target = checkWritePath(file)
  1652. const slides = Array.isArray(args.slides) ? args.slides : []
  1653. if (!slides.length) fail('没有页面内容', 'slides 里至少给一页:{layout:"bullets", title:"…", bullets:["…"]}')
  1654. return writePptx(target, {
  1655. title: String(args.title || '').trim(),
  1656. subtitle: String(args.subtitle || '').trim(),
  1657. meta: String(args.meta || '').trim(),
  1658. footer: String(args.footer || '').trim(),
  1659. accent: String(args.accent || '').trim(),
  1660. closing: String(args.closing || '').trim(),
  1661. slides
  1662. })
  1663. }
  1664. if (action === 'html_to_png') {
  1665. const out = String(args.out || '').trim() ||
  1666. (/^https?:\/\//i.test(file) ? path.join(workspaceDir || '.', 'png', `page-${Date.now()}.png`) : file.replace(/\.html?$/i, '') + '.png')
  1667. const target = checkWritePath(out)
  1668. return htmlToPng({ htmlPath: file, pngPath: target, browserExe: config.browserExe, width: args.width, height: args.height })
  1669. }
  1670. if (action === 'html_to_pdf') {
  1671. const out = String(args.out || '').trim() ||
  1672. (/^https?:\/\//i.test(file) ? path.join(workspaceDir || '.', 'pdf', `page-${Date.now()}.pdf`) : file.replace(/\.html?$/i, '') + '.pdf')
  1673. const target = checkWritePath(out)
  1674. return htmlToPdf({ htmlPath: file, pdfPath: target, browserExe: config.browserExe })
  1675. }
  1676. fail(`不认识的 action:${action}`, '可选 read / write_docx / write_xlsx / write_pptx / html_to_pdf / html_to_png')
  1677. }
  1678. })
  1679. // 这行只用于启动日志里给排查的人看,必须跟上面实际 register 的工具一致
  1680. const base = ['cocorobo_user_profile', 'cocorobo_open_page', 'cocorobo_page_eval', 'cocorobo_page_drop_file', 'cocorobo_page_devtools', 'cocorobo_page_reload', 'cocorobo_api', 'cocorobo_workflow_build', 'cocorobo_image_generate', 'cocorobo_browser', 'cocorobo_office', 'cococlass_courseware_create', 'cococlass_course_from_pptx', 'cocoflow_agent_plan', 'cocoflow_agent_create']
  1681. const list = extras
  1682. ? [...base, 'cococlass_class_list', 'cococlass_courseware_status', 'cococlass_courseware_publish']
  1683. : base
  1684. console.log(`[cocorobo] 已注册 ${list.length} 个工具:${list.join(' / ')}(cocoflow ${cfMock() ? 'mock 模式' : cocoflow.apiBase})`)
  1685. }