diff --git a/README.md b/README.md index 1a78e881..bf9f680d 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,8 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | MiniApp | What it does | Author | | --- | --- | --- | +| [道闸运维知识助手](plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/) | Run a local-model operations console: ingest manuals into a searchable knowledge base, answer with cited standard answers and analysis, and turn plain-language change requests into reviewable SEARCH/REPLACE patches with unified diff, automatic backup and rollback | [yakuyama1979-art](https://github.com/yakuyama1979-art) | +| [道闸运维知识助手](plugins/pendingauthor/daozha-ops-knowledge-assistant/) | Run a local-model operations console: ingest manuals into a searchable knowledge base, answer with cited standard answers and analysis, and turn plain-language change requests into reviewable SEARCH/REPLACE patches with unified diff, automatic backup and rollback | [pendingauthor](https://github.com/pendingauthor) | | [DeepSeek Chat Migration](plugins/danielwalnut/deepseek-chat-migration/) | Preview official DeepSeek web exports locally, restore branches and attachments, and import selected conversations as native MiniMax Code sessions with a bundled importer | [DanielWalnut](https://github.com/DanielWalnut) | | [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | Run OpenFilm inside MiniMax Code with the desktop interface: Studio editor, chat column and local agents, with a web-Studio fallback | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | | [Dynamic Workflow Console](plugins/stevenjj33/workflow-console/) | Run and supervise MiniMax Code dynamic workflows from one page: live status, a stage-and-dependency flow graph, per-node output, approval and control, templates, and report export | [stevenjj33](https://github.com/stevenjj33) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 19c1ac99..3f6bed4e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -57,6 +57,8 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | MiniApp | 功能 | 作者 | | --- | --- | --- | +| [道闸运维知识助手](plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/) | 本地模型驱动的运维控制台:投喂资料建知识库、带来源的标准答案与解析、可审阅的 SEARCH/REPLACE 补丁与 unified diff、自动备份与回滚 | [yakuyama1979-art](https://github.com/yakuyama1979-art) | +| [道闸运维知识助手](plugins/pendingauthor/daozha-ops-knowledge-assistant/) | 本地模型驱动的运维控制台:投喂资料建知识库、带来源的标准答案与解析、可审阅的 SEARCH/REPLACE 补丁与 unified diff、自动备份与回滚 | [pendingauthor](https://github.com/pendingauthor) | | [DeepSeek 会话迁移](plugins/danielwalnut/deepseek-chat-migration/README_ZH.md) | 在本机预览 DeepSeek 网页版官方导出包,恢复分支和附件,并用自带的导入脚本把选中对话导入成 MiniMax Code 原生会话 | [DanielWalnut](https://github.com/DanielWalnut) | | [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | 把 OpenFilm 装进 MiniMax Code:桌面版界面(Studio 编辑器 + 聊天栏 + 本地 agent),桌面模式不可用时回落网页版 | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | | [动态工作流控制台](plugins/stevenjj33/workflow-console/README.zh-CN.md) | 在一个页面里运行并盯住 MiniMax Code 动态工作流:实时状态、按阶段与依赖画出的流程图、节点输出、审核与控制、模板与报告导出 | [stevenjj33](https://github.com/stevenjj33) | diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/.minimax-plugin/plugin.json b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/.minimax-plugin/plugin.json new file mode 100644 index 00000000..81dc39ce --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/.minimax-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": 1, + "name": "daozha-ops-knowledge-assistant", + "displayName": "道闸运维知识助手", + "version": "1.0.0", + "description": "Local-model operations console: ingest manuals into a searchable knowledge base, answer with cited standard answers and analysis, and turn plain-language change requests into reviewable SEARCH/REPLACE patches with unified diff, automatic backup and rollback.", + "author": "yakuyama1979-art", + "icon": "icon.png", + "category": "Business", + "exampleQueries": [ + "打开道闸运维知识助手", + "投喂道闸售后运维规则手册并回答质保期问题" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/LICENSE b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/LICENSE new file mode 100644 index 00000000..123f143a --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 yakuyama1979-art + +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/yakuyama1979-art/daozha-ops-knowledge-assistant/README.md b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/README.md new file mode 100644 index 00000000..f30edfab --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/README.md @@ -0,0 +1,148 @@ +# 道闸运维知识助手 + +A local-model operations console for barrier-gate / access-control after-sales teams. + +Feed it your own manuals, rule sheets and contracts and it builds a searchable local knowledge +base. Ask a question and it returns a **standard answer with its analysis, a confidence score and +the exact source chunks it used**. Ask it to change a piece of code in plain language and it +returns a reviewable `SEARCH`/`REPLACE` patch plus a unified diff — the file is backed up before +anything is written, and any change can be rolled back from the same panel. + +Everything that needs understanding, judgement or generation calls a real model. There are no +canned answers, no keyword matching and no fixed scoring: the local model does the work, and the +page only renders what the model returned. + +## What it does + +| Panel | What it does | +| --- | --- | +| 知识库 / Knowledge base | Ingests `.txt`, `.md`, `.docx`, `.xlsx` and `.pdf` files, tags each with a category (知识点 / 规则 / 合同 / 其他), asks the model for a title, a summary and the key points, splits the text into chunks and stores one `bge-m3` embedding per chunk. | +| 运维问答 / Ops Q&A | Embeds the question, retrieves the top-k chunks by cosine similarity, and asks the model for a standard answer, an analysis, a confidence score and the gaps the material does not cover. Returns every retrieved source with its score. | +| AI 改代码 / AI code edit | Locates the region to change, asks the model for `SEARCH`/`REPLACE` blocks, requires each `SEARCH` block to match the file **exactly once**, and shows a unified diff before anything is written. Files above 12 000 characters go through a two-stage flow (model locates the region, then the patch is generated inside a bounded window). | +| 部署 / Deploy | Runs a deployment command that you saved in the settings, in a working directory that must sit inside an allowed write root, and keeps the exit code, stdout and stderr of every run. | +| 路由与设置 / Routing & settings | Switches the routing mode, and holds the allowed write roots, the material directories, the backup root and the deployment commands. | + +## Model routing + +The app can run entirely on your own machine, entirely on the Host's online model, or mix the +two. Four modes are available in **路由与设置**: + +| Mode | Behaviour | +| --- | --- | +| `auto` | Picks a route per request from the size of the prompt and the local model's context window. If the request is too large for the local window it starts with the online model and degrades back to local; otherwise it starts local and degrades to online. | +| `local_first` | Always tries the local model first, degrades to the online model when the local call fails. | +| `local_only` | Local only. Never calls the online model. | +| `online_only` | Online only. Never calls the local model. | + +Degradation works in both directions and is always reported: every answer and every patch shows +the route that was requested, the route that was actually used, the model that served it and the +reason. `local_only` and `online_only` never degrade. + +Local models come from [Ollama](https://ollama.com) on `http://127.0.0.1:11434` (the base URL is +configurable). The app prefers a chat model whose name starts with `qwen3:14b`; otherwise it +picks the largest available chat model, or falls back to the first one. The context window is +fixed by the model's size: **14B-class models get 8 192 tokens, smaller models get 16 384**. + +The embedding model is always `bge-m3` and never participates in routing — retrieval quality does +not depend on which chat model answered the question. + +The "online" route is the Host's own Agent channel (`context.agent`). It is used for a single +scoped JSON reply, with no file, tool or network access of its own. + +## Install and open it + +1. Install the plugin package (this directory) in MiniMax Code. +2. Start [Ollama](https://ollama.com) and pull the models you want to use: + ```bash + ollama pull qwen3:14b + ollama pull bge-m3 + ``` +3. Open the app and go to **路由与设置**: + - **允许写入的目录** — the roots the AI code editor may write to. Nothing outside these roots + can be modified; a target outside them is rejected with an explicit error. + - **资料目录** — the roots that may be browsed and ingested from disk. + - **备份根目录** — where backups are written. Each patch application creates + `//` holding the original file, a `manifest.json` that maps the backup + file name to its original path, and a `record.json` with the patch and hash details. + - **部署命令** — the commands the deploy panel may run. +4. Pick a routing mode and start ingesting material. + +The panel headings are in Chinese because this is the app's original product language; the +README, the plugin manifest and the code comments are in English. + +## Backup and rollback + +Applying a patch never overwrites a file silently: + +1. The original file is copied into a new timestamped directory under the backup root. +2. `manifest.json` maps `` → ``. +3. `record.json` stores the patch, the unified diff, the SHA-256 of the file before and after, + and the status. +4. The new content is written atomically. + +The backup list in the **AI 改代码** panel lists every recorded operation. **回滚** restores the +file from its backup and verifies the result against the stored hash. Backups written by an +earlier tool with the same `manifest.json` layout are listed and can be rolled back too. + +## Safety properties + +- Writes are confined to the configured write roots. The check resolves the real path, so a + symlink cannot be used to escape a root. +- Only text formats on the editable-extension list can be patched. +- A patch is applied only when every `SEARCH` block matches the current file **exactly once**; a + non-unique or stale match is refused and the model is asked again. +- The deploy panel can only run commands that are already saved in the settings — there is no + free-text command field on a single request — and each command's working directory must be + inside an allowed write root. +- Secrets never reach the page: the page talks to the Node service over narrow business routes + and no model call happens in the browser. + +## Tested environment + +- MiniMax Code 3.1.19 on Windows 11 (build 26300). +- The package declares `agentAccess: ["session.run"]` and `surface.window`, so it needs + **MiniMax Code 3.1.2 or later**. +- Client acceptance exercised in the in-app Browser: ingesting a `.txt` operations manual + (model summary, `bge-m3` index, 1 chunk), asking a warranty-period question (standard answer, + analysis, confidence, cited source with its similarity score, routing decision), previewing a + patch (unique `SEARCH` match and a correct unified diff), applying it (backup directory with + `manifest.json`, before/after SHA-256), rolling it back (file restored, status updated), + running a deployment command (exit code and output captured), switching the routing mode + (persisted and restored), and rejecting a write outside the allowed roots. The console reported + no errors and no failed requests. +- The Node-side test suite additionally covered `.docx`, `.xlsx`, `.pdf` (ASCII and Chinese text + via `ToUnicode`), GBK-encoded text and a corrupt file, all against a real local Ollama. + +## Data & access + +- **Files read** — files the user uploads in the page (`.txt`, `.md`, `.docx`, `.xlsx`, `.pdf`), + files browsed under the configured material directories, and the target source file of a patch + request (which must sit inside an allowed write root). +- **Files written** — the patched target file; the backup copy, `manifest.json` and `record.json` + under the configured backup root; and the Mini App's own state (see below). +- **Network hosts** — the local Ollama server at `http://127.0.0.1:11434` (configurable base URL), + used for `/api/tags`, `/api/chat` and `/api/embed`. No other outbound request is made by this + package. +- **Spawned processes** — the deployment commands the user saved in the settings, each started with + `shell: true` in its configured working directory; on Windows the process tree is terminated with + `taskkill` when the app is disposed. +- **Agent turns** — `context.agent.run` is used for the "online" route, one scoped JSON reply per + request, with no file, tool or network access granted to that turn. +- **Conversations read** — none. The package does not declare `session.read` and never lists or + observes the user's conversations. +- **Tools called** — none. The package does not declare `toolAccess` and never calls a Connector + or MCP tool. +- **Microphone / camera / notifications** — none. `deviceAccess` is not declared and the page + requests no browser permission. +- **Host navigation read** — none. `hostAccess` is not declared; the page only follows the Host's + light/dark theme, which needs no grant. +- **Where state is stored** — in the Host's private `context.dataDir`: `kb/` holds the ingested + chunks, their embeddings and the document records, `patches/` holds the pending patch payloads, + `settings.json` holds the routing mode, the roots, the backup root and the deployment commands, + and `deploy-logs.json` holds the recent deployment logs. The page keeps only its current view + state in `localStorage`. The package reads no Host file and no runtime state outside + `context.dataDir`. + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/README.zh-CN.md b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/README.zh-CN.md new file mode 100644 index 00000000..99699667 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/README.zh-CN.md @@ -0,0 +1,116 @@ +# 道闸运维知识助手 + +面向道闸 / 道闸售后运维团队的本地模型运维控制台。 + +把你自己的手册、规则文件和合同投喂进来,它会建成本地可检索的知识库;提问时给出**带来源的标准 +答案与解析、置信度和命中的原文片段**;用自然语言要求改代码时,给出可审阅的 `SEARCH`/`REPLACE` +补丁与 unified diff——写盘前自动备份,任何一次改动都能在同一个面板回滚。 + +凡是需要理解、判断或生成的地方,都调用真实模型:没有写死的回复,没有关键词匹配,没有固定评分。 +模型返回什么,页面就渲染什么。 + +## 功能 + +| 面板 | 作用 | +| --- | --- | +| 知识库 | 投喂 `.txt`、`.md`、`.docx`、`.xlsx`、`.pdf`,标注分类(知识点 / 规则 / 合同 / 其他),由模型生成标题、摘要与要点,切分成片段后用 `bge-m3` 建立索引。 | +| 运维问答 | 对问题做向量检索,取回相关度最高的片段,再由模型产出标准答案、解析、置信度与资料未覆盖的部分,并列出全部来源及分数。 | +| AI 改代码 | 定位要改的区域,由模型产出 `SEARCH`/`REPLACE` 补丁块,要求每个 `SEARCH` 在原文中**唯一匹配**,写入前先展示 unified diff。超过 12000 字符的大文件走「模型定位区域 → 在窗口内生成补丁」两阶段。 | +| 部署 | 执行设置里已保存的部署命令,工作目录必须位于允许写入的目录之下,并保留退出码、标准输出与错误输出。 | +| 路由与设置 | 切换路由模式,维护允许写入的目录、资料目录、备份根目录与部署命令。 | + +## 模型路由 + +四种模式在**路由与设置**里切换: + +| 模式 | 行为 | +| --- | --- | +| `auto` | 按请求体量与本地模型上下文窗口逐次决策。超出本地窗口先走在线模型、失败再降级回本地;否则先走本地、失败降级到在线。 | +| `local_first` | 始终先调用本地模型,本地失败降级到在线模型。 | +| `local_only` | 只调用本地模型,不做任何在线降级。 | +| `online_only` | 只调用在线模型,不做任何本地降级。 | + +降级是双向的,且每次都会说明:答案与补丁都会显示「请求的路由 / 实际使用的路由 / 实际使用的模型 / +原因」。`local_only` 与 `online_only` 不降级。 + +本地模型来自 [Ollama](https://ollama.com),默认 `http://127.0.0.1:11434`(地址可改)。优先选择名称以 +`qwen3:14b` 开头的对话模型,否则取参数量最大的可用对话模型,再退回第一个。上下文窗口按模型规模固定: +**14B 级 8192 token,更小的模型 16384 token。** + +嵌入模型固定使用 `bge-m3`,且不参与路由——检索质量不随回答问题的聊天模型变化。 + +「在线」路由走宿主的 Agent 通道(`context.agent`),每次只取一次受限的 JSON 回复,该回合本身没有文件、 +工具与网络权限。 + +## 安装与打开 + +1. 在 MiniMax Code 中安装本插件包。 +2. 启动 [Ollama](https://ollama.com) 并拉取所需模型: + ```bash + ollama pull qwen3:14b + ollama pull bge-m3 + ``` +3. 打开应用,进入**路由与设置**: + - **允许写入的目录**——AI 改代码只能写这些根目录,越界会被明确拒绝。 + - **资料目录**——允许浏览与投喂的根目录。 + - **备份根目录**——备份写入位置。每次应用补丁都会新建 `<备份根目录>/<时间戳>/`,内含原文备份、 + 把备份文件名映射回原路径的 `manifest.json`,以及记录补丁与哈希的 `record.json`。 + - **部署命令**——部署面板允许执行的命令。 +4. 选择路由模式,开始投喂资料。 + +面板标题保持中文,这是产品原本的语言;README、插件清单与代码注释使用英文。 + +## 备份与回滚 + +应用补丁不会静默覆盖文件: + +1. 原文复制到备份根目录下新建的时间戳目录。 +2. `manifest.json` 记录 `<备份文件名>` → `<原文件绝对路径>`。 +3. `record.json` 记录补丁、unified diff、改动前后的 SHA-256 与状态。 +4. 新内容以原子方式写盘。 + +**AI 改代码**面板列出所有已记录的操作,**回滚**会从备份还原文件并校验哈希。早前工具用同一套 +`manifest.json` 格式留下的备份同样会被列出,也可以回滚。 + +## 安全边界 + +- 写入被限制在配置的允许目录内,校验使用真实路径,符号链接无法越界。 +- 只有可编辑扩展名白名单里的文本文件能被改写。 +- 只有当每个 `SEARCH` 块在当前文件中**唯一匹配**时补丁才会落盘;匹配不唯一或已过期都会拒绝,并让模型重做。 +- 部署面板只能执行设置里已保存的命令,没有单次请求的自由文本命令入口;每条命令的工作目录必须位于允许写入的目录内。 +- 密钥不会进入页面:页面只通过受限业务路由与 Node 服务通信,浏览器里不发生任何模型调用。 + +## 测试环境 + +- MiniMax Code 3.1.19,Windows 11(build 26300)。 +- 插件声明了 `agentAccess: ["session.run"]` 与 `surface.window`,因此需要 **MiniMax Code 3.1.2 或更高版本**。 +- 已在应用内浏览器完成客户端验收:投喂 `.txt` 运维手册(模型摘要、`bge-m3` 索引、1 个片段)、询问质保期 + 问题(标准答案、解析、置信度、引用来源及其相关度、路由决策)、补丁预览(`SEARCH` 唯一匹配与正确的 + unified diff)、应用补丁(备份目录含 `manifest.json`、前后 SHA-256)、回滚(文件还原、状态更新)、执行 + 部署命令(捕获退出码与输出)、切换路由模式(落盘并还原)、越界写入被拒。控制台无报错、无失败请求。 +- Node 侧测试套件另外覆盖了 `.docx`、`.xlsx`、`.pdf`(ASCII 与通过 `ToUnicode` 的中文)、GBK 编码文本与损坏 + 文件,全部基于真实本地 Ollama。 + +## 数据与权限 + +- **读取的文件**——页面中上传的文件(`.txt`、`.md`、`.docx`、`.xlsx`、`.pdf`)、在资料目录下浏览的文件, + 以及补丁请求的目标源文件(必须位于允许写入的目录内)。 +- **写入的文件**——被改动的目标文件;备份根目录下的备份副本、`manifest.json` 与 `record.json`;以及应用 + 自身的状态文件(见下)。 +- **网络主机**——本地 Ollama 服务 `http://127.0.0.1:11434`(地址可改),使用 `/api/tags`、`/api/chat`、 + `/api/embed`。本插件包不发起其他出站请求。 +- **派生进程**——用户在设置中保存的部署命令,以 `shell: true` 在配置的工作目录中启动;Windows 上应用销毁 + 时用 `taskkill` 结束整个进程树。 +- **Agent 回合**——`context.agent.run` 用于「在线」路由,每次请求一个受限的 JSON 回复,该回合不获得文件、 + 工具或网络权限。 +- **读取的会话**——无。未声明 `session.read`,从不列出或观察用户会话。 +- **调用的工具**——无。未声明 `toolAccess`,从不调用 Connector 或 MCP 工具。 +- **麦克风 / 摄像头 / 通知**——无。未声明 `deviceAccess`,页面不申请任何浏览器权限。 +- **读取宿主导航**——无。未声明 `hostAccess`;页面只跟随宿主明暗主题,该能力无需授权。 +- **状态存放位置**——宿主的私有 `context.dataDir`:`kb/` 存放投喂的片段、向量与文档记录,`patches/` 存放待应用 + 的补丁,`settings.json` 存放路由模式、各目录与部署命令,`deploy-logs.json` 存放部署日志。页面只在 + `localStorage` 保存当前视图状态。插件不读取任何宿主文件,也不读取 `context.dataDir` 之外的运行时状态。 + +## 许可证 + +MIT,见 [LICENSE](LICENSE)。 diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/icon.png b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/icon.png new file mode 100644 index 00000000..299a26cb Binary files /dev/null and b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/icon.png differ diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/app.js b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/app.js new file mode 100644 index 00000000..3703b738 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/app.js @@ -0,0 +1,901 @@ +// 道闸运维知识助手 — Client logic. +// Every panel talks to the Node service over narrow business routes; no model call +// ever happens in the page. + +const state = { + view: 'kb', + settings: null, + routingModes: [], + writeRoots: [], + categories: [], + ollama: null, + onlineModel: null, + documents: [], + backups: [], + deployLogs: [], + kbFiles: [], + kbSelected: null, + patchFiles: [], + patchSelected: null, + patchId: null, +}; + +const VIEW_META = { + kb: { title: '知识库', desc: '投喂道闸运维资料,建立可检索的本地知识库' }, + ask: { title: '运维问答', desc: '检索本地知识库,产出带来源的标准答案与解析' }, + patch: { title: 'AI 改代码', desc: '生成 SEARCH/REPLACE 补丁,备份后可回滚' }, + deploy: { title: '部署', desc: '执行已配置的部署命令并保留执行日志' }, + settings: { title: '路由与设置', desc: '切换模型路由模式,配置资料目录与备份位置' }, +}; + +const VIEW_STATE_KEY = 'miniapp-view-state'; + +const element = (id) => document.getElementById(id); + +function escapeHtml(value) { + return String(value ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +async function api(path, options = {}) { + const response = await fetch(path, { + method: options.method || 'GET', + headers: options.body === undefined ? undefined : { 'content-type': 'application/json' }, + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + const raw = await response.text(); + let payload = {}; + try { + payload = raw ? JSON.parse(raw) : {}; + } catch { + payload = { ok: false, error: 'invalid_response', message: raw.slice(0, 200) }; + } + if (!response.ok || payload.ok === false) { + const error = new Error(payload.message || payload.error || `请求失败 (${response.status})`); + error.code = payload.error || 'request_failed'; + throw error; + } + return payload; +} + +function toast(message, tone = 'info') { + const stack = element('toasts'); + const node = document.createElement('div'); + node.className = 'toast'; + node.dataset.tone = tone; + node.textContent = message; + stack.append(node); + window.setTimeout(() => node.remove(), 5200); +} + +function setNote(id, message, tone = '') { + const node = element(id); + if (!node) return; + node.textContent = message; + if (tone) node.dataset.tone = tone; + else delete node.dataset.tone; +} + +function describeRoute(route) { + if (!route) return '未知路由'; + const parts = [`路由:${route.requested}`]; + parts.push(`实际:${route.used === 'local' ? '本地' : '在线'}${route.model ? ` · ${route.model}` : ''}`); + if (route.degraded) parts.push(`降级自:${route.degradedFrom === 'local' ? '本地' : '在线'}`); + if (route.reason) parts.push(route.reason); + return parts.join('|'); +} + +/* ------------------------------------------------------------ view switch */ + +function switchView(name) { + if (!VIEW_META[name]) return; + state.view = name; + for (const panel of document.querySelectorAll('.view-panel')) { + panel.hidden = panel.id !== `view-${name}`; + } + for (const button of document.querySelectorAll('.nav-item')) { + const active = button.dataset.view === name; + button.classList.toggle('is-active', active); + if (active) button.setAttribute('aria-current', 'page'); + else button.removeAttribute('aria-current'); + } + element('view-title').textContent = VIEW_META[name].title; + element('view-desc').textContent = VIEW_META[name].desc; + saveViewState(); +} + +/* ------------------------------------------------------------ view state */ + +function saveViewState() { + try { + localStorage.setItem( + VIEW_STATE_KEY, + JSON.stringify({ + view: state.view, + askQuestion: element('ask-question').value, + askTopK: element('ask-topk').value, + patchRequirement: element('patch-requirement').value, + patchPath: element('patch-path').value, + }), + ); + } catch { + /* storage may be unavailable */ + } +} + +function restoreViewState() { + let saved = null; + try { + saved = JSON.parse(localStorage.getItem(VIEW_STATE_KEY) || 'null'); + } catch { + saved = null; + } + if (!saved) return; + if (saved.view && VIEW_META[saved.view]) state.view = saved.view; + if (typeof saved.askQuestion === 'string') element('ask-question').value = saved.askQuestion; + if (typeof saved.askTopK === 'string') element('ask-topk').value = saved.askTopK; + if (typeof saved.patchRequirement === 'string') { + element('patch-requirement').value = saved.patchRequirement; + } + if (typeof saved.patchPath === 'string') element('patch-path').value = saved.patchPath; +} + +/* -------------------------------------------------------------- rendering */ + +function renderSidebarStatus() { + const dot = element('status-dot'); + const text = element('status-text'); + if (state.ollama && state.ollama.reachable) { + const chat = state.ollama.models.filter((model) => + (model.capabilities || []).includes('completion'), + ); + const embedding = state.ollama.models.filter((model) => + (model.capabilities || []).includes('embedding'), + ); + dot.dataset.state = chat.length ? 'ok' : 'warn'; + text.textContent = `本地 Ollama ${state.ollama.version || ''} 可用 · 对话模型 ${chat.length} 个 · 嵌入模型 ${embedding.length} 个`; + } else { + dot.dataset.state = 'error'; + text.textContent = `本地模型不可用:${(state.ollama && state.ollama.error) || '未知原因'}`; + } +} + +function renderDocuments() { + element('kb-count').textContent = `${state.documents.length} 份`; + const container = element('kb-documents'); + if (!state.documents.length) { + container.innerHTML = + '

知识库还是空的

投喂一份运维手册或规则文件后即可开始问答。

'; + return; + } + const rows = state.documents + .map((document) => { + const route = document.modelRoute ? document.modelRoute.used : ''; + return ` + +

${escapeHtml(document.title || document.name)}

+

${escapeHtml(document.name)} · ${escapeHtml(document.kind)} · ${document.sizeBytes} 字节

+ + ${escapeHtml(document.category)} + ${document.chunkCount} 片段 + +

${escapeHtml(String(document.summary || '').slice(0, 60) || '—')}

+

${escapeHtml(route ? `入库模型:${route}` : '')}

+ + + + + `; + }) + .join(''); + container.innerHTML = `
+ + ${rows}
资料分类索引摘要
`; +} + +function renderBackups() { + element('backup-count').textContent = `${state.backups.length} 条`; + const container = element('patch-backups'); + if (!state.backups.length) { + container.innerHTML = + '

还没有备份记录

应用补丁时会自动备份原文并写入 manifest.json。

'; + return; + } + const rows = state.backups + .map( + (record) => ` + +

${escapeHtml(record.targetPath)}

+

${escapeHtml(record.backupDirectory)}

+ + ${escapeHtml(record.status === 'rolled_back' ? '已回滚' : '已应用')} + ${escapeHtml(String(record.createdAt).replace('T', ' ').slice(0, 19))} + + + + `, + ) + .join(''); + container.innerHTML = `
+ + ${rows}
目标文件状态时间
`; +} + +function renderDeploy() { + const container = element('deploy-list'); + const commands = (state.settings && state.settings.deployCommands) || []; + if (!commands.length) { + container.innerHTML = + '

还没有部署命令

在左侧添加一条命令,工作目录必须在允许写入的目录之下。

'; + } else { + container.innerHTML = `
${commands + .map( + (command) => `
+
+

${escapeHtml(command.name)}

+

${escapeHtml(command.command)}

+

工作目录:${escapeHtml(command.workdir)}

+
+
+ + + +
+
`, + ) + .join('')}
`; + } + + element('deploy-log-count').textContent = `${state.deployLogs.length} 条`; + const logs = element('deploy-logs'); + if (!state.deployLogs.length) { + logs.innerHTML = + '

还没有执行记录

执行部署命令后这里会保留命令、退出码与输出。

'; + } else { + logs.innerHTML = `
${state.deployLogs + .map( + (log) => `
+
+ ${escapeHtml(log.name)} + ${log.ok ? '成功' : '失败'} · 退出码 ${log.code ?? '—'} +
+

${escapeHtml(log.command)}

+

${escapeHtml(log.workdir)} · ${log.durationMs}ms · ${escapeHtml(String(log.at).replace('T', ' ').slice(0, 19))}

+ ${log.stdout ? `
${escapeHtml(log.stdout.slice(0, 4000))}
` : ''} + ${log.stderr ? `
${escapeHtml(log.stderr.slice(0, 2000))}
` : ''} +
`, + ) + .join('')}
`; + } +} + +function renderSettings() { + const container = element('routing-modes'); + const current = state.settings ? state.settings.routingMode : 'auto'; + container.innerHTML = state.routingModes + .map( + (mode) => + ``, + ) + .join(''); + const active = state.routingModes.find((mode) => mode.id === current); + element('routing-hint').textContent = active ? active.hint : ''; + + const local = element('local-models'); + const models = (state.ollama && state.ollama.models) || []; + if (!models.length) { + local.innerHTML = `

本地模型不可用

${escapeHtml((state.ollama && state.ollama.error) || '未检测到 Ollama')}

`; + } else { + local.innerHTML = `
${models + .map( + (model) => `
+
+

${escapeHtml(model.name)}

+

${escapeHtml(model.parameterSize || '未知规模')} · ${escapeHtml((model.capabilities || []).join(' / '))}

+
+
`, + ) + .join('')}
`; + } + + const online = element('online-model'); + online.innerHTML = `
+
+

${escapeHtml((state.onlineModel && state.onlineModel.label) || '在线模型')}

+

${state.onlineModel && state.onlineModel.available ? '通道已就绪,用于本地失败时的降级' : '通道未授权,无法作为降级目标'}

+
+ ${state.onlineModel && state.onlineModel.available ? '可用' : '不可用'} +
`; + + if (state.settings) { + element('write-roots').value = (state.settings.writeRoots || []).join('\n'); + element('ingest-roots').value = (state.settings.ingestRoots || []).join('\n'); + element('backup-root').value = state.settings.backupRoot || ''; + } +} + +function renderKbRoots() { + const roots = (state.settings && state.settings.ingestRoots) || []; + const select = element('kb-root'); + const previous = select.value; + select.innerHTML = roots + .map((root) => ``) + .join(''); + if (roots.includes(previous)) select.value = previous; +} + +function renderPatchRoots() { + const select = element('patch-root'); + const previous = select.value; + select.innerHTML = state.writeRoots + .map((root) => ``) + .join(''); + if (state.writeRoots.includes(previous)) select.value = previous; + element('patch-roots-label').textContent = state.writeRoots.length + ? state.writeRoots.join('、') + : '尚未配置(请先在「路由与设置」中填写允许写入的目录)'; +} + +function renderCategories() { + const select = element('kb-category'); + const previous = select.value; + select.innerHTML = state.categories + .map((category) => ``) + .join(''); + if (state.categories.includes(previous)) select.value = previous; +} + +function renderFileList(containerId, files, selectedPath, emptyText) { + const container = element(containerId); + if (!files.length) { + container.innerHTML = `

${escapeHtml(emptyText)}

`; + return; + } + container.innerHTML = files + .map( + (file) => ``, + ) + .join(''); +} + +/* ---------------------------------------------------------------- actions */ + +async function loadState() { + const payload = await api('/api/state'); + state.settings = payload.settings; + state.routingModes = payload.routingModes || []; + state.writeRoots = payload.writeRoots || []; + state.categories = payload.categories || []; + state.ollama = payload.ollama; + state.onlineModel = payload.onlineModel; + state.documents = payload.documents || []; + state.backups = payload.backups || []; + state.deployLogs = payload.deployLogs || []; + + renderSidebarStatus(); + renderCategories(); + renderKbRoots(); + renderPatchRoots(); + renderDocuments(); + renderBackups(); + renderDeploy(); + renderSettings(); +} + +async function loadFiles(kind, root) { + const query = `kind=${encodeURIComponent(kind)}&root=${encodeURIComponent(root)}`; + const payload = await api(`/api/files?${query}`); + if (kind === 'document') { + state.kbFiles = payload.files; + state.kbSelected = null; + renderFileList('kb-file-list', state.kbFiles, null, '该目录下没有可投喂的资料文件'); + element('kb-ingest-path-btn').disabled = true; + } else { + state.patchFiles = payload.files; + state.patchSelected = null; + renderFileList('patch-file-list', state.patchFiles, null, '该目录下没有可修改的源文件'); + } +} + +async function fileToBase64(file) { + const bytes = new Uint8Array(await file.arrayBuffer()); + let binary = ''; + const chunkSize = 0x8000; + for (let index = 0; index < bytes.length; index += chunkSize) { + binary += String.fromCharCode.apply(null, bytes.subarray(index, index + chunkSize)); + } + return btoa(binary); +} + +async function ingestFromUpload(event) { + event.preventDefault(); + const input = element('kb-files'); + const category = element('kb-category').value; + const files = Array.from(input.files || []); + if (!files.length) { + setNote('kb-upload-status', '请先选择要投喂的文件', 'error'); + return; + } + const button = element('kb-upload-btn'); + button.disabled = true; + try { + for (const file of files) { + setNote('kb-upload-status', `正在解析并索引:${file.name} …`); + const dataBase64 = await fileToBase64(file); + const payload = await api('/api/documents', { + method: 'POST', + body: { category, name: file.name, dataBase64 }, + }); + setNote( + 'kb-upload-status', + `已投喂 ${payload.document.name}(${payload.document.chunkCount} 片段,模型:${payload.route.used === 'local' ? '本地' : '在线'})`, + 'ok', + ); + toast(`已入库:${payload.document.name}`, 'ok'); + } + input.value = ''; + await loadState(); + } catch (error) { + setNote('kb-upload-status', error.message, 'error'); + } finally { + button.disabled = false; + } +} + +async function ingestFromPath() { + if (!state.kbSelected) return; + const button = element('kb-ingest-path-btn'); + button.disabled = true; + try { + setNote('kb-browse-status', '正在解析并索引 …'); + const payload = await api('/api/documents', { + method: 'POST', + body: { category: element('kb-category').value, path: state.kbSelected }, + }); + setNote( + 'kb-browse-status', + `已投喂 ${payload.document.name}(${payload.document.chunkCount} 片段)`, + 'ok', + ); + toast(`已入库:${payload.document.name}`, 'ok'); + await loadState(); + } catch (error) { + setNote('kb-browse-status', error.message, 'error'); + } finally { + button.disabled = false; + } +} + +async function submitQuestion(event) { + event.preventDefault(); + const button = element('ask-btn'); + const question = element('ask-question').value.trim(); + if (!question) { + setNote('ask-status', '请先输入问题', 'error'); + return; + } + button.disabled = true; + setNote('ask-status', '正在检索知识库并生成答案 …'); + try { + const payload = await api('/api/ask', { + method: 'POST', + body: { question, topK: Number(element('ask-topk').value) || undefined }, + }); + renderAnswer(payload); + setNote('ask-status', '', ''); + } catch (error) { + setNote('ask-status', error.message, 'error'); + element('ask-result-card').hidden = true; + } finally { + button.disabled = false; + } +} + +function renderAnswer(payload) { + element('ask-result-card').hidden = false; + element('ask-route-pill').textContent = + payload.route.used === 'local' ? `本地模型 · ${payload.route.model}` : '在线模型'; + element('ask-route-pill').dataset.tone = payload.route.degraded ? 'warn' : 'ok'; + + const confidence = + typeof payload.answer.confidence === 'number' ? `${payload.answer.confidence} / 100` : '未给出'; + const missing = payload.answer.missing.length + ? `

资料未覆盖

${payload.answer.missing + .map((item) => `· ${escapeHtml(item)}`) + .join('\n')}

` + : ''; + + const sources = payload.sources.length + ? `
+

检索到的来源(按相关度排序)

+
${payload.sources + .map( + (source) => `
+
+ ${escapeHtml(source.documentName)} + ${escapeHtml(source.category)} + 片段 ${source.chunkIndex + 1} + 相关度 ${source.score} +
+

${escapeHtml(source.preview)}

+
`, + ) + .join('')}
+
` + : `

检索到的来源

知识库中没有匹配的资料片段,请先投喂相关运维资料。

`; + + element('ask-result').innerHTML = ` +
+

标准答案

+

${escapeHtml(payload.answer.standardAnswer)}

+
+
+

解析

+

${escapeHtml(payload.answer.analysis || '模型未单独给出解析')}

+
+
+

置信度

+

${escapeHtml(confidence)}

+
+ ${missing} + ${sources} +
+

调用路由

+

${escapeHtml(describeRoute(payload.route))}

+
`; +} + +async function submitPatch(event) { + event.preventDefault(); + const button = element('patch-preview-btn'); + const targetPath = element('patch-path').value.trim(); + const requirement = element('patch-requirement').value.trim(); + if (!targetPath) { + setNote('patch-status', '请先选择或填写目标文件路径', 'error'); + return; + } + if (!requirement) { + setNote('patch-status', '请先描述修改要求', 'error'); + return; + } + button.disabled = true; + setNote('patch-status', '模型正在定位代码并生成补丁 …'); + try { + const payload = await api('/api/patch', { method: 'POST', body: { targetPath, requirement } }); + state.patchId = payload.patchId; + renderPatch(payload); + setNote('patch-status', '', ''); + } catch (error) { + setNote('patch-status', error.message, 'error'); + element('patch-result-card').hidden = true; + } finally { + button.disabled = false; + } +} + +function renderPatch(payload) { + element('patch-result-card').hidden = false; + element('patch-route-pill').textContent = + payload.route.used === 'local' ? `本地模型 · ${payload.route.model}` : '在线模型'; + element('patch-route-pill').dataset.tone = payload.route.degraded ? 'warn' : 'ok'; + + const blocks = payload.blocks + .map( + (block, index) => `
+

补丁块 ${index + 1} · SEARCH 必须唯一匹配原文

+
<<<<<<< SEARCH
+${escapeHtml(block.search)}
+=======
+${escapeHtml(block.replace)}
+>>>>>>> REPLACE
+
`, + ) + .join(''); + + const diff = payload.diff + .split('\n') + .map((line) => { + if (line.startsWith('@@')) return `${escapeHtml(line)}`; + if (line.startsWith('+')) return `${escapeHtml(line)}`; + if (line.startsWith('-')) return `${escapeHtml(line)}`; + return escapeHtml(line); + }) + .join('\n'); + + element('patch-result').innerHTML = ` +
+

目标文件

+

${escapeHtml(payload.targetPath)}

+

定位方式

+

${escapeHtml(payload.locatedBy)} · 第 ${payload.window.from}-${payload.window.to} 行 · 文件共 ${payload.fileLines} 行${payload.window.truncated ? '(区域已截断)' : ''}

+
+ ${blocks} +
+

unified diff

+
${diff}
+
+
+

调用路由

+

${escapeHtml(describeRoute(payload.route))}

+
+
+ + 应用前会自动备份原文并写入 manifest.json。 +
`; +} + +async function applyPatch(patchId) { + if (!patchId) return; + try { + const payload = await api('/api/patch/apply', { method: 'POST', body: { patchId } }); + toast(`已写入,备份目录:${payload.backupPath}`, 'ok'); + element('patch-result').insertAdjacentHTML( + 'beforeend', + `

应用结果

+

备份目录:${escapeHtml(payload.backupPath)}
manifest:${escapeHtml(payload.manifestPath)}
原文件哈希:${escapeHtml(payload.sha256Before)}
新文件哈希:${escapeHtml(payload.sha256After)}

`, + ); + await loadState(); + } catch (error) { + toast(error.message, 'error'); + } +} + +async function rollbackOperation(operationId) { + try { + const payload = await api('/api/rollback', { method: 'POST', body: { operationId } }); + if (payload.ok) toast(`已回滚:${payload.targetPath}`, 'ok'); + else toast('回滚后校验失败,请检查备份文件', 'error'); + await loadState(); + } catch (error) { + toast(error.message, 'error'); + } +} + +async function saveDeployCommands() { + const name = element('deploy-name').value.trim(); + const command = element('deploy-command').value.trim(); + const workdir = element('deploy-workdir').value.trim(); + if (!command) { + setNote('deploy-config-status', '请填写要执行的命令', 'error'); + return; + } + const commands = [...((state.settings && state.settings.deployCommands) || [])]; + const existingIndex = commands.findIndex((item) => item.name === name && name); + const entry = { id: existingIndex >= 0 ? commands[existingIndex].id : `cmd-${Date.now()}`, name: name || command, command, workdir }; + if (existingIndex >= 0) commands[existingIndex] = entry; + else commands.push(entry); + try { + await api('/api/settings', { method: 'POST', body: { deployCommands: commands } }); + setNote('deploy-config-status', '已保存部署命令', 'ok'); + toast('部署命令已保存', 'ok'); + await loadState(); + } catch (error) { + setNote('deploy-config-status', error.message, 'error'); + } +} + +async function runDeploy(commandId) { + try { + const payload = await api('/api/deploy', { method: 'POST', body: { commandId } }); + const log = payload.log; + if (log.ok) toast(`命令执行成功:${log.name}`, 'ok'); + else toast(`命令执行失败(退出码 ${log.code ?? '—'})`, 'error'); + await loadState(); + } catch (error) { + toast(error.message, 'error'); + } +} + +async function removeDeploy(commandId) { + const commands = ((state.settings && state.settings.deployCommands) || []).filter( + (item) => item.id !== commandId, + ); + try { + await api('/api/settings', { method: 'POST', body: { deployCommands: commands } }); + await loadState(); + } catch (error) { + toast(error.message, 'error'); + } +} + +async function setRoutingMode(mode) { + try { + await api('/api/settings', { method: 'POST', body: { routingMode: mode } }); + await loadState(); + toast(`路由模式已切换为 ${mode}`, 'ok'); + } catch (error) { + toast(error.message, 'error'); + } +} + +async function saveRoots(event) { + event.preventDefault(); + const writeRoots = element('write-roots') + .value.split('\n') + .map((line) => line.trim()) + .filter(Boolean); + const roots = element('ingest-roots') + .value.split('\n') + .map((line) => line.trim()) + .filter(Boolean); + try { + await api('/api/settings', { + method: 'POST', + body: { + writeRoots, + ingestRoots: roots, + backupRoot: element('backup-root').value.trim(), + }, + }); + setNote('roots-status', '已保存允许写入的目录、资料目录与备份位置', 'ok'); + toast('设置已保存', 'ok'); + await loadState(); + } catch (error) { + setNote('roots-status', error.message, 'error'); + } +} + +async function deleteDocument(documentId) { + try { + await api(`/api/documents?id=${encodeURIComponent(documentId)}`, { method: 'DELETE' }); + toast('资料已从知识库移除', 'ok'); + await loadState(); + } catch (error) { + toast(error.message, 'error'); + } +} + +/* ----------------------------------------------------------------- wiring */ + +function bindEvents() { + for (const button of document.querySelectorAll('.nav-item')) { + button.addEventListener('click', () => switchView(button.dataset.view)); + } + + element('topbar-actions').innerHTML = + ''; + element('refresh-state').addEventListener('click', async () => { + try { + await loadState(); + toast('状态已刷新', 'ok'); + } catch (error) { + toast(error.message, 'error'); + } + }); + + element('kb-upload-form').addEventListener('submit', ingestFromUpload); + element('kb-ingest-path-btn').addEventListener('click', ingestFromPath); + element('kb-root').addEventListener('change', async () => { + try { + await loadFiles('document', element('kb-root').value); + setNote('kb-browse-status', ''); + } catch (error) { + setNote('kb-browse-status', error.message, 'error'); + } + }); + element('kb-file-list').addEventListener('click', (event) => { + const button = event.target.closest('[data-file]'); + if (!button) return; + state.kbSelected = button.dataset.file; + renderFileList('kb-file-list', state.kbFiles, state.kbSelected, ''); + element('kb-ingest-path-btn').disabled = false; + }); + + element('ask-form').addEventListener('submit', submitQuestion); + + element('patch-form').addEventListener('submit', submitPatch); + element('patch-root').addEventListener('change', async () => { + try { + await loadFiles('code', element('patch-root').value); + } catch (error) { + toast(error.message, 'error'); + } + }); + element('patch-file-list').addEventListener('click', (event) => { + const button = event.target.closest('[data-file]'); + if (!button) return; + state.patchSelected = button.dataset.file; + element('patch-path').value = button.dataset.file; + renderFileList('patch-file-list', state.patchFiles, state.patchSelected, ''); + }); + + element('patch-result').addEventListener('click', (event) => { + const button = event.target.closest('[data-apply-patch]'); + if (button) void applyPatch(button.dataset.applyPatch); + }); + element('patch-backups').addEventListener('click', (event) => { + const button = event.target.closest('[data-rollback]'); + if (button) void rollbackOperation(button.dataset.rollback); + }); + element('kb-documents').addEventListener('click', (event) => { + const button = event.target.closest('[data-delete-document]'); + if (button) void deleteDocument(button.dataset.deleteDocument); + }); + + element('deploy-form').addEventListener('submit', (event) => { + event.preventDefault(); + void saveDeployCommands(); + }); + element('deploy-reset-btn').addEventListener('click', () => { + element('deploy-name').value = ''; + element('deploy-command').value = ''; + element('deploy-workdir').value = ''; + setNote('deploy-config-status', ''); + }); + element('deploy-list').addEventListener('click', (event) => { + const run = event.target.closest('[data-run-deploy]'); + if (run) { + void runDeploy(run.dataset.runDeploy); + return; + } + const edit = event.target.closest('[data-edit-deploy]'); + if (edit) { + const command = ((state.settings && state.settings.deployCommands) || []).find( + (item) => item.id === edit.dataset.editDeploy, + ); + if (command) { + element('deploy-name').value = command.name; + element('deploy-command').value = command.command; + element('deploy-workdir').value = command.workdir; + } + return; + } + const remove = event.target.closest('[data-remove-deploy]'); + if (remove) void removeDeploy(remove.dataset.removeDeploy); + }); + + element('routing-modes').addEventListener('click', (event) => { + const button = event.target.closest('[data-routing]'); + if (button) void setRoutingMode(button.dataset.routing); + }); + element('roots-form').addEventListener('submit', saveRoots); + + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') saveViewState(); + }); +} + +function applyHostTheme() { + const host = window.mcode && window.mcode.miniapp && window.mcode.miniapp.host; + if (!host || !host.ui || typeof host.ui.subscribe !== 'function') { + const media = window.matchMedia('(prefers-color-scheme: dark)'); + const apply = () => { + document.documentElement.dataset.theme = media.matches ? 'dark' : 'light'; + }; + media.addEventListener('change', apply); + apply(); + return; + } + const subscription = host.ui.subscribe( + ({ theme }) => { + if (theme === 'dark' || theme === 'light') document.documentElement.dataset.theme = theme; + }, + { onError: () => undefined }, + ); + window.addEventListener('pagehide', () => subscription && subscription.dispose(), { once: true }); +} + +async function boot() { + applyHostTheme(); + restoreViewState(); + bindEvents(); + switchView(state.view); + try { + await loadState(); + const roots = (state.settings && state.settings.ingestRoots) || []; + if (roots.length) await loadFiles('document', roots[0]); + if (state.writeRoots.length) await loadFiles('code', state.writeRoots[0]); + } catch (error) { + setNote('kb-upload-status', error.message, 'error'); + toast(error.message, 'error'); + } +} + +void boot(); diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/index.html b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/index.html new file mode 100644 index 00000000..0eac24fa --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/index.html @@ -0,0 +1,275 @@ + + + + + + 道闸运维知识助手 + + + +
+ + +
+
+
+

知识库

+

投喂道闸运维资料,建立可检索的本地知识库

+
+
+
+ +
+ +
+
+
+

投喂资料

+

支持 txt / md / docx / xlsx / pdf,投喂后由本地模型自动归纳并向量化。

+
+
+ + +
+
+ + +
+ +

+
+
+ +
+

从资料目录投喂

+

从已配置的资料目录中选择文件,换合同或规则时可直接重新投喂。

+
+
+ + +
+
+ +

+
+
+
+ +
+
+

已入库资料

+ 0 份 +
+
+
+
+ + + + + + + + + + + + +
+
+
+ +
+ + + diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/styles.css b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/styles.css new file mode 100644 index 00000000..bf89a650 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/client/styles.css @@ -0,0 +1,810 @@ +/* 道闸运维知识助手 — Mini App Client styles. + Semantic color tokens follow the MiniMax Code visual baseline. */ + +: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-code-bg: #f7f7f8; + --mcode-focus: #0094fc; +} + +[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-code-bg: #1f1f1f; + --mcode-focus: #0077d9; +} + +* { + box-sizing: border-box; +} + +[hidden] { + display: none !important; +} + +html, +body { + margin: 0; + padding: 0; +} + +body { + background: var(--mcode-bg-secondary); + color: var(--mcode-text); + font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', 'PingFang SC', + 'Hiragino Sans GB', 'Microsoft YaHei', Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +h1, +h2, +h3 { + margin: 0; + font-weight: 600; + line-height: 1.4; +} + +p { + margin: 0; +} + +code, +pre, +.mono { + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} + +.layout { + display: flex; + min-height: 100vh; + align-items: stretch; +} + +/* ------------------------------------------------------------- sidebar */ + +.sidebar { + width: 220px; + flex: 0 0 220px; + display: flex; + flex-direction: column; + gap: 20px; + padding: 20px 14px; + background: var(--mcode-surface); + border-right: 1px solid var(--mcode-border); +} + +.brand { + display: flex; + gap: 10px; + align-items: flex-start; + padding: 0 6px; + flex: none; +} + +.brand-mark { + width: 22px; + height: 22px; + flex: none; + margin-top: 2px; + fill: none; + stroke: var(--mcode-accent); + stroke-width: 1.6; + stroke-linecap: round; + stroke-linejoin: round; +} + +.brand-title { + font-size: 14px; + font-weight: 600; + color: var(--mcode-text); + white-space: nowrap; +} + +.brand-sub { + margin-top: 2px; + font-size: 12px; + color: var(--mcode-text-subtle); + white-space: nowrap; +} + +.nav { + display: flex; + flex-direction: column; + gap: 2px; +} + +.nav-item { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + padding: 8px 10px; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--mcode-text-muted); + font: inherit; + text-align: left; + cursor: pointer; + transition: background-color 150ms ease-out, color 150ms ease-out; +} + +.nav-item svg { + width: 16px; + height: 16px; + flex: none; + fill: none; + stroke: currentColor; + stroke-width: 1.6; + stroke-linecap: round; + stroke-linejoin: round; +} + +.nav-item:hover { + background: var(--mcode-surface-muted); + color: var(--mcode-text); +} + +.nav-item.is-active { + background: var(--mcode-surface-muted); + color: var(--mcode-text); + font-weight: 500; +} + +.nav-item:focus-visible, +.btn:focus-visible, +.picker-item:focus-visible, +input:focus-visible, +select:focus-visible, +textarea:focus-visible { + outline: 2px solid var(--mcode-focus); + outline-offset: 1px; +} + +.sidebar-status { + margin-top: auto; + display: flex; + gap: 8px; + align-items: flex-start; + padding: 10px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + font-size: 12px; + color: var(--mcode-text-muted); + line-height: 1.45; +} + +.status-dot { + width: 7px; + height: 7px; + margin-top: 6px; + flex: none; + border-radius: 50%; + background: var(--mcode-text-subtle); +} + +.status-dot[data-state='ok'] { + background: var(--mcode-success); +} + +.status-dot[data-state='warn'] { + background: var(--mcode-warning); +} + +.status-dot[data-state='error'] { + background: var(--mcode-danger); +} + +/* ---------------------------------------------------------------- main */ + +.main { + flex: 1 1 auto; + min-width: 0; + display: flex; + flex-direction: column; +} + +.topbar { + display: flex; + gap: 16px; + align-items: flex-start; + justify-content: space-between; + padding: 20px 24px 16px; + background: var(--mcode-surface); + border-bottom: 1px solid var(--mcode-border); +} + +.topbar-copy h1 { + font-size: 18px; + line-height: 28px; +} + +.topbar-copy p { + margin-top: 2px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.topbar-actions { + display: flex; + gap: 8px; + align-items: center; +} + +.content { + flex: 1 1 auto; + padding: 24px; + display: flex; + flex-direction: column; + gap: 24px; +} + +.view-panel { + display: flex; + flex-direction: column; + gap: 24px; +} + +.grid-two { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); + gap: 24px; + align-items: start; +} + +/* --------------------------------------------------------------- cards */ + +.card { + background: var(--mcode-surface); + border: 1px solid var(--mcode-border); + border-radius: 12px; + padding: 20px 22px; +} + +.card-head { + display: flex; + gap: 12px; + align-items: center; + justify-content: space-between; + margin-bottom: 12px; +} + +.card-title { + font-size: 16px; + line-height: 24px; +} + +.card-desc { + margin-top: 4px; + margin-bottom: 16px; + font-size: 12px; + color: var(--mcode-text-muted); + line-height: 1.6; +} + +.pill { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 10px; + border-radius: 999px; + background: var(--mcode-surface-muted); + border: 1px solid var(--mcode-border); + font-size: 12px; + color: var(--mcode-text-muted); + white-space: nowrap; +} + +.pill[data-tone='ok'] { + color: var(--mcode-success); + border-color: color-mix(in srgb, var(--mcode-success) 40%, transparent); +} + +.pill[data-tone='warn'] { + color: var(--mcode-warning); + border-color: color-mix(in srgb, var(--mcode-warning) 40%, transparent); +} + +.pill[data-tone='error'] { + color: var(--mcode-danger); + border-color: color-mix(in srgb, var(--mcode-danger) 40%, transparent); +} + +/* --------------------------------------------------------------- forms */ + +.stack { + display: flex; + flex-direction: column; + gap: 12px; +} + +/* A lone primary button sizes to its label instead of stretching across the form. */ +.stack > .btn { + align-self: flex-start; +} + +.field { + display: flex; + flex-direction: column; + gap: 6px; +} + +.field label { + font-size: 12px; + color: var(--mcode-text-muted); +} + +.field-inline { + max-width: 180px; +} + +input[type='text'], +input[type='number'], +select, +textarea { + width: 100%; + min-height: 36px; + padding: 7px 10px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-bg); + color: var(--mcode-text); + font: inherit; + font-size: 13px; +} + +textarea { + resize: vertical; + line-height: 1.6; +} + +input::placeholder, +textarea::placeholder { + color: var(--mcode-text-subtle); +} + +input[type='file'] { + padding: 7px 10px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.row-actions { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 34px; + padding: 6px 14px; + border-radius: 8px; + border: 1px solid transparent; + font: inherit; + font-size: 13px; + cursor: pointer; + transition: background-color 150ms ease-out, border-color 150ms ease-out, + color 150ms ease-out, opacity 150ms ease-out; +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.btn-primary { + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); +} + +.btn-secondary { + background: var(--mcode-surface-muted); + border-color: var(--mcode-border); + color: var(--mcode-text); +} + +.btn-ghost { + background: transparent; + border-color: var(--mcode-border); + color: var(--mcode-text-muted); +} + +.btn-danger { + background: transparent; + border-color: color-mix(in srgb, var(--mcode-danger) 45%, transparent); + color: var(--mcode-danger); +} + +.btn-small { + min-height: 28px; + padding: 3px 10px; + font-size: 12px; +} + +.form-note { + font-size: 12px; + color: var(--mcode-text-muted); + min-height: 18px; + line-height: 1.5; +} + +.form-note[data-tone='error'] { + color: var(--mcode-danger); +} + +.form-note[data-tone='ok'] { + color: var(--mcode-success); +} + +/* ------------------------------------------------------------- pickers */ + +.picker { + max-height: 240px; + overflow-y: auto; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-bg); +} + +.picker-item { + display: flex; + gap: 10px; + align-items: baseline; + width: 100%; + padding: 7px 10px; + border: 0; + border-bottom: 1px solid var(--mcode-border); + background: transparent; + color: var(--mcode-text); + font: inherit; + font-size: 13px; + text-align: left; + cursor: pointer; +} + +.picker-item:last-child { + border-bottom: 0; +} + +.picker-item:hover { + background: var(--mcode-surface-muted); +} + +.picker-item[aria-selected='true'] { + background: var(--mcode-surface-muted); + box-shadow: inset 2px 0 0 var(--mcode-accent); +} + +.picker-item .picker-meta { + margin-left: auto; + font-size: 11px; + color: var(--mcode-text-subtle); + white-space: nowrap; +} + +.empty-state { + padding: 28px 16px; + text-align: center; + color: var(--mcode-text-muted); + font-size: 13px; +} + +.empty-state .empty-title { + color: var(--mcode-text); + font-weight: 500; + margin-bottom: 4px; +} + +/* --------------------------------------------------------------- table */ + +.table-wrap { + overflow-x: auto; + border: 1px solid var(--mcode-border); + border-radius: 8px; +} + +table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +th { + padding: 9px 12px; + background: var(--mcode-surface-muted); + color: var(--mcode-text-muted); + font-weight: 500; + font-size: 12px; + text-align: left; + white-space: nowrap; +} + +td { + padding: 10px 12px; + border-top: 1px solid var(--mcode-border); + vertical-align: top; +} + +td.cell-actions { + text-align: right; + white-space: nowrap; +} + +.cell-title { + font-weight: 500; + color: var(--mcode-text); +} + +.cell-meta { + margin-top: 2px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +/* Narrow columns keep their content on one line; the table scrolls in its container. */ +.cell-nowrap { + white-space: nowrap; +} + +/* -------------------------------------------------------------- answer */ + +.answer-block + .answer-block { + margin-top: 16px; + padding-top: 16px; + border-top: 1px solid var(--mcode-border); +} + +.answer-label { + font-size: 12px; + color: var(--mcode-text-muted); + margin-bottom: 6px; +} + +.answer-text { + font-size: 14px; + line-height: 1.65; + color: var(--mcode-text); + white-space: pre-wrap; +} + +.source-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.source-item { + padding: 10px 12px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); +} + +.source-head { + display: flex; + gap: 8px; + align-items: center; + flex-wrap: wrap; + font-size: 12px; + color: var(--mcode-text-muted); + margin-bottom: 4px; +} + +.source-name { + color: var(--mcode-text); + font-weight: 500; + font-size: 13px; +} + +.source-text { + font-size: 12px; + color: var(--mcode-text-muted); + line-height: 1.6; +} + +/* --------------------------------------------------------------- code */ + +.code-block { + margin: 0; + padding: 12px 14px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-code-bg); + color: var(--mcode-text); + font-size: 12px; + line-height: 1.6; + overflow-x: auto; + white-space: pre; +} + +.code-block + .code-block { + margin-top: 12px; +} + +.diff-add { + color: var(--mcode-success); +} + +.diff-del { + color: var(--mcode-danger); +} + +.diff-hunk { + color: var(--mcode-accent); +} + +/* ------------------------------------------------------------ segmented */ + +.segmented { + display: inline-flex; + flex-wrap: wrap; + gap: 4px; + padding: 4px; + border-radius: 8px; + background: var(--mcode-surface-muted); + border: 1px solid var(--mcode-border); +} + +.segmented-item { + padding: 6px 14px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--mcode-text-muted); + font: inherit; + font-size: 13px; + cursor: pointer; + transition: background-color 150ms ease-out, color 150ms ease-out; +} + +.segmented-item:hover { + color: var(--mcode-text); +} + +.segmented-item[aria-checked='true'] { + background: var(--mcode-surface); + color: var(--mcode-text); + font-weight: 500; + box-shadow: 0 1px 2px rgb(10 10 10 / 8%); +} + +/* -------------------------------------------------------------- models */ + +.model-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.model-row { + display: flex; + gap: 10px; + align-items: center; + justify-content: space-between; + padding: 8px 10px; + border: 1px solid var(--mcode-border); + border-radius: 8px; +} + +.model-name { + font-size: 13px; + font-weight: 500; +} + +.model-meta { + font-size: 12px; + color: var(--mcode-text-muted); +} + +/* --------------------------------------------------------------- toast */ + +.toast-stack { + position: fixed; + right: 20px; + bottom: 20px; + display: flex; + flex-direction: column; + gap: 8px; + z-index: 40; +} + +.toast { + max-width: 360px; + padding: 10px 14px; + border-radius: 8px; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface); + color: var(--mcode-text); + font-size: 13px; + box-shadow: 0 0 20px rgb(10 10 10 / 8%); +} + +.toast[data-tone='error'] { + border-color: color-mix(in srgb, var(--mcode-danger) 45%, transparent); + color: var(--mcode-danger); +} + +.toast[data-tone='ok'] { + border-color: color-mix(in srgb, var(--mcode-success) 45%, transparent); + color: var(--mcode-success); +} + +/* ------------------------------------------------------------ responsive */ + +@media (max-width: 900px) { + .layout { + flex-direction: column; + } + + .sidebar { + width: 100%; + flex: none; + flex-direction: column; + align-items: stretch; + gap: 12px; + border-right: 0; + border-bottom: 1px solid var(--mcode-border); + padding: 12px 16px; + } + + .nav { + flex-direction: row; + gap: 4px; + overflow-x: auto; + } + + .nav-item { + width: auto; + white-space: nowrap; + } + + .sidebar-status { + display: none; + } + + .content, + .topbar { + padding: 16px; + } +} + +@media (prefers-reduced-motion: reduce) { + * { + transition-duration: 0.01ms !important; + animation-duration: 0.01ms !important; + } +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/miniapp.json b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/miniapp.json new file mode 100644 index 00000000..7b1f6a4b --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/miniapp.json @@ -0,0 +1,31 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/dashboard", + "window": { + "width": 1280, + "height": 860, + "minWidth": 720, + "minHeight": 520, + "resizable": true + } + }, + "mcpEndpoints": [], + "agentAccess": [ + "session.run" + ], + "agentConcurrency": 2 +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/backup.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/backup.mjs new file mode 100644 index 00000000..e958bb2d --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/backup.mjs @@ -0,0 +1,159 @@ +// Backup before writing, manifest recording, and rollback. +// The backup location follows the established workflow: \\. + +import { createHash, randomUUID } from 'node:crypto'; +import path from 'node:path'; +import { ensureDir, readJson, writeFileAtomic, writeJsonAtomic } from './store.mjs'; +import { assertWritable, findWriteRoot } from './paths.mjs'; + +export function sha256(buffer) { + return createHash('sha256').update(buffer).digest('hex'); +} + +function stamp(date = new Date()) { + const pad = (value) => String(value).padStart(2, '0'); + return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad( + date.getHours(), + )}${pad(date.getMinutes())}${pad(date.getSeconds())}`; +} + +function flattenName(targetPath, root) { + const relative = path.relative(root, targetPath) || path.basename(targetPath); + const flat = relative.split(path.sep).join('__').replace(/[^\w.\-]/g, '_'); + return flat.length > 120 ? `${flat.slice(0, 100)}_${sha256(targetPath).slice(0, 8)}` : flat; +} + +/** + * Writes the original file into the backup directory and records the operation. + * @param {{ backupRoot:string, targetPath:string, root:string, originalBuffer:Buffer, patch:Array, diff:string }} input + */ +export async function createBackup(input) { + const { backupRoot, targetPath, root, originalBuffer, patch, diff } = input; + const operationId = randomUUID(); + const directory = path.join(backupRoot, `${stamp()}_${operationId.slice(0, 8)}`); + await ensureDir(directory); + + const backupFile = flattenName(targetPath, root); + await writeFileAtomic(path.join(directory, backupFile), originalBuffer); + + // manifest.json keeps the established shape: backup file name -> original absolute path. + const manifest = { [backupFile]: targetPath }; + await writeJsonAtomic(path.join(directory, 'manifest.json'), manifest); + + const record = { + id: operationId, + createdAt: new Date().toISOString(), + targetPath, + root, + backupFile, + backupDirectory: directory, + originalSha256: sha256(originalBuffer), + originalBytes: originalBuffer.length, + patch, + diff, + status: 'applied', + rolledBackAt: null, + rollbackResult: null, + }; + await writeJsonAtomic(path.join(directory, 'record.json'), record); + return record; +} + +/** + * Lists every recorded operation, newest first. Backups written by the earlier + * desktop tool are listed too when they only carry a manifest.json. + * @param {string} backupRoot + */ +export async function listBackups(backupRoot) { + const { readdir } = await import('node:fs/promises'); + let entries = []; + try { + entries = await readdir(backupRoot, { withFileTypes: true }); + } catch { + return []; + } + const results = []; + for (const entry of entries) { + if (!entry.isDirectory()) continue; + const directory = path.join(backupRoot, entry.name); + const record = await readJson(path.join(directory, 'record.json'), null); + if (record) { + results.push(record); + continue; + } + const manifest = await readJson(path.join(directory, 'manifest.json'), null); + if (!manifest || typeof manifest !== 'object') continue; + for (const [backupFile, targetPath] of Object.entries(manifest)) { + if (typeof targetPath !== 'string' || !path.isAbsolute(targetPath)) continue; + results.push({ + id: `legacy-${entry.name}-${backupFile}`, + createdAt: legacyTimestamp(entry.name), + targetPath, + root: findWriteRoot(targetPath) || path.dirname(targetPath), + backupFile, + backupDirectory: directory, + originalSha256: null, + originalBytes: null, + patch: [], + diff: '', + status: 'applied', + legacy: true, + rolledBackAt: null, + rollbackResult: null, + }); + } + } + return results.sort((left, right) => String(right.createdAt).localeCompare(String(left.createdAt))); +} + +function legacyTimestamp(name) { + const matched = /(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})/.exec(name); + if (!matched) return new Date(0).toISOString(); + return new Date( + Number(matched[1]), + Number(matched[2]) - 1, + Number(matched[3]), + Number(matched[4]), + Number(matched[5]), + Number(matched[6]), + ).toISOString(); +} + +/** + * Restores a file from its backup. + * @param {{ backupRoot:string, operationId:string }} input + */ +export async function rollback(input) { + const { backupRoot, operationId } = input; + const records = await listBackups(backupRoot); + const record = records.find((item) => item.id === operationId); + if (!record) throw new Error('backup_operation_not_found'); + + const { readFile } = await import('node:fs/promises'); + const backupPath = path.join(record.backupDirectory, record.backupFile); + const originalBuffer = await readFile(backupPath); + const digest = sha256(originalBuffer); + if (record.originalSha256 && digest !== record.originalSha256) { + throw new Error('backup_file_integrity_mismatch'); + } + + const target = await assertWritable(record.targetPath); + await writeFileAtomic(target.path, originalBuffer); + + const restored = sha256(await readFile(target.path)); + const ok = record.originalSha256 ? restored === record.originalSha256 : true; + record.status = ok ? 'rolled_back' : 'rollback_failed'; + record.rolledBackAt = new Date().toISOString(); + record.rollbackResult = { ok, sha256: restored, restoredBytes: originalBuffer.length }; + await writeJsonAtomic(path.join(record.backupDirectory, 'record.json'), record); + + return { + ok, + targetPath: record.targetPath, + backupDirectory: record.backupDirectory, + backupFile: record.backupFile, + restoredSha256: restored, + expectedSha256: record.originalSha256 || restored, + rolledBackAt: record.rolledBackAt, + }; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/deploy.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/deploy.mjs new file mode 100644 index 00000000..7704e921 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/deploy.mjs @@ -0,0 +1,87 @@ +// Deployment command runner. Commands come from the saved configuration, never from a +// free-text field on a single request. + +import { spawn } from 'node:child_process'; + +const OUTPUT_LIMIT = 200000; +const activeChildren = new Set(); + +function killTree(child) { + if (!child.pid) return; + if (process.platform === 'win32') { + try { + spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true }); + return; + } catch { + /* fall through to the plain kill */ + } + } + try { + child.kill('SIGKILL'); + } catch { + /* the process already exited */ + } +} + +/** + * @param {{ command:string, cwd:string, timeoutMs?:number, signal?:AbortSignal }} input + */ +export function runDeploy(input) { + const { command, cwd, timeoutMs = 120000, signal } = input; + return new Promise((resolve) => { + const startedAt = Date.now(); + let stdout = ''; + let stderr = ''; + let timedOut = false; + let cancelled = false; + let settled = false; + + const child = spawn(command, { + cwd, + shell: true, + windowsHide: true, + env: process.env, + }); + activeChildren.add(child); + + const finish = (result) => { + if (settled) return; + settled = true; + clearTimeout(timer); + signal?.removeEventListener('abort', onAbort); + activeChildren.delete(child); + resolve({ ...result, stdout, stderr, durationMs: Date.now() - startedAt }); + }; + + const timer = setTimeout(() => { + timedOut = true; + killTree(child); + }, timeoutMs); + + const onAbort = () => { + cancelled = true; + killTree(child); + }; + signal?.addEventListener('abort', onAbort, { once: true }); + + child.stdout?.on('data', (data) => { + if (stdout.length < OUTPUT_LIMIT) stdout += data.toString(); + }); + child.stderr?.on('data', (data) => { + if (stderr.length < OUTPUT_LIMIT) stderr += data.toString(); + }); + child.on('error', (error) => { + finish({ ok: false, code: null, timedOut, cancelled, error: error.message }); + }); + child.on('close', (code) => { + finish({ ok: code === 0 && !timedOut && !cancelled, code, timedOut, cancelled, error: null }); + }); + }); +} + +export function stopActiveDeploys() { + for (const child of [...activeChildren]) { + killTree(child); + } + activeChildren.clear(); +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/http.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/http.mjs new file mode 100644 index 00000000..4e8fd5bf --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/http.mjs @@ -0,0 +1,84 @@ +// Minimal JSON-over-HTTP helper built on Node built-ins only. +// The Mini App runtime must not depend on a third-party HTTP client. + +import { request as httpRequest } from 'node:http'; +import { request as httpsRequest } from 'node:https'; + +const MAX_RESPONSE_BYTES = 32 * 1024 * 1024; + +/** + * @param {string} url + * @param {{ method?: string, body?: unknown, headers?: Record, timeoutMs?: number, signal?: AbortSignal }} options + */ +export function requestJson(url, options = {}) { + const { method = 'GET', body, headers = {}, timeoutMs = 120000, signal } = options; + return new Promise((resolve, reject) => { + let target; + try { + target = new URL(url); + } catch (error) { + reject(new Error(`invalid_url:${url}`)); + return; + } + const send = target.protocol === 'https:' ? httpsRequest : httpRequest; + const payload = + body === undefined + ? undefined + : Buffer.from(typeof body === 'string' ? body : JSON.stringify(body), 'utf8'); + + const request = send( + { + protocol: target.protocol, + hostname: target.hostname, + port: target.port || (target.protocol === 'https:' ? 443 : 80), + path: `${target.pathname}${target.search}`, + method, + headers: { + accept: 'application/json', + ...(payload + ? { 'content-type': 'application/json', 'content-length': String(payload.length) } + : {}), + ...headers, + }, + signal, + }, + (response) => { + const chunks = []; + let size = 0; + response.on('data', (chunk) => { + size += chunk.length; + if (size > MAX_RESPONSE_BYTES) { + request.destroy(new Error('response_too_large')); + return; + } + chunks.push(chunk); + }); + response.on('end', () => { + const raw = Buffer.concat(chunks).toString('utf8'); + const contentType = String(response.headers['content-type'] || ''); + let parsed = null; + if (contentType.includes('application/json')) { + try { + parsed = JSON.parse(raw); + } catch { + parsed = null; + } + } + if ((response.statusCode || 500) >= 400) { + const error = new Error(`http_status_${response.statusCode}`); + error.statusCode = response.statusCode; + error.body = raw.slice(0, 2000); + reject(error); + return; + } + resolve({ statusCode: response.statusCode || 200, body: parsed, raw, headers: response.headers }); + }); + }, + ); + + request.setTimeout(timeoutMs, () => request.destroy(new Error('request_timeout'))); + request.on('error', reject); + if (payload) request.write(payload); + request.end(); + }); +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/kb.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/kb.mjs new file mode 100644 index 00000000..79efe341 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/kb.mjs @@ -0,0 +1,268 @@ +// Knowledge base: documents, chunks and bge-m3 vectors, persisted under the plugin dataDir. + +import { randomUUID } from 'node:crypto'; +import path from 'node:path'; +import { EMBEDDING_MODEL, embed } from './ollama.mjs'; +import { ensureDir, readJson, removeIfExists, writeFileAtomic, writeJsonAtomic } from './store.mjs'; + +export const CATEGORIES = ['知识点', '规则', '合同', '其他']; + +const CHUNK_TARGET_CHARS = 700; +const CHUNK_OVERLAP_CHARS = 120; + +let registryCache = null; + +/** + * Splits a document into overlapping chunks that keep paragraph boundaries. + * @param {string} text + */ +export function chunkText(text, options = {}) { + const target = options.target || CHUNK_TARGET_CHARS; + const overlap = options.overlap || CHUNK_OVERLAP_CHARS; + const clean = String(text || '').replace(/\r\n/g, '\n').trim(); + if (!clean) return []; + + const units = []; + for (const paragraph of clean.split(/\n{2,}/)) { + const trimmed = paragraph.trim(); + if (!trimmed) continue; + if (trimmed.length <= target) { + units.push(trimmed); + continue; + } + let buffer = ''; + for (const sentence of trimmed.split(/(?<=[。!?;!?;])/)) { + if (!sentence) continue; + if (buffer.length + sentence.length > target && buffer) { + units.push(buffer.trim()); + buffer = ''; + } + buffer += sentence; + } + if (buffer.trim()) units.push(buffer.trim()); + } + + const chunks = []; + let current = ''; + let offset = 0; + for (const unit of units) { + if (current && current.length + unit.length + 2 > target) { + chunks.push({ text: current.trim(), start: offset, end: offset + current.length }); + const tail = current.slice(-overlap); + offset += Math.max(0, current.length - overlap); + current = `${tail}\n${unit}`; + } else { + current = current ? `${current}\n${unit}` : unit; + } + } + if (current.trim()) chunks.push({ text: current.trim(), start: offset, end: offset + current.length }); + return chunks; +} + +function documentDirectory(kbDir, documentId) { + return path.join(kbDir, documentId); +} + +/** + * Persists a parsed document together with its vectors. + * @param {{ kbDir:string, ollamaBase:string, name:string, category:string, kind:string, sourcePath:string|null, sizeBytes:number, text:string, analysis:object }} input + */ +export async function saveDocument(input) { + const { + kbDir, ollamaBase, name, category, kind, sourcePath, sizeBytes, text, analysis, + } = input; + const documentId = randomUUID(); + const chunks = chunkText(text); + if (!chunks.length) throw new Error('document_has_no_indexable_text'); + + const vectors = await embed({ + base: ollamaBase, + model: EMBEDDING_MODEL, + inputs: chunks.map((chunk) => chunk.text), + }); + + const directory = documentDirectory(kbDir, documentId); + await ensureDir(directory); + await writeJsonAtomic(path.join(directory, 'chunks.json'), chunks); + + const dimension = vectors[0].length; + const flat = new Float32Array(vectors.length * dimension); + vectors.forEach((vector, index) => flat.set(vector, index * dimension)); + await writeFileAtomic(path.join(directory, 'vectors.bin'), Buffer.from(flat.buffer)); + + const document = { + id: documentId, + name, + category, + kind, + sourcePath: sourcePath || null, + sizeBytes, + chunkCount: chunks.length, + characterCount: text.length, + createdAt: new Date().toISOString(), + embeddingModel: EMBEDDING_MODEL, + title: analysis?.title || name, + summary: analysis?.summary || '', + keyPoints: analysis?.keyPoints || [], + modelRoute: analysis?.route || null, + }; + + const index = await readIndex(kbDir); + index.documents = index.documents.filter((item) => item.id !== documentId); + index.documents.push(document); + await writeJsonAtomic(path.join(kbDir, 'index.json'), index); + registryCache = null; + return document; +} + +async function readIndex(kbDir) { + const index = await readJson(path.join(kbDir, 'index.json'), null); + if (index && Array.isArray(index.documents)) return index; + return { documents: [] }; +} + +export async function listDocuments(kbDir) { + const index = await readIndex(kbDir); + return index.documents.slice().sort((left, right) => String(right.createdAt).localeCompare(String(left.createdAt))); +} + +export async function deleteDocument(kbDir, documentId) { + const index = await readIndex(kbDir); + const before = index.documents.length; + index.documents = index.documents.filter((item) => item.id !== documentId); + if (index.documents.length === before) return false; + await writeJsonAtomic(path.join(kbDir, 'index.json'), index); + await removeIfExists(documentDirectory(kbDir, documentId)); + registryCache = null; + return true; +} + +/** + * Loads every chunk and vector into memory for retrieval. + */ +async function loadRegistry(kbDir) { + const index = await readIndex(kbDir); + const signature = index.documents + .map((document) => `${document.id}:${document.chunkCount}`) + .join('|'); + if (registryCache && registryCache.kbDir === kbDir && registryCache.signature === signature) { + return registryCache; + } + + const documents = new Map(index.documents.map((document) => [document.id, document])); + const chunks = []; + const vectors = []; + for (const document of index.documents) { + const directory = documentDirectory(kbDir, document.id); + const stored = await readJson(path.join(directory, 'chunks.json'), null); + if (!Array.isArray(stored) || !stored.length) continue; + let buffer = null; + try { + buffer = await import('node:fs/promises').then((fs) => fs.readFile(path.join(directory, 'vectors.bin'))); + } catch { + buffer = null; + } + if (!buffer) continue; + const dimension = buffer.byteLength / stored.length / 4; + if (!Number.isFinite(dimension) || dimension <= 0) continue; + const floats = new Float32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 4); + stored.forEach((chunk, indexInDocument) => { + const vector = floats.slice(indexInDocument * dimension, (indexInDocument + 1) * dimension); + chunks.push({ + documentId: document.id, + chunkIndex: indexInDocument, + text: chunk.text, + start: chunk.start, + end: chunk.end, + }); + vectors.push(vector); + }); + } + + registryCache = { kbDir, signature, documents, chunks, vectors }; + return registryCache; +} + +export function cosineSimilarity(left, right) { + let dot = 0; + let leftNorm = 0; + let rightNorm = 0; + const length = Math.min(left.length, right.length); + for (let index = 0; index < length; index += 1) { + dot += left[index] * right[index]; + leftNorm += left[index] * left[index]; + rightNorm += right[index] * right[index]; + } + if (!leftNorm || !rightNorm) return 0; + return dot / (Math.sqrt(leftNorm) * Math.sqrt(rightNorm)); +} + +/** Splits a query into terms: latin words plus CJK bigrams. */ +export function queryTerms(query) { + const text = String(query || '').toLowerCase(); + const terms = []; + for (const matched of text.match(/[a-z0-9_]{2,}/g) || []) terms.push(matched); + const cjk = text.replace(/[^一-龥]/g, ' '); + for (const run of cjk.split(/\s+/)) { + if (!run) continue; + if (run.length === 1) { + terms.push(run); + continue; + } + for (let index = 0; index < run.length - 1; index += 1) terms.push(run.slice(index, index + 2)); + } + return [...new Set(terms)]; +} + +function keywordScore(text, terms) { + if (!terms.length) return 0; + const haystack = String(text).toLowerCase(); + let hits = 0; + for (const term of terms) { + if (haystack.includes(term)) hits += 1; + } + return hits / terms.length; +} + +/** + * Retrieves the most relevant chunks for a question. + * @param {{ kbDir:string, ollamaBase:string, question:string, topK?:number, signal?:AbortSignal }} input + */ +export async function retrieve(input) { + const { kbDir, ollamaBase, question, topK = 6, signal } = input; + const registry = await loadRegistry(kbDir); + if (!registry.chunks.length) return { matches: [], total: 0 }; + + const [queryVector] = await embed({ base: ollamaBase, model: EMBEDDING_MODEL, inputs: [question], signal }); + const terms = queryTerms(question); + + const scored = registry.chunks.map((chunk, index) => { + const similarity = cosineSimilarity(queryVector, registry.vectors[index]); + const keyword = keywordScore(chunk.text, terms); + return { chunk, score: similarity * 0.78 + keyword * 0.22, similarity, keyword }; + }); + + scored.sort((left, right) => right.score - left.score); + const limit = Math.max(1, Math.min(Number(topK) || 6, 20)); + const matches = scored.slice(0, limit).map((entry) => { + const document = registry.documents.get(entry.chunk.documentId); + return { + documentId: entry.chunk.documentId, + documentName: document ? document.name : '(已删除资料)', + category: document ? document.category : '其他', + documentKind: document ? document.kind : 'text', + chunkIndex: entry.chunk.chunkIndex, + text: entry.chunk.text, + preview: entry.chunk.text.slice(0, 220), + score: Number(entry.score.toFixed(4)), + similarity: Number(entry.similarity.toFixed(4)), + keywordHit: Number(entry.keyword.toFixed(4)), + }; + }); + + return { matches, total: registry.chunks.length }; +} + +export function invalidateRegistry() { + registryCache = null; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/llm.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/llm.mjs new file mode 100644 index 00000000..42b5136b --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/llm.mjs @@ -0,0 +1,197 @@ +// One entry point for model work: build the prompt, pick the route, run it, and report +// exactly which route answered and whether a degradation happened. + +import { chat as ollamaChat, listModels } from './ollama.mjs'; +import { buildRoutePlan, pickLocalModel } from './router.mjs'; + +export class LlmError extends Error { + constructor(code, message, details) { + super(message || code); + this.code = code; + this.details = details || null; + } +} + +/** + * Runs one model task. + * @param {{ ollamaBase:string, agent?:object, logger?:object }} context + * @param {{ task:string, mode:string, system:string, prompt:string, signal?:AbortSignal, temperature?:number, requireLarge?:boolean }} options + */ +export async function complete(context, options) { + const { task, mode, system, prompt, signal, temperature = 0.2, requireLarge = false } = options; + const attempts = []; + + let localModel = null; + let localProbeError = null; + try { + const models = await listModels(context.ollamaBase, signal); + localModel = pickLocalModel(models, { requireLarge }); + } catch (error) { + localProbeError = error instanceof Error ? error.message : String(error); + } + + const promptChars = String(system || '').length + String(prompt || '').length; + const plan = buildRoutePlan({ mode, localModel, promptChars }); + + for (const route of plan.order) { + try { + if (route === 'local') { + if (!localModel) { + throw new LlmError( + 'local_model_unavailable', + localProbeError + ? `本地模型不可用:${localProbeError}` + : '本机没有可用的本地对话模型', + ); + } + const result = await ollamaChat({ + base: context.ollamaBase, + model: localModel.name, + numCtx: localModel.numCtx, + temperature, + signal, + messages: [ + { role: 'system', content: String(system || '') }, + { role: 'user', content: String(prompt || '') }, + ], + }); + attempts.push({ route: 'local', ok: true, model: localModel.name }); + return { + text: result.text, + route: { + requested: mode, + used: 'local', + model: localModel.name, + numCtx: localModel.numCtx, + degraded: false, + degradedFrom: null, + fallbackReason: null, + plan: plan.order, + reason: plan.reason, + attempts, + }, + }; + } + + const online = await runOnline(context.agent, system, prompt, signal); + attempts.push({ route: 'online', ok: true, model: online.model || 'online' }); + return { + text: online.text, + route: { + requested: mode, + used: 'online', + model: online.model || 'online', + numCtx: null, + degraded: plan.order[0] !== 'online', + degradedFrom: plan.order[0] !== 'online' ? plan.order[0] : null, + fallbackReason: plan.order[0] !== 'online' ? plan.reason : null, + plan: plan.order, + reason: plan.reason, + attempts, + }, + }; + } catch (error) { + const code = error && error.code ? error.code : 'model_call_failed'; + const message = error instanceof Error ? error.message : String(error); + attempts.push({ route, ok: false, error: `${code}: ${message}` }); + if (!plan.degrade) break; + context.logger?.warn('miniapp.model.route_failed', { route, code }); + } + } + + const failure = attempts.find((attempt) => !attempt.ok); + throw new LlmError( + 'model_unavailable', + `模型调用失败:${failure ? failure.error : '无可用路由'}`, + { attempts, plan }, + ); +} + +/** + * The online route is the Host Agent turn. It is scoped to a single JSON reply and + * is not allowed to touch files, tools or the network. + */ +async function runOnline(agent, system, prompt, signal) { + if (!agent || typeof agent.run !== 'function') { + throw new LlmError('online_agent_unavailable', '在线模型通道不可用'); + } + const text = [ + '你是「道闸运维知识助手」的后端推理引擎。', + '只依据下面提供的内容作答:不要调用任何工具、不要读写文件、不要联网、不要访问其他会话。', + '严格只输出一个 JSON 对象,不要输出前言、解释文字或 Markdown 代码块。', + '', + '【系统要求】', + String(system || ''), + '', + '【任务内容】', + String(prompt || ''), + ].join('\n'); + + const result = await agent.run({ text }, { signal }); + if (result.status === 'error') { + throw new LlmError( + 'online_agent_error', + `在线模型返回错误:${(result.error && result.error.code) || 'unknown'}`, + ); + } + if (result.status === 'aborted') { + throw new LlmError('online_agent_aborted', '在线模型调用被中止'); + } + const raw = String(result.text || '').trim(); + if (!raw) throw new LlmError('online_empty_response', '在线模型没有返回内容'); + return { + text: raw, + model: result.model ? `${result.model.providerId}/${result.model.modelId}` : 'online', + }; +} + +/** + * Extracts the first balanced JSON object from a model reply. + * @param {string} text + */ +export function parseJsonObject(text) { + const source = String(text || ''); + const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(source); + const candidates = []; + if (fenced) candidates.push(fenced[1]); + candidates.push(source); + for (const candidate of candidates) { + const trimmed = candidate.trim(); + if (!trimmed) continue; + try { + const parsed = JSON.parse(trimmed); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed; + } catch { + /* try the next candidate */ + } + const start = trimmed.indexOf('{'); + if (start < 0) continue; + let depth = 0; + let inString = false; + let escaped = false; + for (let index = start; index < trimmed.length; index += 1) { + const char = trimmed[index]; + if (inString) { + if (escaped) escaped = false; + else if (char === '\\') escaped = true; + else if (char === '"') inString = false; + continue; + } + if (char === '"') inString = true; + else if (char === '{') depth += 1; + else if (char === '}') { + depth -= 1; + if (depth === 0) { + try { + const parsed = JSON.parse(trimmed.slice(start, index + 1)); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed; + } catch { + break; + } + break; + } + } + } + } + return null; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/ollama.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/ollama.mjs new file mode 100644 index 00000000..e00b2905 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/ollama.mjs @@ -0,0 +1,92 @@ +// Local Ollama client. The embedding model is fixed by the product rules. + +import { requestJson } from './http.mjs'; + +export const DEFAULT_OLLAMA_BASE = 'http://127.0.0.1:11434'; +export const EMBEDDING_MODEL = 'bge-m3'; +export const PREFERRED_CHAT_MODEL = 'qwen3:14b'; +/** Fixed context policy: 14B models run with an 8K window, smaller models with 16K. */ +export const LARGE_MODEL_CTX = 8192; +export const SMALL_MODEL_CTX = 16384; +export const LARGE_MODEL_PARAM_B = 13; + +export function normalizeBase(base) { + const value = String(base || DEFAULT_OLLAMA_BASE).trim(); + return value.replace(/\/+$/, '') || DEFAULT_OLLAMA_BASE; +} + +/** + * @param {string} base + * @param {AbortSignal} [signal] + * @returns {Promise>} + */ +export async function listModels(base, signal) { + const response = await requestJson(`${normalizeBase(base)}/api/tags`, { signal, timeoutMs: 8000 }); + const models = response.body && response.body.models; + if (!Array.isArray(models)) throw new Error('ollama_tags_invalid'); + return models; +} + +/** + * @param {string} base + * @param {AbortSignal} [signal] + */ +export async function ollamaVersion(base, signal) { + const response = await requestJson(`${normalizeBase(base)}/api/version`, { signal, timeoutMs: 5000 }); + return response.body && response.body.version ? String(response.body.version) : 'unknown'; +} + +/** + * @param {{ base:string, model:string, messages:Array<{role:string,content:string}>, numCtx:number, temperature?:number, timeoutMs?:number, signal?:AbortSignal }} options + */ +export async function chat(options) { + const { base, model, messages, numCtx, temperature = 0.2, timeoutMs = 240000, signal } = options; + const response = await requestJson(`${normalizeBase(base)}/api/chat`, { + method: 'POST', + body: { + model, + messages, + stream: false, + think: false, + options: { num_ctx: numCtx, temperature }, + }, + timeoutMs, + signal, + }); + const payload = response.body || {}; + const message = payload.message || {}; + const text = stripThinking(String(message.content ?? payload.response ?? '')); + if (!text) throw new Error('ollama_empty_response'); + return { text, model, numCtx, raw: payload }; +} + +/** + * @param {{ base:string, model?:string, inputs:string[], timeoutMs?:number, signal?:AbortSignal }} options + * @returns {Promise} + */ +export async function embed(options) { + const { base, model = EMBEDDING_MODEL, inputs, timeoutMs = 180000, signal } = options; + if (!Array.isArray(inputs) || inputs.length === 0) throw new Error('embed_input_required'); + const response = await requestJson(`${normalizeBase(base)}/api/embed`, { + method: 'POST', + body: { model, input: inputs }, + timeoutMs, + signal, + }); + const vectors = response.body && response.body.embeddings; + if (!Array.isArray(vectors) || vectors.length !== inputs.length) { + throw new Error('ollama_embed_response_invalid'); + } + for (const vector of vectors) { + if (!Array.isArray(vector) || vector.length === 0) throw new Error('ollama_embed_vector_invalid'); + } + return vectors; +} + +/** Removes reasoning blocks some chat templates still inline into the answer. */ +export function stripThinking(text) { + return String(text) + .replace(/[\s\S]*?<\/think>/gi, '') + .replace(/^[\s\S]*$/i, '') + .trim(); +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/docx.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/docx.mjs new file mode 100644 index 00000000..e926475e --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/docx.mjs @@ -0,0 +1,55 @@ +// .docx text extraction: reads word/document.xml out of the OOXML container. + +import { readZip } from './zip.mjs'; + +/** + * @param {Buffer} buffer + * @returns {{ text: string, paragraphs: string[], tables: number }} + */ +export function parseDocx(buffer) { + const zip = readZip(buffer); + if (!zip.has('word/document.xml')) { + throw new Error('docx_document_part_missing'); + } + let xml = zip.read('word/document.xml').toString('utf8'); + // Drop tracked deletions so removed text never becomes knowledge. + xml = xml.replace(//g, ''); + + const paragraphs = []; + const paragraphPattern = /]*>([\s\S]*?)<\/w:p>/g; + let matched = paragraphPattern.exec(xml); + while (matched) { + const text = extractParagraphText(matched[1]); + if (text.trim()) paragraphs.push(text.trim()); + matched = paragraphPattern.exec(xml); + } + + const tables = (xml.match(/]*\/>|]*\/>|]*>([\s\S]*?)<\/w:t>/g; + let matched = pattern.exec(fragment); + while (matched) { + if (matched[0].startsWith('') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code))) + .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCodePoint(Number.parseInt(code, 16))) + .replace(/&/g, '&'); +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/index.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/index.mjs new file mode 100644 index 00000000..d3be9869 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/index.mjs @@ -0,0 +1,72 @@ +// Dispatches a document to the right text extractor. + +import { parseDocx } from './docx.mjs'; +import { parseXlsx } from './xlsx.mjs'; +import { parsePdf } from './pdf.mjs'; + +export const SUPPORTED_EXTENSIONS = ['.txt', '.md', '.markdown', '.docx', '.xlsx', '.pdf']; + +export function extensionOf(name) { + const base = String(name || '').split(/[\\/]/).pop() || ''; + const index = base.lastIndexOf('.'); + return index < 0 ? '' : base.slice(index).toLowerCase(); +} + +export function isSupportedFile(name) { + return SUPPORTED_EXTENSIONS.includes(extensionOf(name)); +} + +/** + * @param {string} name + * @param {Buffer} buffer + * @returns {{ text:string, kind:string, meta:object }} + */ +export function parseDocument(name, buffer) { + const extension = extensionOf(name); + if (extension === '.txt' || extension === '.md' || extension === '.markdown') { + const text = decodeText(buffer); + if (!text.trim()) throw new Error('file_has_no_text'); + return { text, kind: 'text', meta: { characters: text.length } }; + } + if (extension === '.docx') { + const result = parseDocx(buffer); + return { + text: result.text, + kind: 'docx', + meta: { paragraphs: result.paragraphs.length, tables: result.tables }, + }; + } + if (extension === '.xlsx') { + const result = parseXlsx(buffer); + return { text: result.text, kind: 'xlsx', meta: { sheets: result.sheets } }; + } + if (extension === '.pdf') { + const result = parsePdf(buffer); + return { text: result.text, kind: 'pdf', meta: { pages: result.pages, title: result.title } }; + } + throw new Error(`unsupported_file_type:${extension || 'unknown'}`); +} + +/** Decodes text with a BOM aware UTF-8 / UTF-16 / GBK fallback chain. */ +export function decodeText(buffer) { + if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) { + return buffer.subarray(3).toString('utf8'); + } + if (buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xfe) { + return new TextDecoder('utf-16le').decode(buffer.subarray(2)); + } + if (buffer.length >= 2 && buffer[0] === 0xfe && buffer[1] === 0xff) { + const swapped = Buffer.from(buffer.subarray(2)); + if (swapped.length >= 2) swapped.swap16(); + return swapped.toString('utf16le'); + } + const utf8 = new TextDecoder('utf-8').decode(buffer); + if (!utf8.includes('\ufffd')) return utf8; + try { + const gbk = new TextDecoder('gbk').decode(buffer); + if (!gbk.includes('\ufffd')) return gbk; + } catch { + /* TextDecoder without GBK support */ + } + return utf8; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/pdf.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/pdf.mjs new file mode 100644 index 00000000..85dec77a --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/pdf.mjs @@ -0,0 +1,539 @@ +// PDF text extraction without third-party dependencies. +// Handles object streams, FlateDecode, per-font ToUnicode CMaps and the usual text operators. + +import { inflateSync, inflateRawSync } from 'node:zlib'; + +const MAX_PAGES = 500; + +/** + * @param {Buffer} buffer + * @returns {{ text: string, pages: number, title: string }} + */ +export function parsePdf(buffer) { + // latin1 keeps a 1:1 byte<->char mapping, so string offsets equal byte offsets. + const text = buffer.toString('latin1'); + if (!text.includes('%PDF-')) throw new Error('pdf_header_missing'); + if (/\/Encrypt\b/.test(text)) throw new Error('pdf_encrypted_not_supported'); + + const objects = collectObjects(text); + expandObjectStreams(objects); + const pages = collectPages(objects); + if (!pages.length) throw new Error('pdf_no_page_found'); + + const blocks = []; + let extracted = 0; + for (const page of pages.slice(0, MAX_PAGES)) { + const content = pageContent(objects, page); + if (!content || !content.length) continue; + const fonts = pageFonts(objects, page); + const pageText = extractText(content, fonts); + if (pageText.trim()) { + extracted += 1; + blocks.push(pageText); + } + } + + if (!extracted) { + throw new Error('pdf_no_text_layer_found'); + } + const joined = blocks.join('\n\n'); + return { text: joined, pages: pages.length, title: documentTitle(objects) }; +} + +/* ------------------------------------------------------------------ objects */ + +function collectObjects(text) { + const objects = new Map(); + const pattern = /(\d+)\s+(\d+)\s+obj\b/g; + let matched = pattern.exec(text); + while (matched) { + const number = Number(matched[1]); + const bodyStart = matched.index + matched[0].length; + const head = text.slice(bodyStart, bodyStart + 4000); + const streamMatch = /\bstream\r?\n/.exec(head); + let dict; + let stream = null; + if (streamMatch) { + const dictEnd = bodyStart + streamMatch.index; + dict = text.slice(bodyStart, dictEnd); + const dataStart = dictEnd + streamMatch[0].length; + const endStream = text.indexOf('endstream', dataStart); + let dataEnd = endStream < 0 ? text.length : endStream; + if (text[dataEnd - 1] === '\n') dataEnd -= 1; + if (text[dataEnd - 1] === '\r') dataEnd -= 1; + stream = decodeStream(dict, Buffer.from(text.slice(dataStart, dataEnd), 'latin1')); + } else { + const endObj = text.indexOf('endobj', bodyStart); + dict = text.slice(bodyStart, endObj < 0 ? text.length : endObj); + } + if (!objects.has(number)) objects.set(number, { number, dict, stream }); + matched = pattern.exec(text); + } + return objects; +} + +function decodeStream(dict, raw) { + if (!raw.length) return null; + const filter = /\/Filter\s*(?:\/\w+|\[[^\]]*\])/.exec(dict); + const filterText = filter ? filter[0] : ''; + if (!filterText) return raw; + if (!/FlateDecode/.test(filterText)) return null; + let inflated = null; + try { + inflated = inflateSync(raw); + } catch { + try { + inflated = inflateRawSync(raw); + } catch { + return null; + } + } + return applyPredictor(dict, inflated); +} + +function applyPredictor(dict, data) { + const predictor = Number((/\/Predictor\s+(\d+)/.exec(dict) || [])[1] || 1); + if (!predictor || predictor < 2) return data; + const columns = Number((/\/Columns\s+(\d+)/.exec(dict) || [])[1] || 1); + const colors = Number((/\/Colors\s+(\d+)/.exec(dict) || [])[1] || 1); + const bpc = Number((/\/BitsPerComponent\s+(\d+)/.exec(dict) || [])[1] || 8); + const bpp = Math.max(1, (colors * bpc) / 8); + const rowLength = Math.ceil((columns * colors * bpc) / 8); + if (predictor === 2) { + if (bpc !== 8) return data; + const rows = Math.floor(data.length / rowLength); + for (let row = 0; row < rows; row += 1) { + const base = row * rowLength; + for (let index = bpp; index < rowLength; index += 1) { + data[base + index] = (data[base + index] + data[base + index - bpp]) & 0xff; + } + } + return data; + } + // PNG predictors: each row is prefixed with a filter type byte. + const stride = rowLength + 1; + const rows = Math.floor(data.length / stride); + const out = Buffer.alloc(rows * rowLength); + let previous = Buffer.alloc(rowLength); + for (let row = 0; row < rows; row += 1) { + const filterType = data[row * stride]; + const source = data.subarray(row * stride + 1, row * stride + 1 + rowLength); + const target = out.subarray(row * rowLength, (row + 1) * rowLength); + source.copy(target); + for (let index = 0; index < rowLength; index += 1) { + const left = index >= bpp ? target[index - bpp] : 0; + const up = previous[index]; + const upLeft = index >= bpp ? previous[index - bpp] : 0; + if (filterType === 1) target[index] = (target[index] + left) & 0xff; + else if (filterType === 2) target[index] = (target[index] + up) & 0xff; + else if (filterType === 3) target[index] = (target[index] + ((left + up) >> 1)) & 0xff; + else if (filterType === 4) { + const p = left + up - upLeft; + const pa = Math.abs(p - left); + const pb = Math.abs(p - up); + const pc = Math.abs(p - upLeft); + const value = pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft; + target[index] = (target[index] + value) & 0xff; + } + } + target.copy(previous); + } + return out; +} + +function expandObjectStreams(objects) { + for (const object of [...objects.values()]) { + if (!/\/Type\s*\/ObjStm/.test(object.dict) || !object.stream) continue; + const count = Number((/\/N\s+(\d+)/.exec(object.dict) || [])[1] || 0); + const first = Number((/\/First\s+(\d+)/.exec(object.dict) || [])[1] || 0); + if (!count || !first) continue; + const content = object.stream.toString('latin1'); + const header = content.slice(0, first).trim().split(/\s+/).map(Number); + for (let index = 0; index < count; index += 1) { + const number = header[index * 2]; + const relativeOffset = header[index * 2 + 1]; + if (!Number.isFinite(number) || !Number.isFinite(relativeOffset)) continue; + const nextOffset = index + 1 < count ? header[(index + 1) * 2 + 1] : content.length - first; + const body = content.slice(first + relativeOffset, first + nextOffset); + if (!objects.has(number)) objects.set(number, { number, dict: body, stream: null }); + } + } +} + +/* -------------------------------------------------------------------- pages */ + +function collectPages(objects) { + const pages = []; + let rootNumber = null; + for (const object of objects.values()) { + if (/\/Type\s*\/Catalog/.test(object.dict)) { + const reference = /\/Pages\s+(\d+)\s+\d+\s+R/.exec(object.dict); + if (reference) rootNumber = Number(reference[1]); + } + } + if (rootNumber !== null) { + walkPageTree(objects, rootNumber, null, pages, 0); + } + if (!pages.length) { + for (const object of objects.values()) { + if (/\/Type\s*\/Page\b/.test(object.dict)) pages.push({ number: object.number, dict: object.dict, inherited: null }); + } + } + return pages; +} + +function walkPageTree(objects, number, inherited, out, depth) { + if (depth > 64 || out.length >= MAX_PAGES) return; + const object = objects.get(number); + if (!object) return; + const dict = object.dict; + if (/\/Type\s*\/Page\b/.test(dict)) { + out.push({ number, dict, inherited }); + return; + } + let resources = inherited; + const resourceReference = /\/Resources\s+(\d+)\s+\d+\s+R/.exec(dict); + if (resourceReference) { + const resourceObject = objects.get(Number(resourceReference[1])); + if (resourceObject) resources = resourceObject.dict; + } + const kids = /\/Kids\s*\[([^\]]*)\]/.exec(dict); + if (!kids) return; + const references = [...kids[1].matchAll(/(\d+)\s+\d+\s+R/g)].map((match) => Number(match[1])); + for (const reference of references) walkPageTree(objects, reference, resources, out, depth + 1); +} + +function pageContent(objects, page) { + const arrayMatch = /\/Contents\s*\[([^\]]*)\]/.exec(page.dict); + if (arrayMatch) { + const references = [...arrayMatch[1].matchAll(/(\d+)\s+\d+\s+R/g)].map((match) => Number(match[1])); + const parts = references.map((reference) => objects.get(reference)?.stream).filter(Boolean); + return parts.length ? Buffer.concat(parts) : null; + } + const reference = /\/Contents\s+(\d+)\s+\d+\s+R/.exec(page.dict); + if (reference) return objects.get(Number(reference[1]))?.stream || null; + return null; +} + +function pageFonts(objects, page) { + const fonts = new Map(); + let resources = page.inherited; + if (!resources) resources = extractInlineDict(page.dict, '/Resources'); + if (!resources) return fonts; + let fontDictionary = null; + const fontReference = /\/Font\s+(\d+)\s+\d+\s+R/.exec(resources); + if (fontReference) fontDictionary = objects.get(Number(fontReference[1]))?.dict || null; + else fontDictionary = extractInlineDict(resources, '/Font'); + if (!fontDictionary) return fonts; + + const pattern = /\/([A-Za-z0-9_.#+-]+)\s+(\d+)\s+\d+\s+R/g; + let matched = pattern.exec(fontDictionary); + while (matched) { + const name = `/${matched[1]}`; + const fontObject = objects.get(Number(matched[2])); + const toUnicodeReference = /\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(fontObject?.dict || ''); + let cmap = null; + if (toUnicodeReference) { + const cmapObject = objects.get(Number(toUnicodeReference[1])); + if (cmapObject?.stream) cmap = parseCMap(cmapObject.stream.toString('latin1')); + } + fonts.set(name, cmap); + matched = pattern.exec(fontDictionary); + } + return fonts; +} + +function extractInlineDict(dictionary, key) { + const index = dictionary.indexOf(key); + if (index < 0) return null; + const start = dictionary.indexOf('<<', index); + if (start < 0) return null; + let depth = 0; + let cursor = start; + while (cursor < dictionary.length - 1) { + if (dictionary[cursor] === '<' && dictionary[cursor + 1] === '<') { + depth += 1; + cursor += 2; + continue; + } + if (dictionary[cursor] === '>' && dictionary[cursor + 1] === '>') { + depth -= 1; + cursor += 2; + if (depth === 0) return dictionary.slice(start, cursor); + continue; + } + cursor += 1; + } + return null; +} + +/* --------------------------------------------------------------------- CMaps */ + +function parseCMap(source) { + const map = new Map(); + let codeBytes = 1; + + const charPattern = /beginbfchar([\s\S]*?)endbfchar/g; + let section = charPattern.exec(source); + while (section) { + const pairs = [...section[1].matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g)]; + for (const pair of pairs) { + codeBytes = Math.max(codeBytes, pair[1].length > 2 ? 2 : 1); + map.set(Number.parseInt(pair[1], 16), hexToUtf16(pair[2])); + } + section = charPattern.exec(source); + } + + const rangePattern = /beginbfrange([\s\S]*?)endbfrange/g; + section = rangePattern.exec(source); + while (section) { + const body = section[1]; + const pattern = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*(?:<([0-9A-Fa-f]+)>|\[([\s\S]*?)\])/g; + let matched = pattern.exec(body); + while (matched) { + const low = Number.parseInt(matched[1], 16); + const high = Number.parseInt(matched[2], 16); + codeBytes = Math.max(codeBytes, matched[1].length > 2 ? 2 : 1); + if (matched[3]) { + const baseValue = Number.parseInt(matched[3], 16); + const width = matched[3].length; + for (let code = low; code <= high && code - low < 65536; code += 1) { + const shifted = (baseValue + (code - low)).toString(16).padStart(width, '0'); + map.set(code, hexToUtf16(shifted)); + } + } else if (matched[4]) { + const items = [...matched[4].matchAll(/<([0-9A-Fa-f]+)>/g)].map((item) => item[1]); + items.forEach((item, index) => map.set(low + index, hexToUtf16(item))); + } + matched = pattern.exec(body); + } + section = rangePattern.exec(source); + } + + const spacePattern = /begincodespacerange([\s\S]*?)endcodespacerange/g; + section = spacePattern.exec(source); + while (section) { + const ranges = [...section[1].matchAll(/<([0-9A-Fa-f]+)>/g)]; + for (const range of ranges) { + codeBytes = Math.max(codeBytes, range[1].length > 2 ? 2 : 1); + } + section = spacePattern.exec(source); + } + + return { map, codeBytes }; +} + +function hexToUtf16(hex) { + const clean = String(hex).replace(/\s+/g, ''); + const padded = clean.length % 2 === 0 ? clean : `${clean}0`; + const bytes = Buffer.from(padded, 'hex'); + const swapped = Buffer.from(bytes); + if (swapped.length >= 2) swapped.swap16(); + return swapped.toString('utf16le'); +} + +/* ------------------------------------------------------------- text operators */ + +function extractText(content, fonts) { + const source = content.toString('latin1'); + let out = ''; + let cmap = null; + let cursor = 0; + const operands = []; + + const flushOperator = (operator) => { + switch (operator) { + case 'Tf': { + const name = operands.find((item) => item.type === 'name'); + if (name) cmap = fonts.get(`/${name.value}`) || null; + break; + } + case 'Tj': { + const text = operands.find((item) => item.type === 'string'); + if (text) out += decodeBytes(text.value, cmap); + break; + } + case 'TJ': { + const array = operands.find((item) => item.type === 'array'); + if (array) { + for (const item of array.items) { + if (item.type === 'string') out += decodeBytes(item.value, cmap); + else if (item.type === 'number' && item.value <= -120) out += ' '; + } + } + break; + } + case "'": { + const text = operands.find((item) => item.type === 'string'); + if (text) out += decodeBytes(text.value, cmap) + '\n'; + break; + } + case '"': { + const text = operands.find((item) => item.type === 'string'); + if (text) out += decodeBytes(text.value, cmap) + '\n'; + break; + } + case 'Td': + case 'TD': { + const numbers = operands.filter((item) => item.type === 'number'); + const ty = numbers.length >= 2 ? numbers[numbers.length - 1].value : 0; + const tx = numbers.length >= 2 ? numbers[numbers.length - 2].value : 0; + if (ty !== 0) out += '\n'; + else if (tx !== 0) out += ' '; + break; + } + case 'Tm': { + const numbers = operands.filter((item) => item.type === 'number'); + const fy = numbers.length >= 6 ? numbers[5].value : 0; + if (fy !== 0) out += '\n'; + break; + } + case 'T*': + out += '\n'; + break; + default: + break; + } + operands.length = 0; + }; + + while (cursor < source.length) { + const char = source[cursor]; + if (char === '(') { + const literal = readLiteralString(source, cursor); + operands.push({ type: 'string', value: literal.value }); + cursor = literal.next; + continue; + } + if (char === '<' && source[cursor + 1] !== '<') { + const end = source.indexOf('>', cursor); + if (end < 0) break; + const hex = source.slice(cursor + 1, end).replace(/\s+/g, ''); + const padded = hex.length % 2 === 0 ? hex : `${hex}0`; + operands.push({ type: 'string', value: Buffer.from(padded, 'hex') }); + cursor = end + 1; + continue; + } + if (char === '<') { + const end = source.indexOf('>>', cursor); + cursor = end < 0 ? source.length : end + 2; + continue; + } + if (char === '[') { + operands.push({ type: 'array', items: [] }); + cursor += 1; + continue; + } + if (char === ']') { + for (let index = operands.length - 1; index >= 0; index -= 1) { + if (operands[index].type === 'array') { + const items = operands.slice(index + 1); + operands.length = index; + operands[index].items = items; + break; + } + } + cursor += 1; + continue; + } + if (char === '/') { + const matched = /^\/([^\s/[\]<>(){}%]+)/.exec(source.slice(cursor)); + if (matched) { + operands.push({ type: 'name', value: matched[1] }); + cursor += matched[0].length; + continue; + } + } + const numberMatch = /^[+-]?(\d+\.?\d*|\.\d+)/.exec(source.slice(cursor)); + if (numberMatch) { + operands.push({ type: 'number', value: Number.parseFloat(numberMatch[0]) }); + cursor += numberMatch[0].length; + continue; + } + const operatorMatch = /^[A-Za-z'"*][A-Za-z0-9*'"]*/.exec(source.slice(cursor)); + if (operatorMatch) { + flushOperator(operatorMatch[0]); + cursor += operatorMatch[0].length; + continue; + } + cursor += 1; + } + + return out + .replace(/[ \t]+\n/g, '\n') + .replace(/\n{3,}/g, '\n\n') + .trim(); +} + +function readLiteralString(source, start) { + const bytes = []; + let cursor = start + 1; + let depth = 1; + while (cursor < source.length) { + const char = source[cursor]; + if (char === '\\') { + const next = source[cursor + 1]; + const escapes = { n: 10, r: 13, t: 9, b: 8, f: 12, '(': 40, ')': 41, '\\': 92 }; + if (next in escapes) { + bytes.push(escapes[next]); + cursor += 2; + continue; + } + if (next === '\n') { + cursor += 2; + continue; + } + if (next === '\r') { + cursor += source[cursor + 2] === '\n' ? 3 : 2; + continue; + } + const octal = /^[0-7]{1,3}/.exec(source.slice(cursor + 1)); + if (octal) { + bytes.push(Number.parseInt(octal[0], 8) & 0xff); + cursor += 1 + octal[0].length; + continue; + } + bytes.push(next ? next.charCodeAt(0) : 92); + cursor += 2; + continue; + } + if (char === '(') depth += 1; + if (char === ')') { + depth -= 1; + if (depth === 0) { + cursor += 1; + break; + } + } + bytes.push(source.charCodeAt(cursor) & 0xff); + cursor += 1; + } + return { value: Buffer.from(bytes), next: cursor }; +} + +function decodeBytes(bytes, cmap) { + if (!bytes.length) return ''; + if (!cmap || !cmap.map.size) { + const utf8 = bytes.toString('utf8'); + return utf8.includes('\ufffd') ? bytes.toString('latin1') : utf8; + } + const width = Math.max(1, cmap.codeBytes); + let out = ''; + for (let index = 0; index < bytes.length; index += width) { + let code = 0; + for (let offset = 0; offset < width; offset += 1) { + code = (code << 8) | (bytes[index + offset] || 0); + } + const mapped = cmap.map.get(code); + if (mapped !== undefined) out += mapped; + } + return out; +} + +function documentTitle(objects) { + for (const object of objects.values()) { + const match = /\/Title\s*\(([^)]*)\)/.exec(object.dict || ''); + if (match) return match[1]; + } + return ''; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/xlsx.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/xlsx.mjs new file mode 100644 index 00000000..8acdb879 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/xlsx.mjs @@ -0,0 +1,131 @@ +// .xlsx text extraction: shared strings plus every worksheet, rendered as tab separated rows. + +import { readZip } from './zip.mjs'; +import { decodeXml } from './docx.mjs'; + +/** + * @param {Buffer} buffer + * @returns {{ text: string, sheets: Array<{name:string, rows:number}> }} + */ +export function parseXlsx(buffer) { + const zip = readZip(buffer); + const shared = readSharedStrings(zip); + const sheetFiles = zip + .names() + .filter((name) => /^xl\/worksheets\/sheet\d+\.xml$/.test(name)) + .sort((left, right) => sheetNumber(left) - sheetNumber(right)); + if (!sheetFiles.length) throw new Error('xlsx_no_worksheet_found'); + + const sheetNames = readSheetNames(zip); + const blocks = []; + const sheets = []; + sheetFiles.forEach((file, index) => { + const xml = zip.read(file).toString('utf8'); + const rows = readWorksheetRows(xml, shared); + const name = sheetNames[index] || `Sheet${index + 1}`; + sheets.push({ name, rows: rows.length }); + const body = rows.map((row) => row.join('\t')).join('\n'); + blocks.push(`## 工作表:${name}\n${body}`); + }); + + const text = blocks.join('\n\n'); + if (!text.trim()) throw new Error('xlsx_no_text_content'); + return { text, sheets }; +} + +function sheetNumber(file) { + const matched = /sheet(\d+)\.xml$/.exec(file); + return matched ? Number(matched[1]) : 0; +} + +function readSharedStrings(zip) { + if (!zip.has('xl/sharedStrings.xml')) return []; + const xml = zip.read('xl/sharedStrings.xml').toString('utf8'); + const values = []; + const pattern = /]*>([\s\S]*?)<\/si>/g; + let matched = pattern.exec(xml); + while (matched) { + const parts = []; + const textPattern = /]*>([\s\S]*?)<\/t>/g; + let textMatch = textPattern.exec(matched[1]); + while (textMatch) { + parts.push(decodeXml(textMatch[1] || '')); + textMatch = textPattern.exec(matched[1]); + } + values.push(parts.join('')); + matched = pattern.exec(xml); + } + return values; +} + +function readSheetNames(zip) { + if (!zip.has('xl/workbook.xml')) return []; + const xml = zip.read('xl/workbook.xml').toString('utf8'); + const names = []; + const pattern = /]*\bname="([^"]*)"[^>]*>/g; + let matched = pattern.exec(xml); + while (matched) { + names.push(decodeXml(matched[1])); + matched = pattern.exec(xml); + } + return names; +} + +function readWorksheetRows(xml, shared) { + const rows = []; + const rowPattern = /]*>([\s\S]*?)<\/row>/g; + let rowMatch = rowPattern.exec(xml); + while (rowMatch) { + const cells = []; + let maxIndex = -1; + const cellPattern = /]*?)(?:\/>|>([\s\S]*?)<\/c>)/g; + let cellMatch = cellPattern.exec(rowMatch[1]); + while (cellMatch) { + const attributes = cellMatch[1] || ''; + const body = cellMatch[2] || ''; + const reference = /\br="([A-Z]+)\d+"/.exec(attributes); + const type = /\bt="([^"]+)"/.exec(attributes); + const columnIndex = reference ? columnFromLetters(reference[1]) : cells.length; + const value = readCellValue(body, type ? type[1] : '', shared); + cells[columnIndex] = value; + if (columnIndex > maxIndex) maxIndex = columnIndex; + cellMatch = cellPattern.exec(rowMatch[1]); + } + const normalized = []; + for (let index = 0; index <= maxIndex; index += 1) { + normalized.push(cells[index] === undefined ? '' : String(cells[index])); + } + if (normalized.some((cell) => cell !== '')) rows.push(normalized); + rowMatch = rowPattern.exec(xml); + } + return rows; +} + +function readCellValue(body, type, shared) { + if (type === 'inlineStr') { + const parts = []; + const pattern = /]*>([\s\S]*?)<\/t>/g; + let matched = pattern.exec(body); + while (matched) { + parts.push(decodeXml(matched[1] || '')); + matched = pattern.exec(body); + } + return parts.join(''); + } + const valueMatch = /]*>([\s\S]*?)<\/v>/.exec(body); + const raw = valueMatch ? decodeXml(valueMatch[1] || '') : ''; + if (type === 's') { + const index = Number(raw); + return Number.isFinite(index) && shared[index] !== undefined ? shared[index] : ''; + } + if (type === 'b') return raw === '1' ? 'TRUE' : 'FALSE'; + return raw; +} + +function columnFromLetters(letters) { + let index = 0; + for (const char of letters) { + index = index * 26 + (char.charCodeAt(0) - 64); + } + return index - 1; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/zip.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/zip.mjs new file mode 100644 index 00000000..ddc57e1b --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/parse/zip.mjs @@ -0,0 +1,72 @@ +// Minimal ZIP reader (deflate + stored) built on node:zlib. +// Enough for OOXML containers (.docx / .xlsx) without any third-party dependency. + +import { inflateRawSync } from 'node:zlib'; + +const EOCD_SIGNATURE = 0x06054b50; +const CENTRAL_SIGNATURE = 0x02014b50; +const LOCAL_SIGNATURE = 0x04034b50; + +/** + * @param {Buffer} buffer + */ +export function readZip(buffer) { + let eocd = -1; + const floor = Math.max(0, buffer.length - 66000); + for (let index = buffer.length - 22; index >= floor; index -= 1) { + if (buffer.readUInt32LE(index) === EOCD_SIGNATURE) { + eocd = index; + break; + } + } + if (eocd < 0) throw new Error('zip_end_of_central_directory_not_found'); + + const entryCount = buffer.readUInt16LE(eocd + 10); + let offset = buffer.readUInt32LE(eocd + 16); + if (offset === 0xffffffff || entryCount === 0xffff) { + throw new Error('zip64_container_not_supported'); + } + + const entries = new Map(); + for (let index = 0; index < entryCount; index += 1) { + if (offset + 46 > buffer.length) throw new Error('zip_central_directory_truncated'); + if (buffer.readUInt32LE(offset) !== CENTRAL_SIGNATURE) { + throw new Error('zip_central_directory_invalid'); + } + const method = buffer.readUInt16LE(offset + 10); + const compressedSize = buffer.readUInt32LE(offset + 20); + const uncompressedSize = buffer.readUInt32LE(offset + 24); + const nameLength = buffer.readUInt16LE(offset + 28); + const extraLength = buffer.readUInt16LE(offset + 30); + const commentLength = buffer.readUInt16LE(offset + 32); + const localOffset = buffer.readUInt32LE(offset + 42); + const name = buffer.toString('utf8', offset + 46, offset + 46 + nameLength); + entries.set(name, { method, compressedSize, uncompressedSize, localOffset }); + offset += 46 + nameLength + extraLength + commentLength; + } + + return { + names: () => [...entries.keys()], + has: (name) => entries.has(name), + read(name) { + const entry = entries.get(name); + if (!entry) throw new Error(`zip_entry_missing:${name}`); + const local = entry.localOffset; + if (local + 30 > buffer.length) throw new Error('zip_local_header_truncated'); + if (buffer.readUInt32LE(local) !== LOCAL_SIGNATURE) throw new Error('zip_local_header_invalid'); + const nameLength = buffer.readUInt16LE(local + 26); + const extraLength = buffer.readUInt16LE(local + 28); + const start = local + 30 + nameLength + extraLength; + const data = buffer.subarray(start, start + entry.compressedSize); + if (entry.method === 0) return data; + if (entry.method === 8) { + try { + return inflateRawSync(data); + } catch { + throw new Error('zip_inflate_failed'); + } + } + throw new Error(`zip_compression_method_unsupported:${entry.method}`); + }, + }; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/patch.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/patch.mjs new file mode 100644 index 00000000..25d5ca02 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/patch.mjs @@ -0,0 +1,338 @@ +// SEARCH/REPLACE patch parsing, unique-match verification and unified diff generation. + +const SEARCH_MARKER = /^<{3,}\s*SEARCH\b/; +const SEPARATOR_MARKER = /^={3,}\s*$/; +const REPLACE_MARKER = /^>{3,}\s*REPLACE\b/; + +/** + * Parses SEARCH/REPLACE blocks out of a model reply. + * @param {string} modelText + * @returns {Array<{ search:string, replace:string }>} + */ +export function parsePatchBlocks(modelText) { + const lines = String(modelText || '').replace(/\r\n/g, '\n').split('\n'); + const blocks = []; + let state = null; + let searchLines = []; + let replaceLines = []; + + const flush = () => { + if (state === null) return; + const search = trimBlankEdges(searchLines); + const replace = trimBlankEdges(replaceLines); + if (search) blocks.push({ search, replace }); + state = null; + searchLines = []; + replaceLines = []; + }; + + for (const line of lines) { + const trimmed = line.trim(); + if (SEARCH_MARKER.test(trimmed)) { + flush(); + state = 'search'; + continue; + } + if (SEPARATOR_MARKER.test(trimmed) && state === 'search') { + state = 'replace'; + continue; + } + if (REPLACE_MARKER.test(trimmed)) { + flush(); + continue; + } + if (state === 'search') searchLines.push(line); + else if (state === 'replace') replaceLines.push(line); + } + flush(); + return blocks; +} + +function trimBlankEdges(lines) { + let start = 0; + let end = lines.length; + while (start < end && lines[start].trim() === '') start += 1; + while (end > start && lines[end - 1].trim() === '') end -= 1; + return lines.slice(start, end).join('\n'); +} + +export function countOccurrences(content, needle) { + if (!needle) return 0; + let count = 0; + let index = content.indexOf(needle); + while (index !== -1) { + count += 1; + index = content.indexOf(needle, index + Math.max(1, needle.length)); + } + return count; +} + +/** + * Applies patch blocks. Every block must match the current text exactly once. + * @param {string} content + * @param {Array<{ search:string, replace:string }>} blocks + */ +export function applyBlocks(content, blocks) { + if (!blocks.length) throw new Error('patch_no_blocks_parsed'); + let current = String(content); + const applied = []; + for (const block of blocks) { + const search = block.search; + if (!search.trim()) throw new Error('patch_search_block_empty'); + let occurrences = countOccurrences(current, search); + let usedSearch = search; + let normalized = false; + if (occurrences === 0) { + const relaxed = search + .split('\n') + .map((line) => line.replace(/[ \t]+$/, '')) + .join('\n'); + if (relaxed !== search) { + occurrences = countOccurrences(current, relaxed); + if (occurrences === 1) { + usedSearch = relaxed; + normalized = true; + } + } + } + if (occurrences === 0) { + throw new Error(`patch_search_not_found: 第 ${applied.length + 1} 个补丁块在文件中找不到原文`); + } + if (occurrences > 1) { + throw new Error( + `patch_search_not_unique: 第 ${applied.length + 1} 个补丁块在文件中出现 ${occurrences} 次,需要补充上下文`, + ); + } + current = current.replace(usedSearch, () => block.replace); + applied.push({ + index: applied.length, + occurrences, + normalized, + matchedCharacters: usedSearch.length, + }); + } + return { content: current, applied }; +} + +/* --------------------------------------------------------------- unified diff */ + +export function unifiedDiff(oldText, newText, oldLabel = 'a/file', newLabel = 'b/file', context = 3) { + const before = String(oldText).split('\n'); + const after = String(newText).split('\n'); + + let start = 0; + while (start < before.length && start < after.length && before[start] === after[start]) start += 1; + let endBefore = before.length; + let endAfter = after.length; + while ( + endBefore > start && + endAfter > start && + before[endBefore - 1] === after[endAfter - 1] + ) { + endBefore -= 1; + endAfter -= 1; + } + + const middleBefore = before.slice(start, endBefore); + const middleAfter = after.slice(start, endAfter); + const operations = diffOperations(middleBefore, middleAfter); + if (!operations.some((operation) => operation.type !== 'eq')) return ''; + + const items = []; + // Leading context: the common prefix, trimmed to `context` lines. + const leadStart = Math.max(0, start - context); + for (let index = leadStart; index < start; index += 1) { + items.push({ type: 'eq', value: before[index], oldIndex: index, newIndex: index }); + } + // Changed region. + let oldIndex = start; + let newIndex = start; + for (const operation of operations) { + if (operation.type === 'eq') { + items.push({ type: 'eq', value: operation.value, oldIndex, newIndex }); + oldIndex += 1; + newIndex += 1; + } else if (operation.type === 'del') { + items.push({ type: 'del', value: operation.value, oldIndex, newIndex }); + oldIndex += 1; + } else { + items.push({ type: 'ins', value: operation.value, oldIndex, newIndex }); + newIndex += 1; + } + } + // Trailing context: the common suffix, trimmed to `context` lines. + const tailCount = Math.min(context, after.length - endAfter); + for (let offset = 0; offset < tailCount; offset += 1) { + items.push({ + type: 'eq', + value: after[endAfter + offset], + oldIndex: endBefore + offset, + newIndex: endAfter + offset, + }); + } + + const changedPositions = []; + items.forEach((item, index) => { + if (item.type !== 'eq') changedPositions.push(index); + }); + if (!changedPositions.length) return ''; + + const groups = []; + let groupStart = changedPositions[0]; + let groupEnd = changedPositions[0]; + for (const position of changedPositions.slice(1)) { + if (position - groupEnd > context * 2) { + groups.push([groupStart, groupEnd]); + groupStart = position; + } + groupEnd = position; + } + groups.push([groupStart, groupEnd]); + + const lines = [`--- ${oldLabel}`, `+++ ${newLabel}`]; + for (const [from, to] of groups) { + const sliceStart = Math.max(0, from - context); + const sliceEnd = Math.min(items.length - 1, to + context); + const slice = items.slice(sliceStart, sliceEnd + 1); + const oldCount = slice.filter((item) => item.type !== 'ins').length; + const newCount = slice.filter((item) => item.type !== 'del').length; + const oldStart = slice.find((item) => item.type !== 'ins'); + const newStart = slice.find((item) => item.type !== 'del'); + lines.push( + `@@ -${(oldStart ? oldStart.oldIndex : 0) + 1},${oldCount} +${(newStart ? newStart.newIndex : 0) + 1},${newCount} @@`, + ); + for (const item of slice) { + const marker = item.type === 'eq' ? ' ' : item.type === 'del' ? '-' : '+'; + lines.push(`${marker}${item.value}`); + } + } + return `${lines.join('\n')}\n`; +} + +function diffOperations(before, after) { + const n = before.length; + const m = after.length; + if (n * m > 4_000_000) { + return [ + ...before.map((value) => ({ type: 'del', value })), + ...after.map((value) => ({ type: 'ins', value })), + ]; + } + const width = m + 1; + const table = new Uint32Array((n + 1) * width); + for (let i = n - 1; i >= 0; i -= 1) { + for (let j = m - 1; j >= 0; j -= 1) { + table[i * width + j] = + before[i] === after[j] + ? table[(i + 1) * width + j + 1] + 1 + : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]); + } + } + const operations = []; + let i = 0; + let j = 0; + while (i < n && j < m) { + if (before[i] === after[j]) { + operations.push({ type: 'eq', value: before[i] }); + i += 1; + j += 1; + } else if (table[(i + 1) * width + j] >= table[i * width + j + 1]) { + operations.push({ type: 'del', value: before[i] }); + i += 1; + } else { + operations.push({ type: 'ins', value: after[j] }); + j += 1; + } + } + while (i < n) { + operations.push({ type: 'del', value: before[i] }); + i += 1; + } + while (j < m) { + operations.push({ type: 'ins', value: after[j] }); + j += 1; + } + return operations; +} + +/* ------------------------------------------------------------------- outlines */ + +const ANCHOR_PATTERNS = [ + /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|const|let|var)\s+[\w$]/, + /^\s*(?:def|class)\s+\w/, + /^\s*#\s*\S/, + /^\s*\/\/\s*\S/, + /^\s*\/\*\s*\S/, + /^\s*@media\b/, + /^\s*[.#][\w-][^{]*\{/, + /^\s*<\/?[a-zA-Z][^>]*>/, + /^\s*(?:if|for|while|switch|case)\b/, +]; + +/** + * Builds a compact outline of a file so a model can locate the right region + * even when the file does not fit into the context window. + * @param {string} content + */ +export function buildOutline(content, options = {}) { + const limit = options.limit || 160; + const lines = String(content).split('\n'); + const anchors = []; + lines.forEach((line, index) => { + if (anchors.length >= limit) return; + const trimmed = line.trim(); + if (!trimmed || trimmed.length > 160) return; + if (!ANCHOR_PATTERNS.some((pattern) => pattern.test(line))) return; + anchors.push(`${index + 1}: ${trimmed}`); + }); + return { + totalLines: lines.length, + totalCharacters: content.length, + anchors, + header: lines.slice(0, 12).join('\n'), + }; +} + +/** + * Extracts a window of lines around a located region. + * @param {string} content + * @param {number} startLine 1-based + * @param {number} endLine 1-based + */ +export function extractWindow(content, startLine, endLine, padding = 6) { + const lines = String(content).split('\n'); + const from = Math.max(1, startLine - padding); + const to = Math.min(lines.length, endLine + padding); + return { + from, + to, + text: lines.slice(from - 1, to).join('\n'), + }; +} + +/** Finds the densest region of a file for keywords found in a requirement. */ +export function locateByKeywords(content, requirement) { + const lines = String(content).split('\n'); + const terms = String(requirement || '') + .toLowerCase() + .split(/[^a-z0-9一-龥]+/) + .filter((term) => term.length >= 2); + if (!terms.length) return null; + const hits = lines.map((line) => { + const lower = line.toLowerCase(); + let score = 0; + for (const term of terms) if (lower.includes(term)) score += 1; + return score; + }); + let best = null; + let window = 0; + lines.forEach((_, index) => { + window += hits[index].score; + if (index >= 40) window -= hits[index - 40].score; + if (!best || window > best.score) best = { score: window, index }; + }); + if (!best || best.score <= 0) return null; + const start = Math.max(1, best.index - 20); + const end = Math.min(lines.length, best.index + 40); + return { startLine: start, endLine: end, method: 'keyword' }; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/paths.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/paths.mjs new file mode 100644 index 00000000..fd41234e --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/paths.mjs @@ -0,0 +1,89 @@ +// Write-scope guard. AI code editing is confined to the directories the user allows. + +import { realpath } from 'node:fs/promises'; +import path from 'node:path'; + +/** Text formats the patch engine may rewrite. Binary assets are left untouched. */ +export const EDITABLE_EXTENSIONS = [ + '.html', '.htm', '.css', '.js', '.mjs', '.cjs', '.ts', '.jsx', '.tsx', + '.py', '.md', '.markdown', '.txt', '.json', '.yml', '.yaml', '.xml', '.sql', + '.sh', '.ps1', '.bat', '.cmd', '.ini', '.conf', '.vue', '.php', '.java', '.go', +]; + +/** + * The directories AI code editing may write to. The Mini App sets these from the + * user's saved settings, so nothing is assumed about the machine it runs on. + */ +let writeRoots = []; + +export function configureWriteRoots(roots) { + writeRoots = (Array.isArray(roots) ? roots : []) + .map((root) => String(root || '').trim()) + .filter(Boolean) + .map((root) => path.resolve(root)); +} + +export function getWriteRoots() { + return [...writeRoots]; +} + +export function normalizePath(target) { + return path.resolve(String(target || '').trim()); +} + +export function isUnder(target, root) { + const resolved = path.resolve(target).toLowerCase(); + const base = path.resolve(root).toLowerCase(); + const relative = path.relative(base, resolved); + if (relative === '') return true; + return !relative.startsWith('..') && !path.isAbsolute(relative); +} + +export function findWriteRoot(target) { + return writeRoots.find((root) => isUnder(target, root)) || null; +} + +/** + * Validates that a target file may be written. + * @param {string} targetPath + * @returns {Promise<{ path:string, root:string, extension:string }>} + */ +export async function assertWritable(targetPath) { + const raw = String(targetPath || '').trim(); + if (!raw) throw new Error('target_path_required'); + if (!path.isAbsolute(raw)) throw new Error('target_path_must_be_absolute'); + if (!writeRoots.length) { + throw new Error('write_roots_not_configured: 请先在「路由与设置」里填写允许写入的目录'); + } + + const resolved = normalizePath(raw); + const root = findWriteRoot(resolved); + if (!root) { + throw new Error(`target_outside_allowed_roots: 只允许写入 ${writeRoots.join(' 与 ')}`); + } + + const extension = path.extname(resolved).toLowerCase(); + if (!EDITABLE_EXTENSIONS.includes(extension)) { + throw new Error(`target_extension_not_editable: ${extension || '无扩展名'}`); + } + + // A symlink could point outside the approved roots; compare the real path too. + const real = await realpath(resolved).catch(() => null); + if (real) { + const realRoot = findWriteRoot(real); + if (!realRoot) throw new Error('target_outside_allowed_roots: 目标真实路径超出允许目录'); + return { path: real, root: realRoot, extension }; + } + + // The file does not exist yet: validate its parent directory instead. + const parent = path.dirname(resolved); + const realParent = await realpath(parent).catch(() => null); + if (!realParent) throw new Error(`target_directory_unavailable:${path.basename(parent)}`); + if (!findWriteRoot(realParent)) throw new Error('target_outside_allowed_roots: 目标目录超出允许范围'); + return { path: resolved, root, extension }; +} + +/** Reads a file that may live in the configured reference folders. */ +export function isUnderAny(target, roots) { + return (roots || []).some((root) => isUnder(target, root)); +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/prompts.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/prompts.mjs new file mode 100644 index 00000000..1b2fc8d1 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/prompts.mjs @@ -0,0 +1,123 @@ +// Prompt builders. Every prompt asks for one JSON object so the reply can be verified +// before it reaches the page. + +export const CATEGORY_VALUES = ['知识点', '规则', '合同', '其他']; + +export function analyzeDocumentPrompt({ name, category, text }) { + return { + system: '你是道闸售后运维的资料归档助手,负责把投喂的资料整理成可检索的知识条目。只依据资料原文,不要编造原文没有的内容。', + prompt: [ + `资料名称:${name}`, + `用户指定的资料分类:${category}`, + '', + '请只输出一个 JSON 对象:', + '{"title":"简短的资料标题","summary":"120字以内的资料摘要","keyPoints":["关键条款"],"suggestedCategory":"知识点|规则|合同|其他","suggestedCategoryReason":"一句话理由"}', + '', + '资料原文:', + '---', + String(text).slice(0, 12000), + '---', + ].join('\n'), + }; +} + +export function answerQuestionPrompt({ question, contexts }) { + const blocks = contexts.map((context, index) => { + const label = `S${index + 1}`; + return `【${label}】资料:${context.documentName}(分类:${context.category},片段 ${context.chunkIndex + 1})\n${context.text}`; + }); + const material = blocks.length + ? blocks.join('\n\n') + : '(本次检索没有命中任何资料片段)'; + return { + system: '你是道闸售后运维专家。只依据给出的资料片段回答问题,不得编造资料中没有的条款。若资料不足,必须明确写出缺少哪些依据。', + prompt: [ + `问题:${question}`, + '', + '资料片段:', + material, + '', + '请只输出一个 JSON 对象:', + '{"standardAnswer":"面向运维人员的标准答案,可直接执行","analysis":"解析:判断依据、适用条款、风险提示","confidence":0,"cited":["S1"],"missing":["资料没有覆盖的点"]}', + 'confidence 为 0-100 的置信度;cited 只能填写实际引用的片段编号,没有命中时填写空数组。', + ].join('\n'), + }; +} + +export function locateChangePrompt({ fileName, outline, requirement }) { + return { + system: '你是代码定位助手。根据文件结构大纲判断需要修改的代码区域,只输出 JSON,不要输出解释。', + prompt: [ + `文件:${fileName}`, + `修改要求:${requirement}`, + '', + `文件共 ${outline.totalLines} 行,结构大纲如下(行号: 内容):`, + outline.anchors.join('\n'), + '', + '请只输出一个 JSON 对象:{"startLine":起始行号,"endLine":结束行号,"reason":"判断理由"}', + '行号必须是文件里真实存在的范围,并且要完整覆盖需要改动的代码块。', + ].join('\n'), + }; +} + +export function generatePatchPrompt({ fileName, requirement, window, header }) { + return { + system: [ + '你是资深工程师,擅长对代码做最小且精确的修改。', + '你必须只输出 SEARCH/REPLACE 补丁块,不要输出任何解释、前言或总结。', + ].join('\n'), + prompt: [ + `文件:${fileName}`, + `修改要求:${requirement}`, + '', + '文件开头(仅供理解上下文,不要修改它):', + header, + '', + `相关区域:第 ${window.from} 行到第 ${window.to} 行`, + '区域内容:', + '---', + window.text, + '---', + '', + '输出格式:', + '<<<<<<< SEARCH', + '(逐字复制自上面区域、且在原文件中只出现一次的原文,至少 1 行)', + '=======', + '(替换后的新内容)', + '>>>>>>> REPLACE', + '', + '需要多处修改时可以输出多个补丁块。SEARCH 原文必须与文件中内容逐字一致且唯一。', + ].join('\n'), + }; +} + +export function refinePatchPrompt({ fileName, requirement, window, header, problem }) { + return { + system: [ + '你是资深工程师。你上一次给出的补丁无法安全应用,请重新给出。', + '只输出 SEARCH/REPLACE 补丁块,不要输出任何解释。', + ].join('\n'), + prompt: [ + `文件:${fileName}`, + `修改要求:${requirement}`, + `上一次的问题:${problem}`, + '', + '文件开头(仅供理解上下文):', + header, + '', + `相关区域:第 ${window.from} 行到第 ${window.to} 行`, + '区域内容:', + '---', + window.text, + '---', + '', + '请让 SEARCH 原文更短但仍能唯一确定位置,并确保在整份文件中只出现一次。', + '输出格式:', + '<<<<<<< SEARCH', + '...', + '=======', + '...', + '>>>>>>> REPLACE', + ].join('\n'), + }; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/router.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/router.mjs new file mode 100644 index 00000000..e01c24fb --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/router.mjs @@ -0,0 +1,141 @@ +// Hybrid routing: local Ollama models and the online model, with explicit degradation. + +import { + LARGE_MODEL_CTX, + LARGE_MODEL_PARAM_B, + PREFERRED_CHAT_MODEL, + SMALL_MODEL_CTX, +} from './ollama.mjs'; + +export const ROUTING_MODES = [ + { + id: 'auto', + label: '自动', + hint: '按内容体量与本地模型能力自动选择,本地不可用或在线失败时双向降级', + }, + { + id: 'local_first', + label: '本地优先', + hint: '始终先调用本地模型,本地失败降级到在线模型', + }, + { + id: 'local_only', + label: '仅本地', + hint: '只调用本地 Ollama,不做任何在线降级', + }, + { + id: 'online_only', + label: '仅在线', + hint: '只调用在线模型,不做任何本地降级', + }, +]; + +export const ROUTING_MODE_IDS = ROUTING_MODES.map((mode) => mode.id); + +export function isRoutingMode(value) { + return ROUTING_MODE_IDS.includes(value); +} + +export function parameterSizeB(model) { + const raw = String((model && model.details && model.details.parameter_size) || ''); + const matched = /([\d.]+)/.exec(raw); + return matched ? Number.parseFloat(matched[1]) : 0; +} + +export function isLargeModel(model) { + return parameterSizeB(model) >= LARGE_MODEL_PARAM_B; +} + +/** Fixed context policy from the product rules: 14B → 8K, smaller models → 16K. */ +export function numCtxFor(model) { + return isLargeModel(model) ? LARGE_MODEL_CTX : SMALL_MODEL_CTX; +} + +export function chatModels(models) { + return models.filter( + (model) => Array.isArray(model.capabilities) && model.capabilities.includes('completion'), + ); +} + +/** + * Picks the local chat model for a task. + * @param {Array} models + * @param {{ requireLarge?: boolean }} [options] + */ +export function pickLocalModel(models, options = {}) { + const chats = chatModels(models); + if (!chats.length) return null; + const preferred = chats.find((model) => + String(model.name).toLowerCase().startsWith(PREFERRED_CHAT_MODEL), + ); + if (preferred) { + return { + name: preferred.name, + numCtx: numCtxFor(preferred), + kind: 'preferred', + parameterSizeB: parameterSizeB(preferred), + }; + } + if (options.requireLarge) { + const large = chats.find(isLargeModel); + if (!large) return null; + return { + name: large.name, + numCtx: numCtxFor(large), + kind: 'large', + parameterSizeB: parameterSizeB(large), + }; + } + const large = chats.find(isLargeModel); + const chosen = large || chats[0]; + return { + name: chosen.name, + numCtx: numCtxFor(chosen), + kind: large ? 'large' : 'fallback', + parameterSizeB: parameterSizeB(chosen), + }; +} + +/** + * Decides which routes to try, in order. + * @param {{ mode:string, localModel:object|null, promptChars:number }} input + */ +export function buildRoutePlan(input) { + const { mode, localModel, promptChars } = input; + if (mode === 'online_only') { + return { order: ['online'], degrade: false, reason: '仅在线模式:不调用本地模型' }; + } + if (mode === 'local_only') { + return { order: ['local'], degrade: false, reason: '仅本地模式:不调用在线模型' }; + } + if (mode === 'local_first') { + return localModel + ? { + order: ['local', 'online'], + degrade: true, + reason: `本地优先:先调用 ${localModel.name},失败降级到在线模型`, + } + : { order: ['online'], degrade: true, reason: '本地优先:本机无可用本地模型,直接调用在线模型' }; + } + // auto + if (!localModel) { + return { + order: ['online'], + degrade: true, + reason: '自动:本机未发现可用的本地对话模型', + }; + } + const capacityChars = Math.round(localModel.numCtx * 1.4); + if (promptChars > capacityChars) { + return { + order: ['online', 'local'], + degrade: true, + reason: `自动:内容约 ${promptChars} 字符,超过本地 ${localModel.numCtx} token 窗口,先走在线模型`, + }; + } + return { + order: ['local', 'online'], + degrade: true, + reason: `自动:内容约 ${promptChars} 字符,可放入本地 ${localModel.numCtx} token 窗口,先走本地模型`, + }; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/store.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/store.mjs new file mode 100644 index 00000000..fdc7a264 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/lib/store.mjs @@ -0,0 +1,40 @@ +// Durable state helpers. Every write is atomic: temporary file in the same directory, +// then a rename over the target, so a forced shutdown never leaves a half written file. + +import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; + +export async function ensureDir(directory) { + await mkdir(directory, { recursive: true }); +} + +export async function writeJsonAtomic(file, value) { + await ensureDir(dirname(file)); + const temporary = `${file}.${process.pid}.${Date.now()}.tmp`; + await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8'); + await rename(temporary, file); +} + +export async function readJson(file, fallback = null) { + try { + const raw = await readFile(file, 'utf8'); + return JSON.parse(raw); + } catch { + return fallback; + } +} + +export async function writeFileAtomic(file, data) { + await ensureDir(dirname(file)); + const temporary = `${file}.${process.pid}.${Date.now()}.tmp`; + await writeFile(temporary, data); + await rename(temporary, file); +} + +export async function readFileBuffer(file) { + return readFile(file); +} + +export async function removeIfExists(target) { + await rm(target, { recursive: true, force: true }); +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/miniapp-api.ts b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..5276c6f8 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/miniapp-api.ts @@ -0,0 +1,641 @@ +/** + * 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). + * 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 user switched this provider off for the Mini App; not dispatched. */ + | 'CONNECTOR_NOT_PERMITTED' + | '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_NOT_PERMITTED' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Present whenever the manifest declares `"toolAccess": ["call"]`, even when the user switched + * `tool:call` off: calls then fail with `TOOL_NOT_PERMITTED`. Every `call` is judged by the user's + * global permission rules: `deny` is `TOOL_NOT_PERMITTED`, `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' + | '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'; +} + +/** + * Present when the manifest declares `agentAccess` (`"session.run"` and/or `"session.read"`). + * `run` / `reply` / `answer` / `models` / `agents` / `create` need `session.run`; `observe` and + * `sessions` need `session.read` except for this Mini App's own sessions (see + * agent-interaction.md). + * A new Node session uses the primary Agent unless `agent` names one from `agents()`, 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 `agents()`. 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` / `agents` / `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. */ + 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 `agents()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** + * 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 `session.read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `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. Check `context.capabilities?.has('agent.observe')` first. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** Check `context.capabilities?.has('agent.sessions')` first. */ + sessions(): 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()`). + * Check `context.capabilities?.has('agent.session')`. + */ + session(sessionId: string): 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 Host features, fixed per Host version. It says nothing about this + * Mini App's manifest or authorization: `has('agent.run')` is true on a Host that supports the + * Agent API even when `context.agent` is absent because `agentAccess` was not declared. + * Older Hosts do not inject `capabilities`; check `context.capabilities?.has(...)`. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Present when the manifest declares a `hostConnectorAccess` provider; a provider the user + * switched off is missing from `list()` and its calls fail with `CONNECTOR_NOT_PERMITTED`. + */ + readonly hostConnector?: HostConnectorClient; + /** Installed MCP and Connector tools, each call judged by the user's permission rules. */ + readonly tool?: MiniAppToolClient; + /** + * Present when the manifest declares `agentAccess: ["session.run"]`; while the user has it + * switched off, calls fail with `NOT_PERMITTED`. + */ + readonly agent?: MiniAppAgentClient; +} + +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/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/server.mjs b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/server.mjs new file mode 100644 index 00000000..76cb1204 --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/miniapp/node/server.mjs @@ -0,0 +1,802 @@ +// @ts-check + +import { createServer } from 'node:http'; +import { randomUUID } from 'node:crypto'; +import { readFile, readdir, stat } from 'node:fs/promises'; +import path from 'node:path'; + +import { complete, LlmError, parseJsonObject } from './lib/llm.mjs'; +import { ROUTING_MODES, isRoutingMode } from './lib/router.mjs'; +import { DEFAULT_OLLAMA_BASE, listModels, ollamaVersion } from './lib/ollama.mjs'; +import { CATEGORIES, deleteDocument, listDocuments, retrieve, saveDocument } from './lib/kb.mjs'; +import { + SUPPORTED_EXTENSIONS, + extensionOf, + isSupportedFile, + parseDocument, +} from './lib/parse/index.mjs'; +import { + applyBlocks, + buildOutline, + extractWindow, + locateByKeywords, + parsePatchBlocks, + unifiedDiff, +} from './lib/patch.mjs'; +import { + EDITABLE_EXTENSIONS, + assertWritable, + configureWriteRoots, + getWriteRoots, + isUnderAny, +} from './lib/paths.mjs'; +import { createBackup, listBackups, rollback, sha256 } from './lib/backup.mjs'; +import { runDeploy, stopActiveDeploys } from './lib/deploy.mjs'; +import { ensureDir, readJson, writeFileAtomic, writeJsonAtomic } from './lib/store.mjs'; +import { + analyzeDocumentPrompt, + answerQuestionPrompt, + generatePatchPrompt, + locateChangePrompt, + refinePatchPrompt, +} from './lib/prompts.mjs'; + +const MAX_UPLOAD_BYTES = 25 * 1024 * 1024; +const LARGE_FILE_CHARS = 12000; +const MAX_WINDOW_CHARS = 7000; +const DEPLOY_LOG_LIMIT = 50; +const FILE_LIST_LIMIT = 400; + +const DEFAULT_SETTINGS = { + routingMode: 'auto', + ollamaBase: DEFAULT_OLLAMA_BASE, + backupRoot: '', + ingestRoots: [], + writeRoots: [], + topK: 6, + deployCommands: [], +}; + +/** + * @param {import('./miniapp-api.js').MiniAppContext} context + */ +export async function start(context) { + const dataDir = context.dataDir; + const kbDir = path.join(dataDir, 'kb'); + const patchesDir = path.join(dataDir, 'patches'); + const settingsFile = path.join(dataDir, 'settings.json'); + const deployLogFile = path.join(dataDir, 'deploy-logs.json'); + await ensureDir(kbDir); + await ensureDir(patchesDir); + + const stored = await readJson(settingsFile, null); + let settings = { ...DEFAULT_SETTINGS, ...(stored && typeof stored === 'object' ? stored : {}) }; + if (!isRoutingMode(settings.routingMode)) settings.routingMode = DEFAULT_SETTINGS.routingMode; + if (!Array.isArray(settings.deployCommands)) settings.deployCommands = DEFAULT_SETTINGS.deployCommands; + if (!Array.isArray(settings.ingestRoots)) settings.ingestRoots = DEFAULT_SETTINGS.ingestRoots; + if (!Array.isArray(settings.writeRoots)) settings.writeRoots = DEFAULT_SETTINGS.writeRoots; + configureWriteRoots(settings.writeRoots); + + const modelContext = { + ollamaBase: settings.ollamaBase, + agent: context.agent, + logger: context.logger, + }; + + /* ------------------------------------------------------------- utilities */ + + const sendJson = (response, status, payload) => { + const body = JSON.stringify(payload); + response.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + 'content-length': Buffer.byteLength(body), + }); + response.end(body); + }; + + const readBody = (request, limit = MAX_UPLOAD_BYTES) => + new Promise((resolve, reject) => { + const chunks = []; + let size = 0; + request.on('data', (chunk) => { + size += chunk.length; + if (size > limit) { + reject(new Error('payload_too_large')); + request.destroy(); + return; + } + chunks.push(chunk); + }); + request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + request.on('error', reject); + }); + + const readJsonBody = async (request) => { + const raw = await readBody(request); + if (!raw.trim()) return {}; + try { + const parsed = JSON.parse(raw); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { + throw new Error('invalid_json_body'); + } + }; + + const serveAsset = async (response, fileName, contentType) => { + try { + const content = await readFile(path.join(context.pluginRoot, 'miniapp/client', fileName)); + response.writeHead(200, { + 'content-type': contentType, + 'cache-control': 'no-store', + 'content-length': content.length, + }); + response.end(content); + } catch { + response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); + response.end('asset not found'); + } + }; + + /* ----------------------------------------------------------------- state */ + + const readState = async () => { + let ollama = { reachable: false, version: null, models: [], error: null }; + try { + const [version, models] = await Promise.all([ + ollamaVersion(settings.ollamaBase), + listModels(settings.ollamaBase), + ]); + ollama = { + reachable: true, + version, + error: null, + models: models.map((model) => ({ + name: model.name, + capabilities: model.capabilities || [], + parameterSize: (model.details && model.details.parameter_size) || '', + })), + }; + } catch (error) { + ollama = { ...ollama, error: error instanceof Error ? error.message : String(error) }; + } + return { + ok: true, + settings, + routingModes: ROUTING_MODES, + writeRoots: getWriteRoots(), + categories: CATEGORIES, + supportedExtensions: SUPPORTED_EXTENSIONS, + codeExtensions: EDITABLE_EXTENSIONS, + ollama, + onlineModel: { + available: Boolean(context.agent), + label: 'MiniMax 在线模型(Agent 通道)', + }, + documents: await listDocuments(kbDir), + backups: await listBackups(settings.backupRoot), + deployLogs: (await readJson(deployLogFile, [])) || [], + }; + }; + + const saveSettings = async (patch) => { + const next = { ...settings }; + if (patch.routingMode !== undefined) { + if (!isRoutingMode(patch.routingMode)) throw new Error('invalid_routing_mode'); + next.routingMode = patch.routingMode; + } + if (patch.ollamaBase !== undefined) { + const base = String(patch.ollamaBase).trim().replace(/\/+$/, ''); + if (!/^https?:\/\/.+/i.test(base)) throw new Error('invalid_ollama_base'); + next.ollamaBase = base; + } + if (patch.backupRoot !== undefined) { + const root = String(patch.backupRoot).trim(); + if (root && !path.isAbsolute(root)) throw new Error('invalid_backup_root'); + next.backupRoot = root; + } + if (patch.ingestRoots !== undefined) { + if (!Array.isArray(patch.ingestRoots)) throw new Error('invalid_ingest_roots'); + next.ingestRoots = patch.ingestRoots + .map((root) => String(root).trim()) + .filter(Boolean) + .map((root) => { + if (!path.isAbsolute(root)) throw new Error('invalid_ingest_root'); + return root; + }); + } + if (patch.writeRoots !== undefined) { + if (!Array.isArray(patch.writeRoots)) throw new Error('invalid_write_roots'); + next.writeRoots = patch.writeRoots + .map((root) => String(root).trim()) + .filter(Boolean) + .map((root) => { + if (!path.isAbsolute(root)) throw new Error('invalid_write_root'); + return root; + }); + } + if (patch.topK !== undefined) { + const topK = Number(patch.topK); + if (!Number.isInteger(topK) || topK < 1 || topK > 20) throw new Error('invalid_top_k'); + next.topK = topK; + } + if (patch.deployCommands !== undefined) { + if (!Array.isArray(patch.deployCommands)) throw new Error('invalid_deploy_commands'); + next.deployCommands = patch.deployCommands.map((entry) => { + const command = String(entry.command || '').trim(); + const workdir = String(entry.workdir || '').trim(); + if (!command) throw new Error('deploy_command_required'); + if (command.length > 500) throw new Error('deploy_command_too_long'); + if (!path.isAbsolute(workdir)) throw new Error('invalid_deploy_workdir'); + const resolved = path.resolve(workdir); + if (!getWriteRoots().some((root) => isUnderAny(resolved, [root]))) { + throw new Error('deploy_workdir_outside_allowed_roots: 工作目录必须在允许写入的目录之下'); + } + return { + id: String(entry.id || randomUUID()).trim(), + name: String(entry.name || command).trim(), + command, + workdir: resolved, + }; + }); + } + settings = next; + modelContext.ollamaBase = settings.ollamaBase; + configureWriteRoots(settings.writeRoots); + await writeJsonAtomic(settingsFile, settings); + return settings; + }; + + /* -------------------------------------------------------------- documents */ + + const ingestDocument = async (body) => { + const category = String(body.category || '').trim(); + if (!CATEGORIES.includes(category)) throw new Error('invalid_category'); + + let name = String(body.name || '').trim(); + let buffer; + let sourcePath = null; + + if (typeof body.dataBase64 === 'string' && body.dataBase64) { + buffer = Buffer.from(body.dataBase64, 'base64'); + if (!buffer.length) throw new Error('uploaded_file_empty'); + if (!name) throw new Error('uploaded_file_name_required'); + if (buffer.length > MAX_UPLOAD_BYTES) throw new Error('uploaded_file_too_large'); + } else if (body.path) { + const requested = path.resolve(String(body.path).trim()); + if (!isUnderAny(requested, settings.ingestRoots)) { + throw new Error('source_path_outside_ingest_roots: 资料只能从已配置的资料目录读取'); + } + const info = await stat(requested).catch(() => null); + if (!info || !info.isFile()) throw new Error('source_file_not_found'); + if (info.size > MAX_UPLOAD_BYTES) throw new Error('source_file_too_large'); + buffer = await readFile(requested); + sourcePath = requested; + name = path.basename(requested); + } else { + throw new Error('document_source_required'); + } + + if (!isSupportedFile(name)) throw new Error(`unsupported_file_type:${extensionOf(name) || '未知'}`); + const parsed = parseDocument(name, buffer); + + const prompt = analyzeDocumentPrompt({ name, category, text: parsed.text }); + const analysis = await complete(modelContext, { + task: 'analyze', + mode: settings.routingMode, + system: prompt.system, + prompt: prompt.prompt, + signal: context.signal, + }); + const parsedAnalysis = parseJsonObject(analysis.text) || {}; + + const document = await saveDocument({ + kbDir, + ollamaBase: settings.ollamaBase, + name, + category, + kind: parsed.kind, + sourcePath, + sizeBytes: buffer.length, + text: parsed.text, + analysis: { + title: parsedAnalysis.title, + summary: parsedAnalysis.summary, + keyPoints: Array.isArray(parsedAnalysis.keyPoints) ? parsedAnalysis.keyPoints : [], + suggestedCategory: parsedAnalysis.suggestedCategory, + suggestedCategoryReason: parsedAnalysis.suggestedCategoryReason, + route: analysis.route, + }, + }); + + return { + ok: true, + document, + analysis: { + title: parsedAnalysis.title || document.title, + summary: parsedAnalysis.summary || '', + keyPoints: document.keyPoints, + suggestedCategory: parsedAnalysis.suggestedCategory || '', + suggestedCategoryReason: parsedAnalysis.suggestedCategoryReason || '', + }, + parseMeta: parsed.meta, + route: analysis.route, + }; + }; + + /* ------------------------------------------------------------------ files */ + + const listFiles = async (url) => { + const kind = url.searchParams.get('kind') === 'code' ? 'code' : 'document'; + const root = String(url.searchParams.get('root') || '').trim(); + const relative = String(url.searchParams.get('path') || '').trim(); + const allowed = kind === 'code' ? getWriteRoots() : settings.ingestRoots; + if (!allowed.length) { + throw new Error( + kind === 'code' + ? 'write_roots_not_configured: 请先在「路由与设置」里填写允许写入的目录' + : 'ingest_roots_not_configured: 请先在「路由与设置」里填写资料目录', + ); + } + if (!allowed.some((entry) => isUnderAny(root, [entry]))) { + throw new Error('directory_not_allowed'); + } + const base = path.resolve(root); + const directory = relative ? path.resolve(base, relative) : base; + if (!isUnderAny(directory, [base])) throw new Error('directory_not_allowed'); + + const allowedExtensions = kind === 'code' ? EDITABLE_EXTENSIONS : SUPPORTED_EXTENSIONS; + const results = []; + const walk = async (current, depth) => { + if (depth > 3 || results.length >= FILE_LIST_LIMIT) return; + const entries = await readdir(current, { withFileTypes: true }).catch(() => []); + for (const entry of entries) { + if (results.length >= FILE_LIST_LIMIT) return; + if (entry.name.startsWith('.')) continue; + const full = path.join(current, entry.name); + if (entry.isDirectory()) { + await walk(full, depth + 1); + continue; + } + if (!entry.isFile()) continue; + const extension = extensionOf(entry.name); + if (!allowedExtensions.includes(extension)) continue; + const info = await stat(full).catch(() => null); + results.push({ + name: entry.name, + path: full, + relative: path.relative(base, full), + extension, + sizeBytes: info ? info.size : 0, + }); + } + }; + await walk(directory, 0); + return { ok: true, root: base, kind, files: results }; + }; + + /* -------------------------------------------------------------------- ask */ + + const ask = async (body) => { + const question = String(body.question || '').trim(); + if (!question) throw new Error('question_required'); + const topK = body.topK ? Number(body.topK) : settings.topK; + const { matches } = await retrieve({ + kbDir, + ollamaBase: settings.ollamaBase, + question, + topK, + signal: context.signal, + }); + + const prompt = answerQuestionPrompt({ question, contexts: matches }); + const result = await complete(modelContext, { + task: 'answer', + mode: settings.routingMode, + system: prompt.system, + prompt: prompt.prompt, + signal: context.signal, + }); + const parsed = parseJsonObject(result.text) || {}; + const citedLabels = Array.isArray(parsed.cited) ? parsed.cited.map(String) : []; + const cited = citedLabels + .map((label) => { + const index = Number.parseInt(label.replace(/^[^0-9]*/, ''), 10) - 1; + return Number.isFinite(index) ? matches[index] : undefined; + }) + .filter(Boolean); + + return { + ok: true, + question, + matched: matches.length > 0, + answer: { + standardAnswer: parsed.standardAnswer || result.text, + analysis: parsed.analysis || '', + confidence: typeof parsed.confidence === 'number' ? parsed.confidence : null, + missing: Array.isArray(parsed.missing) ? parsed.missing : [], + structured: Boolean(parsed.standardAnswer), + }, + cited, + sources: matches.map((match) => ({ + documentId: match.documentId, + documentName: match.documentName, + category: match.category, + chunkIndex: match.chunkIndex, + score: match.score, + similarity: match.similarity, + preview: match.preview, + })), + route: result.route, + }; + }; + + /* ------------------------------------------------------------------ patch */ + + const createPatch = async (body) => { + const requirement = String(body.requirement || '').trim(); + if (!requirement) throw new Error('requirement_required'); + const target = await assertWritable(body.targetPath); + const originalBuffer = await readFile(target.path); + const original = originalBuffer.toString('utf8'); + const fileName = path.basename(target.path); + const outline = buildOutline(original); + + let window; + let locatedBy = 'whole-file'; + if (original.length > LARGE_FILE_CHARS) { + let region = null; + const locatePrompt = locateChangePrompt({ fileName, outline, requirement }); + const locateResult = await complete(modelContext, { + task: 'locate', + mode: settings.routingMode, + system: locatePrompt.system, + prompt: locatePrompt.prompt, + signal: context.signal, + }); + const located = parseJsonObject(locateResult.text) || {}; + const startLine = Number(located.startLine); + const endLine = Number(located.endLine); + if ( + Number.isFinite(startLine) && + Number.isFinite(endLine) && + startLine >= 1 && + endLine >= startLine && + startLine <= outline.totalLines + ) { + region = { startLine, endLine: Math.min(endLine, outline.totalLines) }; + locatedBy = 'model'; + } + if (!region) { + const fallback = locateByKeywords(original, requirement); + region = fallback + ? { startLine: fallback.startLine, endLine: fallback.endLine } + : { startLine: 1, endLine: Math.min(outline.totalLines, 120) }; + locatedBy = fallback ? 'keyword' : 'file-start'; + } + window = extractWindow(original, region.startLine, region.endLine, 8); + if (window.text.length > MAX_WINDOW_CHARS) { + window = { ...window, text: window.text.slice(0, MAX_WINDOW_CHARS), truncated: true }; + } + } else { + window = { from: 1, to: outline.totalLines, text: original, truncated: false }; + } + + let blocks = null; + let newContent = null; + let appliedInfo = null; + let route = null; + let problem = '模型没有返回 SEARCH/REPLACE 补丁块'; + + for (let attempt = 0; attempt < 2; attempt += 1) { + const prompt = + attempt === 0 + ? generatePatchPrompt({ + fileName, + requirement, + window, + header: outline.header, + }) + : refinePatchPrompt({ + fileName, + requirement, + window, + header: outline.header, + problem, + }); + const result = await complete(modelContext, { + task: 'patch', + mode: settings.routingMode, + system: prompt.system, + prompt: prompt.prompt, + requireLarge: settings.routingMode === 'auto', + signal: context.signal, + }); + route = result.route; + const parsedBlocks = parsePatchBlocks(result.text); + if (!parsedBlocks.length) { + problem = '模型没有返回可解析的 SEARCH/REPLACE 补丁块'; + continue; + } + try { + const applied = applyBlocks(original, parsedBlocks); + blocks = parsedBlocks; + newContent = applied.content; + appliedInfo = applied.applied; + break; + } catch (error) { + problem = error instanceof Error ? error.message : String(error); + } + } + + if (!blocks) throw new Error(`patch_generation_failed: ${problem}`); + + const relativeLabel = path.relative(target.root, target.path).split(path.sep).join('/'); + const diff = unifiedDiff(original, newContent, `a/${relativeLabel}`, `b/${relativeLabel}`); + const patchId = randomUUID(); + await writeJsonAtomic(path.join(patchesDir, `${patchId}.json`), { + id: patchId, + createdAt: new Date().toISOString(), + targetPath: target.path, + root: target.root, + requirement, + fileName, + originalSha256: sha256(originalBuffer), + originalBytes: originalBuffer.length, + blocks, + applied: appliedInfo, + diff, + newContent, + locatedBy, + window: { from: window.from, to: window.to, truncated: Boolean(window.truncated) }, + status: 'previewed', + }); + + return { + ok: true, + patchId, + targetPath: target.path, + root: target.root, + fileName, + requirement, + blocks, + applied: appliedInfo, + diff, + locatedBy, + window: { from: window.from, to: window.to, truncated: Boolean(window.truncated) }, + fileLines: outline.totalLines, + route, + }; + }; + + const applyPatch = async (body) => { + const patchId = String(body.patchId || '').trim(); + if (!patchId) throw new Error('patch_id_required'); + const record = await readJson(path.join(patchesDir, `${patchId}.json`), null); + if (!record) throw new Error('patch_not_found'); + + const target = await assertWritable(record.targetPath); + const currentBuffer = await readFile(target.path); + if (sha256(currentBuffer) !== record.originalSha256) { + throw new Error('target_changed_since_preview: 目标文件在预览之后已被修改,请重新生成补丁'); + } + + if (!settings.backupRoot) { + throw new Error('backup_root_not_configured: 请先在「路由与设置」里填写备份根目录'); + } + const backup = await createBackup({ + backupRoot: settings.backupRoot, + targetPath: target.path, + root: target.root, + originalBuffer: currentBuffer, + patch: record.blocks, + diff: record.diff, + }); + + await writeFileAtomic(target.path, Buffer.from(record.newContent, 'utf8')); + const afterBuffer = await readFile(target.path); + const afterSha = sha256(afterBuffer); + + record.status = 'applied'; + record.appliedAt = new Date().toISOString(); + record.backup = { + id: backup.id, + directory: backup.backupDirectory, + file: backup.backupFile, + manifestPath: path.join(backup.backupDirectory, 'manifest.json'), + recordPath: path.join(backup.backupDirectory, 'record.json'), + }; + record.sha256Before = record.originalSha256; + record.sha256After = afterSha; + await writeJsonAtomic(path.join(patchesDir, `${patchId}.json`), record); + + return { + ok: true, + patchId, + targetPath: target.path, + backupPath: backup.backupDirectory, + backupFile: backup.backupFile, + manifestPath: record.backup.manifestPath, + recordPath: record.backup.recordPath, + backupId: backup.id, + sha256Before: record.originalSha256, + sha256After: afterSha, + diff: record.diff, + }; + }; + + const runRollback = async (body) => { + const operationId = String(body.operationId || '').trim(); + if (!operationId) throw new Error('operation_id_required'); + if (!settings.backupRoot) { + throw new Error('backup_root_not_configured: 请先在「路由与设置」里填写备份根目录'); + } + const result = await rollback({ backupRoot: settings.backupRoot, operationId }); + return { ok: result.ok, ...result }; + }; + + /* ----------------------------------------------------------------- deploy */ + + const deploy = async (body) => { + const commandId = String(body.commandId || '').trim(); + const entry = settings.deployCommands.find((item) => item.id === commandId); + if (!entry) throw new Error('deploy_command_not_found'); + const cwd = path.resolve(entry.workdir); + if (!getWriteRoots().some((root) => isUnderAny(cwd, [root]))) { + throw new Error('deploy_workdir_outside_allowed_roots'); + } + const result = await runDeploy({ + command: entry.command, + cwd, + timeoutMs: 120000, + signal: context.signal, + }); + const log = { + id: randomUUID(), + at: new Date().toISOString(), + commandId: entry.id, + name: entry.name, + command: entry.command, + workdir: cwd, + ok: result.ok, + code: result.code, + stdout: result.stdout, + stderr: result.stderr, + error: result.error, + timedOut: result.timedOut, + durationMs: result.durationMs, + }; + const logs = (await readJson(deployLogFile, [])) || []; + logs.unshift(log); + await writeJsonAtomic(deployLogFile, logs.slice(0, DEPLOY_LOG_LIMIT)); + return { ok: true, log, logs: logs.slice(0, DEPLOY_LOG_LIMIT) }; + }; + + /* ------------------------------------------------------------------ routes */ + + const routeApi = async (route, method, url, request) => { + if (method === 'GET' && route === '/api/state') return readState(); + if (method === 'POST' && route === '/api/settings') { + const body = await readJsonBody(request); + return { ok: true, settings: await saveSettings(body) }; + } + if (method === 'GET' && route === '/api/documents') { + return { ok: true, documents: await listDocuments(kbDir) }; + } + if (method === 'POST' && route === '/api/documents') { + const body = await readJsonBody(request); + return ingestDocument(body); + } + if (method === 'DELETE' && route === '/api/documents') { + const id = String(url.searchParams.get('id') || '').trim(); + if (!id) throw new Error('document_id_required'); + const removed = await deleteDocument(kbDir, id); + if (!removed) throw new Error('document_not_found'); + return { ok: true, documentId: id }; + } + if (method === 'GET' && route === '/api/files') return listFiles(url); + if (method === 'POST' && route === '/api/ask') { + const body = await readJsonBody(request); + return ask(body); + } + if (method === 'POST' && route === '/api/patch') { + const body = await readJsonBody(request); + return createPatch(body); + } + if (method === 'POST' && route === '/api/patch/apply') { + const body = await readJsonBody(request); + return applyPatch(body); + } + if (method === 'GET' && route === '/api/backups') { + return { ok: true, backups: await listBackups(settings.backupRoot) }; + } + if (method === 'POST' && route === '/api/rollback') { + const body = await readJsonBody(request); + return runRollback(body); + } + if (method === 'POST' && route === '/api/deploy') { + const body = await readJsonBody(request); + return deploy(body); + } + throw new Error('not_found'); + }; + + const handle = async (request, response) => { + const url = new URL(request.url || '/', 'http://miniapp.local'); + const route = url.pathname; + const method = request.method || 'GET'; + + if (method === 'GET' && (route === '/' || route === '/dashboard')) { + await serveAsset(response, 'index.html', 'text/html; charset=utf-8'); + return; + } + if (method === 'GET' && route === '/app.js') { + await serveAsset(response, 'app.js', 'text/javascript; charset=utf-8'); + return; + } + if (method === 'GET' && route === '/styles.css') { + await serveAsset(response, 'styles.css', 'text/css; charset=utf-8'); + return; + } + if (route.startsWith('/api/')) { + try { + const payload = await routeApi(route, method, url, request); + sendJson(response, 200, payload); + } catch (error) { + const code = + error instanceof LlmError + ? error.code + : String((error && error.message) || 'request_failed').split(':')[0]; + const message = error instanceof Error ? error.message : String(error); + context.logger.warn('miniapp.request.failed', { route, code }); + sendJson(response, 400, { ok: false, error: code, message }); + } + return; + } + sendJson(response, 404, { ok: false, error: 'not_found', message: '未知路由' }); + }; + + const server = createServer((request, response) => { + handle(request, response).catch((error) => { + context.logger.error('miniapp.request.unhandled', { message: String(error && error.message) }); + if (!response.headersSent) { + sendJson(response, 500, { + ok: false, + error: 'internal_error', + message: error instanceof Error ? error.message : '未知错误', + }); + } else { + response.end(); + } + }); + }); + + await new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(context.listen.port, context.listen.host, () => { + server.off('error', onError); + resolve(); + }); + }); + context.logger.info('miniapp.runtime.listening'); + + let disposed = false; + const dispose = async () => { + if (disposed) return; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + stopActiveDeploys(); + await new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections?.(); + }); + }; + const onAbort = () => { + void dispose(); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} diff --git a/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/package.json b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/yakuyama1979-art/daozha-ops-knowledge-assistant/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +}