diff --git a/README.md b/README.md index aeec38bd..1ecbdab5 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | MiniApp | What it does | Author | | --- | --- | --- | +| [Work Group](plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/) | A chat-style work group where several MiniMax Code Agents reply in one thread, mention each other to hand work over, and ask you for tool approvals and answers as cards in the page | [liuhaolin07](https://github.com/liuhaolin07) | | [Prompt Enhancer](plugins/skypata/prompt-enhancer/) | Rewrite a one-line request into a complete prompt for a coding assistant; the model list and reasoning levels come from MiniMax Code's own configuration, and the rewrite runs on your signed-in account | [skypata](https://github.com/skypata) | | [Postman Lite](plugins/ssugarr/postman-lite/) | A lightweight local API request tool: build requests, send them through a local proxy that sidesteps browser CORS limits, and inspect responses, with collections kept as plain JSON | [ssugarr](https://github.com/ssugarr) | | [Weekly Planner](plugins/alanhean/weekly-planner/) | A local weekly planner: add tasks with a date and a priority, review them day by day, tick them off, and track the week's completion rate | [Alanhean](https://github.com/Alanhean) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 65903d90..fcb80016 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -57,6 +57,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | MiniApp | 功能 | 作者 | | --- | --- | --- | +| [工作群](plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.zh-CN.md) | 聊天式工作群:多个 MiniMax Code Agent 在同一个群里回复、互相 @ 接力,工具审批和提问以卡片形式在页面里完成 | [liuhaolin07](https://github.com/liuhaolin07) | | [提示词增强器](plugins/skypata/prompt-enhancer/) | 把一句话改写成可以直接交给编码助手的完整提示词,模型清单与推理等级取自 MiniMax Code 自己的配置,改写走你已登录的账号 | [skypata](https://github.com/skypata) | | [Postman Lite](plugins/ssugarr/postman-lite/README.zh-CN.md) | 轻量的本地 API 请求工具:构建请求、通过本地代理转发(绕过浏览器 CORS 限制)、查看响应,集合以纯 JSON 保存 | [ssugarr](https://github.com/ssugarr) | | [周计划](plugins/alanhean/weekly-planner/README.zh-CN.md) | 本地周计划:手动录入任务、日期与优先级,按天查看安排,勾选完成并跟踪本周完成率 | [Alanhean](https://github.com/Alanhean) | diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/.minimax-plugin/plugin.json b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/.minimax-plugin/plugin.json new file mode 100644 index 00000000..c93a163c --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/.minimax-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": 1, + "name": "miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8", + "displayName": "工作群", + "version": "1.0.0", + "description": "一个可以接入多个 Agent 的工作群:在群里 @ 成员,成员各自用独立会话回复,并可在回复里点名其他成员接力;工具审批和问题都在群里完成。", + "author": "liuhaolin07", + "icon": "icon.png", + "category": "Productivity", + "exampleQueries": [ + "打开工作群,让调研和评审一起看这个需求。", + "在工作群里 @执行 把这份清单整理成表格。" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/LICENSE b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/LICENSE new file mode 100644 index 00000000..a82460b9 --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 liuhaolin07 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.md b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.md new file mode 100644 index 00000000..77857191 --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.md @@ -0,0 +1,87 @@ +# Work Group (`miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8`) + +English | [简体中文](./README.zh-CN.md) + +A chat-style work group inside MiniMax Code. Several Agents sit in one thread with you: mention the +ones you need, each replies from its own session, and a member can mention another member to hand +work over. Tool approvals and questions from an Agent arrive as cards in the group instead of in a +separate chat. + +## Install + +Copy this directory, including the hidden `.minimax-plugin/`, into the MiniMax Code plugins +directory as `miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/` (`~/.minimax/plugins/` by default; the +root README's Install section explains where that directory is). Restart MiniMax Code and ask the +Agent to "打开工作群" or "Open Work Group". + +## Use + +- The group starts with four members bound to your configured Agents: 协调者 (coordinator, your + default Agent), 调研 (Explore), 执行 (Worker) and 评审 (Verifier). Add, edit or remove members at + any time; a member can be bound to a real Agent or defined as a custom role with its own + instructions. +- Mention members with `@name` (or the chips above the input). Mentioned members reply; with no + mention the coordinator replies. A member's reply that mentions another member queues that member + next, up to 3 levels deep and 6 turns per message. +- When a member needs a tool, the group shows an approval card with the tool name, reason and input. + Nothing runs until you choose "允许一次" (allow once) or "拒绝" (deny). When a member asks you a + question, the group shows the questionnaire and continues the turn after you submit it. +- Each member keeps its own session, so it remembers what it did earlier. "重置会话" starts it over, + "在会话中查看" opens that session in the chat side panel. +- "停止" cancels a member's running turn, "全部停止" cancels everything queued, and "清空对话" + deletes the transcript and resets every session. +- Members, messages, approvals and questions are stored by the Node service, so a restart or a + reclaimed page restores the group. A pending approval that was interrupted by a restart is shown + as expired rather than left waiting. + +## Tested environment + +- MiniMax Code 3.1.19 on Windows 11 (x64), installed from the workspace package and opened through + the Agent. Client acceptance exercised: initial view and empty state, member panel, add a member → + reload → still present → delete with confirmation, send a message → a real Agent turn completed + and rendered, clear the conversation. Console: no errors. Network: no failed requests. +- Not exercised in a live turn: the tool approval card, the questionnaire card, the stop control, + and opening a member session in the side panel. Those paths were exercised against a mocked Agent + runtime, together with mention chaining, session continuation, member validation and restart + recovery. +- The package uses the legacy `agentAccess` and `window.mcode.miniapp` spellings on purpose so it + also loads on clients before 3.1.20. With `agentAccess` and `agentConcurrency` declared, the + minimum client is MiniMax Code 3.1.2. + +## Data & access + +- Files: reads its own `miniapp/client/*` assets. Writes one JSON state file, `group-state.json`, in + the Host-provided `context.dataDir`. +- Network: none beyond the Host-assigned loopback port. +- Processes: none. +- Agent turns: yes. `agentAccess: ["session.run"]` lets each member run Agent turns with that + Agent's full capabilities (files, shell, Skills, MCP), up to 4 turns at once. A Node-initiated + turn works in this Mini App's own Agent directory; a turn started from a page opened in a chat + uses that chat's project directory. +- Conversations read: none of your own conversations. Only the sessions this Mini App creates. +- Tools and Connectors called: none directly. An Agent may call its own tools; every + `permission.requested` is shown in the page and answered with `allowOnce` or `deny` only after + you choose. +- Microphone, camera, notifications: none. +- Host navigation read: none. +- File extensions handled: none. +- State: members, messages, approvals and questionnaires in `context.dataDir`; the unsent draft and + scroll position in the page's `sessionStorage`. + +## Files + +```text +.minimax-plugin/plugin.json Plugin manifest +package.json Mini App declaration +miniapp/miniapp.json Payload roots, Node entry, page route, agentAccess +miniapp/client/index.html The page served at /group +miniapp/client/styles.css Page styles +miniapp/client/app.js Page logic: polling, rendering, cards, member form +miniapp/node/server.mjs Node entry: start(context) → { dispose } +miniapp/node/miniapp-api.ts Type declarations for the runtime context; not loaded at runtime +icon.png Plugin icon +``` + +## License + +[MIT](./LICENSE) diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.zh-CN.md b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.zh-CN.md new file mode 100644 index 00000000..6b92f3d9 --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.zh-CN.md @@ -0,0 +1,56 @@ +# 工作群(`miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8`) + +[English](./README.md) | 简体中文 + +MiniMax Code 里的聊天式工作群。你和多个 Agent 在同一个群里:@ 需要的成员,每个成员用自己的会话回复,成员可以在回复里 @ 其他成员接力。Agent 的工具审批和提问都以卡片形式出现在群里,不需要切到别的聊天。 + +## 安装 + +把整个目录(含隐藏的 `.minimax-plugin/`)复制到 MiniMax Code 的插件目录,目录名为 +`miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/`(默认 `~/.minimax/plugins/`,根 README 的安装一节说明了该目录的位置)。重启 MiniMax Code,然后让 Agent「打开工作群」。 + +## 使用 + +- 群内预置四位成员,分别绑定你已配置的 Agent:协调者(默认 Agent)、调研(Explore)、执行(Worker)、评审(Verifier)。可以随时添加、编辑或删除成员;成员可以绑定真实 Agent,也可以是带职责指令的自定义角色。 +- 用 `@名称`(或输入框上方的胶囊)点名成员,被点名的成员回复;不点名时由协调者回复。成员在回复里 @ 其他成员时,被点名的成员会排在其后发言,最多接力 3 层、每条消息最多 6 次运行。 +- 成员需要调用工具时,群里会出现审批卡,显示工具名、原因和参数;你选择「允许一次」或「拒绝」之前不会执行。成员向你提问时会出现问卷卡,提交后自动续跑。 +- 每个成员保持自己的会话,会记得之前做过什么。「重置会话」让它从新会话开始,「在会话中查看」把该成员的会话在聊天侧栏打开。 +- 「停止」取消某个成员正在进行的回合,「全部停止」取消所有排队和进行中的回合,「清空对话」删除聊天记录并重置所有会话。 +- 成员、消息、审批和问题由 Node 服务持久化,重启或页面被回收后群会恢复;因重启中断的审批卡会显示为已失效,不会一直挂着。 + +## 测试环境 + +- MiniMax Code 3.1.19,Windows 11(x64)。从工作区包安装,通过 Agent 打开。客户端验收覆盖:初始视图与空状态、成员面板、添加成员 → 刷新后仍在 → 带确认框删除、发送消息 → 真实 Agent 回合完成并渲染、清空对话。控制台无错误,网络无失败请求。 +- 未在真实回合中触发:工具审批卡、问卷卡、停止按钮、在侧栏打开成员会话。这些路径在模拟 Agent 运行时下验证过,点名接力、会话延续、成员校验和重启恢复也在其中。 +- 本包有意使用旧的 `agentAccess` 与 `window.mcode.miniapp` 写法,以便在 3.1.20 之前的客户端上也能加载。声明了 `agentAccess` 与 `agentConcurrency`,最低客户端为 MiniMax Code 3.1.2。 + +## 数据与权限 + +- 文件:只读取自身的 `miniapp/client/*` 资源;在宿主提供的 `context.dataDir` 中写入一个 JSON 状态文件 `group-state.json`。 +- 网络:除宿主分配的本地回环端口外不访问其他地址。 +- 进程:不启动子进程。 +- Agent 回合:会。`agentAccess: ["session.run"]` 让成员以该 Agent 的完整能力(文件、Shell、Skills、MCP)运行回合,同时最多 4 个。Node 发起的回合在本 Mini App 自己的 Agent 目录中工作;从某个聊天里打开的页面发起的回合使用该聊天的项目目录。 +- 读取的会话:不读取你的任何自有会话,只使用本 Mini App 自己创建的会话。 +- 调用的工具与连接器:不直接调用。Agent 可能调用自己的工具;每个 `permission.requested` 都会显示在页面上,只有你做出选择后才会以 `allowOnce` 或 `deny` 回应。 +- 麦克风、摄像头、通知:不使用。 +- 读取宿主导航:不使用。 +- 处理的文件扩展名:无。 +- 状态:成员、消息、审批和问卷存放在 `context.dataDir`;未发送的草稿和滚动位置存放在页面的 `sessionStorage`。 + +## 文件 + +```text +.minimax-plugin/plugin.json 插件清单 +package.json Mini App 声明 +miniapp/miniapp.json 载荷根目录、Node 入口、页面路由、agentAccess +miniapp/client/index.html /group 页面 +miniapp/client/styles.css 页面样式 +miniapp/client/app.js 页面逻辑:轮询、渲染、卡片、成员表单 +miniapp/node/server.mjs Node 入口:start(context) → { dispose } +miniapp/node/miniapp-api.ts 运行时上下文的类型声明,运行时不会加载 +icon.png 插件图标 +``` + +## 许可 + +[MIT](./LICENSE) diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/icon.png b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/icon.png new file mode 100644 index 00000000..299a26cb Binary files /dev/null and b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/icon.png differ diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/app.js b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/app.js new file mode 100644 index 00000000..127755f3 --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/app.js @@ -0,0 +1,1098 @@ +const POLL_ACTIVE_MS = 500; +const POLL_IDLE_MS = 2500; +const VIEW_KEY = 'mcode-group-view'; + +const state = { + bootId: null, + rev: -1, + data: null, + agents: [], + agentsError: null, + selectedMentions: new Set(), + messageEls: new Map(), + memberKey: '', + mentionKey: '', + pollTimer: null, + polling: false, + editingMemberId: null, + banner: null, +}; + +const $ = (selector) => document.querySelector(selector); + +const els = { + groupName: $('#group-name'), + groupSub: $('#group-sub'), + banner: $('#banner'), + messages: $('#messages'), + empty: $('#empty-state'), + composer: $('#composer'), + input: $('#composer-input'), + hint: $('#composer-hint'), + send: $('#btn-send'), + mentionBar: $('#mention-bar'), + memberList: $('#member-list'), + agentNote: $('#agent-note'), + panel: $('#member-panel'), + toggleMembers: $('#btn-toggle-members'), + stop: $('#btn-stop'), + clear: $('#btn-clear'), + addMember: $('#btn-add-member'), + memberModal: $('#member-modal'), + memberForm: $('#member-form'), + memberTitle: $('#member-modal-title'), + memberName: $('#member-name'), + memberNameError: $('#member-name-error'), + memberAgentField: $('#member-agent-field'), + memberAgent: $('#member-agent'), + memberAgentNote: $('#member-agent-note'), + memberRole: $('#member-role'), + memberInstructions: $('#member-instructions'), + memberCoordinator: $('#member-coordinator'), + memberError: $('#member-error'), + memberCancel: $('#member-cancel'), + confirmModal: $('#confirm-modal'), + confirmTitle: $('#confirm-title'), + confirmText: $('#confirm-text'), + confirmOk: $('#confirm-ok'), + confirmCancel: $('#confirm-cancel'), + toast: $('#toast'), +}; + +// ------------------------------------------------------------------ theme + +function applyTheme(theme) { + document.documentElement.dataset.theme = theme === 'dark' ? 'dark' : 'light'; +} + +function applySystemTheme() { + const dark = window.matchMedia?.('(prefers-color-scheme: dark)').matches; + applyTheme(dark ? 'dark' : 'light'); +} + +function setupTheme() { + const hostUi = window.mcode?.miniapp?.host?.ui; + if (hostUi?.subscribe) { + try { + const subscription = hostUi.subscribe( + (snapshot) => applyTheme(snapshot?.theme), + { onError: () => applySystemTheme() }, + ); + window.addEventListener('pagehide', () => subscription?.dispose?.(), { once: true }); + return; + } catch { + applySystemTheme(); + return; + } + } + applySystemTheme(); + window.matchMedia?.('(prefers-color-scheme: dark)').addEventListener?.('change', applySystemTheme); +} + +// -------------------------------------------------------------------- api + +async function api(path, options = {}) { + const response = await fetch(path, { + method: options.method ?? 'GET', + headers: options.body ? { 'content-type': 'application/json' } : undefined, + body: options.body ? JSON.stringify(options.body) : undefined, + }); + const text = await response.text(); + let payload = null; + try { + payload = text ? JSON.parse(text) : null; + } catch { + payload = null; + } + if (!response.ok) { + const error = new Error(payload?.error || `http_${response.status}`); + error.code = payload?.error || `http_${response.status}`; + throw error; + } + return payload; +} + +// ------------------------------------------------------------------- text + +function escapeHtml(text) { + return String(text ?? '').replace(/[&<>"']/g, (char) => { + switch (char) { + case '&': + return '&'; + case '<': + return '<'; + case '>': + return '>'; + case '"': + return '"'; + default: + return '''; + } + }); +} + +function renderInline(text) { + let html = escapeHtml(text); + html = html.replace(/`([^`]+)`/g, '$1'); + html = html.replace(/\*\*([^*]+)\*\*/g, '$1'); + html = html.replace( + /(^|[\s((])@([^\s@,。,.!?!?::;;()()]{1,24})/g, + (match, prefix, name) => `${prefix}@${name}`, + ); + return html; +} + +function renderTextBlock(value) { + const paragraphs = value + .split(/\n{2,}/) + .map((paragraph) => paragraph.trim()) + .filter(Boolean); + return paragraphs + .map((paragraph) => { + const lines = paragraph.split('\n'); + if (lines.length > 1 && lines.every((line) => /^\s*[-*]\s+/.test(line))) { + return ``; + } + if (lines.length > 1 && lines.every((line) => /^\s*\d+\.\s+/.test(line))) { + return `
    ${lines + .map((line) => `
  1. ${renderInline(line.replace(/^\s*\d+\.\s+/, ''))}
  2. `) + .join('')}
`; + } + return `

${lines.map(renderInline).join('
')}

`; + }) + .join(''); +} + +function renderMarkdown(text) { + const source = String(text ?? ''); + if (!source.trim()) return ''; + const blocks = []; + const fence = /```[\w-]*\n([\s\S]*?)```/g; + let lastIndex = 0; + let match = fence.exec(source); + while (match) { + if (match.index > lastIndex) blocks.push({ type: 'text', value: source.slice(lastIndex, match.index) }); + blocks.push({ type: 'code', value: match[1] }); + lastIndex = fence.lastIndex; + match = fence.exec(source); + } + if (lastIndex < source.length) blocks.push({ type: 'text', value: source.slice(lastIndex) }); + return blocks + .map((block) => + block.type === 'code' + ? `
${escapeHtml(block.value.replace(/\n$/, ''))}
` + : renderTextBlock(block.value), + ) + .join(''); +} + +function formatTime(ms) { + if (!ms) return ''; + try { + return new Date(ms).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }); + } catch { + return ''; + } +} + +const MEMBER_STATUS = { idle: '空闲', running: '运行中', waiting: '等你处理' }; + +function messageStatusText(message) { + switch (message.status) { + case 'streaming': + return message.queued > 0 ? `排队中(第 ${message.queued} 位)` : '运行中'; + case 'waiting': + return '等你回答'; + case 'error': + return '失败'; + case 'aborted': + return '已停止'; + case 'interrupted': + return '已中断'; + case 'superseded': + return '已重试'; + default: + return ''; + } +} + +function cardStateText(status) { + switch (status) { + case 'allowed': + return '已允许一次'; + case 'denied': + return '已拒绝'; + case 'cancelled': + return '已取消'; + case 'stale': + return '已失效(进程重启)'; + case 'answered': + return '已回答'; + default: + return status; + } +} + +const MEMBER_ERRORS = { + invalid_name: '名称不能为空,不能包含 @,最多 24 个字符。', + name_taken: '这个名称已经被占用。', + agent_required: '请选择一个要绑定的 Agent。', + instructions_required: '自定义角色需要填写职责指令。', +}; + +// ------------------------------------------------------------------ toast + +let toastTimer = null; +function toast(text) { + els.toast.textContent = text; + els.toast.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { + els.toast.hidden = true; + }, 2600); +} + +function confirmAction(title, text, okLabel = '确认') { + return new Promise((resolve) => { + els.confirmTitle.textContent = title; + els.confirmText.textContent = text; + els.confirmOk.textContent = okLabel; + const finish = (value) => { + els.confirmOk.removeEventListener('click', onOk); + els.confirmCancel.removeEventListener('click', onCancel); + els.confirmModal.removeEventListener('close', onClose); + if (els.confirmModal.open) els.confirmModal.close(); + resolve(value); + }; + const onOk = () => finish(true); + const onCancel = () => finish(false); + const onClose = () => finish(false); + els.confirmOk.addEventListener('click', onOk); + els.confirmCancel.addEventListener('click', onCancel); + els.confirmModal.addEventListener('close', onClose); + els.confirmModal.showModal(); + }); +} + +// ------------------------------------------------------------------- poll + +function isActive() { + const data = state.data; + if (!data) return true; + if (data.runtime.active > 0 || data.runtime.queue > 0) return true; + return data.members.some((member) => member.status !== 'idle'); +} + +function schedulePoll(delay) { + clearTimeout(state.pollTimer); + state.pollTimer = setTimeout(() => { + void poll(); + }, delay); +} + +async function poll(options = {}) { + if (state.polling) return; + // A page can load while the panel is hidden; read once anyway so the first view is populated. + if (!options.force && document.visibilityState !== 'visible') return; + state.polling = true; + try { + const query = state.bootId ? `?since=${state.rev}&boot=${encodeURIComponent(state.bootId)}` : ''; + const result = await api(`/api/state${query}`); + if (!result.unchanged) { + state.bootId = result.bootId; + state.rev = result.rev; + state.data = result.state; + state.banner = null; + render(); + } + } catch (error) { + state.banner = `无法连接群服务(${error.code || 'network_error'}),稍后自动重试。`; + renderBanner(); + } finally { + state.polling = false; + if (document.visibilityState === 'visible') schedulePoll(isActive() ? POLL_ACTIVE_MS : POLL_IDLE_MS); + } +} + +async function refresh() { + clearTimeout(state.pollTimer); + await poll({ force: true }); +} + +async function loadAgents() { + try { + const result = await api('/api/agents'); + state.agents = Array.isArray(result.agents) ? result.agents : []; + state.agentsError = result.error ?? null; + } catch (error) { + state.agents = []; + state.agentsError = error.code || 'unavailable'; + } + renderMemberPanel(); +} + +// ----------------------------------------------------------------- render + +function render() { + if (!state.data) return; + renderHeader(); + renderBanner(); + renderMemberPanel(); + renderMentionBar(); + renderMessages(); + renderComposerState(); +} + +function renderHeader() { + const data = state.data; + els.groupName.textContent = data.group.name || '工作群'; + const coordinator = data.members.find((member) => member.coordinator); + const parts = [`${data.members.length} 位成员`]; + if (coordinator) parts.push(`协调者:${coordinator.name}`); + if (data.runtime.active > 0 || data.runtime.queue > 0) { + parts.push(`进行中 ${data.runtime.active}${data.runtime.queue ? `,排队 ${data.runtime.queue}` : ''}`); + } + els.groupSub.textContent = parts.join(' · '); + els.stop.disabled = !(data.runtime.active > 0 || data.runtime.queue > 0); +} + +function renderBanner() { + const data = state.data; + let text = state.banner; + if (!text && data && data.runtime.agentAvailable === false) { + text = '当前宿主没有授予 Agent 运行权限,成员无法发言。可以在插件详情里打开 session.run。'; + } + els.banner.hidden = !text; + els.banner.textContent = text || ''; +} + +function renderMemberPanel() { + const data = state.data; + if (!data) return; + const key = JSON.stringify( + data.members.map((member) => [member.id, member.name, member.role, member.kind, member.agentDisplayName, member.status, member.coordinator, member.sessionId]), + ); + if (key !== state.memberKey) { + state.memberKey = key; + els.memberList.replaceChildren( + ...data.members.map((member) => { + const item = document.createElement('li'); + item.className = 'member'; + item.dataset.id = member.id; + + const head = document.createElement('div'); + head.className = 'member-head'; + const avatar = document.createElement('span'); + avatar.className = 'avatar'; + avatar.setAttribute('aria-hidden', 'true'); + avatar.textContent = member.name.slice(0, 1); + const name = document.createElement('span'); + name.className = 'member-name'; + name.textContent = member.name + (member.coordinator ? '(协调者)' : ''); + const status = document.createElement('span'); + status.className = 'member-state'; + status.dataset.status = member.status; + status.textContent = MEMBER_STATUS[member.status] || member.status; + head.append(avatar, name, status); + + const role = document.createElement('p'); + role.className = 'member-role'; + role.textContent = member.role || '未填写职责'; + + const agent = document.createElement('p'); + agent.className = 'member-agent'; + agent.textContent = + member.kind === 'agent' + ? `真实 Agent:${member.agentDisplayName || member.agentName}` + : '自定义角色(使用默认 Agent)'; + + const actions = document.createElement('div'); + actions.className = 'member-actions'; + actions.append( + linkButton('编辑', () => openMemberModal(member)), + linkButton('重置会话', () => resetMember(member)), + ); + if (member.status === 'running') { + actions.append(linkButton('停止', () => cancelMember(member))); + } + actions.append( + linkButton('删除', async () => { + const ok = await confirmAction('删除成员', `确定从群里移除「${member.name}」吗?它的会话记录会保留在本地,但不再参与群聊。`, '删除'); + if (!ok) return; + await mutate(`/api/members/${encodeURIComponent(member.id)}`, 'DELETE', '已删除成员'); + }), + ); + + item.append(head, role, agent, actions); + return item; + }), + ); + } + + const note = []; + if (state.agentsError) note.push(`读取已配置 Agent 失败(${state.agentsError}),仍可使用自定义角色。`); + else if (state.agents.length === 0) note.push('当前没有可绑定的已配置 Agent,可以先添加自定义角色。'); + els.agentNote.textContent = note.join(' '); +} + +function linkButton(label, onClick) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'btn btn-link'; + button.textContent = label; + button.addEventListener('click', () => { + void onClick(); + }); + return button; +} + +function renderMentionBar() { + const data = state.data; + const key = JSON.stringify(data.members.map((member) => [member.id, member.name])); + if (key === state.mentionKey) return; + state.mentionKey = key; + for (const id of [...state.selectedMentions]) { + if (!data.members.some((member) => member.id === id)) state.selectedMentions.delete(id); + } + els.mentionBar.replaceChildren( + ...data.members.map((member) => { + const chip = document.createElement('button'); + chip.type = 'button'; + chip.className = 'mention-chip'; + chip.dataset.id = member.id; + chip.setAttribute('aria-pressed', String(state.selectedMentions.has(member.id))); + chip.textContent = `@${member.name}`; + chip.addEventListener('click', () => toggleMention(member)); + return chip; + }), + ); +} + +function toggleMention(member) { + const token = `@${member.name} `; + const input = els.input; + if (state.selectedMentions.has(member.id)) { + state.selectedMentions.delete(member.id); + input.value = input.value.split(token).join(''); + } else { + state.selectedMentions.add(member.id); + if (!input.value.includes(`@${member.name}`)) { + input.value = input.value ? `${input.value.replace(/\s*$/, ' ')}${token}` : token; + } + } + for (const chip of els.mentionBar.querySelectorAll('.mention-chip')) { + chip.setAttribute('aria-pressed', String(state.selectedMentions.has(chip.dataset.id))); + } + input.focus(); +} + +function renderComposerState() { + const data = state.data; + const coordinator = data.members.find((member) => member.coordinator) || data.members[0]; + els.hint.textContent = coordinator + ? `不 @ 任何人时,由协调者「${coordinator.name}」回复。Enter 发送,Shift+Enter 换行。` + : '先添加一位成员,再发消息。'; + els.send.disabled = data.members.length === 0; +} + +function createMessageEl(message) { + const root = document.createElement('article'); + root.className = `msg msg-${message.author}`; + root.dataset.id = message.id; + + const avatar = document.createElement('span'); + avatar.className = 'avatar'; + avatar.setAttribute('aria-hidden', 'true'); + + const body = document.createElement('div'); + body.className = 'msg-body'; + + const meta = document.createElement('div'); + meta.className = 'msg-meta'; + const name = document.createElement('span'); + name.className = 'msg-name'; + const tag = document.createElement('span'); + tag.className = 'msg-tag'; + const time = document.createElement('time'); + time.className = 'msg-time'; + const status = document.createElement('span'); + status.className = 'msg-status'; + meta.append(name, tag, time, status); + + const bubble = document.createElement('div'); + bubble.className = 'bubble'; + const error = document.createElement('p'); + error.className = 'msg-error'; + error.hidden = true; + const activity = document.createElement('div'); + activity.className = 'activity'; + const chained = document.createElement('p'); + chained.className = 'chained'; + chained.hidden = true; + const cards = document.createElement('div'); + cards.className = 'cards'; + const actions = document.createElement('div'); + actions.className = 'msg-actions'; + + body.append(meta, bubble, error, activity, chained, cards, actions); + root.append(avatar, body); + + return { + root, + avatar, + name, + tag, + time, + status, + bubble, + error, + activity, + chained, + cards, + actions, + rendered: { text: null, activity: null, cards: null, actions: null }, + }; +} + +function cardsFor(messageId) { + const data = state.data; + return { + approvals: data.approvals.filter((card) => card.messageId === messageId), + questions: data.questions.filter((card) => card.messageId === messageId), + }; +} + +function buildApprovalCard(card) { + const el = document.createElement('div'); + el.className = `card card-approval status-${card.status}`; + el.setAttribute('role', 'group'); + el.setAttribute('aria-label', `工具审批:${card.toolName}`); + + const title = document.createElement('p'); + title.className = 'card-title'; + title.innerHTML = `${escapeHtml(card.memberName)} 请求调用工具 ${escapeHtml(card.toolName)}`; + el.append(title); + + if (card.reason) { + const reason = document.createElement('p'); + reason.className = 'card-reason'; + reason.textContent = card.reason; + el.append(reason); + } + if (card.toolInput) { + const input = document.createElement('pre'); + input.className = 'card-input'; + input.textContent = card.toolInput; + el.append(input); + } + + const actions = document.createElement('div'); + actions.className = 'card-actions'; + if (card.status === 'pending') { + const allow = document.createElement('button'); + allow.type = 'button'; + allow.className = 'btn btn-primary btn-small'; + allow.textContent = '允许一次'; + allow.addEventListener('click', () => void decideApproval(card.id, 'allowOnce')); + const deny = document.createElement('button'); + deny.type = 'button'; + deny.className = 'btn btn-small'; + deny.textContent = '拒绝'; + deny.addEventListener('click', () => void decideApproval(card.id, 'deny')); + actions.append(allow, deny); + } else { + const state = document.createElement('span'); + state.className = 'card-state'; + state.textContent = cardStateText(card.status); + actions.append(state); + } + el.append(actions); + return el; +} + +function buildQuestionCard(card) { + const el = document.createElement('div'); + el.className = `card card-question status-${card.status}`; + el.setAttribute('role', 'group'); + el.setAttribute('aria-label', `${card.memberName} 需要你回答`); + + const title = document.createElement('p'); + title.className = 'card-title'; + title.innerHTML = `${escapeHtml(card.memberName)} 需要你回答`; + el.append(title); + + const steps = Array.isArray(card.request?.steps) ? card.request.steps : []; + if (card.status !== 'pending') { + const state = document.createElement('span'); + state.className = 'card-state'; + state.textContent = cardStateText(card.status); + el.append(state); + return el; + } + + const form = document.createElement('form'); + form.className = 'question-form'; + const refs = []; + + steps.forEach((step, index) => { + const fieldset = document.createElement('fieldset'); + fieldset.className = 'question-step'; + const legend = document.createElement('legend'); + legend.textContent = step.question || `问题 ${index + 1}`; + fieldset.append(legend); + if (step.description) { + const description = document.createElement('p'); + description.className = 'card-reason'; + description.textContent = step.description; + fieldset.append(description); + } + const multiple = step.selectionMode === 'multiple'; + const name = `step-${card.id}-${step.id}`; + for (const option of step.options ?? []) { + const label = document.createElement('label'); + label.className = 'option'; + const input = document.createElement('input'); + input.type = multiple ? 'checkbox' : 'radio'; + input.name = name; + input.value = option.id; + label.append(input, document.createTextNode(option.label)); + if (option.description) { + const desc = document.createElement('span'); + desc.className = 'option-desc'; + desc.textContent = option.description; + label.append(desc); + } + fieldset.append(label); + } + const otherLabel = document.createElement('label'); + otherLabel.className = 'option'; + const otherInput = document.createElement('input'); + otherInput.type = multiple ? 'checkbox' : 'radio'; + otherInput.name = name; + otherInput.value = '__other__'; + const otherText = document.createElement('input'); + otherText.type = 'text'; + otherText.className = 'input other-text'; + otherText.placeholder = '其他(可填写)'; + otherLabel.append(otherInput, document.createTextNode('其他'), otherText); + fieldset.append(otherLabel); + form.append(fieldset); + refs.push({ step, name, otherText }); + }); + + const submit = document.createElement('button'); + submit.type = 'submit'; + submit.className = 'btn btn-primary btn-small'; + submit.textContent = '提交回答'; + form.append(submit); + + form.addEventListener('submit', (event) => { + event.preventDefault(); + const answers = refs.map(({ step, name, otherText }) => { + const checked = [...form.querySelectorAll(`input[name="${CSS.escape(name)}"]:checked`)].map((input) => input.value); + const other = checked.includes('__other__'); + return { + stepId: step.id, + selectedOptionIds: checked.filter((value) => value !== '__other__'), + selectedOther: other, + ...(other ? { otherText: otherText.value } : {}), + }; + }); + submit.disabled = true; + void submitAnswers(card.id, answers).finally(() => { + submit.disabled = false; + }); + }); + + el.append(form); + return el; +} + +function updateMessageEl(entry, message) { + const member = message.memberId ? state.data.members.find((item) => item.id === message.memberId) : null; + entry.avatar.textContent = (message.name || '?').slice(0, 1); + entry.name.textContent = message.author === 'user' ? '我' : message.name; + entry.tag.textContent = member?.kind === 'agent' ? member.agentDisplayName || member.agentName || '' : ''; + entry.time.textContent = formatTime(message.createdAt); + const statusText = messageStatusText(message); + entry.status.textContent = statusText; + entry.status.dataset.status = message.status; + entry.status.hidden = !statusText; + + const text = `${message.text ?? ''}${message.streaming ?? ''}`; + if (text !== entry.rendered.text) { + entry.rendered.text = text; + entry.bubble.innerHTML = renderMarkdown(text); + entry.bubble.hidden = !text.trim(); + } + + entry.error.hidden = !message.error; + entry.error.textContent = message.error || ''; + + const activityKey = JSON.stringify(message.activity ?? []); + if (activityKey !== entry.rendered.activity) { + entry.rendered.activity = activityKey; + entry.activity.replaceChildren( + ...(message.activity ?? []).map((item) => { + const chip = document.createElement('span'); + chip.className = 'chip'; + if (item.ok === true) chip.dataset.ok = 'true'; + if (item.ok === false) chip.dataset.ok = 'false'; + chip.textContent = `${item.name}${item.ok === true ? ' · 完成' : item.ok === false ? ' · 失败' : ' · 进行中'}`; + return chip; + }), + ); + } + + const chained = message.chained ?? []; + entry.chained.hidden = chained.length === 0; + entry.chained.textContent = chained.length ? `已点名:${chained.join('、')}` : ''; + + const { approvals, questions } = cardsFor(message.id); + const cardsKey = JSON.stringify([ + approvals.map((card) => [card.id, card.status]), + questions.map((card) => [card.id, card.status]), + ]); + if (cardsKey !== entry.rendered.cards) { + entry.rendered.cards = cardsKey; + entry.cards.replaceChildren( + ...approvals.map(buildApprovalCard), + ...questions.map(buildQuestionCard), + ); + } + + const canOpen = Boolean(message.sessionId) && Boolean(window.mcode?.miniapp?.agent?.open); + const actionsKey = JSON.stringify([message.status, Boolean(message.retry), canOpen]); + if (actionsKey !== entry.rendered.actions) { + entry.rendered.actions = actionsKey; + const actions = []; + if (message.status === 'streaming' || message.status === 'waiting') { + actions.push(linkButton('停止', () => cancelMemberById(message.memberId))); + } + if (message.status === 'error' && message.retry) { + actions.push(linkButton('重试', () => retryMessage(message.id))); + } + if (canOpen) { + actions.push( + linkButton('在会话中查看', () => { + void window.mcode.miniapp.agent.open(message.sessionId).catch(() => { + toast('无法打开会话侧栏'); + }); + }), + ); + } + entry.actions.replaceChildren(...actions); + } +} + +function renderMessages() { + const data = state.data; + const container = els.messages; + const nearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 140; + + els.empty.hidden = data.messages.length > 0; + + const seen = new Set(); + let previous = null; + for (const message of data.messages) { + let entry = state.messageEls.get(message.id); + if (!entry) { + entry = createMessageEl(message); + state.messageEls.set(message.id, entry); + } + updateMessageEl(entry, message); + seen.add(message.id); + const expected = previous ? previous.nextElementSibling : container.firstElementChild; + if (entry.root !== expected) container.insertBefore(entry.root, expected); + previous = entry.root; + } + for (const [id, entry] of state.messageEls) { + if (!seen.has(id)) { + entry.root.remove(); + state.messageEls.delete(id); + } + } + + if (nearBottom) container.scrollTop = container.scrollHeight; +} + +// ---------------------------------------------------------------- actions + +async function mutate(path, method, successText, body) { + try { + await api(path, { method, body }); + if (successText) toast(successText); + await refresh(); + return true; + } catch (error) { + toast(`操作失败:${error.code || 'unknown'}`); + return false; + } +} + +async function sendMessage() { + const text = els.input.value.trim(); + if (!text) { + toast('先写点内容再发送'); + els.input.focus(); + return; + } + els.send.disabled = true; + try { + await api('/api/messages', { + method: 'POST', + body: { text, mentions: [...state.selectedMentions] }, + }); + els.input.value = ''; + state.selectedMentions.clear(); + for (const chip of els.mentionBar.querySelectorAll('.mention-chip')) { + chip.setAttribute('aria-pressed', 'false'); + } + await refresh(); + els.messages.scrollTop = els.messages.scrollHeight; + } catch (error) { + toast(`发送失败:${error.code || 'unknown'}`); + } finally { + els.send.disabled = state.data ? state.data.members.length === 0 : false; + els.input.focus(); + } +} + +async function decideApproval(id, decision) { + try { + await api(`/api/approvals/${encodeURIComponent(id)}`, { method: 'POST', body: { decision } }); + } catch (error) { + toast(`审批失败:${error.code || 'unknown'}`); + } + await refresh(); +} + +async function submitAnswers(id, answers) { + try { + await api(`/api/questions/${encodeURIComponent(id)}`, { method: 'POST', body: { answers } }); + } catch (error) { + toast(`提交失败:${error.code || 'unknown'}`); + } + await refresh(); +} + +async function retryMessage(messageId) { + await mutate('/api/retry', 'POST', '已重新排队', { messageId }); +} + +async function cancelMemberById(memberId) { + if (!memberId) return; + await mutate(`/api/members/${encodeURIComponent(memberId)}/cancel`, 'POST', '已停止'); +} + +async function cancelMember(member) { + await cancelMemberById(member.id); +} + +async function resetMember(member) { + const ok = await confirmAction('重置会话', `「${member.name}」会忘记之前的对话,下次发言从新会话开始。`, '重置'); + if (!ok) return; + await mutate(`/api/members/${encodeURIComponent(member.id)}/reset`, 'POST', '已重置会话'); +} + +// ------------------------------------------------------------ member form + +function selectedKind() { + const checked = els.memberForm.querySelector('input[name="member-kind"]:checked'); + return checked?.value === 'role' ? 'role' : 'agent'; +} + +function syncKindFields() { + const kind = selectedKind(); + els.memberAgentField.hidden = kind !== 'agent'; + if (kind === 'agent') { + els.memberAgentNote.textContent = state.agents.length + ? '成员会使用这个 Agent 的完整能力,并保持自己的会话记忆。' + : '当前没有可绑定的已配置 Agent,请改用自定义角色。'; + } +} + +function fillAgentOptions(selected) { + els.memberAgent.replaceChildren( + ...state.agents.map((agent) => { + const option = document.createElement('option'); + option.value = agent.name; + option.textContent = agent.primary ? `${agent.displayName}(默认)` : agent.displayName; + option.dataset.display = agent.displayName; + return option; + }), + ); + if (selected) els.memberAgent.value = selected; +} + +async function openMemberModal(member) { + state.editingMemberId = member?.id ?? null; + els.memberTitle.textContent = member ? '编辑成员' : '添加成员'; + els.memberError.hidden = true; + els.memberNameError.hidden = true; + els.memberName.value = member?.name ?? ''; + els.memberRole.value = member?.role ?? ''; + els.memberInstructions.value = member?.instructions ?? ''; + els.memberCoordinator.checked = member?.coordinator === true; + const kind = member?.kind ?? (state.agents.length ? 'agent' : 'role'); + for (const input of els.memberForm.querySelectorAll('input[name="member-kind"]')) { + input.checked = input.value === kind; + } + if (!state.agents.length && !member) await loadAgents(); + fillAgentOptions(member?.agentName ?? undefined); + if (!state.agents.length && kind === 'agent') { + for (const input of els.memberForm.querySelectorAll('input[name="member-kind"]')) { + input.checked = input.value === 'role'; + } + } + syncKindFields(); + els.memberModal.showModal(); + els.memberName.focus(); +} + +function closeMemberModal() { + if (els.memberModal.open) els.memberModal.close(); +} + +async function submitMemberForm(event) { + event.preventDefault(); + els.memberError.hidden = true; + els.memberNameError.hidden = true; + const name = els.memberName.value.trim(); + if (!name || name.includes('@')) { + els.memberNameError.textContent = MEMBER_ERRORS.invalid_name; + els.memberNameError.hidden = false; + els.memberName.focus(); + return; + } + const kind = selectedKind(); + const agentOption = els.memberAgent.selectedOptions[0]; + const body = { + name, + kind, + agentName: kind === 'agent' ? els.memberAgent.value || null : null, + agentDisplayName: kind === 'agent' ? agentOption?.dataset.display ?? null : null, + role: els.memberRole.value.trim(), + instructions: els.memberInstructions.value.trim(), + coordinator: els.memberCoordinator.checked, + }; + const editing = state.editingMemberId; + try { + if (editing) { + await api(`/api/members/${encodeURIComponent(editing)}`, { method: 'PATCH', body }); + toast('已保存成员'); + } else { + await api('/api/members', { method: 'POST', body }); + toast('已添加成员'); + } + closeMemberModal(); + await refresh(); + } catch (error) { + els.memberError.textContent = MEMBER_ERRORS[error.code] || `保存失败(${error.code || 'unknown'})`; + els.memberError.hidden = false; + } +} + +// ------------------------------------------------------------- view state + +function saveViewState() { + try { + sessionStorage.setItem( + VIEW_KEY, + JSON.stringify({ draft: els.input.value, scrollTop: els.messages.scrollTop }), + ); + } catch { + /* View state is a convenience only. */ + } +} + +function restoreViewState() { + try { + const raw = sessionStorage.getItem(VIEW_KEY); + if (!raw) return; + const saved = JSON.parse(raw); + if (typeof saved?.draft === 'string' && saved.draft) els.input.value = saved.draft; + if (Number.isFinite(saved?.scrollTop)) { + requestAnimationFrame(() => { + els.messages.scrollTop = saved.scrollTop; + }); + } + } catch { + /* Ignore malformed view state. */ + } +} + +// ------------------------------------------------------------------ wiring + +function wire() { + els.composer.addEventListener('submit', (event) => { + event.preventDefault(); + void sendMessage(); + }); + + els.input.addEventListener('keydown', (event) => { + if (event.key !== 'Enter' || event.shiftKey || event.isComposing) return; + event.preventDefault(); + void sendMessage(); + }); + + els.input.addEventListener('input', () => { + const value = els.input.value; + for (const member of state.data?.members ?? []) { + const present = value.includes(`@${member.name}`); + if (present) state.selectedMentions.add(member.id); + else state.selectedMentions.delete(member.id); + } + for (const chip of els.mentionBar.querySelectorAll('.mention-chip')) { + chip.setAttribute('aria-pressed', String(state.selectedMentions.has(chip.dataset.id))); + } + }); + + els.stop.addEventListener('click', () => { + void mutate('/api/stop', 'POST', '已停止全部成员'); + }); + + els.clear.addEventListener('click', async () => { + const ok = await confirmAction('清空对话', '会删除群里的全部消息和审批记录,并重置所有成员的会话。', '清空'); + if (!ok) return; + await mutate('/api/clear', 'POST', '已清空对话'); + }); + + els.addMember.addEventListener('click', () => { + void openMemberModal(null); + }); + + els.memberCancel.addEventListener('click', closeMemberModal); + els.memberForm.addEventListener('submit', (event) => { + void submitMemberForm(event); + }); + for (const input of els.memberForm.querySelectorAll('input[name="member-kind"]')) { + input.addEventListener('change', syncKindFields); + } + + els.toggleMembers.addEventListener('click', () => { + const open = els.panel.classList.toggle('open'); + els.toggleMembers.setAttribute('aria-expanded', String(open)); + }); + + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + clearTimeout(state.pollTimer); + saveViewState(); + return; + } + void refresh(); + }); + + window.addEventListener('pagehide', saveViewState); +} + +setupTheme(); +wire(); +restoreViewState(); +void (async () => { + await poll({ force: true }); + await loadAgents(); +})(); diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/index.html b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/index.html new file mode 100644 index 00000000..af91b8dd --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/index.html @@ -0,0 +1,114 @@ + + + + + + 工作群 + + + +
+
+
+

工作群

+

正在加载群信息…

+
+
+ + + +
+
+ + + +
+
+
+ + +
+
+ + + +
+
+ + +
+
+ + +
+

添加成员

+
+ + + +
+
+ 类型 + + +
+
+ + +

+
+
+ + +
+
+ + +

自定义角色必填;真实 Agent 可留空,作为补充要求。

+
+ + + +
+
+ + +
+

确认操作

+

+ +
+
+ + + + + diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/styles.css b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/styles.css new file mode 100644 index 00000000..332ab3d5 --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/client/styles.css @@ -0,0 +1,815 @@ +:root, +[data-theme='light'] { + --mcode-bg: #ffffff; + --mcode-bg-secondary: #f5f5f5; + --mcode-surface: #ffffff; + --mcode-surface-muted: #fafafa; + --mcode-text: #171717; + --mcode-text-muted: #666666; + --mcode-text-subtle: #adadad; + --mcode-border: #0a0a0a14; + --mcode-border-strong: #0a0a0af2; + --mcode-accent: #0094fc; + --mcode-success: #04b54b; + --mcode-warning: #f56811; + --mcode-danger: #f73646; + --mcode-primary-action-bg: #171717; + --mcode-primary-action-text: #ffffff; + --mcode-shadow: 0 0 20px rgb(10 10 10 / 8%); + --mcode-avatar-bg: #eef1f4; +} + +[data-theme='dark'] { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; + --mcode-shadow: 0 0 20px rgb(0 0 0 / 40%); + --mcode-avatar-bg: #333333; +} + +* { + box-sizing: border-box; +} + +[hidden] { + display: none !important; +} + +html, +body { + height: 100%; + margin: 0; +} + +body { + background: var(--mcode-bg); + color: var(--mcode-text); + font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.6; +} + +code, +pre, +.mono { + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; +} + +.app { + display: flex; + flex-direction: column; + height: 100%; + min-height: 480px; +} + +/* ---------------------------------------------------------------- topbar */ + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 24px; + border-bottom: 1px solid var(--mcode-border); + background: var(--mcode-surface); +} + +.title-block h1 { + margin: 0; + font-size: 18px; + line-height: 28px; + font-weight: 600; +} + +.subtitle { + margin: 2px 0 0; + font-size: 12px; + line-height: 16px; + color: var(--mcode-text-muted); +} + +.topbar-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.banner { + padding: 8px 24px; + border-bottom: 1px solid var(--mcode-border); + background: var(--mcode-surface-muted); + color: var(--mcode-danger); + font-size: 13px; +} + +/* --------------------------------------------------------------- buttons */ + +.btn { + height: 32px; + padding: 0 12px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); + color: var(--mcode-text); + font: inherit; + font-size: 13px; + cursor: pointer; + transition: background-color 150ms ease-out, opacity 150ms ease-out; +} + +.btn:hover:not(:disabled) { + background: var(--mcode-bg-secondary); +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.btn:focus-visible, +.input:focus-visible, +.option input:focus-visible, +.mention-chip:focus-visible { + outline: 2px solid var(--mcode-accent); + outline-offset: 1px; +} + +.btn-primary { + background: var(--mcode-primary-action-bg); + border-color: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); +} + +.btn-primary:hover:not(:disabled) { + background: var(--mcode-primary-action-bg); + opacity: 0.88; +} + +.btn-danger { + color: var(--mcode-danger); +} + +.btn-small { + height: 28px; + padding: 0 10px; + font-size: 12px; +} + +.btn-link { + height: auto; + padding: 0; + border: 0; + background: transparent; + color: var(--mcode-accent); + font-size: 12px; +} + +.btn-link:hover:not(:disabled) { + background: transparent; + text-decoration: underline; +} + +/* ---------------------------------------------------------------- layout */ + +.layout { + display: flex; + flex: 1; + min-height: 0; +} + +.chat { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + min-height: 0; +} + +.messages { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 16px 24px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.empty { + padding: 24px; + margin: 0 24px 16px; + border: 1px dashed var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface-muted); +} + +.empty-title { + margin: 0 0 4px; + font-weight: 500; +} + +.empty-text { + margin: 0; + color: var(--mcode-text-muted); + font-size: 13px; +} + +/* -------------------------------------------------------------- messages */ + +.msg { + display: flex; + gap: 12px; + align-items: flex-start; +} + +.avatar { + flex: 0 0 32px; + width: 32px; + height: 32px; + border-radius: 8px; + background: var(--mcode-avatar-bg); + color: var(--mcode-text-muted); + display: flex; + align-items: center; + justify-content: center; + font-size: 13px; + font-weight: 600; +} + +.msg-user .avatar { + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); +} + +.msg-body { + flex: 1; + min-width: 0; + max-width: 720px; +} + +.msg-meta { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 8px; + margin-bottom: 4px; +} + +.msg-name { + font-weight: 500; +} + +.msg-tag, +.msg-time, +.msg-status { + font-size: 12px; + color: var(--mcode-text-muted); +} + +.msg-status[data-status='running'] { + color: var(--mcode-accent); +} + +.msg-status[data-status='waiting'] { + color: var(--mcode-warning); +} + +.msg-status[data-status='error'], +.msg-status[data-status='interrupted'] { + color: var(--mcode-danger); +} + +.bubble { + padding: 10px 12px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); + overflow-wrap: anywhere; +} + +.msg-user .bubble { + background: var(--mcode-surface-muted); +} + +.bubble p { + margin: 0 0 8px; +} + +.bubble p:last-child { + margin-bottom: 0; +} + +.bubble ul, +.bubble ol { + margin: 0 0 8px; + padding-left: 20px; +} + +.bubble code { + padding: 1px 4px; + border-radius: 4px; + background: var(--mcode-surface-muted); + font-size: 12px; +} + +.bubble pre.code { + margin: 0 0 8px; + padding: 8px 10px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); + overflow-x: auto; + font-size: 12px; + line-height: 1.5; +} + +.bubble pre.code code { + padding: 0; + background: transparent; +} + +.mention { + padding: 0 4px; + border-radius: 4px; + background: var(--mcode-surface-muted); + color: var(--mcode-accent); + font-weight: 500; +} + +.msg-error { + margin: 6px 0 0; + color: var(--mcode-danger); + font-size: 12px; +} + +.activity { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 6px; +} + +.activity:empty { + display: none; +} + +.chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 1px 8px; + border: 1px solid var(--mcode-border); + border-radius: 999px; + background: var(--mcode-surface-muted); + color: var(--mcode-text-muted); + font-size: 12px; +} + +.chip[data-ok='true'] { + color: var(--mcode-success); +} + +.chip[data-ok='false'] { + color: var(--mcode-danger); +} + +.chained { + margin: 6px 0 0; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.msg-actions { + display: flex; + flex-wrap: wrap; + gap: 12px; + margin-top: 6px; +} + +.msg-actions:empty { + display: none; +} + +/* ----------------------------------------------------------------- cards */ + +.cards { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 8px; +} + +.cards:empty { + display: none; +} + +.card { + padding: 12px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface-muted); +} + +.card-approval.status-pending, +.card-question.status-pending { + border-color: var(--mcode-warning); +} + +.card-title { + margin: 0 0 6px; + font-size: 13px; +} + +.card-reason { + margin: 0 0 8px; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.card-input { + margin: 0 0 8px; + padding: 8px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface); + max-height: 160px; + overflow: auto; + font-size: 12px; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.card-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; +} + +.card-state { + font-size: 12px; + color: var(--mcode-text-muted); +} + +.question-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.question-step { + margin: 0; + padding: 8px 12px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface); +} + +.question-step legend { + padding: 0 4px; + font-size: 13px; + font-weight: 500; +} + +.option { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + padding: 4px 0; + font-size: 13px; + cursor: pointer; +} + +.option-desc { + flex-basis: 100%; + padding-left: 22px; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.other-text { + flex: 1; + min-width: 160px; + height: 32px; +} + +/* -------------------------------------------------------------- composer */ + +.composer { + padding: 12px 24px 16px; + border-top: 1px solid var(--mcode-border); + background: var(--mcode-surface); +} + +.mention-bar { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-bottom: 8px; +} + +.mention-chip { + height: 26px; + padding: 0 10px; + border: 1px solid var(--mcode-border); + border-radius: 999px; + background: var(--mcode-surface-muted); + color: var(--mcode-text-muted); + font: inherit; + font-size: 12px; + cursor: pointer; +} + +.mention-chip[aria-pressed='true'] { + border-color: var(--mcode-accent); + color: var(--mcode-accent); +} + +.input { + width: 100%; + height: 36px; + padding: 0 10px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface); + color: var(--mcode-text); + font: inherit; + font-size: 14px; +} + +.input::placeholder { + color: var(--mcode-text-subtle); +} + +.textarea { + height: auto; + padding: 8px 10px; + line-height: 1.6; + resize: vertical; +} + +.composer-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-top: 8px; +} + +.hint { + margin: 0; + color: var(--mcode-text-muted); + font-size: 12px; +} + +/* ----------------------------------------------------------------- panel */ + +.panel { + flex: 0 0 240px; + width: 240px; + padding: 16px; + border-left: 1px solid var(--mcode-border); + background: var(--mcode-bg-secondary); + overflow-y: auto; +} + +.panel-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 12px; +} + +.panel-head h2 { + margin: 0; + font-size: 16px; + line-height: 24px; + font-weight: 500; +} + +.member-list { + display: flex; + flex-direction: column; + gap: 8px; + margin: 0; + padding: 0; + list-style: none; +} + +.member { + padding: 10px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.member-head { + display: flex; + align-items: center; + gap: 8px; +} + +.member-name { + font-weight: 500; +} + +.member-state { + margin-left: auto; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.member-state[data-status='running'] { + color: var(--mcode-accent); +} + +.member-state[data-status='waiting'] { + color: var(--mcode-warning); +} + +.member-role { + margin: 6px 0 0; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.member-agent { + margin: 2px 0 0; + color: var(--mcode-text-subtle); + font-size: 12px; +} + +.member-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; + margin-top: 8px; +} + +.panel-note { + margin: 12px 0 0; + color: var(--mcode-text-muted); + font-size: 12px; +} + +/* ---------------------------------------------------------------- modals */ + +.modal { + width: min(480px, calc(100vw - 32px)); + padding: 20px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); + color: var(--mcode-text); + box-shadow: var(--mcode-shadow); +} + +.modal::backdrop { + background: rgb(10 10 10 / 40%); +} + +.modal h2 { + margin: 0 0 16px; + font-size: 16px; + line-height: 24px; + font-weight: 500; +} + +.modal-small { + width: min(360px, calc(100vw - 32px)); +} + +.confirm-body p { + margin: 0 0 16px; + color: var(--mcode-text-muted); +} + +.field { + display: flex; + flex-direction: column; + gap: 6px; + margin: 0 0 12px; + padding: 0; + border: 0; +} + +.field label, +.field legend { + padding: 0; + font-size: 13px; + font-weight: 500; +} + +.field-inline { + flex-direction: row; + flex-wrap: wrap; + align-items: center; + gap: 16px; +} + +.field-inline legend { + float: left; + margin-right: 8px; +} + +.field-note { + margin: 0; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.field-error, +.form-error { + margin: 0; + color: var(--mcode-danger); + font-size: 12px; +} + +.form-error { + margin: 8px 0 0; +} + +.modal-actions { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 16px; +} + +.toast { + position: fixed; + left: 50%; + bottom: 24px; + transform: translateX(-50%); + padding: 8px 16px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface); + box-shadow: var(--mcode-shadow); + font-size: 13px; + z-index: 10; +} + +/* ------------------------------------------------------------ responsive */ + +@media (max-width: 768px) { + .topbar { + padding: 12px 16px; + } + + .messages, + .composer { + padding-left: 16px; + padding-right: 16px; + } + + .panel { + position: fixed; + inset: 57px 0 0 auto; + width: min(280px, 100vw); + box-shadow: var(--mcode-shadow); + display: none; + } + + .panel.open { + display: block; + } + + .empty { + margin-left: 16px; + margin-right: 16px; + } +} + +@media (prefers-reduced-motion: reduce) { + * { + transition: none !important; + animation: none !important; + } +} diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/miniapp.json b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/miniapp.json new file mode 100644 index 00000000..e6dac466 --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/miniapp.json @@ -0,0 +1,24 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/group" + }, + "mcpEndpoints": [], + "agentAccess": [ + "session.run" + ], + "agentConcurrency": 4 +} diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/node/miniapp-api.ts b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..49a0dc87 --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/node/miniapp-api.ts @@ -0,0 +1,687 @@ +/** + * Agent-facing Mini App runtime authoring declarations. + * + * Copy this file into a generated plugin for type checking. It contains no Host implementation; + * the Host injects runtime values through start(context) (see docs/runtime.md). + * Keep the .ts filename: Electron packaging excludes .d.ts files from dependency assets. + */ +export type JsonPrimitive = null | boolean | number | string; +export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[]; +export type JsonObject = { readonly [key: string]: JsonValue }; + +declare const HOST_CONNECTOR_TOOL_REF: unique symbol; +export type HostConnectorToolRef = string & { + readonly [HOST_CONNECTOR_TOOL_REF]: 'HostConnectorToolRef'; +}; + +export interface HostConnectorTool { + readonly toolRef: HostConnectorToolRef; + readonly provider: string; + readonly name: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly outputSchema?: JsonValue; +} + +export interface HostConnectorListResult { + readonly tools: readonly HostConnectorTool[]; + readonly partial: boolean; +} + +export interface HostConnectorCallOptions { + readonly signal?: AbortSignal; +} + +export interface HostConnectorCallResult { + readonly invocationId: string; + /** + * Raw provider result; it is not normalized by the Host and may be an object, array, or primitive. + * A single text-block array is one provider shape, not a global Host transport contract. + * Decode only a probe-observed envelope; preserve every other value, including direct strings. + */ + readonly value: JsonValue; +} + +export interface HostConnectorClient { + /** Candidate-safe inventory only; available before and after activation. */ + list(options?: HostConnectorCallOptions): Promise; + /** Activation-only business dispatch; call from request handling, never start(context). */ + call( + toolRef: HostConnectorToolRef, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; +} + +export type HostConnectorErrorDisposition = + | 'not_dispatched' + | 'provider_reported' + | 'unknown_after_dispatch'; + +export type HostConnectorErrorCode = + | 'TOOL_REF_STALE' + | 'SERVICE_RESTARTED' + | 'REQUEST_CANCELLED' + | 'CONNECTOR_TIMEOUT' + | 'INVALID_ARGUMENTS' + | 'CONNECTOR_PROVIDER_ERROR' + | 'CONNECTOR_UNAVAILABLE' + /** The manifest did not declare the required grant; not dispatched. */ + | 'NOT_PERMITTED' + /** The user switched this provider off for the Mini App; not dispatched. */ + | 'PERMISSION_DENIED' + | 'CONNECTOR_OUTCOME_UNKNOWN'; + +export interface HostConnectorError extends Error { + readonly code: HostConnectorErrorCode; + readonly disposition: HostConnectorErrorDisposition; + readonly retryable: boolean; + readonly invocationId?: string; + readonly diagnostic?: { + readonly issues: readonly { + readonly path: string; + readonly constraint: string; + readonly limit?: number; + }[]; + }; +} + +/** What a call would meet now under the user's global permission rules; informational only. */ +export type MiniAppToolPermission = 'allow' | 'ask' | 'deny'; + +/** + * `name` is the runtime name an Agent sees (`mcp____`, `connector____`). + * Take it from `list()`; do not build it. + */ +export type MiniAppTool = + | { + readonly name: string; + readonly kind: 'connector'; + readonly provider: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + } + | { + readonly name: string; + readonly kind: 'mcp'; + /** Any installed MCP server: a Plugin's, the user's `mcp.json`, or a Host built-in one. */ + readonly server: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + }; + +export interface MiniAppToolListResult { + readonly tools: readonly MiniAppTool[]; + /** A source could not be listed; the listed tools are still callable. */ + readonly partial: boolean; +} + +export type MiniAppToolCallResult = + | { + readonly invocationId: string; + readonly kind: 'connector'; + /** Raw provider result, as in `HostConnectorCallResult.value`. */ + readonly value: JsonValue; + } + | { + readonly invocationId: string; + readonly kind: 'mcp'; + /** The MCP tool reported its own failure; `content` keeps its error text. */ + readonly isError: boolean; + /** MCP content blocks such as `{ type: 'text', text }`, passed through as JSON. */ + readonly content: readonly JsonValue[]; + readonly structuredContent?: JsonObject; + }; + +/** + * Thrown with the `HostConnectorError` shape; Connector tools keep their Connector codes too. The + * code names the cause; `disposition` alone says whether the tool may have run (`TOOL_TIMEOUT` and + * `REQUEST_CANCELLED` can be either `not_dispatched` or `unknown_after_dispatch`). + */ +export type MiniAppToolErrorCode = + | HostConnectorErrorCode + | 'INVALID_ARGUMENTS' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Always present (MiniMax Code 3.1.20 or later; see docs/tool.md). Without `permissions.tool: ["call"]` + * (or the older `"toolAccess": ["call"]`), every method rejects `NOT_PERMITTED`. With `tool:call` + * switched off, `call()` rejects `PERMISSION_DENIED` while `list()` and `request()` resolve with + * `deny` for each tool. Every `call` is judged by the user's global rules: `deny` is + * `PERMISSION_DENIED`, `ask` shows a Host prompt, and nobody to ask is `TOOL_APPROVAL_REQUIRED`. + * `list` works before activation; call `call` only from request handling after activation. Connector + * tools time out after 30 s and MCP tools after at most 120 s, counted after any prompt. The Host + * never retries; reconcile an `unknown_after_dispatch` outcome before repeating a write. + */ +export interface MiniAppToolClient { + list(options?: HostConnectorCallOptions): Promise; + call( + name: string, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; + /** + * One Host prompt for the named tools (1–10, from `list()`) still at `ask`; the user ticks which + * to always allow. Resolves every name's state afterwards (for your UI only). When nobody can be + * asked it rejects with `TOOL_APPROVAL_REQUIRED` whose error carries `permissions`. With + * `tool:call` switched off it answers `deny` for every name without a prompt. + * Needs `capabilities.has('tool.request')`. + */ + request( + names: readonly string[], + options?: HostConnectorCallOptions, + ): Promise>; +} + +export interface MiniAppLogger { + debug(message: string, fields?: JsonObject): void; + info(message: string, fields?: JsonObject): void; + warn(message: string, fields?: JsonObject): void; + error(message: string, fields?: JsonObject): void; +} + +/** + * How the call's text ended: in its own turn (`finished` / `error` / `aborted`), or, only with + * `whenBusy`, joined into the turn that was already running (`steered`; that turn's own + * call gets the reply). + */ +export type MiniAppAgentRunStatus = 'finished' | 'error' | 'aborted' | 'steered'; + +/** + * The Desktop composer's follow-up behaviours while a session runs a turn. `queue`: the text runs + * as the next turn and the call follows it. `steer`: the running turn reads the text at its next + * input point (the call resolves `steered`), or, if it answered first, the text runs as the next + * turn and the call follows it. + */ +export type MiniAppAgentWhenBusy = 'queue' | 'steer'; + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: JsonObject; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a Node-created session starts with. */ + readonly default: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** `aborted` only when the Host confirmed the abort; an unconfirmed one rejects with `AGENT_OUTCOME_UNKNOWN`. */ + readonly status: MiniAppAgentRunStatus; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + * + * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even + * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the + * session's single-run slot while `question.requested` is delivered, so call `answer` only after + * that `run` resolves (an earlier call rejects with `BUSY`). Ignore event types you do not know. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + /** A tool call is waiting for approval; decide it with `agent.reply`. */ + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + /** The turn paused on a questionnaire; continue with `agent.answer`. */ + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: Exclude; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunOptions { + readonly signal?: AbortSignal; + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +export type MiniAppAgentErrorCode = + | 'NOT_PERMITTED' + | 'PERMISSION_DENIED' + | 'BUSY' + | 'SESSION_NOT_FOUND' + | 'INVALID_ARGUMENTS' + | 'AGENT_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'AGENT_OUTCOME_UNKNOWN' + | 'REQUEST_NOT_FOUND'; + +export interface MiniAppAgentError extends Error { + readonly code: MiniAppAgentErrorCode; + /** + * True when nothing was started and the same call may be retried later. + * `AGENT_OUTCOME_UNKNOWN` is never retryable: the turn may have run. + */ + readonly retryable: boolean; + /** + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. + */ + readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; +} + +/** + * Always present (MiniMax Code 3.1.20 or later; see docs/agent.md). `run` / `reply` / `answer` / + * `models` / `list` / `create` need `permissions.agent: ["run"]`. The deprecated `observe` / + * `sessions` / `session` are the `context.session` methods and follow its rule (see docs/agent.md). + * A new Node session uses the primary Agent unless `agent` names one from `list()`, and works in + * this Mini App's own Agent directory and on the runtime default model; + * continuing a session keeps its Agent, directory and model (unless `model` switches it), including + * one a page created using its host chat's Agent, project directory and model; a session never + * changes its Agent. Runs one turn with that Agent's full capabilities + * (files, shell, Skills, MCP including this Mini App's own), and resolves when the turn ends. + * + * Interaction is yours to render: pass `onEvent` and handle `permission.requested` with + * `reply` and `question.requested` with `answer`. A permission request waits only while + * someone can answer it: this run passed `onEvent`, or a page of this Mini App currently has + * the session open in a chat side panel via `open`. Otherwise it is denied (the model is told + * why), and a questionnaire ends the turn with `result.pendingQuestion`. A run waiting on a + * permission is released by `cancel`/abort, process exit or republish. Up to `agentConcurrency` + * runs (default 4) per Mini App run at once; further `run` / `answer` calls wait in order (up to + * four times that many, see `run.queued`), and aborting a waiting call rejects it with + * `REQUEST_CANCELLED`. A `whenBusy` call on a session that already has a call in flight shares + * that call's slot. Cancelling a queued `whenBusy` text removes it (`REQUEST_CANCELLED`); a steered + * text cannot be withdrawn (`AGENT_OUTCOME_UNKNOWN`, the running turn goes on). + */ +export interface MiniAppAgentClient { + run( + input: { + readonly text: string; + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a + * new session's model: it must be one `models()` lists; unusable is `INVALID_ARGUMENTS`, + * missing BYOK credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `list()`. Passing it + * with `sessionId` is `INVALID_ARGUMENTS`. + */ + readonly agent?: string; + /** + * Only with `sessionId`: what to do when that session is already running a turn; on an idle + * session the call starts a turn as usual. Omit to reject with `BUSY` (`session_busy`). + */ + readonly whenBusy?: MiniAppAgentWhenBusy; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Decide a pending permission request. Never writes the user's global rules. Node replies + * have 16 separate pending slots; `run` / `answer` / `models` / `list` / `create` and Connector + * requests share another 16. Filling that ordinary budget still permits replies. A full reply + * budget rejects with retryable `AGENT_UNAVAILABLE`. + */ + reply(input: { + readonly sessionId: string; + readonly requestId: string; + readonly decision: 'allowOnce' | 'deny'; + }): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `AGENT_OUTCOME_UNKNOWN` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: { + readonly sessionId: string; + readonly requestId: string; + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `run`'s `model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Returns the model catalog and runtime `default`. Pass `default` directly as `model` to + * `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, add a selected `variant` + * if needed and preserve `variant: ''`. If thinking is supported, select an effort from + * `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + list(): Promise; + /** @deprecated Use `list()`; the Host warns once and removes this name in a later version. */ + agents(): Promise; + /** + * Create a session (agent, this Mini App's Agent directory, the runtime default model) without + * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's + * `create` binds the session to its chat instead, and its `sessionId` can be continued here. + * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's + * agent from `list()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** @deprecated Use `context.session.observe`; the Host warns once and removes this name in a later version. */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** @deprecated Use `context.session.list`; the Host warns once and removes this name in a later version. */ + sessions(): Promise; + /** @deprecated Use `context.session.get`; the Host warns once and removes this name in a later version. */ + session(sessionId: string): Promise; +} + +/** + * Always present (MiniMax Code 3.1.20 or later; see docs/agent.md). Read-only access to the user's + * conversations (the Desktop chat list). + * Every method needs `permissions.session: ["read"]`, except that this Mini App's own sessions (those + * `agent.create` / `agent.run` made) are readable under `permissions.agent: ["run"]` alone; while the + * user has `read` switched off, calls on other sessions fail with `PERMISSION_DENIED` and running + * observers end. Check `context.capabilities?.has('session.list')` on Hosts that may predate it. + * Neither grant implies the other; `observe({ all: true })` always needs `permissions.session: ["read"]`. + */ +export interface MiniAppSessionClient { + /** The user's visible root conversations, most recently updated first (at most 50). */ + list(): Promise; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session.get()`). + */ + get(sessionId: string): Promise; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort + * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription + * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, + * or `read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `PERMISSION_DENIED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots + * and no ordinary request budget. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; +} + +export interface MiniAppLifecycle { + dispose(): void | Promise; +} + +export interface MiniAppContext { + readonly pluginId: string; + readonly pluginRoot: string; + readonly dataDir: string; + readonly listen: Readonly<{ readonly host: '127.0.0.1'; readonly port: number }>; + readonly signal: AbortSignal; + readonly logger: MiniAppLogger; + /** + * Synchronous probe of the methods this Host offers **on the Node side**, named by API path + * (`agent.run`, `agent.list`, `session.list`, `session.get`, `session.observe`, + * `connector.call`, `connector.list`, `tool.call`, `tool.list`, `tool.request`). A + * page-only method is false here. A few Host-wide names remain until the deprecated aliases go: + * `agent.agents`, `agent.observe`, `agent.sessions`, `agent.session`, `hostConnector`, `tool`. + * The `hostConnector*` probe names stay beside `connector.*` until the alias goes. + * It says nothing about this Mini App's manifest or authorization: `has('agent.run')` is true + * even when the manifest does not grant it. Older Hosts do not + * inject `capabilities`; check `context.capabilities?.has(...)`. `has('session.list')` tells a + * `context.session` Host from one that only has the deprecated `context.agent.sessions` names. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Always present on MiniMax Code 3.1.20 or later. Without `permissions.connector` (or the older + * `hostConnectorAccess`), every method rejects `NOT_PERMITTED`. A provider the user switched off + * is missing from `list()` and its calls reject with `PERMISSION_DENIED`. + */ + readonly connector: HostConnectorClient; + /** + * @deprecated `connector`. Always present on 3.1.20 or later. Forwards to the same client and + * warns once on the first method call (`MINIAPP-DEP-007`); it is not the same object reference, + * so do not compare the two or use both as map keys. + */ + readonly hostConnector: HostConnectorClient; + /** Always present on 3.1.20 or later. Calls installed MCP and Connector tools under the user's permission rules. */ + readonly tool: MiniAppToolClient; + /** + * Always present on 3.1.20 or later, as on the page. Its methods need `permissions.agent: ["run"]`; + * they reject with `NOT_PERMITTED` if the manifest does not declare it and `PERMISSION_DENIED` + * if the user switched it off. Session aliases follow `context.session`'s rules. + */ + readonly agent: MiniAppAgentClient; + /** + * Always present on 3.1.20 or later, as on the page. Reading conversations other than this Mini + * App's own needs `permissions.session: ["read"]`. Own sessions can also use + * `permissions.agent: ["run"]`. + */ + readonly session: MiniAppSessionClient; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +export interface MiniAppModule { + /** Resolve only after the listener accepts connections and every route is installed. */ + start(context: MiniAppContext): Promise; +} diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/node/server.mjs b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/node/server.mjs new file mode 100644 index 00000000..ad0fff0c --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/miniapp/node/server.mjs @@ -0,0 +1,1248 @@ +// @ts-check +import { randomUUID } from 'node:crypto'; +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +const STATE_FILE = 'group-state.json'; +const STATE_SCHEMA = 1; +const MAX_MESSAGES = 300; +const MAX_CARDS = 100; +const MAX_BODY_BYTES = 1_000_000; +const MAX_USER_TEXT = 20_000; +const MAX_NAME = 24; +const MAX_ROLE = 80; +const MAX_INSTRUCTIONS = 4_000; +const TRANSCRIPT_MESSAGES = 14; +const TRANSCRIPT_CHARS = 12_000; +const PERSIST_THROTTLE_MS = 400; +/** Must stay at or below the manifest's agentConcurrency. */ +const RUN_LIMIT = 4; +const DEFAULT_CHAIN_DEPTH = 3; +const DEFAULT_MAX_RUNS = 6; + +const ASSETS = new Map([ + ['/', { file: 'index.html', type: 'text/html; charset=utf-8' }], + ['/group', { file: 'index.html', type: 'text/html; charset=utf-8' }], + ['/client/styles.css', { file: 'styles.css', type: 'text/css; charset=utf-8' }], + ['/client/app.js', { file: 'app.js', type: 'text/javascript; charset=utf-8' }], +]); + +/** + * @param {MiniAppContext} context + * @returns {Promise} + */ +export async function start(context) { + const bootId = randomUUID(); + const clientDir = join(context.pluginRoot, 'miniapp', 'client'); + const statePath = join(context.dataDir, STATE_FILE); + + /** @type {any} */ + let state = null; + let rev = 0; + /** @type {ReturnType | null} */ + let persistTimer = null; + let persistChain = Promise.resolve(); + let disposed = false; + + const runtime = { + /** @type {Map} */ + runs: new Map(), + /** @type {any[]} */ + queue: [], + active: 0, + /** @type {{ agents: any[]; error: string | null } | null} */ + agents: null, + }; + + // ---------------------------------------------------------------- helpers + + function codeOf(error) { + if (error && typeof error === 'object' && 'code' in error) return String(/** @type {any} */ (error).code); + return 'unknown'; + } + + function httpError(status, code) { + const error = new Error(code); + /** @type {any} */ (error).statusCode = status; + /** @type {any} */ (error).code = code; + return error; + } + + function truncate(text, max) { + const value = String(text ?? ''); + return value.length > max ? `${value.slice(0, max)}…` : value; + } + + function bump() { + rev += 1; + schedulePersist(); + } + + function schedulePersist() { + if (disposed || persistTimer) return; + persistTimer = setTimeout(() => { + persistTimer = null; + void persistNow(); + }, PERSIST_THROTTLE_MS); + } + + function persistNow() { + if (persistTimer) { + clearTimeout(persistTimer); + persistTimer = null; + } + if (!state) return persistChain; + const payload = JSON.stringify({ + schema: STATE_SCHEMA, + group: state.group, + members: state.members, + messages: state.messages, + approvals: state.approvals, + questions: state.questions, + settings: state.settings, + }); + persistChain = persistChain + .then(async () => { + await mkdir(context.dataDir, { recursive: true }); + const temp = `${statePath}.tmp-${randomUUID()}`; + await writeFile(temp, payload, 'utf8'); + await rename(temp, statePath); + }) + .catch((error) => { + context.logger.error('miniapp.persist.failed', { code: codeOf(error) }); + }); + return persistChain; + } + + // ------------------------------------------------------------- state load + + function normalize(raw) { + const members = Array.isArray(raw?.members) ? raw.members : []; + const messages = Array.isArray(raw?.messages) ? raw.messages : []; + return { + group: { + name: typeof raw?.group?.name === 'string' && raw.group.name ? raw.group.name : '工作群', + topic: typeof raw?.group?.topic === 'string' ? raw.group.topic : '', + }, + members: members + .filter((member) => member && typeof member.id === 'string' && typeof member.name === 'string') + .map((member) => ({ + id: member.id, + name: member.name, + kind: member.kind === 'agent' ? 'agent' : 'role', + agentName: typeof member.agentName === 'string' ? member.agentName : null, + agentDisplayName: typeof member.agentDisplayName === 'string' ? member.agentDisplayName : null, + role: typeof member.role === 'string' ? member.role : '', + instructions: typeof member.instructions === 'string' ? member.instructions : '', + coordinator: member.coordinator === true, + sessionId: typeof member.sessionId === 'string' ? member.sessionId : null, + createdAt: Number(member.createdAt) || Date.now(), + })), + messages: messages + .filter((message) => message && typeof message.id === 'string') + .map((message) => ({ + id: message.id, + author: message.author === 'user' || message.author === 'system' ? message.author : 'member', + memberId: typeof message.memberId === 'string' ? message.memberId : null, + name: typeof message.name === 'string' ? message.name : '', + text: typeof message.text === 'string' ? message.text : '', + streaming: '', + mentions: Array.isArray(message.mentions) ? message.mentions.map(String) : [], + activity: Array.isArray(message.activity) ? message.activity : [], + status: typeof message.status === 'string' ? message.status : 'done', + error: typeof message.error === 'string' ? message.error : null, + originId: typeof message.originId === 'string' ? message.originId : null, + depth: Number(message.depth) || 0, + trigger: typeof message.trigger === 'string' ? message.trigger : 'user', + triggerName: typeof message.triggerName === 'string' ? message.triggerName : null, + chained: Array.isArray(message.chained) ? message.chained.map(String) : [], + runs: Number(message.runs) || 0, + sessionId: typeof message.sessionId === 'string' ? message.sessionId : null, + queued: 0, + retry: + message.retry && typeof message.retry === 'object' && typeof message.retry.memberId === 'string' + ? { + memberId: message.retry.memberId, + originId: typeof message.retry.originId === 'string' ? message.retry.originId : null, + depth: Number(message.retry.depth) || 0, + trigger: typeof message.retry.trigger === 'string' ? message.retry.trigger : 'user', + triggerName: typeof message.retry.triggerName === 'string' ? message.retry.triggerName : null, + } + : null, + createdAt: Number(message.createdAt) || Date.now(), + })), + approvals: Array.isArray(raw?.approvals) ? raw.approvals : [], + questions: Array.isArray(raw?.questions) ? raw.questions : [], + settings: { + chainDepth: Number(raw?.settings?.chainDepth) || DEFAULT_CHAIN_DEPTH, + maxRuns: Number(raw?.settings?.maxRuns) || DEFAULT_MAX_RUNS, + }, + }; + } + + function recoverInterrupted() { + for (const message of state.messages) { + if (message.status === 'streaming' || message.status === 'waiting') { + message.status = 'interrupted'; + message.streaming = ''; + } + } + for (const card of state.approvals) { + if (card.status === 'pending') card.status = 'stale'; + } + for (const card of state.questions) { + if (card.status === 'pending') card.status = 'stale'; + } + } + + async function listAgents() { + if (!context.agent || typeof context.agent.agents !== 'function') { + return { agents: [], error: 'unavailable' }; + } + try { + const result = await context.agent.agents(); + const agents = Array.isArray(result?.agents) ? result.agents : []; + return { + agents: agents.map((agent) => ({ + name: String(agent.name), + displayName: String(agent.displayName || agent.name), + primary: agent.primary === true, + })), + error: null, + }; + } catch (error) { + return { agents: [], error: codeOf(error) }; + } + } + + async function seedState() { + const { agents } = await listAgents(); + const byName = new Map(agents.map((agent) => [agent.name, agent])); + const primary = agents.find((agent) => agent.primary) || agents[0] || null; + const presets = [ + { + name: '协调者', + agentName: primary?.name ?? null, + role: '理解目标、拆解任务、点名成员、汇总结论', + instructions: + '你是群里的协调者。收到消息后先判断目标,再决定自己回答还是点名其他成员(用 @成员名)。每次只推进一轮,不要代替别人发言,也不要替用户做决定。', + }, + { + name: '调研', + agentName: 'explore', + role: '只读调研:定位代码与资料,给出证据和结论', + instructions: + '你是调研成员。只做只读调查:定位文件、代码和资料,给出具体证据位置与结论。不修改任何文件。', + }, + { + name: '执行', + agentName: 'worker', + role: '按群里约定的范围完成具体改动或产出', + instructions: + '你是执行成员。按群里约定的范围完成具体改动或产出,说明改了哪些文件、验证了什么。范围不清时先说明你的假设。', + }, + { + name: '评审', + agentName: 'verifier', + role: '独立核对成果,给出通过或不通过及证据', + instructions: + '你是评审成员。独立核对成果是否满足要求,给出通过或不通过的结论和具体证据,不修改被评审的成果。', + }, + ]; + const members = presets.map((preset, index) => { + const agent = preset.agentName ? byName.get(preset.agentName) : null; + return { + id: randomUUID(), + name: preset.name, + kind: agent ? 'agent' : 'role', + agentName: agent ? agent.name : null, + agentDisplayName: agent ? agent.displayName : null, + role: preset.role, + instructions: preset.instructions, + coordinator: index === 0, + sessionId: null, + createdAt: Date.now() + index, + }; + }); + return { + group: { name: '工作群', topic: '' }, + members, + messages: [], + approvals: [], + questions: [], + settings: { chainDepth: DEFAULT_CHAIN_DEPTH, maxRuns: DEFAULT_MAX_RUNS }, + }; + } + + async function ensureState() { + if (state) return state; + let loaded = null; + try { + loaded = JSON.parse(await readFile(statePath, 'utf8')); + } catch { + loaded = null; + } + if (loaded && typeof loaded === 'object' && Array.isArray(loaded.members)) { + state = normalize(loaded); + recoverInterrupted(); + rev += 1; + await persistNow(); + } else { + state = await seedState(); + rev += 1; + await persistNow(); + } + return state; + } + + // -------------------------------------------------------------- members + + function findMember(id) { + return state.members.find((member) => member.id === id) || null; + } + + function memberName(id) { + return findMember(id)?.name ?? '已移除成员'; + } + + function pickCoordinator() { + return state.members.find((member) => member.coordinator) || state.members[0] || null; + } + + function parseMentionNames(text) { + const names = []; + const pattern = /@([^\s@,。,.!?!?::;;()()[\]"'“”]{1,24})/g; + let match = pattern.exec(text); + while (match) { + names.push(match[1]); + match = pattern.exec(text); + } + return names; + } + + function resolveMentions(text, explicitIds) { + const resolved = []; + const push = (id) => { + if (id && !resolved.includes(id)) resolved.push(id); + }; + for (const name of parseMentionNames(text)) { + const lowered = name.toLowerCase(); + if (lowered === 'all' || name === '所有人' || name === '全体') { + for (const member of state.members) push(member.id); + continue; + } + const member = state.members.find( + (candidate) => + candidate.name.toLowerCase() === lowered || + (candidate.agentDisplayName && candidate.agentDisplayName.toLowerCase() === lowered), + ); + if (member) push(member.id); + } + for (const id of Array.isArray(explicitIds) ? explicitIds : []) { + if (findMember(String(id))) push(String(id)); + } + return resolved; + } + + function sanitizeMemberInput(body, existing) { + const out = {}; + const has = (key) => body[key] !== undefined; + if (has('name') || !existing) { + const name = String(body.name ?? '').trim(); + if (!name || name.length > MAX_NAME || name.includes('@')) throw httpError(400, 'invalid_name'); + const clash = state.members.some( + (member) => member.name.toLowerCase() === name.toLowerCase() && member.id !== existing?.id, + ); + if (clash) throw httpError(409, 'name_taken'); + out.name = name; + } + if (has('kind') || !existing) { + const kind = body.kind === 'agent' ? 'agent' : 'role'; + out.kind = kind; + } + if (has('agentName') || !existing) { + const agentName = typeof body.agentName === 'string' && body.agentName.trim() ? body.agentName.trim() : null; + out.agentName = agentName; + out.agentDisplayName = + typeof body.agentDisplayName === 'string' && body.agentDisplayName.trim() + ? body.agentDisplayName.trim().slice(0, 60) + : null; + } + if (has('role') || !existing) { + out.role = String(body.role ?? '').trim().slice(0, MAX_ROLE); + } + if (has('instructions') || !existing) { + out.instructions = String(body.instructions ?? '').trim().slice(0, MAX_INSTRUCTIONS); + } + if (has('coordinator')) { + out.coordinator = body.coordinator === true; + } + return out; + } + + function validateMember(member) { + if (member.kind === 'agent' && !member.agentName) throw httpError(400, 'agent_required'); + if (member.kind === 'role' && !member.instructions) throw httpError(400, 'instructions_required'); + } + + function applyCoordinator(member, coordinator) { + if (!coordinator) return; + for (const other of state.members) other.coordinator = other.id === member.id; + } + + // ----------------------------------------------------------------- turns + + function trimMessages() { + if (state.messages.length > MAX_MESSAGES) { + state.messages.splice(0, state.messages.length - MAX_MESSAGES); + } + if (state.approvals.length > MAX_CARDS) state.approvals.splice(0, state.approvals.length - MAX_CARDS); + if (state.questions.length > MAX_CARDS) state.questions.splice(0, state.questions.length - MAX_CARDS); + } + + function enqueue(item) { + const origin = state.messages.find((message) => message.id === item.originId); + if (origin) { + if (!item.force && (origin.runs || 0) >= state.settings.maxRuns) return false; + origin.runs = (origin.runs || 0) + 1; + } + runtime.queue.push({ id: randomUUID(), ...item }); + return true; + } + + function pump() { + while (!disposed && runtime.queue.length > 0 && runtime.active < RUN_LIMIT) { + const item = runtime.queue.shift(); + runtime.active += 1; + void runTurn(item) + .catch((error) => { + context.logger.error('miniapp.turn.failed', { code: codeOf(error) }); + }) + .finally(() => { + runtime.active -= 1; + pump(); + }); + } + } + + function buildPrompt(member, item, message) { + const roster = state.members + .map((other) => { + const tag = other.kind === 'agent' && other.agentDisplayName ? `(${other.agentDisplayName})` : ''; + const self = other.id === member.id ? ' ← 你' : ''; + return `- ${other.name}${tag}:${other.role || '群成员'}${self}`; + }) + .join('\n'); + + const history = state.messages + .filter((entry) => entry.id !== message.id && entry.status !== 'streaming') + .slice(-TRANSCRIPT_MESSAGES) + .map((entry) => `[${entry.author === 'user' ? '用户' : entry.name}] ${truncate(entry.text, 800)}`) + .join('\n'); + const transcript = truncate(history, TRANSCRIPT_CHARS); + + const latest = state.messages.find((entry) => entry.id === item.originId); + const latestText = latest ? truncate(latest.text, 4000) : ''; + const trigger = + item.trigger === 'chain' + ? `成员「${item.triggerName || '其他成员'}」在回复里点名了你` + : item.trigger === 'answer' + ? '你刚才向用户提了问题,用户已经回答' + : '用户在群里点名了你'; + + const identity = + member.kind === 'role' + ? `你的身份:${member.name}。职责:${member.role || '群成员'}。\n${member.instructions}\n` + : `你的身份:${member.name}。职责:${member.role || '群成员'}。\n${ + member.instructions ? `补充要求:${member.instructions}\n` : '' + }`; + + return [ + '你正在一个工作群里和用户以及其他成员协作。', + '', + identity, + '群成员:', + roster, + '', + '群内最近的对话:', + transcript || '(还没有历史消息)', + '', + `现在:${trigger}。请针对下面这条消息给出你在群里的回复。`, + '---', + latestText || '(见上方对话)', + '---', + '', + '回复要求:', + '1. 只输出你在群里要说的正文,不要写“好的”“收到”这类开场,也不要复述成员名单。', + '2. 需要其他成员接手时,在回复里用 @成员名 点名,并说明要他做什么;不需要就只回答自己的部分。', + '3. 不要代替其他成员发言,也不要替用户做决定。', + '4. 需要调用工具才能回答时按需调用;工具审批由群里的用户决定。', + ].join('\n'); + } + + function describeFailure(code, error) { + switch (code) { + case 'NOT_PERMITTED': + return '此 Mini App 的 Agent 运行权限已关闭,请在插件详情里重新打开 session.run。'; + case 'BUSY': { + const reason = /** @type {any} */ (error)?.reason; + if (reason === 'rate_limited') return '已到每分钟启动上限,稍后点重试。'; + if (reason === 'queue_full') return '等待队列已满,稍后点重试。'; + return '该成员会话正忙(可能在侧栏聊天中),稍后点重试。'; + } + case 'SESSION_NOT_FOUND': + return '该成员会话已不存在,请重置该成员会话后重试。'; + case 'AGENT_OUTCOME_UNKNOWN': + return '这一轮的结果无法确认(可能已经运行),请先在会话中查看再决定是否重试。'; + case 'REQUEST_CANCELLED': + return '已取消。'; + case 'AGENT_UNAVAILABLE': + return 'Agent 暂时不可用,稍后重试。'; + case 'INVALID_ARGUMENTS': + return '请求未被接受,请检查成员绑定的 Agent 是否仍然存在。'; + default: + return `运行失败(${code})。`; + } + } + + function handleEvent(run, member, message, event) { + if (!event || typeof event.type !== 'string') return; + switch (event.type) { + case 'run.queued': + message.queued = Number(event.position) || 1; + bump(); + break; + case 'turn.started': + run.rootSessionId = event.sessionId; + member.sessionId = event.sessionId; + message.sessionId = event.sessionId; + message.queued = 0; + bump(); + break; + case 'text.delta': + message.streaming = `${message.streaming || ''}${event.text ?? ''}`; + bump(); + break; + case 'message.committed': { + const text = String(event.text ?? ''); + if (text) { + message.text = message.text ? `${message.text}\n\n${text}` : text; + run.lastCommitted = text; + } + message.streaming = ''; + bump(); + break; + } + case 'tool.started': + message.activity.push({ name: String(event.name ?? 'tool'), ok: null }); + bump(); + break; + case 'tool.finished': { + for (let index = message.activity.length - 1; index >= 0; index -= 1) { + const entry = message.activity[index]; + if (entry.name === String(event.name ?? '') && entry.ok === null) { + entry.ok = event.ok !== false; + break; + } + } + bump(); + break; + } + case 'permission.requested': + createApproval(run, member, message, event); + break; + case 'question.requested': + createQuestion(run, member, message, { + sessionId: event.sessionId, + requestId: event.requestId, + mode: event.mode, + request: event.request, + }); + break; + default: + break; + } + } + + function createApproval(run, member, message, event) { + const card = { + id: randomUUID(), + runId: run.id, + messageId: message.id, + memberId: member.id, + memberName: member.name, + sessionId: String(event.sessionId ?? run.rootSessionId ?? ''), + requestId: String(event.requestId ?? ''), + toolName: String(event.toolName ?? '工具'), + reason: truncate(event.reason ?? '', 600), + toolInput: typeof event.toolInput === 'string' ? truncate(event.toolInput, 2000) : '', + status: 'pending', + createdAt: Date.now(), + }; + state.approvals.push(card); + trimMessages(); + run.pendingApprovals.add(card.id); + bump(); + } + + function createQuestion(run, member, message, source) { + if (!source.request) return; + const card = { + id: randomUUID(), + runId: run.id, + messageId: message.id, + memberId: member.id, + memberName: member.name, + sessionId: String(source.sessionId ?? run.rootSessionId ?? ''), + requestId: String(source.requestId ?? ''), + mode: String(source.mode ?? 'questionnaire'), + request: source.request, + status: 'pending', + createdAt: Date.now(), + }; + state.questions.push(card); + trimMessages(); + run.pendingQuestions.add(card.id); + bump(); + } + + function createMemberMessage(member, item) { + const message = { + id: randomUUID(), + author: 'member', + memberId: member.id, + name: member.name, + text: '', + streaming: '', + mentions: [], + activity: [], + status: 'streaming', + error: null, + originId: item.originId ?? null, + depth: Number(item.depth) || 0, + trigger: item.trigger ?? 'user', + triggerName: item.triggerName ?? null, + chained: [], + runs: 0, + sessionId: member.sessionId ?? null, + queued: 0, + createdAt: Date.now(), + }; + state.messages.push(message); + trimMessages(); + bump(); + return message; + } + + function scheduleChain(member, message, item) { + if (!message.text || item.trigger === 'answer') return; + if ((item.depth || 0) >= state.settings.chainDepth) return; + const targets = resolveMentions(message.text, []).filter((id) => id !== member.id); + for (const id of targets) { + const queued = enqueue({ + memberId: id, + originId: item.originId, + depth: (item.depth || 0) + 1, + trigger: 'chain', + triggerName: member.name, + }); + if (queued) message.chained.push(memberName(id)); + } + if (message.chained.length) bump(); + } + + function settleRun(run, member, message, result, item) { + if (result?.sessionId) { + member.sessionId = result.sessionId; + message.sessionId = result.sessionId; + } + const finalText = String(result?.text ?? '').trim(); + if (finalText && finalText !== String(run.lastCommitted ?? '').trim()) { + message.text = message.text ? `${message.text}\n\n${finalText}` : finalText; + } + message.streaming = ''; + message.queued = 0; + if (result?.pendingQuestion?.request) { + createQuestion(run, member, message, { + sessionId: result.sessionId, + requestId: result.pendingQuestion.requestId, + mode: result.pendingQuestion.mode, + request: result.pendingQuestion.request, + }); + message.status = 'waiting'; + } else if (result?.status === 'finished') { + message.status = 'done'; + } else if (result?.status === 'aborted') { + message.status = 'aborted'; + } else { + message.status = 'error'; + message.error = describeFailure(String(result?.error?.code ?? 'error'), null); + } + bump(); + if (message.status === 'done') scheduleChain(member, message, item); + } + + function failRun(run, member, message, error, item) { + message.streaming = ''; + message.queued = 0; + message.status = 'error'; + message.error = describeFailure(codeOf(error), error); + message.retry = { + memberId: member.id, + originId: item.originId ?? null, + depth: Number(item.depth) || 0, + trigger: item.trigger ?? 'user', + triggerName: item.triggerName ?? null, + }; + bump(); + } + + async function runTurn(item) { + await ensureState(); + const member = findMember(item.memberId); + if (!member) return; + const message = createMemberMessage(member, item); + const run = { + id: randomUUID(), + memberId: member.id, + messageId: message.id, + controller: new AbortController(), + pendingApprovals: new Set(), + pendingQuestions: new Set(), + settled: false, + lastCommitted: '', + rootSessionId: member.sessionId ?? null, + item, + /** @type {(() => void) | null} */ + resolveDone: null, + done: Promise.resolve(), + }; + run.done = new Promise((resolve) => { + run.resolveDone = resolve; + }); + runtime.runs.set(run.id, run); + + const onEvent = (event) => { + try { + handleEvent(run, member, message, event); + } catch (error) { + context.logger.error('miniapp.event.failed', { code: codeOf(error), type: String(event?.type ?? '') }); + } + }; + + const prompt = buildPrompt(member, item, message); + try { + if (!context.agent || typeof context.agent.run !== 'function') { + throw Object.assign(new Error('agent_unavailable'), { code: 'NOT_PERMITTED' }); + } + /** @type {any} */ + const request = { text: prompt }; + if (member.sessionId) { + request.sessionId = member.sessionId; + request.whenBusy = 'queue'; + } else if (member.kind === 'agent' && member.agentName) { + request.agent = member.agentName; + } + let result; + try { + result = await context.agent.run(request, { signal: run.controller.signal, onEvent }); + } catch (error) { + if (codeOf(error) !== 'SESSION_NOT_FOUND' || !member.sessionId) throw error; + member.sessionId = null; + message.sessionId = null; + bump(); + /** @type {any} */ + const retry = { text: prompt }; + if (member.kind === 'agent' && member.agentName) retry.agent = member.agentName; + result = await context.agent.run(retry, { signal: run.controller.signal, onEvent }); + } + settleRun(run, member, message, result, item); + } catch (error) { + failRun(run, member, message, error, item); + } finally { + run.settled = true; + runtime.runs.delete(run.id); + run.resolveDone?.(); + await persistNow(); + } + } + + async function runAnswer(card, answers) { + await ensureState(); + const member = findMember(card.memberId); + if (!member) throw httpError(404, 'member_not_found'); + const waiting = runtime.runs.get(card.runId); + if (waiting) await waiting.done; + + const item = { originId: card.messageId, depth: state.settings.chainDepth, trigger: 'answer' }; + const message = createMemberMessage(member, item); + const run = { + id: randomUUID(), + memberId: member.id, + messageId: message.id, + controller: new AbortController(), + pendingApprovals: new Set(), + pendingQuestions: new Set(), + settled: false, + lastCommitted: '', + rootSessionId: card.sessionId, + item, + resolveDone: null, + done: Promise.resolve(), + }; + run.done = new Promise((resolve) => { + run.resolveDone = resolve; + }); + runtime.runs.set(run.id, run); + const onEvent = (event) => { + try { + handleEvent(run, member, message, event); + } catch (error) { + context.logger.error('miniapp.event.failed', { code: codeOf(error), type: String(event?.type ?? '') }); + } + }; + try { + const result = await context.agent.answer( + { sessionId: card.sessionId, requestId: card.requestId, answers }, + { signal: run.controller.signal, onEvent }, + ); + settleRun(run, member, message, result, item); + } catch (error) { + failRun(run, member, message, error, item); + } finally { + run.settled = true; + runtime.runs.delete(run.id); + run.resolveDone?.(); + await persistNow(); + } + } + + function cancelMember(memberId) { + let cancelled = 0; + for (const run of runtime.runs.values()) { + if (run.memberId === memberId && !run.settled) { + run.controller.abort(); + cancelled += 1; + } + } + const before = runtime.queue.length; + runtime.queue = runtime.queue.filter((item) => item.memberId !== memberId); + for (const card of state.approvals) { + if (card.memberId === memberId && card.status === 'pending') card.status = 'cancelled'; + } + for (const card of state.questions) { + if (card.memberId === memberId && card.status === 'pending') card.status = 'cancelled'; + } + bump(); + return { cancelled, dequeued: before - runtime.queue.length }; + } + + function stopAll() { + for (const run of runtime.runs.values()) { + if (!run.settled) run.controller.abort(); + } + const dequeued = runtime.queue.length; + runtime.queue = []; + for (const card of state.approvals) { + if (card.status === 'pending') card.status = 'cancelled'; + } + for (const card of state.questions) { + if (card.status === 'pending') card.status = 'cancelled'; + } + bump(); + return { dequeued }; + } + + // ------------------------------------------------------------- snapshot + + function memberStatus(memberId) { + for (const run of runtime.runs.values()) { + if (run.memberId === memberId && !run.settled) return 'running'; + } + if (state.approvals.some((card) => card.memberId === memberId && card.status === 'pending')) return 'waiting'; + if (state.questions.some((card) => card.memberId === memberId && card.status === 'pending')) return 'waiting'; + return 'idle'; + } + + function snapshot() { + return { + group: state.group, + members: state.members.map((member) => ({ ...member, status: memberStatus(member.id) })), + messages: state.messages, + approvals: state.approvals, + questions: state.questions, + settings: state.settings, + runtime: { + queue: runtime.queue.length, + active: runtime.active, + agentAvailable: Boolean(context.agent && typeof context.agent.run === 'function'), + agentsError: runtime.agents?.error ?? null, + }, + }; + } + + // --------------------------------------------------------------- routes + + async function readJsonBody(request) { + /** @type {Buffer[]} */ + const chunks = []; + let size = 0; + for await (const chunk of request) { + size += chunk.length; + if (size > MAX_BODY_BYTES) throw httpError(413, 'body_too_large'); + chunks.push(chunk); + } + if (!chunks.length) return {}; + try { + const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { + throw httpError(400, 'invalid_json'); + } + } + + function sendJson(response, status, payload) { + response.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + }); + response.end(JSON.stringify(payload)); + } + + /** @type {Map} */ + const assetCache = new Map(); + async function readAsset(file) { + const cached = assetCache.get(file); + if (cached) return cached; + const buffer = await readFile(join(clientDir, file)); + assetCache.set(file, buffer); + return buffer; + } + + async function handle(request, response) { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const path = url.pathname; + const method = request.method ?? 'GET'; + + const asset = ASSETS.get(path); + if (asset && method === 'GET') { + const body = await readAsset(asset.file); + response.writeHead(200, { 'content-type': asset.type, 'cache-control': 'no-store' }); + response.end(body); + return; + } + + if (path === '/api/state' && method === 'GET') { + await ensureState(); + const since = Number(url.searchParams.get('since') ?? -1); + const sinceBoot = url.searchParams.get('boot') ?? ''; + if (sinceBoot === bootId && since === rev) { + sendJson(response, 200, { unchanged: true, bootId, rev }); + return; + } + sendJson(response, 200, { bootId, rev, state: snapshot() }); + return; + } + + if (path === '/api/agents' && method === 'GET') { + const result = await listAgents(); + runtime.agents = result; + sendJson(response, 200, result); + return; + } + + if (path === '/api/group' && method === 'POST') { + await ensureState(); + const body = await readJsonBody(request); + if (typeof body.name === 'string') { + const name = body.name.trim().slice(0, 40); + if (!name) throw httpError(400, 'invalid_group_name'); + state.group.name = name; + } + if (typeof body.topic === 'string') state.group.topic = body.topic.trim().slice(0, 200); + bump(); + await persistNow(); + sendJson(response, 200, { ok: true, group: state.group }); + return; + } + + if (path === '/api/members' && method === 'POST') { + await ensureState(); + const body = await readJsonBody(request); + const input = sanitizeMemberInput(body, null); + const member = { + id: randomUUID(), + name: input.name, + kind: input.kind, + agentName: input.agentName ?? null, + agentDisplayName: input.agentDisplayName ?? null, + role: input.role ?? '', + instructions: input.instructions ?? '', + coordinator: input.coordinator === true, + sessionId: null, + createdAt: Date.now(), + }; + validateMember(member); + state.members.push(member); + applyCoordinator(member, member.coordinator); + bump(); + await persistNow(); + sendJson(response, 200, { ok: true, member }); + return; + } + + const memberMatch = /^\/api\/members\/([^/]+)(?:\/([a-z]+))?$/.exec(path); + if (memberMatch) { + await ensureState(); + const member = findMember(decodeURIComponent(memberMatch[1])); + if (!member) throw httpError(404, 'member_not_found'); + const action = memberMatch[2]; + + if (!action && method === 'PATCH') { + const body = await readJsonBody(request); + const input = sanitizeMemberInput(body, member); + const before = { kind: member.kind, agentName: member.agentName }; + Object.assign(member, input); + validateMember(member); + if (before.kind !== member.kind || before.agentName !== member.agentName) member.sessionId = null; + applyCoordinator(member, member.coordinator === true); + bump(); + await persistNow(); + sendJson(response, 200, { ok: true, member }); + return; + } + + if (!action && method === 'DELETE') { + const result = cancelMember(member.id); + state.members = state.members.filter((entry) => entry.id !== member.id); + if (!state.members.some((entry) => entry.coordinator) && state.members[0]) { + state.members[0].coordinator = true; + } + bump(); + await persistNow(); + sendJson(response, 200, { ok: true, ...result }); + return; + } + + if (action === 'cancel' && method === 'POST') { + const result = cancelMember(member.id); + await persistNow(); + sendJson(response, 200, { ok: true, ...result }); + return; + } + + if (action === 'reset' && method === 'POST') { + cancelMember(member.id); + member.sessionId = null; + bump(); + await persistNow(); + sendJson(response, 200, { ok: true, member }); + return; + } + + throw httpError(405, 'method_not_allowed'); + } + + if (path === '/api/messages' && method === 'POST') { + await ensureState(); + const body = await readJsonBody(request); + const text = String(body.text ?? '').trim(); + if (!text) throw httpError(400, 'empty_message'); + if (text.length > MAX_USER_TEXT) throw httpError(400, 'text_too_long'); + const targets = resolveMentions(text, body.mentions); + const message = { + id: randomUUID(), + author: 'user', + memberId: null, + name: '我', + text, + streaming: '', + mentions: targets.map((id) => memberName(id)), + activity: [], + status: 'done', + error: null, + originId: null, + depth: 0, + trigger: 'user', + triggerName: null, + chained: [], + runs: 0, + sessionId: null, + createdAt: Date.now(), + }; + state.messages.push(message); + trimMessages(); + const effective = targets.length ? targets : [pickCoordinator()?.id].filter(Boolean); + let enqueued = 0; + for (const id of effective) { + if (enqueue({ memberId: id, originId: message.id, depth: 0, trigger: 'user' })) enqueued += 1; + } + bump(); + await persistNow(); + pump(); + sendJson(response, 200, { ok: true, message, enqueued }); + return; + } + + if (path === '/api/retry' && method === 'POST') { + await ensureState(); + const body = await readJsonBody(request); + const message = state.messages.find((entry) => entry.id === String(body.messageId ?? '')); + if (!message || !message.retry) throw httpError(404, 'retry_not_available'); + const retry = message.retry; + message.retry = null; + message.status = 'superseded'; + const queued = enqueue({ + memberId: retry.memberId, + originId: retry.originId, + depth: retry.depth, + trigger: retry.trigger, + triggerName: retry.triggerName, + force: true, + }); + bump(); + await persistNow(); + pump(); + sendJson(response, 200, { ok: true, queued }); + return; + } + + const approvalMatch = /^\/api\/approvals\/([^/]+)$/.exec(path); + if (approvalMatch && method === 'POST') { + await ensureState(); + const body = await readJsonBody(request); + const decision = body.decision === 'allowOnce' ? 'allowOnce' : body.decision === 'deny' ? 'deny' : null; + if (!decision) throw httpError(400, 'invalid_decision'); + const card = state.approvals.find((entry) => entry.id === decodeURIComponent(approvalMatch[1])); + if (!card) throw httpError(404, 'approval_not_found'); + if (card.status !== 'pending') throw httpError(409, 'already_settled'); + try { + await context.agent.reply({ sessionId: card.sessionId, requestId: card.requestId, decision }); + card.status = decision === 'allowOnce' ? 'allowed' : 'denied'; + } catch (error) { + card.status = codeOf(error) === 'REQUEST_NOT_FOUND' ? 'stale' : 'pending'; + if (card.status === 'pending') { + bump(); + sendJson(response, 502, { error: 'reply_failed', code: codeOf(error) }); + return; + } + } + card.decidedAt = Date.now(); + bump(); + await persistNow(); + sendJson(response, 200, { ok: true, approval: card }); + return; + } + + const questionMatch = /^\/api\/questions\/([^/]+)$/.exec(path); + if (questionMatch && method === 'POST') { + await ensureState(); + const body = await readJsonBody(request); + const card = state.questions.find((entry) => entry.id === decodeURIComponent(questionMatch[1])); + if (!card) throw httpError(404, 'question_not_found'); + if (card.status !== 'pending') throw httpError(409, 'already_settled'); + const answers = Array.isArray(body.answers) ? body.answers : null; + if (!answers) throw httpError(400, 'invalid_answers'); + const normalized = answers.map((answer) => ({ + stepId: String(answer?.stepId ?? ''), + selectedOptionIds: Array.isArray(answer?.selectedOptionIds) ? answer.selectedOptionIds.map(String) : [], + selectedOther: answer?.selectedOther === true, + ...(typeof answer?.otherText === 'string' ? { otherText: answer.otherText.slice(0, 4000) } : {}), + ...(answer?.skipped === true ? { skipped: true } : {}), + })); + card.status = 'answered'; + card.answeredAt = Date.now(); + bump(); + await persistNow(); + void runAnswer(card, normalized).catch((error) => { + context.logger.error('miniapp.answer.failed', { code: codeOf(error) }); + }); + sendJson(response, 200, { ok: true, question: card }); + return; + } + + if (path === '/api/stop' && method === 'POST') { + await ensureState(); + const result = stopAll(); + await persistNow(); + sendJson(response, 200, { ok: true, ...result }); + return; + } + + if (path === '/api/clear' && method === 'POST') { + await ensureState(); + stopAll(); + state.messages = []; + state.approvals = []; + state.questions = []; + for (const member of state.members) member.sessionId = null; + bump(); + await persistNow(); + sendJson(response, 200, { ok: true }); + return; + } + + sendJson(response, 404, { error: 'not_found' }); + } + + const server = createServer((request, response) => { + void handle(request, response).catch((error) => { + const status = Number(/** @type {any} */ (error)?.statusCode) || 500; + const code = codeOf(error); + context.logger.error('miniapp.request.failed', { code, status }); + if (response.headersSent) { + response.end(); + return; + } + sendJson(response, status, { error: code }); + }); + }); + + await new Promise((resolve, reject) => { + const onError = (/** @type {unknown} */ error) => reject(error); + server.once('error', onError); + server.listen(context.listen.port, context.listen.host, () => { + server.off('error', onError); + resolve(undefined); + }); + }); + context.logger.info('miniapp.runtime.listening', { surface: '/group' }); + + let disposal; + const dispose = () => { + if (disposal) return disposal; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + for (const run of runtime.runs.values()) { + if (!run.settled) run.controller.abort(); + } + runtime.queue = []; + if (persistTimer) { + clearTimeout(persistTimer); + persistTimer = null; + } + const flushed = Promise.race([ + persistNow(), + new Promise((resolve) => setTimeout(resolve, 500)), + ]); + server.closeAllConnections?.(); + disposal = flushed.then( + () => + new Promise((resolve) => { + server.close(() => resolve(undefined)); + }), + ); + return disposal; + }; + const onAbort = () => { + void dispose().catch(() => undefined); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} diff --git a/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/package.json b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +}