diff --git a/README.md b/README.md index a085538a..289dab87 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | MiniApp | What it does | Author | | --- | --- | --- | +| [MiniMax in WSL](plugins/jeisux92/minimax-in-wsl/) | Run the MiniMax Code agent inside WSL: pick a distro and a working directory, then watch every turn stream in as a chat with tool calls, token usage and a working Stop button | [jeisux92](https://github.com/jeisux92) | | [Work Group](plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/) | A chat-style work group where several MiniMax Code Agents reply in one thread, mention each other to hand work over, and ask you for tool approvals and answers as cards in the page | [liuhaolin07](https://github.com/liuhaolin07) | | [Prompt Enhancer](plugins/skypata/prompt-enhancer/) | Rewrite a one-line request into a complete prompt for a coding assistant; the model list and reasoning levels come from MiniMax Code's own configuration, and the rewrite runs on your signed-in account | [skypata](https://github.com/skypata) | | [Postman Lite](plugins/ssugarr/postman-lite/) | A lightweight local API request tool: build requests, send them through a local proxy that sidesteps browser CORS limits, and inspect responses, with collections kept as plain JSON | [ssugarr](https://github.com/ssugarr) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 79d64bff..0e36d81c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -57,6 +57,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | MiniApp | 功能 | 作者 | | --- | --- | --- | +| [MiniMax in WSL](plugins/jeisux92/minimax-in-wsl/) | 在 WSL 里运行 MiniMax Code Agent:选择发行版和工作目录,每一轮都以聊天的形式流式呈现,并展示工具调用、token 用量和可用的停止按钮 | [jeisux92](https://github.com/jeisux92) | | [工作群](plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.zh-CN.md) | 聊天式工作群:多个 MiniMax Code Agent 在同一个群里回复、互相 @ 接力,工具审批和提问以卡片形式在页面里完成 | [liuhaolin07](https://github.com/liuhaolin07) | | [提示词增强器](plugins/skypata/prompt-enhancer/) | 把一句话改写成可以直接交给编码助手的完整提示词,模型清单与推理等级取自 MiniMax Code 自己的配置,改写走你已登录的账号 | [skypata](https://github.com/skypata) | | [Postman Lite](plugins/ssugarr/postman-lite/README.zh-CN.md) | 轻量的本地 API 请求工具:构建请求、通过本地代理转发(绕过浏览器 CORS 限制)、查看响应,集合以纯 JSON 保存 | [ssugarr](https://github.com/ssugarr) | diff --git a/plugins/jeisux92/minimax-in-wsl/.minimax-plugin/plugin.json b/plugins/jeisux92/minimax-in-wsl/.minimax-plugin/plugin.json new file mode 100644 index 00000000..bff99175 --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/.minimax-plugin/plugin.json @@ -0,0 +1,16 @@ +{ + "schemaVersion": 1, + "name": "minimax-in-wsl", + "displayName": "MiniMax in WSL", + "version": "1.0.0", + "description": "Run the MiniMax Code agent inside WSL and stream every turn into a chat workspace.", + "author": "jeisux92", + "icon": "icon.png", + "category": "Code", + "exampleQueries": [ + "Open MiniMax in WSL and start a task in a project directory." + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/jeisux92/minimax-in-wsl/LICENSE b/plugins/jeisux92/minimax-in-wsl/LICENSE new file mode 100644 index 00000000..ddab092c --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 jeisux92 + +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/jeisux92/minimax-in-wsl/README.md b/plugins/jeisux92/minimax-in-wsl/README.md new file mode 100644 index 00000000..5d44b8b0 --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/README.md @@ -0,0 +1,149 @@ +# MiniMax in WSL (`minimax-in-wsl`) + +Run the MiniMax Code agent inside WSL and watch every turn arrive in a chat. + +Sometimes the code you want an agent to work on lives in a Linux environment: a +WSL distro with its own toolchain, its own dependencies, its own files. This +Mini App puts that agent in a workspace next to the conversation. You pick a +distro and a working directory, type a task, and the turn streams in as a +chat: the agent's messages, its reasoning, every tool call it makes, and the +token usage when it finishes. + +Under the hood nothing is simulated. Each message starts a real +`mcode exec --output-format stream-json` inside the distro, driven by the +MiniMax Code CLI that you sign in to, working in the directory you chose. + +## Install + +Copy this directory, including the hidden `.minimax-plugin/`, into the +MiniMax Code plugins directory as `minimax-in-wsl/` +(`~/.minimax/plugins/minimax-in-wsl/` by default; the root README's Install +section explains where that directory is). Restart MiniMax Code and ask the +Agent to "Open MiniMax in WSL". + +Requirements: + +- Windows with WSL and `wsl.exe` on `PATH`. The app drives whatever distros + `wsl.exe -l -q` reports, and the first one that is not a Docker internal + distro is offered by default. +- The MiniMax Code CLI inside the distro. If it is missing, the app says so + and offers to install it with the official installer + (`https://filecdn.minimax.chat/public/install.sh`); it never installs + anything until you click. +- A signed-in MiniMax account in that distro. The app starts + `mcode login --region --no-browser`, shows the authorization URL + and the user code, and you approve the request in your own browser. + +The commands run as the default user of that distro for your Windows account. +On a stock Ubuntu install that is often `root`, because WSL falls back to root +when no default user is configured in `/etc/wsl.conf`. The app does not change +that, and it does not escalate privileges. If you want the agent to work as an +ordinary user, configure one in the distro first and make sure the directory +you pick is readable by it. + +## Using it + +- **Workspace.** The *Directory* picker lists the distro's home directory and + any directory below it, or below `/mnt/c/Users/*`, that looks like a project + (it contains `.git`, `package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod` + or `AGENTS.md`). The list is a convenience, not a limit: the run uses exactly + the directory you select. +- **Permissions.** Headless `mcode exec` cannot stop for an approval prompt, so + the app offers the CLI's own policies instead. *Smart* is the CLI default and + lets it judge each action; *Full access* approves automatically; *Read only* + blocks changes. Choose deliberately — an agent with full access in a + directory can modify it. +- **Conversation.** Follow-up messages continue the same CLI session, so the + agent keeps the context of the turn before. +- **Stop.** Cancelling stops the CLI and everything it started, not just the + top-level process, so a long-running tool does not keep going in the + background. + +## Tested environment + +- MiniMax Code 3.1.23 on Windows 11 (arm64), installed from this directory and + opened through the Agent. +- The package declares `surface.window`, so it needs MiniMax Code 3.1.2 or + later. +- WSL 2 with Ubuntu 24.04.1 (aarch64) and the MiniMax Code CLI 0.8.2 + installed inside it. +- Client acceptance exercised: the status probe read the CLI version and the + sign-in state from the distro; the workspace picker listed the detected + project directories; the setup panel offered the installer when the CLI was + absent and the sign-in flow when it was not authenticated; a real turn ran + end to end and streamed agent messages, reasoning and two tool calls into the + transcript; a follow-up turn continued the same session and answered from the + earlier context; the transcript survived a page reload; and a long-running + turn was cancelled with the Stop button, which stopped the CLI together with + the tool it had started. +- Not verified: macOS and Linux hosts, where `wsl.exe` does not exist; a distro + whose shell is not bash; the China account region; a host without a + reachable npm registry inside the distro. + +## Data & access + +**Agent turns.** This Mini App runs no Host Agent turns: it declares no +`permissions.agent` and never calls `context.agent` or `window.miniapp.agent`. +The agent you see is the MiniMax Code CLI running headless inside your own +WSL distro, under your own MiniMax account, with the CLI's own tools and its +own permission policy. Its output is rendered as untrusted text and is never +executed or interpreted by this app. + +**Files read** (all inside the distro): + +- `~/.minimax/config.yaml`, to show the configured default model. +- `~/.minimax/auth/prod/*/mcode-public/auth-state.json`, to tell "signed in" + from "not signed in". Only the `status` field is read; tokens in that file + are never read, copied or displayed. +- Directory names below the distro's home directory and below `/mnt/c/Users/*`, + to build the workspace picker. + +**Files written:** + +- `conversation.json` in the Mini App's own data directory (`context.dataDir`), + holding the transcript of the current conversation. It is written atomically + (temporary file, then rename). +- The browser's `localStorage`, key `minimax-wsl-view`, holding only the + selected distro and directory. This is a view preference, not domain data. +- Inside the distro, and only while a run is in flight: `/tmp/mcode-prompt-*` + (the prompt text, removed when the run ends), `/tmp/mcode-run-.pid` (the + process id used to cancel a run, removed when the run ends or is cancelled) + and `/tmp/mcode-install-.sh` (the downloaded installer). +- If you click *Install into WSL*, the official MiniMax Code installer writes + `~/.minimax-code/` (the CLI and its private Node.js runtime) and + `~/.minimax-code-install-logs/`, and appends the CLI's path to `~/.bashrc`. + +**Network.** The Mini App's own process makes no outbound network requests; it +serves only the assigned loopback port. All network access happens inside the +distro, from the CLI and the installer: + +- `account.minimax.io` — the sign-in page, which the app prints and you open in + your own browser. +- The MiniMax API endpoints the CLI itself uses for model requests. +- `filecdn.minimax.chat` — the official installer, only when you click + *Install into WSL*. +- `nodejs.org` — a private Node.js runtime, only when the installer finds that + the distro's npm cannot reach a registry. +- `registry.npmjs.org` — the npm registry, for resolving the CLI release and + for checking that npm works. + +**Processes spawned.** Every command is run as an argument array, never through +an interactive shell, and user text never reaches a command line: + +- `wsl.exe -d -- bash -s -- `, which runs a fixed script + supplied on standard input. The prompt and the working directory are + base64-encoded inside that script and decoded in the distro, so neither can + alter the command. +- Inside the distro: `mcode --version`, `mcode login --region + --no-browser`, `mcode exec --output-format stream-json --input - --cwd + --permission ` (optionally `--session `), `npm view + @minimax-ai/code version --json` as an npm health check, `curl` to download + the installer, `bash install.sh`, and `kill`/`pkill` to cancel a run. +- The CLI is started under `setsid` so it leads its own process group; a + cancel signals that whole group, which is why no tool keeps running after a + stop. + +**Not used:** no Host Agent turns, no reading of your conversations, no +connector or MCP tools, no microphone, camera or system notifications, no Host +navigation reading, and no file-extension handlers. The Mini App declares no +permissions at all, so the plugin details show no switchable grants. diff --git a/plugins/jeisux92/minimax-in-wsl/icon.png b/plugins/jeisux92/minimax-in-wsl/icon.png new file mode 100644 index 00000000..299a26cb Binary files /dev/null and b/plugins/jeisux92/minimax-in-wsl/icon.png differ diff --git a/plugins/jeisux92/minimax-in-wsl/miniapp/client/app.js b/plugins/jeisux92/minimax-in-wsl/miniapp/client/app.js new file mode 100644 index 00000000..ece6b672 --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/miniapp/client/app.js @@ -0,0 +1,726 @@ +// MiniMax in WSL — client logic. +// +// The page never talks to WSL directly. It reads status, picks a workspace, +// and posts prompts to the Mini App's own service, which runs every task as a +// real `mcode exec` inside the distro and streams the CLI's events back. + +const transcript = document.getElementById('transcript'); +const emptyState = document.getElementById('empty-state'); +const composer = document.getElementById('composer'); +const promptInput = document.getElementById('prompt'); +const sendButton = document.getElementById('send'); +const stopButton = document.getElementById('stop'); +const distroSelect = document.getElementById('distro'); +const workspaceSelect = document.getElementById('workspace'); +const permissionSelect = document.getElementById('permission'); +const statusPills = document.getElementById('status-pills'); +const subtitle = document.getElementById('subtitle'); +const setupStatus = document.getElementById('setup-status'); +const setupActions = document.getElementById('setup-actions'); +const setupLog = document.getElementById('setup-log'); +const authBox = document.getElementById('auth-box'); +const authCode = document.getElementById('auth-code'); +const authLink = document.getElementById('auth-link'); +const turnList = document.getElementById('turn-list'); +const newChatButton = document.getElementById('new-chat'); +const refreshButton = document.getElementById('refresh'); +const composerHint = document.getElementById('composer-hint'); +const workspaceHint = document.getElementById('workspace-hint'); + +const state = { + status: null, + distro: '', + cwd: '', + workspaces: [], + conversation: { turns: [], sessionId: '', cwd: '' }, + running: false, + activeRunId: '', + region: 'global', +}; + +/* ------------------------------------------------------------------ utils */ + +function formatValue(value) { + if (typeof value === 'string') return value; + try { + return JSON.stringify(value, null, 2); + } catch { + return String(value); + } +} + +function describeToolState(status, hasOutput) { + if (typeof status === 'string') { + const value = status.toLowerCase(); + if (value === 'error' || value === 'failed') return 'failed'; + if (value === 'success' || value === 'completed' || value === 'done' || value === 'finished') { + return 'completed'; + } + if (value === 'running' || value === 'pending' || value === 'in_progress') return 'running'; + } + return hasOutput ? 'completed' : 'running'; +} + +function statusLabel(status) { + switch (status) { + case 'succeeded': + return 'Completed'; + case 'failed': + return 'Failed'; + case 'cancelled': + return 'Cancelled'; + case 'timeout': + return 'Timed out'; + case 'limit_exceeded': + return 'Step limit reached'; + case 'running': + return 'Running'; + default: + return status ?? 'Unknown'; + } +} + +function scrollToBottom() { + transcript.scrollTop = transcript.scrollHeight; +} + +/* --------------------------------------------------------------- streaming */ + +/** + * Read a server sent event stream from a POST response. + */ +async function streamSse(url, body, handlers) { + const response = await fetch(url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }); + + if (!response.ok) { + let message = `The request failed (${response.status}).`; + try { + const data = await response.json(); + if (data && data.error) message = String(data.error); + } catch { + /* keep the generic message */ + } + throw new Error(message); + } + if (!response.body) throw new Error('The runtime did not return a stream.'); + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + + while (true) { + const { value, done } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + let index = buffer.indexOf('\n\n'); + while (index !== -1) { + const chunk = buffer.slice(0, index); + buffer = buffer.slice(index + 2); + handleChunk(chunk, handlers); + index = buffer.indexOf('\n\n'); + } + } +} + +function handleChunk(chunk, handlers) { + let name = 'message'; + const dataLines = []; + for (const line of chunk.split('\n')) { + if (line.startsWith('event:')) name = line.slice(6).trim(); + else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim()); + } + if (dataLines.length === 0) return; + let data; + try { + data = JSON.parse(dataLines.join('\n')); + } catch { + return; + } + handlers.onEvent?.(name, data); +} + +/* ------------------------------------------------------------ turn rendering */ + +function createTurnView(turn) { + const root = document.createElement('article'); + root.className = 'turn'; + + const promptNode = document.createElement('div'); + promptNode.className = 'turn-prompt'; + promptNode.textContent = turn.prompt ?? ''; + root.append(promptNode); + + const body = document.createElement('div'); + body.className = 'turn-body'; + root.append(body); + + const foot = document.createElement('div'); + foot.className = 'turn-foot'; + foot.hidden = true; + root.append(foot); + + /** @type {Map} */ + const items = new Map(); + + const view = { + root, + body, + foot, + items, + hasAgentText: false, + error: '', + usage: null, + modelUsed: '', + status: 'running', + }; + + view.apply = (event) => { + if (!event || typeof event.type !== 'string') return; + switch (event.type) { + case 'item.started': + case 'item.updated': + case 'item.completed': + applyItem(view, event); + break; + case 'turn.completed': + if (event.usage) view.usage = event.usage; + if (event.model) view.modelUsed = String(event.model.modelId ?? event.model.providerId ?? ''); + break; + case 'turn.failed': + view.status = String(event.status ?? 'failed'); + if (event.error && typeof event.error === 'object') { + view.error = String(event.error.message ?? 'The turn failed.'); + } + break; + case 'exec.completed': { + const result = event.result ?? {}; + view.status = String(result.status ?? 'succeeded'); + if (result.usage) view.usage = result.usage; + if (result.error && typeof result.error === 'object') { + view.error = String(result.error.message ?? view.error); + } + const output = typeof result.output === 'string' ? result.output.trim() : ''; + if (output && !view.hasAgentText) { + const node = document.createElement('div'); + node.className = 'message'; + node.textContent = output; + body.append(node); + view.hasAgentText = true; + } + break; + } + default: + break; + } + }; + + view.finish = (finalTurn) => { + const status = finalTurn?.status ?? view.status; + const usage = finalTurn?.usage ?? view.usage; + const modelUsed = finalTurn?.modelUsed || view.modelUsed; + const error = finalTurn?.error || view.error; + + foot.hidden = false; + foot.textContent = ''; + + const statusNode = document.createElement('span'); + statusNode.className = `turn-status status-${status}`; + statusNode.textContent = statusLabel(status); + foot.append(statusNode); + + if (error) { + const errorNode = document.createElement('span'); + errorNode.className = 'notice notice-error'; + errorNode.textContent = error; + foot.append(errorNode); + } + if (modelUsed) { + const modelNode = document.createElement('span'); + modelNode.textContent = `Model: ${modelUsed}`; + foot.append(modelNode); + } + if (usage && typeof usage.totalTokens === 'number') { + const tokenNode = document.createElement('span'); + tokenNode.textContent = `Tokens: ${usage.totalTokens}`; + foot.append(tokenNode); + } + const startedAt = finalTurn?.startedAt ?? 0; + const endedAt = finalTurn?.endedAt ?? 0; + if (startedAt && endedAt > startedAt) { + const durationNode = document.createElement('span'); + durationNode.textContent = `Duration: ${((endedAt - startedAt) / 1000).toFixed(1)} s`; + foot.append(durationNode); + } + }; + + return view; +} + +function createItemEntry(item) { + if (item.type === 'reasoning') { + const node = document.createElement('details'); + node.className = 'reasoning'; + const summary = document.createElement('summary'); + summary.textContent = 'Thinking'; + const bodyNode = document.createElement('div'); + bodyNode.className = 'reasoning-body'; + node.append(summary, bodyNode); + return { node, textNode: bodyNode, text: '' }; + } + + if (item.type === 'tool_call') { + const node = document.createElement('div'); + node.className = 'tool'; + const head = document.createElement('div'); + head.className = 'tool-head'; + const nameNode = document.createElement('span'); + nameNode.className = 'tool-name'; + nameNode.textContent = item.toolCall?.name ?? 'tool'; + const stateNode = document.createElement('span'); + stateNode.className = 'tool-state'; + stateNode.textContent = 'running'; + head.append(nameNode, stateNode); + const details = document.createElement('details'); + const summary = document.createElement('summary'); + summary.textContent = 'Details'; + const pre = document.createElement('pre'); + details.append(summary, pre); + node.append(head, details); + return { node, textNode: pre, text: '', stateNode, nameNode }; + } + + const node = document.createElement('div'); + node.className = 'message'; + const textNode = document.createElement('span'); + node.append(textNode); + return { node, textNode, text: '' }; +} + +function applyItem(view, event) { + const item = event.item; + if (!item || typeof item.id !== 'string') return; + + let entry = view.items.get(item.id); + if (!entry) { + entry = createItemEntry(item); + view.items.set(item.id, entry); + view.body.append(entry.node); + } + + if (item.type === 'agent_message' || item.type === 'reasoning') { + if (typeof item.contentDelta === 'string') entry.text += item.contentDelta; + if (typeof item.content === 'string') entry.text = item.content; + entry.textNode.textContent = entry.text; + if (item.type === 'agent_message' && entry.text.trim()) view.hasAgentText = true; + return; + } + + if (item.type === 'tool_call') { + const toolCall = item.toolCall ?? {}; + if (toolCall.name) entry.nameNode.textContent = String(toolCall.name); + const hasOutput = toolCall.output !== undefined && toolCall.output !== null; + entry.stateNode.textContent = describeToolState(toolCall.status, hasOutput); + const parts = []; + if (toolCall.input !== undefined) parts.push(`Input\n${formatValue(toolCall.input)}`); + if (hasOutput) parts.push(`Output\n${formatValue(toolCall.output)}`); + if (toolCall.durationMs !== undefined) parts.push(`Duration\n${toolCall.durationMs} ms`); + entry.textNode.textContent = parts.join('\n\n') || 'No details reported.'; + return; + } + + entry.textNode.textContent = `Unsupported item type: ${String(item.type)}`; +} + +function renderConversation() { + transcript.textContent = ''; + const turns = Array.isArray(state.conversation.turns) ? state.conversation.turns : []; + + if (turns.length === 0) { + const empty = document.createElement('div'); + empty.className = 'empty'; + const heading = document.createElement('h2'); + heading.textContent = 'Run MiniMax Code inside WSL'; + const text = document.createElement('p'); + text.textContent = + 'Pick a directory, then describe a task. Every message starts a real mcode exec run inside the selected distro.'; + empty.append(heading, text); + transcript.append(empty); + } else { + for (const turn of turns) { + const view = createTurnView(turn); + for (const event of turn.events ?? []) view.apply(event); + view.finish(turn); + transcript.append(view.root); + } + } + + renderTurnList(turns); + scrollToBottom(); +} + +function renderTurnList(turns) { + turnList.textContent = ''; + const recent = turns.slice(-8).reverse(); + for (const turn of recent) { + const item = document.createElement('li'); + const prompt = String(turn.prompt ?? '').replace(/\s+/g, ' ').trim(); + item.textContent = prompt.length > 60 ? `${prompt.slice(0, 60)}…` : prompt; + item.title = prompt; + turnList.append(item); + } +} + +/* ------------------------------------------------------------------- panels */ + +function addPill(text, variant) { + const pill = document.createElement('li'); + pill.className = `pill ${variant}`; + pill.textContent = text; + statusPills.append(pill); +} + +function renderPills() { + statusPills.textContent = ''; + const status = state.status; + if (!status) return; + addPill(status.distro || 'WSL', 'pill'); + addPill( + status.cliPath ? `CLI ${status.cliVersion || 'installed'}` : 'CLI not installed', + status.cliPath ? 'pill-ok' : 'pill-danger', + ); + addPill(status.signedIn ? 'Signed in' : 'Not signed in', status.signedIn ? 'pill-ok' : 'pill-warn'); +} + +function renderSetup() { + setupActions.textContent = ''; + authBox.hidden = true; + const status = state.status; + + if (!status) { + setupStatus.textContent = 'Checking the CLI…'; + return; + } + + if (!status.cliPath) { + setupStatus.textContent = 'The MiniMax Code CLI is not installed in this distro yet.'; + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'btn btn-primary'; + button.textContent = 'Install into WSL'; + button.addEventListener('click', () => void runInstall(button)); + setupActions.append(button); + return; + } + + if (!status.signedIn) { + setupStatus.textContent = `MiniMax Code ${status.cliVersion} is installed. Sign in to run agent tasks.`; + + const regionSelect = document.createElement('select'); + regionSelect.id = 'region'; + regionSelect.setAttribute('aria-label', 'Account region'); + for (const [value, label] of [ + ['global', 'Global account'], + ['cn', 'China account'], + ]) { + const option = document.createElement('option'); + option.value = value; + option.textContent = label; + regionSelect.append(option); + } + regionSelect.value = state.region; + regionSelect.addEventListener('change', () => { + state.region = regionSelect.value; + }); + + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'btn btn-primary'; + button.textContent = 'Sign in'; + button.addEventListener('click', () => void runLogin(button)); + + setupActions.append(regionSelect, button); + return; + } + + setupStatus.textContent = `MiniMax Code ${status.cliVersion} is installed and signed in.`; +} + +async function runInstall(button) { + button.disabled = true; + setupLog.hidden = false; + setupLog.textContent = ''; + try { + await streamSse('/api/install', { distro: state.distro }, { + onEvent: (name, data) => { + if (name === 'log' && data.line) setupLog.textContent += `${data.line}\n`; + if (name === 'error' && data.message) setupLog.textContent += `Error: ${data.message}\n`; + }, + }); + } catch (error) { + setupLog.textContent += `Error: ${error.message}\n`; + } finally { + button.disabled = false; + await refreshStatus(); + } +} + +async function runLogin(button) { + button.disabled = true; + setupLog.hidden = false; + setupLog.textContent = ''; + try { + await streamSse('/api/login', { distro: state.distro, region: state.region }, { + onEvent: (name, data) => { + if (name === 'log') { + if (data.line) setupLog.textContent += `${data.line}\n`; + if (data.authorizationUrl) { + authLink.href = data.authorizationUrl; + authBox.hidden = false; + } + if (data.userCode) authCode.textContent = data.userCode; + } + if (name === 'error' && data.message) setupLog.textContent += `Error: ${data.message}\n`; + }, + }); + } catch (error) { + setupLog.textContent += `Error: ${error.message}\n`; + } finally { + button.disabled = false; + await refreshStatus(); + } +} + +/* -------------------------------------------------------------------- data */ + +async function refreshStatus() { + const response = await fetch(`/api/status${state.distro ? `?distro=${encodeURIComponent(state.distro)}` : ''}`); + if (!response.ok) throw new Error('Could not read the WSL status.'); + const status = await response.json(); + const previousDistro = state.distro; + state.status = status; + state.distro = status.distro ?? ''; + + if (Array.isArray(status.distros) && status.distros.length > 0) { + distroSelect.textContent = ''; + for (const name of status.distros) { + const option = document.createElement('option'); + option.value = name; + option.textContent = name; + distroSelect.append(option); + } + distroSelect.value = state.distro; + } + + subtitle.textContent = status.cliPath + ? `MiniMax Code ${status.cliVersion} in ${status.distro}` + : `Connecting to ${status.distro}…`; + + renderPills(); + renderSetup(); + + if (previousDistro !== state.distro) await loadWorkspaces(); +} + +async function loadWorkspaces() { + try { + const response = await fetch( + `/api/workspaces${state.distro ? `?distro=${encodeURIComponent(state.distro)}` : ''}`, + ); + if (!response.ok) throw new Error('Could not list workspaces.'); + const data = await response.json(); + state.workspaces = Array.isArray(data.directories) ? data.directories : []; + const previous = state.cwd || state.conversation.cwd || data.home || ''; + workspaceSelect.textContent = ''; + for (const directory of state.workspaces) { + const option = document.createElement('option'); + option.value = directory; + option.textContent = directory; + workspaceSelect.append(option); + } + if (previous && state.workspaces.includes(previous)) { + state.cwd = previous; + workspaceSelect.value = previous; + } else { + state.cwd = state.workspaces[0] ?? ''; + workspaceSelect.value = state.cwd; + } + workspaceHint.textContent = state.workspaces.length + ? `${state.workspaces.length} directories detected.` + : 'No project directories detected; the home directory is used.'; + } catch (error) { + workspaceHint.textContent = error.message; + } +} + +async function loadConversation() { + const response = await fetch('/api/conversation'); + if (!response.ok) throw new Error('Could not load the conversation.'); + state.conversation = await response.json(); + renderConversation(); +} + +/* ------------------------------------------------------------------ actions */ + +function setRunning(running) { + state.running = running; + sendButton.disabled = running; + sendButton.textContent = running ? 'Running…' : 'Send'; + stopButton.hidden = !running; +} + +async function sendRun(event) { + event.preventDefault(); + const prompt = promptInput.value.trim(); + if (!prompt || state.running) return; + + if (!state.status?.cliPath) { + composerHint.textContent = 'Install the MiniMax Code CLI in WSL first.'; + return; + } + if (!state.status?.signedIn) { + composerHint.textContent = 'Sign in to MiniMax Code first.'; + return; + } + + composerHint.textContent = ''; + promptInput.value = ''; + setRunning(true); + + const view = createTurnView({ prompt }); + transcript.append(view.root); + scrollToBottom(); + + try { + await streamSse( + '/api/run', + { + prompt, + cwd: state.cwd, + permission: permissionSelect.value, + sessionId: state.conversation.sessionId ?? '', + distro: state.distro, + }, + { + onEvent: (name, data) => { + if (name === 'mcode' && data.event) { + view.apply(data.event); + scrollToBottom(); + } else if (name === 'log' && data.line) { + composerHint.textContent = data.line; + } else if (name === 'turn' && data.turn) { + if (data.turn.id) state.activeRunId = data.turn.id; + view.finish(data.turn); + } else if (name === 'end') { + if (data.sessionId) state.conversation.sessionId = data.sessionId; + } else if (name === 'error' && data.message) { + composerHint.textContent = data.message; + } + }, + }, + ); + } catch (error) { + composerHint.textContent = error.message; + const notice = document.createElement('div'); + notice.className = 'notice notice-error'; + notice.textContent = error.message; + view.body.append(notice); + } finally { + setRunning(false); + state.activeRunId = ''; + await loadConversation(); + await refreshStatus(); + if (!composerHint.textContent.startsWith('Error')) composerHint.textContent = ''; + } +} + +async function stopRun() { + stopButton.disabled = true; + composerHint.textContent = 'Stopping the run…'; + try { + await fetch('/api/cancel', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ distro: state.distro, token: state.activeRunId }), + }); + } finally { + stopButton.disabled = false; + } +} + +async function startNewChat() { + await fetch('/api/conversation/reset', { method: 'POST' }); + state.conversation = { turns: [], sessionId: '', cwd: '' }; + renderConversation(); +} + +/* -------------------------------------------------------------------- wiring */ + +composer.addEventListener('submit', (event) => void sendRun(event)); +stopButton.addEventListener('click', () => void stopRun()); +newChatButton.addEventListener('click', () => void startNewChat()); +refreshButton.addEventListener('click', () => void refreshStatus()); + +distroSelect.addEventListener('change', () => { + state.distro = distroSelect.value; + state.conversation.sessionId = ''; + void refreshStatus(); +}); + +workspaceSelect.addEventListener('change', () => { + state.cwd = workspaceSelect.value; + state.conversation.sessionId = ''; +}); + +promptInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault(); + void sendRun(new Event('submit')); + } +}); + +document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + // The page can be destroyed while hidden; the conversation lives on the + // service, so only the view state needs saving. + try { + window.localStorage.setItem( + 'minimax-wsl-view', + JSON.stringify({ cwd: state.cwd, distro: state.distro }), + ); + } catch { + /* storage is optional */ + } + } +}); + +async function boot() { + try { + const stored = window.localStorage.getItem('minimax-wsl-view'); + if (stored) { + const parsed = JSON.parse(stored); + if (parsed && typeof parsed.cwd === 'string') state.cwd = parsed.cwd; + } + } catch { + /* storage is optional */ + } + + try { + await loadConversation(); + } catch { + renderConversation(); + } + + try { + await refreshStatus(); + await loadWorkspaces(); + } catch (error) { + subtitle.textContent = error.message; + setupStatus.textContent = error.message; + } +} + +void boot(); diff --git a/plugins/jeisux92/minimax-in-wsl/miniapp/client/index.html b/plugins/jeisux92/minimax-in-wsl/miniapp/client/index.html new file mode 100644 index 00000000..6f4b40a2 --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/miniapp/client/index.html @@ -0,0 +1,113 @@ + + + + + + MiniMax in WSL + + + +
+
+
+ +
+

MiniMax in WSL

+

Connecting to WSL…

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

    Run MiniMax Code inside WSL

    +

    + Pick a directory, then describe a task. Every message starts a real + mcode exec run inside the selected distro. +

    +
    +
    + +
    + + +
    +

    +
    + + +
    +
    +
    +
    +
    +
    + + + + diff --git a/plugins/jeisux92/minimax-in-wsl/miniapp/client/styles.css b/plugins/jeisux92/minimax-in-wsl/miniapp/client/styles.css new file mode 100644 index 00000000..067cb989 --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/miniapp/client/styles.css @@ -0,0 +1,702 @@ +/* MiniMax in WSL — Mini App client styles. + Colors are declared once as semantic variables and referenced everywhere else. */ + +: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: #f5f5f5; + --mcode-shadow: 0 0 20px rgb(10 10 10 / 8%); +} + +[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-shadow: 0 0 20px rgb(0 0 0 / 35%); +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme='light']) { + --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-shadow: 0 0 20px rgb(0 0 0 / 35%); + } +} + +* { + box-sizing: border-box; +} + +/* Author class rules set `display`, which would otherwise beat the user-agent + rule for the `hidden` attribute. */ +[hidden] { + display: none !important; +} + +html, +body { + margin: 0; + height: 100%; +} + +body { + background: var(--mcode-bg); + color: var(--mcode-text); + font-family: + ui-sans-serif, + -apple-system, + system-ui, + 'Segoe UI', + Helvetica, + Arial, + sans-serif; + font-size: 14px; + line-height: 1.55; + -webkit-font-smoothing: antialiased; +} + +code, +pre, +.mono { + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +.app { + display: flex; + flex-direction: column; + height: 100vh; +} + +/* ---------- header ---------- */ + +.app-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 24px; + border-bottom: 1px solid var(--mcode-border); + background: var(--mcode-bg); + flex: 0 0 auto; +} + +.brand { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; +} + +.brand-mark { + width: 28px; + height: 28px; + flex: 0 0 auto; + fill: none; + stroke: var(--mcode-text); + stroke-width: 1.5; + stroke-linecap: round; +} + +.brand-text h1 { + margin: 0; + font-size: 18px; + line-height: 24px; + font-weight: 600; +} + +.brand-text p { + margin: 0; + font-size: 12px; + line-height: 16px; + color: var(--mcode-text-muted); +} + +.header-status { + display: flex; + align-items: center; + gap: 12px; +} + +.pills { + display: flex; + align-items: center; + gap: 8px; + margin: 0; + padding: 0; + list-style: none; + flex-wrap: wrap; +} + +.pill { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + border-radius: 999px; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface-muted); + color: var(--mcode-text-muted); + font-size: 12px; + line-height: 16px; + white-space: nowrap; +} + +.pill-ok { + color: var(--mcode-success); + border-color: color-mix(in srgb, var(--mcode-success) 35%, transparent); +} + +.pill-warn { + color: var(--mcode-warning); + border-color: color-mix(in srgb, var(--mcode-warning) 35%, transparent); +} + +.pill-danger { + color: var(--mcode-danger); + border-color: color-mix(in srgb, var(--mcode-danger) 35%, transparent); +} + +/* ---------- layout ---------- */ + +.app-body { + display: flex; + flex: 1 1 auto; + min-height: 0; +} + +.sidebar { + width: 240px; + flex: 0 0 240px; + border-right: 1px solid var(--mcode-border); + background: var(--mcode-bg-secondary); + padding: 16px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 16px; +} + +.panel { + background: var(--mcode-surface); + border: 1px solid var(--mcode-border); + border-radius: 12px; + padding: 16px; +} + +.panel h2 { + margin: 0 0 12px; + font-size: 16px; + line-height: 24px; + font-weight: 500; +} + +.panel-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.panel-head h2 { + margin: 0 0 8px; +} + +.panel-status { + margin: 0 0 12px; + color: var(--mcode-text-muted); + font-size: 13px; +} + +.field { + display: flex; + flex-direction: column; + gap: 4px; + margin-bottom: 12px; +} + +.field label { + font-size: 12px; + color: var(--mcode-text-muted); +} + +select, +textarea, +input { + font: inherit; + color: var(--mcode-text); + background: var(--mcode-surface-muted); + border: 1px solid var(--mcode-border); + border-radius: 8px; + padding: 8px 10px; + width: 100%; +} + +select { + height: 36px; + cursor: pointer; +} + +select:focus-visible, +textarea:focus-visible, +button:focus-visible, +a:focus-visible { + outline: 2px solid var(--mcode-accent); + outline-offset: 1px; +} + +.hint { + margin: 0; + font-size: 12px; + line-height: 16px; + color: var(--mcode-text-subtle); +} + +.setup-actions { + display: flex; + flex-direction: column; + gap: 8px; +} + +.auth-box { + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid var(--mcode-border); + display: flex; + flex-direction: column; + gap: 8px; + align-items: flex-start; +} + +.auth-code-label { + margin: 0; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.auth-code { + margin: 0; + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 20px; + font-weight: 600; + letter-spacing: 0.08em; +} + +.log { + margin: 12px 0 0; + padding: 10px; + max-height: 220px; + overflow: auto; + background: var(--mcode-code-bg); + border: 1px solid var(--mcode-border); + border-radius: 8px; + font-size: 12px; + line-height: 1.5; + white-space: pre-wrap; + word-break: break-word; + color: var(--mcode-text-muted); +} + +.turn-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 2px; +} + +.turn-list li { + font-size: 12px; + line-height: 18px; + color: var(--mcode-text-muted); + padding: 4px 0; + border-bottom: 1px solid var(--mcode-border); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.turn-list li:last-child { + border-bottom: none; +} + +/* ---------- buttons ---------- */ + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 34px; + padding: 0 14px; + border-radius: 8px; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface-muted); + color: var(--mcode-text); + font: inherit; + font-weight: 500; + cursor: pointer; + text-decoration: none; + transition: + background-color 150ms ease-out, + opacity 150ms ease-out; +} + +.btn:hover:not(:disabled) { + background: var(--mcode-bg-secondary); +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.btn-primary { + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); + border-color: transparent; +} + +.btn-primary:hover:not(:disabled) { + background: var(--mcode-primary-action-bg); + opacity: 0.88; +} + +.btn-secondary { + background: transparent; +} + +.btn-danger { + background: transparent; + color: var(--mcode-danger); + border-color: color-mix(in srgb, var(--mcode-danger) 40%, transparent); +} + +.btn-text { + height: 24px; + padding: 0 8px; + background: transparent; + border-color: transparent; + color: var(--mcode-accent); + font-size: 12px; +} + +/* A label that may wrap needs to grow instead of overflowing its own box. */ +.btn-wrap { + height: auto; + min-height: 34px; + padding: 8px 14px; + text-align: center; + line-height: 1.3; +} + +/* ---------- chat ---------- */ + +.chat { + flex: 1 1 auto; + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; +} + +.transcript { + flex: 1 1 auto; + overflow-y: auto; + padding: 24px; + display: flex; + flex-direction: column; + gap: 20px; +} + +.empty { + margin: auto; + max-width: 460px; + text-align: center; + color: var(--mcode-text-muted); +} + +.empty h2 { + margin: 0 0 8px; + font-size: 18px; + font-weight: 600; + color: var(--mcode-text); +} + +.empty p { + margin: 0; +} + +.empty code { + padding: 1px 5px; + border-radius: 4px; + background: var(--mcode-code-bg); +} + +.turn { + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); + overflow: hidden; +} + +.turn-prompt { + padding: 12px 16px; + background: var(--mcode-surface-muted); + border-bottom: 1px solid var(--mcode-border); + font-weight: 500; + white-space: pre-wrap; + word-break: break-word; +} + +.turn-body { + padding: 12px 16px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.turn-foot { + display: flex; + flex-wrap: wrap; + gap: 12px; + padding: 8px 16px; + border-top: 1px solid var(--mcode-border); + font-size: 12px; + color: var(--mcode-text-muted); +} + +.turn-status { + font-weight: 500; +} + +.status-succeeded { + color: var(--mcode-success); +} + +.status-failed { + color: var(--mcode-danger); +} + +.status-cancelled { + color: var(--mcode-warning); +} + +.status-running { + color: var(--mcode-accent); +} + +.message { + white-space: pre-wrap; + word-break: break-word; +} + +.reasoning { + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); +} + +.reasoning > summary { + cursor: pointer; + padding: 8px 12px; + font-size: 12px; + color: var(--mcode-text-muted); + user-select: none; +} + +.reasoning-body { + padding: 0 12px 12px; + white-space: pre-wrap; + word-break: break-word; + color: var(--mcode-text-muted); + font-size: 13px; +} + +.tool { + border: 1px solid var(--mcode-border); + border-radius: 8px; + overflow: hidden; +} + +.tool-head { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + background: var(--mcode-surface-muted); + font-size: 13px; +} + +.tool-name { + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + font-weight: 500; +} + +.tool-state { + font-size: 12px; + color: var(--mcode-text-muted); +} + +.tool > details > summary { + cursor: pointer; + padding: 6px 12px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.tool pre { + margin: 0; + padding: 8px 12px; + max-height: 260px; + overflow: auto; + background: var(--mcode-code-bg); + font-size: 12px; + white-space: pre-wrap; + word-break: break-word; +} + +.notice { + font-size: 13px; + color: var(--mcode-text-muted); +} + +.notice-error { + color: var(--mcode-danger); +} + +/* ---------- composer ---------- */ + +.composer { + flex: 0 0 auto; + border-top: 1px solid var(--mcode-border); + padding: 16px 24px; + background: var(--mcode-bg); + display: flex; + flex-direction: column; + gap: 8px; +} + +.composer textarea { + resize: vertical; + min-height: 64px; + max-height: 220px; + background: var(--mcode-surface); +} + +.composer-bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.composer-buttons { + display: flex; + gap: 8px; +} + +@media (max-width: 860px) { + .app-body { + flex-direction: column; + } + + .sidebar { + width: 100%; + flex: 0 0 auto; + border-right: none; + border-bottom: 1px solid var(--mcode-border); + display: grid; + grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); + align-items: start; + gap: 12px; + padding: 12px 16px; + overflow: visible; + } + + .panel { + padding: 12px; + } + + .panel h2 { + margin-bottom: 8px; + font-size: 14px; + } + + .field { + margin-bottom: 8px; + } + + .turn-list { + max-height: 110px; + overflow-y: auto; + } + + .app-header { + padding: 12px 16px; + } + + .transcript, + .composer { + padding: 16px; + } +} + +@media (prefers-reduced-motion: reduce) { + * { + transition: none !important; + } +} diff --git a/plugins/jeisux92/minimax-in-wsl/miniapp/miniapp.json b/plugins/jeisux92/minimax-in-wsl/miniapp/miniapp.json new file mode 100644 index 00000000..8eb14fdf --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/miniapp/miniapp.json @@ -0,0 +1,27 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/chat", + "window": { + "width": 1120, + "height": 780, + "minWidth": 640, + "minHeight": 480, + "resizable": true + } + }, + "mcpEndpoints": [] +} diff --git a/plugins/jeisux92/minimax-in-wsl/miniapp/node/mcode.mjs b/plugins/jeisux92/minimax-in-wsl/miniapp/node/mcode.mjs new file mode 100644 index 00000000..b80fb54a --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/miniapp/node/mcode.mjs @@ -0,0 +1,475 @@ +// @ts-check + +/** + * MiniMax Code CLI orchestration inside WSL. + * + * The CLI is the real product surface: every run is a genuine `mcode exec` inside + * the distro. Scripts are delivered over stdin (see wsl.mjs), so user supplied + * text never reaches a command line unencoded. + */ + +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { toBase64 } from './wsl.mjs'; + +const INSTALL_URL = 'https://filecdn.minimax.chat/public/install.sh'; +const RUN_TIMEOUT_MS = 60 * 60 * 1000; +const CLI_TIMEOUT_ARG = '60m'; + +/** Auth states that mean "the user still has to sign in". */ +const PENDING_AUTH_STATES = new Set([ + '', + 'anonymous', + 'authorizing', + 'expired', + 'logged_out', + 'pending', + 'signed_out', + 'unauthorized', +]); + +/** + * Resolves the CLI inside the distro. A non-interactive shell never sources + * ~/.bashrc, so `mcode` is normally absent from PATH: check the installer's own + * location first, then the usual PATH entries. + */ +const CLI_RESOLVE = ` +_cli="" +for _c in "$HOME/.minimax-code/bin/mcode" "$HOME/.local/bin/mcode" "/usr/local/bin/mcode" "/usr/bin/mcode"; do + if [ -x "$_c" ]; then _cli="$_c"; break; fi +done +if [ -z "$_cli" ]; then _cli="$(command -v mcode 2>/dev/null || true)"; fi +`; + +const STATUS_SCRIPT = `set +e +export LC_ALL=C.UTF-8 LANG=C.UTF-8 +${CLI_RESOLVE} +_ver="" +if [ -n "$_cli" ]; then _ver="$("$_cli" --version 2>/dev/null | tail -n 1 | tr -d '\\r')"; fi +_auth="" +for _r in en cn; do + _f="$HOME/.minimax/auth/prod/$_r/mcode-public/auth-state.json" + if [ -f "$_f" ]; then + _s="$(grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' "$_f" 2>/dev/null | head -n 1 | sed 's/.*:[[:space:]]*"\\(.*\\)"$/\\1/')" + if [ -n "$_s" ]; then _auth="$_r:$_s"; break; fi + fi +done +_model="$(grep -m 1 'defaultModel' "$HOME/.minimax/config.yaml" 2>/dev/null | sed 's/^[[:space:]]*defaultModel:[[:space:]]*//')" +printf 'cli_path\\t%s\\n' "$_cli" +printf 'cli_version\\t%s\\n' "$_ver" +printf 'auth_state\\t%s\\n' "$_auth" +printf 'default_model\\t%s\\n' "$_model" +printf 'home\\t%s\\n' "$HOME" +printf 'user\\t%s\\n' "$(id -un 2>/dev/null)" +printf 'node_version\\t%s\\n' "$(node --version 2>/dev/null)" +`; + +const WORKSPACES_SCRIPT = `set +e +export LC_ALL=C.UTF-8 LANG=C.UTF-8 +printf 'home\\t%s\\n' "$HOME" +find "$HOME" -maxdepth 2 -mindepth 1 -type d \\( -name .git -o -name package.json -o -name pyproject.toml -o -name Cargo.toml -o -name go.mod -o -name AGENTS.md \\) -printf 'dir\\t%h\\n' 2>/dev/null | sort -u | head -n 40 +for _u in /mnt/c/Users/*; do + [ -d "$_u" ] || continue + find "$_u" -maxdepth 2 -mindepth 1 -type d \\( -name .git -o -name package.json -o -name pyproject.toml -o -name AGENTS.md \\) -printf 'dir\\t%h\\n' 2>/dev/null | sort -u | head -n 25 +done +`; + +const NPM_PROBE_SCRIPT = `set +e +export LC_ALL=C.UTF-8 LANG=C.UTF-8 +command -v npm >/dev/null 2>&1 || exit 1 +timeout 30 npm view @minimax-ai/code version --json --fetch-timeout 20000 2>/dev/null +`; + +const INSTALL_SCRIPT = `set +e +export LC_ALL=C.UTF-8 LANG=C.UTF-8 +_token="$1" +_mode="$2" +_tmp="/tmp/mcode-install-$_token.sh" +echo "Downloading the official MiniMax Code installer..." +if ! curl -fsSL "${INSTALL_URL}" -o "$_tmp"; then + echo "Could not download the installer." + exit 1 +fi +if [ "$_mode" = "isolated" ]; then + echo "The system npm cannot reach the registry, so an isolated Node.js runtime will be installed." + PATH=/usr/bin:/bin:/usr/sbin:/sbin bash "$_tmp" +else + bash "$_tmp" +fi +_code=$? +echo "Installer finished with exit code $_code." +exit $_code +`; + +const LOGIN_SCRIPT = `set +e +export LC_ALL=C.UTF-8 LANG=C.UTF-8 +_token="$1" +_region="$2" +_pidfile="/tmp/mcode-login-$_token.pid" +${CLI_RESOLVE} +if [ -z "$_cli" ]; then + echo "The MiniMax Code CLI was not found in this distro." + exit 127 +fi +# setsid gives the CLI its own process group so a cancel can stop it cleanly. +if command -v setsid >/dev/null 2>&1; then + setsid bash -c 'echo $$ > "$1"; shift; exec "$@"' _ "$_pidfile" "$_cli" login --region "$_region" --no-browser & +else + bash -c 'echo $$ > "$1"; shift; exec "$@"' _ "$_pidfile" "$_cli" login --region "$_region" --no-browser & +fi +_child=$! +wait "$_child" +_code=$? +rm -f "$_pidfile" +exit $_code +`; + +/** + * @param {{ cwdB64: string, promptB64: string, permission: string, sessionId: string, model: string }} parts + */ +function buildExecScript(parts) { + const { cwdB64, promptB64, permission, sessionId, model } = parts; + return `set +e +export LC_ALL=C.UTF-8 LANG=C.UTF-8 +_token="$1" +_pidfile="/tmp/mcode-run-$_token.pid" +_cwd="$(printf '%s' '${cwdB64}' | base64 -d 2>/dev/null)" +_session="${sessionId}" +_model="${model}" +${CLI_RESOLVE} +if [ -z "$_cli" ]; then + echo '{"type":"error","message":"The MiniMax Code CLI was not found in this distro."}' + exit 127 +fi +if [ ! -d "$_cwd" ]; then + echo '{"type":"error","message":"The selected workspace directory does not exist in this distro."}' + exit 66 +fi +_prompt="$(mktemp /tmp/mcode-prompt-XXXXXX)" || exit 70 +# A cancelled run cannot clean up after itself, so drop stale prompt files. +find /tmp -maxdepth 1 -name 'mcode-prompt-*' -mmin +60 -delete 2>/dev/null +printf '%s' '${promptB64}' | base64 -d > "$_prompt" +_cmd=(exec --output-format stream-json --input - --timeout ${CLI_TIMEOUT_ARG} --cwd "$_cwd" --permission ${permission}) +if [ -n "$_session" ]; then _cmd+=(--session "$_session"); fi +if [ -n "$_model" ]; then _cmd+=(--model "$_model"); fi +# setsid puts the CLI in its own process group. The inner shell records its own +# PID, which the exec keeps, so cancelling can stop the CLI and every tool it +# started instead of leaving orphans that keep the output pipe open. +if command -v setsid >/dev/null 2>&1; then + setsid bash -c 'echo $$ > "$1"; shift; exec "$@"' _ "$_pidfile" "$_cli" "\${_cmd[@]}" < "$_prompt" & +else + bash -c 'echo $$ > "$1"; shift; exec "$@"' _ "$_pidfile" "$_cli" "\${_cmd[@]}" < "$_prompt" & +fi +_child=$! +wait "$_child" +_code=$? +rm -f "$_prompt" "$_pidfile" +exit $_code +`; +} + +/** @param {unknown} value */ +function isAbsolutePath(value) { + return ( + typeof value === 'string' && + value.length > 0 && + value.length <= 1024 && + value.startsWith('/') && + !/[\0\r\n]/.test(value) + ); +} + +/** @param {unknown} value */ +function isSafeToken(value) { + return typeof value === 'string' && /^[A-Za-z0-9._-]{1,128}$/.test(value); +} + +/** @param {unknown} value */ +function isSafeModel(value) { + return typeof value === 'string' && value.length > 0 && /^[A-Za-z0-9._/#-]{1,128}$/.test(value); +} + +export class MCodeService { + /** + * @param {{ dataDir: string, logger: { info: Function, warn: Function, error: Function } }} context + * @param {import('./wsl.mjs').WslRunner} runner + */ + constructor(context, runner) { + this.context = context; + this.runner = runner; + this.stateFile = join(context.dataDir, 'conversation.json'); + } + + /** @returns {string} */ + newToken() { + return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`; + } + + /** + * Run a script and collect its output. + * + * @param {string} distro + * @param {string} script + * @param {{ args?: string[], timeoutMs?: number }} [options] + */ + runCapture(distro, script, options = {}) { + const { args = [], timeoutMs = 30000 } = options; + return new Promise((resolve) => { + let stdout = ''; + let stderr = ''; + this.runner.runScript(distro, script, { + args, + timeoutMs, + onStdout: (chunk) => { + stdout += chunk; + if (stdout.length > 400_000) stdout = stdout.slice(-200_000); + }, + onStderr: (chunk) => { + stderr += chunk; + if (stderr.length > 100_000) stderr = stderr.slice(-50_000); + }, + onClose: (code) => resolve({ code: code ?? -1, stdout, stderr }), + }); + }); + } + + /** + * @param {string} distro + * @returns {Promise<{ + * ok: boolean, + * distro: string, + * cliPath: string, + * cliVersion: string, + * authRegion: string, + * authState: string, + * signedIn: boolean, + * defaultModel: string, + * home: string, + * user: string, + * nodeVersion: string, + * error?: string, + * }>} + */ + async getStatus(distro) { + const result = await this.runCapture(distro, STATUS_SCRIPT, { timeoutMs: 30000 }); + /** @type {Record} */ + const fields = {}; + for (const line of result.stdout.split(/\r?\n/)) { + if (!line.trim()) continue; + const index = line.indexOf('\t'); + if (index === -1) continue; + fields[line.slice(0, index).trim()] = line.slice(index + 1).trim(); + } + + const authState = fields.auth_state ?? ''; + const separator = authState.indexOf(':'); + const authRegion = separator === -1 ? '' : authState.slice(0, separator); + const rawState = separator === -1 ? authState : authState.slice(separator + 1); + + return { + ok: result.code === 0, + distro, + cliPath: fields.cli_path ?? '', + cliVersion: fields.cli_version ?? '', + authRegion, + authState: rawState, + signedIn: authRegion !== '' && !PENDING_AUTH_STATES.has(rawState), + defaultModel: fields.default_model ?? '', + home: fields.home ?? '', + user: fields.user ?? '', + nodeVersion: fields.node_version ?? '', + error: result.code === 0 ? undefined : 'Could not read the WSL status.', + }; + } + + /** + * @param {string} distro + * @returns {Promise<{ home: string, directories: string[] }>} + */ + async listWorkspaces(distro) { + const result = await this.runCapture(distro, WORKSPACES_SCRIPT, { timeoutMs: 60000 }); + /** @type {string[]} */ + const directories = []; + let home = ''; + for (const line of result.stdout.split(/\r?\n/)) { + if (!line.trim()) continue; + const index = line.indexOf('\t'); + if (index === -1) continue; + const key = line.slice(0, index).trim(); + const value = line.slice(index + 1).trim(); + if (key === 'home') home = value; + else if (key === 'dir' && value) directories.push(value); + } + const unique = [...new Set(directories)].filter((dir) => isAbsolutePath(dir)); + if (home && isAbsolutePath(home)) unique.unshift(home); + return { home, directories: unique.slice(0, 60) }; + } + + /** + * @param {string} distro + * @returns {Promise} whether the system npm can reach the registry. + */ + async checkNpm(distro) { + const result = await this.runCapture(distro, NPM_PROBE_SCRIPT, { timeoutMs: 45000 }); + const text = result.stdout.trim(); + return /"?\d+\.\d+\.\d+"?/.test(text); + } + + /** + * Install the MiniMax Code CLI into the distro with the official installer. + * + * @param {string} distro + * @param {string} token + * @param {{ onLog: (line: string) => void }} handlers + * @returns {Promise} + */ + async install(distro, token, handlers) { + const npmUsable = await this.checkNpm(distro); + const mode = npmUsable ? 'system' : 'isolated'; + handlers.onLog( + npmUsable + ? 'Using the Node.js and npm already present in the distro.' + : 'The system npm cannot reach the npm registry, so an isolated Node.js runtime will be installed.', + ); + return this.runStreaming(distro, INSTALL_SCRIPT, { args: [token, mode], handlers }); + } + + /** + * Start the interactive sign-in flow. The CLI prints an authorization URL and + * a user code, then waits for the browser approval. + * + * @param {string} distro + * @param {string} token + * @param {string} region + * @param {{ onLog: (line: string) => void }} handlers + * @returns {Promise} + */ + async login(distro, token, region, handlers) { + return this.runStreaming(distro, LOGIN_SCRIPT, { args: [token, region], handlers }); + } + + /** + * Run one agent turn and forward every stream-json event. + * + * @param {{ + * distro: string, + * prompt: string, + * cwd: string, + * permission: string, + * sessionId: string, + * model: string, + * token: string, + * }} options + * @param {{ + * onEvent: (event: Record) => void, + * onLog: (line: string) => void, + * }} handlers + * @returns {Promise} + */ + async runExec(options, handlers) { + const { distro, prompt, cwd, permission, sessionId, model, token } = options; + if (!isAbsolutePath(cwd)) throw new Error('The workspace directory is not valid.'); + if (sessionId && !isSafeToken(sessionId)) throw new Error('The session id is not valid.'); + if (model && !isSafeModel(model)) throw new Error('The model id is not valid.'); + if (!['smart', 'full', 'off'].includes(permission)) throw new Error('The permission mode is not valid.'); + + const script = buildExecScript({ + cwdB64: toBase64(cwd), + promptB64: toBase64(prompt), + permission, + sessionId, + model, + }); + + return this.runStreaming(distro, script, { args: [token], tag: token, handlers, stream: true }); + } + + /** + * @param {string} distro + * @param {string} script + * @param {{ + * args?: string[], + * tag?: string, + * handlers: { onLog: (line: string) => void, onEvent?: (event: Record) => void }, + * stream?: boolean, + * }} options + * @returns {Promise} + */ + runStreaming(distro, script, options) { + const { args = [], tag = '', handlers, stream = false } = options; + return new Promise((resolve) => { + let buffer = ''; + this.runner.runScript(distro, script, { + args, + tag, + timeoutMs: RUN_TIMEOUT_MS, + onStdout: (chunk) => { + buffer += chunk; + let index = buffer.indexOf('\n'); + while (index !== -1) { + const line = buffer.slice(0, index).trim(); + buffer = buffer.slice(index + 1); + if (line) this.handleLine(line, handlers, stream); + index = buffer.indexOf('\n'); + } + }, + onStderr: (chunk) => { + for (const line of chunk.split(/\r?\n/)) { + if (line.trim()) handlers.onLog(line.trim()); + } + }, + onClose: (code) => resolve(code ?? -1), + }); + }); + } + + /** + * @param {string} line + * @param {{ onLog: (line: string) => void, onEvent?: (event: Record) => void }} handlers + * @param {boolean} stream + */ + handleLine(line, handlers, stream) { + if (!stream) { + handlers.onLog(line); + return; + } + /** @type {unknown} */ + let parsed; + try { + parsed = JSON.parse(line); + } catch { + handlers.onLog(line); + return; + } + if (parsed && typeof parsed === 'object' && typeof (/** @type {any} */ (parsed).type) === 'string') { + handlers.onEvent?.(/** @type {Record} */ (parsed)); + return; + } + handlers.onLog(line); + } + + /** @returns {Promise>} */ + async loadConversation() { + try { + const raw = await readFile(this.stateFile, 'utf8'); + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === 'object' && Array.isArray(/** @type {any} */ (parsed).turns)) { + return parsed; + } + } catch { + /* no conversation yet */ + } + return { id: 'current', cwd: '', sessionId: '', turns: [], updatedAt: 0 }; + } + + /** + * @param {Record} conversation + * @returns {Promise} + */ + async saveConversation(conversation) { + await mkdir(this.context.dataDir, { recursive: true }); + const temporary = `${this.stateFile}.${process.pid}.tmp`; + await writeFile(temporary, JSON.stringify(conversation), 'utf8'); + await rename(temporary, this.stateFile); + } +} diff --git a/plugins/jeisux92/minimax-in-wsl/miniapp/node/miniapp-api.ts b/plugins/jeisux92/minimax-in-wsl/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..1b68a48d --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/miniapp/node/miniapp-api.ts @@ -0,0 +1,686 @@ +/** + * 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 manifest did not declare the required grant; not dispatched. */ + | 'NOT_PERMITTED' + /** The user switched this provider off for the Mini App; not dispatched. */ + | 'PERMISSION_DENIED' + | 'CONNECTOR_OUTCOME_UNKNOWN'; + +export interface HostConnectorError extends Error { + readonly code: HostConnectorErrorCode; + readonly disposition: HostConnectorErrorDisposition; + readonly retryable: boolean; + readonly invocationId?: string; + readonly diagnostic?: { + readonly issues: readonly { + readonly path: string; + readonly constraint: string; + readonly limit?: number; + }[]; + }; +} + +/** What a call would meet now under the user's global permission rules; informational only. */ +export type MiniAppToolPermission = 'allow' | 'ask' | 'deny'; + +/** + * `name` is the runtime name an Agent sees (`mcp____`, `connector____`). + * Take it from `list()`; do not build it. + */ +export type MiniAppTool = + | { + readonly name: string; + readonly kind: 'connector'; + readonly provider: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + } + | { + readonly name: string; + readonly kind: 'mcp'; + /** Any installed MCP server: a Plugin's, the user's `mcp.json`, or a Host built-in one. */ + readonly server: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + }; + +export interface MiniAppToolListResult { + readonly tools: readonly MiniAppTool[]; + /** A source could not be listed; the listed tools are still callable. */ + readonly partial: boolean; +} + +export type MiniAppToolCallResult = + | { + readonly invocationId: string; + readonly kind: 'connector'; + /** Raw provider result, as in `HostConnectorCallResult.value`. */ + readonly value: JsonValue; + } + | { + readonly invocationId: string; + readonly kind: 'mcp'; + /** The MCP tool reported its own failure; `content` keeps its error text. */ + readonly isError: boolean; + /** MCP content blocks such as `{ type: 'text', text }`, passed through as JSON. */ + readonly content: readonly JsonValue[]; + readonly structuredContent?: JsonObject; + }; + +/** + * Thrown with the `HostConnectorError` shape; Connector tools keep their Connector codes too. The + * code names the cause; `disposition` alone says whether the tool may have run (`TOOL_TIMEOUT` and + * `REQUEST_CANCELLED` can be either `not_dispatched` or `unknown_after_dispatch`). + */ +export type MiniAppToolErrorCode = + | HostConnectorErrorCode + | 'INVALID_ARGUMENTS' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Always present. Without `permissions.tool: ["call"]` (or the older `"toolAccess": ["call"]`), + * every method rejects `NOT_PERMITTED`. With `tool:call` switched off, `call()` rejects + * `PERMISSION_DENIED` while `list()` and `request()` resolve with `deny` for each tool. Every `call` + * is judged by the user's global rules: `deny` is `PERMISSION_DENIED`, `ask` shows a Host prompt, and nobody to + * ask is `TOOL_APPROVAL_REQUIRED`. `list` works before activation; call `call` only from request + * handling after activation. Connector tools time out after 30 s and MCP tools after at most 120 s, + * counted after any prompt. The Host never retries; reconcile an `unknown_after_dispatch` outcome + * before repeating a write. + */ +export interface MiniAppToolClient { + list(options?: HostConnectorCallOptions): Promise; + call( + name: string, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; + /** + * One Host prompt for the named tools (1–10, from `list()`) still at `ask`; the user ticks which + * to always allow. Resolves every name's state afterwards (for your UI only). When nobody can be + * asked it rejects with `TOOL_APPROVAL_REQUIRED` whose error carries `permissions`. With + * `tool:call` switched off it answers `deny` for every name without a prompt. + * Needs `capabilities.has('tool.request')`. + */ + request( + names: readonly string[], + options?: HostConnectorCallOptions, + ): Promise>; +} + +export interface MiniAppLogger { + debug(message: string, fields?: JsonObject): void; + info(message: string, fields?: JsonObject): void; + warn(message: string, fields?: JsonObject): void; + error(message: string, fields?: JsonObject): void; +} + +/** + * How the call's text ended: in its own turn (`finished` / `error` / `aborted`), or, only with + * `whenBusy`, joined into the turn that was already running (`steered`; that turn's own + * call gets the reply). + */ +export type MiniAppAgentRunStatus = 'finished' | 'error' | 'aborted' | 'steered'; + +/** + * The Desktop composer's follow-up behaviours while a session runs a turn. `queue`: the text runs + * as the next turn and the call follows it. `steer`: the running turn reads the text at its next + * input point (the call resolves `steered`), or, if it answered first, the text runs as the next + * turn and the call follows it. + */ +export type MiniAppAgentWhenBusy = 'queue' | 'steer'; + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: JsonObject; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a Node-created session starts with. */ + readonly default: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** `aborted` only when the Host confirmed the abort; an unconfirmed one rejects with `AGENT_OUTCOME_UNKNOWN`. */ + readonly status: MiniAppAgentRunStatus; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + */ +/** + * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even + * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the + * session's single-run slot while `question.requested` is delivered, so call `answer` only after + * that `run` resolves (an earlier call rejects with `BUSY`). Ignore event types you do not know. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + /** A tool call is waiting for approval; decide it with `agent.reply`. */ + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + /** The turn paused on a questionnaire; continue with `agent.answer`. */ + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: Exclude; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunOptions { + readonly signal?: AbortSignal; + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +export type MiniAppAgentErrorCode = + | 'NOT_PERMITTED' + | 'PERMISSION_DENIED' + | 'BUSY' + | 'SESSION_NOT_FOUND' + | 'INVALID_ARGUMENTS' + | 'AGENT_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'AGENT_OUTCOME_UNKNOWN' + | 'REQUEST_NOT_FOUND'; + +export interface MiniAppAgentError extends Error { + readonly code: MiniAppAgentErrorCode; + /** + * True when nothing was started and the same call may be retried later. + * `AGENT_OUTCOME_UNKNOWN` is never retryable: the turn may have run. + */ + readonly retryable: boolean; + /** + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. + */ + readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; +} + +/** + * Always present. `run` / `reply` / `answer` / `models` / `list` / `create` need + * `permissions.agent: ["run"]`. The deprecated `observe` / `sessions` / `session` are the + * `context.session` methods and follow its rule (see agent-interaction.md). + * A new Node session uses the primary Agent unless `agent` names one from `list()`, and works in + * this Mini App's own Agent directory and on the runtime default model; + * continuing a session keeps its Agent, directory and model (unless `model` switches it), including + * one a page created using its host chat's Agent, project directory and model; a session never + * changes its Agent. Runs one turn with that Agent's full capabilities + * (files, shell, Skills, MCP including this Mini App's own), and resolves when the turn ends. + * + * Interaction is yours to render: pass `onEvent` and handle `permission.requested` with + * `reply` and `question.requested` with `answer`. A permission request waits only while + * someone can answer it: this run passed `onEvent`, or a page of this Mini App currently has + * the session open in a chat side panel via `open`. Otherwise it is denied (the model is told + * why), and a questionnaire ends the turn with `result.pendingQuestion`. A run waiting on a + * permission is released by `cancel`/abort, process exit or republish. Up to `agentConcurrency` + * runs (default 4) per Mini App run at once; further `run` / `answer` calls wait in order (up to + * four times that many, see `run.queued`), and aborting a waiting call rejects it with + * `REQUEST_CANCELLED`. A `whenBusy` call on a session that already has a call in flight shares + * that call's slot. Cancelling a queued `whenBusy` text removes it (`REQUEST_CANCELLED`); a steered + * text cannot be withdrawn (`AGENT_OUTCOME_UNKNOWN`, the running turn goes on). + */ +export interface MiniAppAgentClient { + run( + input: { + readonly text: string; + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a + * new session's model: it must be one `models()` lists; unusable is `INVALID_ARGUMENTS`, + * missing BYOK credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `list()`. Passing it + * with `sessionId` is `INVALID_ARGUMENTS`. + */ + readonly agent?: string; + /** + * Only with `sessionId`: what to do when that session is already running a turn; on an idle + * session the call starts a turn as usual. Omit to reject with `BUSY` (`session_busy`). + */ + readonly whenBusy?: MiniAppAgentWhenBusy; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Decide a pending permission request. Never writes the user's global rules. Node replies + * have 16 separate pending slots; `run` / `answer` / `models` / `list` / `create` and Connector + * requests share another 16. Filling that ordinary budget still permits replies. A full reply + * budget rejects with retryable `AGENT_UNAVAILABLE`. + */ + reply(input: { + readonly sessionId: string; + readonly requestId: string; + readonly decision: 'allowOnce' | 'deny'; + }): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `AGENT_OUTCOME_UNKNOWN` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: { + readonly sessionId: string; + readonly requestId: string; + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `run`'s `model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Returns the model catalog and runtime `default`. Pass `default` directly as `model` to + * `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, add a selected `variant` + * if needed and preserve `variant: ''`. If thinking is supported, select an effort from + * `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + list(): Promise; + /** @deprecated Use `list()`; the Host warns once and removes this name in a later version. */ + agents(): Promise; + /** + * Create a session (agent, this Mini App's Agent directory, the runtime default model) without + * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's + * `create` binds the session to its chat instead, and its `sessionId` can be continued here. + * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's + * agent from `list()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** @deprecated Use `context.session.observe`; the Host warns once and removes this name in a later version. */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** @deprecated Use `context.session.list`; the Host warns once and removes this name in a later version. */ + sessions(): Promise; + /** @deprecated Use `context.session.get`; the Host warns once and removes this name in a later version. */ + session(sessionId: string): Promise; +} + +/** + * Always present. Read-only access to the user's conversations (the Desktop chat list). + * Every method needs `permissions.session: ["read"]`, except that this Mini App's own sessions (those + * `agent.create` / `agent.run` made) are readable under `permissions.agent: ["run"]` alone; while the + * user has `read` switched off, calls on other sessions fail with `PERMISSION_DENIED` and running + * observers end. Check `context.capabilities?.has('session.list')` on Hosts that may predate it. + * Neither grant implies the other; `observe({ all: true })` always needs `permissions.session: ["read"]`. + */ +export interface MiniAppSessionClient { + /** The user's visible root conversations, most recently updated first (at most 50). */ + list(): Promise; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session.get()`). + */ + get(sessionId: string): Promise; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort + * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription + * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, + * or `read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `PERMISSION_DENIED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots + * and no ordinary request budget. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; +} + +export interface MiniAppLifecycle { + dispose(): void | Promise; +} + +export interface MiniAppContext { + readonly pluginId: string; + readonly pluginRoot: string; + readonly dataDir: string; + readonly listen: Readonly<{ readonly host: '127.0.0.1'; readonly port: number }>; + readonly signal: AbortSignal; + readonly logger: MiniAppLogger; + /** + * Synchronous probe of the methods this Host offers **on the Node side**, named by API path + * (`agent.run`, `agent.list`, `session.list`, `session.get`, `session.observe`, + * `connector.call`, `connector.list`, `tool.call`, `tool.list`, `tool.request`). A + * page-only method is false here. A few Host-wide names remain until the deprecated aliases go: + * `agent.agents`, `agent.observe`, `agent.sessions`, `agent.session`, `hostConnector`, `tool`. + * The `hostConnector*` probe names stay beside `connector.*` until the alias goes. + * It says nothing about this Mini App's manifest or authorization: `has('agent.run')` is true + * even when the manifest does not grant it. Older Hosts do not + * inject `capabilities`; check `context.capabilities?.has(...)`. `has('session.list')` tells a + * `context.session` Host from one that only has the deprecated `context.agent.sessions` names. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Always present. Without `permissions.connector` (or the older `hostConnectorAccess`), every + * method rejects `NOT_PERMITTED`. A provider the user switched off is missing from `list()` + * and its calls reject with `PERMISSION_DENIED`. + */ + readonly connector: HostConnectorClient; + /** + * @deprecated `connector`. Always present. Forwards to the same client and warns once on the first method call + * (`MINIAPP-DEP-007`); it is not the same object reference, so do not compare the two or use + * both as map keys. + */ + readonly hostConnector: HostConnectorClient; + /** Always present. Calls installed MCP and Connector tools under the user's permission rules. */ + readonly tool: MiniAppToolClient; + /** + * Always present, as on the page. Its methods need `permissions.agent: ["run"]`; they reject + * with `NOT_PERMITTED` if the manifest does not declare it and `PERMISSION_DENIED` if the user + * switched it off. Session aliases follow `context.session`'s rules. + */ + readonly agent: MiniAppAgentClient; + /** + * Always present, as on the page. Reading conversations other than this Mini App's own needs + * `permissions.session: ["read"]`. Own sessions can also use `permissions.agent: ["run"]`. + */ + readonly session: MiniAppSessionClient; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +export interface MiniAppModule { + /** Resolve only after the listener accepts connections and every route is installed. */ + start(context: MiniAppContext): Promise; +} diff --git a/plugins/jeisux92/minimax-in-wsl/miniapp/node/server.mjs b/plugins/jeisux92/minimax-in-wsl/miniapp/node/server.mjs new file mode 100644 index 00000000..610fc105 --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/miniapp/node/server.mjs @@ -0,0 +1,384 @@ +// @ts-check + +/** + * Mini App Node entry. + * + * The service owns every WSL interaction: status, workspace discovery, the + * installer, the sign-in flow, and the agent runs themselves. The page only + * talks to these narrow business routes; it never chooses a program or a + * command line. + */ + +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { WslRunner } from './wsl.mjs'; +import { MCodeService } from './mcode.mjs'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +const CLIENT_FILES = { + '/chat': 'index.html', + '/chat/': 'index.html', + '/chat/app.js': 'app.js', + '/chat/styles.css': 'styles.css', +}; + +const CONTENT_TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', +}; + +const MAX_BODY_BYTES = 512 * 1024; + +/** + * @param {import('node:http').ServerResponse} response + * @param {string} event + * @param {unknown} data + */ +function sendEvent(response, event, data) { + response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); +} + +/** + * @param {import('node:http').IncomingMessage} request + * @returns {Promise>} + */ +async function readJsonBody(request) { + /** @type {Buffer[]} */ + const chunks = []; + let size = 0; + for await (const chunk of request) { + size += chunk.length; + if (size > MAX_BODY_BYTES) throw new Error('The request payload is too large.'); + chunks.push(chunk); + } + const text = Buffer.concat(chunks).toString('utf8'); + if (!text.trim()) return {}; + const parsed = JSON.parse(text); + if (!parsed || typeof parsed !== 'object') throw new Error('The request payload is not valid.'); + return parsed; +} + +/** + * Keep the stored transcript compact by merging consecutive text deltas of the + * same item. The final `item.completed` event always carries the full text. + * + * @param {any[]} events + * @param {Record} event + */ +function recordEvent(events, event) { + const last = events[events.length - 1]; + if ( + event.type === 'item.updated' && + last && + last.type === 'item.updated' && + last.item && + event.item && + last.item.id === event.item.id && + typeof last.item.contentDelta === 'string' && + typeof event.item.contentDelta === 'string' + ) { + last.item.contentDelta = last.item.contentDelta + event.item.contentDelta; + return; + } + events.push(event); + if (events.length > 4000) events.splice(0, events.length - 4000); +} + +export async function start(context) { + const runner = new WslRunner(context); + const service = new MCodeService(context, runner); + + /** @type {Map} */ + const activeRuns = new Map(); + + /** @type {string[]} */ + let distroCache = []; + let distroCacheAt = 0; + + const listDistros = async () => { + const now = Date.now(); + if (distroCache.length > 0 && now - distroCacheAt < 60_000) return distroCache; + try { + distroCache = await runner.listDistros(); + } catch { + distroCache = []; + } + distroCacheAt = now; + return distroCache; + }; + + /** + * @param {unknown} requested + * @returns {Promise} + */ + const resolveDistro = async (requested) => { + const distros = await listDistros(); + if (typeof requested === 'string' && distros.includes(requested)) return requested; + const preferred = distros.find((name) => !name.toLowerCase().includes('docker')); + return preferred ?? distros[0] ?? 'Ubuntu'; + }; + + const server = createServer((request, response) => { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const path = url.pathname; + + void (async () => { + try { + if (request.method === 'GET' && CLIENT_FILES[path]) { + const file = CLIENT_FILES[path]; + const body = await readFile(join(context.pluginRoot, 'miniapp/client', file)); + const extension = file.slice(file.lastIndexOf('.')); + const type = CONTENT_TYPES[/** @type {keyof typeof CONTENT_TYPES} */ (extension)] ?? 'text/plain; charset=utf-8'; + response.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }); + response.end(body); + return; + } + + if (request.method === 'GET' && path === '/api/status') { + const distro = await resolveDistro(url.searchParams.get('distro')); + const [status, distros] = await Promise.all([service.getStatus(distro), listDistros()]); + response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ ...status, distros })); + return; + } + + if (request.method === 'GET' && path === '/api/workspaces') { + const distro = await resolveDistro(url.searchParams.get('distro')); + const workspaces = await service.listWorkspaces(distro); + response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify(workspaces)); + return; + } + + if (request.method === 'GET' && path === '/api/conversation') { + const conversation = await service.loadConversation(); + response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify(conversation)); + return; + } + + if (request.method === 'POST' && path === '/api/conversation/reset') { + const conversation = { id: 'current', cwd: '', sessionId: '', turns: [], updatedAt: Date.now() }; + await service.saveConversation(conversation); + response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ ok: true })); + return; + } + + if (request.method === 'POST' && path === '/api/cancel') { + const body = await readJsonBody(request); + const distro = await resolveDistro(body.distro); + const token = typeof body.token === 'string' ? body.token : ''; + if (token) { + const run = activeRuns.get(token); + if (run) run.cancelled = true; + runner.cancel(distro, token); + runner.closeLocal(token); + } + response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ ok: true })); + return; + } + + if (request.method === 'POST' && path === '/api/install') { + const body = await readJsonBody(request); + const distro = await resolveDistro(body.distro); + const token = service.newToken(); + response.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + sendEvent(response, 'log', { line: 'Starting the MiniMax Code CLI installer in WSL...' }); + const code = await service.install(distro, token, { + onLog: (line) => sendEvent(response, 'log', { line }), + }); + sendEvent(response, 'end', { code }); + response.end(); + return; + } + + if (request.method === 'POST' && path === '/api/login') { + const body = await readJsonBody(request); + const distro = await resolveDistro(body.distro); + const region = body.region === 'cn' ? 'cn' : 'global'; + const token = service.newToken(); + response.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + const code = await service.login(distro, token, region, { + onLog: (line) => { + const url = line.match(/https:\/\/\S+/); + const userCode = line.match(/Code:\s*(\S+)/); + sendEvent(response, 'log', { + line, + authorizationUrl: url ? url[0] : undefined, + userCode: userCode ? userCode[1] : undefined, + }); + }, + }); + sendEvent(response, 'end', { code }); + response.end(); + return; + } + + if (request.method === 'POST' && path === '/api/run') { + const body = await readJsonBody(request); + const distro = await resolveDistro(body.distro); + const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : ''; + if (!prompt) { + response.writeHead(400, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ error: 'The prompt is empty.' })); + return; + } + const cwd = typeof body.cwd === 'string' ? body.cwd : ''; + const permission = ['smart', 'full', 'off'].includes(body.permission) ? body.permission : 'smart'; + const model = typeof body.model === 'string' ? body.model : ''; + const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''; + + const conversation = await service.loadConversation(); + const turn = { + id: service.newToken(), + prompt, + cwd, + permission, + model, + startedAt: Date.now(), + endedAt: 0, + status: 'running', + events: [], + sessionId, + usage: null, + modelUsed: '', + }; + + response.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + sendEvent(response, 'turn', { turn: { ...turn, events: [] } }); + + const runState = { cancelled: false }; + activeRuns.set(turn.id, runState); + + let clientGone = false; + request.on('close', () => { + clientGone = true; + }); + + const code = await service.runExec( + { distro, prompt, cwd, permission, sessionId, model, token: turn.id }, + { + onEvent: (event) => { + recordEvent(turn.events, event); + if (event.type === 'session.started' || event.type === 'session.resumed') { + if (typeof event.sessionId === 'string') turn.sessionId = event.sessionId; + } + if (event.type === 'turn.completed') { + if (event.usage) turn.usage = event.usage; + if (event.model) turn.modelUsed = String(event.model.modelId ?? ''); + } + if (event.type === 'exec.completed') { + const result = event.result; + if (result && typeof result === 'object') { + turn.status = String(result.status ?? 'succeeded'); + if (typeof result.sessionId === 'string') turn.sessionId = result.sessionId; + if (result.usage) turn.usage = result.usage; + } + } + if (event.type === 'turn.failed') { + turn.status = String(event.status ?? 'failed'); + if (event.error && typeof event.error === 'object') { + turn.error = String(event.error.message ?? 'The turn failed.'); + } + } + if (!clientGone) sendEvent(response, 'mcode', { event }); + }, + onLog: (line) => { + if (!clientGone) sendEvent(response, 'log', { line }); + }, + }, + ); + + turn.endedAt = Date.now(); + activeRuns.delete(turn.id); + if (runState.cancelled) { + turn.status = 'cancelled'; + turn.error = 'The run was cancelled.'; + } else if (turn.status === 'running') { + turn.status = code === 0 ? 'succeeded' : code === 130 ? 'cancelled' : 'failed'; + if (code !== 0 && !turn.error) { + turn.error = + code === 130 + ? 'The run was cancelled.' + : `The MiniMax Code CLI exited with code ${code}.`; + } + } + if (turn.error && turn.status === 'succeeded') turn.status = 'failed'; + + conversation.turns = [...(conversation.turns ?? []), turn]; + conversation.sessionId = turn.sessionId || conversation.sessionId; + conversation.cwd = cwd || conversation.cwd; + conversation.updatedAt = Date.now(); + await service.saveConversation(conversation); + + if (!clientGone) { + sendEvent(response, 'turn', { turn }); + sendEvent(response, 'end', { status: turn.status, sessionId: turn.sessionId }); + } + response.end(); + return; + } + + response.writeHead(404, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ error: 'not_found' })); + } catch (error) { + const message = error instanceof Error ? error.message : 'Unexpected server error.'; + context.logger.error('miniapp.request.failed', { message }); + if (!response.headersSent) { + response.writeHead(500, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ error: message })); + } else { + try { + sendEvent(response, 'error', { message }); + } catch { + /* the client is gone */ + } + response.end(); + } + } + })(); + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(context.listen.port, context.listen.host, () => { + server.off('error', reject); + resolve(undefined); + }); + }); + context.logger.info('miniapp.runtime.listening'); + + let disposed = false; + const dispose = async () => { + if (disposed) return; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + await new Promise((resolve) => server.close(() => resolve(undefined))); + await runner.dispose(); + }; + const onAbort = () => { + void dispose(); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} diff --git a/plugins/jeisux92/minimax-in-wsl/miniapp/node/wsl.mjs b/plugins/jeisux92/minimax-in-wsl/miniapp/node/wsl.mjs new file mode 100644 index 00000000..83717765 --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/miniapp/node/wsl.mjs @@ -0,0 +1,204 @@ +// @ts-check + +/** + * WSL process plumbing. + * + * Every script is delivered to `bash -s` over stdin, so script content is never + * quoted by a Windows command line and never re-parsed by an intermediate shell. + * User supplied text (prompts, working directories) travels base64 encoded and is + * decoded inside the distro. + */ + +import { spawn } from 'node:child_process'; + +const WSL_EXE = 'wsl.exe'; + +/** + * wsl.exe frequently writes UTF-16LE, so detect and decode it. + * @param {Buffer} buffer + * @returns {string} + */ +export function decodeWslOutput(buffer) { + if (buffer.length >= 2 && buffer.includes(0)) { + return buffer.toString('utf16le').replace(/\0/g, ''); + } + return buffer.toString('utf8'); +} + +/** + * @param {unknown} value + * @returns {string} + */ +export function toBase64(value) { + return Buffer.from(String(value), 'utf8').toString('base64'); +} + +/** + * @param {string} command + * @returns {string} + */ +export function decodeBase64(command) { + return Buffer.from(command, 'base64').toString('utf8'); +} + +export class WslRunner { + /** @param {{ logger: { info: Function, warn: Function, error: Function } }} context */ + constructor(context) { + this.context = context; + /** @type {Set} */ + this.children = new Set(); + /** @type {Map} */ + this.tagged = new Map(); + } + + /** + * @returns {Promise} + */ + listDistros() { + return new Promise((resolve, reject) => { + const child = spawn(WSL_EXE, ['-l', '-q'], { windowsHide: true }); + /** @type {Buffer[]} */ + const chunks = []; + child.stdout.on('data', (chunk) => chunks.push(chunk)); + child.stderr.on('data', () => {}); + child.on('error', reject); + child.on('close', (code) => { + if (code !== 0) { + reject(new Error(`wsl.exe -l -q exited with code ${code}`)); + return; + } + const text = decodeWslOutput(Buffer.concat(chunks)); + const names = text + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line.length > 0); + resolve([...new Set(names)]); + }); + }); + } + + /** + * Run a script inside a distro. + * + * @param {string} distro + * @param {string} script Script body, delivered on stdin. + * @param {{ + * args?: string[], + * tag?: string, + * onStdout?: (chunk: string) => void, + * onStderr?: (chunk: string) => void, + * onClose?: (code: number | null, signal: NodeJS.Signals | null) => void, + * timeoutMs?: number, + * }} [options] + */ + runScript(distro, script, options = {}) { + const { args = [], tag = '', onStdout, onStderr, onClose, timeoutMs = 0 } = options; + + const child = spawn(WSL_EXE, ['-d', distro, '--', 'bash', '-s', '--', ...args], { + windowsHide: true, + stdio: ['pipe', 'pipe', 'pipe'], + }); + this.children.add(child); + if (tag) this.tagged.set(tag, child); + + /** @type {NodeJS.Timeout | undefined} */ + let timer; + if (timeoutMs > 0) { + timer = setTimeout(() => { + try { + child.kill('SIGKILL'); + } catch { + /* the child may already be gone */ + } + }, timeoutMs); + timer.unref?.(); + } + + const settle = (code, signal) => { + if (timer) clearTimeout(timer); + this.children.delete(child); + if (tag && this.tagged.get(tag) === child) this.tagged.delete(tag); + onClose?.(code, signal); + }; + + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + child.stdout.on('data', (chunk) => onStdout?.(String(chunk))); + child.stderr.on('data', (chunk) => onStderr?.(String(chunk))); + child.on('error', (error) => { + this.context.logger.error('wsl.spawn.failed', { message: error.message }); + settle(null, null); + }); + child.on('close', (code, signal) => settle(code, signal)); + + child.stdin.on('error', () => { + /* the distro may close stdin early; the close handler reports the real result */ + }); + child.stdin.end(script, 'utf8'); + + return child; + } + + /** + * Kill a running script and the CLI process it started inside the distro. + * + * The CLI runs in its own process group, so the group is signalled first and + * the process itself second. Without this, a tool the CLI started would keep + * the output pipe open and the run would never settle. + * + * @param {string} distro + * @param {string} token + */ + cancel(distro, token) { + const safeToken = String(token).replace(/[^A-Za-z0-9]/g, ''); + if (!safeToken) return; + const script = [ + 'for f in "/tmp/mcode-run-$1.pid" "/tmp/mcode-login-$1.pid" "/tmp/mcode-install-$1.pid"; do', + ' if [ -f "$f" ]; then', + ' p="$(cat "$f" 2>/dev/null)"', + ' case "$p" in', + " ''|*[!0-9]*) ;;", + ' *)', + ' pkill -TERM -P "$p" 2>/dev/null', + ' kill -TERM -"$p" 2>/dev/null', + ' kill -TERM "$p" 2>/dev/null', + ' ;;', + ' esac', + ' rm -f "$f"', + ' fi', + 'done', + 'exit 0', + ].join('\n'); + this.runScript(distro, script, { args: [safeToken] }); + } + + /** + * Close the Windows side of a run so its output pipe cannot keep the request + * open. The distro side is stopped by {@link cancel}. + * + * @param {string} token + */ + closeLocal(token) { + const child = this.tagged.get(token); + if (!child) return; + try { + child.kill('SIGKILL'); + } catch { + /* already gone */ + } + } + + /** + * @returns {Promise} + */ + async dispose() { + for (const child of this.children) { + try { + child.kill('SIGKILL'); + } catch { + /* already gone */ + } + } + this.children.clear(); + } +} diff --git a/plugins/jeisux92/minimax-in-wsl/package.json b/plugins/jeisux92/minimax-in-wsl/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/jeisux92/minimax-in-wsl/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +}