|
@@ -0,0 +1,1793 @@
|
|
|
|
|
+/**
|
|
|
|
|
+ * CocoBuddy 教师端 dsh 插件
|
|
|
|
|
+ * ------------------------
|
|
|
|
|
+ * 第一阶段只开放两个"创建"能力,越少越好用:
|
|
|
|
|
+ * cococlass_courseware_create —— 一句话 → cococlass 课件
|
|
|
|
|
+ * cococlass_course_from_pptx —— 本地 PPTX 交给平台前端解析建课
|
|
|
|
|
+ * cocoflow_agent_create —— 一句话 → cocoflow 工作流智能体
|
|
|
|
|
+ *
|
|
|
|
|
+ * 设计约束(改代码前先读):
|
|
|
|
|
+ * 1. 工具名带业务域前缀(cococlass_ / cocoflow_),模型看名字就知道选哪个。
|
|
|
|
|
+ * 2. 粒度对齐老师的一句自然语言,不暴露 CRUD,也不让模型自己拼多步。
|
|
|
|
|
+ * 3. 建课件是分钟级长任务:工具内部自己等,等不到就把 taskId 和链接交出去,
|
|
|
|
|
+ * 绝不要求模型连续轮询(那会把对话刷成一堆工具气泡)。
|
|
|
|
|
+ * 4. 登录态每次从 authFile 读取,换账号/续期不需要重启进程。
|
|
|
|
|
+ * 5. 其余能力(班级列表/发布/我的课件)由 config.extras 控制,默认不开。
|
|
|
|
|
+ */
|
|
|
|
|
+
|
|
|
|
|
+import fs from 'node:fs'
|
|
|
|
|
+import path from 'node:path'
|
|
|
|
|
+import { createUserCenter } from './user.mjs'
|
|
|
|
|
+import { createBrowserController } from './browser.mjs'
|
|
|
|
|
+import { readOfficeFile, writeDocx, writeXlsx, writePptx, htmlToPdf, htmlToPng } from './office.mjs'
|
|
|
|
|
+import { buildWorkflowFile, WorkflowError, WorkflowIOError } from './workflow-build.mjs'
|
|
|
|
|
+
|
|
|
|
|
+const DEFAULT_API_BASE = 'https://cloud.cocorobo.cn'
|
|
|
|
|
+const API_PREFIX = '/agent/v1'
|
|
|
|
|
+
|
|
|
|
|
+// 建课件默认最多在工具里等 45 秒,剩下的交给"续查"链接,避免工具调用超时
|
|
|
|
|
+const DEFAULT_WAIT_MS = 45_000
|
|
|
|
|
+
|
|
|
|
|
+export const name = 'cocorobo'
|
|
|
|
|
+export const inject = ['tools']
|
|
|
|
|
+
|
|
|
|
|
+export function apply (ctx, config = {}) {
|
|
|
|
|
+ const apiBase = (config.apiBase || DEFAULT_API_BASE).replace(/\/+$/, '')
|
|
|
|
|
+ // 门户页面基址:创建完成后要在客户端右侧打开的那个网页。和接口同域,
|
|
|
|
|
+ // 随语言/区域切换(cloud.cocorobo.cn / .hk / .com),所以默认跟着 apiBase 走。
|
|
|
|
|
+ const portalBase = String(config.portalBase || apiBase).replace(/\/+$/, '')
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 平台页面的 hash 路由:
|
|
|
|
|
+ * 智能体 {portal}/#!/agent/<agentId>
|
|
|
|
|
+ * 课件/课程 {portal}/#!/cococlass/<coursewareId>
|
|
|
|
|
+ * 工具结果里带 openUrl,客户端插件会据此在右侧打开浏览器页
|
|
|
|
|
+ * (见 resources/plugin/cocorobo-brand/client.js)。
|
|
|
|
|
+ */
|
|
|
|
|
+ const pageUrl = (kind, id) => (id ? `${portalBase}/#!/${kind}/${encodeURIComponent(id)}` : '')
|
|
|
|
|
+ // 课件编辑器(PPT 解析 + 保存都在这个前端里跑)
|
|
|
|
|
+ const pptBase = String(config.cococlassPptBase || 'https://ppt.cocorobo.cn').replace(/\/+$/, '')
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 应用中心(/api/pbl/*):第三个后端,独立域名 pbl.cocorobo.cn。
|
|
|
|
|
+ * 智能体"发布成应用"之后的分类、权限、详情、列表都在这里,不在 appapi,
|
|
|
|
|
+ * 也不在 cloud 的 /agent/v1。实测只带平台 apiKey(Bearer)就够,不需要网页 cookie。
|
|
|
|
|
+ */
|
|
|
|
|
+ const appStoreBase = String(config.appStoreApiBase || 'https://pbl.cocorobo.cn').replace(/\/+$/, '')
|
|
|
|
|
+ // 统一模型网关(openai 兼容):图片走它,key 与业务 apiKey 同一把(见 electron/llm.js)
|
|
|
|
|
+ const llmBase = String(config.llmBaseURL || '').trim().replace(/\/+$/, '')
|
|
|
|
|
+ // 图像网关默认与文本同一个;服务端若把图片单独挂在别的地址,用 imageBaseURL 覆盖,不用发版
|
|
|
|
|
+ const imageBase = String(config.imageBaseURL || '').trim().replace(/\/+$/, '') || llmBase
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 图片作品统一落在老师的数据目录里,不是当前 cwd:
|
|
|
|
|
+ * 引擎的 cwd 会随会话变化,换个会话老师就找不到刚生成的图了。
|
|
|
|
|
+ */
|
|
|
|
|
+ const workspaceDir = String(
|
|
|
|
|
+ config.workspaceDir ||
|
|
|
|
|
+ (config.authFile ? path.join(path.dirname(path.dirname(config.authFile)), 'workspace') : '')
|
|
|
|
|
+ )
|
|
|
|
|
+ const authFile = config.authFile
|
|
|
|
|
+ const forceMock = config.mock !== false
|
|
|
|
|
+ const extras = config.extras === true
|
|
|
|
|
+ const waitMs = Number(config.waitMs) || DEFAULT_WAIT_MS
|
|
|
|
|
+
|
|
|
|
|
+ const readAuth = () => {
|
|
|
|
|
+ try {
|
|
|
|
|
+ return JSON.parse(fs.readFileSync(authFile, 'utf8'))
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ return { apiBase, token: '', mock: forceMock }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const isMock = () => forceMock || !!readAuth().mock
|
|
|
|
|
+ const token = () => (readAuth().token || '').trim()
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 当前登录老师(cococlass / cocoflow 共用同一份)。
|
|
|
|
|
+ * 身份先读 authFile;缺 organizeid / apiKey 时按缓存的 userid 去平台补全,
|
|
|
|
|
+ * 补全结果写回 authFile —— "登录回调没带 organizeid" 只影响第一次调用。
|
|
|
|
|
+ */
|
|
|
|
|
+ const user = createUserCenter({
|
|
|
|
|
+ authFile,
|
|
|
|
|
+ apiBase,
|
|
|
|
|
+ pblBase: config.pblBase || config.cocoroboPblBase || '',
|
|
|
|
|
+ mock: forceMock,
|
|
|
|
|
+ // 默认只走判 cookie 的 selectUser;selectUser2 是无鉴权测试接口,只有本机调试才显式打开
|
|
|
|
|
+ allowTestApi: config.pblTestApi === true
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ function fail (message, hint) {
|
|
|
|
|
+ throw new Error(hint ? `${message}。${hint}` : message)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function idempotencyKey (prefix) {
|
|
|
|
|
+ const uuid = globalThis.crypto && globalThis.crypto.randomUUID
|
|
|
|
|
+ ? globalThis.crypto.randomUUID()
|
|
|
|
|
+ : `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
|
|
|
|
+ return `${prefix}-${uuid}`
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** 平台可能返回 {code,data} 包装,统一拆一层,工具里就不用到处判断。 */
|
|
|
|
|
+ function unwrap (json) {
|
|
|
|
|
+ if (json && typeof json === 'object' && json.data && typeof json.data === 'object' && !Array.isArray(json.data)) {
|
|
|
|
|
+ return json.data
|
|
|
|
|
+ }
|
|
|
|
|
+ return json || {}
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async function api (pathname, init = {}) {
|
|
|
|
|
+ const url = `${apiBase}${API_PREFIX}${pathname}`
|
|
|
|
|
+ // 身份与凭据都走用户中心:key 可能是刚按 userid 补全回来的那一把
|
|
|
|
|
+ const me = await user.resolve()
|
|
|
|
|
+ const tk = me.apiKey || token()
|
|
|
|
|
+ if (!tk) fail('还没有登录账号', '请在客户端里完成登录后重试')
|
|
|
|
|
+ let res
|
|
|
|
|
+ try {
|
|
|
|
|
+ res = await fetch(url, {
|
|
|
|
|
+ ...init,
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ 'content-type': 'application/json',
|
|
|
|
|
+ authorization: `Bearer ${tk}`,
|
|
|
|
|
+ // 平台侧可直接用这几个头定位老师/学校;没有就省略,平台自己按 apiKey 反查
|
|
|
|
|
+ ...(me.userid ? { 'x-user-id': me.userid } : {}),
|
|
|
|
|
+ ...(me.schoolName ? { 'x-school-name': encodeURIComponent(me.schoolName) } : {}),
|
|
|
|
|
+ ...(me.organizeId ? { 'x-org-id': me.organizeId } : {}),
|
|
|
|
|
+ ...(init.headers || {})
|
|
|
|
|
+ },
|
|
|
|
|
+ signal: init.signal
|
|
|
|
|
+ })
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ if (err && err.name === 'AbortError') throw err
|
|
|
|
|
+ fail(`连不上平台接口 ${pathname}`, `${err.message};请检查网络或平台地址`)
|
|
|
|
|
+ }
|
|
|
|
|
+ const text = await res.text()
|
|
|
|
|
+ if (res.status === 401 || res.status === 403) fail('登录已过期或没有权限', '请重新登录客户端')
|
|
|
|
|
+ let json = null
|
|
|
|
|
+ try { json = text ? JSON.parse(text) : null } catch { /* 非 JSON */ }
|
|
|
|
|
+ if (!res.ok) {
|
|
|
|
|
+ const msg = json && (json.message || json.msg || json.error)
|
|
|
|
|
+ fail(`平台接口 ${pathname} 返回 ${res.status}`, msg || text.slice(0, 200))
|
|
|
|
|
+ }
|
|
|
|
|
+ if (json === null) fail(`平台接口 ${pathname} 返回的不是 JSON`, '请确认接口已按契约实现')
|
|
|
|
|
+ if (typeof json.code === 'number' && json.code !== 0) {
|
|
|
|
|
+ fail(json.message || json.msg || `平台返回错误码 ${json.code}`)
|
|
|
|
|
+ }
|
|
|
|
|
+ return unwrap(json)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
|
|
|
+
|
|
|
|
|
+ // ------------------------------------------------------------------ 进度
|
|
|
|
|
+ const RUNNING = new Set(['queued', 'pending', 'running', 'processing', 'generating', 'in_progress'])
|
|
|
|
|
+ const DONE = new Set(['done', 'success', 'succeeded', 'completed', 'finished', 'ready'])
|
|
|
|
|
+ const FAILED = new Set(['failed', 'error', 'canceled', 'cancelled', 'timeout'])
|
|
|
|
|
+
|
|
|
|
|
+ function stateOf (task) {
|
|
|
|
|
+ const raw = String(task.status || task.state || '').toLowerCase()
|
|
|
|
|
+ if (DONE.has(raw)) return 'done'
|
|
|
|
|
+ if (FAILED.has(raw)) return 'failed'
|
|
|
|
|
+ if (RUNNING.has(raw)) return 'running'
|
|
|
|
|
+ // 有结果地址基本就等于做完了,兼容只回 previewUrl 不回收敛状态的平台
|
|
|
|
|
+ if (task.previewUrl || task.coursewareId || task.resultUrl) return 'done'
|
|
|
|
|
+ return 'running'
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 在工具内部等异步任务收敛。
|
|
|
|
|
+ * 收敛了返回结果;超时返回 running 快照(带链接);失败抛出可读原因。
|
|
|
|
|
+ */
|
|
|
|
|
+ async function waitTask (taskId, { timeoutMs, signal, initial }) {
|
|
|
|
|
+ const deadline = Date.now() + timeoutMs
|
|
|
|
|
+ let snap = initial || { taskId, status: 'queued' }
|
|
|
|
|
+ let delay = 1200
|
|
|
|
|
+ while (Date.now() < deadline) {
|
|
|
|
|
+ if (signal && signal.aborted) throw new Error('已取消')
|
|
|
|
|
+ if (stateOf(snap) === 'done') return snap
|
|
|
|
|
+ if (stateOf(snap) === 'failed') {
|
|
|
|
|
+ fail(snap.message || snap.error || '平台生成失败', '可以调整要求后重新生成一次')
|
|
|
|
|
+ }
|
|
|
|
|
+ await sleep(delay)
|
|
|
|
|
+ delay = Math.min(Math.round(delay * 1.4), 6000)
|
|
|
|
|
+ // mock 模式下没有平台接口可问:直接用本地假任务推进,否则会拿空 token 去请求
|
|
|
|
|
+ // /tasks 并被判成"还没有登录账号",整条链路连试都试不了。
|
|
|
|
|
+ snap = isMock()
|
|
|
|
|
+ ? { ...mockTaskState(taskId), taskId }
|
|
|
|
|
+ : { ...(await api(`/tasks/${encodeURIComponent(taskId)}`, { signal })), taskId }
|
|
|
|
|
+ }
|
|
|
|
|
+ return { ...snap, taskId, status: snap.status || 'running', timedOut: true }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ---------------------------------------------------------------- mock 实现
|
|
|
|
|
+ // 平台接口还没上线时,让整条链路(对话 → 工具 → 结果卡片)先跑起来。
|
|
|
|
|
+ const mockTasks = new Map()
|
|
|
|
|
+ const mockAgents = []
|
|
|
|
|
+ let mockSeq = 0
|
|
|
|
|
+
|
|
|
|
|
+ const MOCK_CLASSES = [
|
|
|
|
|
+ { id: 'cls-1001', name: '三年级 2 班', grade: '三年级', students: 38 },
|
|
|
|
|
+ { id: 'cls-1002', name: '四年级 1 班', grade: '四年级', students: 41 },
|
|
|
|
|
+ { id: 'cls-1003', name: '八年级 2 班', grade: '八年级', students: 42 }
|
|
|
|
|
+ ]
|
|
|
|
|
+
|
|
|
|
|
+ function mockCreateTask (kind, input) {
|
|
|
|
|
+ mockSeq += 1
|
|
|
|
|
+ const id = `mock-${Date.now().toString(36)}-${mockSeq}`
|
|
|
|
|
+ mockTasks.set(id, { id, kind, input, createdAt: Date.now() })
|
|
|
|
|
+ return { taskId: id, status: 'queued' }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function mockTaskState (id) {
|
|
|
|
|
+ const t = mockTasks.get(id)
|
|
|
|
|
+ if (!t) fail(`找不到任务 ${id}`, '任务可能已过期,请重新创建')
|
|
|
|
|
+ const elapsed = Date.now() - t.createdAt
|
|
|
|
|
+ if (elapsed < 2000) return { taskId: id, status: 'running', progress: 30, stage: '正在生成课程大纲' }
|
|
|
|
|
+ if (elapsed < 4500) return { taskId: id, status: 'running', progress: 72, stage: '正在生成页面与配图' }
|
|
|
|
|
+ return {
|
|
|
|
|
+ taskId: id,
|
|
|
|
|
+ status: 'done',
|
|
|
|
|
+ progress: 100,
|
|
|
|
|
+ stage: '已完成',
|
|
|
|
|
+ title: t.input.title,
|
|
|
|
|
+ coursewareId: `cw-${id.slice(-6)}`,
|
|
|
|
|
+ pageCount: 12,
|
|
|
|
|
+ previewUrl: `${apiBase}/cococlass/courseware/${id}/preview`,
|
|
|
|
|
+ editUrl: `${apiBase}/cococlass/courseware/${id}/edit`
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const textOut = (value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
|
|
|
|
|
+ const jsonOut = { schema: { type: 'object', additionalProperties: true }, render: (_a, v) => textOut(v) }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * ctx.tools.register 的 parameters 要的是**完整 JSON Schema**
|
|
|
|
|
+ * ({type:'object', properties, required}),不是 defineTool 那套「属性表 + required:true」的简写。
|
|
|
|
|
+ * 简写原样发给模型会直接 400:
|
|
|
|
|
+ * Provider API error: tools[n].function.parameters must be a JSON Schema of type object
|
|
|
|
|
+ * 所以这里统一把手写属性表编译成模型要的形状。
|
|
|
|
|
+ */
|
|
|
|
|
+ function params (props = {}) {
|
|
|
|
|
+ const properties = {}
|
|
|
|
|
+ const required = []
|
|
|
|
|
+ for (const [key, spec] of Object.entries(props)) {
|
|
|
|
|
+ const { required: isRequired, ...rest } = spec || {}
|
|
|
|
|
+ properties[key] = rest
|
|
|
|
|
+ if (isRequired) required.push(key)
|
|
|
|
|
+ }
|
|
|
|
|
+ return { type: 'object', properties, ...(required.length ? { required } : {}) }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ============================================== 用户中心:我是谁
|
|
|
|
|
+ // cococlass / cocoflow 的业务工具内部都会调 user.resolve(),所以这把工具不是"必经步骤",
|
|
|
|
|
+ // 而是给两种情况用:老师直接问"我现在是哪个账号",以及业务工具报缺 userid / organizeId 时排查。
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_user_profile',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '读取当前登录老师的平台账号信息(userid、姓名、学校、机构 id、账号名)。' +
|
|
|
|
|
+ 'cococlass 与 cocoflow 的工具会自动使用这份身份,通常不必手动调用;' +
|
|
|
|
|
+ '老师问"我现在登录的是谁/用的哪个账号",或工具报缺身份信息时再调用它。' +
|
|
|
|
|
+ '返回里不含密钥明文。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ refresh: { type: 'boolean', description: 'true 表示忽略缓存、重新向平台读一次(换账号或怀疑信息不对时用)' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 20_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ const profile = await user.describe({ force: !!(args && args.refresh) })
|
|
|
|
|
+ return {
|
|
|
|
|
+ ...profile,
|
|
|
|
|
+ hint: profile.missing.length
|
|
|
|
|
+ ? `缺少 ${profile.missing.join(' / ')}:请老师在客户端退出后重新登录一次;仍然缺就是登录回调没把这些参数带回来`
|
|
|
|
|
+ : ''
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ========================================== 把平台页面放到客户端右侧
|
|
|
|
|
+ // 老师说"在右边打开/打开看看/把它调出来"时,模型需要一把能真的开页面的工具,
|
|
|
|
|
+ // 否则只会回"我没有打开网页的能力"。这里只做一件事:返回 openUrl,
|
|
|
|
|
+ // 客户端品牌插件收到结果就在右侧栏开页签(与建课件/建智能体同一套机制)。
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_open_page',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '在客户端右侧栏打开一个可可乐博平台的页面,老师不用离开对话。' +
|
|
|
|
|
+ '老师说"在右边打开/打开看看/把某个课件、智能体、课程页面调出来"时调用;' +
|
|
|
|
|
+ '已知智能体或课件的 id 时可以直接拼链接。' +
|
|
|
|
|
+ 'url 必须是 cocorobo 平台地址(cloud.cocorobo.cn / ppt.cocorobo.cn / beta.cloud.cocorobo.cn 等)。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ url: { type: 'string', required: true, description: '要打开的完整地址(https:// 开头),也接受 /#!/agent/<id> 这种站内路径' },
|
|
|
|
|
+ title: { type: 'string', description: '页面名称,仅用于对话说明' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 10_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ let url = String(args.url || '').trim()
|
|
|
|
|
+ if (!url) fail('缺少 url', '给出要打开的完整地址')
|
|
|
|
|
+ // 站内路径补成完整地址:模型常直接把路由写出来,不该因此失败
|
|
|
|
|
+ if (url.startsWith('#')) url = `${portalBase}/${url}`
|
|
|
|
|
+ else if (url.startsWith('/')) url = `${portalBase}${url}`
|
|
|
|
|
+ if (!/^https?:\/\//i.test(url)) fail('url 需要是 http(s) 地址', `收到的是 ${url}`)
|
|
|
|
|
+ // 只放行平台域名:右边栏是登录态上下文,随便开外站等于把老师带走
|
|
|
|
|
+ if (!/^https?:\/\/([a-z0-9-]+\.)*cocorobo\.(cn|hk|com)(\/|$)/i.test(url)) {
|
|
|
|
|
+ fail('只支持可可乐博平台页面', `这个地址不属于平台域名:${url}`)
|
|
|
|
|
+ }
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ openUrl: url,
|
|
|
|
|
+ title: String(args.title || '').trim(),
|
|
|
|
|
+ message: '已在客户端右侧打开,简单说一句"右边可以看了"就行'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ====================================== 在右侧页面里执行一段脚本
|
|
|
|
|
+ // 技能要"在右边那个页面上做一件事"(调用模块暴露的 window.__cocorobo 函数、
|
|
|
|
|
+ // 读页面上的状态),是各产品组最常见的诉求。工具跑在引擎进程、页面在外壳进程,
|
|
|
|
|
+ // 以前没有回路;现在外壳开了一条只走 127.0.0.1 的通道(electron/page-bridge.js),
|
|
|
|
|
+ // 这里只是它的入口。凭据每次启动重新生成,插件调用时才读。
|
|
|
|
|
+ const bridgeFile = String(config.bridgeFile || '').trim()
|
|
|
|
|
+
|
|
|
|
|
+ function bridgeInfo () {
|
|
|
|
|
+ if (!bridgeFile) return null
|
|
|
|
|
+ try {
|
|
|
|
|
+ const raw = JSON.parse(fs.readFileSync(bridgeFile, 'utf8'))
|
|
|
|
|
+ if (!raw || !raw.port || !raw.token) return null
|
|
|
|
|
+ return raw
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ return null
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_page_eval',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '在客户端右侧已经打开的可可乐博平台页面上执行一段 JavaScript,并把结果拿回来。' +
|
|
|
|
|
+ '页面模块暴露了 window.__cocorobo.<模块>.<方法>(题库筛选、课件定位、白板载入等)时用它调用;' +
|
|
|
|
|
+ '也可以读页面状态(当前课件 id、列表条数)。' +
|
|
|
|
|
+ '右侧没有平台页面时返回 no-guest —— 先用 cocorobo_open_page 打开,再调用。' +
|
|
|
|
|
+ '只对平台域名生效,不能开新页、不能导航、不能读本地文件、不能操作老师的账号设置。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ code: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ required: true,
|
|
|
|
|
+ description: '要执行的 JS:表达式或 async IIFE,返回值必须可 JSON 序列化。' +
|
|
|
|
|
+ '例:window.__cocorobo.questionBank.filter({ kw: "分数" })'
|
|
|
|
|
+ },
|
|
|
|
|
+ urlMatch: { type: 'string', description: '按地址挑页面,如 cloud.cocorobo.cn;不填就用当前可见的平台页面' },
|
|
|
|
|
+ timeoutMs: { type: 'number', description: '超时毫秒,默认 8000,上限 20000' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 25_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ const code = String(args.code || '').trim()
|
|
|
|
|
+ if (!code) fail('缺少 code', '给出要执行的 JS,例如 window.__cocorobo.cococlass.currentLesson()')
|
|
|
|
|
+
|
|
|
|
|
+ const info = bridgeInfo()
|
|
|
|
|
+ if (!info) {
|
|
|
|
|
+ fail(
|
|
|
|
|
+ '页面执行通道还没就绪',
|
|
|
|
|
+ '让老师重启客户端后再试;如果只是想打开页面,用 cocorobo_open_page(它不需要这条通道)'
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ let data = null
|
|
|
|
|
+ try {
|
|
|
|
|
+ const res = await fetch(`http://127.0.0.1:${info.port}/page/eval`, {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ 'content-type': 'application/json',
|
|
|
|
|
+ authorization: `Bearer ${info.token}`
|
|
|
|
|
+ },
|
|
|
|
|
+ body: JSON.stringify({
|
|
|
|
|
+ code,
|
|
|
|
|
+ urlMatch: String(args.urlMatch || '').trim(),
|
|
|
|
|
+ timeoutMs: Number(args.timeoutMs) || 0
|
|
|
|
|
+ })
|
|
|
|
|
+ })
|
|
|
|
|
+ data = await res.json()
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ fail('页面执行通道连不上', `客户端可能已退出或换了通道端口:${err.message}`)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (!data || data.ok !== true) {
|
|
|
|
|
+ const reason = String((data && data.error) || 'unknown')
|
|
|
|
|
+ if (reason === 'no-guest') {
|
|
|
|
|
+ fail('右侧还没有打开平台页面', '先用 cocorobo_open_page 打开对应页面,再执行脚本')
|
|
|
|
|
+ }
|
|
|
|
|
+ if (reason === 'timeout') {
|
|
|
|
|
+ fail('页面脚本超时', '把动作拆小;页面可能还在加载,先确认已经打开完成')
|
|
|
|
|
+ }
|
|
|
|
|
+ fail(
|
|
|
|
|
+ `页面脚本执行失败:${reason}`,
|
|
|
|
|
+ '确认页面里确实有这段代码(例如 window.__cocorobo.<模块>.<方法>),不要凭空调用不存在的函数'
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ url: data.url || '',
|
|
|
|
|
+ value: data.value,
|
|
|
|
|
+ truncated: data.truncated === true,
|
|
|
|
|
+ message: '结果已经拿到:按结果回答老师,不要把 JS 代码念出来'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ====================================== 把本地文件投进右侧页面
|
|
|
|
|
+ // 老师在对话里给了 PPT、或文件已经在技能工作区时,页面侧脚本投不进去:
|
|
|
|
|
+ // executeJavaScript 只能跑文本,浏览器也不允许脚本凭空造 File 塞进 input.files
|
|
|
|
|
+ // (需要用户手势)。字节在外壳进程里,所以走 /page/dropFile —— 和 page_eval
|
|
|
|
|
+ // 同一条 127.0.0.1 通道、同一份凭据。没有这把工具时,模型只能答
|
|
|
|
|
+ // "我在页面里造不出 File,你自己拖一下"(2026-11-20 用户现场)。
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_page_drop_file',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '把老师放进对话的文件直接交给右侧平台页面:可以是上传控件,也可以是页面自己暴露的函数(pageFn)。' +
|
|
|
|
|
+ '等同于老师自己点「选择文件」或把文件拖进页面。支持任意类型(pptx/ppt/pdf/docx/xlsx/图片/音视频…),单文件上限 512MB。' +
|
|
|
|
|
+ '给了 pageFn 就把真 File 交给那个函数,函数返回值原样带回;不给 pageFn 就塞进页面的 input[type=file] 并派发 change。' +
|
|
|
|
|
+ '页面钩子收数组的(如建课页 window.handleFileUpload(File[]))传 pageFnArgs:"array"。' +
|
|
|
|
|
+ '禁止为搬运文件编写任何本地 HTTP 服务 / serve_pptx.js / 127.0.0.1 临时端口:字节已由本工具读入并还原成真 File,起服务是过期写法。' +
|
|
|
|
|
+ '投递只负责"把文件交到页面手上",页面处理完再用 cocorobo_page_eval 回读状态核对。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ path: { type: 'string', required: true, description: '本地文件的绝对路径(技能工作区里的那份)' },
|
|
|
|
|
+ pageFn: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ description: '页面函数路径,例如建课页 window.handleFileUpload(最里层 ppt iframe,收 File[],须配 pageFnArgs:"array")。' +
|
|
|
|
|
+ '给了就优先调它,页面没有这个函数才退回 input。函数发在哪一层 frame 都行,会自动找。'
|
|
|
|
|
+ },
|
|
|
|
|
+ pageFnArgs: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ enum: ['single', 'array'],
|
|
|
|
|
+ description: '页面函数入参形态:默认 single = fn(file, meta);array = fn([file], meta),用于 handleFileUpload(File[]) 这类收数组的钩子。'
|
|
|
|
|
+ },
|
|
|
|
|
+ name: { type: 'string', description: '页面上显示的文件名;不填就用 path 的文件名' },
|
|
|
|
|
+ urlMatch: { type: 'string', description: '按地址挑页签,如 ppt.cocorobo.cn;不填就取最新打开的平台页签' },
|
|
|
|
|
+ clickText: {
|
|
|
|
|
+ type: 'array',
|
|
|
|
|
+ items: { type: 'string' },
|
|
|
|
|
+ description: '上传入口的按钮文字,页面需要先点一下才露出控件时用,如 ["上传本地文件"]'
|
|
|
|
|
+ },
|
|
|
|
|
+ pageFnTimeoutMs: { type: 'number', description: '等页面函数返回的毫秒数,默认 120000(页面可能要传完 S3 才返回)' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 300_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ const file = String(args.path || '').trim()
|
|
|
|
|
+ if (!file) fail('缺少 path', '给出技能工作区里那份文件的绝对路径')
|
|
|
|
|
+
|
|
|
|
|
+ const info = bridgeInfo()
|
|
|
|
|
+ if (!info) {
|
|
|
|
|
+ fail('页面执行通道还没就绪', '让老师重启客户端后再试')
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ let data = null
|
|
|
|
|
+ try {
|
|
|
|
|
+ const res = await fetch(`http://127.0.0.1:${info.port}/page/dropFile`, {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ 'content-type': 'application/json',
|
|
|
|
|
+ authorization: `Bearer ${info.token}`
|
|
|
|
|
+ },
|
|
|
|
|
+ body: JSON.stringify({
|
|
|
|
|
+ path: file,
|
|
|
|
|
+ name: String(args.name || ''),
|
|
|
|
|
+ urlMatch: String(args.urlMatch || ''),
|
|
|
|
|
+ clickText: Array.isArray(args.clickText) ? args.clickText.map(String) : [],
|
|
|
|
|
+ pageFn: String(args.pageFn || ''),
|
|
|
|
|
+ pageFnArgs: String(args.pageFnArgs || '') === 'array' ? 'array' : 'single',
|
|
|
|
|
+ pageFnTimeoutMs: Number(args.pageFnTimeoutMs) || 0
|
|
|
|
|
+ })
|
|
|
|
|
+ })
|
|
|
|
|
+ data = await res.json()
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ fail('页面执行通道连不上', `客户端可能已退出或换了通道端口:${err.message}`)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (!data || data.ok !== true) {
|
|
|
|
|
+ const reason = String((data && data.error) || 'unknown')
|
|
|
|
|
+ if (reason === 'no-guest') {
|
|
|
|
|
+ fail('右侧还没有打开平台页面', '先用 cocorobo_open_page 打开对应页面,再投递文件')
|
|
|
|
|
+ }
|
|
|
|
|
+ if (reason === 'path-not-allowed') {
|
|
|
|
|
+ fail('文件不在技能工作区里', '通道只读应用数据目录,先把文件复制进工作区再投递')
|
|
|
|
|
+ }
|
|
|
|
|
+ if (reason === 'too-large') {
|
|
|
|
|
+ fail('文件太大', `上限 512MB,收到 ${data && data.size ? Math.round(data.size / 1048576) + 'MB' : '未知大小'}`)
|
|
|
|
|
+ }
|
|
|
|
|
+ if (reason === 'file-missing') {
|
|
|
|
|
+ fail('文件不存在', `检查路径:${file}`)
|
|
|
|
|
+ }
|
|
|
|
|
+ if (reason === 'no-fn') {
|
|
|
|
|
+ fail(
|
|
|
|
|
+ '页面里没有这个函数',
|
|
|
|
|
+ `${data.fn || args.pageFn} 不存在。确认页面已挂到 window(层级、拼写),或直接不传 pageFn 走上传控件`
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+ if (reason === 'fn-threw' || reason === 'fn-timeout') {
|
|
|
|
|
+ fail(
|
|
|
|
|
+ reason === 'fn-timeout' ? '页面函数没有按时返回' : '页面函数执行报错',
|
|
|
|
|
+ String((data && data.hint) || (data && data.message) || '文件已经交到页面手里,问题在页面内部;不要重复投递')
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+ if (reason === 'no-target') {
|
|
|
|
|
+ fail(
|
|
|
|
|
+ '页面上没找到上传控件',
|
|
|
|
|
+ '确认建课弹窗已经停在「上传本地文件」那一步;必要时用 clickText 指一下入口按钮,或传 pageFn 直接调页面函数'
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+ fail(`投递失败:${reason}`, String((data && data.hint) || ''))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ url: data.url || '',
|
|
|
|
|
+ name: data.name || '',
|
|
|
|
|
+ via: data.via || 'change',
|
|
|
|
|
+ fn: data.fn || '',
|
|
|
|
|
+ value: data.value,
|
|
|
|
|
+ size: data.size || 0,
|
|
|
|
|
+ message: data.via === 'fn'
|
|
|
|
|
+ ? '文件已经交给页面函数,返回值见 value;页面处理完再用 cocorobo_page_eval 回读核对'
|
|
|
|
|
+ : '文件已经投进页面,等页面解析完再用 cocorobo_page_eval 回读核对(看页数,不看返回值)'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ====================================== 右侧页面的开发者工具
|
|
|
|
|
+ // 老师排查"右边点了没反应"要看控制台。右侧栏是 Electron <webview>,外壳菜单里的
|
|
|
|
|
+ // 开发者工具只作用于工作台自己,够不到它;以前模型只能说"我没有这个接口"。
|
|
|
|
|
+ // 客户端补了一条 127.0.0.1 的路由(electron/page-bridge.js 的 /page/devtools),
|
|
|
|
|
+ // 这里只是入口 —— 和 page_eval 共用同一份凭据与"只认平台页面"的挑选规则。
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_page_devtools',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '打开或关闭客户端右侧内嵌浏览器的开发者工具(DevTools / F12 面板),默认弹成独立窗口。' +
|
|
|
|
|
+ '老师说「打开右侧调试工具」「打开 F12」「开开发者工具」「看看右边页面的控制台/报错」时用它。' +
|
|
|
|
|
+ '只对右侧已经打开的可可乐博平台页面生效;右侧没开页面时返回 no-guest,先用 cocorobo_open_page 打开。' +
|
|
|
|
|
+ '不要用 cocorobo_page_eval 去模拟,也不要说"没有这个接口"。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ action: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ enum: ['open', 'close', 'toggle'],
|
|
|
|
|
+ description: 'open(默认,已开则不重复开)/ close / toggle'
|
|
|
|
|
+ },
|
|
|
|
|
+ urlMatch: { type: 'string', description: '按地址挑页面,如 cloud.cocorobo.cn;不填就用当前可见的平台页面' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 15_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ const info = bridgeInfo()
|
|
|
|
|
+ if (!info) {
|
|
|
|
|
+ fail('页面执行通道还没就绪', '让老师重启客户端后再试')
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ let data = null
|
|
|
|
|
+ try {
|
|
|
|
|
+ const res = await fetch(`http://127.0.0.1:${info.port}/page/devtools`, {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ 'content-type': 'application/json',
|
|
|
|
|
+ authorization: `Bearer ${info.token}`
|
|
|
|
|
+ },
|
|
|
|
|
+ body: JSON.stringify({
|
|
|
|
|
+ action: String(args.action || 'open').trim().toLowerCase(),
|
|
|
|
|
+ urlMatch: String(args.urlMatch || '').trim()
|
|
|
|
|
+ })
|
|
|
|
|
+ })
|
|
|
|
|
+ data = await res.json()
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ fail('页面执行通道连不上', `客户端可能已退出或换了通道端口:${err.message}`)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (!data || data.ok !== true) {
|
|
|
|
|
+ const reason = String((data && data.error) || 'unknown')
|
|
|
|
|
+ if (reason === 'no-guest') {
|
|
|
|
|
+ fail('右侧还没有打开平台页面', '先用 cocorobo_open_page 打开对应页面,再开调试工具')
|
|
|
|
|
+ }
|
|
|
|
|
+ fail(`调试工具没开起来:${reason}`, (data && data.hint) || '让老师确认右侧页面还在,再试一次')
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ url: data.url || '',
|
|
|
|
|
+ opened: data.opened === true,
|
|
|
|
|
+ action: data.action || 'open',
|
|
|
|
|
+ message: data.message || (data.opened ? '调试工具已打开(独立窗口)' : '调试工具已关闭')
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ====================================== 右侧页面的刷新 / 清缓存
|
|
|
|
|
+ // "服务端更新了,客户端里还是旧页面"这条反馈反复出现。原因有两层:
|
|
|
|
|
+ // 1. 右栏页签打开后一直活着,点同一个入口只把页签顶到前面,不会重新请求;
|
|
|
|
|
+ // 2. 平台不少响应没带 Cache-Control,Chromium 会按"最近改动时间的 10%"启发式缓存,
|
|
|
|
|
+ // 页面能旧几个小时;js/css 是固定文件名,同样是旧文件。
|
|
|
|
|
+ // 客户端已经在请求/响应头上做了协商缓存(electron/cache-policy.js),这里再给
|
|
|
|
|
+ // 模型一个显式出口:普通刷新 / 硬刷新(等于 Chrome 的 Ctrl+Shift+R)。
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_page_reload',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '刷新客户端右侧内嵌浏览器里的页面,可选硬刷新(清 HTTP 缓存 + 该站点的 Service Worker)。' +
|
|
|
|
|
+ '老师说「刷新一下右边」「页面还是旧的」「服务器更新了没同步」「强制刷新」「清一下缓存再打开」时用它。' +
|
|
|
|
|
+ 'hard=true 等于在 Chrome 里按 Ctrl+Shift+R,服务端发新版后一定拿得到新文件;' +
|
|
|
|
|
+ '只是页面卡住、想重新加载时用 hard=false。' +
|
|
|
|
|
+ '只对右侧已经打开的可可乐博平台页面生效;返回 no-guest 时先用 cocorobo_open_page 打开。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ hard: {
|
|
|
|
|
+ type: 'boolean',
|
|
|
|
|
+ description: 'true=硬刷新(清缓存和 Service Worker,版本更新后用);false=普通刷新(默认)'
|
|
|
|
|
+ },
|
|
|
|
|
+ urlMatch: { type: 'string', description: '按地址挑页面,如 ppt.cocorobo.cn;不填就用当前可见的平台页面' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 30_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ const info = bridgeInfo()
|
|
|
|
|
+ if (!info) {
|
|
|
|
|
+ fail('页面执行通道还没就绪', '让老师重启客户端后再试')
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const hard = args.hard === true || String(args.hard).toLowerCase() === 'true'
|
|
|
|
|
+ let data = null
|
|
|
|
|
+ try {
|
|
|
|
|
+ const res = await fetch(`http://127.0.0.1:${info.port}/page/reload`, {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ 'content-type': 'application/json',
|
|
|
|
|
+ authorization: `Bearer ${info.token}`
|
|
|
|
|
+ },
|
|
|
|
|
+ body: JSON.stringify({
|
|
|
|
|
+ hard,
|
|
|
|
|
+ urlMatch: String(args.urlMatch || '').trim()
|
|
|
|
|
+ })
|
|
|
|
|
+ })
|
|
|
|
|
+ data = await res.json()
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ fail('页面执行通道连不上', `客户端可能已退出或换了通道端口:${err.message}`)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (!data || data.ok !== true) {
|
|
|
|
|
+ const reason = String((data && data.error) || 'unknown')
|
|
|
|
|
+ if (reason === 'no-guest') {
|
|
|
|
|
+ fail('右侧还没有打开平台页面', '先用 cocorobo_open_page 打开对应页面,再刷新')
|
|
|
|
|
+ }
|
|
|
|
|
+ fail(`刷新失败:${reason}`, (data && data.hint) || '让老师确认右侧页面还在,再试一次')
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ url: data.url || '',
|
|
|
|
|
+ hard: data.hard === true,
|
|
|
|
|
+ message: data.message || (hard ? '已硬刷新(清缓存后重新加载)' : '已刷新')
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ======================================== 通用接口调用(技能作者不用写函数)
|
|
|
|
|
+ // 为什么要有这把工具:业务接口由各模块组自己加,每加一个就让客户端发一版是不现实的。
|
|
|
|
|
+ // 有了它,新增接口 = 改 SKILL.md 里一行 {target, method, path},插件与客户端都不用动。
|
|
|
|
|
+ //
|
|
|
|
|
+ // 边界(有意收窄,别当成"任意 HTTP 代理"):
|
|
|
|
|
+ // · 只能打两个后端:platform(config.apiBase + /agent/v1)、cocoflow(config.cocoflowApiBase)
|
|
|
|
|
+ // · 不接受自定义 header / 任意 URL,凭据一律由客户端注入,技能拿不到 key
|
|
|
|
|
+ // · 写操作(非 GET)必须 confirmed=true,避免技能自作主张改老师账号里的数据
|
|
|
|
|
+ const API_TARGETS = {
|
|
|
|
|
+ platform: {
|
|
|
|
|
+ label: '教学平台',
|
|
|
|
|
+ base: () => `${apiBase}${API_PREFIX}`,
|
|
|
|
|
+ // 平台认 apiKey;x-user-id / x-org-id 是给人看的定位信息,缺了不影响鉴权
|
|
|
|
|
+ auth: async () => {
|
|
|
|
|
+ const me = await user.resolve()
|
|
|
|
|
+ const tk = me.apiKey || token()
|
|
|
|
|
+ if (!tk) fail('还没有登录账号', '请在客户端里完成登录后重试')
|
|
|
|
|
+ return {
|
|
|
|
|
+ authorization: `Bearer ${tk}`,
|
|
|
|
|
+ ...(me.userid ? { 'x-user-id': me.userid } : {}),
|
|
|
|
|
+ ...(me.organizeId ? { 'x-org-id': me.organizeId } : {}),
|
|
|
|
|
+ ...(me.schoolName ? { 'x-school-name': encodeURIComponent(me.schoolName) } : {})
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ },
|
|
|
|
|
+ cocoflow: {
|
|
|
|
|
+ label: 'cocoflow',
|
|
|
|
|
+ base: () => cocoflow.apiBase,
|
|
|
|
|
+ // appapi 与主站同一套登录态:cookie 或 Bearer 有一份就能读
|
|
|
|
|
+ auth: async () => {
|
|
|
|
|
+ const tk = cocoflow.token || token()
|
|
|
|
|
+ return {
|
|
|
|
|
+ ...(tk ? { authorization: `Bearer ${tk}` } : {}),
|
|
|
|
|
+ ...(cocoflow.cookie ? { cookie: cocoflow.cookie } : {})
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ },
|
|
|
|
|
+ appstore: {
|
|
|
|
|
+ label: '应用中心',
|
|
|
|
|
+ base: () => appStoreBase,
|
|
|
|
|
+ // /api/pbl/* 认平台 apiKey(Bearer)。实测 cookie、Bearer、甚至不带凭据
|
|
|
|
|
+ // 都能读分类这类公共数据,但写操作(发布)必须带上真身份,所以统一按平台
|
|
|
|
|
+ // 那把 key 走,和 platform 一致。
|
|
|
|
|
+ auth: async () => {
|
|
|
|
|
+ const me = await user.resolve()
|
|
|
|
|
+ const tk = me.apiKey || token()
|
|
|
|
|
+ if (!tk) fail('还没有登录账号', '请在客户端里完成登录后重试')
|
|
|
|
|
+ return {
|
|
|
|
|
+ authorization: `Bearer ${tk}`,
|
|
|
|
|
+ ...(me.userid ? { 'x-user-id': me.userid } : {}),
|
|
|
|
|
+ ...(me.organizeId ? { 'x-org-id': me.organizeId } : {})
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async function callBackend (args, exec) {
|
|
|
|
|
+ const targetKey = String(args.target || '').trim()
|
|
|
|
|
+ const target = API_TARGETS[targetKey]
|
|
|
|
|
+ if (!target) fail(`不支持的 target:${targetKey || '空'}`, '只能是 platform、cocoflow 或 appstore')
|
|
|
|
|
+
|
|
|
|
|
+ const method = String(args.method || 'GET').toUpperCase()
|
|
|
|
|
+ if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
|
|
|
|
|
+ fail(`不支持的 method:${method}`, '只能是 GET / POST / PUT / PATCH / DELETE')
|
|
|
|
|
+ }
|
|
|
|
|
+ if (method !== 'GET' && args.confirmed !== true) {
|
|
|
|
|
+ fail(
|
|
|
|
|
+ `${method} 会改动老师账号里的数据,需要老师明确同意`,
|
|
|
|
|
+ '先把要做什么、影响什么讲给老师听,老师回复"可以/确认"后再带 confirmed: true 调用'
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const pathname = String(args.path || '').trim()
|
|
|
|
|
+ if (!pathname.startsWith('/')) fail('path 必须以 / 开头', '例如 /courseware 或 /api/agents/agent')
|
|
|
|
|
+ if (pathname.includes('://')) fail('path 只能写路径,不能写完整网址', '域名由 target 决定,不能自己指定')
|
|
|
|
|
+ if (pathname.includes('?')) fail('path 里不要带查询串', '把参数放进 query 字段,客户端会拼好')
|
|
|
|
|
+ if (pathname.split('/').includes('..')) fail('path 里不能有 ..', '只写真实的接口路径')
|
|
|
|
|
+
|
|
|
|
|
+ let url
|
|
|
|
|
+ try {
|
|
|
|
|
+ url = new URL(target.base() + pathname)
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ fail('拼出来的接口地址不合法', `target=${targetKey} path=${pathname}`)
|
|
|
|
|
+ }
|
|
|
|
|
+ const query = args.query && typeof args.query === 'object' ? args.query : {}
|
|
|
|
|
+ for (const [k, v] of Object.entries(query)) {
|
|
|
|
|
+ if (v === undefined || v === null || v === '') continue
|
|
|
|
|
+ if (Array.isArray(v)) v.forEach((item) => url.searchParams.append(k, String(item)))
|
|
|
|
|
+ else url.searchParams.set(k, String(v))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ let payload
|
|
|
|
|
+ if (method !== 'GET' && args.body !== undefined && args.body !== null) {
|
|
|
|
|
+ payload = JSON.stringify(args.body)
|
|
|
|
|
+ // 图片 base64 之类很容易把对话撑爆,超过就明确拒绝而不是静默截断
|
|
|
|
|
+ if (payload.length > 6 * 1024 * 1024) {
|
|
|
|
|
+ fail('请求体超过 6MB', '不要用这把工具传大文件;文件请走课件/资源上传那条链路')
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const headers = { 'content-type': 'application/json', ...(await target.auth()) }
|
|
|
|
|
+ const startedAt = Date.now()
|
|
|
|
|
+ console.log(`[api] → ${method} ${targetKey} ${pathname}`)
|
|
|
|
|
+
|
|
|
|
|
+ const ac = new AbortController()
|
|
|
|
|
+ const timer = setTimeout(() => ac.abort(), 30_000)
|
|
|
|
|
+ if (exec && exec.signal) {
|
|
|
|
|
+ if (exec.signal.aborted) ac.abort()
|
|
|
|
|
+ else exec.signal.addEventListener('abort', () => ac.abort(), { once: true })
|
|
|
|
|
+ }
|
|
|
|
|
+ let res, text
|
|
|
|
|
+ try {
|
|
|
|
|
+ res = await fetch(url.toString(), { method, headers, body: payload, signal: ac.signal })
|
|
|
|
|
+ text = await res.text()
|
|
|
|
|
+ console.log(`[api] ← ${method} ${targetKey} ${pathname} ${res.status} ${Date.now() - startedAt}ms`)
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ const aborted = err && (err.name === 'AbortError' || err.name === 'TimeoutError')
|
|
|
|
|
+ fail(
|
|
|
|
|
+ aborted ? `${target.label}接口超时(30s)` : `连不上${target.label}接口 ${pathname}`,
|
|
|
|
|
+ aborted ? '接口可能在做耗时任务;能异步的话改成先提交再查状态' : `${err.message};请检查网络`
|
|
|
|
|
+ )
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ clearTimeout(timer)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ let json = null
|
|
|
|
|
+ try { json = text ? JSON.parse(text) : null } catch { /* 可能不是 JSON */ }
|
|
|
|
|
+
|
|
|
|
|
+ if (res.status === 401 || res.status === 403) {
|
|
|
|
|
+ fail('登录已过期或没有权限', '让老师退出后重新登录一次再试;不要重试同一把凭据')
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const payloadOut = json === null ? String(text || '').slice(0, 200_000) : json
|
|
|
|
|
+
|
|
|
|
|
+ // 平台对不存在的路径不返回 404,而是回 200 + SPA 兜底网页(实测)。不识别的话,
|
|
|
|
|
+ // 技能会把一整页 HTML 当成接口数据,最后对老师编出一个"查到了"的结论。
|
|
|
|
|
+ const ctype = String(res.headers.get('content-type') || '')
|
|
|
|
|
+ const htmlFallback = json === null && (ctype.includes('text/html') || /^\s*<!DOCTYPE html/i.test(String(text || '')))
|
|
|
|
|
+ if (htmlFallback) {
|
|
|
|
|
+ console.log(`[api] ⚠ ${targetKey} ${pathname} 返回网页而不是 JSON(路径错了或后端未部署)`)
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: false,
|
|
|
|
|
+ status: res.status,
|
|
|
|
|
+ ms: Date.now() - startedAt,
|
|
|
|
|
+ target: targetKey,
|
|
|
|
|
+ method,
|
|
|
|
|
+ path: pathname,
|
|
|
|
|
+ code: 'html-fallback',
|
|
|
|
|
+ error: '接口返回的是网页,不是 JSON:这个路径不存在,或后端还没部署',
|
|
|
|
|
+ hint: '不要把这页 HTML 当数据用,也不要告诉老师"查到了"。核对 path 是否与接口文档一致,或改走 cocorobo_page_eval'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: res.ok,
|
|
|
|
|
+ status: res.status,
|
|
|
|
|
+ ms: Date.now() - startedAt,
|
|
|
|
|
+ target: targetKey,
|
|
|
|
|
+ method,
|
|
|
|
|
+ path: pathname,
|
|
|
|
|
+ ...(res.ok
|
|
|
|
|
+ ? { data: payloadOut }
|
|
|
|
|
+ : { error: payloadOut, hint: '接口返回了非 2xx:先把 status 与 error 里的 message 讲清楚,不要自己编数据' }),
|
|
|
|
|
+ ...(json === null ? { raw: true } : {})
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_api',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '调用可可乐博平台接口(通用通道)。各模块组新增业务接口时,**不需要客户端加工具**:' +
|
|
|
|
|
+ '在 SKILL.md 里写好 target / method / path / query / body 即可,凭据由客户端注入。' +
|
|
|
|
|
+ 'target=cocoflow 打 appapi(智能体、知识库等),target=platform 打教学平台 /agent/v1(课件、题库等),' +
|
|
|
|
|
+ 'target=appstore 打应用中心 /api/pbl(智能体发布、应用分类、应用详情)。' +
|
|
|
|
|
+ '只能打这三个后端,不能填任意网址、不能自定义 header、不能上传大文件。' +
|
|
|
|
|
+ 'GET 直接调;POST/PUT/PATCH/DELETE 属于写操作,必须老师明确同意后带 confirmed=true。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ target: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ enum: ['platform', 'cocoflow', 'appstore'],
|
|
|
|
|
+ required: true,
|
|
|
|
|
+ description: 'platform=教学平台(/agent/v1),cocoflow=appapi 智能体平台,appstore=应用中心(/api/pbl)'
|
|
|
|
|
+ },
|
|
|
|
|
+ method: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
|
|
|
|
|
+ description: 'HTTP 方法,默认 GET'
|
|
|
|
|
+ },
|
|
|
|
|
+ path: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ required: true,
|
|
|
|
|
+ description: '以 / 开头的接口路径,例如 /api/agents/agent(不要带域名,不要带 ? 查询串)'
|
|
|
|
|
+ },
|
|
|
|
|
+ query: { type: 'object', description: '查询参数对象;数组会展开成重复参数' },
|
|
|
|
|
+ body: { type: 'object', description: 'JSON 请求体(POST/PUT/PATCH 用),上限 6MB' },
|
|
|
|
|
+ confirmed: {
|
|
|
|
|
+ type: 'boolean',
|
|
|
|
|
+ description: '写操作必填:仅当老师明确同意后才为 true;GET 不需要'
|
|
|
|
|
+ }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 40_000,
|
|
|
|
|
+ async execute (args, exec) {
|
|
|
|
|
+ return callBackend(args, exec)
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ============================================== 工作流:方案 → 可导入的 JSON
|
|
|
|
|
+ // 原来靠技能里的 build_workflow.py,但老师电脑没有 Python(Windows 基本都没有),
|
|
|
|
|
+ // 这条命令会直接失败。编译器是纯 JSON 变换,放进客户端就没有外部依赖了。
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_workflow_build',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '把 CocoFlow 工作流方案(plan)编译成可直接导入的工作流 JSON 文件。' +
|
|
|
|
|
+ '只做本地校验和格式转换,不联网、不碰老师账号里的数据。' +
|
|
|
|
|
+ '方案不合法时会把具体原因返回,按提示改完再调一次即可。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ plan: {
|
|
|
|
|
+ type: 'object',
|
|
|
|
|
+ required: true,
|
|
|
|
|
+ description: '工作流方案:schemaVersion:1、name、model,以及 steps 或 routes(二选一),可选 description/opening/form'
|
|
|
|
|
+ },
|
|
|
|
|
+ outputPath: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ required: true,
|
|
|
|
|
+ description: '输出文件的绝对路径。文件必须不存在(不覆盖已有文件),建议放在老师的桌面或文档目录'
|
|
|
|
|
+ }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 20_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ const result = buildWorkflowFile(args.plan, args.outputPath)
|
|
|
|
|
+ const nodes = result.workflow.content.nodes
|
|
|
|
|
+ const steps = nodes.filter((n) => n.type === 'UserTask')
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ path: result.path,
|
|
|
|
|
+ bytes: result.bytes,
|
|
|
|
|
+ nodes: nodes.length,
|
|
|
|
|
+ edges: result.workflow.content.edges.length,
|
|
|
|
|
+ // 给模型做汇报用:节点顺序 + 每个智能体的名字,避免它凭空描述
|
|
|
|
|
+ steps: steps.map((n) => n.properties.item.assistantName),
|
|
|
|
|
+ hasForm: nodes.some((n) => n.type === 'form_card'),
|
|
|
|
|
+ hasBranch: nodes.some((n) => n.type === 'boss_card')
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ if (err instanceof WorkflowError) {
|
|
|
|
|
+ fail(`方案没通过校验:${err.message}`, '按上面这条改方案,改完再调一次;不要自己拼 JSON 文件')
|
|
|
|
|
+ }
|
|
|
|
|
+ if (err instanceof WorkflowIOError) {
|
|
|
|
|
+ fail(err.message, '换一个输出路径再试;不要删老师已有的文件')
|
|
|
|
|
+ }
|
|
|
|
|
+ throw err
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ================================================ 图片处理(doubao seedream)
|
|
|
|
|
+ // 老师要"画一张图/给课件配图/把这张图改成…"时,模型需要真的能出图,
|
|
|
|
|
+ // 否则只会回"我没有画图的能力"。平台网关(onehub)是 openai 兼容的
|
|
|
|
|
+ // /images/generations,key 与业务 apiKey 同一把。
|
|
|
|
|
+ //
|
|
|
|
|
+ // 模型策略:优先 seedream 5.0 flash,平台分组没开这个渠道时网关回 503,
|
|
|
|
|
+ // 就立刻退回已开通的 3.0(实测唯一稳定可用的),并在结果里如实标注。
|
|
|
|
|
+ // 这样平台哪天补开 5.0,客户端不用改代码就自动切过去。
|
|
|
|
|
+ const IMAGE_MODEL_PREFERRED = String(config.imageModel || 'doubao-seedream-5-0-flash-260915').trim()
|
|
|
|
|
+ const IMAGE_MODEL_READY = String(config.imageModelReady || 'doubao-seedream-3-0-t2i-250415').trim()
|
|
|
|
|
+ // 记住"某个模型刚被网关拒过",5 分钟内不再白试一次(否则每张图都要多等一轮)
|
|
|
|
|
+ const imageModelBlocked = new Map()
|
|
|
|
|
+ const IMAGE_BLOCK_TTL = 5 * 60_000
|
|
|
|
|
+
|
|
|
|
|
+ const imageModelUsable = (model) => {
|
|
|
|
|
+ const at = imageModelBlocked.get(model)
|
|
|
|
|
+ return !at || Date.now() - at > IMAGE_BLOCK_TTL
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** 按文件头判定真实格式:接口回的常是 JPEG,扩展名必须跟着字节走 */
|
|
|
|
|
+ const imageExtOf = (buf) => {
|
|
|
|
|
+ if (buf.length > 4 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return '.png'
|
|
|
|
|
+ if (buf.length > 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return '.jpg'
|
|
|
|
|
+ if (buf.length > 12 && buf.slice(8, 12).toString('ascii') === 'WEBP') return '.webp'
|
|
|
|
|
+ return '.png'
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_image_generate',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '生成图片——老师要的任何一张图都必须走这里,不要用写 HTML 截屏、PowerShell/System.Drawing 或 Python 自己画。' +
|
|
|
|
|
+ '只给 prompt 是文生图;同时给 image 是图生图(按参考图改风格/改背景/换配色/做成海报,保留原构图与原图里的数字文字)。' +
|
|
|
|
|
+ '老师说"画一张…/生成一张配图/给这节课配个插图/做个封面/做成战报图"时调用;' +
|
|
|
|
|
+ '老师说"改这张图/换成水彩风/去掉背景/把字改成…/按这张截图做一张夸张的"时,把那张图的本地路径放进 image 再调用。' +
|
|
|
|
|
+ '返回本地文件路径,可以交给后续的课件步骤或告诉老师在哪儿看。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ prompt: { type: 'string', required: true, description: '画面描述,越具体越好:主体、场景、风格、文字标注、画面比例' },
|
|
|
|
|
+ image: { type: 'string', description: '参考图:本地文件路径或 http(s) 链接。传了就是图生图,保持构图只改 prompt 里说的部分;不传就是文生图' },
|
|
|
|
|
+ size: { type: 'string', description: '输出尺寸,格式 宽x高:方图 1024x1024,横图 1536x1024,竖图 1024x1536' },
|
|
|
|
|
+ model: { type: 'string', description: '一般不用填;平台未开通首选模型时会自动换用可用模型' },
|
|
|
|
|
+ savePath: { type: 'string', description: '保存路径;不填自动存到工作区 images/ 下' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ // 图像模型排队 + 出图通常 20~60 秒,给足时间,避免模型以为失败了重复调用
|
|
|
|
|
+ timeoutMs: 240_000,
|
|
|
|
|
+ async execute (args, exec) {
|
|
|
|
|
+ void exec
|
|
|
|
|
+ const prompt = String(args.prompt || '').trim()
|
|
|
|
|
+ if (!prompt) fail('缺少画面描述', '把老师要的画面写成一句话放进 prompt,例如「三年级科学:水循环示意图,扁平插画」')
|
|
|
|
|
+ let requested = String(args.model || '').trim() || IMAGE_MODEL_PREFERRED
|
|
|
|
|
+ // 只放行图像模型:模型偶尔会把手边的文本模型填进来,那种请求必然 400
|
|
|
|
|
+ if (!/image|seedream|flux|dall-?e|t2i|wanx?/i.test(requested)) {
|
|
|
|
|
+ fail(`“${requested}”不是图像模型`, '图片处理不需要传文本模型,去掉 model 参数即可')
|
|
|
|
|
+ }
|
|
|
|
|
+ // 网关侧已开启「请求体完整透传」(DoneHub 的 pass_through_body),image 会原样到上游。
|
|
|
|
|
+ // 只有显式配了 imageReference:false 的老环境才拒绝,避免又把"改图"答成"重画"。
|
|
|
|
|
+ if (String(args.image || '').trim() && config.imageReference === false) {
|
|
|
|
|
+ fail(
|
|
|
|
|
+ '当前出图通道没有开启参考图透传,改不了已有图片',
|
|
|
|
|
+ '只能按文字描述重新画一张;不要声称会保留原图细节'
|
|
|
|
|
+ )
|
|
|
|
|
+ }
|
|
|
|
|
+ // seedream 3.0 只吃「宽x高」,2K/4K 这类关键字留给以后开通的版本,先归一化
|
|
|
|
|
+ const wantSize = String(args.size || '').trim()
|
|
|
|
|
+ const size = /^\d{2,4}x\d{2,4}$/.test(wantSize) ? wantSize : '1024x1024'
|
|
|
|
|
+
|
|
|
|
|
+ // 参考图:本地文件转 data URL,http(s) 原样传(两种都实测透传成功)
|
|
|
|
|
+ let imageRef = String(args.image || '').trim()
|
|
|
|
|
+ if (imageRef && !/^https?:\/\//i.test(imageRef)) {
|
|
|
|
|
+ const refPath = path.resolve(imageRef)
|
|
|
|
|
+ let stat
|
|
|
|
|
+ try { stat = fs.statSync(refPath) } catch { fail('参考图不存在', `读不到 ${refPath}`) }
|
|
|
|
|
+ if (!stat.isFile()) fail('参考图不是文件', refPath)
|
|
|
|
|
+ if (stat.size > 10 * 1048576) fail('参考图太大', `${(stat.size / 1048576).toFixed(1)}MB,请压缩到 10MB 以内`)
|
|
|
|
|
+ const ext = path.extname(refPath).toLowerCase().replace('.', '') || 'png'
|
|
|
|
|
+ const mime = ext === 'jpg' ? 'jpeg' : ext
|
|
|
|
|
+ imageRef = `data:image/${mime};base64,${fs.readFileSync(refPath).toString('base64')}`
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (isMock()) {
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ mock: true,
|
|
|
|
|
+ model: requested,
|
|
|
|
|
+ prompt,
|
|
|
|
|
+ message: '当前是演示模式,没有真的出图;接入平台账号后会返回图片文件'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 演示模式不碰网络;真出图才要求网关地址(老版本 patch 没写这一项)
|
|
|
|
|
+ if (!imageBase) fail('缺少模型网关地址', '客户端启动时没有写入 llmBaseURL,请重启客户端;仍然失败请反馈')
|
|
|
|
|
+
|
|
|
|
|
+ const me = await user.resolve()
|
|
|
|
|
+ // 网关 key 优先:服务端单独下发的那把才可能带图像渠道。
|
|
|
|
|
+ const key = readAuth().llmKey || me.apiKey || token()
|
|
|
|
|
+ if (!key) fail('还没有登录账号', '请先在客户端完成登录')
|
|
|
|
|
+
|
|
|
|
|
+ // 参考图要求模型本身吃图像输入:t2i(text-to-image)型号会静默忽略 image,
|
|
|
|
|
+ // 出图跟参考图毫无关系却不报错,是最坏的情况,所以带参考图时直接把它换掉。
|
|
|
|
|
+ const canUseReference = (m) => !/t2i/i.test(m)
|
|
|
|
|
+ if (imageRef && !canUseReference(requested)) requested = IMAGE_MODEL_PREFERRED
|
|
|
|
|
+
|
|
|
|
|
+ // 候选链:老师/调用方指定的 → 首选 → 已开通的兜底,去重后按顺序试
|
|
|
|
|
+ const chain = [...new Set([requested, IMAGE_MODEL_PREFERRED, IMAGE_MODEL_READY])].filter(Boolean)
|
|
|
|
|
+ const usable = chain.filter(imageModelUsable)
|
|
|
|
|
+ const attempts = (usable.length ? usable : [IMAGE_MODEL_READY])
|
|
|
|
|
+ .filter((m) => !imageRef || canUseReference(m))
|
|
|
|
|
+ if (!attempts.length) {
|
|
|
|
|
+ fail('没有可用于图生图的模型', '当前只开通了纯文生图(t2i)模型,需要平台开通支持参考图的 seedream 4.0+ 或 seededit i2i')
|
|
|
|
|
+ }
|
|
|
|
|
+ let lastError = ''
|
|
|
|
|
+
|
|
|
|
|
+ for (const model of attempts) {
|
|
|
|
|
+ const body = { model, prompt, n: 1, size, response_format: 'b64_json' }
|
|
|
|
|
+ if (imageRef) body.image = imageRef
|
|
|
|
|
+
|
|
|
|
|
+ let res
|
|
|
|
|
+ try {
|
|
|
|
|
+ res = await fetch(`${imageBase}/images/generations`, {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
|
|
|
|
|
+ body: JSON.stringify(body)
|
|
|
|
|
+ })
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ fail('连不上模型网关', `${err.message};请检查网络后重试`)
|
|
|
|
|
+ }
|
|
|
|
|
+ const text = await res.text()
|
|
|
|
|
+ let json = null
|
|
|
|
|
+ try { json = text ? JSON.parse(text) : null } catch { /* 网关偶发返回 html */ }
|
|
|
|
|
+
|
|
|
|
|
+ if (!res.ok) {
|
|
|
|
|
+ const detail = (json && json.error && (json.error.message || json.error.code)) || text.slice(0, 200)
|
|
|
|
|
+ // 503=分组没有可用上游、404=没这个模型:都说明该模型现在用不了,换下一个
|
|
|
|
|
+ if (res.status === 503 || res.status === 404) {
|
|
|
|
|
+ imageModelBlocked.set(model, Date.now())
|
|
|
|
|
+ lastError = `${model}:${detail}`
|
|
|
|
|
+ continue
|
|
|
|
|
+ }
|
|
|
|
|
+ // 内容审核:换描述重试才有效,重试同一条只会再被拦一次
|
|
|
|
|
+ if (/Sensitive|sensitive/i.test(text)) {
|
|
|
|
|
+ fail('这个画面被内容审核拦下了', '换一种说法:去掉"解剖""人体"这类词,改成具体的教学场景描述再试')
|
|
|
|
|
+ }
|
|
|
|
|
+ fail(`图像接口返回 ${res.status}`, String(detail).slice(0, 200))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const list = json && (json.data || json.images || json.output)
|
|
|
|
|
+ const first = Array.isArray(list) ? list[0] : list
|
|
|
|
|
+ const url = first && (first.url || first.image_url || (typeof first === 'string' ? first : ''))
|
|
|
|
|
+ const b64 = first && (first.b64_json || first.b64)
|
|
|
|
|
+ if (!url && !b64) fail('图像接口没有返回图片', `返回内容:${text.slice(0, 200)}`)
|
|
|
|
|
+
|
|
|
|
|
+ // 先把字节拿到手:seedream 回的是 JPEG,文件名写 .png 会让一些软件打不开
|
|
|
|
|
+ let data = null
|
|
|
|
|
+ if (b64) {
|
|
|
|
|
+ data = Buffer.from(b64, 'base64')
|
|
|
|
|
+ } else {
|
|
|
|
|
+ const imgRes = await fetch(url)
|
|
|
|
|
+ if (!imgRes.ok) fail(`下载生成的图片失败(${imgRes.status})`, '生成成功了但没能存到本地,请重试一次')
|
|
|
|
|
+ data = Buffer.from(await imgRes.arrayBuffer())
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!data || !data.length) fail('生成的图片是空文件', '请重试一次;连续失败请反馈')
|
|
|
|
|
+
|
|
|
|
|
+ // 落盘:网关给的 url 有有效期,老师过几天再点就看不到了
|
|
|
|
|
+ const target = String(args.savePath || '').trim()
|
|
|
|
|
+ ? path.resolve(String(args.savePath).trim())
|
|
|
|
|
+ : path.join(workspaceDir || '.', 'images', `image-${Date.now()}${imageExtOf(data)}`)
|
|
|
|
|
+ fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
|
|
|
+ fs.writeFileSync(target, data)
|
|
|
|
|
+ const bytes = fs.statSync(target).size
|
|
|
|
|
+ if (!bytes) fail('生成的图片是空文件', '请重试一次;连续失败请反馈')
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ model,
|
|
|
|
|
+ requestedModel: requested,
|
|
|
|
|
+ fallback: model !== requested,
|
|
|
|
|
+ file: target,
|
|
|
|
|
+ size,
|
|
|
|
|
+ bytes,
|
|
|
|
|
+ prompt,
|
|
|
|
|
+ // true = 这张是按参考图改的;老师问"跟原来像不像"时据此回答
|
|
|
|
|
+ usedReference: Boolean(imageRef),
|
|
|
|
|
+ // 平台出图强制带右下角「AI生成」标识,watermark:false 实测无效,别向老师承诺能去掉
|
|
|
|
|
+ watermarked: true,
|
|
|
|
|
+ message: `图片已生成:${target}。告诉老师"图好了,存在这个位置"即可;右下角带平台的 AI 生成标识,不要说模型名或接口细节`
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ fail('图像服务当前不可用', `${lastError || '网关没有可用的图像模型'}。请平台侧确认 seedream 图像渠道已开通`)
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ===================================================== cococlass:建课件
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cococlass_courseware_create',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '在 cococlass 里创建一份课件(备课/一节课/课件/讲义)。' +
|
|
|
|
|
+ '老师说"帮我做一节课/把这节课备了/生成课件"时调用。' +
|
|
|
|
|
+ '工具自己会等生成结果:返回 done 时客户端右侧已经打开课件页面,跟老师说一声就好;' +
|
|
|
|
|
+ '返回 running 时右侧打开的是进度页,告诉老师还在生成,不要连续调用本工具。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ title: { type: 'string', required: true, description: '课件标题,例如"认识三角形"' },
|
|
|
|
|
+ subject: { type: 'string', description: '学科,例如 数学 / 物理 / 语文' },
|
|
|
|
|
+ grade: { type: 'string', description: '学段年级,例如 三年级 / 八年级' },
|
|
|
|
|
+ duration: { type: 'number', description: '课时长度(分钟),默认 40' },
|
|
|
|
|
+ requirements: { type: 'string', description: '老师的额外要求,例如"多举生活例子,结尾带课堂练习"' },
|
|
|
|
|
+ outline: {
|
|
|
|
|
+ type: 'array',
|
|
|
|
|
+ items: { type: 'string' },
|
|
|
|
|
+ description: '已和老师确认过的页面大纲;有就传,避免模型重新发挥'
|
|
|
|
|
+ }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 120_000,
|
|
|
|
|
+ async execute (args, exec) {
|
|
|
|
|
+ if (!args.title) fail('缺少课件标题', '先问老师这节课讲什么')
|
|
|
|
|
+ const payload = {
|
|
|
|
|
+ title: String(args.title).trim(),
|
|
|
|
|
+ subject: args.subject || '',
|
|
|
|
|
+ grade: args.grade || '',
|
|
|
|
|
+ duration: Number(args.duration) || 40,
|
|
|
|
|
+ requirements: args.requirements || '',
|
|
|
|
|
+ outline: Array.isArray(args.outline) ? args.outline : [],
|
|
|
|
|
+ source: 'cocorobo-workspace'
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (isMock()) {
|
|
|
|
|
+ const created = mockCreateTask('courseware', payload)
|
|
|
|
|
+ const final = await waitTask(created.taskId, { timeoutMs: 20_000, signal: exec.signal, initial: created })
|
|
|
|
|
+ return { ok: true, ...final, openUrl: pageUrl('cococlass', final.coursewareId || final.id || '') }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const created = await api('/cococlass/courseware/drafts', {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ body: JSON.stringify(payload),
|
|
|
|
|
+ headers: { 'idempotency-key': idempotencyKey('cw') },
|
|
|
|
|
+ signal: exec.signal
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ const taskId = created.taskId || created.id
|
|
|
|
|
+ if (!taskId) {
|
|
|
|
|
+ // 同步返回(小课件直接生成完):原样交回给模型,只补一个能直接打开的页面地址
|
|
|
|
|
+ return { ok: true, status: 'done', ...created, openUrl: pageUrl('cococlass', created.coursewareId || created.id || '') }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const final = await waitTask(taskId, { timeoutMs: waitMs, signal: exec.signal, initial: created })
|
|
|
|
|
+ const done = stateOf(final) === 'done'
|
|
|
|
|
+ const coursewareId = final.coursewareId || final.id || ''
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ status: done ? 'done' : 'running',
|
|
|
|
|
+ taskId,
|
|
|
|
|
+ title: final.title || payload.title,
|
|
|
|
|
+ coursewareId,
|
|
|
|
|
+ pageCount: final.pageCount || final.pages || null,
|
|
|
|
|
+ previewUrl: final.previewUrl || final.resultUrl || '',
|
|
|
|
|
+ editUrl: final.editUrl || '',
|
|
|
|
|
+ // 客户端右侧会自动打开这个地址(老师不用再复制链接到浏览器)
|
|
|
|
|
+ openUrl: pageUrl('cococlass', coursewareId),
|
|
|
|
|
+ progress: final.progress || null,
|
|
|
|
|
+ stage: final.stage || '',
|
|
|
|
|
+ progressUrl: final.previewUrl || `${apiBase}/agent/v1/tasks/${taskId}`,
|
|
|
|
|
+ message: done
|
|
|
|
|
+ ? '课件已生成,客户端右侧已打开课件页面;简单说一句"做好了,右边可以看",再问是否要发布到班级'
|
|
|
|
|
+ : '平台还在生成,客户端右侧已打开进度页;告诉老师可以继续等,不要连续重复调用本工具'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ======================================= cococlass:本地 PPTX 直接建课
|
|
|
|
|
+ // 平台的 PPT 解析完全在前端(ppt.cocorobo.cn 的 importPPTXFile:FileReader
|
|
|
|
|
+ // 读 ArrayBuffer → JSZip 拆 pptx → 转成 slides JSON → 图片传 S3 → 保存)。
|
|
|
|
|
+ // 这条链路没有对外接口,解析函数也没挂到 window 上,唯一入口是页面里的
|
|
|
|
|
+ // 上传控件(`.file-input` + `input[name=upload][accept=".pptx,.ppt,.pdf"]`)。
|
|
|
|
|
+ // 所以这里不重写解析,只把文件交给页面:工具结果带 uploadFile,
|
|
|
|
|
+ // 客户端右侧打开编辑器后构造 File 走该控件的 drop / change,
|
|
|
|
|
+ // 等于老师手选文件,后面全由平台自己的代码跑完。
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cococlass_course_from_pptx',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '把本地已生成的 PPTX 交给 cococlass 平台解析成课程。' +
|
|
|
|
|
+ '老师说"把这份 PPT 建成课程/传到 cococlass"且文件已存在时调用;' +
|
|
|
|
|
+ '还没有文件就先用 PPT 生成技能把 .pptx 做出来。' +
|
|
|
|
|
+ '有课程 id 就传 courseid(导进已有课程),没有就打开建课页新建。' +
|
|
|
|
|
+ '调用后右侧会自动填文件并开始解析,告诉老师看右侧即可。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ pptxPath: { type: 'string', required: true, description: 'PPTX 文件绝对路径(技能生成后的输出路径)' },
|
|
|
|
|
+ courseid: { type: 'string', description: '已有课程 id;不传则走新建课程' },
|
|
|
|
|
+ title: { type: 'string', description: '课程名,仅用于对话说明' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 20_000,
|
|
|
|
|
+ async execute (args, exec) {
|
|
|
|
|
+ void exec
|
|
|
|
|
+ const file = String(args.pptxPath || '').trim()
|
|
|
|
|
+ if (!file) fail('缺少 pptxPath', '先确认 PPT 文件的实际路径')
|
|
|
|
|
+ if (!/\.pptx$/i.test(file)) fail('只支持 .pptx 文件', `收到的是 ${file};请先用 PPT 技能导出 .pptx`)
|
|
|
|
|
+ let size = 0
|
|
|
|
|
+ try {
|
|
|
|
|
+ size = fs.statSync(file).size
|
|
|
|
|
+ if (size <= 0) throw new Error('empty')
|
|
|
|
|
+ } catch {
|
|
|
|
|
+ fail('PPTX 文件不存在或为空', `路径 ${file} 读不到;确认生成步骤是否真的完成了`)
|
|
|
|
|
+ }
|
|
|
|
|
+ const id = await user.resolve({ needKey: false })
|
|
|
|
|
+ const courseid = String(args.courseid || '').trim()
|
|
|
|
|
+ const q = new URLSearchParams()
|
|
|
|
|
+ q.set('mode', 'editor3')
|
|
|
|
|
+ if (id.userid) q.set('userid', id.userid)
|
|
|
|
|
+ if (courseid) q.set('courseid', courseid)
|
|
|
|
|
+ // 有课程 id → 直接进编辑器;没课程 id → 开门户页,让它进教学中心并弹出
|
|
|
|
|
+ //「创建新课程」(弹窗里的上传控件一渲染就有,文件用 drop 投进去,不点它,
|
|
|
|
|
+ // 点它会拉起系统文件框)。
|
|
|
|
|
+ const openUrl = courseid
|
|
|
|
|
+ ? `${pptBase}/?${q.toString()}`
|
|
|
|
|
+ : String(config.cococlassUrl || '').trim() || `${portalBase}/`
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ status: 'uploading',
|
|
|
|
|
+ title: String(args.title || '').trim(),
|
|
|
|
|
+ courseid,
|
|
|
|
|
+ file,
|
|
|
|
|
+ size,
|
|
|
|
|
+ openUrl,
|
|
|
|
|
+ uploadFile: {
|
|
|
|
|
+ path: file,
|
|
|
|
|
+ name: file.split(/[\\/]/).pop(),
|
|
|
|
|
+ clickText: courseid ? [] : ['教学中心', '创建课程', '创建新课程', '新建课程'],
|
|
|
|
|
+ urlMatch: 'cocorobo'
|
|
|
|
|
+ },
|
|
|
|
|
+ message: '已在右侧打开页面并把文件交给平台解析;解析完会自己跳转,不要重复调用本工具'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ==================================================== cocoflow:建智能体
|
|
|
|
|
+ // 真实接口(appapi.cocorobo.cn,浏览器抓包对齐):
|
|
|
|
|
+ // POST /api/agents/agent 建智能体骨架,返回 id / assistant_id / thread_id
|
|
|
|
|
+ // PUT /api/agents/agent/{id} 写入提示词等完整配置
|
|
|
|
|
+ // 创建会在老师账号里留下真智能体,所以拆成两把工具:
|
|
|
|
|
+ // cocoflow_agent_plan 只出方案,不落库
|
|
|
|
|
+ // cocoflow_agent_create 必须等老师明确说"创建"才允许调(confirmed 门禁)
|
|
|
|
|
+ const COCOFLOW_DEFAULT_HEAD_URL =
|
|
|
|
|
+ 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/default%2F%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F11741770951146.png'
|
|
|
|
|
+ const COCOFLOW_DEFAULT_JSON_DATA = JSON.stringify({
|
|
|
|
|
+ voiceInteractionMode: false, syncTranscriptionText: false, autoPlay: false, sttLanguage: 'zh-CN', cyid: ''
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ const cocoflow = {
|
|
|
|
|
+ apiBase: String(config.cocoflowApiBase || 'https://appapi.cocorobo.cn').replace(/\/+$/, ''),
|
|
|
|
|
+ modelType: String(config.cocoflowModelType || 'open-doubao'),
|
|
|
|
|
+ headUrl: String(config.cocoflowHeadUrl || COCOFLOW_DEFAULT_HEAD_URL),
|
|
|
|
|
+ userId: String(config.cocoflowUserId || '').trim(),
|
|
|
|
|
+ username: String(config.cocoflowUsername || '').trim(),
|
|
|
|
|
+ organizeId: String(config.cocoflowOrganizeId || '').trim(),
|
|
|
|
|
+ token: String(config.cocoflowToken || '').trim(),
|
|
|
|
|
+ cookie: String(config.cocoflowCookie || '').trim(),
|
|
|
|
|
+ // cocoflow 自己的 mock 开关:没单独配就跟随全局 mock。
|
|
|
|
|
+ // 想只测 cocoflow 真实接口,把 config.json 里 cocoflowMock 设 false 即可。
|
|
|
|
|
+ mock: typeof config.cocoflowMock === 'boolean' ? config.cocoflowMock : null
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const cfMock = () => (cocoflow.mock !== null ? cocoflow.mock : isMock())
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * cocoflow 的身份:**登录授权带回的为准**(authFile 的 userid/username/organizeId,
|
|
|
|
|
+ * 与 cocorobo://auth/callback 里的 userid/organizeid 同源)。
|
|
|
|
|
+ * 授权没带 organizeid 时由用户中心按 userid 去平台补全,config 里的
|
|
|
|
|
+ * cocoflowUserId / cocoflowOrganizeId 只在没登录或 mock 登录时兜底。
|
|
|
|
|
+ * mock 登录的 mock-teacher 绝不能当成真 userId 传给平台。
|
|
|
|
|
+ */
|
|
|
|
|
+ async function cfIdentity () {
|
|
|
|
|
+ // cocoflow 走 cookie/Bearer,不强制要求 apiKey;这里只关心"人是谁、属于哪个机构"
|
|
|
|
|
+ const id = await user.resolve({ needKey: false })
|
|
|
|
|
+ const authorized = !id.mock && !String(id.userid || '').startsWith('mock')
|
|
|
|
|
+ return {
|
|
|
|
|
+ userId: (authorized && id.userid) || cocoflow.userId || '',
|
|
|
|
|
+ username: (authorized && id.username) || cocoflow.username || '老师',
|
|
|
|
|
+ organizeId: (authorized && id.organizeId) || cocoflow.organizeId || '',
|
|
|
|
|
+ source: id.source
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** appapi 没有 /agent/v1 前缀,凭据形态也不同(浏览器抓的是 cookie),单独一个请求函数。 */
|
|
|
|
|
+ async function cfApi (pathname, init = {}) {
|
|
|
|
|
+ const headers = { 'content-type': 'application/json', ...(init.headers || {}) }
|
|
|
|
|
+ const tk = cocoflow.token || token()
|
|
|
|
|
+ if (tk) headers.authorization = `Bearer ${tk}`
|
|
|
|
|
+ if (cocoflow.cookie) headers.cookie = cocoflow.cookie
|
|
|
|
|
+ // 排查用:SKILL.md 里看不到任何接口地址,真正打 appapi 的是这里。
|
|
|
|
|
+ // 只记方法/路径/状态码,不记 body(body 里有老师的提示词全文)。
|
|
|
|
|
+ const method = String(init.method || 'GET').toUpperCase()
|
|
|
|
|
+ const startedAt = Date.now()
|
|
|
|
|
+ const authUsed = cocoflow.cookie && tk ? 'cookie+bearer' : (cocoflow.cookie ? 'cookie' : (tk ? 'bearer' : '无凭据'))
|
|
|
|
|
+ console.log(`[cocoflow] → ${method} ${pathname}(鉴权 ${authUsed})`)
|
|
|
|
|
+ let res
|
|
|
|
|
+ try {
|
|
|
|
|
+ res = await fetch(`${cocoflow.apiBase}${pathname}`, { ...init, headers, signal: init.signal })
|
|
|
|
|
+ console.log(`[cocoflow] ← ${method} ${pathname} ${res.status} ${Date.now() - startedAt}ms`)
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ console.log(`[cocoflow] ✗ ${method} ${pathname} ${err && err.message} ${Date.now() - startedAt}ms`)
|
|
|
|
|
+ if (err && err.name === 'AbortError') throw err
|
|
|
|
|
+ fail(`连不上 cocoflow 接口 ${pathname}`, `${err.message};请检查网络`)
|
|
|
|
|
+ }
|
|
|
|
|
+ const text = await res.text()
|
|
|
|
|
+ let json = null
|
|
|
|
|
+ try { json = text ? JSON.parse(text) : null } catch { /* 非 JSON */ }
|
|
|
|
|
+ if (!res.ok) {
|
|
|
|
|
+ const msg = json && (json.message || json.msg || json.error)
|
|
|
|
|
+ fail(`cocoflow 接口 ${pathname} 返回 ${res.status}`, msg || text.slice(0, 200))
|
|
|
|
|
+ }
|
|
|
|
|
+ if (json === null) fail(`cocoflow 接口 ${pathname} 返回的不是 JSON`, text.slice(0, 200))
|
|
|
|
|
+ return json
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** 从需求里起个默认名,老师不满意会改,所以只求"像个名字"。 */
|
|
|
|
|
+ function suggestName (args) {
|
|
|
|
|
+ if (args.name) return String(args.name).trim().slice(0, 20)
|
|
|
|
|
+ const grade = args.grade || ''
|
|
|
|
|
+ const subject = args.subject || ''
|
|
|
|
|
+ if (subject) return `${grade}${subject}助手`.slice(0, 20)
|
|
|
|
|
+ return '我的智能体'
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** 提示词初稿:结构化模板比让模型自由发挥稳定,老师后续会改。 */
|
|
|
|
|
+ function draftInstructions (name, args) {
|
|
|
|
|
+ const out = []
|
|
|
|
|
+ out.push('# 角色')
|
|
|
|
|
+ out.push(`你是「${name}」,服务对象是${args.grade || '中小学'}的${args.subject || ''}学生与老师。`)
|
|
|
|
|
+ if (args.tone) out.push(`说话风格:${args.tone}。`)
|
|
|
|
|
+ out.push('', '# 职责')
|
|
|
|
|
+ out.push(String(args.need || '').trim())
|
|
|
|
|
+ const steps = Array.isArray(args.steps) ? args.steps.filter(Boolean) : []
|
|
|
|
|
+ if (steps.length) {
|
|
|
|
|
+ out.push('', '# 工作流程')
|
|
|
|
|
+ steps.forEach((s, i) => out.push(`${i + 1}. ${s}`))
|
|
|
|
|
+ }
|
|
|
|
|
+ out.push('', '# 输出要求')
|
|
|
|
|
+ out.push('- 用中文回答,结论清晰、可直接使用。')
|
|
|
|
|
+ if (args.boundaries) out.push(`- ${args.boundaries}`)
|
|
|
|
|
+ out.push('- 超出职责范围的问题,礼貌说明并建议向老师求助。')
|
|
|
|
|
+ return out.join('\n')
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocoflow_agent_plan',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '老师想做一个 cocoflow 智能体时的第一步:把需求整理成「名称 + 简介 + 提示词」方案。' +
|
|
|
|
|
+ '本工具不创建任何东西、不碰平台接口。' +
|
|
|
|
|
+ '拿到方案后必须把名称/简介/提示词完整展示给老师,并问"就按这个在 cocoflow 创建吗?"——' +
|
|
|
|
|
+ '老师明确回复"创建/确认/可以"之前,禁止调用 cocoflow_agent_create。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ need: { type: 'string', required: true, description: '老师的原话需求,例如"想要一个帮学生改作文的助手"' },
|
|
|
|
|
+ subject: { type: 'string', description: '学科' },
|
|
|
|
|
+ grade: { type: 'string', description: '学段年级' },
|
|
|
|
|
+ tone: { type: 'string', description: '说话风格,例如"像耐心的老师,多用提问引导"' },
|
|
|
|
|
+ steps: { type: 'array', items: { type: 'string' }, description: '做事顺序(3–6 步),老师没说就按学科常识补并列出来让老师过目' },
|
|
|
|
|
+ boundaries: { type: 'string', description: '边界规则,例如"不要直接给答案,先给提示"' },
|
|
|
|
|
+ name: { type: 'string', description: '老师已经定好的名字;没定就省略,用工具起的默认名' },
|
|
|
|
|
+ instructions: { type: 'string', description: '老师自己写好了完整提示词时填这里,原样采用、不再改写' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 20_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ if (!args.need && !args.instructions) fail('缺少需求描述', '先问老师想要一个什么样的助手')
|
|
|
|
|
+ const name = suggestName(args)
|
|
|
|
|
+ const instructions = String(args.instructions || '').trim() || draftInstructions(name, args)
|
|
|
|
|
+ const description = String(args.need || '').trim().slice(0, 60)
|
|
|
|
|
+ return {
|
|
|
|
|
+ plan: { assistantName: name, description, instructions },
|
|
|
|
|
+ message:
|
|
|
|
|
+ '这是准备在 cocoflow 创建的方案(还未创建)。把 plan 里的名称/简介/提示词完整展示给老师,' +
|
|
|
|
|
+ '问"就按这个创建吗?要改哪里直接说"。老师明确同意后,把确认过的 assistantName/description/' +
|
|
|
|
|
+ 'instructions 原样传给 cocoflow_agent_create 并把 confirmed 设为 true;老师没同意前不要调。'
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocoflow_agent_create',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '在 cocoflow 里真正创建智能体并写入提示词(POST 建骨架 + PUT 写提示词,两步都做完才算成功)。' +
|
|
|
|
|
+ '硬性规则:必须先用 cocoflow_agent_plan 出方案并给老师确认,老师明确回复"创建/确认/可以"后才能调用;' +
|
|
|
|
|
+ '老师还在讨论、修改、犹豫时禁止调用。assistantName/description/instructions 要传老师确认过的版本,不要自己改写。' +
|
|
|
|
|
+ '创建成功后客户端右侧会自动打开智能体页面,不要自己拼链接发给老师。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ assistantName: { type: 'string', required: true, description: '老师确认过的智能体名称' },
|
|
|
|
|
+ description: { type: 'string', required: true, description: '老师确认过的一句话简介' },
|
|
|
|
|
+ instructions: { type: 'string', required: true, description: '老师确认过的提示词全文,原样传入' },
|
|
|
|
|
+ confirmed: {
|
|
|
|
|
+ type: 'boolean',
|
|
|
|
|
+ required: true,
|
|
|
|
|
+ description: '仅当老师在对话里明确同意创建后才能为 true;false 时本工具直接拒绝执行'
|
|
|
|
|
+ },
|
|
|
|
|
+ modelType: { type: 'string', description: '模型类型,默认 open-doubao,老师没提就不要传' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 60_000,
|
|
|
|
|
+ async execute (args, exec) {
|
|
|
|
|
+ // 门禁:宁可多问一句,也不能在老师账号里留下没确认过的智能体
|
|
|
|
|
+ if (!args.confirmed) {
|
|
|
|
|
+ fail('老师还没有明确同意创建', '先用 cocoflow_agent_plan 出方案给老师确认,老师回复"创建"后再来')
|
|
|
|
|
+ }
|
|
|
|
|
+ const assistantName = String(args.assistantName || '').trim()
|
|
|
|
|
+ const description = String(args.description || '').trim()
|
|
|
|
|
+ const instructions = String(args.instructions || '').trim()
|
|
|
|
|
+ if (!assistantName) fail('缺少智能体名称', '回上一步让老师定个名字')
|
|
|
|
|
+ if (!instructions) fail('缺少提示词', '回上一步把提示词跟老师确认好')
|
|
|
|
|
+
|
|
|
|
|
+ if (cfMock()) {
|
|
|
|
|
+ const agentId = `ag-${Date.now().toString(36)}`
|
|
|
|
|
+ mockAgents.push({ agentId, assistantName, description, instructions, createdAt: new Date().toISOString() })
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: true,
|
|
|
|
|
+ status: 'done',
|
|
|
|
|
+ mock: true,
|
|
|
|
|
+ agentId,
|
|
|
|
|
+ name: assistantName,
|
|
|
|
|
+ openUrl: pageUrl('agent', agentId),
|
|
|
|
|
+ message: `智能体「${assistantName}」已创建(mock),提示词 ${instructions.length} 字;客户端右侧已打开智能体页面`
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const me = await cfIdentity()
|
|
|
|
|
+ if (!me.userId) {
|
|
|
|
|
+ fail('读不到老师账号(userid)',
|
|
|
|
|
+ '客户端里重新登录一次即可;仍在登录态的话,说明登录回调没有带回 userid,让平台侧确认回调参数')
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!me.organizeId) {
|
|
|
|
|
+ fail('读不到老师所属机构(organizeId)',
|
|
|
|
|
+ '已按当前 userid 向平台补全过但仍为空:请确认登录回调带上 organizeid,或在 config.json 里配置 cocoflowOrganizeId')
|
|
|
|
|
+ }
|
|
|
|
|
+ const modelType = String(args.modelType || cocoflow.modelType)
|
|
|
|
|
+
|
|
|
|
|
+ // 第一步:建骨架
|
|
|
|
|
+ const created = await cfApi('/api/agents/agent', {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ body: JSON.stringify({
|
|
|
|
|
+ userId: me.userId,
|
|
|
|
|
+ username: me.username,
|
|
|
|
|
+ assistantName,
|
|
|
|
|
+ isRetrieval: 0,
|
|
|
|
|
+ isCode: 0,
|
|
|
|
|
+ isGoogle: 0,
|
|
|
|
|
+ isDalleImage: 0,
|
|
|
|
|
+ organize_id: me.organizeId,
|
|
|
|
|
+ vector_store_id: '',
|
|
|
|
|
+ modelType,
|
|
|
|
|
+ inputMode: 'text',
|
|
|
|
|
+ outputMode: 'text',
|
|
|
|
|
+ headUrl: cocoflow.headUrl,
|
|
|
|
|
+ description,
|
|
|
|
|
+ jsonData: ''
|
|
|
|
|
+ }),
|
|
|
|
|
+ signal: exec.signal
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ const agentId = created.id || created.agentId || ''
|
|
|
|
|
+ if (!agentId) fail('平台没有返回智能体 id', JSON.stringify(created).slice(0, 200))
|
|
|
|
|
+
|
|
|
|
|
+ // 第二步:写提示词。失败不吞掉 —— 智能体已经建出来,老师必须知道提示词没写进去
|
|
|
|
|
+ let promptWritten = true
|
|
|
|
|
+ let promptError = ''
|
|
|
|
|
+ try {
|
|
|
|
|
+ await cfApi(`/api/agents/agent/${encodeURIComponent(agentId)}`, {
|
|
|
|
|
+ method: 'PUT',
|
|
|
|
|
+ body: JSON.stringify({
|
|
|
|
|
+ prologue: null,
|
|
|
|
|
+ description,
|
|
|
|
|
+ instructions,
|
|
|
|
|
+ isAutoReply: 0,
|
|
|
|
|
+ file_ids: '',
|
|
|
|
|
+ file_names: '',
|
|
|
|
|
+ folder_ids: '',
|
|
|
|
|
+ folder_names: '',
|
|
|
|
|
+ modelType,
|
|
|
|
|
+ functionNames: '',
|
|
|
|
|
+ functionContents: '[]',
|
|
|
|
|
+ tools: [{ type: 'file_search' }],
|
|
|
|
|
+ inputMode: 'text',
|
|
|
|
|
+ outputMode: 'text',
|
|
|
|
|
+ vector_store_id: created.vector_store_id || '',
|
|
|
|
|
+ assistantName,
|
|
|
|
|
+ jsonData: cocoflow.jsonData || COCOFLOW_DEFAULT_JSON_DATA
|
|
|
|
|
+ }),
|
|
|
|
|
+ signal: exec.signal
|
|
|
|
|
+ })
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ promptWritten = false
|
|
|
|
|
+ promptError = err.message
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ ok: promptWritten,
|
|
|
|
|
+ status: 'done',
|
|
|
|
|
+ agentId,
|
|
|
|
|
+ assistantId: created.assistant_id || '',
|
|
|
|
|
+ threadId: created.thread_id || '',
|
|
|
|
|
+ name: created.assistantName || assistantName,
|
|
|
|
|
+ // 客户端右侧会自动打开这个地址(智能体详情页)
|
|
|
|
|
+ openUrl: pageUrl('agent', agentId),
|
|
|
|
|
+ promptWritten,
|
|
|
|
|
+ ...(promptWritten ? {} : { promptError }),
|
|
|
|
|
+ message: promptWritten
|
|
|
|
|
+ ? `智能体「${assistantName}」已创建,提示词已写入,客户端右侧已打开。告诉老师知识库与发布还要在网页端操作即可`
|
|
|
|
|
+ : `智能体「${assistantName}」已创建,但提示词写入失败:${promptError}。让老师到右侧页面手动补,或调整后重试`
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ================================================== 可选能力(默认关闭)
|
|
|
|
|
+ if (extras) {
|
|
|
|
|
+ // 原来这里有个 cocorobo_whoami(打平台 /me 取账号+班级)。账号信息已由常驻的
|
|
|
|
|
+ // cocorobo_user_profile 提供(且不依赖 /me 是否上线),班级由下面的 class_list 负责,
|
|
|
|
|
+ // 所以合并掉,避免两把工具对"我是谁"给出不同答案。
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cococlass_class_list',
|
|
|
|
|
+ description: '列出可发布的班级(含 classId),发布课件前用它取 id。',
|
|
|
|
|
+ parameters: params({ keyword: { type: 'string', description: '按班级名筛选' } }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 20_000,
|
|
|
|
|
+ async execute ({ keyword }, exec) {
|
|
|
|
|
+ if (isMock()) {
|
|
|
|
|
+ return { classes: keyword ? MOCK_CLASSES.filter((c) => c.name.includes(keyword)) : MOCK_CLASSES }
|
|
|
|
|
+ }
|
|
|
|
|
+ const q = keyword ? `?keyword=${encodeURIComponent(keyword)}` : ''
|
|
|
|
|
+ return api(`/cococlass/classes${q}`, { signal: exec.signal })
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cococlass_courseware_status',
|
|
|
|
|
+ description: '查询课件生成任务进度(创建时已自动等待,只有在需要追问进度时才用)。',
|
|
|
|
|
+ parameters: params({ taskId: { type: 'string', required: true } }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 20_000,
|
|
|
|
|
+ async execute ({ taskId }, exec) {
|
|
|
|
|
+ if (isMock()) return mockTaskState(taskId)
|
|
|
|
|
+ return api(`/tasks/${encodeURIComponent(taskId)}`, { signal: exec.signal })
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cococlass_courseware_publish',
|
|
|
|
|
+ description: '把课件发布到班级(写操作,必须老师明确同意后再调用)。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ coursewareId: { type: 'string', required: true },
|
|
|
|
|
+ classId: { type: 'string', required: true },
|
|
|
|
|
+ publishAt: { type: 'string', description: '预约时间 ISO8601,留空立即发布' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 30_000,
|
|
|
|
|
+ async execute ({ coursewareId, classId, publishAt }, exec) {
|
|
|
|
|
+ if (isMock()) {
|
|
|
|
|
+ const cls = MOCK_CLASSES.find((c) => c.id === classId)
|
|
|
|
|
+ if (!cls) fail(`找不到班级 ${classId}`)
|
|
|
|
|
+ return {
|
|
|
|
|
+ published: true,
|
|
|
|
|
+ coursewareId,
|
|
|
|
|
+ classId,
|
|
|
|
|
+ className: cls.name,
|
|
|
|
|
+ publishAt: publishAt || new Date().toISOString(),
|
|
|
|
|
+ shareUrl: `${apiBase}/cococlass/class/${classId}?cw=${coursewareId}`
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return api(`/cococlass/courseware/${encodeURIComponent(coursewareId)}/publish`, {
|
|
|
|
|
+ method: 'POST',
|
|
|
|
|
+ body: JSON.stringify({ classId, publishAt: publishAt || null }),
|
|
|
|
|
+ signal: exec.signal
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ============================================ 浏览器:真的上网干活
|
|
|
|
|
+ // 引擎自身没有"操作网页"的工具(右侧栏只是展示),老师要查资料/盯竞品/填表单时
|
|
|
|
|
+ // 模型只能说"我没有联网能力"。这里用 Chrome/Edge 的 DevTools 协议自己开一个
|
|
|
|
|
+ // 独立浏览器实例(独立 profile,不碰老师日常浏览器),把常用动作暴露成一把工具。
|
|
|
|
|
+ const browser = createBrowserController({
|
|
|
|
|
+ userDataDir: workspaceDir ? path.join(workspaceDir, '.browser-profile') : '',
|
|
|
|
|
+ browserExe: config.browserExe,
|
|
|
|
|
+ headless: config.browserHeadless !== false
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_browser',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '用真实浏览器打开网页并操作它:读取正文、点按钮、填输入框、截图、跑一段页面脚本。' +
|
|
|
|
|
+ '老师要"上网查一下 / 打开这个链接看看 / 搜一下… / 把这个网页的内容整理出来 / 在网站上填个表"时用。' +
|
|
|
|
|
+ '典型顺序:action=open 拿 tabId → action=text 读内容(需要时 click/type)→ 再 text 确认结果。' +
|
|
|
|
|
+ '只支持 http/https;不能读本地文件,也不要用它登录老师的平台账号(平台页面走 cocorobo_open_page 在右侧打开)。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ action: {
|
|
|
|
|
+ type: 'string',
|
|
|
|
|
+ required: true,
|
|
|
|
|
+ enum: ['open', 'goto', 'text', 'click', 'type', 'screenshot', 'eval', 'tabs', 'close', 'quit'],
|
|
|
|
|
+ description: 'open=新开页面;goto=当前页跳转;text=取正文;click=点击;type=输入;screenshot=截图;eval=执行脚本;tabs=列出页签;close/quit=关页签/关浏览器'
|
|
|
|
|
+ },
|
|
|
|
|
+ url: { type: 'string', description: 'open / goto 时必填,http(s) 完整地址' },
|
|
|
|
|
+ tabId: { type: 'string', description: '页签 id(open 的返回里有);不填就用最近打开的那个' },
|
|
|
|
|
+ selector: { type: 'string', description: 'CSS 选择器。click 时可只给 text;type 时必填(如 input[name=q])' },
|
|
|
|
|
+ text: { type: 'string', description: 'click 时=按钮上的文字;type 时=要输入的内容' },
|
|
|
|
|
+ submit: { type: 'boolean', description: 'type 时是否提交(回车/提交表单)' },
|
|
|
|
|
+ index: { type: 'number', description: 'click 命中多个时点第几个,默认 0(第一个)' },
|
|
|
|
|
+ expression: { type: 'string', description: 'eval 时执行的 JS 表达式,返回可序列化值' },
|
|
|
|
|
+ file: { type: 'string', description: 'screenshot 保存路径,不填存到工作区 screenshots/' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 90_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ const action = String(args.action || '').trim()
|
|
|
|
|
+ const tabId = String(args.tabId || '').trim() || undefined
|
|
|
|
|
+ try {
|
|
|
|
|
+ if (action === 'open') return await browser.open(args.url)
|
|
|
|
|
+ if (action === 'goto') return await browser.goto(args.url, tabId)
|
|
|
|
|
+ if (action === 'text') return await browser.pageText(tabId, { selector: String(args.selector || 'body') })
|
|
|
|
|
+ if (action === 'click') {
|
|
|
|
|
+ return await browser.click(tabId, {
|
|
|
|
|
+ selector: String(args.selector || ''),
|
|
|
|
|
+ text: String(args.text || ''),
|
|
|
|
|
+ index: Number(args.index) || 0
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'type') {
|
|
|
|
|
+ if (!String(args.selector || '').trim()) fail('缺少 selector', '输入框要给出 CSS 选择器,例如 input[name=q];不确定就先取一次页面文字')
|
|
|
|
|
+ return await browser.type(tabId, {
|
|
|
|
|
+ selector: String(args.selector),
|
|
|
|
|
+ text: String(args.text ?? ''),
|
|
|
|
|
+ submit: args.submit === true
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'screenshot') {
|
|
|
|
|
+ const dir = workspaceDir || '.'
|
|
|
|
|
+ const file = String(args.file || '').trim() || path.join(dir, 'screenshots', `page-${Date.now()}.png`)
|
|
|
|
|
+ return await browser.screenshot(tabId, file)
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'eval') {
|
|
|
|
|
+ if (!String(args.expression || '').trim()) fail('缺少 expression', 'eval 需要一段 JS 表达式')
|
|
|
|
|
+ return { value: await browser.evaluate(tabId, args.expression) }
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'tabs') {
|
|
|
|
|
+ const list = await browser.listTabs()
|
|
|
|
|
+ return { tabs: list.map((t) => ({ id: t.id, title: t.title, url: t.url })) }
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'close') {
|
|
|
|
|
+ if (!tabId) fail('缺少 tabId', '先 action=tabs 看有哪些页签')
|
|
|
|
|
+ return await browser.closeTab(tabId)
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'quit') return await browser.quit()
|
|
|
|
|
+ fail(`不认识的 action:${action}`, '可选 open / goto / text / click / type / screenshot / eval / tabs / close / quit')
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ fail(err.message || '浏览器操作失败', '可以先用 action=tabs 看当前页面状态,或换一个网址重试')
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // ============================================ 本地 Office / PDF 文件
|
|
|
|
|
+ // 老师的工作常常落在 Word/Excel/PDF 上:读一份成绩表、把大纲写成文档、
|
|
|
|
|
+ // 把网页或讲义打成 PDF。这里直接读写文件,不依赖 WPS 界面(COM 会被安全策略拦)。
|
|
|
|
|
+ const writeRoots = [
|
|
|
|
|
+ workspaceDir,
|
|
|
|
|
+ path.join(process.env.USERPROFILE || process.env.HOME || '', 'Desktop'),
|
|
|
|
|
+ path.join(process.env.USERPROFILE || process.env.HOME || '', 'Documents'),
|
|
|
|
|
+ path.join(process.env.USERPROFILE || process.env.HOME || '', 'Downloads')
|
|
|
|
|
+ ].filter(Boolean).map((p) => path.resolve(p))
|
|
|
|
|
+
|
|
|
|
|
+ function checkWritePath (file) {
|
|
|
|
|
+ const target = path.resolve(String(file || ''))
|
|
|
|
|
+ const ok = writeRoots.some((root) => target === root || target.startsWith(root + path.sep))
|
|
|
|
|
+ if (!ok) fail('只能在 工作区 / 桌面 / 文档 / 下载 里创建文件', `收到的是 ${target}`)
|
|
|
|
|
+ return target
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ ctx.tools.register({
|
|
|
|
|
+ name: 'cocorobo_office',
|
|
|
|
|
+ description:
|
|
|
|
|
+ '读写老师电脑上的 Office 文件:读 docx/xlsx/pptx/pdf 的内容,生成 docx/xlsx/pptx,把 HTML 导成 PDF 或 PNG。' +
|
|
|
|
|
+ '老师说"看看这份文档/表格里写了什么""把这些内容整理成 Word/Excel""做一份 PPT 课件/说课稿""把这份讲义转成 PDF"时用。' +
|
|
|
|
|
+ 'read 支持 .docx/.xlsx/.pptx/.pdf;.doc/.xls/.ppt 老格式会报错,需要先另存为新格式。' +
|
|
|
|
|
+ 'write_pptx 生成 16:9 可编辑课件(标题/要点/配图),老师在 WPS 和 PowerPoint 里都能直接改。' +
|
|
|
|
|
+ 'html_to_pdf / html_to_png 把自写的 HTML(思维导图、板书、海报)导出成 PDF 或 PNG。' +
|
|
|
|
|
+ '中文 PDF 常见字体未内嵌,读出来是乱码——遇到会直接报"读不了",不要猜内容。',
|
|
|
|
|
+ parameters: params({
|
|
|
|
|
+ action: { type: 'string', required: true, enum: ['read', 'write_docx', 'write_xlsx', 'write_pptx', 'html_to_pdf', 'html_to_png'], description: '要做的操作' },
|
|
|
|
|
+ file: { type: 'string', required: true, description: '文件绝对路径。read 时是源文件;write_* 时是要生成的文件;html_to_pdf 时是 HTML 路径或网址' },
|
|
|
|
|
+ title: { type: 'string', description: 'write_docx 的文档标题;write_pptx 的封面主标题' },
|
|
|
|
|
+ blocks: {
|
|
|
|
|
+ type: 'array',
|
|
|
|
|
+ description: 'write_docx 的正文块:[{type:"heading",level:1,text:"…"} | {type:"paragraph",text:"…"} | {type:"bullet",text:"…"} | {type:"table",rows:[["列1","列2"],…]}]',
|
|
|
|
|
+ items: { type: 'object', additionalProperties: true }
|
|
|
|
|
+ },
|
|
|
|
|
+ sheets: {
|
|
|
|
|
+ type: 'array',
|
|
|
|
|
+ description: 'write_xlsx 的工作表:[{name:"成绩",rows:[["姓名","分数"],["张三",92]]}]',
|
|
|
|
|
+ items: { type: 'object', additionalProperties: true }
|
|
|
|
|
+ },
|
|
|
|
|
+ slides: {
|
|
|
|
|
+ type: 'array',
|
|
|
|
|
+ description: 'write_pptx 的页面(封面自动加):[{layout:"section"|"bullets"|"image"|"closing", title:"…", subtitle:"…", bullets:["…"], image:"配图绝对路径", note:"小字备注"}]',
|
|
|
|
|
+ items: { type: 'object', additionalProperties: true }
|
|
|
|
|
+ },
|
|
|
|
|
+ subtitle: { type: 'string', description: 'write_pptx 封面副标题,如"五年级数学 · 第 3 单元"' },
|
|
|
|
|
+ meta: { type: 'string', description: 'write_pptx 封面的署名行,如"授课教师:李老师"' },
|
|
|
|
|
+ footer: { type: 'string', description: 'write_pptx 每页左下角页脚,可不填' },
|
|
|
|
|
+ accent: { type: 'string', description: 'write_pptx 主色,十六进制如 #2563EB;不填用蓝色' },
|
|
|
|
|
+ closing: { type: 'string', description: 'write_pptx 结尾页文字,不填则不加结尾页' },
|
|
|
|
|
+ out: { type: 'string', description: 'html_to_pdf / html_to_png 的输出路径,不填则与 HTML 同名' },
|
|
|
|
|
+ width: { type: 'number', description: 'html_to_png 的画布宽度(像素),不填 1400' },
|
|
|
|
|
+ height: { type: 'number', description: 'html_to_png 的画布高度(像素),不填 900' }
|
|
|
|
|
+ }),
|
|
|
|
|
+ output: jsonOut,
|
|
|
|
|
+ timeoutMs: 120_000,
|
|
|
|
|
+ async execute (args) {
|
|
|
|
|
+ const action = String(args.action || '').trim()
|
|
|
|
|
+ const file = String(args.file || '').trim()
|
|
|
|
|
+ if (!file) fail('缺少 file', '给出文件的绝对路径')
|
|
|
|
|
+ if (action === 'read') {
|
|
|
|
|
+ const target = path.resolve(file)
|
|
|
|
|
+ let stat
|
|
|
|
|
+ try { stat = fs.statSync(target) } catch { fail('文件不存在', `读不到 ${target}`) }
|
|
|
|
|
+ if (stat.size > 60 * 1048576) fail('文件太大', `${(stat.size / 1048576).toFixed(0)}MB,超过 60MB 请先拆分`)
|
|
|
|
|
+ const result = readOfficeFile(target)
|
|
|
|
|
+ if (result.kind === 'pdf' && !result.readable) {
|
|
|
|
|
+ fail('这个 PDF 读不出文字', result.hint)
|
|
|
|
|
+ }
|
|
|
|
|
+ return { ...result, file: target, size: stat.size }
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'write_docx') {
|
|
|
|
|
+ const target = checkWritePath(file)
|
|
|
|
|
+ return writeDocx(target, { title: String(args.title || ''), blocks: Array.isArray(args.blocks) ? args.blocks : [] })
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'write_xlsx') {
|
|
|
|
|
+ const target = checkWritePath(file)
|
|
|
|
|
+ return writeXlsx(target, { sheets: Array.isArray(args.sheets) ? args.sheets : [] })
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'write_pptx') {
|
|
|
|
|
+ const target = checkWritePath(file)
|
|
|
|
|
+ const slides = Array.isArray(args.slides) ? args.slides : []
|
|
|
|
|
+ if (!slides.length) fail('没有页面内容', 'slides 里至少给一页:{layout:"bullets", title:"…", bullets:["…"]}')
|
|
|
|
|
+ return writePptx(target, {
|
|
|
|
|
+ title: String(args.title || '').trim(),
|
|
|
|
|
+ subtitle: String(args.subtitle || '').trim(),
|
|
|
|
|
+ meta: String(args.meta || '').trim(),
|
|
|
|
|
+ footer: String(args.footer || '').trim(),
|
|
|
|
|
+ accent: String(args.accent || '').trim(),
|
|
|
|
|
+ closing: String(args.closing || '').trim(),
|
|
|
|
|
+ slides
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'html_to_png') {
|
|
|
|
|
+ const out = String(args.out || '').trim() ||
|
|
|
|
|
+ (/^https?:\/\//i.test(file) ? path.join(workspaceDir || '.', 'png', `page-${Date.now()}.png`) : file.replace(/\.html?$/i, '') + '.png')
|
|
|
|
|
+ const target = checkWritePath(out)
|
|
|
|
|
+ return htmlToPng({ htmlPath: file, pngPath: target, browserExe: config.browserExe, width: args.width, height: args.height })
|
|
|
|
|
+ }
|
|
|
|
|
+ if (action === 'html_to_pdf') {
|
|
|
|
|
+ const out = String(args.out || '').trim() ||
|
|
|
|
|
+ (/^https?:\/\//i.test(file) ? path.join(workspaceDir || '.', 'pdf', `page-${Date.now()}.pdf`) : file.replace(/\.html?$/i, '') + '.pdf')
|
|
|
|
|
+ const target = checkWritePath(out)
|
|
|
|
|
+ return htmlToPdf({ htmlPath: file, pdfPath: target, browserExe: config.browserExe })
|
|
|
|
|
+ }
|
|
|
|
|
+ fail(`不认识的 action:${action}`, '可选 read / write_docx / write_xlsx / write_pptx / html_to_pdf / html_to_png')
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ // 这行只用于启动日志里给排查的人看,必须跟上面实际 register 的工具一致
|
|
|
|
|
+ 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']
|
|
|
|
|
+ const list = extras
|
|
|
|
|
+ ? [...base, 'cococlass_class_list', 'cococlass_courseware_status', 'cococlass_courseware_publish']
|
|
|
|
|
+ : base
|
|
|
|
|
+ console.log(`[cocorobo] 已注册 ${list.length} 个工具:${list.join(' / ')}(cocoflow ${cfMock() ? 'mock 模式' : cocoflow.apiBase})`)
|
|
|
|
|
+}
|