agent-console 1.0.0: a page plugin that drives the local Agent CLIs (#535)
Adds Agent Console (@magpie-community/page-agent-console 1.0.0), a community page plugin that drives the Agent CLIs on this computer (Claude Code, Codex, ACP agents) through a local daemon on 127.0.0.1, with its source in packages/agent-console and a registry entry. Claude Code is the user's own `claude` CLI driven over stream-json (daemon/src/providers/claude/cli.ts); no Anthropic SDK is installed, bundled or in the branch's history. Cold install ~45 MB (node-pty ~26 MB), stated in the README and registry summary in en and zh. By qingnian108 (#535). What was run at 8e8f910 (mote, macOS, throwaway HOME, no real accounts): - packages/agent-console: `npm ci --ignore-scripts --workspaces=false`; `node scripts/verify-build.mjs`: all five bundles byte-identical (daemon/dist/main.js 08c95aa3…, app/app.js 9a6911f3…); `vitest run`: 45 files, 254 passed, 17 skipped; `npm run check` clean. - Real Claude Code 2.1.316 (npm @anthropic-ai/claude-code, sandbox HOME/CLAUDE_CONFIG_DIR, local fake Messages API): `AC_REAL_CLAUDE=… vitest run --config vitest.real.config.ts test/real/claude-cli.real.test.ts`: 4 of 4 (initialize lists 51 slash commands, streaming turn, Bash permission approved and denied, interrupt, --resume with set_model). - Probe: the driver's exact argv with `--permission-mode bypassPermissions --allow-dangerously-skip-permissions`: the tool runs with no can_use_tool request. - Repo root: `HOME=$(mktemp -d) bun test`: 4006 tests, 0 fail; `bun scripts/check.mjs` exit 0. - Install as magpie does: `npm pack --ignore-scripts` (552 KB) then `bun add --ignore-scripts`: 45 MB node_modules, no @anthropic-ai/*, index.mjs imports. - Read every changed line since 41c7a94: argv values limited to SAFE_ARG tokens (no cmd.exe metacharacters reach the shim path), no new network hosts, no install scripts, no eval; no commit in main..8e8f910 contains claude-agent-sdk. Not tried: magpie's desktop window loading the page; a Windows .cmd/.ps1 claude shim end to end.
This commit is contained in:
@@ -120,6 +120,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi
|
|||||||
| [agent-office](packages/agent-office) | What are my agents doing: a real WebGL 3D office with six scenes, an isometric/2D office, grouped workbench, Today usage and recent conversations | no `magpie.read`; its host part reads local session files of Claude Code, Codex, Copilot CLI, Kimi Code, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) |
|
| [agent-office](packages/agent-office) | What are my agents doing: a real WebGL 3D office with six scenes, an isometric/2D office, grouped workbench, Today usage and recent conversations | no `magpie.read`; its host part reads local session files of Claude Code, Codex, Copilot CLI, Kimi Code, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) |
|
||||||
| [fingerprint](packages/fingerprint) | Numeric response fingerprints to investigate suspected model substitution across providers, with shared challenges, candidate rankings, local evidence and JSON export | none (its local service calls magpie’s gateway; sampling uses provider quota) |
|
| [fingerprint](packages/fingerprint) | Numeric response fingerprints to investigate suspected model substitution across providers, with shared challenges, candidate rankings, local evidence and JSON export | none (its local service calls magpie’s gateway; sampling uses provider quota) |
|
||||||
| [chat](packages/chat) | Chat with magpie's models, your MCP servers, instructions and skills, by Magic_zero ([Magiczerowxy](https://github.com/Magiczerowxy)). Has a host part: a local service the page goes to | none (its service calls magpie's gateway) |
|
| [chat](packages/chat) | Chat with magpie's models, your MCP servers, instructions and skills, by Magic_zero ([Magiczerowxy](https://github.com/Magiczerowxy)). Has a host part: a local service the page goes to | none (its service calls magpie's gateway) |
|
||||||
|
| [agent-console](packages/agent-console) | Drive the Agent CLIs on this computer (Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh) with a timeline, Git changes, files and a terminal, by [qingnian108](https://github.com/qingnian108). Has a host part: a gate and a daemon on 127.0.0.1, started when the page opens | none (its daemon runs the Agent CLIs you pick, in the projects you open) |
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
magpie plugin add @magpie-community/page-<name>
|
magpie plugin add @magpie-community/page-<name>
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
[test]
|
||||||
|
# packages/agent-console has its own vitest suite with npm dependencies (npm ci
|
||||||
|
# in that folder, then npm test); the root `bun test` doesn't install them
|
||||||
|
pathIgnorePatterns = ["packages/agent-console/test/**", "packages/agent-console/web/**"]
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
*.ts text eol=lf
|
||||||
|
*.tsx text eol=lf
|
||||||
|
*.mjs text eol=lf
|
||||||
|
*.js text eol=lf
|
||||||
|
*.css text eol=lf
|
||||||
|
*.html text eol=lf
|
||||||
|
*.json text eol=lf
|
||||||
|
*.md text eol=lf
|
||||||
|
app/** -text
|
||||||
|
daemon/dist/** -text
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
_tmp/
|
||||||
|
node_modules/
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
page/session.js
|
||||||
|
*.tgz
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 qingnian108
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
# Agent Console
|
||||||
|
|
||||||
|
A Magpie page plugin that drives real local Agent CLIs (Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh). Each conversation is a **persistent Agent session** on a standalone Node daemon. Close or refresh the page — the Agent keeps running while Magpie is open. Reopen the page and you pick up where you left off. When Magpie quits, the daemon and its Agents stop; threads are persisted and can be resumed next time.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Requires [Magpie](https://usemagpie.ai) ≥ 0.1.1340 and Node.js ≥ 20.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
magpie plugin add @magpie-community/page-agent-console
|
||||||
|
```
|
||||||
|
|
||||||
|
Or in Magpie: **Settings → Plugins → Add plugin**, enter `@magpie-community/page-agent-console` (or find **Agent Console** in Discover). After install, **Agent Console** appears in the sidebar plugin group.
|
||||||
|
|
||||||
|
Install the Agent CLIs you want to use (for example `claude` or `codex`). Missing CLIs show an install hint in Settings.
|
||||||
|
|
||||||
|
A cold install is about **46 MB** of `node_modules`, mostly `node-pty`'s native terminal module (~26 MB). Claude Code is **not** bundled: to use the Claude Code Agent, install the `claude` CLI yourself (`npm i -g @anthropic-ai/claude-code` or Anthropic's native installer). / 冷安装约占 **46 MB** 的 `node_modules`,主要是 `node-pty` 原生终端模块(约 26 MB)。插件**不**附带 Claude Code:要用 Claude Code Agent,请自行安装 `claude` CLI(`npm i -g @anthropic-ai/claude-code` 或 Anthropic 的原生安装器)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
This is not a gateway chat box. The daemon talks to the real CLIs through `claude -p --input-format stream-json --output-format stream-json` (the user's own `claude`, with its control messages for permissions, interrupt, model and mode), `codex app-server`, and ACP, normalizes a structured event stream (tool calls, thinking, permission requests, usage), and pushes it to the React page over WebSocket.
|
||||||
|
|
||||||
|
UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar (projects × threads), conversation timeline, and a right panel (changes / files / terminal).
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Persistent sessions**: each thread binds to a long-lived Agent process; after a daemon restart, running threads are marked closed and can be resumed (`--resume` / `thread/resume`)
|
||||||
|
- **Multiple Agents**: Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh; missing CLIs show an install hint
|
||||||
|
- **Model / permission / thinking**: per-thread; four permission modes and five thinking levels (what each Agent actually supports)
|
||||||
|
- **Structured timeline**: user message → thinking (expandable) → tool calls (read / edit / command, with line-level diffs) → todos → usage and duration; answer permission requests (tools / plan / questions) on the card
|
||||||
|
- **Steer and queue**: steer while running, queue the next message, interrupt
|
||||||
|
- **Changes panel**: git status refresh every 3s, unified per-file diffs; discarded untracked files go to trash instead of a hard delete
|
||||||
|
- **Files panel**: lazy directory tree (respects `.gitignore`), syntax-highlighted preview
|
||||||
|
- **Terminal panel**: real PTY via node-pty (pwsh / powershell); reconnects after reopening the page; degrades if PTY is unavailable
|
||||||
|
- **Images**: attach or paste images (and text files). Only PNG, JPEG, GIF and WebP are sent as images. Claude Code and Codex take them natively; Claude Code gets a text file (up to 1 MB) as a plain-text document, Codex gets its path; any other file (SVG, binaries, images over Claude's 5 MB limit) goes by path, with a notice. An ACP Agent (Cursor, Copilot, OpenCode, Pi, Devin CLI, dsh) gets image blocks when its ACP `initialize` advertises `promptCapabilities.image`; otherwise it gets each image's file path (as text and a `resource_link`), so it can open it with its file tools, and the timeline says it can't see the image itself. The composer says so before you send once the Agent has been asked. dsh answers `initialize` for the route its ACP starts on (its `acp` config row, which ships as a model dsh's catalog doesn't have) and refuses image blocks otherwise, so Agent Console starts dsh with a `--patch` overlay that puts that row on the conversation's model: on a model that sees images (Magpie writes those as `input: [text, image]`) dsh then takes image blocks; after a switch to another model in the same chat, images go by path and dsh opens them with its `read_image` tool. Checked on 2026-10-31 with the real CLIs, a throwaway HOME, no sign-in and a local stand-in for the model API (`npm run test:real`, see `test/real/`): the image reaches the model request from Claude Code 2.1.316 (stream-json), Codex 0.165.0, Copilot 1.0.105 (BYOK), OpenCode 1.19.5, Pi (pi-acp 0.0.34 + pi 1.4.0) and dsh 0.2.1-rc.5; Devin CLI 3000.11.234 and Cursor 2026.10.22 advertise images and Devin gets the image block, but both need a sign-in to run a model. Inline media is capped at 10 MB per file and 16 MB per message (an ACP SDK peer refuses messages over 32 MB); larger images go by path
|
||||||
|
- **Import history**: import matching sessions from `~/.claude/projects` and `~/.codex/sessions` as new threads (resumable)
|
||||||
|
- **Thread management**: search (Ctrl+K), pin, rename, archive, delete (trash), export Markdown, thread info (usage / cost / session ID)
|
||||||
|
- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 8 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit`) so UI work does not burn tokens
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
Magpie window
|
||||||
|
└─ page/index.html (sandbox="allow-scripts" iframe, served by Magpie from /_magpie/plugin/<per-run id>/)
|
||||||
|
│ reads page/session.js {port, key} (gate key only, written by the plugin host)
|
||||||
|
│ navigates itself to http://127.0.0.1:<port>/open?k=<key>&theme=…
|
||||||
|
▼
|
||||||
|
Magpie plugin host (Bun) ── index.mjs + lib/gate.mjs "gate" on 127.0.0.1:<port> (default 3488)
|
||||||
|
│ first /open: spawns the daemon as a child process (node, --port 0, stdin lifeline, --parent-pid)
|
||||||
|
│ 302 → http://127.0.0.1:<daemonPort>/?theme=…#t=<token>
|
||||||
|
▼
|
||||||
|
daemon (Node, daemon/dist/main.js) ── HTTP + WebSocket on an ephemeral 127.0.0.1 port
|
||||||
|
└─ React app (app/) reads the token from location.hash, sends it as the x-agent-console header
|
||||||
|
and in the WebSocket hello
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security model
|
||||||
|
|
||||||
|
The daemon can run Agents with full access to your machine, so the token that unlocks it must never be readable by another web page.
|
||||||
|
|
||||||
|
- **Two secrets per plugin-host run.** Each run generates two independent random 256-bit values: a **gate key** and the **daemon token**. Only the gate key is ever written to a file.
|
||||||
|
- **Why `session.js` holds only the gate key.** Magpie serves the page folder at `/_magpie/plugin/<per-run id>/`, where the id is an HMAC that changes every time Magpie starts and is handed out only to Magpie's own window. Magpie does not check `Origin`, `Host`, `Sec-Fetch-*` or a cookie on these files, and sends no `Cross-Origin-Resource-Policy`, so the unguessable path is their only protection. A classic `<script src>` include is not subject to CORS, so any page that learned the path (a different localhost port, a `file:` page, any website) could run `session.js` and read `globalThis.AgentConsoleSession`. That is why the file never contains the daemon token.
|
||||||
|
- **Token handoff.** After the gate binds its port, the host writes `{port, key}` to `page/session.js` (atomic write, mode 0600; git-ignored and excluded from the npm package). The page navigates to the gate's `/open?k=<key>`; the gate compares the key in constant time, starts or reuses the daemon and redirects to it with the daemon token **only in the URL fragment** (`#t=…`). The fragment is never sent to a server, written to a log, or leaked through `Referer`, and the window that ends up holding it belongs to the daemon's origin (an opaque origin inside Magpie's sandboxed frame), so the page that started the navigation cannot read it. A leaked gate key therefore lets another page at most open the console UI in a frame or tab it cannot read; it does not unlock the daemon's API or WebSocket. No HTML served by the daemon contains the token; an unauthenticated `GET /` returns a page with no secret in it.
|
||||||
|
- **`Origin: null` is not trusted.** Any site can produce `Origin: null` (sandboxed iframes, `data:` and `file:` pages). The token is the only authority:
|
||||||
|
- static routes (`/`, `app.js`, …) refuse `Origin: null` and foreign origins with 403 and never send CORS headers;
|
||||||
|
- token routes (`/api/*`, `/attachments/*`, WebSocket hello) accept `Origin: null` only as a way to *present* the token (the Magpie iframe has an opaque origin); `access-control-allow-origin: null` is emitted only on responses to requests that carried a valid token, plus the preflight for `/api/upload`; credentials are never allowed;
|
||||||
|
- any other origin gets 403 even with a valid token.
|
||||||
|
- **Host is checked on every request and WebSocket upgrade** (gate and daemon): it must be `127.0.0.1:<port>` or `localhost:<port>` with the actually bound port, otherwise 421. This blocks DNS rebinding, where the attacker's requests carry no `Origin` at all.
|
||||||
|
- The gate answers only `GET /open?k=<gate key>` (the daemon token is not accepted there), refuses any request that carries an `Origin` header, and sends `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`.
|
||||||
|
- WebSocket connections must send `hello` with the token within 5 seconds, otherwise they are closed with code 4401.
|
||||||
|
|
||||||
|
## Lifecycle
|
||||||
|
|
||||||
|
- Importing `index.mjs` has no side effects (no port, no process, no files).
|
||||||
|
- `server()` (called by Magpie's plugin host at host start-up — this includes short-lived hosts started by CLI commands such as `magpie plugin add` or `magpie plugin list`) binds the gate and writes `page/session.js`. If the port is busy it retries every 2 s in the background without blocking the host; a detached 0.1.0 daemon still holding the port is shut down once, only after it proves its identity by answering `/api/ping` with the token from `daemon.json`.
|
||||||
|
- The daemon starts when the page is opened for the first time and is reused for later opens. It is a normal (non-detached) child of the plugin host.
|
||||||
|
- The daemon exits when its stdin pipe closes or its parent pid disappears (checked every 2 s) — i.e. when Magpie quits or the plugin host restarts — and after 60 minutes idle.
|
||||||
|
- Magpie's plugin host treats the value returned by `server()` as OpenCode hooks and never calls `stop()`; it exits the Bun process when Magpie closes its stdin. A synchronous `exit` handler therefore closes the daemon's lifeline, signals it, and removes the `session.js` this host wrote. `stop()` (used by tests and other hosts) closes the gate, ends the daemon (graceful, then forced) and removes `session.js`.
|
||||||
|
- Agents stop with the daemon. Threads are persisted and can be resumed after reopening the page. On macOS/Linux every Agent CLI, the Codex app-server and the no-PTY shell run in their own process group, so stopping one ends everything it started; on Windows the same is done with `taskkill /T`. A process `exit` hook reaps any tree still alive when the daemon exits.
|
||||||
|
|
||||||
|
## Platforms
|
||||||
|
|
||||||
|
The plugin runs wherever Magpie runs (Windows, macOS, Linux). It needs **Node.js 20+** on `PATH`: Magpie's plugin host is Bun, but the daemon and `node-pty` need Node. If Node is missing, opening the page shows "Node.js was not found" (the gate's 503 page) instead of silently running under Bun; a too-old Node gives a similar message.
|
||||||
|
|
||||||
|
- **Finding Agent CLIs.** `PATH` is scanned in JavaScript (no `where.exe`/`which`; `where.exe` prints in the console code page, which garbled Chinese user names). The first hit in `PATH` order wins. Common install dirs are also searched because a GUI app may start with a minimal `PATH` (Magpie adds the login-shell `PATH` itself; this is a fallback): Homebrew (`/opt/homebrew/bin`, `/usr/local/bin`), `~/.local/bin`, npm global, Volta, Bun, `~/.claude/local`, `%APPDATA%\npm`.
|
||||||
|
- **Windows shims.** `.exe` runs directly; npm `.cmd` shims run their `cli.js` with Node; `.ps1`-only shims run with `powershell -NoProfile -ExecutionPolicy Bypass -File`; any other `.cmd`/`.bat` runs through `cmd.exe` with cross-spawn-style escaping (spaces, `&`, `%`, quotes and Chinese in paths and arguments are safe).
|
||||||
|
- **Terminal.** `node-pty` prebuilds cover win32/darwin/linux × x64/arm64 (Linux prebuilds are glibc only). Default shell: Windows `pwsh` → `powershell` → `cmd`; macOS/Linux `$SHELL` if it exists, else `zsh` (macOS) / `bash` / `sh`. If `node-pty` cannot load, a simple non-PTY terminal is used ([details](#when-node-pty-cant-be-loaded)). On macOS the exec bit of `node-pty`'s `spawn-helper` is restored if the package extraction dropped it.
|
||||||
|
- **Folder picker.** Windows: PowerShell `FolderBrowserDialog`; macOS: `osascript` "choose folder"; Linux: `zenity` or `kdialog` when a graphical session exists; otherwise type the path.
|
||||||
|
- **Paths.** Project paths are compared case-insensitively on Windows and macOS (and NFC-normalized on macOS); `realpath.native` resolves 8.3 short names and `subst` drives; UNC paths work. Discarding an untracked file moves it to the trash with a copy fallback when the project and data dir are on different drives.
|
||||||
|
- **Encoding.** Agent output is decoded as UTF-8; the folder picker falls back to GBK (CP936); the file preview tries UTF-8, then GBK. Git runs with `core.quotepath=false` so Chinese file names show as-is.
|
||||||
|
- **Magpie desktop window → `http://127.0.0.1`.** Magpie's window origin is `wails://` on macOS/Linux and `http://wails.localhost` on Windows. The plugin frame navigates itself to the gate on `http://127.0.0.1`, as Magpie's plugin-runtime docs describe for page plugins. On macOS, Magpie's `Info.plist` has no ATS keys and ATS exempts IP-address hosts by default, and the main window has no CSP that could block the frame, so the navigation is allowed. This is the one item that still needs a run on a real Mac.
|
||||||
|
- **Clickjacking / `frame-ancestors`.** Not set on purpose. The UI must load inside Magpie's frame on every mode: `wails://` (a non-special scheme whose origin WebKit may treat as opaque), `http://wails.localhost`, and `magpie web` on any address, LAN IP or reverse proxy. No `frame-ancestors` list covers all of them without breaking one. Framing the console also requires the gate key, which only Magpie's per-run page path hands out.
|
||||||
|
|
||||||
|
## Reproducible build
|
||||||
|
|
||||||
|
`app/app.js`, `app/app.css`, `app/index.html`, `daemon/dist/main.js` and `daemon/dist/main.js.map` are committed build outputs of `web/src` and `daemon/src` (esbuild, options in `scripts/build-v1.mjs`). They are committed because this repository ships packages as they are checked in: `publish.yml` packs each package onto the `dist` branch with `npm pack --ignore-scripts` (`scripts/dist.mjs`) and publishes it with `npm publish` from its folder, with no install or build step. So the bundles in a pull request are exactly what users get, and `verify:build` proves they are the build of the source next to them.
|
||||||
|
|
||||||
|
The build is deterministic: no timestamps, no absolute paths, LF line endings enforced by `.gitattributes`. From this folder (`packages/agent-console`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm ci --workspaces=false # the repository root is an npm workspace; this installs here, from this folder's package-lock.json
|
||||||
|
npm run build
|
||||||
|
git diff --exit-code app daemon/dist # no output = identical bytes
|
||||||
|
npm run verify:build # rebuilds into a temp dir, byte-compares, prints SHA-256
|
||||||
|
```
|
||||||
|
|
||||||
|
`verify:build` prints `OK <sha256> <file>` for each bundle and exits non-zero on any mismatch. Without `--workspaces=false`, npm treats this folder as a member of the root workspace and looks for a lockfile at the repository root, which there isn't.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
All dependencies and devDependencies are pinned to exact versions, and `package-lock.json` matches them (`npm ci` succeeds).
|
||||||
|
|
||||||
|
- **Installed for users** (`dependencies`): `@agentclientprotocol/sdk`, `ignore`, `ws`, `zod`. These are what `daemon/dist/main.js` imports (esbuild bundles it with `packages: "external"`, so every package it imports is loaded from `node_modules`); `index.mjs` itself only imports `ws`.
|
||||||
|
- **Optional** (`optionalDependencies`): `node-pty`, for the terminal panel only (see below).
|
||||||
|
- **Build only** (`devDependencies`): the UI packages `react`, `react-dom`, `@xterm/xterm`, `@xterm/addon-fit`, `lucide-react`, `marked`, `dompurify`, `highlight.js`, `zustand`, `@tanstack/react-virtual` and `clsx` are bundled into `app/app.js` and never loaded from `node_modules` at run time, plus esbuild, TypeScript, vitest and type packages.
|
||||||
|
- No Claude Code or Anthropic package is installed or bundled: the Claude Code Agent is the user's own `claude` CLI, started per conversation and driven over its stream-json protocol (`daemon/src/providers/claude/cli.ts`).
|
||||||
|
|
||||||
|
### Why `node-pty` is `1.2.0-beta.15`
|
||||||
|
|
||||||
|
Magpie installs a plugin with `bun add` and does not run its dependencies' install scripts (usemagpie.ai/docs/plugins, "Installing"). `node-pty`'s own `install` script (`node scripts/prebuild.js || node-gyp rebuild`) therefore never runs, so the only binary a user gets is the one inside `node-pty`'s npm tarball under `prebuilds/<platform>-<arch>/`.
|
||||||
|
|
||||||
|
- `node-pty@1.1.0`, the current `latest`, ships prebuilds for `darwin-x64`, `darwin-arm64`, `win32-x64` and `win32-arm64` only. On Linux it has no binary at all unless `node-gyp` compiles one at install time, which Magpie never does.
|
||||||
|
- `node-pty@1.2.0-beta.2` and later add `linux-x64` and `linux-arm64` prebuilds (glibc 2.28 or newer). `1.2.0-beta.15` is the beta this plugin is built and tested against, pinned exactly so a later, untested beta is never picked up (`beta.16`–`beta.18` came out on 2026-10-22/23). It also drops winpty, which more than halves the tarball (27 MB unpacked, against 64 MB for 1.1.0).
|
||||||
|
- The prebuilds are N-API addons, so one binary works on every Node version from 20 up; Node upgrades need no rebuild.
|
||||||
|
|
||||||
|
Checked with `npm view node-pty versions dist-tags` and by listing `prebuilds/` in the `1.1.0`, `1.2.0-beta.1` … `beta.15` tarballs. Once a stable `node-pty` release ships the Linux prebuilds, the pin moves to it.
|
||||||
|
|
||||||
|
### When `node-pty` can't be loaded
|
||||||
|
|
||||||
|
Only the terminal panel is affected; the daemon, the Agents and everything else keep working.
|
||||||
|
|
||||||
|
- No prebuild for the machine (for example Linux on musl/Alpine, 32-bit ARM, or glibc older than 2.28), a binary that fails to load, or `node-pty` missing because an install that does run scripts failed to build it: `node-pty` is loaded lazily, only when a terminal is opened, and the load error is caught and logged (`node-pty 加载失败,终端退化无 PTY 方案` in `logs/`).
|
||||||
|
- `pty.spawn` throwing (for example macOS `posix_spawnp failed`) is caught the same way. On macOS the exec bit of `spawn-helper` is restored first, since some extractions drop it.
|
||||||
|
- In both cases the terminal opens as a plain shell over pipes, and the panel shows "Simple terminal (no full TTY programs)". Commands run and print, but full-screen programs (vim, top, less) and line editing need a real TTY and don't work there.
|
||||||
|
- `node-pty` is an `optionalDependency`, so an `npm install` that runs install scripts and can't build it still installs the plugin.
|
||||||
|
|
||||||
|
`test/v1/terminal-fallback.test.ts` covers both cases: `node-pty` failing to import and `pty.spawn` throwing.
|
||||||
|
|
||||||
|
## Data directory
|
||||||
|
|
||||||
|
```
|
||||||
|
$XDG_CONFIG_HOME/magpie/agent-console/ (default ~/.config/magpie/agent-console on every OS;
|
||||||
|
on Windows ~ is %USERPROFILE%, the same root Magpie uses)
|
||||||
|
daemon.json pid/port/token/version of the running daemon (mode 0600)
|
||||||
|
settings.json settings (default Agent / permission / send key / panel widths…)
|
||||||
|
projects.json project list
|
||||||
|
threads/<id>/ meta.json + timeline.jsonl (event persistence, replay on reconnect)
|
||||||
|
attachments/ uploaded files
|
||||||
|
trash/ deleted threads and discarded new files (not hard-deleted)
|
||||||
|
logs/ daily rotating logs (kept 7 days); logs/daemon-spawn.log has the plugin host's view
|
||||||
|
```
|
||||||
|
|
||||||
|
Magpie in portable mode keeps its own config next to the executable, but this plugin still uses the directory above (it follows `XDG_CONFIG_HOME`).
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
In `packages/agent-console`, after `npm ci --workspaces=false` (use `npm install --workspaces=false` too when changing dependencies, so the lockfile stays in this folder):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build # daemon esm + web iife (app/ and daemon/dist are committed)
|
||||||
|
npm run verify:build # check committed bundles match a clean build
|
||||||
|
npm run dev # daemon on port 3499, data dir _tmp/xdg-dev (does not touch real data)
|
||||||
|
npm run check # typecheck both tsconfigs
|
||||||
|
npm test # vitest (test/v1 + web/src); the repository's root `bun test` skips these (bunfig.toml) and runs agent-console.test.mjs
|
||||||
|
npm run e2e:v1 # e2e: spawn daemon(3497) + Edge/Chrome/Chromium, Mock Agent (MSEDGE_PATH / CHROME_PATH to override)
|
||||||
|
node scripts/verify-windows.mjs [--quick] # one-command platform self-check, see docs/VERIFY-windows.md
|
||||||
|
npm run shot:v1 # screenshot set (light/dark × scenes → _tmp/shots-v1/)
|
||||||
|
|
||||||
|
# Mock (no real tokens)
|
||||||
|
AGENT_CONSOLE_MOCK=1 npm run dev
|
||||||
|
# scripts: default /perm /plan /ask /slow /error /long (5000-event stress) /exit
|
||||||
|
```
|
||||||
|
|
||||||
|
| Env | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `AGENT_CONSOLE_PORT` | gate port in the plugin / daemon port in standalone mode (3488; plugin `options.port` wins) |
|
||||||
|
| `AGENT_CONSOLE_MOCK=1` | register the mock provider |
|
||||||
|
| `AGENT_CONSOLE_TOKEN` | fixed page token (tests/screenshots only; do not set in production) |
|
||||||
|
| `AGENT_CONSOLE_IDLE_EXIT_MIN` | idle auto-exit minutes (default 60) |
|
||||||
|
| `XDG_CONFIG_HOME` | data root (`_tmp/xdg-dev` in development) |
|
||||||
|
|
||||||
|
Daemon CLI: `node daemon/dist/main.js [--port N|0] [--data DIR] [--token T] [--parent-pid PID]`. In standalone mode (no `--parent-pid`) it prints the URL to open, `http://127.0.0.1:<port>/#t=<token>`, to the console.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT (see LICENSE). Third-party licenses are in THIRD-PARTY-NOTICES.md: the 5 installed packages and the 11 bundled into `app/app.js` (mostly MIT; DOMPurify MPL-2.0/Apache-2.0, highlight.js BSD-3-Clause, lucide-react ISC). Build/test: esbuild, vitest, TypeScript, playwright-core.
|
||||||
|
|
||||||
|
Architecture takes cues from Paseo (persistent daemon + provider abstraction) and T3 Code (timeline shape and three-column layout) — ideas only, no copied code.
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Third-Party Notices
|
||||||
|
|
||||||
|
## Design references
|
||||||
|
|
||||||
|
The persistent-session architecture, event protocol and UI layout of this plugin were designed
|
||||||
|
with reference to the following open-source projects (only design ideas and protocol shapes were
|
||||||
|
referenced; no source code was copied):
|
||||||
|
|
||||||
|
- **Paseo** (https://github.com/getpaseo/paseo)
|
||||||
|
— persistent daemon + WebSocket event push, and the provider session abstraction.
|
||||||
|
- **T3 Code** (https://github.com/pingdotgg/t3code, MIT)
|
||||||
|
— timeline item shapes (tool groups, permission cards, plan cards) and the three-column workbench layout.
|
||||||
|
|
||||||
|
## npm dependencies and their licenses
|
||||||
|
|
||||||
|
Installed with the plugin (`dependencies`, and `node-pty` as an `optionalDependency`):
|
||||||
|
|
||||||
|
| Package | Version | License |
|
||||||
|
|---|---|---|
|
||||||
|
| @agentclientprotocol/sdk | 2.1.0 | Apache-2.0 |
|
||||||
|
| ignore | 7.0.14 | MIT |
|
||||||
|
| node-pty (optional) | 1.2.0-beta.15 | MIT |
|
||||||
|
| ws | 8.22.0 | MIT |
|
||||||
|
| zod | 4.6.7 | MIT |
|
||||||
|
|
||||||
|
Bundled into `app/app.js` (`devDependencies`: not installed for users, but their code ships inside the bundle):
|
||||||
|
|
||||||
|
| Package | Version | License |
|
||||||
|
|---|---|---|
|
||||||
|
| @tanstack/react-virtual | 3.14.24 | MIT |
|
||||||
|
| @xterm/addon-fit | 0.11.0 | MIT |
|
||||||
|
| @xterm/xterm | 6.0.0 | MIT |
|
||||||
|
| clsx | 2.1.1 | MIT |
|
||||||
|
| dompurify | 3.4.17 | MPL-2.0 OR Apache-2.0 |
|
||||||
|
| highlight.js | 11.12.0 | BSD-3-Clause |
|
||||||
|
| lucide-react | 1.64.0 | ISC |
|
||||||
|
| marked | 18.1.2 | MIT |
|
||||||
|
| react | 19.3.1 | MIT |
|
||||||
|
| react-dom | 19.3.1 | MIT |
|
||||||
|
| zustand | 5.0.16 | MIT |
|
||||||
|
|
||||||
|
Build and test tools (`devDependencies`; nothing from them ships):
|
||||||
|
typescript (Apache-2.0), esbuild (MIT), vitest (MIT), playwright-core (Apache-2.0),
|
||||||
|
@types/* (MIT).
|
||||||
|
|
||||||
|
The Codex app-server JSON-RPC schema files (`daemon/src/providers/codex/schema/`) are generated
|
||||||
|
locally by `codex app-server generate-json-schema`. They describe the OpenAI Codex CLI interface
|
||||||
|
and are used under the Codex license; the plugin uses them only for protocol integration.
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
// What the repository's root `bun test` checks for Agent Console, with no npm
|
||||||
|
// install: the package's shape and dependency split, that the magpie page reads
|
||||||
|
// nothing and reaches no network but its own navigation, that the bundles load
|
||||||
|
// only declared packages, and the gate's Origin/Host/key rules. The full suite
|
||||||
|
// (daemon, lifeline, PR #535 HTTP probes, terminal fallback) is vitest with npm
|
||||||
|
// dependencies: `npm ci --workspaces=false && npm test` in this folder; the root
|
||||||
|
// bunfig.toml keeps `bun test` out of it.
|
||||||
|
import { expect, test } from "bun:test"
|
||||||
|
import { existsSync, readFileSync } from "node:fs"
|
||||||
|
import { builtinModules } from "node:module"
|
||||||
|
import { request } from "node:http"
|
||||||
|
import { createServer } from "node:net"
|
||||||
|
import { join } from "node:path"
|
||||||
|
import { pathToFileURL } from "node:url"
|
||||||
|
|
||||||
|
const dir = import.meta.dir
|
||||||
|
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))
|
||||||
|
const read = (f) => readFileSync(join(dir, f), "utf8")
|
||||||
|
|
||||||
|
const RUNTIME = ["@agentclientprotocol/sdk", "ignore", "ws", "zod"]
|
||||||
|
const BUNDLED = ["@tanstack/react-virtual", "@xterm/addon-fit", "@xterm/xterm", "clsx", "dompurify", "highlight.js", "lucide-react", "marked", "react", "react-dom", "zustand"]
|
||||||
|
|
||||||
|
test("package.json: name, page, permissions and files", () => {
|
||||||
|
expect(pkg.name).toBe("@magpie-community/page-agent-console")
|
||||||
|
expect(pkg.type).toBe("module")
|
||||||
|
expect(pkg.main).toBe("./index.mjs")
|
||||||
|
expect(pkg.magpie.page.title).toBe("Agent Console")
|
||||||
|
for (const f of [pkg.magpie.page.file, pkg.magpie.page.icon]) expect(existsSync(join(dir, f))).toBe(true)
|
||||||
|
expect(pkg.magpie.icon.startsWith("data:image/svg+xml;base64,")).toBe(true)
|
||||||
|
// the page makes no magpie.read
|
||||||
|
expect(pkg.magpie.permissions).toEqual([])
|
||||||
|
// the tarball: no tests, no sources, never the per-run session.js
|
||||||
|
expect(pkg.files).not.toContain("page")
|
||||||
|
expect(pkg.files).toContain("page/index.html")
|
||||||
|
expect(pkg.files).toContain("page/boot.js")
|
||||||
|
for (const f of pkg.files) expect(f.startsWith("test") || f.startsWith("web") || f === "daemon/src").toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("dependencies: only what runs, every version pinned, lockfile in step", () => {
|
||||||
|
expect(Object.keys(pkg.dependencies).sort()).toEqual(RUNTIME)
|
||||||
|
expect(Object.keys(pkg.optionalDependencies)).toEqual(["node-pty"])
|
||||||
|
for (const name of BUNDLED) expect(pkg.devDependencies[name]).toBeDefined()
|
||||||
|
const lock = JSON.parse(read("package-lock.json"))
|
||||||
|
expect(lock.name).toBe(pkg.name)
|
||||||
|
expect(lock.version).toBe(pkg.version)
|
||||||
|
for (const kind of ["dependencies", "optionalDependencies", "devDependencies"]) {
|
||||||
|
for (const [name, version] of Object.entries(pkg[kind])) {
|
||||||
|
expect(version).toMatch(/^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/)
|
||||||
|
expect(lock.packages[`node_modules/${name}`]?.version).toBe(version)
|
||||||
|
expect(lock.packages[""][kind][name]).toBe(version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const name of BUNDLED) expect(lock.packages[`node_modules/${name}`].dev).toBe(true)
|
||||||
|
// Claude Code is the user's own claude CLI: no Anthropic package is installed, locked or bundled
|
||||||
|
const named = [...Object.keys(lock.packages), ...["dependencies", "optionalDependencies", "devDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {}))]
|
||||||
|
expect(named.filter((n) => n.includes("@anthropic-ai/"))).toEqual([])
|
||||||
|
// (the one @anthropic-ai/ name left in the bundle is the install hint for the user's own claude)
|
||||||
|
expect(read("daemon/dist/main.js").match(/@anthropic-ai\/[\w-]+/g)?.filter((n) => n !== "@anthropic-ai/claude-code") ?? []).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the daemon bundle and the host part import only builtins and declared packages", () => {
|
||||||
|
const builtins = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]))
|
||||||
|
const allowed = new Set([...RUNTIME, "node-pty"])
|
||||||
|
const specs = (src) => [...src.matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*)["']([^"'./][^"']*)["']/g)].map((m) => m[1])
|
||||||
|
const sources = ["daemon/dist/main.js", "index.mjs", "lib/gate.mjs", "lib/pathscan.mjs"].map(read)
|
||||||
|
const seen = new Set(sources.flatMap(specs))
|
||||||
|
expect(seen.size).toBeGreaterThan(5)
|
||||||
|
for (const s of seen) {
|
||||||
|
const name = s.startsWith("@") ? s.split("/").slice(0, 2).join("/") : s.split("/")[0]
|
||||||
|
if (!builtins.has(s)) expect(allowed.has(name) ? name : `undeclared ${s}`).toBe(name)
|
||||||
|
}
|
||||||
|
// the UI packages are inside app/app.js, never loaded from node_modules
|
||||||
|
for (const name of BUNDLED) expect(seen.has(name)).toBe(false)
|
||||||
|
// node-pty is loaded lazily, so a missing or broken binary can only cost the terminal
|
||||||
|
expect(read("daemon/dist/main.js")).not.toMatch(/from\s*["']node-pty["']/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the page reads nothing from magpie and reaches no network", () => {
|
||||||
|
const html = read("page/index.html")
|
||||||
|
// the code, without its comments (they name the gate's URL)
|
||||||
|
const boot = read("page/boot.js").replace(/^\s*\/\/.*$/gm, "").replace(/\/\*.*?\*\//g, "")
|
||||||
|
const scripts = [...html.matchAll(/<script[^>]*src="([^"]+)"/g)].map((m) => m[1])
|
||||||
|
expect(scripts).toEqual(["_magpie/bridge.js", "session.js", "boot.js"])
|
||||||
|
expect(html).not.toMatch(/<script(?![^>]*src=)[^>]*>/)
|
||||||
|
expect(html).not.toMatch(/https?:\/\//)
|
||||||
|
expect(boot).not.toMatch(/magpie\??\.read\s*\(/)
|
||||||
|
expect(boot).not.toMatch(/\.options\??\.(get|set)\b/)
|
||||||
|
for (const api of ["fetch(", "XMLHttpRequest", "WebSocket", "EventSource", "sendBeacon", "importScripts"]) expect(boot.includes(api)).toBe(false)
|
||||||
|
// its one way out: navigating its own frame to the gate on 127.0.0.1
|
||||||
|
expect([...boot.matchAll(/https?:\/\/[^"'`]+/g)].map((m) => m[0])).toEqual(["http://127.0.0.1:"])
|
||||||
|
expect(boot).toContain('location.replace("http://127.0.0.1:" + session.port + "/open?"')
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the host part is an OpenCode v1 server, as magpie loads a page's host part", async () => {
|
||||||
|
const mod = await import(pathToFileURL(join(dir, "index.mjs")).href)
|
||||||
|
expect(mod.default.id).toBe("agent-console")
|
||||||
|
expect(typeof mod.default.server).toBe("function")
|
||||||
|
})
|
||||||
|
|
||||||
|
const freePort = () =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
const s = createServer()
|
||||||
|
s.once("error", reject)
|
||||||
|
s.listen(0, "127.0.0.1", () => {
|
||||||
|
const { port } = s.address()
|
||||||
|
s.close(() => resolve(port))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const get = (port, path, headers = {}) =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
const r = request({ host: "127.0.0.1", port, path, headers }, (res) => {
|
||||||
|
let body = ""
|
||||||
|
res.on("data", (c) => (body += c))
|
||||||
|
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body }))
|
||||||
|
})
|
||||||
|
r.on("error", reject)
|
||||||
|
r.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
test("the gate: Host checked, any Origin refused, the token only in the # fragment", async () => {
|
||||||
|
const { createGate } = await import(pathToFileURL(join(dir, "lib", "gate.mjs")).href)
|
||||||
|
const port = await freePort()
|
||||||
|
const key = "c".repeat(64)
|
||||||
|
const token = "a".repeat(64)
|
||||||
|
let opened = 0
|
||||||
|
const gate = createGate({ port, key, token, ensureDaemon: async () => (opened++, { port: 45678 }) })
|
||||||
|
await gate.listen()
|
||||||
|
try {
|
||||||
|
expect((await get(port, `/open?k=${key}`, { host: `evil.example:${port}` })).status).toBe(421)
|
||||||
|
expect((await get(port, `/open?k=${key}`, { origin: "null" })).status).toBe(403)
|
||||||
|
expect((await get(port, `/open?k=${key}`, { origin: "https://evil.example" })).status).toBe(403)
|
||||||
|
expect((await get(port, "/open?k=wrong")).status).toBe(403)
|
||||||
|
expect((await get(port, `/open?k=${token}`)).status).toBe(403)
|
||||||
|
expect(opened).toBe(0)
|
||||||
|
const ok = await get(port, `/open?k=${key}&theme=dark`)
|
||||||
|
expect(ok.status).toBe(302)
|
||||||
|
expect(ok.headers.location).toBe(`http://127.0.0.1:45678/?theme=dark#t=${token}`)
|
||||||
|
expect(ok.headers["access-control-allow-origin"]).toBeUndefined()
|
||||||
|
expect(ok.body).not.toContain(token)
|
||||||
|
} finally {
|
||||||
|
await gate.close()
|
||||||
|
}
|
||||||
|
})
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,14 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light dark">
|
||||||
|
<title>Agent Console</title>
|
||||||
|
<link rel="stylesheet" href="app.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script src="app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
|
||||||
|
<rect width="128" height="128" rx="28" fill="#0d9488"/>
|
||||||
|
<path d="M34 44h60a8 8 0 0 1 8 8v24a8 8 0 0 1-8 8H62l-14 12v-12H34a8 8 0 0 1-8-8V52a8 8 0 0 1 8-8z" fill="#fff"/>
|
||||||
|
<g fill="#0d9488">
|
||||||
|
<circle cx="48" cy="62" r="5"/>
|
||||||
|
<circle cx="64" cy="62" r="5"/>
|
||||||
|
<circle cx="80" cy="62" r="5"/>
|
||||||
|
</g>
|
||||||
|
<path d="M40 96l-8 12M88 96l8 12" stroke="#fff" stroke-width="6" stroke-linecap="round"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 497 B |
+7952
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,136 @@
|
|||||||
|
// Line-level diff (ported from lib/diff.mjs): oldStr/newStr → { hunks, added, removed }
|
||||||
|
// hunk: { oldStart, newStart, lines: [{ t: " "|"+"|"-", s }] }
|
||||||
|
// LCS minimal edit script; keep context lines between changes and merge nearby small blocks into one hunk.
|
||||||
|
|
||||||
|
const CONTEXT = 3;
|
||||||
|
const MERGE_GAP = 6;
|
||||||
|
const MAX_LINES = 400;
|
||||||
|
|
||||||
|
export type DiffLine = { t: " " | "+" | "-"; s: string };
|
||||||
|
export type Hunk = { oldStart: number; newStart: number; lines: DiffLine[] };
|
||||||
|
export type DiffResult = { hunks: Hunk[]; added: number; removed: number; truncated?: boolean };
|
||||||
|
|
||||||
|
export function diffLines(oldStr = "", newStr = "", { context = CONTEXT } = {}): DiffResult {
|
||||||
|
const a = splitLines(oldStr);
|
||||||
|
const b = splitLines(newStr);
|
||||||
|
if (a.length > MAX_LINES || b.length > MAX_LINES) return coarseDiff(a, b);
|
||||||
|
const ops = lcsOps(a, b);
|
||||||
|
return buildHunks(ops, context);
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitLines(s: string): string[] {
|
||||||
|
s = String(s);
|
||||||
|
if (!s) return [];
|
||||||
|
return s.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
type Op = { t: " " | "+" | "-"; s: string };
|
||||||
|
|
||||||
|
function lcsOps(a: string[], b: string[]): Op[] {
|
||||||
|
const n = a.length;
|
||||||
|
const m = b.length;
|
||||||
|
const dp = new Uint32Array((n + 1) * (m + 1));
|
||||||
|
for (let i = n - 1; i >= 0; i--)
|
||||||
|
for (let j = m - 1; j >= 0; j--)
|
||||||
|
dp[i * (m + 1) + j] = a[i] === b[j]
|
||||||
|
? dp[(i + 1) * (m + 1) + j + 1] + 1
|
||||||
|
: Math.max(dp[(i + 1) * (m + 1) + j], dp[i * (m + 1) + j + 1]);
|
||||||
|
const ops: Op[] = [];
|
||||||
|
let i = 0;
|
||||||
|
let j = 0;
|
||||||
|
while (i < n && j < m) {
|
||||||
|
if (a[i] === b[j]) {
|
||||||
|
ops.push({ t: " ", s: a[i] });
|
||||||
|
i++; j++;
|
||||||
|
} else if (dp[(i + 1) * (m + 1) + j] >= dp[i * (m + 1) + j + 1]) {
|
||||||
|
ops.push({ t: "-", s: a[i] });
|
||||||
|
i++;
|
||||||
|
} else {
|
||||||
|
ops.push({ t: "+", s: b[j] });
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (i < n) ops.push({ t: "-", s: a[i++] });
|
||||||
|
while (j < m) ops.push({ t: "+", s: b[j++] });
|
||||||
|
return ops;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildHunks(ops: Op[], context: number): DiffResult {
|
||||||
|
const changed: number[] = [];
|
||||||
|
ops.forEach((op, i) => {
|
||||||
|
if (op.t !== " ") changed.push(i);
|
||||||
|
});
|
||||||
|
if (!changed.length) return { hunks: [], added: 0, removed: 0 };
|
||||||
|
|
||||||
|
let added = 0;
|
||||||
|
let removed = 0;
|
||||||
|
for (const op of ops) {
|
||||||
|
if (op.t === "+") added++;
|
||||||
|
else if (op.t === "-") removed++;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ranges: { s: number; e: number }[] = [];
|
||||||
|
for (const idx of changed) {
|
||||||
|
const s = Math.max(0, idx - context);
|
||||||
|
const e = Math.min(ops.length, idx + context + 1);
|
||||||
|
const last = ranges[ranges.length - 1];
|
||||||
|
if (last && s <= last.e + MERGE_GAP) last.e = Math.max(last.e, e);
|
||||||
|
else ranges.push({ s, e });
|
||||||
|
}
|
||||||
|
|
||||||
|
const hunks: Hunk[] = [];
|
||||||
|
let oldLn = 1;
|
||||||
|
let newLn = 1;
|
||||||
|
const oldNos: number[] = [];
|
||||||
|
const newNos: number[] = [];
|
||||||
|
for (const op of ops) {
|
||||||
|
oldNos.push(oldLn);
|
||||||
|
newNos.push(newLn);
|
||||||
|
if (op.t !== "+") oldLn++;
|
||||||
|
if (op.t !== "-") newLn++;
|
||||||
|
}
|
||||||
|
for (const r of ranges) {
|
||||||
|
hunks.push({
|
||||||
|
oldStart: oldNos[r.s],
|
||||||
|
newStart: newNos[r.s],
|
||||||
|
lines: ops.slice(r.s, r.e).map((op) => ({ t: op.t, s: op.s })),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { hunks, added, removed };
|
||||||
|
}
|
||||||
|
|
||||||
|
function coarseDiff(a: string[], b: string[]): DiffResult {
|
||||||
|
return {
|
||||||
|
hunks: [
|
||||||
|
{
|
||||||
|
oldStart: 1,
|
||||||
|
newStart: 1,
|
||||||
|
lines: [...a.map((s) => ({ t: "-" as const, s })), ...b.map((s) => ({ t: "+" as const, s }))].slice(0, 2000),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
added: b.length,
|
||||||
|
removed: a.length,
|
||||||
|
truncated: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the detail for Edit/MultiEdit: compute hunks from old/new or edits[]
|
||||||
|
export function editDetail(detail: Record<string, unknown> = {}) {
|
||||||
|
if (Array.isArray(detail.edits) && detail.edits.length) {
|
||||||
|
const hunks: Hunk[] = [];
|
||||||
|
let added = 0;
|
||||||
|
let removed = 0;
|
||||||
|
for (const e of detail.edits as { old_string?: string; old?: string; new_string?: string; new?: string }[]) {
|
||||||
|
const d = diffLines(e.old_string ?? e.old ?? "", e.new_string ?? e.new ?? "");
|
||||||
|
for (const h of d.hunks) hunks.push(h);
|
||||||
|
added += d.added;
|
||||||
|
removed += d.removed;
|
||||||
|
}
|
||||||
|
return { path: detail.path, hunks, added, removed };
|
||||||
|
}
|
||||||
|
if (detail.old !== undefined || detail.new !== undefined) {
|
||||||
|
const d = diffLines(String(detail.old ?? ""), String(detail.new ?? ""));
|
||||||
|
return { path: detail.path, hunks: d.hunks, added: d.added, removed: d.removed };
|
||||||
|
}
|
||||||
|
return detail;
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// Tool name → kind / title / detail mapping (ported from lib/agents/kinds.mjs).
|
||||||
|
// Adapters call callInfo(name, input, cwd) to get {kind, title, detail}; the frontend renders by kind.
|
||||||
|
import type { ToolKind } from "../timeline/types.js";
|
||||||
|
|
||||||
|
const MAX_CMD = 80;
|
||||||
|
const trunc = (s: string, n = MAX_CMD): string => (s.length > n ? s.slice(0, n - 1) + "…" : s);
|
||||||
|
|
||||||
|
export function relPath(p: string, cwd: string): string {
|
||||||
|
if (!p) return "";
|
||||||
|
const s = String(p);
|
||||||
|
if (!cwd) return s;
|
||||||
|
const norm = (x: string) => x.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||||
|
const a = norm(s);
|
||||||
|
const b = norm(cwd);
|
||||||
|
if (a.toLowerCase().startsWith(b.toLowerCase() + "/")) return a.slice(b.length + 1);
|
||||||
|
if (a.toLowerCase() === b.toLowerCase()) return ".";
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CallInfo = { kind: ToolKind; title: string; detail: Record<string, unknown> };
|
||||||
|
|
||||||
|
type ToolInput = Record<string, unknown> & { _exists?: boolean };
|
||||||
|
|
||||||
|
export function callInfo(name: string, input: ToolInput = {}, cwd = ""): CallInfo {
|
||||||
|
const t = String(name || "");
|
||||||
|
const f = (kind: ToolKind, title: string, detail: Record<string, unknown>): CallInfo => ({ kind, title, detail });
|
||||||
|
const file = String(input.file_path ?? input.path ?? input.notebook_path ?? "");
|
||||||
|
|
||||||
|
switch (t) {
|
||||||
|
case "Read":
|
||||||
|
return f("read", `读取 ${relPath(file, cwd)}`, { path: file, offset: input.offset, limit: input.limit });
|
||||||
|
case "Edit":
|
||||||
|
return f("edit", `编辑 ${relPath(file, cwd)}`, { path: file, old: input.old_string, new: input.new_string });
|
||||||
|
case "MultiEdit":
|
||||||
|
return f("edit", `编辑 ${relPath(file, cwd)}(${((input.edits as unknown[]) || []).length} 处)`, { path: file, edits: input.edits ?? [] });
|
||||||
|
case "Write":
|
||||||
|
return f("write", `${input._exists ? "覆盖" : "新建"} ${relPath(file, cwd)}`, { path: file, content: input.content });
|
||||||
|
case "NotebookEdit":
|
||||||
|
return f("edit", `编辑笔记本 ${relPath(String(input.notebook_path || file), cwd)}`, { path: input.notebook_path ?? file });
|
||||||
|
case "Bash":
|
||||||
|
return f("bash", `运行 ${trunc(String(input.command ?? ""))}`, { command: input.command, description: input.description });
|
||||||
|
case "BashOutput":
|
||||||
|
return f("bash", `查看输出 ${String(input.bash_id ?? "")}`, { bashId: input.bash_id });
|
||||||
|
case "KillShell":
|
||||||
|
return f("bash", `结束进程 ${String(input.shell_id ?? "")}`, { shellId: input.shell_id });
|
||||||
|
case "Grep":
|
||||||
|
return f("search", `搜索 "${trunc(String(input.pattern ?? ""), 40)}"`, { pattern: input.pattern, path: input.path, glob: input.glob });
|
||||||
|
case "Glob":
|
||||||
|
case "LS":
|
||||||
|
return f("glob", `查找 ${trunc(String(input.pattern ?? input.path ?? ""), 40)}`, { pattern: input.pattern, path: input.path });
|
||||||
|
case "WebFetch":
|
||||||
|
return f("web", `打开 ${hostOf(String(input.url ?? ""))}`, { url: input.url });
|
||||||
|
case "WebSearch":
|
||||||
|
return f("web", `搜索网页 "${trunc(String(input.query ?? ""), 40)}"`, { query: input.query });
|
||||||
|
case "TodoWrite": {
|
||||||
|
const items = todoItems((input.todos as { content?: string; text?: string; status?: string }[]) ?? []);
|
||||||
|
const done = items.filter((x) => x.status === "done").length;
|
||||||
|
return f("todo", `更新待办(${done}/${items.length})`, { items });
|
||||||
|
}
|
||||||
|
case "Task":
|
||||||
|
case "Agent":
|
||||||
|
return f("task", `子任务:${trunc(String(input.description ?? input.prompt ?? ""), 40)}`, { description: input.description });
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const m = /^mcp__([^_]+)__(.+)$/.exec(t);
|
||||||
|
if (m) return f("mcp", `${m[1]} · ${m[2]}`, { server: m[1], tool: m[2] });
|
||||||
|
return f("other", t || "工具", {});
|
||||||
|
}
|
||||||
|
|
||||||
|
function hostOf(url: string): string {
|
||||||
|
try {
|
||||||
|
return new URL(url).host;
|
||||||
|
} catch {
|
||||||
|
return String(url || "").slice(0, 40);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function todoItems(todos: { content?: string; text?: string; status?: string }[] = []): { text: string; status: string }[] {
|
||||||
|
return todos.map((x) => ({
|
||||||
|
text: x.content || x.text || "",
|
||||||
|
status: x.status === "completed" ? "done" : x.status === "in_progress" ? "in_progress" : "pending",
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -0,0 +1,793 @@
|
|||||||
|
// AgentManager (§5.7): conversation runtimes, send/queue/steer/interrupt/permissions, idle recycling, restart recovery.
|
||||||
|
import type { Gateway } from "../ws/gateway.js";
|
||||||
|
import type { ThreadsStore, ThreadMeta } from "../store/threads.js";
|
||||||
|
import type { ProjectsStore } from "../store/projects.js";
|
||||||
|
import type { SettingsStore } from "../store/settings.js";
|
||||||
|
import type { AttachmentStore } from "../store/attachments.js";
|
||||||
|
import type { Provider, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../providers/types.js";
|
||||||
|
import { resolveAttachmentRefs } from "../util/attachmentRefs.js";
|
||||||
|
import { getProvider } from "../providers/registry.js";
|
||||||
|
import { catalogById, providerCreatable } from "../providers/catalog.js";
|
||||||
|
import { isProviderEnabled } from "../providers/enabled.js";
|
||||||
|
import { cachedDetect, cachedModels } from "../providers/infoCache.js";
|
||||||
|
import type { ProviderEvent, TimelineEvent } from "../timeline/types.js";
|
||||||
|
import { Coalescer } from "../timeline/coalescer.js";
|
||||||
|
import { ApiError } from "../ws/methods.js";
|
||||||
|
import { log } from "../log.js";
|
||||||
|
import { tr } from "../util/i18n.js";
|
||||||
|
import {
|
||||||
|
codexSlashCommandsFromEntries,
|
||||||
|
loadCodexSlashEntries,
|
||||||
|
} from "../providers/codex/commands.js";
|
||||||
|
|
||||||
|
const SLASH_CACHE_TTL_MS = 10 * 60 * 1000;
|
||||||
|
|
||||||
|
type QueuedMessage = { id: string; text: string; attachments: { path: string; mime: string; name?: string }[] };
|
||||||
|
type PendingRequest = {
|
||||||
|
kind: "permission" | "question";
|
||||||
|
requestId: string;
|
||||||
|
options: { id: string; label: string; kind: string }[];
|
||||||
|
resolve: (a: RespondAnswer) => void;
|
||||||
|
event: ProviderEvent;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Runtime = {
|
||||||
|
threadId: string;
|
||||||
|
session: ProviderSession | null;
|
||||||
|
status: ThreadMeta["status"];
|
||||||
|
currentTurnId: string | null;
|
||||||
|
queue: QueuedMessage[];
|
||||||
|
pending: Map<string, PendingRequest>;
|
||||||
|
allowAlways: Set<string>;
|
||||||
|
lastActivity: number;
|
||||||
|
coalescer: Coalescer;
|
||||||
|
interruptTimer: NodeJS.Timeout | null;
|
||||||
|
endedTurnIds: Set<string>; // Turns that already have a turn_ended written (dedupe)
|
||||||
|
starting: boolean; // startTurn in progress (session is still null while it is being created)
|
||||||
|
commands: SlashCommand[];
|
||||||
|
sessionCreating: Promise<ProviderSession> | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type DeltaType = "assistant_delta" | "reasoning_delta" | "tool_output_delta";
|
||||||
|
const DELTA_TYPES: DeltaType[] = ["assistant_delta", "reasoning_delta", "tool_output_delta"];
|
||||||
|
// coalescer key = type + \u0000 + itemId; the three delta types coalesce separately and are pushed with their original type
|
||||||
|
const deltaKey = (type: DeltaType, itemId: string) => `${type}\u0000${itemId}`;
|
||||||
|
|
||||||
|
export type SendBehavior = "queue" | "steer";
|
||||||
|
|
||||||
|
export class AgentManager {
|
||||||
|
private runtimes = new Map<string, Runtime>();
|
||||||
|
private recycleTimer: NodeJS.Timeout | null = null;
|
||||||
|
private slashCache = new Map<string, { commands: SlashCommand[]; expires: number }>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private gw: Gateway,
|
||||||
|
private threads: ThreadsStore,
|
||||||
|
private projects: ProjectsStore,
|
||||||
|
private settings: SettingsStore,
|
||||||
|
private attachments: AttachmentStore,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** attachment.path in the frontend's thread.send is really an upload id; resolve it to the file under dataDir/attachments */
|
||||||
|
private resolveAttachments(refs: { path: string; mime: string; name?: string }[]) {
|
||||||
|
return resolveAttachmentRefs(this.attachments, refs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private attachmentLabels(refs: { path: string; mime: string; name?: string }[]) {
|
||||||
|
return refs.map((a) => ({ id: a.path, name: (a.name ?? "").trim() || a.path, mime: a.mime }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called at startup: running/initializing conversations are recovered as closed (§5.7.6)
|
||||||
|
async recoverOnStart(): Promise<void> {
|
||||||
|
for (const meta of await this.threads.list()) {
|
||||||
|
if (meta.status === "running" || meta.status === "initializing") {
|
||||||
|
await this.appendRaw(meta.id, {
|
||||||
|
type: "notice",
|
||||||
|
level: "warn",
|
||||||
|
message: tr("notice.daemonRestart"),
|
||||||
|
});
|
||||||
|
const events = await this.threads.readEvents(meta.id, 0, 50000);
|
||||||
|
// No turn_ended after the last turn_started → append interrupted
|
||||||
|
// (Can't use lastTurnStatus: it records the previous turn, not the one that was running)
|
||||||
|
// user_message is persisted before turn_started; if the provider never sent turn_started the turn is still open
|
||||||
|
let open: string | null = null;
|
||||||
|
for (const e of events) {
|
||||||
|
if (e.type === "turn_started") open = (e as { turnId?: string }).turnId ?? "unknown";
|
||||||
|
else if (e.type === "user_message" && !(e as { steered?: boolean }).steered) open = open ?? "unknown";
|
||||||
|
else if (e.type === "turn_ended") open = null;
|
||||||
|
}
|
||||||
|
if (open !== null) {
|
||||||
|
await this.appendRaw(meta.id, { type: "turn_ended", status: "interrupted", ...(open && open !== "unknown" ? { turnId: open } : {}) } as Partial<TimelineEvent> & { type: "turn_ended" });
|
||||||
|
}
|
||||||
|
// Cancel every unresolved permission request
|
||||||
|
const resolved = new Set(
|
||||||
|
events.filter((e) => e.type === "permission_resolved").map((e) => (e as { requestId: string }).requestId),
|
||||||
|
);
|
||||||
|
for (const e of events) {
|
||||||
|
if (e.type === "permission_request" && !resolved.has((e as { requestId: string }).requestId)) {
|
||||||
|
await this.appendRaw(meta.id, {
|
||||||
|
type: "permission_resolved",
|
||||||
|
requestId: (e as { requestId: string }).requestId,
|
||||||
|
cancelled: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await this.threads.patch(meta.id, { status: "closed", lastTurnStatus: "interrupted" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Idle recycling every minute
|
||||||
|
this.recycleTimer = setInterval(() => void this.recycleIdle(), 60_000);
|
||||||
|
this.recycleTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Close every session; the returned Promise resolves once each close finishes (or fails). Callers add their own timeout. */
|
||||||
|
shutdown(): Promise<void> {
|
||||||
|
if (this.recycleTimer) clearInterval(this.recycleTimer);
|
||||||
|
const all = [...this.runtimes.values()].map((rt) => rt.session?.close().catch(() => {}));
|
||||||
|
this.runtimes.clear();
|
||||||
|
return Promise.all(all).then(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idle-exit check (§5.2.7): busy if any runtime is not idle
|
||||||
|
anyBusy(): boolean {
|
||||||
|
for (const rt of this.runtimes.values()) {
|
||||||
|
if (rt.status === "running" || rt.status === "initializing") return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
runtimeInfo(threadId: string): { status: string; queue: unknown[]; pending: unknown[] } | null {
|
||||||
|
const rt = this.runtimes.get(threadId);
|
||||||
|
if (!rt) return null;
|
||||||
|
return {
|
||||||
|
status: rt.status,
|
||||||
|
queue: rt.queue,
|
||||||
|
pending: [...rt.pending.values()].map((p) => ({
|
||||||
|
requestId: p.requestId,
|
||||||
|
kind: p.kind,
|
||||||
|
options: p.options,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private rt(threadId: string): Runtime {
|
||||||
|
let r = this.runtimes.get(threadId);
|
||||||
|
if (!r) {
|
||||||
|
r = {
|
||||||
|
threadId,
|
||||||
|
session: null,
|
||||||
|
status: "idle",
|
||||||
|
currentTurnId: null,
|
||||||
|
queue: [],
|
||||||
|
pending: new Map(),
|
||||||
|
allowAlways: new Set(),
|
||||||
|
lastActivity: Date.now(),
|
||||||
|
coalescer: this.newCoalescer(threadId),
|
||||||
|
interruptTimer: null,
|
||||||
|
endedTurnIds: new Set(),
|
||||||
|
starting: false,
|
||||||
|
commands: [],
|
||||||
|
sessionCreating: null,
|
||||||
|
};
|
||||||
|
this.runtimes.set(threadId, r);
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private newCoalescer(threadId: string): Coalescer {
|
||||||
|
return new Coalescer(60, (key, text) => {
|
||||||
|
const i = key.indexOf("\u0000");
|
||||||
|
const type = key.slice(0, i) as DeltaType;
|
||||||
|
void this.pushEvent(threadId, { type, itemId: key.slice(i + 1), text });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private flushDeltas(rt: Runtime, itemId: string): void {
|
||||||
|
for (const t of DELTA_TYPES) rt.coalescer.flushItem(deltaKey(t, itemId));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- send ----
|
||||||
|
async send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[] }, behavior: SendBehavior = "queue"): Promise<void> {
|
||||||
|
const meta = await this.mustThread(threadId);
|
||||||
|
if (meta.archived) {
|
||||||
|
await this.threads.patch(threadId, { archived: false });
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||||
|
}
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
rt.lastActivity = Date.now();
|
||||||
|
const attachmentRefs = input.attachments ?? [];
|
||||||
|
|
||||||
|
// Closed (crash/recycle/restart recovery) → drop the old session; the next message resumes via providerSessionId
|
||||||
|
if (meta.status === "closed" && rt.session) {
|
||||||
|
try { await rt.session.close(); } catch {}
|
||||||
|
rt.session = null;
|
||||||
|
rt.commands = [];
|
||||||
|
}
|
||||||
|
if (!rt.starting && rt.session === null && (rt.status === "running" || rt.status === "initializing" || rt.status === "error")) {
|
||||||
|
rt.status = "idle";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rt.status === "running" || rt.starting || rt.status === "initializing") {
|
||||||
|
const provider = this.providerOf(meta);
|
||||||
|
if (behavior === "steer" && provider?.capabilities.steer && rt.session?.steer && !rt.starting) {
|
||||||
|
try {
|
||||||
|
const images = await this.resolveAttachments(attachmentRefs);
|
||||||
|
await rt.session.steer({ text: input.text, images });
|
||||||
|
await this.appendRaw(threadId, {
|
||||||
|
type: "user_message",
|
||||||
|
text: input.text,
|
||||||
|
steered: true,
|
||||||
|
attachments: this.attachmentLabels(attachmentRefs),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
} catch (e) {
|
||||||
|
// Steering failed (e.g. the turn hasn't really started yet) → fall back to queueing so the message isn't lost
|
||||||
|
log("info", `thread ${threadId} 插话失败,改为排队:${String(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const q: QueuedMessage = { id: "q" + Date.now().toString(36), text: input.text, attachments: attachmentRefs };
|
||||||
|
rt.queue.push(q);
|
||||||
|
this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.startTurn(threadId, input.text, attachmentRefs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async startTurn(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[]): Promise<void> {
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
rt.starting = true;
|
||||||
|
try {
|
||||||
|
await this.startTurnInner(threadId, text, attachmentRefs);
|
||||||
|
} finally {
|
||||||
|
rt.starting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async startTurnInner(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[]): Promise<void> {
|
||||||
|
const meta = await this.mustThread(threadId);
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
// Conversations that already ran (have a providerSessionId) ignore "disabled": disabling only blocks new conversations
|
||||||
|
const provider = await this.assertProviderUsable(meta.provider, { allowDisabled: !!meta.providerSessionId });
|
||||||
|
|
||||||
|
if (!rt.session) {
|
||||||
|
await this.setStatus(threadId, "initializing");
|
||||||
|
try {
|
||||||
|
await this.createSessionIfNeeded(threadId, { updateStatus: true });
|
||||||
|
} catch (e) {
|
||||||
|
await this.appendRaw(threadId, { type: "notice", level: "error", message: tr("notice.sessionStartFailed", { detail: String((e as Error)?.message ?? e) }) });
|
||||||
|
await this.appendRaw(threadId, { type: "turn_ended", status: "failed", error: String((e as Error)?.message ?? e) } as Partial<TimelineEvent> & { type: "turn_ended" });
|
||||||
|
await this.setStatus(threadId, "error");
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto title
|
||||||
|
const trimmed = text.trim();
|
||||||
|
if (meta.titleAuto && trimmed) {
|
||||||
|
await this.threads.patch(threadId, { title: trimmed.slice(0, 40), titleAuto: true });
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||||
|
}
|
||||||
|
await this.appendRaw(threadId, {
|
||||||
|
type: "user_message",
|
||||||
|
text,
|
||||||
|
attachments: this.attachmentLabels(attachmentRefs),
|
||||||
|
});
|
||||||
|
await this.setStatus(threadId, "running");
|
||||||
|
try {
|
||||||
|
const images = await this.resolveAttachments(attachmentRefs);
|
||||||
|
await rt.session!.send({ text, images });
|
||||||
|
} catch (e) {
|
||||||
|
// A failed send must not leave the conversation running
|
||||||
|
const msg = String((e as Error)?.message ?? e);
|
||||||
|
await this.appendRaw(threadId, { type: "notice", level: "error", message: tr("notice.sendFailed", { detail: msg }) });
|
||||||
|
await this.appendRaw(threadId, { type: "turn_ended", status: "failed", error: msg } as Partial<TimelineEvent> & { type: "turn_ended" });
|
||||||
|
await this.threads.patch(threadId, { lastTurnStatus: "failed" });
|
||||||
|
rt.currentTurnId = null;
|
||||||
|
await this.setStatus(threadId, "idle");
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- event pump ----
|
||||||
|
private async pumpEvents(threadId: string, session: ProviderSession): Promise<void> {
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
let ended = false;
|
||||||
|
try {
|
||||||
|
for await (const ev of session.events) {
|
||||||
|
await this.onProviderEvent(threadId, ev);
|
||||||
|
if (ev.type === "turn_started") ended = false; // A new turn started: reset (queued messages reuse the same session event stream)
|
||||||
|
if (ev.type === "turn_ended") ended = true;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", `thread ${threadId} 事件流异常:${String(e)}`);
|
||||||
|
}
|
||||||
|
if (!ended && this.rt(threadId).session === session) {
|
||||||
|
// Session exited unexpectedly: append failed
|
||||||
|
await this.onProviderEvent(threadId, {
|
||||||
|
type: "turn_ended",
|
||||||
|
turnId: rt.currentTurnId ?? "unknown",
|
||||||
|
status: "failed",
|
||||||
|
error: tr("turn.agentExit"),
|
||||||
|
});
|
||||||
|
rt.session = null;
|
||||||
|
await this.setStatus(threadId, "closed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async onProviderEvent(threadId: string, ev: ProviderEvent): Promise<void> {
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
rt.lastActivity = Date.now();
|
||||||
|
|
||||||
|
if (ev.type === "provider_session_id") {
|
||||||
|
await this.threads.patch(threadId, { providerSessionId: ev.id });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ev.type === "slash_commands") {
|
||||||
|
rt.commands = ev.commands;
|
||||||
|
const meta = await this.mustThread(threadId);
|
||||||
|
const proj = await this.projects.get(meta.projectId);
|
||||||
|
if (proj) this.putSlashCache(meta.provider, proj.path, ev.commands);
|
||||||
|
this.gw.publish(`thread:${threadId}`, { type: "commands", commands: ev.commands });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ev.type === "turn_started") {
|
||||||
|
rt.currentTurnId = ev.turnId;
|
||||||
|
await this.appendRaw(threadId, ev);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ev.type === "assistant_delta" || ev.type === "reasoning_delta" || ev.type === "tool_output_delta") {
|
||||||
|
// Goes through the coalescer, not persisted
|
||||||
|
rt.coalescer.push(deltaKey(ev.type, ev.itemId), ev.text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Before persisting a complete event, flush that itemId's pending deltas first (keeps ordering)
|
||||||
|
const evItemId = (ev as { itemId?: unknown }).itemId;
|
||||||
|
if (typeof evItemId === "string") this.flushDeltas(rt, evItemId);
|
||||||
|
if (ev.type === "assistant_message" || ev.type === "reasoning") {
|
||||||
|
await this.appendRaw(threadId, ev);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ev.type === "usage") {
|
||||||
|
const meta = await this.mustThread(threadId);
|
||||||
|
const u = meta.usage;
|
||||||
|
await this.threads.patch(threadId, {
|
||||||
|
usage: {
|
||||||
|
inputTokens: u.inputTokens + ev.inputTokens,
|
||||||
|
outputTokens: u.outputTokens + ev.outputTokens,
|
||||||
|
cacheReadTokens: u.cacheReadTokens + ev.cacheReadTokens,
|
||||||
|
costUsd: u.costUsd + ev.costUsd,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.pushEvent(threadId, ev); // Pushing without persisting would also work; persisted so it can be reviewed later
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ev.type === "permission_request" || ev.type === "question") {
|
||||||
|
const options = ev.type === "permission_request" ? ev.options : [];
|
||||||
|
const pending: PendingRequest = {
|
||||||
|
kind: ev.type === "permission_request" ? "permission" : "question",
|
||||||
|
requestId: ev.requestId,
|
||||||
|
options,
|
||||||
|
resolve: () => {},
|
||||||
|
event: ev,
|
||||||
|
};
|
||||||
|
// allowAlways hit → approve directly
|
||||||
|
const toolName = (ev as { detail?: { toolName?: string } }).detail?.toolName;
|
||||||
|
if (toolName && rt.allowAlways.has(toolName)) {
|
||||||
|
rt.session?.respond(ev.requestId, { optionId: "accept" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rt.pending.set(ev.requestId, pending);
|
||||||
|
await this.appendRaw(threadId, ev);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ev.type === "permission_resolved" || ev.type === "question_answered") {
|
||||||
|
// The manager already persisted it (respond / interrupt) → drop the provider's echo to avoid duplicates
|
||||||
|
if (!rt.pending.delete(ev.requestId)) return;
|
||||||
|
await this.appendRaw(threadId, ev);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ev.type === "turn_ended") {
|
||||||
|
// End a turn only once (drop a late one from the provider after the interrupt fallback already ended it)
|
||||||
|
if (ev.turnId && ev.turnId !== "unknown" && rt.endedTurnIds.has(ev.turnId)) return;
|
||||||
|
if (rt.interruptTimer) {
|
||||||
|
clearTimeout(rt.interruptTimer);
|
||||||
|
rt.interruptTimer = null;
|
||||||
|
}
|
||||||
|
if (ev.turnId && ev.turnId !== "unknown") rt.endedTurnIds.add(ev.turnId);
|
||||||
|
rt.coalescer.dispose();
|
||||||
|
rt.coalescer = this.newCoalescer(threadId);
|
||||||
|
await this.appendRaw(threadId, ev);
|
||||||
|
await this.threads.patch(threadId, { lastTurnStatus: ev.status });
|
||||||
|
rt.currentTurnId = null;
|
||||||
|
// After a failure/crash the session is dead (mock /exit) → clear it
|
||||||
|
if (ev.status === "failed" && rt.session && !this.alive(rt.session)) rt.session = null;
|
||||||
|
await this.setStatus(threadId, "idle");
|
||||||
|
// Next queued message
|
||||||
|
const next = rt.queue.shift();
|
||||||
|
if (next) {
|
||||||
|
this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue });
|
||||||
|
// A queued message that fails to start is only logged; it must not break the event pump (startTurn already wrote notice/turn_ended)
|
||||||
|
await this.startTurn(threadId, next.text, next.attachments).catch((e) => {
|
||||||
|
log("warn", `thread ${threadId} 排队消息启动失败:${String(e)}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Everything else: persist + push
|
||||||
|
await this.appendRaw(threadId, ev);
|
||||||
|
}
|
||||||
|
|
||||||
|
private alive(_s: ProviderSession): boolean {
|
||||||
|
return true; // mock /exit closes the queue; end of the event stream is handled separately
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- respond (permission/question answers) ----
|
||||||
|
async respond(threadId: string, requestId: string, answer: RespondAnswer): Promise<void> {
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
const pending = rt.pending.get(requestId);
|
||||||
|
if (!pending) throw new ApiError("not_found", "授权/提问不存在或已回应");
|
||||||
|
if (pending.kind === "permission" && answer.optionId) {
|
||||||
|
const valid = pending.options.some((o) => o.id === answer.optionId);
|
||||||
|
if (!valid) throw new ApiError("bad_params", `optionId 非法:${answer.optionId}`);
|
||||||
|
}
|
||||||
|
rt.pending.delete(requestId);
|
||||||
|
if (pending.kind === "permission") {
|
||||||
|
await this.appendRaw(threadId, {
|
||||||
|
type: "permission_resolved",
|
||||||
|
requestId,
|
||||||
|
optionId: answer.optionId,
|
||||||
|
cancelled: answer.cancelled,
|
||||||
|
});
|
||||||
|
const opt = pending.options.find((o) => o.id === answer.optionId);
|
||||||
|
if (opt?.kind === "allow_always") {
|
||||||
|
const toolName = (pending.event as { detail?: { toolName?: string } }).detail?.toolName;
|
||||||
|
if (toolName) rt.allowAlways.add(toolName);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await this.appendRaw(threadId, {
|
||||||
|
type: "question_answered",
|
||||||
|
requestId,
|
||||||
|
answers: answer.answers ?? {},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
rt.session?.respond(requestId, answer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- interrupt ----
|
||||||
|
async interrupt(threadId: string): Promise<void> {
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
if (!rt.session || rt.status !== "running") return;
|
||||||
|
// Invalidate all pending requests
|
||||||
|
for (const [id, p] of rt.pending) {
|
||||||
|
await this.appendRaw(threadId, { type: "permission_resolved", requestId: id, cancelled: true });
|
||||||
|
p.resolve({ cancelled: true });
|
||||||
|
}
|
||||||
|
rt.pending.clear();
|
||||||
|
await rt.session.interrupt();
|
||||||
|
const turnId = rt.currentTurnId;
|
||||||
|
// No turn_ended within 1 second → append interrupted
|
||||||
|
// Use the normal turn_ended path: clear currentTurnId, write lastTurnStatus, continue the queue
|
||||||
|
rt.interruptTimer = setTimeout(() => {
|
||||||
|
rt.interruptTimer = null;
|
||||||
|
if (rt.currentTurnId === turnId && turnId) {
|
||||||
|
void this.onProviderEvent(threadId, { type: "turn_ended", turnId, status: "interrupted" }).catch((e) => {
|
||||||
|
log("warn", `thread ${threadId} 打断兜底失败:${String(e)}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- setModel / setMode / setEffort ----
|
||||||
|
async setModel(threadId: string, model: string | null): Promise<void> {
|
||||||
|
const meta = await this.mustThread(threadId);
|
||||||
|
let effort = meta.effort;
|
||||||
|
const p = getProvider(meta.provider);
|
||||||
|
if (p) {
|
||||||
|
const models = await cachedModels(p);
|
||||||
|
const row = models.find((m) => (model ? m.id === model : m.isDefault)) ?? models[0];
|
||||||
|
const opts = row?.thinkingOptions ?? [];
|
||||||
|
if (effort && opts.length && !opts.some((o) => o.id === effort)) {
|
||||||
|
effort = null;
|
||||||
|
await this.appendRaw(threadId, {
|
||||||
|
type: "notice",
|
||||||
|
level: "info",
|
||||||
|
message: tr("notice.effortResetOnModel"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await this.threads.patch(threadId, { model, effort });
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
if (rt.session) await rt.session.setModel(model);
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||||
|
}
|
||||||
|
async setMode(threadId: string, mode: Mode): Promise<void> {
|
||||||
|
await this.threads.patch(threadId, { mode });
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
if (rt.session) await rt.session.setMode(mode);
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||||
|
}
|
||||||
|
async setEffort(threadId: string, effort: string | null): Promise<void> {
|
||||||
|
const meta = await this.mustThread(threadId);
|
||||||
|
await this.threads.patch(threadId, { effort });
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
if (rt.session) await rt.session.setEffort(effort);
|
||||||
|
if (meta.provider === "claude" && (rt.status === "running" || rt.status === "initializing")) {
|
||||||
|
await this.appendRaw(threadId, {
|
||||||
|
type: "notice",
|
||||||
|
level: "info",
|
||||||
|
message: tr("notice.effortNextTurn"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||||
|
}
|
||||||
|
|
||||||
|
async setCursorOpts(
|
||||||
|
threadId: string,
|
||||||
|
patch: { cursorFast?: boolean; cursorAutoReview?: boolean },
|
||||||
|
): Promise<void> {
|
||||||
|
const meta = await this.mustThread(threadId);
|
||||||
|
if (meta.provider !== "cursor") throw new ApiError("bad_params", "仅 Cursor 对话支持该选项");
|
||||||
|
const next = await this.threads.patch(threadId, patch);
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
const sess = rt.session as { updateCursorOpts?(f: boolean, a: boolean): Promise<void> } | null;
|
||||||
|
if (sess?.updateCursorOpts) {
|
||||||
|
await sess.updateCursorOpts(!!next.cursorFast, !!next.cursorAutoReview);
|
||||||
|
}
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: next });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The Agent can be switched only before any user message and while not running */
|
||||||
|
async setProvider(threadId: string, providerId: string): Promise<void> {
|
||||||
|
await this.mustThread(threadId);
|
||||||
|
const meta = await this.threads.get(threadId);
|
||||||
|
if (!meta) throw new ApiError("not_found", "对话不存在");
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
if (rt.status === "running" || rt.status === "initializing" || rt.starting) {
|
||||||
|
throw new ApiError("busy", "对话运行中,不能更换 Agent");
|
||||||
|
}
|
||||||
|
const events = await this.threads.readEvents(threadId, 0, 5000);
|
||||||
|
if (events.some((e) => e.type === "user_message")) {
|
||||||
|
throw new ApiError("bad_params", "已有消息,不能更换 Agent");
|
||||||
|
}
|
||||||
|
const p = await this.assertProviderUsable(providerId);
|
||||||
|
if (rt.session) {
|
||||||
|
try {
|
||||||
|
await rt.session.close();
|
||||||
|
} catch {}
|
||||||
|
rt.session = null;
|
||||||
|
rt.commands = [];
|
||||||
|
}
|
||||||
|
rt.status = "idle";
|
||||||
|
await this.threads.patch(threadId, {
|
||||||
|
provider: providerId,
|
||||||
|
model: null,
|
||||||
|
mode: p.capabilities.modes.includes(meta.mode) ? meta.mode : (p.capabilities.modes[0] ?? "default"),
|
||||||
|
effort: null,
|
||||||
|
providerSessionId: null,
|
||||||
|
status: "idle",
|
||||||
|
});
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||||
|
}
|
||||||
|
|
||||||
|
async close(threadId: string): Promise<void> {
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
if (rt.session) {
|
||||||
|
try {
|
||||||
|
await rt.session.close();
|
||||||
|
} catch {}
|
||||||
|
rt.session = null;
|
||||||
|
rt.commands = [];
|
||||||
|
}
|
||||||
|
await this.setStatus(threadId, "closed");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Slash commands: no session by default; only with load:true do we create a session for providers that need one to list them */
|
||||||
|
async listCommands(threadId: string, opts?: { load?: boolean }): Promise<SlashCommand[]> {
|
||||||
|
let meta: ThreadMeta;
|
||||||
|
try {
|
||||||
|
meta = await this.mustThread(threadId);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
const proj = await this.projects.get(meta.projectId);
|
||||||
|
if (!proj) return [];
|
||||||
|
|
||||||
|
if (meta.provider === "codex") {
|
||||||
|
try {
|
||||||
|
const commands = codexSlashCommandsFromEntries(await loadCodexSlashEntries(proj.path));
|
||||||
|
rt.commands = commands;
|
||||||
|
this.putSlashCache(meta.provider, proj.path, commands);
|
||||||
|
return commands;
|
||||||
|
} catch {
|
||||||
|
return this.getSlashCache(meta.provider, proj.path) ?? rt.commands;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rt.session) {
|
||||||
|
try {
|
||||||
|
const commands = await rt.session.listCommands();
|
||||||
|
rt.commands = commands;
|
||||||
|
this.putSlashCache(meta.provider, proj.path, commands);
|
||||||
|
return commands;
|
||||||
|
} catch {
|
||||||
|
return rt.commands.length ? rt.commands : (this.getSlashCache(meta.provider, proj.path) ?? []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cached = this.getSlashCache(meta.provider, proj.path);
|
||||||
|
if (cached) {
|
||||||
|
rt.commands = cached;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!opts?.load) return [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = await this.createSessionIfNeeded(threadId, { updateStatus: false });
|
||||||
|
const commands = await session.listCommands();
|
||||||
|
rt.commands = commands;
|
||||||
|
this.putSlashCache(meta.provider, proj.path, commands);
|
||||||
|
return commands;
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private slashCacheKey(provider: string, projectPath: string): string {
|
||||||
|
return `${provider}\u0000${projectPath}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getSlashCache(provider: string, projectPath: string): SlashCommand[] | null {
|
||||||
|
const hit = this.slashCache.get(this.slashCacheKey(provider, projectPath));
|
||||||
|
if (!hit) return null;
|
||||||
|
if (Date.now() > hit.expires) {
|
||||||
|
this.slashCache.delete(this.slashCacheKey(provider, projectPath));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return hit.commands;
|
||||||
|
}
|
||||||
|
|
||||||
|
private putSlashCache(provider: string, projectPath: string, commands: SlashCommand[]): void {
|
||||||
|
// Don't cache an empty list: commands often arrive late (async push), and a cached empty result would keep the menu empty for the TTL
|
||||||
|
if (!commands.length) return;
|
||||||
|
this.slashCache.set(this.slashCacheKey(provider, projectPath), {
|
||||||
|
commands,
|
||||||
|
expires: Date.now() + SLASH_CACHE_TTL_MS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async createSessionIfNeeded(
|
||||||
|
threadId: string,
|
||||||
|
opts: { updateStatus: boolean },
|
||||||
|
): Promise<ProviderSession> {
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
if (rt.session) return rt.session;
|
||||||
|
if (rt.sessionCreating) return rt.sessionCreating;
|
||||||
|
|
||||||
|
const creating = this.createSessionInner(threadId, opts);
|
||||||
|
rt.sessionCreating = creating;
|
||||||
|
try {
|
||||||
|
return await creating;
|
||||||
|
} finally {
|
||||||
|
if (rt.sessionCreating === creating) rt.sessionCreating = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async createSessionInner(
|
||||||
|
threadId: string,
|
||||||
|
opts: { updateStatus: boolean },
|
||||||
|
): Promise<ProviderSession> {
|
||||||
|
const meta = await this.mustThread(threadId);
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
if (rt.session) return rt.session;
|
||||||
|
const provider = await this.assertProviderUsable(meta.provider, { allowDisabled: !!meta.providerSessionId });
|
||||||
|
const proj = await this.projects.get(meta.projectId);
|
||||||
|
if (!proj) throw new ApiError("not_found", "项目不存在");
|
||||||
|
let model = meta.model;
|
||||||
|
// DSH model IDs come from ACP; old conversations may still hold a model ID from another Agent.
|
||||||
|
// Clear that stale value so it isn't sent to the wrong Magpie provider route.
|
||||||
|
if (meta.provider === "dsh" && model) {
|
||||||
|
// Use the cache: listModels spawns a dsh ACP probe process, too wasteful to do for every new session
|
||||||
|
const available = await cachedModels(provider).catch(() => []);
|
||||||
|
if (available.length && !available.some((m) => m.id === model)) {
|
||||||
|
// Prefer DSH's Magpie-routed model so it doesn't fall back to DeepSeek's official model without an API key.
|
||||||
|
model = available.find((m) => /magpie/i.test(m.id))?.id ?? available.find((m) => m.isDefault)?.id ?? null;
|
||||||
|
await this.threads.patch(threadId, { model });
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||||
|
}
|
||||||
|
} else if (meta.provider === "dsh" && !model) {
|
||||||
|
// No model picked: start dsh on the route a new conversation would use (its ACP takes images only for the route it starts on)
|
||||||
|
const available = await cachedModels(provider).catch(() => []);
|
||||||
|
const magpie = available.filter((m) => /magpie/i.test(m.id));
|
||||||
|
model = (magpie.find((m) => m.isDefault) ?? magpie[0] ?? available.find((m) => m.isDefault))?.id ?? null;
|
||||||
|
}
|
||||||
|
if (opts.updateStatus) await this.setStatus(threadId, "initializing");
|
||||||
|
const settings = await this.settings.get();
|
||||||
|
const custom = settings.providerCommand?.[meta.provider];
|
||||||
|
const launch =
|
||||||
|
custom?.executable?.trim()
|
||||||
|
? { cmd: custom.executable.trim(), prefixArgs: custom.args ?? [] }
|
||||||
|
: undefined;
|
||||||
|
rt.session = await provider.createSession({
|
||||||
|
threadId,
|
||||||
|
cwd: proj.path,
|
||||||
|
model,
|
||||||
|
mode: meta.mode,
|
||||||
|
effort: meta.effort,
|
||||||
|
resumeId: meta.providerSessionId,
|
||||||
|
cursorFast: meta.cursorFast,
|
||||||
|
cursorAutoReview: meta.cursorAutoReview,
|
||||||
|
launch,
|
||||||
|
});
|
||||||
|
void this.pumpEvents(threadId, rt.session);
|
||||||
|
return rt.session;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteThread(threadId: string): Promise<void> {
|
||||||
|
await this.close(threadId);
|
||||||
|
this.runtimes.delete(threadId);
|
||||||
|
await this.threads.delete(threadId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- internals ----
|
||||||
|
private async mustThread(threadId: string): Promise<ThreadMeta> {
|
||||||
|
const meta = await this.threads.get(threadId);
|
||||||
|
if (!meta) throw new ApiError("not_found", "对话不存在");
|
||||||
|
return meta;
|
||||||
|
}
|
||||||
|
|
||||||
|
private providerOf(meta: ThreadMeta): Provider | undefined {
|
||||||
|
return getProvider(meta.provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertProviderUsable(providerId: string, opts: { allowDisabled?: boolean } = {}): Promise<Provider> {
|
||||||
|
const p = getProvider(providerId);
|
||||||
|
if (!p) throw new ApiError("bad_params", `未知 Agent:${providerId}`);
|
||||||
|
const s = await this.settings.get();
|
||||||
|
if (!opts.allowDisabled && !isProviderEnabled(s, providerId)) {
|
||||||
|
throw new ApiError("bad_params", `${p.name} 已在设置中禁用`);
|
||||||
|
}
|
||||||
|
const entry = catalogById(providerId);
|
||||||
|
if (entry && !providerCreatable(entry.status)) {
|
||||||
|
throw new ApiError("bad_params", `${p.name} 尚未接入,暂不能新建对话`);
|
||||||
|
}
|
||||||
|
const det = await cachedDetect(p);
|
||||||
|
if (!det.available) throw new ApiError("bad_params", det.reason ?? `${p.name} 未安装或不可用`);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async setStatus(threadId: string, status: ThreadMeta["status"]): Promise<void> {
|
||||||
|
const rt = this.rt(threadId);
|
||||||
|
rt.status = status;
|
||||||
|
const meta = await this.threads.patch(threadId, { status });
|
||||||
|
this.gw.publish("sidebar", { type: "thread.upsert", thread: meta });
|
||||||
|
this.gw.publish(`thread:${threadId}`, { type: "status", status }); // Frontend running state / timer / send button
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append an event: seq is assigned in the store's serialized section, persisted, then pushed to thread:<id>
|
||||||
|
private async appendRaw(threadId: string, ev: Record<string, unknown> & { type: TimelineEvent["type"] }): Promise<void> {
|
||||||
|
const full = await this.threads.appendEvent(threadId, { ...ev, ts: Date.now() });
|
||||||
|
this.gw.publish(`thread:${threadId}`, { type: "event", event: full });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push without persisting (for coalescer deltas; usage is already accumulated above).
|
||||||
|
// Unpersisted events take no seq: seq=-1 so the frontend dedupes only by persisted seq,
|
||||||
|
// otherwise deltas would push the client's maxSeq up and the following persisted events would be dropped by mistake.
|
||||||
|
private async pushEvent(threadId: string, ev: Record<string, unknown> & { type: TimelineEvent["type"] }): Promise<void> {
|
||||||
|
const full = { ...ev, seq: -1, ts: Date.now(), threadId } as TimelineEvent;
|
||||||
|
this.gw.publish(`thread:${threadId}`, { type: "event", event: full });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async recycleIdle(): Promise<void> {
|
||||||
|
const s = await this.settings.get();
|
||||||
|
const limit = (s.idleCloseMinutes ?? 30) * 60_000;
|
||||||
|
for (const rt of this.runtimes.values()) {
|
||||||
|
if (rt.status === "idle" && rt.pending.size === 0 && Date.now() - rt.lastActivity > limit) {
|
||||||
|
log("info", `空闲回收 thread ${rt.threadId}`);
|
||||||
|
await this.close(rt.threadId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Arguments and environment: port, dataDir, token, version, idleExitMinutes
|
||||||
|
import { randomBytes } from "node:crypto";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { join, resolve, dirname } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { daemonBuildStamp } from "./util/buildStamp.js";
|
||||||
|
|
||||||
|
export type Config = {
|
||||||
|
port: number;
|
||||||
|
dataDir: string;
|
||||||
|
token: string;
|
||||||
|
version: string;
|
||||||
|
idleExitMinutes: number;
|
||||||
|
buildStamp: string;
|
||||||
|
parentPid?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function pkgVersion(): string {
|
||||||
|
try {
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
// dist/main.js → ../../package.json; src/main.ts also ends up in dist via esbuild
|
||||||
|
const pkg = JSON.parse(readFileSync(join(here, "..", "..", "package.json"), "utf8"));
|
||||||
|
return String(pkg.version || "0.0.0");
|
||||||
|
} catch {
|
||||||
|
return "0.0.0";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --data <dir> sets the data root (equivalent to setting XDG_CONFIG_HOME and then joining magpie/agent-console?
|
||||||
|
// EXEC §5.2: --data <dir> (data root, equivalent to setting XDG_CONFIG_HOME; default $XDG_CONFIG_HOME
|
||||||
|
// or ~/.config, then joined with magpie/agent-console). i.e. the --data value has XDG_CONFIG_HOME semantics.
|
||||||
|
export function parseConfig(argv: string[]): Config {
|
||||||
|
let port: number | null = null;
|
||||||
|
let data: string | null = null;
|
||||||
|
let token: string | null = null;
|
||||||
|
let parentPid: number | undefined;
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const a = argv[i];
|
||||||
|
if (a === "--port" && argv[i + 1]) port = Number(argv[++i]);
|
||||||
|
else if (a.startsWith("--port=")) port = Number(a.slice(7));
|
||||||
|
else if (a === "--data" && argv[i + 1]) data = argv[++i];
|
||||||
|
else if (a.startsWith("--data=")) data = a.slice(7);
|
||||||
|
else if (a === "--token" && argv[i + 1]) token = argv[++i];
|
||||||
|
else if (a.startsWith("--token=")) token = a.slice(8);
|
||||||
|
else if (a === "--parent-pid" && argv[i + 1]) parentPid = Number(argv[++i]);
|
||||||
|
else if (a.startsWith("--parent-pid=")) parentPid = Number(a.slice(13));
|
||||||
|
}
|
||||||
|
if (port == null || !Number.isInteger(port) || port < 0 || port > 65535) {
|
||||||
|
const envPort = Number(process.env.AGENT_CONSOLE_PORT || "");
|
||||||
|
port = Number.isInteger(envPort) && envPort >= 0 && envPort <= 65535 ? envPort : 3488;
|
||||||
|
}
|
||||||
|
const xdg = data ?? process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
|
||||||
|
const dataDir = resolve(join(xdg, "magpie", "agent-console"));
|
||||||
|
const idleEnv = Number(process.env.AGENT_CONSOLE_IDLE_EXIT_MIN || "");
|
||||||
|
return {
|
||||||
|
port,
|
||||||
|
dataDir,
|
||||||
|
token: token ?? process.env.AGENT_CONSOLE_TOKEN ?? randomBytes(16).toString("hex"),
|
||||||
|
version: pkgVersion(),
|
||||||
|
idleExitMinutes: Number.isFinite(idleEnv) && idleEnv > 0 ? idleEnv : 60,
|
||||||
|
buildStamp: daemonBuildStamp(),
|
||||||
|
parentPid: Number.isInteger(parentPid) ? parentPid : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// FileService (§5.9): file tree (lazily, one level at a time) and file preview.
|
||||||
|
// tree: ignore .git/node_modules + the project root .gitignore (ignore library); directories first, sorted by name; ≤2000 per level.
|
||||||
|
// read: ≤1MB; a \0 in the first 8KB → {binary}; otherwise {text, language} (inferred from the extension).
|
||||||
|
import { readdir, readFile, stat } from "node:fs/promises";
|
||||||
|
import { join, normalize, sep, relative, extname } from "node:path";
|
||||||
|
import ignore from "ignore";
|
||||||
|
|
||||||
|
export type TreeEntry = { name: string; path: string; isDir: boolean };
|
||||||
|
export type ReadResult = {
|
||||||
|
text?: string;
|
||||||
|
language?: string;
|
||||||
|
encoding?: "utf8" | "gbk";
|
||||||
|
binary?: boolean;
|
||||||
|
tooLarge?: boolean;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Text decoding: UTF-8 (BOM stripped); if it isn't valid UTF-8 try GBK once (old files on Chinese Windows), else lenient UTF-8. */
|
||||||
|
export function decodeText(buf: Buffer): { text: string; encoding: "utf8" | "gbk" } {
|
||||||
|
try {
|
||||||
|
const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(buf);
|
||||||
|
return { text, encoding: "utf8" };
|
||||||
|
} catch {}
|
||||||
|
try {
|
||||||
|
const text = new TextDecoder("gbk", { fatal: true }).decode(buf);
|
||||||
|
return { text, encoding: "gbk" };
|
||||||
|
} catch {}
|
||||||
|
return { text: new TextDecoder("utf-8").decode(buf), encoding: "utf8" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_READ = 1024 * 1024;
|
||||||
|
const MAX_PER_LEVEL = 2000;
|
||||||
|
const ALWAYS_IGNORE = new Set([".git", "node_modules"]);
|
||||||
|
|
||||||
|
const LANG: Record<string, string> = {
|
||||||
|
".ts": "typescript", ".tsx": "typescript", ".js": "javascript", ".jsx": "javascript",
|
||||||
|
".mjs": "javascript", ".cjs": "javascript", ".json": "json", ".md": "markdown",
|
||||||
|
".py": "python", ".rs": "rust", ".go": "go", ".java": "java", ".c": "c", ".h": "c",
|
||||||
|
".cpp": "cpp", ".hpp": "cpp", ".cs": "csharp", ".css": "css", ".scss": "scss",
|
||||||
|
".html": "xml", ".htm": "xml", ".xml": "xml", ".svg": "xml", ".yaml": "yaml", ".yml": "yaml",
|
||||||
|
".toml": "ini", ".ini": "ini", ".sh": "bash", ".bash": "bash", ".ps1": "powershell",
|
||||||
|
".sql": "sql", ".lua": "lua", ".rb": "ruby", ".php": "php", ".swift": "swift",
|
||||||
|
".kt": "kotlin", ".vue": "xml", ".svelte": "xml", ".dockerfile": "dockerfile",
|
||||||
|
".txt": "plaintext", ".log": "plaintext",
|
||||||
|
};
|
||||||
|
|
||||||
|
function insidePath(projectPath: string, p: string): string | null {
|
||||||
|
const rel = normalize(p || ".").replace(/\\/g, "/");
|
||||||
|
const abs = normalize(join(projectPath, rel));
|
||||||
|
const proj = normalize(projectPath);
|
||||||
|
if (abs !== proj && !abs.startsWith(proj + sep)) return null;
|
||||||
|
return rel;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class FileService {
|
||||||
|
// Cache an ignore instance per project (.gitignore changes are picked up on the next daemon restart; acceptable cost)
|
||||||
|
// Invalidate by .gitignore mtime: an edited .gitignore takes effect the next time a directory is expanded
|
||||||
|
private igCache = new Map<string, { mtime: number; ig: ReturnType<typeof ignore> | null }>();
|
||||||
|
|
||||||
|
private async igFor(projectPath: string) {
|
||||||
|
const gi = join(projectPath, ".gitignore");
|
||||||
|
const st = await stat(gi).catch(() => null);
|
||||||
|
const mtime = st?.isFile() ? st.mtimeMs : -1;
|
||||||
|
const hit = this.igCache.get(projectPath);
|
||||||
|
if (hit && hit.mtime === mtime) return hit.ig;
|
||||||
|
let ig: ReturnType<typeof ignore> | null = null;
|
||||||
|
if (mtime >= 0) {
|
||||||
|
try {
|
||||||
|
ig = ignore().add(await readFile(gi, "utf8"));
|
||||||
|
} catch {
|
||||||
|
ig = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.igCache.set(projectPath, { mtime, ig });
|
||||||
|
return ig;
|
||||||
|
}
|
||||||
|
|
||||||
|
async tree(projectPath: string, dir: string): Promise<{ entries?: TreeEntry[]; error?: string }> {
|
||||||
|
const rel = insidePath(projectPath, dir);
|
||||||
|
if (rel === null) return { error: "路径不允许" };
|
||||||
|
const abs = join(projectPath, rel);
|
||||||
|
const s = await stat(abs).catch(() => null);
|
||||||
|
if (!s?.isDirectory()) return { error: "目录不存在" };
|
||||||
|
const ig = await this.igFor(projectPath);
|
||||||
|
const dirents = await readdir(abs, { withFileTypes: true }).catch(() => null);
|
||||||
|
if (!dirents) return { error: "无法读取目录" };
|
||||||
|
const out: TreeEntry[] = [];
|
||||||
|
for (const d of dirents) {
|
||||||
|
if (out.length >= MAX_PER_LEVEL) break;
|
||||||
|
const name = d.name;
|
||||||
|
if (ALWAYS_IGNORE.has(name)) continue;
|
||||||
|
const childRel = rel === "." ? name : `${rel}/${name}`;
|
||||||
|
// Only symlinks / junctions get an extra stat (to see whether they point at a directory); large directories are no longer stat'ed entry by entry
|
||||||
|
let isDir = d.isDirectory();
|
||||||
|
if (d.isSymbolicLink()) {
|
||||||
|
const st = await stat(join(projectPath, childRel)).catch(() => null);
|
||||||
|
if (!st) continue;
|
||||||
|
isDir = st.isDirectory();
|
||||||
|
} else if (!d.isFile() && !isDir) {
|
||||||
|
continue; // socket / fifo etc.
|
||||||
|
}
|
||||||
|
if (ig) {
|
||||||
|
// The ignore library wants posix relative paths; directory rules need a trailing / to match directories
|
||||||
|
if (ig.ignores(isDir ? childRel + "/" : childRel)) continue;
|
||||||
|
}
|
||||||
|
out.push({ name, path: childRel, isDir });
|
||||||
|
}
|
||||||
|
out.sort((a, b) => (a.isDir === b.isDir ? a.name.localeCompare(b.name, "zh-CN") : a.isDir ? -1 : 1));
|
||||||
|
return { entries: out };
|
||||||
|
}
|
||||||
|
|
||||||
|
async read(projectPath: string, p: string): Promise<ReadResult> {
|
||||||
|
const rel = insidePath(projectPath, p);
|
||||||
|
if (rel === null) return { error: "路径不允许" };
|
||||||
|
const abs = join(projectPath, rel);
|
||||||
|
const s = await stat(abs).catch(() => null);
|
||||||
|
if (!s) return { error: "文件不存在" };
|
||||||
|
if (!s.isFile()) return { error: "不是文件" };
|
||||||
|
if (s.size > MAX_READ) return { tooLarge: true };
|
||||||
|
const buf = await readFile(abs).catch(() => null);
|
||||||
|
if (!buf) return { error: "无法读取" };
|
||||||
|
const head = buf.subarray(0, 8192);
|
||||||
|
if (head.includes(0)) return { binary: true };
|
||||||
|
const { text, encoding } = decodeText(buf);
|
||||||
|
return { text, encoding, language: LANG[extname(rel).toLowerCase()] ?? "plaintext" };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// GitService (§5.8): runs the local git via execFile (no shell), cwd = project path, 15 s timeout.
|
||||||
|
import { execFile } from "node:child_process";
|
||||||
|
import { existsSync } from "node:fs";
|
||||||
|
import { cp, mkdir, readFile, rename, rm, stat } from "node:fs/promises";
|
||||||
|
import { join, normalize, sep } from "node:path";
|
||||||
|
|
||||||
|
export type GitFileEntry = {
|
||||||
|
path: string;
|
||||||
|
index: string;
|
||||||
|
worktree: string;
|
||||||
|
kind: "modified" | "added" | "deleted" | "untracked" | "renamed";
|
||||||
|
};
|
||||||
|
export type GitStatus = { isRepo: boolean; branch?: string; files?: GitFileEntry[]; error?: string };
|
||||||
|
|
||||||
|
const TIMEOUT = 15_000;
|
||||||
|
const DIFF_LIMIT = 1024 * 1024;
|
||||||
|
|
||||||
|
function runGit(cwd: string, args: string[]): Promise<{ code: number; out: string; err: string }> {
|
||||||
|
return new Promise((res) => {
|
||||||
|
// core.quotepath=false: non-ASCII paths (e.g. Chinese file names) are no longer turned into "\346\226\207" octal escapes in diff headers
|
||||||
|
execFile("git", ["-c", "core.quotepath=false", ...args], { cwd, timeout: TIMEOUT, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (e, stdout, stderr) => {
|
||||||
|
const code = e && typeof (e as { code?: number }).code === "number" ? (e as { code: number }).code! : e ? 1 : 0;
|
||||||
|
const missing = (e as NodeJS.ErrnoException | null)?.code === "ENOENT";
|
||||||
|
res({ code, out: String(stdout ?? ""), err: missing ? "找不到 git(请先安装 git 并加入 PATH)" : String(stderr || (e?.message ?? "")) });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// The path must be inside the project (no .. escape); returns the project-relative path (posix form)
|
||||||
|
function insidePath(projectPath: string, p: string): string | null {
|
||||||
|
const rel = normalize(p).replace(/\\/g, "/");
|
||||||
|
const abs = normalize(join(projectPath, rel));
|
||||||
|
const proj = normalize(projectPath);
|
||||||
|
if (abs !== proj && !abs.startsWith(proj + sep)) return null;
|
||||||
|
return rel.replace(/\\/g, "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
// rename across drives/volumes (Windows project on D:, data dir on C:; different mount points on Linux) fails with EXDEV → copy then delete
|
||||||
|
export async function moveAcrossDevices(
|
||||||
|
from: string,
|
||||||
|
to: string,
|
||||||
|
ops: { rename?: typeof rename; cp?: typeof cp; rm?: typeof rm } = {},
|
||||||
|
): Promise<void> {
|
||||||
|
const ren = ops.rename ?? rename;
|
||||||
|
try {
|
||||||
|
await ren(from, to);
|
||||||
|
} catch (e) {
|
||||||
|
const code = (e as NodeJS.ErrnoException)?.code;
|
||||||
|
if (code !== "EXDEV") throw e;
|
||||||
|
await (ops.cp ?? cp)(from, to, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true });
|
||||||
|
await (ops.rm ?? rm)(from, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GitService {
|
||||||
|
// projectPath is resolved from projectId by the caller (the service doesn't know about the store)
|
||||||
|
async status(projectPath: string): Promise<GitStatus> {
|
||||||
|
const inside = await runGit(projectPath, ["rev-parse", "--is-inside-work-tree"]);
|
||||||
|
if (inside.code !== 0 || inside.out.trim() !== "true") return { isRepo: false };
|
||||||
|
const br = await runGit(projectPath, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||||
|
const st = await runGit(projectPath, ["status", "--porcelain=v1", "-z", "-uall"]);
|
||||||
|
if (st.code !== 0) return { isRepo: true, branch: br.out.trim() || undefined, error: st.err.trim() || "status 失败" };
|
||||||
|
const files: GitFileEntry[] = [];
|
||||||
|
const parts = st.out.split("\0");
|
||||||
|
for (let i = 0; i < parts.length; i++) {
|
||||||
|
const rec = parts[i];
|
||||||
|
if (!rec || rec.length < 4) continue;
|
||||||
|
const index = rec[0];
|
||||||
|
const worktree = rec[1];
|
||||||
|
let path = rec.slice(3);
|
||||||
|
let kind: GitFileEntry["kind"] = "modified";
|
||||||
|
if (index === "?" && worktree === "?") kind = "untracked";
|
||||||
|
else if (index === "R" || worktree === "R") {
|
||||||
|
kind = "renamed";
|
||||||
|
// A renamed record looks like "R new\0old": the next part is the old path, skip it
|
||||||
|
i++;
|
||||||
|
} else if (index === "A" || worktree === "A") kind = "added";
|
||||||
|
else if (index === "D" || worktree === "D") kind = "deleted";
|
||||||
|
files.push({ path, index, worktree, kind });
|
||||||
|
}
|
||||||
|
return { isRepo: true, branch: br.out.trim() || undefined, files };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unified diff text; {tooLarge:true} when the diff is > 1MB
|
||||||
|
async diff(projectPath: string, p: string): Promise<{ diff?: string; tooLarge?: boolean; untracked?: boolean; error?: string }> {
|
||||||
|
const rel = insidePath(projectPath, p);
|
||||||
|
if (!rel) return { error: "路径不允许" };
|
||||||
|
// Check untracked first (git diff prints nothing for untracked files)
|
||||||
|
const ls = await runGit(projectPath, ["ls-files", "--error-unmatch", "--", rel]);
|
||||||
|
if (ls.code !== 0) {
|
||||||
|
// Untracked/not in the index: treat the whole file as added
|
||||||
|
const full = join(projectPath, rel);
|
||||||
|
if (!existsSync(full)) return { error: "文件不存在" };
|
||||||
|
const s = await stat(full);
|
||||||
|
if (!s.isFile()) return { error: "不是文件" };
|
||||||
|
if (s.size > DIFF_LIMIT) return { tooLarge: true };
|
||||||
|
const text = await readFile(full, "utf8").catch(() => null);
|
||||||
|
if (text === null) return { error: "二进制或无法读取" };
|
||||||
|
const lines = text.split("\n").map((l) => "+" + l).join("\n");
|
||||||
|
return { untracked: true, diff: `--- /dev/null\n+++ b/${rel}\n@@ -0,0 +1,${text.split("\n").length} @@\n${lines}` };
|
||||||
|
}
|
||||||
|
let d = await runGit(projectPath, ["diff", "--no-color", "--", rel]);
|
||||||
|
if (d.code !== 0) return { error: d.err.trim() || "diff 失败" };
|
||||||
|
if (!d.out.trim()) {
|
||||||
|
d = await runGit(projectPath, ["diff", "--cached", "--no-color", "--", rel]);
|
||||||
|
if (d.code !== 0) return { error: d.err.trim() || "diff 失败" };
|
||||||
|
}
|
||||||
|
if (d.out.length > DIFF_LIMIT) return { tooLarge: true };
|
||||||
|
return { diff: d.out };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tracked → git restore; untracked → move to trash/discarded/<ts>/<relpath>
|
||||||
|
async discard(projectPath: string, p: string, dataDir: string): Promise<{ ok: boolean; trashedTo?: string; error?: string }> {
|
||||||
|
const rel = insidePath(projectPath, p);
|
||||||
|
if (!rel) return { ok: false, error: "路径不允许" };
|
||||||
|
// Only discard a single file: an empty path / "." would make git restore act on the whole repository
|
||||||
|
if (rel === "." || rel === "" || rel === "./") return { ok: false, error: "路径不允许" };
|
||||||
|
const ls = await runGit(projectPath, ["ls-files", "--error-unmatch", "--", rel]);
|
||||||
|
if (ls.code === 0) {
|
||||||
|
let r = await runGit(projectPath, ["restore", "--staged", "--worktree", "--", rel]);
|
||||||
|
if (r.code !== 0) r = await runGit(projectPath, ["checkout", "--", rel]);
|
||||||
|
if (r.code !== 0) return { ok: false, error: r.err.trim() || "放弃失败" };
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
const full = join(projectPath, rel);
|
||||||
|
if (!existsSync(full)) return { ok: false, error: "文件不存在" };
|
||||||
|
const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
||||||
|
const dest = join(dataDir, "trash", "discarded", stamp, rel);
|
||||||
|
await mkdir(join(dest, ".."), { recursive: true });
|
||||||
|
try {
|
||||||
|
await moveAcrossDevices(full, dest);
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: "移动失败:" + String((e as Error)?.message ?? e) };
|
||||||
|
}
|
||||||
|
return { ok: true, trashedTo: dest };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
// Codex history import (§7.6): ~/.codex/sessions/**/rollout-*.jsonl
|
||||||
|
// Layout: session_meta (with cwd) → event_msg → response_item (message/function_call/...)
|
||||||
|
// Import only user messages (minus environment_context and similar wrappers) + the assistant's final reply text; tool steps become notices. Read-only throughout.
|
||||||
|
import { readdir, readFile, stat } from "node:fs/promises";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { samePath } from "../util/paths.js";
|
||||||
|
|
||||||
|
const CODEX_ROOT = join(homedir(), ".codex", "sessions");
|
||||||
|
|
||||||
|
type Rec = Record<string, unknown>;
|
||||||
|
const rec = (v: unknown): Rec => (v && typeof v === "object" ? (v as Rec) : {});
|
||||||
|
const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
|
||||||
|
|
||||||
|
// Environment wrappers in user messages: anything whose first line starts with <environment_context> or <user_instructions> isn't user input
|
||||||
|
const WRAPPERS = /^\s*<(environment_context|user_instructions|skills_instructions|permissions instructions)>/i;
|
||||||
|
|
||||||
|
function textOf(content: unknown, kind: string): string {
|
||||||
|
if (!Array.isArray(content)) return "";
|
||||||
|
return (content as Rec[])
|
||||||
|
.filter((p) => p.type === kind || p.type === "input_text" || p.type === "output_text")
|
||||||
|
.map((p) => str(p.text) ?? "")
|
||||||
|
.join("\n")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find rollout-*.jsonl recursively
|
||||||
|
async function* walk(dir: string, depth = 0): AsyncGenerator<string> {
|
||||||
|
if (depth > 6) return;
|
||||||
|
for (const name of await readdir(dir).catch(() => [] as string[])) {
|
||||||
|
const p = join(dir, name);
|
||||||
|
const s = await stat(p).catch(() => null);
|
||||||
|
if (!s) continue;
|
||||||
|
if (s.isDirectory()) yield* walk(p, depth + 1);
|
||||||
|
else if (/^rollout-.*\.jsonl$/.test(name)) yield p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CodexHistItem = { sessionId: string; title: string; updatedAt: number; messageCount: number };
|
||||||
|
|
||||||
|
export async function listCodexHistory(cwd: string): Promise<CodexHistItem[]> {
|
||||||
|
const out: CodexHistItem[] = [];
|
||||||
|
for await (const path of walk(CODEX_ROOT)) {
|
||||||
|
const m = /rollout-.*-([0-9a-f-]{36})\.jsonl$/i.exec(path);
|
||||||
|
const sessionId = m?.[1];
|
||||||
|
if (!sessionId) continue;
|
||||||
|
const text = await readFile(path, "utf8").catch(() => "");
|
||||||
|
let match = false;
|
||||||
|
let title = "";
|
||||||
|
let count = 0;
|
||||||
|
for (const line of text.split("\n")) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
let r: Rec;
|
||||||
|
try {
|
||||||
|
r = rec(JSON.parse(line));
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// session_meta records payload.cwd
|
||||||
|
if (r.type === "session_meta") {
|
||||||
|
const cwdInFile = str(rec(r.payload).cwd);
|
||||||
|
if (cwdInFile && samePath(cwdInFile, cwd)) match = true;
|
||||||
|
else break; // Not this project: stop reading
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!match) continue;
|
||||||
|
if (r.type === "response_item") {
|
||||||
|
const p = rec(r.payload);
|
||||||
|
if (p.type === "message" && p.role === "user") {
|
||||||
|
const t = textOf(p.content, "input_text");
|
||||||
|
if (t && !WRAPPERS.test(t)) {
|
||||||
|
count++;
|
||||||
|
if (!title) title = t.slice(0, 40);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!match) continue;
|
||||||
|
const s = await stat(path).catch(() => null);
|
||||||
|
out.push({ sessionId, title: title || "(无标题)", updatedAt: s ? Math.round(s.mtimeMs) : 0, messageCount: count });
|
||||||
|
}
|
||||||
|
out.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read one rollout → simplified events (user_message / assistant_message / notice for tool steps / turn_ended)
|
||||||
|
type CodexEv = {
|
||||||
|
type: string; text?: string; message?: string; itemId?: string; level?: string;
|
||||||
|
turnId?: string; status?: string;
|
||||||
|
};
|
||||||
|
export async function readCodexHistory(sessionId: string, cwd: string): Promise<CodexEv[]> {
|
||||||
|
const out: CodexEv[] = [];
|
||||||
|
let file: string | null = null;
|
||||||
|
for await (const p of walk(CODEX_ROOT)) {
|
||||||
|
if (p.endsWith(`${sessionId}.jsonl`)) { file = p; break; }
|
||||||
|
}
|
||||||
|
if (!file) return out;
|
||||||
|
const text = await readFile(file, "utf8").catch(() => "");
|
||||||
|
let matched = false;
|
||||||
|
let aid = 0;
|
||||||
|
// response_item.message and event_msg.item_completed duplicate each other → dedupe by text
|
||||||
|
const seenText = new Set<string>();
|
||||||
|
const pushText = (type: "user_message" | "assistant_message", t: string) => {
|
||||||
|
const key = type + ":" + t;
|
||||||
|
if (!t || seenText.has(key)) return;
|
||||||
|
seenText.add(key);
|
||||||
|
out.push(type === "user_message" ? { type, text: t } : { type, itemId: `imp_a${aid++}`, text: t });
|
||||||
|
};
|
||||||
|
for (const line of text.split("\n")) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
let r: Rec;
|
||||||
|
try {
|
||||||
|
r = rec(JSON.parse(line));
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (r.type === "session_meta") {
|
||||||
|
const c = str(rec(r.payload).cwd);
|
||||||
|
if (c && samePath(c, cwd)) matched = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!matched) continue;
|
||||||
|
// response_item message
|
||||||
|
if (r.type === "response_item") {
|
||||||
|
const p = rec(r.payload);
|
||||||
|
if (p.type === "message") {
|
||||||
|
const role = str(p.role);
|
||||||
|
const phase = str(p.phase);
|
||||||
|
if (role === "user") {
|
||||||
|
const t = textOf(p.content, "input_text");
|
||||||
|
if (t && !WRAPPERS.test(t)) pushText("user_message", t);
|
||||||
|
} else if (role === "assistant" && phase !== "commentary") {
|
||||||
|
const t = textOf(p.content, "output_text");
|
||||||
|
if (t) pushText("assistant_message", t);
|
||||||
|
}
|
||||||
|
} else if (p.type === "function_call" || p.type === "custom_tool_call") {
|
||||||
|
const name = str(p.name) ?? "tool";
|
||||||
|
out.push({ type: "notice", level: "info", message: `(历史)调用 ${name}` });
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// event_msg.item_completed: AgentMessage (Text content blocks) and task_complete.last_agent_message
|
||||||
|
if (r.type === "event_msg") {
|
||||||
|
const p = rec(r.payload);
|
||||||
|
if (p.type === "item_completed") {
|
||||||
|
const it = rec(p.item);
|
||||||
|
if (it.type === "AgentMessage" && it.phase !== "commentary") {
|
||||||
|
const t = textOf(it.content, "Text");
|
||||||
|
if (t) pushText("assistant_message", t);
|
||||||
|
} else if (it.type === "UserMessage") {
|
||||||
|
const t = textOf(it.content, "text");
|
||||||
|
if (t && !WRAPPERS.test(t)) pushText("user_message", t);
|
||||||
|
}
|
||||||
|
} else if (p.type === "task_complete") {
|
||||||
|
const last = str(p.last_agent_message);
|
||||||
|
if (last) pushText("assistant_message", last);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const p2 = rec(r.payload);
|
||||||
|
if (p2.type === "function_call" || p2.type === "custom_tool_call") {
|
||||||
|
// Tool steps collapse into a one-line notice (§7.6, Codex part)
|
||||||
|
const name = str(p2.name) ?? "tool";
|
||||||
|
out.push({ type: "notice", level: "info", message: `(历史)调用 ${name}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push({ type: "turn_ended", turnId: "import", status: "completed" });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// History import (§7.6): Claude sessions live in ~/.claude/projects/<encoded dir>/<sessionId>.jsonl.
|
||||||
|
// Don't guess the encoding rule: list every directory, read the first record with a cwd from each jsonl, match the project with samePath.
|
||||||
|
// Read-only throughout.
|
||||||
|
import { readdir, readFile, stat } from "node:fs/promises";
|
||||||
|
import { existsSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { samePath } from "../util/paths.js";
|
||||||
|
|
||||||
|
const CLAUDE_ROOT = join(homedir(), ".claude", "projects");
|
||||||
|
|
||||||
|
type Rec = Record<string, unknown>;
|
||||||
|
const rec = (v: unknown): Rec => (v && typeof v === "object" ? (v as Rec) : {});
|
||||||
|
const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
|
||||||
|
|
||||||
|
// One jsonl line → {cwd?, title?, isUserText}
|
||||||
|
function parseLine(line: string): { cwd?: string; userText?: string } | null {
|
||||||
|
let r: Rec;
|
||||||
|
try {
|
||||||
|
r = rec(JSON.parse(line));
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const cwd = str(r.cwd);
|
||||||
|
let userText: string | undefined;
|
||||||
|
if (r.type === "user") {
|
||||||
|
const content = rec(r.message).content;
|
||||||
|
if (typeof content === "string") userText = content;
|
||||||
|
else if (Array.isArray(content)) {
|
||||||
|
const t = content.map((p) => (rec(p).type === "text" ? str(rec(p).text) : undefined)).find(Boolean);
|
||||||
|
userText = t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { cwd, userText };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function* linesOf(path: string): AsyncGenerator<string> {
|
||||||
|
const text = await readFile(path, "utf8").catch(() => "");
|
||||||
|
for (const line of text.split("\n")) {
|
||||||
|
if (line.trim()) yield line;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Project cwd → that project's past sessions
|
||||||
|
export async function listClaudeHistory(cwd: string): Promise<{ sessionId: string; title: string; updatedAt: number; messageCount: number }[]> {
|
||||||
|
const out: { sessionId: string; title: string; updatedAt: number; messageCount: number }[] = [];
|
||||||
|
const dirs = await readdir(CLAUDE_ROOT).catch(() => [] as string[]);
|
||||||
|
for (const d of dirs) {
|
||||||
|
const dirPath = join(CLAUDE_ROOT, d);
|
||||||
|
const files = (await readdir(dirPath).catch(() => [] as string[])).filter((f) => f.endsWith(".jsonl"));
|
||||||
|
for (const f of files) {
|
||||||
|
const path = join(dirPath, f);
|
||||||
|
let match = false;
|
||||||
|
let title = "";
|
||||||
|
let count = 0;
|
||||||
|
for await (const line of linesOf(path)) {
|
||||||
|
const p = parseLine(line);
|
||||||
|
if (!p) continue;
|
||||||
|
if (!match) {
|
||||||
|
if (!p.cwd) continue;
|
||||||
|
match = samePath(p.cwd, cwd);
|
||||||
|
if (!match) break;
|
||||||
|
}
|
||||||
|
if (p.userText && !title) title = p.userText.slice(0, 40);
|
||||||
|
if (p.userText) count++;
|
||||||
|
}
|
||||||
|
if (!match) continue;
|
||||||
|
const s = await stat(path).catch(() => null);
|
||||||
|
out.push({
|
||||||
|
sessionId: f.replace(/\.jsonl$/, ""),
|
||||||
|
title: title || "(无标题)",
|
||||||
|
updatedAt: s ? Math.round(s.mtimeMs) : 0,
|
||||||
|
messageCount: count,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read one session's jsonl → SDK message shape (so mapSdkMessage can be reused)
|
||||||
|
export async function readClaudeHistory(sessionId: string, cwd: string): Promise<Rec[]> {
|
||||||
|
const dirs = await readdir(CLAUDE_ROOT).catch(() => [] as string[]);
|
||||||
|
for (const d of dirs) {
|
||||||
|
const path = join(CLAUDE_ROOT, d, `${sessionId}.jsonl`);
|
||||||
|
if (!existsSync(path)) continue;
|
||||||
|
// Confirm it belongs to this project (the first cwd record matches)
|
||||||
|
const msgs: Rec[] = [];
|
||||||
|
let matched = false;
|
||||||
|
for await (const line of linesOf(path)) {
|
||||||
|
const p = parseLine(line);
|
||||||
|
if (!matched) {
|
||||||
|
if (p?.cwd && samePath(p.cwd, cwd)) matched = true;
|
||||||
|
else continue;
|
||||||
|
}
|
||||||
|
let r: Rec;
|
||||||
|
try {
|
||||||
|
r = rec(JSON.parse(line));
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Keep only user/assistant/result — same shape as the SDK's streamed messages, so mapSdkMessage can digest them
|
||||||
|
if (r.type === "user" || r.type === "assistant") msgs.push(r);
|
||||||
|
}
|
||||||
|
return msgs;
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
// HTTP routes: / → app/index.html (no token), static assets, /api/ping, /api/upload, /attachments/*
|
||||||
|
import { createServer, type IncomingMessage, type ServerResponse, type Server } from "node:http";
|
||||||
|
import { readFile, stat } from "node:fs/promises";
|
||||||
|
import { existsSync } from "node:fs";
|
||||||
|
import { join, normalize, extname } from "node:path";
|
||||||
|
import { checkHost, classifyOrigin, tokenEqual } from "./security.js";
|
||||||
|
import type { Config } from "./config.js";
|
||||||
|
import type { AttachmentStore } from "./store/attachments.js";
|
||||||
|
import { log } from "./log.js";
|
||||||
|
|
||||||
|
const MIME: Record<string, string> = {
|
||||||
|
".html": "text/html; charset=utf-8",
|
||||||
|
".js": "text/javascript; charset=utf-8",
|
||||||
|
".css": "text/css; charset=utf-8",
|
||||||
|
".svg": "image/svg+xml",
|
||||||
|
".png": "image/png",
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".jpeg": "image/jpeg",
|
||||||
|
".gif": "image/gif",
|
||||||
|
".webp": "image/webp",
|
||||||
|
".woff2": "font/woff2",
|
||||||
|
".map": "application/json",
|
||||||
|
".json": "application/json; charset=utf-8",
|
||||||
|
};
|
||||||
|
|
||||||
|
const MAX_UPLOAD = 50 * 1024 * 1024; // 50MB
|
||||||
|
const MAX_MSG = 200 * 1024; // Ordinary messages: 200KB
|
||||||
|
|
||||||
|
export type HttpHooks = {
|
||||||
|
onUpgrade?: (req: IncomingMessage, socket: import("node:net").Socket, head: Buffer) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
// A malformed %xx must not become a 500
|
||||||
|
function safeDecode(s: string): string | null {
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(s);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(res: ServerResponse, code: number, body: string | Buffer, headers: Record<string, string> = {}): void {
|
||||||
|
res.writeHead(code, headers);
|
||||||
|
res.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendJson(res: ServerResponse, code: number, obj: unknown, headers: Record<string, string> = {}): void {
|
||||||
|
send(res, code, JSON.stringify(obj), { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...headers });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Common headers for static responses: no caching (the page has no token, but don't let old versions linger), no sniffing, no Referer
|
||||||
|
const STATIC_HEADERS: Record<string, string> = {
|
||||||
|
"cache-control": "no-store",
|
||||||
|
"x-content-type-options": "nosniff",
|
||||||
|
"referrer-policy": "no-referrer",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createHttpServer(cfg: Config, appDir: string, attachments: AttachmentStore, hooks: HttpHooks = {}): Server {
|
||||||
|
const server = createServer(async (req, res) => {
|
||||||
|
try {
|
||||||
|
await route(req, res);
|
||||||
|
} catch (e) {
|
||||||
|
log("error", "HTTP 处理异常", { url: req.url, err: String(e) });
|
||||||
|
if (!res.headersSent) sendJson(res, 500, { ok: false, e: { code: "internal", message: "服务内部错误" } });
|
||||||
|
else res.end();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Origin policy per request (see classifyOrigin in security.ts):
|
||||||
|
// foreign (another site) → always 403, even with a token
|
||||||
|
// opaque (Origin: null) → may only "present" the token on token routes (/api/*, /attachments/*);
|
||||||
|
// it confers no trust by itself. Static routes are always refused.
|
||||||
|
// none / self → static routes allowed (static files contain no token); token routes still need the token.
|
||||||
|
// The CORS header is only given (as null) on responses that carry a valid token + Origin: null; preflight only for /api/upload.
|
||||||
|
async function route(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||||
|
// Host must be loopback + this process's actual port: blocks DNS rebinding (a rebound page's GET carries no Origin)
|
||||||
|
const hostCheck = checkHost(req.headers.host, cfg.port);
|
||||||
|
if (!hostCheck.ok) {
|
||||||
|
sendJson(res, hostCheck.code, { ok: false, e: { code: "bad_host", message: hostCheck.message } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const origin = classifyOrigin(req.headers.origin, cfg.port);
|
||||||
|
if (origin === "foreign") {
|
||||||
|
sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: "来源不允许" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL(req.url ?? "/", `http://127.0.0.1:${cfg.port}`);
|
||||||
|
const pathname = url.pathname;
|
||||||
|
const isApi = pathname.startsWith("/api/");
|
||||||
|
const isAttachment = pathname.startsWith("/attachments/");
|
||||||
|
|
||||||
|
// OPTIONS preflight: browsers don't send custom headers on a preflight, so there is no token here.
|
||||||
|
// Only allow /api/upload, the one cross-origin POST the frontend really makes, and only for null / our own origin;
|
||||||
|
// the preflight itself returns no data, and the real request still has to pass the token check.
|
||||||
|
if (req.method === "OPTIONS") {
|
||||||
|
if (pathname !== "/api/upload" || origin === "none") {
|
||||||
|
sendJson(res, 403, { ok: false, e: { code: "bad_preflight", message: "预检不允许" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
send(res, 204, "", {
|
||||||
|
"access-control-allow-origin": origin === "opaque" ? "null" : `http://127.0.0.1:${cfg.port}`,
|
||||||
|
"access-control-allow-headers": "x-agent-console, content-type",
|
||||||
|
"access-control-allow-methods": "GET, POST, OPTIONS",
|
||||||
|
"access-control-max-age": "600",
|
||||||
|
vary: "origin",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Token routes: the token is the only authorization
|
||||||
|
if (isApi || isAttachment) {
|
||||||
|
const headerToken = req.headers["x-agent-console"];
|
||||||
|
// Attachments accept ?t= (<img src> can't send custom headers); the API only accepts the header
|
||||||
|
const queryToken = isAttachment ? url.searchParams.get("t") : null;
|
||||||
|
const validToken =
|
||||||
|
(typeof headerToken === "string" && tokenEqual(headerToken, cfg.token)) ||
|
||||||
|
(typeof queryToken === "string" && tokenEqual(queryToken, cfg.token));
|
||||||
|
if (!validToken) {
|
||||||
|
sendJson(res, 403, { ok: false, e: { code: "bad_token", message: "令牌无效" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// In a sandbox iframe (no allow-same-origin) the page's origin is null, so even a same-address fetch is cross-origin:
|
||||||
|
// the response needs allow-origin: null to be readable. It's only sent after the token is verified,
|
||||||
|
// so any Origin: null page without the token can read nothing.
|
||||||
|
if (origin === "opaque") {
|
||||||
|
res.setHeader("access-control-allow-origin", "null");
|
||||||
|
res.setHeader("vary", "origin");
|
||||||
|
}
|
||||||
|
if (isApi) {
|
||||||
|
await routeApi(req, res, pathname, url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const id = safeDecode(pathname.slice("/attachments/".length));
|
||||||
|
const a = id === null ? null : await attachments.get(id);
|
||||||
|
if (!a) {
|
||||||
|
sendJson(res, 404, { ok: false, e: { code: "not_found", message: "附件不存在" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await attachments.read(a.id);
|
||||||
|
send(res, 200, data ?? Buffer.alloc(0), { ...STATIC_HEADERS, "content-type": a.mime });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Static assets: refuse Origin: null. Ordinary navigations and <script src>/<link> subresource requests carry no Origin;
|
||||||
|
// one with null can only be someone else's sandboxed/data:/file: page doing a fetch — give it nothing, and no CORS headers.
|
||||||
|
if (origin === "opaque") {
|
||||||
|
sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: "来源不允许" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||||
|
sendJson(res, 405, { ok: false, e: { code: "method", message: "方法不允许" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (pathname === "/" || pathname === "/index.html") {
|
||||||
|
// The token is no longer injected into the page: the plugin gate hands it to the frontend in the #t= fragment (see lib/gate.mjs)
|
||||||
|
try {
|
||||||
|
const html = await readFile(join(appDir, "index.html"), "utf8");
|
||||||
|
send(res, 200, html, { ...STATIC_HEADERS, "content-type": "text/html; charset=utf-8" });
|
||||||
|
} catch {
|
||||||
|
send(res, 503, "app 还没构建(缺 app/index.html)", { ...STATIC_HEADERS, "content-type": "text/plain; charset=utf-8" });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Other static files must be inside app/
|
||||||
|
const decoded = safeDecode(pathname);
|
||||||
|
if (decoded === null) {
|
||||||
|
sendJson(res, 400, { ok: false, e: { code: "bad_path", message: "路径不合法" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rel = normalize(decoded).replace(/^([\\/])+/, "");
|
||||||
|
const full = normalize(join(appDir, rel));
|
||||||
|
if (!full.startsWith(normalize(appDir)) || rel.includes("..")) {
|
||||||
|
sendJson(res, 403, { ok: false, e: { code: "bad_path", message: "路径不允许" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!existsSync(full) || !(await stat(full)).isFile()) {
|
||||||
|
sendJson(res, 404, { ok: false, e: { code: "not_found", message: "文件不存在" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await readFile(full);
|
||||||
|
send(res, 200, data, { ...STATIC_HEADERS, "content-type": MIME[extname(full).toLowerCase()] ?? "application/octet-stream" });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function routeApi(req: IncomingMessage, res: ServerResponse, pathname: string, url: URL): Promise<void> {
|
||||||
|
if (pathname === "/api/ping" && req.method === "GET") {
|
||||||
|
sendJson(res, 200, { ok: true, version: cfg.version, port: cfg.port, pid: process.pid, dataDir: cfg.dataDir, buildStamp: cfg.buildStamp });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (pathname === "/api/upload" && req.method === "POST") {
|
||||||
|
const name = url.searchParams.get("name") ?? "";
|
||||||
|
if (!attachments.allowedExt(name)) {
|
||||||
|
sendJson(res, 400, { ok: false, e: { code: "bad_type", message: "不支持的文件类型" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The declared size is already over the limit: reject without reading the body
|
||||||
|
const declared = Number(req.headers["content-length"] ?? 0);
|
||||||
|
if (declared > MAX_UPLOAD) {
|
||||||
|
res.setHeader("connection", "close");
|
||||||
|
sendJson(res, 413, { ok: false, e: { code: "too_large", message: "文件太大(上限 50MB)" } });
|
||||||
|
req.resume();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
let size = 0;
|
||||||
|
for await (const c of req) {
|
||||||
|
const b = c as Buffer;
|
||||||
|
size += b.length;
|
||||||
|
if (size > MAX_UPLOAD) {
|
||||||
|
res.setHeader("connection", "close");
|
||||||
|
sendJson(res, 413, { ok: false, e: { code: "too_large", message: "文件太大(上限 50MB)" } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chunks.push(b);
|
||||||
|
}
|
||||||
|
const a = await attachments.save(name, Buffer.concat(chunks));
|
||||||
|
sendJson(res, 200, { ok: true, id: a.id, name: a.name, mime: a.mime, size: a.size });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sendJson(res, 404, { ok: false, e: { code: "not_found", message: "接口不存在" } });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hooks.onUpgrade) {
|
||||||
|
server.on("upgrade", hooks.onUpgrade);
|
||||||
|
}
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { sendJson, MAX_MSG };
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
// Simple logging: writes dataDir/logs/daemon-YYYY-MM-DD.log (kept 7 days) and to the console.
|
||||||
|
import { appendFileSync, mkdirSync, readdirSync, rmSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
let logDir = "";
|
||||||
|
let today = "";
|
||||||
|
let logFile = "";
|
||||||
|
|
||||||
|
function fileName(d: Date): string {
|
||||||
|
const p = (n: number) => String(n).padStart(2, "0");
|
||||||
|
return `daemon-${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}.log`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initLog(dataDir: string): void {
|
||||||
|
logDir = join(dataDir, "logs");
|
||||||
|
mkdirSync(logDir, { recursive: true });
|
||||||
|
// Keep 7 days
|
||||||
|
try {
|
||||||
|
const keep = new Set<string>();
|
||||||
|
const now = new Date();
|
||||||
|
for (let i = 0; i < 7; i++) {
|
||||||
|
keep.add(fileName(new Date(now.getTime() - i * 86400000)));
|
||||||
|
}
|
||||||
|
for (const f of readdirSync(logDir)) {
|
||||||
|
if (/^daemon-\d{4}-\d{2}-\d{2}\.log$/.test(f) && !keep.has(f)) {
|
||||||
|
rmSync(join(logDir, f), { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function log(level: "info" | "warn" | "error", msg: string, extra?: unknown): void {
|
||||||
|
const line = `[${new Date().toISOString()}] [${level}] ${msg}${extra !== undefined ? " " + safeJson(extra) : ""}`;
|
||||||
|
try {
|
||||||
|
const d = new Date();
|
||||||
|
const name = fileName(d);
|
||||||
|
if (name !== today && logDir) {
|
||||||
|
today = name;
|
||||||
|
logFile = join(logDir, name);
|
||||||
|
}
|
||||||
|
if (logFile) appendFileSync(logFile, line + "\n", "utf8");
|
||||||
|
} catch {}
|
||||||
|
const fn = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
|
||||||
|
fn(`[agent-console] ${msg}`, extra !== undefined ? extra : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeJson(v: unknown): string {
|
||||||
|
try {
|
||||||
|
return JSON.stringify(v);
|
||||||
|
} catch {
|
||||||
|
return String(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
// Daemon entry: parse arguments, initialize services, start HTTP+WS, write daemon.json, handle exit.
|
||||||
|
import { mkdirSync, existsSync, rmSync, chmodSync } from "node:fs";
|
||||||
|
import { join, dirname } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { parseConfig } from "./config.js";
|
||||||
|
import { initLog, log } from "./log.js";
|
||||||
|
import { createHttpServer } from "./http.js";
|
||||||
|
import { AttachmentStore } from "./store/attachments.js";
|
||||||
|
import { SettingsStore } from "./store/settings.js";
|
||||||
|
import { ProjectsStore } from "./store/projects.js";
|
||||||
|
import { ThreadsStore } from "./store/threads.js";
|
||||||
|
import { Gateway } from "./ws/gateway.js";
|
||||||
|
import { registerMethods } from "./ws/methods.js";
|
||||||
|
import { writeJsonAtomic } from "./util/atomic.js";
|
||||||
|
import { initProviders } from "./providers/registry.js";
|
||||||
|
import { AgentManager } from "./agents/manager.js";
|
||||||
|
import { GitService } from "./git/service.js";
|
||||||
|
import { FileService } from "./files/service.js";
|
||||||
|
import { TerminalService } from "./terminal/service.js";
|
||||||
|
import { augmentPath, pidAlive } from "./util/proc.js";
|
||||||
|
|
||||||
|
// The bundle targets node20: an older Node (or being started by Bun by mistake) gets a clear message instead of crashing on some API
|
||||||
|
const nodeMajor = Number(/^v?(\d+)/.exec(process.versions.node ?? "")?.[1] ?? 0);
|
||||||
|
if (nodeMajor < 20) {
|
||||||
|
console.error(`[agent-console] 需要 Node.js 20 或更高版本,当前 ${process.version}(${process.execPath})`);
|
||||||
|
process.exit(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent CLI .js entries and the Claude SDK look up "node" by name; GUI apps launched from the macOS Dock get a minimal PATH,
|
||||||
|
// so append the current node's directory and common install directories to PATH (existing order unchanged)
|
||||||
|
process.env.PATH = augmentPath(process.env, dirname(process.execPath));
|
||||||
|
|
||||||
|
const cfg = parseConfig(process.argv.slice(2));
|
||||||
|
|
||||||
|
// Top-level safety net: log, don't exit
|
||||||
|
process.on("uncaughtException", (e) => {
|
||||||
|
log("error", "uncaughtException", { err: String(e?.stack ?? e) });
|
||||||
|
});
|
||||||
|
process.on("unhandledRejection", (e) => {
|
||||||
|
log("error", "unhandledRejection", { err: String(e) });
|
||||||
|
});
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
initLog(cfg.dataDir);
|
||||||
|
for (const d of ["threads", "attachments", "trash", "logs"]) {
|
||||||
|
mkdirSync(join(cfg.dataDir, d), { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const appDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "app");
|
||||||
|
const attachments = new AttachmentStore(join(cfg.dataDir, "attachments"));
|
||||||
|
const { bindAttachmentStore } = await import("./util/attachmentRefs.js");
|
||||||
|
bindAttachmentStore(attachments);
|
||||||
|
const settings = new SettingsStore(cfg.dataDir);
|
||||||
|
const projects = new ProjectsStore(cfg.dataDir);
|
||||||
|
const threads = new ThreadsStore(cfg.dataDir);
|
||||||
|
const gateway = new Gateway(cfg);
|
||||||
|
|
||||||
|
initProviders(cfg.version);
|
||||||
|
// Legacy data migration (§10.1): runs once, skipped after v1Migrated; old files are read-only
|
||||||
|
const { migrateLegacy } = await import("./migrate/legacy.js");
|
||||||
|
try {
|
||||||
|
await migrateLegacy(cfg.dataDir, { settings, projects, threads });
|
||||||
|
} catch (e) {
|
||||||
|
log("error", "旧数据迁移失败", { err: String(e) });
|
||||||
|
}
|
||||||
|
const manager = new AgentManager(gateway, threads, projects, settings, attachments);
|
||||||
|
await manager.recoverOnStart();
|
||||||
|
const terminals = new TerminalService(gateway);
|
||||||
|
registerMethods(gateway, {
|
||||||
|
cfg,
|
||||||
|
settings,
|
||||||
|
gateway,
|
||||||
|
projects,
|
||||||
|
threads,
|
||||||
|
manager,
|
||||||
|
git: new GitService(),
|
||||||
|
files: new FileService(),
|
||||||
|
terminals,
|
||||||
|
runtime: (id) => manager.runtimeInfo(id),
|
||||||
|
});
|
||||||
|
|
||||||
|
const server = createHttpServer(cfg, appDir, attachments, {
|
||||||
|
onUpgrade: (req, socket, head) => gateway.handleUpgrade(req, socket, head),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Retry 5 times if the port is in use
|
||||||
|
let attempts = 0;
|
||||||
|
await new Promise<void>((resolveListen, rejectListen) => {
|
||||||
|
const tryListen = () => {
|
||||||
|
attempts++;
|
||||||
|
server.once("error", (e: NodeJS.ErrnoException) => {
|
||||||
|
if (e.code === "EADDRINUSE" && attempts < 6) {
|
||||||
|
log("warn", `端口 ${cfg.port} 被占用,500ms 后重试(第 ${attempts} 次)`);
|
||||||
|
setTimeout(tryListen, 500);
|
||||||
|
} else {
|
||||||
|
rejectListen(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
server.listen(cfg.port, "127.0.0.1");
|
||||||
|
};
|
||||||
|
server.once("listening", () => resolveListen());
|
||||||
|
tryListen();
|
||||||
|
}).catch((e) => {
|
||||||
|
log("error", `端口 ${cfg.port} 无法监听`, { err: String(e) });
|
||||||
|
process.exit(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --port 0: after listening on a random port, write the actual port back into cfg.port. Host/Origin checks read cfg.port,
|
||||||
|
// and no request can arrive before this (listen has only just completed), so there is no window checking against the old port.
|
||||||
|
const bound = server.address();
|
||||||
|
if (bound && typeof bound === "object") cfg.port = bound.port;
|
||||||
|
// Ready line: the plugin host reads this line from stdout to learn the actual port (port and pid only, no token)
|
||||||
|
process.stdout.write(JSON.stringify({ agentConsoleReady: true, port: cfg.port, pid: process.pid }) + "\n");
|
||||||
|
// Background warm-up: after start, pull detection/models for enabled providers into the cache so the first page open doesn't wait
|
||||||
|
void (async () => {
|
||||||
|
const { warmProviderCache } = await import("./providers/warm.js");
|
||||||
|
await warmProviderCache(await settings.get());
|
||||||
|
})().catch((e) => log("warn", "Provider 预热失败", { err: String(e) }));
|
||||||
|
|
||||||
|
const daemonJsonPath = join(cfg.dataDir, "daemon.json");
|
||||||
|
await writeJsonAtomic(daemonJsonPath, {
|
||||||
|
pid: process.pid,
|
||||||
|
port: cfg.port,
|
||||||
|
token: cfg.token,
|
||||||
|
version: cfg.version,
|
||||||
|
buildStamp: cfg.buildStamp,
|
||||||
|
startedAt: Date.now(),
|
||||||
|
});
|
||||||
|
chmodSync(daemonJsonPath, 0o600);
|
||||||
|
log("info", `daemon 已启动 端口 ${cfg.port} 数据目录 ${cfg.dataDir} 版本 ${cfg.version} pid ${process.pid}`);
|
||||||
|
// Standalone dev mode: print the open URL with the token to the console (console only, never the log file)
|
||||||
|
if (!cfg.parentPid) console.log(`[agent-console] 打开 http://127.0.0.1:${cfg.port}/#t=${cfg.token}`);
|
||||||
|
|
||||||
|
// Idle exit: check every minute; no WS connection + no running conversation + no open terminal → exit after idleExitMinutes
|
||||||
|
let idleSince = Date.now();
|
||||||
|
setInterval(() => {
|
||||||
|
const busy = gateway.connectionCount > 0 || manager.anyBusy() || terminals.count > 0;
|
||||||
|
if (busy) idleSince = Date.now();
|
||||||
|
if (Date.now() - idleSince > cfg.idleExitMinutes * 60 * 1000) {
|
||||||
|
log("info", "空闲超时,daemon 退出");
|
||||||
|
shutdown(0);
|
||||||
|
}
|
||||||
|
}, 60 * 1000).unref();
|
||||||
|
|
||||||
|
let shuttingDown = false;
|
||||||
|
function shutdown(code: number): void {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
shuttingDown = true;
|
||||||
|
log("info", "daemon 关闭中");
|
||||||
|
terminals.killAll();
|
||||||
|
gateway.closeAll();
|
||||||
|
try {
|
||||||
|
rmSync(daemonJsonPath, { force: true });
|
||||||
|
} catch {}
|
||||||
|
// Wait for Agent sessions to close cleanly (at most 2.5 s) before exiting; process trees still alive are cleaned up by util/bin's exit hook
|
||||||
|
const sessionsClosed = Promise.race([manager.shutdown(), new Promise((r) => setTimeout(r, 2500))]);
|
||||||
|
void sessionsClosed.then(() => server.close(() => process.exit(code)));
|
||||||
|
setTimeout(() => process.exit(code), 4000).unref();
|
||||||
|
}
|
||||||
|
process.on("SIGINT", () => shutdown(0));
|
||||||
|
process.on("SIGTERM", () => shutdown(0));
|
||||||
|
// Lifeline: when spawned by the plugin host (Magpie's Bun plugin process) we get --parent-pid, and stdin is a pipe the host holds.
|
||||||
|
// Host exits (normally or killed) → pipe closes → stdin end/close → exit;
|
||||||
|
// also check every 2 seconds whether the parent is still alive, in case stdin was inherited by another process and never closed.
|
||||||
|
// Not enabled in standalone dev mode (npm run dev, no --parent-pid); there we rely on idle exit only.
|
||||||
|
if (cfg.parentPid) {
|
||||||
|
const parentPid = cfg.parentPid;
|
||||||
|
const parentWatch = setInterval(() => {
|
||||||
|
if (!pidAlive(parentPid)) {
|
||||||
|
clearInterval(parentWatch);
|
||||||
|
log("info", `父进程 ${parentPid} 已退出,daemon 跟随退出`);
|
||||||
|
shutdown(0);
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
|
parentWatch.unref();
|
||||||
|
process.stdin.on("end", () => shutdown(0));
|
||||||
|
process.stdin.on("close", () => shutdown(0));
|
||||||
|
process.stdin.on("error", () => shutdown(0));
|
||||||
|
process.stdin.resume();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error("[agent-console] 启动失败", e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
// Legacy data migration (§10.1): runs once when the daemon starts.
|
||||||
|
// Old: sessions/<id>/{meta.json,events.jsonl} + projects in settings.json →
|
||||||
|
// New: projects.json + threads/<id>/{meta.json,timeline.jsonl}. Old files are read-only and copied to trash/legacy-<ts>/ as a backup.
|
||||||
|
import { cp, mkdir, readdir, readFile } from "node:fs/promises";
|
||||||
|
import { existsSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { SettingsStore } from "../store/settings.js";
|
||||||
|
import type { ProjectsStore } from "../store/projects.js";
|
||||||
|
import type { ThreadsStore, ThreadMeta } from "../store/threads.js";
|
||||||
|
import type { Mode, TimelineEvent } from "../timeline/types.js";
|
||||||
|
import { appendJsonl } from "../util/jsonl.js";
|
||||||
|
import { writeJsonAtomic } from "../util/atomic.js";
|
||||||
|
import { validId } from "../util/paths.js";
|
||||||
|
import { log } from "../log.js";
|
||||||
|
|
||||||
|
type OldMeta = {
|
||||||
|
id: string; agent: string; cwd: string; model: string; permission: string;
|
||||||
|
title: string; titleAuto: boolean; pinned: boolean; cliSessionId: string | null;
|
||||||
|
created: number; updated: number; lastStatus?: string; totalCost?: number; totalUsage?: { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number } | null;
|
||||||
|
};
|
||||||
|
type OldEvt = Record<string, unknown> & { type: string; seq?: number; ts?: number };
|
||||||
|
|
||||||
|
const SKIP_TITLE = /^\/(slow|deny|error|long|codex)/;
|
||||||
|
const MODE_MAP: Record<string, Mode> = {
|
||||||
|
plan: "plan", default: "default", acceptEdits: "acceptEdits", bypassPermissions: "bypassPermissions",
|
||||||
|
auto: "acceptEdits", full: "bypassPermissions",
|
||||||
|
};
|
||||||
|
const belongsTo = (cwd: string, parent: string) => {
|
||||||
|
const c = cwd.replace(/\\/g, "/").toLowerCase().replace(/\/+$/, "");
|
||||||
|
const p = parent.replace(/\\/g, "/").toLowerCase().replace(/\/+$/, "");
|
||||||
|
return c === p || c.startsWith(p + "/");
|
||||||
|
};
|
||||||
|
|
||||||
|
function stamp(): string {
|
||||||
|
const d = new Date();
|
||||||
|
const p = (n: number) => String(n).padStart(2, "0");
|
||||||
|
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function migrateLegacy(dataDir: string, stores: {
|
||||||
|
settings: SettingsStore; projects: ProjectsStore; threads: ThreadsStore;
|
||||||
|
}): Promise<{ migrated: number; skipped: boolean }> {
|
||||||
|
const settings = await stores.settings.get();
|
||||||
|
if (settings.v1Migrated) return { migrated: 0, skipped: true };
|
||||||
|
const oldDir = join(dataDir, "sessions");
|
||||||
|
const oldSettingsPath = join(dataDir, "settings.json");
|
||||||
|
if (!existsSync(oldDir) && !existsSync(oldSettingsPath)) {
|
||||||
|
await stores.settings.set({ v1Migrated: true });
|
||||||
|
return { migrated: 0, skipped: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Backup
|
||||||
|
const backup = join(dataDir, "trash", `legacy-${stamp()}`);
|
||||||
|
await mkdir(backup, { recursive: true });
|
||||||
|
if (existsSync(oldDir)) await cp(oldDir, join(backup, "sessions"), { recursive: true }).catch(() => {});
|
||||||
|
if (existsSync(oldSettingsPath)) await cp(oldSettingsPath, join(backup, "settings.json")).catch(() => {});
|
||||||
|
|
||||||
|
// Read the old settings (read the file directly; SettingsStore already loaded the same path, the fields coexist without conflict)
|
||||||
|
const oldSettings = existsSync(oldSettingsPath)
|
||||||
|
? (JSON.parse(await readFile(oldSettingsPath, "utf8").catch(() => "{}")) as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
|
||||||
|
// 2. Projects: old settings.projects → projects.json; orphan cwds are added per the adoptOrphans rule
|
||||||
|
const projectIdByPath = new Map<string, string>();
|
||||||
|
const lc = (p: string) => p.replace(/\\/g, "/").toLowerCase().replace(/\/+$/, "");
|
||||||
|
for (const p of (oldSettings.projects as { name?: string; path?: string }[] | undefined) ?? []) {
|
||||||
|
if (!p?.path) continue;
|
||||||
|
try {
|
||||||
|
const proj = await stores.projects.create(p.path, p.name);
|
||||||
|
projectIdByPath.set(lc(proj.path), proj.id);
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "迁移:建项目失败", { path: p.path, err: String(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old session list
|
||||||
|
let sessionIds: string[] = [];
|
||||||
|
try {
|
||||||
|
sessionIds = (await readdir(oldDir)).filter((d) => validId(d) && existsSync(join(oldDir, d, "meta.json")));
|
||||||
|
} catch {}
|
||||||
|
const metas: OldMeta[] = [];
|
||||||
|
for (const id of sessionIds) {
|
||||||
|
try {
|
||||||
|
const m = JSON.parse(await readFile(join(oldDir, id, "meta.json"), "utf8")) as OldMeta;
|
||||||
|
if (m?.cwd) metas.push(m);
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
// Orphan cwd → add a project (subdirectories fold into their parent)
|
||||||
|
const extraDirs: string[] = [];
|
||||||
|
const projPaths = [...projectIdByPath.keys()];
|
||||||
|
for (const m of metas) {
|
||||||
|
const covered = projPaths.some((pp) => belongsTo(m.cwd, pp)) || extraDirs.some((d) => belongsTo(m.cwd, d));
|
||||||
|
if (covered) continue;
|
||||||
|
for (let i = extraDirs.length - 1; i >= 0; i--) if (belongsTo(extraDirs[i], m.cwd)) extraDirs.splice(i, 1);
|
||||||
|
extraDirs.push(m.cwd);
|
||||||
|
}
|
||||||
|
for (const d of extraDirs) {
|
||||||
|
if (!existsSync(d)) continue; // Skip directories that no longer exist (same as the old adoptOrphans)
|
||||||
|
try {
|
||||||
|
const name = d.replace(/\\/g, "/").split("/").filter(Boolean).pop() ?? d;
|
||||||
|
const proj = await stores.projects.create(d, name);
|
||||||
|
projectIdByPath.set(lc(proj.path), proj.id);
|
||||||
|
projPaths.push(lc(proj.path));
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "迁移:补建孤儿项目失败", { path: d, err: String(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectOf = (cwd: string): string | null => {
|
||||||
|
const l = lc(cwd);
|
||||||
|
// Take the longest match (a subdirectory joins the most specific project)
|
||||||
|
let best: string | null = null;
|
||||||
|
for (const [pp, id] of projectIdByPath) {
|
||||||
|
if (belongsTo(l, pp) && (best == null || pp.length > best.length)) best = pp;
|
||||||
|
}
|
||||||
|
return best ? projectIdByPath.get(best)! : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 3. Sessions
|
||||||
|
let migrated = 0;
|
||||||
|
const threadsDir = join(dataDir, "threads");
|
||||||
|
for (const m of metas) {
|
||||||
|
try {
|
||||||
|
const projectId = projectOf(m.cwd);
|
||||||
|
if (!projectId) { log("warn", "迁移:无项目可归,跳过", { id: m.id, cwd: m.cwd }); continue; }
|
||||||
|
const testTitle = SKIP_TITLE.test(m.title ?? "") || m.title === "默认剧本演示";
|
||||||
|
const provider = m.agent === "claude" || m.agent === "codex" ? m.agent : "mock";
|
||||||
|
const archived = testTitle || (m.agent !== "claude" && m.agent !== "codex");
|
||||||
|
const now = Date.now();
|
||||||
|
const meta: ThreadMeta = {
|
||||||
|
id: `t_${m.id.replace(/^s?_?/, "")}`.slice(0, 80),
|
||||||
|
projectId,
|
||||||
|
title: m.title || "旧对话",
|
||||||
|
titleAuto: false,
|
||||||
|
provider,
|
||||||
|
model: m.model || null,
|
||||||
|
mode: MODE_MAP[m.permission] ?? "default",
|
||||||
|
effort: null,
|
||||||
|
providerSessionId: m.cliSessionId || null,
|
||||||
|
status: "closed",
|
||||||
|
pinned: !!m.pinned,
|
||||||
|
archived,
|
||||||
|
createdAt: m.created || now,
|
||||||
|
updatedAt: m.updated || now,
|
||||||
|
lastTurnStatus: m.lastStatus === "ok" ? "completed" : m.lastStatus === "error" ? "failed" : null,
|
||||||
|
usage: {
|
||||||
|
inputTokens: m.totalUsage?.inputTokens ?? 0,
|
||||||
|
outputTokens: m.totalUsage?.outputTokens ?? 0,
|
||||||
|
cacheReadTokens: m.totalUsage?.cacheReadTokens ?? 0,
|
||||||
|
costUsd: m.totalCost ?? 0,
|
||||||
|
},
|
||||||
|
importedFrom: m.cliSessionId ? { provider, sessionId: m.cliSessionId } : undefined,
|
||||||
|
seq: 0,
|
||||||
|
};
|
||||||
|
const tdir = join(threadsDir, meta.id);
|
||||||
|
if (existsSync(tdir)) meta.id = `t_${m.id}_v1`.slice(0, 80);
|
||||||
|
await mkdir(join(threadsDir, meta.id), { recursive: true });
|
||||||
|
|
||||||
|
// Event mapping
|
||||||
|
const oldEvts = (await readFile(join(oldDir, m.id, "events.jsonl"), "utf8").catch(() => ""))
|
||||||
|
.split("\n").filter((l) => l.trim())
|
||||||
|
.map((l) => { try { return JSON.parse(l) as OldEvt; } catch { return null; } })
|
||||||
|
.filter((x): x is OldEvt => !!x);
|
||||||
|
const lines: TimelineEvent[] = [];
|
||||||
|
const openTools = new Map<string, { kind: string; title: string; input?: unknown; detail?: unknown }>();
|
||||||
|
let seq = 0;
|
||||||
|
const push = (ev: Record<string, unknown> & { type: TimelineEvent["type"] }) => {
|
||||||
|
seq++;
|
||||||
|
lines.push({ ...ev, seq, ts: Date.now(), threadId: meta.id } as TimelineEvent);
|
||||||
|
};
|
||||||
|
for (const e of oldEvts) {
|
||||||
|
switch (e.type) {
|
||||||
|
case "user": push({ type: "user_message", text: String(e.text ?? "") }); break;
|
||||||
|
case "text": push({ type: "assistant_message", itemId: `lg_${seq}`, text: String(e.text ?? "") }); break;
|
||||||
|
case "thinking": push({ type: "reasoning", itemId: `lg_${seq}`, text: String(e.text ?? "") }); break;
|
||||||
|
case "tool.call": {
|
||||||
|
const key = String(e.itemId ?? e.callId ?? `c${seq}`);
|
||||||
|
openTools.set(key, { kind: String(e.kind ?? "other"), title: String(e.title ?? e.kind ?? "工具"), input: e.input, detail: e.detail });
|
||||||
|
push({ type: "tool_call", itemId: key, kind: "other", title: String(e.title ?? "工具"), status: "running", input: e.input, detail: e.detail });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "tool.result": {
|
||||||
|
const key = String(e.itemId ?? e.callId ?? `c${seq}`);
|
||||||
|
const open = openTools.get(key);
|
||||||
|
openTools.delete(key);
|
||||||
|
push({
|
||||||
|
type: "tool_call", itemId: key,
|
||||||
|
kind: (open?.kind ?? "other") as import("../timeline/types.js").ToolKind,
|
||||||
|
title: open?.title ?? "工具",
|
||||||
|
status: e.ok === false || e.error ? "failed" : "ok",
|
||||||
|
output: typeof e.output === "string" ? e.output.slice(0, 20000) : undefined,
|
||||||
|
detail: open?.detail,
|
||||||
|
} as Record<string, unknown> & { type: "tool_call" });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "todo": {
|
||||||
|
const items = (e.items as { text?: string; status?: string }[] | undefined) ?? [];
|
||||||
|
push({ type: "todo", items: items.map((i) => ({ text: String(i.text ?? ""), status: i.status === "done" ? "done" : i.status === "in_progress" ? "in_progress" : "todo" })) });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "permission.denied": push({ type: "notice", level: "warn", message: `已拒绝:${String(e.title ?? e.kind ?? "")}` }); break;
|
||||||
|
case "permission.request": case "permission.resolved": break; // Old permission cards are stale; don't recreate them
|
||||||
|
case "notice": push({ type: "notice", level: (e.level as "info" | "warn" | "error") ?? "info", message: String(e.message ?? "") }); break;
|
||||||
|
case "run.end": {
|
||||||
|
const u = e.usage as { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number } | undefined;
|
||||||
|
if (u) push({ type: "usage", turnId: `lg_t${seq}`, inputTokens: u.inputTokens ?? 0, outputTokens: u.outputTokens ?? 0, cacheReadTokens: u.cacheReadTokens ?? 0, costUsd: (e.costUsd as number) ?? 0 });
|
||||||
|
push({ type: "turn_ended", turnId: `lg_t${seq}`, status: e.status === "error" ? "failed" : e.status === "interrupted" ? "interrupted" : "completed", durationMs: (e.ms as number) ?? undefined, error: e.error as string | undefined });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "run.start": break;
|
||||||
|
case "init": break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Unclosed tool.call → mark failed
|
||||||
|
for (const [key, o] of openTools) {
|
||||||
|
seq++;
|
||||||
|
lines.push({ type: "tool_call", itemId: key, kind: "other", title: o.title, status: "failed", seq, ts: Date.now(), threadId: meta.id } as TimelineEvent);
|
||||||
|
}
|
||||||
|
for (const ev of lines) await appendJsonl(join(threadsDir, meta.id, "timeline.jsonl"), ev);
|
||||||
|
meta.seq = seq;
|
||||||
|
await writeJsonAtomic(join(threadsDir, meta.id, "meta.json"), meta);
|
||||||
|
migrated++;
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "迁移:会话失败", { id: m.id, err: String(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Merge settings (UI preference fields only)
|
||||||
|
const patch: Record<string, unknown> = { v1Migrated: true };
|
||||||
|
if (typeof oldSettings.theme === "string") patch.theme = oldSettings.theme;
|
||||||
|
if (typeof oldSettings.sendKey === "string") patch.sendKey = oldSettings.sendKey;
|
||||||
|
if (typeof oldSettings.showThinking === "boolean") patch.showThinking = oldSettings.showThinking;
|
||||||
|
if (typeof oldSettings.defaultAgent === "string") patch.defaultProvider = oldSettings.defaultAgent === "claude" || oldSettings.defaultAgent === "codex" ? oldSettings.defaultAgent : "claude";
|
||||||
|
if (typeof oldSettings.defaultPermission === "string") patch.defaultMode = MODE_MAP[oldSettings.defaultPermission] ?? "default";
|
||||||
|
await stores.settings.set(patch);
|
||||||
|
|
||||||
|
log("info", `旧数据迁移完成:${migrated} 个会话、${projectIdByPath.size} 个项目,备份在 ${backup}`);
|
||||||
|
return { migrated, skipped: false };
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import type { ModelInfo } from "../types.js";
|
||||||
|
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
|
||||||
|
|
||||||
|
export function runCli(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 25000): Promise<string> {
|
||||||
|
return new Promise((resolvePromise, reject) => {
|
||||||
|
let out = "";
|
||||||
|
const p = spawnBin(r, args, { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
void killTree(p, { graceMs: 500 }); // On Windows a .cmd wrapper must be killed together with its child processes
|
||||||
|
} catch {}
|
||||||
|
reject(new Error("timeout"));
|
||||||
|
}, timeoutMs);
|
||||||
|
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.on("error", reject);
|
||||||
|
p.on("close", () => {
|
||||||
|
clearTimeout(t);
|
||||||
|
resolvePromise(out);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** devin models list: indented lines are model ids followed by the display name */
|
||||||
|
export function parseDevinModelsList(text: string): ModelInfo[] {
|
||||||
|
const models: ModelInfo[] = [];
|
||||||
|
for (const line of text.split(/\r?\n/)) {
|
||||||
|
const m = line.match(/^\s{2,}([a-z0-9][a-z0-9-]*)\s{2,}(.+?)(?:\s+\[|$)/i);
|
||||||
|
if (!m) continue;
|
||||||
|
const id = m[1].trim();
|
||||||
|
if (id === "aliases" || id.startsWith("aliases:")) continue;
|
||||||
|
const name = m[2].trim();
|
||||||
|
if (!id || id.length < 3) continue;
|
||||||
|
models.push({ id, name });
|
||||||
|
}
|
||||||
|
if (!models.length) return [{ id: "default", name: "默认", isDefault: true }];
|
||||||
|
const adaptive = models.find((x) => x.id === "adaptive");
|
||||||
|
if (adaptive) adaptive.isDefault = true;
|
||||||
|
else models[0]!.isDefault = true;
|
||||||
|
return models;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** opencode models: one provider/model-id per line */
|
||||||
|
export function parseOpencodeModels(text: string): ModelInfo[] {
|
||||||
|
const models: ModelInfo[] = [];
|
||||||
|
for (const line of text.split(/\r?\n/)) {
|
||||||
|
const id = line.trim();
|
||||||
|
if (!id || /\s/.test(id) || id.startsWith("Usage:")) continue;
|
||||||
|
if (!id.includes("/")) continue;
|
||||||
|
const name = id.includes("/") ? id.split("/").slice(1).join("/") : id;
|
||||||
|
models.push({ id, name: name.replace(/-/g, " ") });
|
||||||
|
}
|
||||||
|
if (!models.length) return [{ id: "default", name: "默认", isDefault: true }];
|
||||||
|
models[0]!.isDefault = true;
|
||||||
|
return models;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function devinListModels(r: ResolveResult & { ok: true }): Promise<ModelInfo[]> {
|
||||||
|
const text = await runCli(r, ["models", "list"], 35000);
|
||||||
|
return parseDevinModelsList(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function opencodeListModels(r: ResolveResult & { ok: true }): Promise<ModelInfo[]> {
|
||||||
|
const text = await runCli(r, ["models"], 20000);
|
||||||
|
return parseOpencodeModels(text);
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { readFile, writeFile } from "node:fs/promises";
|
||||||
|
import type { ClientApp } from "@agentclientprotocol/sdk";
|
||||||
|
import { methods } from "@agentclientprotocol/sdk";
|
||||||
|
import type { RespondAnswer } from "../types.js";
|
||||||
|
import type { ProviderEvent } from "../../timeline/types.js";
|
||||||
|
|
||||||
|
export type PermBridge = {
|
||||||
|
push(ev: ProviderEvent): void;
|
||||||
|
waitFor(requestId: string): Promise<RespondAnswer>;
|
||||||
|
/** Cursor Auto-review: no permission card, allow is chosen automatically */
|
||||||
|
autoAcceptPermissions?: () => boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function registerAcpClientHandlers(app: ClientApp, bridge: PermBridge): void {
|
||||||
|
app.onRequest(methods.client.fs.readTextFile, async (ctx) => {
|
||||||
|
const text = await readFile(ctx.params.path, "utf8");
|
||||||
|
return { content: text };
|
||||||
|
});
|
||||||
|
app.onRequest(methods.client.fs.writeTextFile, async (ctx) => {
|
||||||
|
await writeFile(ctx.params.path, ctx.params.content, "utf8");
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
app.onRequest(methods.client.session.requestPermission, async (ctx) => {
|
||||||
|
const tc = ctx.params.toolCall;
|
||||||
|
const options = ctx.params.options.map((o) => ({
|
||||||
|
id: o.optionId,
|
||||||
|
label: o.name,
|
||||||
|
kind: o.kind,
|
||||||
|
}));
|
||||||
|
if (bridge.autoAcceptPermissions?.()) {
|
||||||
|
const allow =
|
||||||
|
options.find((o) => o.kind === "allow_once" || o.kind === "allow_always") ?? options[0];
|
||||||
|
if (allow) return { outcome: { outcome: "selected", optionId: allow.id } };
|
||||||
|
}
|
||||||
|
const requestId = "p" + Math.random().toString(36).slice(2, 10);
|
||||||
|
bridge.push({
|
||||||
|
type: "permission_request",
|
||||||
|
requestId,
|
||||||
|
title: tc.title ?? tc.name ?? "需要授权",
|
||||||
|
kind: tc.kind ?? "tool",
|
||||||
|
detail: tc.rawInput ?? undefined,
|
||||||
|
options,
|
||||||
|
});
|
||||||
|
const answer = await bridge.waitFor(requestId);
|
||||||
|
if (answer.cancelled) return { outcome: { outcome: "cancelled" } };
|
||||||
|
const optionId = answer.optionId ?? options[0]?.id;
|
||||||
|
if (!optionId) return { outcome: { outcome: "cancelled" } };
|
||||||
|
return { outcome: { outcome: "selected", optionId } };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import type { ModelInfo } from "../types.js";
|
||||||
|
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
|
||||||
|
|
||||||
|
function runCmd(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 20000): Promise<string> {
|
||||||
|
return new Promise((resolvePromise, reject) => {
|
||||||
|
let out = "";
|
||||||
|
const p = spawnBin(r, args, { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
void killTree(p, { graceMs: 500 }); // On Windows a .cmd wrapper must be killed together with its child processes
|
||||||
|
} catch {}
|
||||||
|
reject(new Error("timeout"));
|
||||||
|
}, timeoutMs);
|
||||||
|
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.on("error", reject);
|
||||||
|
p.on("close", () => {
|
||||||
|
clearTimeout(t);
|
||||||
|
resolvePromise(out);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseCursorListModels(text: string): ModelInfo[] {
|
||||||
|
const models: ModelInfo[] = [];
|
||||||
|
for (const line of text.split(/\r?\n/)) {
|
||||||
|
const t = line.trim();
|
||||||
|
if (!t || t.startsWith("Available") || t.startsWith("Tip:")) continue;
|
||||||
|
const m = t.match(/^(\S+)\s+-\s+(.+)$/);
|
||||||
|
if (!m) continue;
|
||||||
|
const id = m[1];
|
||||||
|
const rest = m[2];
|
||||||
|
const isDefault = /\(default\)/i.test(rest);
|
||||||
|
const isCurrent = /\(current\)/i.test(rest);
|
||||||
|
const name = rest.replace(/\s*\((default|current)\)\s*/gi, "").trim();
|
||||||
|
models.push({ id, name, isDefault: isDefault || id === "auto", ...(isCurrent ? {} : {}) });
|
||||||
|
}
|
||||||
|
if (!models.length) return [{ id: "auto", name: "Auto", isDefault: true }];
|
||||||
|
if (!models.some((x) => x.isDefault)) {
|
||||||
|
const auto = models.find((x) => x.id === "auto");
|
||||||
|
if (auto) auto.isDefault = true;
|
||||||
|
}
|
||||||
|
return models;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cursor CLI: Fast toggle → model parameter string (see --model 'id[fast=true]') */
|
||||||
|
// Model values come from the options Cursor reports over ACP, e.g. `claude-opus-5-5[context=300k,effort=medium,fast=false]`:
|
||||||
|
// without Fast, send them back unchanged (keeping context/effort and other parameters); with Fast, change only the fast parameter.
|
||||||
|
// When a thinking level is chosen, write it as that model's own level parameter (e.g. grok-4.6[effort=high], gpt-5.6-sol[reasoning=max]).
|
||||||
|
export function cursorWireModel(
|
||||||
|
modelId: string | null,
|
||||||
|
fast: boolean,
|
||||||
|
thinking?: { param: string; value: string },
|
||||||
|
): string | null {
|
||||||
|
if (!modelId) return null;
|
||||||
|
const id = modelId.trim();
|
||||||
|
if (!fast && !thinking) return id;
|
||||||
|
const m = id.match(/^(.*?)\[(.*)\]$/u);
|
||||||
|
if (!m && !thinking) return id.endsWith("-fast") ? id : `${id}[fast=true]`;
|
||||||
|
const base = m ? m[1] : id;
|
||||||
|
const params = (m ? m[2].split(",") : [])
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter((s) => s && (!fast || !/^fast=/.test(s)) && (!thinking || !s.startsWith(`${thinking.param}=`)));
|
||||||
|
if (thinking) params.push(`${thinking.param}=${thinking.value}`);
|
||||||
|
if (fast) params.push("fast=true");
|
||||||
|
return `${base}[${params.join(",")}]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cursorListModels(r: ResolveResult & { ok: true }): Promise<ModelInfo[]> {
|
||||||
|
const text = await runCmd(r, ["--list-models"]);
|
||||||
|
return parseCursorListModels(text);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// dsh (DeepSeek Harness) over ACP: start it on the model the conversation uses, so it can take images.
|
||||||
|
//
|
||||||
|
// dsh decides at ACP initialize whether it accepts image blocks, from the route in its `acp` config row
|
||||||
|
// (`dsh-acp`'s supportsAcpImagePrompts), not from the session's model. That row ships as
|
||||||
|
// deepseek-official / deepseek-v4-flash, which isn't in dsh's own catalog (deepseek-flash is) and isn't a
|
||||||
|
// route Magpie writes (Magpie writes `agent-default-model` and its `magpie*` routes, not the `acp` row).
|
||||||
|
// So dsh 0.2.1-rc.5 / 0.2.2-alpha.2 answer promptCapabilities.image: false and then refuse every image
|
||||||
|
// block ("inline image prompts were not advertised by this connection"), even on a model that sees images.
|
||||||
|
//
|
||||||
|
// The launcher takes `--patch <file>` overlays, applied after the profile and home patches. We start dsh
|
||||||
|
// with one that sets the `acp` row to the conversation's route ([provider, model], the value dsh's ACP model
|
||||||
|
// option uses). dsh then advertises image input exactly when that route declares it (a Magpie model it can
|
||||||
|
// see images with is written as `input: [text, image]`) and passes the image to the model.
|
||||||
|
// A model picked later in the same session goes by path: dsh's read_image tool opens it on a model that sees images.
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { mkdir, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
export const DSH_ACP_ARGS = ["--profile", "acp"];
|
||||||
|
|
||||||
|
export type DshRoute = { provider: string; model: string };
|
||||||
|
|
||||||
|
/** dsh's ACP model value is JSON [provider, model]; anything else isn't a route */
|
||||||
|
export function dshRoute(model: string | null | undefined): DshRoute | null {
|
||||||
|
if (!model) return null;
|
||||||
|
try {
|
||||||
|
const v = JSON.parse(model) as unknown;
|
||||||
|
if (Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "string" && v[0] && v[1]) {
|
||||||
|
return { provider: v[0], model: v[1] };
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* not a dsh route */
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The patch list that starts dsh's ACP on this route (JSON strings are valid YAML double-quoted scalars) */
|
||||||
|
export function dshRoutePatch(route: DshRoute): string {
|
||||||
|
return [
|
||||||
|
"# Agent Console: the route dsh's ACP starts on, so initialize advertises image input for it",
|
||||||
|
"- id: acp",
|
||||||
|
" config:",
|
||||||
|
` provider: ${JSON.stringify(route.provider)}`,
|
||||||
|
` model: ${JSON.stringify(route.model)}`,
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Arguments for `dsh`: the ACP profile, plus a --patch overlay naming the route when the model is one */
|
||||||
|
export async function dshAcpArgs(model: string | null | undefined, dir = join(tmpdir(), "agent-console-dsh")): Promise<string[]> {
|
||||||
|
const route = dshRoute(model);
|
||||||
|
if (!route) return [...DSH_ACP_ARGS];
|
||||||
|
const body = dshRoutePatch(route);
|
||||||
|
const file = join(dir, `acp-route-${createHash("sha256").update(body).digest("hex").slice(0, 16)}.yml`);
|
||||||
|
await mkdir(dir, { recursive: true });
|
||||||
|
await writeFile(file, body, { mode: 0o600 });
|
||||||
|
return [...DSH_ACP_ARGS, "--patch", file];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The route a new dsh conversation starts on, as the manager picks it: a Magpie route first, else dsh's current one */
|
||||||
|
export function dshDefaultModel(models: { id: string }[], current: string | null): string | null {
|
||||||
|
return models.find((m) => /magpie/i.test(m.id))?.id ?? current ?? models[0]?.id ?? null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import type * as schema from "@agentclientprotocol/sdk";
|
||||||
|
import type { ProviderEvent } from "../../timeline/types.js";
|
||||||
|
import type { ToolKind } from "../../timeline/types.js";
|
||||||
|
|
||||||
|
const rid = () => Math.random().toString(36).slice(2, 8);
|
||||||
|
|
||||||
|
function mapToolKind(k: schema.ToolKind | null | undefined): ToolKind {
|
||||||
|
switch (k) {
|
||||||
|
case "read":
|
||||||
|
case "edit":
|
||||||
|
case "search":
|
||||||
|
return k;
|
||||||
|
case "execute":
|
||||||
|
return "bash";
|
||||||
|
case "fetch":
|
||||||
|
return "web";
|
||||||
|
default:
|
||||||
|
return "other";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapToolStatus(s: schema.ToolCallStatus | null | undefined): "running" | "ok" | "failed" {
|
||||||
|
if (s === "completed") return "ok";
|
||||||
|
if (s === "failed") return "failed";
|
||||||
|
return "running";
|
||||||
|
}
|
||||||
|
|
||||||
|
function textFromContent(content: schema.ContentBlock): string {
|
||||||
|
if (content.type === "text") return content.text;
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MapCtx = { itemPrefix: string; messageIds: Map<string, string> };
|
||||||
|
|
||||||
|
export function newMapCtx(): MapCtx {
|
||||||
|
return { itemPrefix: "a" + rid() + "_", messageIds: new Map() };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapSessionUpdate(update: schema.SessionUpdate, ctx: MapCtx): ProviderEvent[] {
|
||||||
|
const out: ProviderEvent[] = [];
|
||||||
|
const mid = "messageId" in update && update.messageId ? String(update.messageId) : null;
|
||||||
|
|
||||||
|
switch (update.sessionUpdate) {
|
||||||
|
case "agent_message_chunk": {
|
||||||
|
const text = textFromContent(update.content);
|
||||||
|
if (!text) break;
|
||||||
|
const itemId = mid ? ctx.messageIds.get(mid) ?? ctx.itemPrefix + mid : ctx.itemPrefix + "msg";
|
||||||
|
if (mid) ctx.messageIds.set(mid, itemId);
|
||||||
|
out.push({ type: "assistant_delta", itemId, text });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "agent_thought_chunk": {
|
||||||
|
const text = textFromContent(update.content);
|
||||||
|
if (!text) break;
|
||||||
|
const itemId = mid ? ctx.itemPrefix + "t_" + mid : ctx.itemPrefix + "think";
|
||||||
|
out.push({ type: "reasoning_delta", itemId, text });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "tool_call":
|
||||||
|
out.push({
|
||||||
|
type: "tool_call",
|
||||||
|
itemId: ctx.itemPrefix + update.toolCallId,
|
||||||
|
kind: mapToolKind(update.kind),
|
||||||
|
title: update.title,
|
||||||
|
status: mapToolStatus(update.status),
|
||||||
|
input: update.rawInput,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "tool_call_update":
|
||||||
|
out.push({
|
||||||
|
type: "tool_call",
|
||||||
|
itemId: ctx.itemPrefix + update.toolCallId,
|
||||||
|
kind: mapToolKind(update.kind),
|
||||||
|
title: update.title ?? update.name ?? "tool",
|
||||||
|
status: mapToolStatus(update.status),
|
||||||
|
input: update.rawInput,
|
||||||
|
output: typeof update.rawOutput === "string" ? update.rawOutput : undefined,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "plan":
|
||||||
|
out.push({
|
||||||
|
type: "plan",
|
||||||
|
itemId: ctx.itemPrefix + "plan",
|
||||||
|
markdown: update.entries.map((e) => `- ${e.content}`).join("\n"),
|
||||||
|
entries: update.entries.map((e) => ({ step: e.content, status: e.status ?? "" })),
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "notice":
|
||||||
|
out.push({
|
||||||
|
type: "notice",
|
||||||
|
level: update.severity === "error" ? "error" : update.severity === "warning" ? "warn" : "info",
|
||||||
|
message: update.description ? `${update.title}: ${update.description}` : update.title,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "usage_update":
|
||||||
|
out.push({
|
||||||
|
type: "usage",
|
||||||
|
inputTokens: update.used,
|
||||||
|
outputTokens: 0,
|
||||||
|
cacheReadTokens: 0,
|
||||||
|
costUsd: typeof update.cost?.amount === "number" ? update.cost.amount : 0,
|
||||||
|
contextWindow: update.size,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stopToTurnEnd(stopReason: schema.StopReason, turnId: string, err?: string): ProviderEvent {
|
||||||
|
if (stopReason === "cancelled") {
|
||||||
|
return { type: "turn_ended", turnId, status: "interrupted" };
|
||||||
|
}
|
||||||
|
if (stopReason === "refusal" || stopReason === "max_tokens") {
|
||||||
|
return { type: "turn_ended", turnId, status: "failed", error: err ?? stopReason };
|
||||||
|
}
|
||||||
|
return { type: "turn_ended", turnId, status: "completed" };
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
// ACP probe: start the Agent's ACP process once → initialize → session/new, read the models and thinking levels it reports, then close it.
|
||||||
|
// Sends no prompt and costs nothing. This is the Agent's own model list (as Paseo does), more reliable than parsing CLI text.
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import type { ModelInfo } from "../types.js";
|
||||||
|
import type { ResolveResult } from "../../util/bin.js";
|
||||||
|
import { spawnResolved, killAcpChild } from "./spawn.js";
|
||||||
|
import { log } from "../../log.js";
|
||||||
|
import { promptCapsFromInitialize, rememberPromptCaps, type AcpPromptCaps } from "./promptCaps.js";
|
||||||
|
import { DSH_ACP_ARGS, dshAcpArgs, dshDefaultModel, dshRoute } from "./dsh.js";
|
||||||
|
|
||||||
|
type SelectOption = { value?: unknown; name?: unknown; options?: SelectOption[] };
|
||||||
|
type ConfigOption = { id?: string; category?: string; type?: string; currentValue?: unknown; options?: SelectOption[] };
|
||||||
|
|
||||||
|
export type AcpProbeResult = {
|
||||||
|
models: { id: string; name: string }[];
|
||||||
|
currentModel: string | null;
|
||||||
|
thinking: { id: string; label: string }[];
|
||||||
|
currentThinking: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function flatten(opts: SelectOption[] | undefined): { id: string; name: string }[] {
|
||||||
|
const out: { id: string; name: string }[] = [];
|
||||||
|
for (const o of opts ?? []) {
|
||||||
|
if (o.options) out.push(...flatten(o.options));
|
||||||
|
else if (typeof o.value === "string" && o.value) {
|
||||||
|
out.push({ id: o.value, name: typeof o.name === "string" && o.name ? o.name : o.value });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Dedupe (Copilot reports auto twice)
|
||||||
|
return out.filter((m, i) => out.findIndex((x) => x.id === m.id) === i);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Extract models and thinking levels from a session/new response (pure function, easy to test) */
|
||||||
|
export function parseAcpSession(res: { configOptions?: ConfigOption[]; models?: { currentModelId?: string; availableModels?: { modelId?: string; name?: string }[] } }): AcpProbeResult {
|
||||||
|
const opts = res.configOptions ?? [];
|
||||||
|
const modelOpt = opts.find((o) => o.type === "select" && (o.category === "model" || o.id === "model"));
|
||||||
|
const thoughtOpt = opts.find((o) => o.type === "select" && (o.category === "thought_level" || o.id === "thought_level"));
|
||||||
|
let models = flatten(modelOpt?.options);
|
||||||
|
let currentModel = typeof modelOpt?.currentValue === "string" ? modelOpt.currentValue : null;
|
||||||
|
if (!models.length && res.models?.availableModels?.length) {
|
||||||
|
models = res.models.availableModels
|
||||||
|
.filter((m) => typeof m.modelId === "string" && m.modelId)
|
||||||
|
.map((m) => ({ id: m.modelId!, name: m.name || m.modelId! }));
|
||||||
|
models = models.filter((m, i) => models.findIndex((x) => x.id === m.id) === i);
|
||||||
|
currentModel = res.models.currentModelId ?? currentModel;
|
||||||
|
}
|
||||||
|
const thinking = flatten(thoughtOpt?.options).map((t) => ({ id: t.id, label: t.name }));
|
||||||
|
const currentThinking = typeof thoughtOpt?.currentValue === "string" ? thoughtOpt.currentValue : null;
|
||||||
|
return { models, currentModel, thinking, currentThinking };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** providerId: remember what the Agent's initialize advertised for prompts (images) under this id */
|
||||||
|
export function probeAcp(r: ResolveResult & { ok: true }, acpArgs: string[], timeoutMs = 30000, providerId?: string): Promise<AcpProbeResult> {
|
||||||
|
return probeAcpRaw(r, acpArgs, timeoutMs).then((x) => {
|
||||||
|
rememberPromptCaps(providerId, x.promptCaps);
|
||||||
|
return x.parsed;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Like probeAcp, but also calls an Agent-specific method after session/new (e.g. Cursor's cursor/list_available_models) */
|
||||||
|
export function probeAcpRaw(
|
||||||
|
r: ResolveResult & { ok: true },
|
||||||
|
acpArgs: string[],
|
||||||
|
timeoutMs = 30000,
|
||||||
|
extMethod?: string,
|
||||||
|
): Promise<{ parsed: AcpProbeResult; ext: unknown; promptCaps: AcpPromptCaps }> {
|
||||||
|
return new Promise((resolvePromise, reject) => {
|
||||||
|
const child = spawnResolved(r, acpArgs, { cwd: tmpdir() });
|
||||||
|
let buf = "";
|
||||||
|
let nextId = 0;
|
||||||
|
const pending = new Map<number, { res: (v: unknown) => void; rej: (e: Error) => void }>();
|
||||||
|
let done = false;
|
||||||
|
const finish = (err: Error | null, v?: { parsed: AcpProbeResult; ext: unknown; promptCaps: AcpPromptCaps }) => {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
void killAcpChild(child).catch(() => {});
|
||||||
|
if (err) reject(err);
|
||||||
|
else resolvePromise(v!);
|
||||||
|
};
|
||||||
|
const timer = setTimeout(() => finish(new Error("ACP 探测超时")), timeoutMs);
|
||||||
|
const send = (method: string, params: unknown) =>
|
||||||
|
new Promise<unknown>((res, rej) => {
|
||||||
|
const id = ++nextId;
|
||||||
|
pending.set(id, { res, rej });
|
||||||
|
child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
|
||||||
|
});
|
||||||
|
child.on("error", (e) => finish(e));
|
||||||
|
child.on("close", () => finish(new Error("ACP 进程提前退出")));
|
||||||
|
child.stderr?.on("data", () => {});
|
||||||
|
child.stdout?.on("data", (d: Buffer) => {
|
||||||
|
buf += d.toString();
|
||||||
|
let n: number;
|
||||||
|
while ((n = buf.indexOf("\n")) >= 0) {
|
||||||
|
const line = buf.slice(0, n).trim();
|
||||||
|
buf = buf.slice(n + 1);
|
||||||
|
if (!line) continue;
|
||||||
|
let m: { id?: number; method?: string; result?: unknown; error?: unknown };
|
||||||
|
try {
|
||||||
|
m = JSON.parse(line);
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (m.id !== undefined && !m.method && pending.has(m.id)) {
|
||||||
|
const p = pending.get(m.id)!;
|
||||||
|
pending.delete(m.id);
|
||||||
|
if (m.error) p.rej(new Error(JSON.stringify(m.error)));
|
||||||
|
else p.res(m.result);
|
||||||
|
} else if (m.id !== undefined && m.method) {
|
||||||
|
// Requests from the Agent (shouldn't happen during a probe): always answer empty so it doesn't hang
|
||||||
|
child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", id: m.id, result: null }) + "\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const init = await send("initialize", { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "Agent Console", version: "probe" } });
|
||||||
|
const res = (await send("session/new", { cwd: tmpdir(), mcpServers: [] })) as Parameters<typeof parseAcpSession>[0];
|
||||||
|
let ext: unknown = null;
|
||||||
|
if (extMethod) ext = await send(extMethod, {}).catch(() => null);
|
||||||
|
finish(null, { parsed: parseAcpSession(res ?? {}), ext, promptCaps: promptCapsFromInitialize(init) });
|
||||||
|
} catch (e) {
|
||||||
|
finish(e instanceof Error ? e : new Error(String(e)));
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Probe result → model list: the current model is the default; thinking levels hang on the current model (other models' levels are only known after switching, so reuse the same set for now) */
|
||||||
|
export function probeToModels(p: AcpProbeResult): ModelInfo[] {
|
||||||
|
return p.models.map((m) => ({
|
||||||
|
id: m.id,
|
||||||
|
name: m.name,
|
||||||
|
isDefault: m.id === p.currentModel,
|
||||||
|
...(p.thinking.length
|
||||||
|
? { thinkingOptions: p.thinking, defaultThinking: p.currentThinking ?? undefined }
|
||||||
|
: {}),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
const EFFORT_LABEL: Record<string, string> = {
|
||||||
|
none: "None", minimal: "Minimal", low: "Low", medium: "Medium", high: "High", xhigh: "Extra High", max: "Max",
|
||||||
|
};
|
||||||
|
|
||||||
|
type CursorCatalog = {
|
||||||
|
models?: { value?: string; name?: string; configOptions?: ConfigOption[] }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cursor: a model's thinking levels are not in the session-level thought_level but in each model's own parameter (effort / reasoning_effort / reasoning).
|
||||||
|
* Following Paseo's resolveCursorCatalogModels: call Cursor's extension method cursor/list_available_models to get each model's parameter definitions.
|
||||||
|
* The model id is the base name without parameters (grok-4.6); thinkingParam records the level parameter name, sent as grok-4.6[effort=high].
|
||||||
|
*/
|
||||||
|
export function cursorCatalogToModels(catalog: CursorCatalog, currentModel: string | null): ModelInfo[] {
|
||||||
|
const currentBase = currentModel?.replace(/\[.*\]$/u, "") ?? null;
|
||||||
|
const out: ModelInfo[] = [];
|
||||||
|
for (const m of catalog.models ?? []) {
|
||||||
|
if (typeof m.value !== "string" || !m.value) continue;
|
||||||
|
const id = m.value.replace(/\[.*\]$/u, "");
|
||||||
|
const thought = (m.configOptions ?? []).find((o) => o.category === "thought_level");
|
||||||
|
const levels = flatten(thought?.options);
|
||||||
|
out.push({
|
||||||
|
id,
|
||||||
|
name: typeof m.name === "string" && m.name ? m.name : id,
|
||||||
|
isDefault: id === currentBase,
|
||||||
|
...(thought && levels.length
|
||||||
|
? {
|
||||||
|
thinkingOptions: levels.map((l) => ({ id: l.id, label: EFFORT_LABEL[l.id] ?? l.name })),
|
||||||
|
defaultThinking: typeof thought.currentValue === "string" ? thought.currentValue : undefined,
|
||||||
|
thinkingParam: thought.id,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cursorProbeModels(acpArgs: string[], providerId?: string) {
|
||||||
|
return async (r: ResolveResult & { ok: true }): Promise<ModelInfo[]> => {
|
||||||
|
try {
|
||||||
|
const { parsed, ext, promptCaps } = await probeAcpRaw(r, acpArgs, 40000, "cursor/list_available_models");
|
||||||
|
rememberPromptCaps(providerId, promptCaps);
|
||||||
|
const fromCatalog = ext ? cursorCatalogToModels(ext as CursorCatalog, parsed.currentModel) : [];
|
||||||
|
// If the extension method is unavailable (older Cursor CLI), fall back to the model list reported by the session (no levels)
|
||||||
|
return fromCatalog.length ? fromCatalog : probeToModels(parsed);
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "Cursor 模型探测失败", { err: String(e) });
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* dsh: the model list from a plain `dsh --profile acp`, then whether it takes images from an initialize started on the
|
||||||
|
* route a new conversation uses (dsh answers for the route it starts on, see dsh.ts).
|
||||||
|
*/
|
||||||
|
export function dshProbeModels(providerId?: string) {
|
||||||
|
return async (r: ResolveResult & { ok: true }): Promise<ModelInfo[]> => {
|
||||||
|
try {
|
||||||
|
const first = await probeAcpRaw(r, DSH_ACP_ARGS, 30000);
|
||||||
|
let caps = first.promptCaps;
|
||||||
|
const start = dshDefaultModel(first.parsed.models, first.parsed.currentModel);
|
||||||
|
if (start && start !== first.parsed.currentModel && dshRoute(start)) {
|
||||||
|
caps = await probeAcpRaw(r, await dshAcpArgs(start), 30000).then((x) => x.promptCaps, () => caps);
|
||||||
|
}
|
||||||
|
rememberPromptCaps(providerId, caps);
|
||||||
|
return probeToModels(first.parsed);
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "ACP 探测模型失败", { err: String(e) });
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function acpProbeModels(acpArgs: string[], providerId?: string) {
|
||||||
|
return async (r: ResolveResult & { ok: true }): Promise<ModelInfo[]> => {
|
||||||
|
try {
|
||||||
|
return probeToModels(await probeAcp(r, acpArgs, 30000, providerId));
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "ACP 探测模型失败", { err: String(e) });
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// Turn one user message (text + attachments) into an ACP prompt (ContentBlock[]) for what this Agent accepts.
|
||||||
|
// - PNG/JPEG/GIF/WebP: an image block (base64 + mimeType) when the Agent advertises promptCapabilities.image;
|
||||||
|
// otherwise the saved file's absolute path, as a resource_link (ACP baseline) and as a line of text,
|
||||||
|
// so an Agent with file tools can still open it; the caller shows a notice that it can't see the image.
|
||||||
|
// - audio/* : an audio block when promptCapabilities.audio, else the same path fallback.
|
||||||
|
// - text : an embedded resource (its text) when promptCapabilities.embeddedContext and small enough, else a path.
|
||||||
|
// Every attachment is either sent or named by path: nothing is dropped silently.
|
||||||
|
import type { ContentBlock } from "@agentclientprotocol/sdk";
|
||||||
|
import { readFile, stat } from "node:fs/promises";
|
||||||
|
import { basename } from "node:path";
|
||||||
|
import { pathToFileURL } from "node:url";
|
||||||
|
import { resolveImagePath } from "../../util/attachmentRefs.js";
|
||||||
|
import type { AcpPromptCaps } from "./promptCaps.js";
|
||||||
|
import { attachmentKind } from "../../util/attachmentKinds.js";
|
||||||
|
|
||||||
|
/** Largest image / audio sent inline as base64 (above it, the path is sent instead) */
|
||||||
|
export const MAX_INLINE_MEDIA_BYTES = 10 * 1024 * 1024;
|
||||||
|
/** All inline media of one prompt together. Base64 adds a third, and an Agent built on the ACP SDK refuses an incoming
|
||||||
|
* line over 32 MB (DEFAULT_MAX_MESSAGE_BYTES), so one prompt stays well under that; the rest goes by path. */
|
||||||
|
export const MAX_INLINE_TOTAL_BYTES = 16 * 1024 * 1024;
|
||||||
|
/** Largest text file embedded as a resource */
|
||||||
|
export const MAX_EMBED_TEXT_BYTES = 1024 * 1024;
|
||||||
|
|
||||||
|
export type AcpPromptBuild = {
|
||||||
|
blocks: ContentBlock[];
|
||||||
|
/** Images that went by path because the Agent doesn't take image blocks */
|
||||||
|
imagesByPath: string[];
|
||||||
|
/** Other problems worth a notice (unreadable file, too large) */
|
||||||
|
warnings: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const isText = (mime: string) => attachmentKind(mime) === "text";
|
||||||
|
|
||||||
|
export async function buildAcpPrompt(
|
||||||
|
text: string,
|
||||||
|
attachments: { path: string; mime: string }[],
|
||||||
|
caps: AcpPromptCaps,
|
||||||
|
): Promise<AcpPromptBuild> {
|
||||||
|
const media: ContentBlock[] = [];
|
||||||
|
const links: ContentBlock[] = [];
|
||||||
|
const pathLines: string[] = [];
|
||||||
|
const imagesByPath: string[] = [];
|
||||||
|
const warnings: string[] = [];
|
||||||
|
let inlineBytes = 0;
|
||||||
|
|
||||||
|
const byPath = (file: string, mime: string, size: number | null, label: string) => {
|
||||||
|
links.push({ type: "resource_link", uri: pathToFileURL(file).href, name: basename(file), mimeType: mime, ...(size !== null ? { size } : {}) });
|
||||||
|
pathLines.push(`${label}: ${file}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const a of attachments) {
|
||||||
|
const mime = a.mime || "application/octet-stream";
|
||||||
|
let file: string;
|
||||||
|
let size: number | null = null;
|
||||||
|
try {
|
||||||
|
file = await resolveImagePath(a.path);
|
||||||
|
size = (await stat(file)).size;
|
||||||
|
} catch (e) {
|
||||||
|
warnings.push(`${a.path}: ${String((e as Error)?.message ?? e)}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Only the four image types model APIs take (svg, bmp… go by path like any other file)
|
||||||
|
const image = attachmentKind(mime) === "image";
|
||||||
|
const audio = mime.startsWith("audio/");
|
||||||
|
if ((image && caps.image) || (audio && caps.audio)) {
|
||||||
|
if (size > MAX_INLINE_MEDIA_BYTES || inlineBytes + size > MAX_INLINE_TOTAL_BYTES) {
|
||||||
|
const limit = size > MAX_INLINE_MEDIA_BYTES ? MAX_INLINE_MEDIA_BYTES : MAX_INLINE_TOTAL_BYTES;
|
||||||
|
warnings.push(`${basename(file)}: ${(size / 1024 / 1024).toFixed(1)} MB, over the ${limit / 1024 / 1024} MB inline limit; sent as a file path`);
|
||||||
|
byPath(file, mime, size, image ? "Attached image" : "Attached audio");
|
||||||
|
if (image) imagesByPath.push(file);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const data = (await readFile(file)).toString("base64");
|
||||||
|
media.push(image ? { type: "image", data, mimeType: mime } : { type: "audio", data, mimeType: mime });
|
||||||
|
inlineBytes += size;
|
||||||
|
} catch (e) {
|
||||||
|
warnings.push(`${basename(file)}: ${String((e as Error)?.message ?? e)}`);
|
||||||
|
byPath(file, mime, size, image ? "Attached image" : "Attached audio");
|
||||||
|
if (image) imagesByPath.push(file);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (image || audio) {
|
||||||
|
byPath(file, mime, size, image ? "Attached image" : "Attached audio");
|
||||||
|
if (image) imagesByPath.push(file);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isText(mime) && caps.embeddedContext && size <= MAX_EMBED_TEXT_BYTES && inlineBytes + size <= MAX_INLINE_TOTAL_BYTES) {
|
||||||
|
try {
|
||||||
|
const body = await readFile(file, "utf8");
|
||||||
|
media.push({ type: "resource", resource: { uri: pathToFileURL(file).href, mimeType: mime, text: body } });
|
||||||
|
inlineBytes += size;
|
||||||
|
continue;
|
||||||
|
} catch {
|
||||||
|
/* fall back to the path */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
byPath(file, mime, size, "Attached file");
|
||||||
|
}
|
||||||
|
|
||||||
|
const fullText = [text, ...(pathLines.length ? [pathLines.join("\n")] : [])].filter(Boolean).join("\n\n");
|
||||||
|
const blocks: ContentBlock[] = [];
|
||||||
|
if (fullText) blocks.push({ type: "text", text: fullText });
|
||||||
|
blocks.push(...media, ...links);
|
||||||
|
return { blocks, imagesByPath, warnings };
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// What each ACP Agent says it accepts in a prompt: initialize → agentCapabilities.promptCapabilities.
|
||||||
|
// ACP's baseline is text and resource_link; image / audio / embedded resources are opt-in per Agent.
|
||||||
|
// Learned from the model probe (startup warm-up, providers.list) and from every session's initialize,
|
||||||
|
// kept in memory per provider id, and read by the provider's capabilities (images) and by AcpSession.send.
|
||||||
|
export type AcpPromptCaps = { image: boolean; audio: boolean; embeddedContext: boolean };
|
||||||
|
|
||||||
|
const learned = new Map<string, AcpPromptCaps>();
|
||||||
|
|
||||||
|
/** Normalize an initialize response (anything: Agents may leave fields out, which means false) */
|
||||||
|
export function promptCapsFromInitialize(res: unknown): AcpPromptCaps {
|
||||||
|
const pc = (res as { agentCapabilities?: { promptCapabilities?: Record<string, unknown> | null } | null } | null)
|
||||||
|
?.agentCapabilities?.promptCapabilities;
|
||||||
|
return {
|
||||||
|
image: pc?.image === true,
|
||||||
|
audio: pc?.audio === true,
|
||||||
|
embeddedContext: pc?.embeddedContext === true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rememberPromptCaps(providerId: string | undefined, caps: AcpPromptCaps): void {
|
||||||
|
if (providerId) learned.set(providerId, caps);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** undefined until the Agent has been probed or a session has initialized */
|
||||||
|
export function knownPromptCaps(providerId: string): AcpPromptCaps | undefined {
|
||||||
|
return learned.get(providerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function forgetPromptCaps(providerId?: string): void {
|
||||||
|
if (providerId) learned.delete(providerId);
|
||||||
|
else learned.clear();
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import type { Provider, DetectResult, ModelInfo, Capabilities, Mode } from "../types.js";
|
||||||
|
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
|
||||||
|
import { resolveFirstBin } from "../../util/bin.js";
|
||||||
|
import { AcpSession } from "./session.js";
|
||||||
|
import { knownPromptCaps } from "./promptCaps.js";
|
||||||
|
|
||||||
|
export type AcpProviderConfig = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
binName: string;
|
||||||
|
/** Takes precedence over binName: detect / listModels / session resolve these in order */
|
||||||
|
binCandidates?: string[];
|
||||||
|
acpArgs: string[];
|
||||||
|
/** Arguments for one session's ACP process from its model (dsh starts on the conversation's route); default acpArgs */
|
||||||
|
argsFor?: (model: string | null) => Promise<string[]>;
|
||||||
|
/** The Agent decides at initialize whether it takes images, for the model it started on (dsh): a model picked later sends images by path */
|
||||||
|
imagesFollowStartModel?: boolean;
|
||||||
|
installHint: string;
|
||||||
|
appVersion?: string;
|
||||||
|
flavor?: "cursor" | "generic";
|
||||||
|
capabilities?: Capabilities;
|
||||||
|
fetchModels?: (r: ResolveResult & { ok: true }) => Promise<ModelInfo[]>;
|
||||||
|
/** Our permission modes → this Agent's mode names over ACP; when given, only modes in the table are shown */
|
||||||
|
modeMap?: Partial<Record<Mode, string>>;
|
||||||
|
/** Mode names shown in the UI (the Agent's own naming) */
|
||||||
|
modeLabels?: Partial<Record<Mode, string>>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const acpCapabilities: Capabilities = {
|
||||||
|
resume: true,
|
||||||
|
interrupt: true,
|
||||||
|
steer: false,
|
||||||
|
images: false,
|
||||||
|
plan: true,
|
||||||
|
questions: false,
|
||||||
|
cost: false,
|
||||||
|
effort: [],
|
||||||
|
modes: ["plan", "default", "acceptEdits", "bypassPermissions"],
|
||||||
|
};
|
||||||
|
|
||||||
|
export const cursorAcpCapabilities: Capabilities = {
|
||||||
|
...acpCapabilities,
|
||||||
|
questions: true,
|
||||||
|
modes: ["default", "plan", "ask"],
|
||||||
|
};
|
||||||
|
|
||||||
|
function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 8000): Promise<string> {
|
||||||
|
return new Promise((resolvePromise, reject) => {
|
||||||
|
let out = "";
|
||||||
|
const p = spawnBin(r, args, { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
void killTree(p, { graceMs: 500 }); // On Windows a .cmd wrapper must be killed together with its child processes
|
||||||
|
} catch {}
|
||||||
|
reject(new Error("timeout"));
|
||||||
|
}, timeoutMs);
|
||||||
|
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.on("error", reject);
|
||||||
|
p.on("close", (code) => {
|
||||||
|
clearTimeout(t);
|
||||||
|
if (code === 0 || out.trim()) resolvePromise(out.trim());
|
||||||
|
else reject(new Error("exit " + code));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveProviderBin(cfg: AcpProviderConfig) {
|
||||||
|
const names = cfg.binCandidates?.length ? cfg.binCandidates : [cfg.binName];
|
||||||
|
return resolveFirstBin(names);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAcpProvider(cfg: AcpProviderConfig): Provider {
|
||||||
|
const base = cfg.capabilities ?? acpCapabilities;
|
||||||
|
// With a mode table, expose only the modes the Agent really has (in our fixed order)
|
||||||
|
const ORDER: Mode[] = ["plan", "default", "acceptEdits", "bypassPermissions"];
|
||||||
|
const caps: Capabilities = cfg.modeMap
|
||||||
|
? { ...base, modes: ORDER.filter((m) => cfg.modeMap![m] !== undefined), modeLabels: cfg.modeLabels }
|
||||||
|
: base;
|
||||||
|
return {
|
||||||
|
id: cfg.id,
|
||||||
|
name: cfg.name,
|
||||||
|
// images is what the Agent's own initialize says (probe at warm-up / providers.list, or any session); until then unknown
|
||||||
|
get capabilities(): Capabilities {
|
||||||
|
const learned = knownPromptCaps(cfg.id);
|
||||||
|
return learned ? { ...caps, images: learned.image, imagesKnown: true } : { ...caps, images: false, imagesKnown: false };
|
||||||
|
},
|
||||||
|
async detect(): Promise<DetectResult> {
|
||||||
|
const r = await resolveProviderBin(cfg);
|
||||||
|
if (!r.ok) {
|
||||||
|
return { available: false, reason: r.reason, installHint: cfg.installHint };
|
||||||
|
}
|
||||||
|
let version: string | undefined;
|
||||||
|
try {
|
||||||
|
if (cfg.id === "cursor") {
|
||||||
|
version = (await runVersion(r, ["--version"])).split(/\r?\n/)[0]?.trim();
|
||||||
|
} else if (cfg.id === "devin") {
|
||||||
|
version = (await runVersion(r, ["version"])).split(/\r?\n/)[0]?.trim();
|
||||||
|
} else if (cfg.id === "opencode") {
|
||||||
|
version = (await runVersion(r, ["--version"])).split(/\r?\n/)[0]?.trim();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* Having the binary is enough */
|
||||||
|
}
|
||||||
|
return { available: true, bin: r.display, version };
|
||||||
|
},
|
||||||
|
async listModels(): Promise<ModelInfo[]> {
|
||||||
|
const r = await resolveProviderBin(cfg);
|
||||||
|
if (!r.ok) return [{ id: "default", name: "默认", isDefault: true }];
|
||||||
|
if (cfg.fetchModels) return cfg.fetchModels(r);
|
||||||
|
return [{ id: "default", name: "默认", isDefault: true }];
|
||||||
|
},
|
||||||
|
async createSession(o) {
|
||||||
|
return new AcpSession({
|
||||||
|
threadId: o.threadId,
|
||||||
|
providerId: cfg.id,
|
||||||
|
providerName: cfg.name,
|
||||||
|
cwd: o.cwd,
|
||||||
|
model: o.model,
|
||||||
|
mode: o.mode,
|
||||||
|
effort: o.effort,
|
||||||
|
resumeId: o.resumeId,
|
||||||
|
binName: cfg.binName,
|
||||||
|
binCandidates: cfg.binCandidates ?? [cfg.binName],
|
||||||
|
acpArgs: cfg.argsFor ? await cfg.argsFor(o.model) : cfg.acpArgs,
|
||||||
|
imagesFollowStartModel: cfg.imagesFollowStartModel,
|
||||||
|
appVersion: cfg.appVersion ?? "0.0.1",
|
||||||
|
flavor: cfg.flavor ?? "generic",
|
||||||
|
modeMap: cfg.modeMap,
|
||||||
|
cursorFast: o.cursorFast,
|
||||||
|
cursorAutoReview: o.cursorAutoReview,
|
||||||
|
launch: o.launch,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,534 @@
|
|||||||
|
// Persistent ACP session: cursor-agent acp / devin acp and others.
|
||||||
|
import type { ActiveSession, ClientConnection, ClientContext } from "@agentclientprotocol/sdk";
|
||||||
|
import { client, methods, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
||||||
|
import type { ChildProcess } from "node:child_process";
|
||||||
|
import type { ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
|
||||||
|
import { mapAcpAvailableCommands, sortSlashCommands } from "../slash.js";
|
||||||
|
import type { ProviderEvent } from "../../timeline/types.js";
|
||||||
|
import { AsyncQueue } from "../../util/queue.js";
|
||||||
|
import { resolveFirstBin, type ResolveResult } from "../../util/bin.js";
|
||||||
|
import { absCwd, acpStreamFromChild, killAcpChild, spawnResolved } from "./spawn.js";
|
||||||
|
import { registerAcpClientHandlers } from "./clientHandlers.js";
|
||||||
|
import { mapSessionUpdate, newMapCtx, stopToTurnEnd, type MapCtx } from "./mapUpdate.js";
|
||||||
|
import { promptCapsFromInitialize, rememberPromptCaps, type AcpPromptCaps } from "./promptCaps.js";
|
||||||
|
import { pickReconnect, sessionOpenFromInitialize } from "./sessionCaps.js";
|
||||||
|
import { buildAcpPrompt } from "./prompt.js";
|
||||||
|
import { tr } from "../../util/i18n.js";
|
||||||
|
|
||||||
|
type AcpSelectValue = { value?: string; name?: string; options?: AcpSelectValue[] };
|
||||||
|
type AcpConfigOption = { id: string; category?: string | null; type?: string; currentValue?: unknown; options?: AcpSelectValue[] };
|
||||||
|
import { log } from "../../log.js";
|
||||||
|
|
||||||
|
const rid = () => Math.random().toString(36).slice(2, 10);
|
||||||
|
|
||||||
|
type AttachableCtx = {
|
||||||
|
attachSession(response: { sessionId: string; modes?: unknown; configOptions?: unknown }): ActiveSession;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AcpSessionOpts = {
|
||||||
|
threadId: string;
|
||||||
|
/** Provider id and display name: the Agent's prompt capabilities are remembered under the id; notices name the Agent */
|
||||||
|
providerId?: string;
|
||||||
|
providerName?: string;
|
||||||
|
cwd: string;
|
||||||
|
model: string | null;
|
||||||
|
mode: Mode;
|
||||||
|
effort: string | null;
|
||||||
|
resumeId: string | null;
|
||||||
|
binName: string;
|
||||||
|
binCandidates: string[];
|
||||||
|
acpArgs: string[];
|
||||||
|
/** initialize's image answer holds for the start model only (dsh): after a switch, images go by path */
|
||||||
|
imagesFollowStartModel?: boolean;
|
||||||
|
appVersion: string;
|
||||||
|
flavor: "cursor" | "generic";
|
||||||
|
modeMap?: Partial<Record<Mode, string>>;
|
||||||
|
cursorFast?: boolean;
|
||||||
|
cursorAutoReview?: boolean;
|
||||||
|
launch?: { cmd: string; prefixArgs: string[] };
|
||||||
|
};
|
||||||
|
|
||||||
|
export class AcpSession implements ProviderSession {
|
||||||
|
events: AsyncIterable<ProviderEvent>;
|
||||||
|
private q = new AsyncQueue<ProviderEvent>();
|
||||||
|
private child: ChildProcess | null = null;
|
||||||
|
private conn: ClientConnection | null = null;
|
||||||
|
private ctx: ClientContext | null = null;
|
||||||
|
private active: ActiveSession | null = null;
|
||||||
|
private initErr: Error | null = null;
|
||||||
|
private initPromise: Promise<void>;
|
||||||
|
private closed = false;
|
||||||
|
private turnId: string | null = null;
|
||||||
|
private turnNum = 0;
|
||||||
|
private running = false;
|
||||||
|
private permPending = new Map<string, (a: RespondAnswer) => void>();
|
||||||
|
private mapCtx: MapCtx = newMapCtx();
|
||||||
|
private modelConfigId: string | null = null;
|
||||||
|
private thoughtConfigId: string | null = null;
|
||||||
|
private cursorFast = false;
|
||||||
|
private cursorAutoReview = false;
|
||||||
|
private slashCommands: SlashCommand[] = [];
|
||||||
|
private activeTurnId: string | null = null;
|
||||||
|
private configOptions: AcpConfigOption[] | null = null;
|
||||||
|
// initialize → agentCapabilities.promptCapabilities (ACP baseline until initialize answers: text + resource_link)
|
||||||
|
private promptCaps: AcpPromptCaps = { image: false, audio: false, embeddedContext: false };
|
||||||
|
private initCaps: AcpPromptCaps = this.promptCaps;
|
||||||
|
private startModel: string | null = null;
|
||||||
|
private wakePump: (() => void) | null = null;
|
||||||
|
// listCommands waits for the first batch of commands (or confirmation there are none), following Paseo's waitForInitialCommands
|
||||||
|
private commandsReady!: Promise<void>;
|
||||||
|
private settleCommands!: () => void;
|
||||||
|
|
||||||
|
constructor(private o: AcpSessionOpts) {
|
||||||
|
this.events = this.q;
|
||||||
|
this.startModel = o.model; // the model the process is launched for (argsFor), before any setModel
|
||||||
|
this.cursorFast = o.cursorFast ?? false;
|
||||||
|
// The shield (auto-accept permission prompts) UI was removed: never auto-approve, so conversations that once turned it on don't keep approving with the toggle hidden
|
||||||
|
this.cursorAutoReview = false;
|
||||||
|
this.commandsReady = new Promise<void>((r) => (this.settleCommands = r));
|
||||||
|
this.initPromise = this.boot();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async boot(): Promise<void> {
|
||||||
|
const bin = this.o.launch
|
||||||
|
? ({
|
||||||
|
ok: true as const,
|
||||||
|
cmd: this.o.launch.cmd,
|
||||||
|
prefixArgs: this.o.launch.prefixArgs,
|
||||||
|
display: this.o.launch.cmd,
|
||||||
|
via: "custom",
|
||||||
|
binName: "custom",
|
||||||
|
} satisfies ResolveResult & { ok: true; binName: string })
|
||||||
|
: await resolveFirstBin(this.o.binCandidates?.length ? this.o.binCandidates : [this.o.binName]);
|
||||||
|
if (!bin.ok) throw new Error(bin.reason);
|
||||||
|
try {
|
||||||
|
this.child = spawnResolved(bin, this.o.acpArgs, { cwd: this.o.cwd });
|
||||||
|
this.child.stderr?.on("data", (d: Buffer) => {
|
||||||
|
const t = d.toString().trim();
|
||||||
|
if (t) log("info", `[${this.o.binName} acp] ${t.slice(0, 500)}`);
|
||||||
|
});
|
||||||
|
this.child.on("error", (e) => this.failInit(e));
|
||||||
|
this.child.on("close", (code) => {
|
||||||
|
if (!this.closed && code !== 0) {
|
||||||
|
this.q.push({ type: "notice", level: "error", message: `${this.o.binName} 进程退出 (${code})` });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const app = client({ name: "magpie-agent-console" });
|
||||||
|
registerAcpClientHandlers(app, {
|
||||||
|
push: (ev) => this.q.push(ev),
|
||||||
|
waitFor: (id) => this.waitPerm(id),
|
||||||
|
autoAcceptPermissions: () => this.cursorAutoReview,
|
||||||
|
});
|
||||||
|
const stream = acpStreamFromChild(this.child);
|
||||||
|
this.conn = app.connect(stream);
|
||||||
|
this.ctx = this.conn.agent;
|
||||||
|
const initRes = await this.ctx.request(methods.agent.initialize, {
|
||||||
|
protocolVersion: PROTOCOL_VERSION,
|
||||||
|
// Cursor: declare support for the parameterized model picker (as Paseo does); only then does it expose levels / Fast as separate config options
|
||||||
|
clientCapabilities: this.o.flavor === "cursor" ? { _meta: { parameterizedModelPicker: true } } : {},
|
||||||
|
clientInfo: { name: "Agent Console", version: this.o.appVersion },
|
||||||
|
});
|
||||||
|
this.promptCaps = promptCapsFromInitialize(initRes);
|
||||||
|
this.initCaps = this.promptCaps;
|
||||||
|
rememberPromptCaps(this.o.providerId, this.promptCaps);
|
||||||
|
|
||||||
|
const cwd = absCwd(this.o.cwd);
|
||||||
|
const ctx = this.ctx;
|
||||||
|
if (!ctx) throw new Error("ACP 未连接");
|
||||||
|
if (this.o.resumeId) {
|
||||||
|
// Prefer the method the Agent's initialize advertises: load (replays history) over resume (reconnects only); neither → new session + notice
|
||||||
|
const how = pickReconnect(sessionOpenFromInitialize(initRes));
|
||||||
|
if (how === "load" || how === "resume") {
|
||||||
|
const method = how === "load" ? methods.agent.session.load : methods.agent.session.resume;
|
||||||
|
const restored = (await ctx.request(method, {
|
||||||
|
sessionId: this.o.resumeId,
|
||||||
|
cwd,
|
||||||
|
mcpServers: [],
|
||||||
|
})) as { modes?: unknown; configOptions?: AcpConfigOption[] };
|
||||||
|
this.active = (ctx as unknown as AttachableCtx).attachSession({
|
||||||
|
sessionId: this.o.resumeId,
|
||||||
|
modes: restored.modes,
|
||||||
|
configOptions: restored.configOptions,
|
||||||
|
});
|
||||||
|
if (Array.isArray(restored.configOptions)) this.configOptions = restored.configOptions;
|
||||||
|
} else {
|
||||||
|
this.active = await ctx.buildSession(cwd).start();
|
||||||
|
const agent = this.o.providerName ?? this.o.binName;
|
||||||
|
this.q.push({ type: "notice", level: "warn", message: tr("notice.acpSessionNotRestored", { agent }) });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.active = await ctx.buildSession(cwd).start();
|
||||||
|
}
|
||||||
|
this.syncModelConfigId();
|
||||||
|
this.syncThoughtConfigId();
|
||||||
|
await this.applySessionMode(this.o.mode);
|
||||||
|
await this.applySessionModel(this.o.model); // Also applies the thinking level
|
||||||
|
await this.applyCursorAutoReviewConfig(this.cursorAutoReview);
|
||||||
|
this.q.push({ type: "provider_session_id", id: this.active.sessionId });
|
||||||
|
const init = (this.active.newSessionResponse as { availableCommands?: { name: string; description: string; input?: { hint?: string } | null }[] })
|
||||||
|
?.availableCommands;
|
||||||
|
if (init?.length) this.applyAvailableCommands(init);
|
||||||
|
void this.pumpUpdates();
|
||||||
|
} catch (e) {
|
||||||
|
this.failInit(e);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private failInit(e: unknown): void {
|
||||||
|
this.initErr = e instanceof Error ? e : new Error(String(e));
|
||||||
|
}
|
||||||
|
|
||||||
|
private applyAvailableCommands(
|
||||||
|
raw: { name: string; description: string; input?: { hint?: string } | null }[],
|
||||||
|
): void {
|
||||||
|
this.slashCommands = sortSlashCommands(mapAcpAvailableCommands(raw));
|
||||||
|
this.q.push({ type: "slash_commands", commands: this.slashCommands });
|
||||||
|
this.settleCommands();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ready(): Promise<void> {
|
||||||
|
await this.initPromise.catch(() => {});
|
||||||
|
if (this.initErr) throw this.initErr;
|
||||||
|
if (!this.active) throw new Error("ACP 会话未就绪");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The config options currently in effect: each set_config_option response returns the latest set (levels change after switching models); otherwise use session/new's */
|
||||||
|
private currentConfig(): AcpConfigOption[] {
|
||||||
|
return (this.configOptions ?? this.active?.newSessionResponse.configOptions ?? []) as AcpConfigOption[];
|
||||||
|
}
|
||||||
|
|
||||||
|
private syncModelConfigId(): void {
|
||||||
|
for (const o of this.currentConfig()) {
|
||||||
|
if (o.type === "select" && (o.category === "model" || o.id === "model")) {
|
||||||
|
this.modelConfigId = o.id;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.o.flavor === "cursor") this.modelConfigId = "model";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Level options belong to the current model: recompute on every refresh (cleared when switching to a model without levels)
|
||||||
|
private syncThoughtConfigId(): void {
|
||||||
|
this.thoughtConfigId = null;
|
||||||
|
const opts = this.currentConfig().filter((o) => o.type === "select");
|
||||||
|
const hit =
|
||||||
|
opts.find((o) => o.category === "thought_level") ??
|
||||||
|
opts.find((o) => /thought|thinking|effort|reasoning/i.test(o.id ?? ""));
|
||||||
|
if (hit) this.thoughtConfigId = hit.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** set_config_option, then refresh local state from the latest config options it returns */
|
||||||
|
private async setOption(configId: string, value: string): Promise<boolean> {
|
||||||
|
if (!this.ctx || !this.active) return false;
|
||||||
|
try {
|
||||||
|
const res = (await this.ctx.request(methods.agent.session.setConfigOption, {
|
||||||
|
sessionId: this.active.sessionId,
|
||||||
|
configId,
|
||||||
|
value,
|
||||||
|
})) as { configOptions?: AcpConfigOption[] } | null;
|
||||||
|
if (Array.isArray(res?.configOptions)) {
|
||||||
|
this.configOptions = res.configOptions;
|
||||||
|
this.syncThoughtConfigId();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
log("info", `ACP set_config_option(${configId}=${value}): ${String(e)}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applySessionThought(effort: string | null): Promise<void> {
|
||||||
|
if (!effort || !this.thoughtConfigId) return;
|
||||||
|
// Don't send a level the current model doesn't support (the level set changes after switching models)
|
||||||
|
const opt = this.currentConfig().find((o) => o.id === this.thoughtConfigId);
|
||||||
|
const values = (opt?.options ?? []).flatMap((x) => (x.options ? x.options : [x])).map((x) => x.value);
|
||||||
|
if (values.length && !values.includes(effort)) return;
|
||||||
|
await this.setOption(this.thoughtConfigId, effort);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mode choices the Agent reports: prefer a category=mode select in configOptions, otherwise ACP modes.availableModes */
|
||||||
|
private modeChoices(): { id: string; name: string; configId: string | null }[] {
|
||||||
|
const opt = this.currentConfig().find(
|
||||||
|
(o) => o.type === "select" && (o.category === "mode" || o.id === "mode"),
|
||||||
|
) as { id: string; options?: { value?: string; name?: string }[] } | undefined;
|
||||||
|
if (opt?.options?.length) {
|
||||||
|
return opt.options
|
||||||
|
.filter((x) => typeof x.value === "string")
|
||||||
|
.map((x) => ({ id: x.value!, name: x.name ?? x.value!, configId: opt.id }));
|
||||||
|
}
|
||||||
|
return (this.active?.modes?.availableModes ?? []).map((m) => ({ id: m.id, name: m.name, configId: null }));
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveAcpModeId(mode: Mode): string | null {
|
||||||
|
if (this.o.modeMap) {
|
||||||
|
// Find the Agent's real mode via the table; Copilot's mode ids are URLs (…/session-modes#agent), so match on the # suffix
|
||||||
|
const want = this.o.modeMap[mode];
|
||||||
|
if (!want) return null;
|
||||||
|
const hit = this.modeChoices().find(
|
||||||
|
(m) => m.id === want || m.id.endsWith(`#${want}`) || m.name.toLowerCase() === want,
|
||||||
|
);
|
||||||
|
return hit?.id ?? want;
|
||||||
|
}
|
||||||
|
if (this.o.flavor === "cursor") {
|
||||||
|
const map: Partial<Record<Mode, string>> = { default: "agent", plan: "plan", ask: "ask" };
|
||||||
|
const want = map[mode] ?? "agent";
|
||||||
|
const avail = this.active?.modes?.availableModes ?? [];
|
||||||
|
const hit = avail.find((m) => m.id === want || m.name.toLowerCase() === want);
|
||||||
|
return hit?.id ?? want;
|
||||||
|
}
|
||||||
|
return mode === "plan" ? "plan" : "default";
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applySessionMode(mode: Mode): Promise<void> {
|
||||||
|
if (!this.ctx || !this.active) return;
|
||||||
|
// Copilot "Allow All" (as Paseo does): use the agent mode, then turn the allow_all config on; turn it off for other modes
|
||||||
|
const hasAllowAll = this.currentConfig().some((o) => o.id === "allow_all");
|
||||||
|
if (this.o.modeMap?.[mode] === "allow-all") {
|
||||||
|
const agentId = this.modeChoices().find((m) => m.id === "agent" || m.id.endsWith("#agent"));
|
||||||
|
if (agentId?.configId) await this.setOption(agentId.configId, agentId.id);
|
||||||
|
if (hasAllowAll) await this.setOption("allow_all", "on");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (hasAllowAll && this.o.modeMap) await this.setOption("allow_all", "off");
|
||||||
|
const modeId = this.resolveAcpModeId(mode);
|
||||||
|
if (!modeId) return; // This Agent has no such mode: don't send anything
|
||||||
|
try {
|
||||||
|
// Modes offered as a config option (Devin / OpenCode / Copilot) use set_config_option, otherwise set_mode
|
||||||
|
const viaConfig = this.modeChoices().find((m) => m.id === modeId)?.configId;
|
||||||
|
if (viaConfig) {
|
||||||
|
await this.setOption(viaConfig, modeId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await this.ctx.request(methods.agent.session.setMode, {
|
||||||
|
sessionId: this.active.sessionId,
|
||||||
|
modeId,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
log("info", `ACP setMode(${mode}): ${String(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Switch model → refresh level options from the new config options it returns → then apply the level (as Paseo does).
|
||||||
|
* Cursor connects with parameterizedModelPicker: only the base model name is sent (grok-4.6); level / Fast are separate config options.
|
||||||
|
*/
|
||||||
|
private async applySessionModel(model: string | null): Promise<void> {
|
||||||
|
if (!this.ctx || !this.active) return;
|
||||||
|
const value = model && this.o.flavor === "cursor" ? model.replace(/\[.*\]$/u, "") : model;
|
||||||
|
if (value) {
|
||||||
|
const modelOption = this.currentConfig().find((o) => o.id === (this.modelConfigId ?? "model"));
|
||||||
|
const values = (modelOption?.options ?? []).flatMap((x) => x.options ? x.options : [x])
|
||||||
|
.map((x) => x.value).filter((x): x is string => typeof x === "string");
|
||||||
|
// Old sessions may have saved another Agent's model ID. Skip invalid values and let ACP keep its current model.
|
||||||
|
if (!values.length || values.includes(value)) {
|
||||||
|
await this.setOption(this.modelConfigId ?? "model", value);
|
||||||
|
} else {
|
||||||
|
log("info", `忽略 ${this.o.binName} 的无效模型:${value}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.o.flavor === "cursor" && this.cursorFast && this.currentConfig().some((o) => o.id === "fast")) {
|
||||||
|
await this.setOption("fast", "true");
|
||||||
|
}
|
||||||
|
await this.applySessionThought(this.o.effort);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applyCursorAutoReviewConfig(on: boolean): Promise<void> {
|
||||||
|
if (this.o.flavor !== "cursor" || !this.ctx || !this.active) return;
|
||||||
|
for (const configId of ["auto_review", "autoReview", "smart_auto"]) {
|
||||||
|
try {
|
||||||
|
await this.ctx.request(methods.agent.session.setConfigOption, {
|
||||||
|
sessionId: this.active.sessionId,
|
||||||
|
configId,
|
||||||
|
type: "boolean",
|
||||||
|
value: on,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
} catch {
|
||||||
|
/* try the next configId */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cursor only: Fast / Auto-review (can be changed while the session is open) */
|
||||||
|
async updateCursorOpts(fast: boolean, autoReview: boolean): Promise<void> {
|
||||||
|
this.cursorFast = fast;
|
||||||
|
void autoReview; // See the constructor: auto-approval is no longer supported
|
||||||
|
await this.ready();
|
||||||
|
await this.applySessionModel(this.o.model);
|
||||||
|
await this.applyCursorAutoReviewConfig(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private waitPerm(requestId: string): Promise<RespondAnswer> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
this.permPending.set(requestId, resolve);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
respond(requestId: string, answer: RespondAnswer): void {
|
||||||
|
const r = this.permPending.get(requestId);
|
||||||
|
if (r) {
|
||||||
|
this.permPending.delete(requestId);
|
||||||
|
r(answer);
|
||||||
|
this.q.push({
|
||||||
|
type: "permission_resolved",
|
||||||
|
requestId,
|
||||||
|
optionId: answer.optionId,
|
||||||
|
cancelled: answer.cancelled,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async send(input: SendInput): Promise<void> {
|
||||||
|
await this.ready();
|
||||||
|
if (this.running) throw new Error("当前轮次尚未结束");
|
||||||
|
this.turnNum++;
|
||||||
|
this.turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum;
|
||||||
|
this.mapCtx = newMapCtx();
|
||||||
|
this.running = true;
|
||||||
|
this.q.push({
|
||||||
|
type: "turn_started",
|
||||||
|
turnId: this.turnId,
|
||||||
|
model: this.o.model,
|
||||||
|
mode: this.o.mode,
|
||||||
|
effort: this.o.effort,
|
||||||
|
});
|
||||||
|
const text = input.text.trim();
|
||||||
|
const attachments = input.images ?? [];
|
||||||
|
if (!text && !attachments.length) {
|
||||||
|
this.running = false;
|
||||||
|
this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// An image-only message is still a prompt: images go as image blocks when the Agent takes them, else by file path
|
||||||
|
const built = await buildAcpPrompt(text, attachments, this.promptCaps);
|
||||||
|
const agent = this.o.providerName ?? this.o.binName;
|
||||||
|
if (built.imagesByPath.length && !this.promptCaps.image) {
|
||||||
|
const switched = this.o.imagesFollowStartModel && this.initCaps.image && this.o.model !== this.startModel;
|
||||||
|
this.q.push({ type: "notice", level: "warn", message: tr(switched ? "notice.acpImageByPathSwitched" : "notice.acpImageByPath", { agent, paths: built.imagesByPath.join(", ") }) });
|
||||||
|
}
|
||||||
|
for (const w of built.warnings) this.q.push({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) });
|
||||||
|
if (!built.blocks.length) {
|
||||||
|
// Every attachment failed to resolve and there was no text: nothing to send
|
||||||
|
this.running = false;
|
||||||
|
this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void this.runTurn(built.blocks);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send this turn's prompt; reading updates is the job of the persistent pumpUpdates() (following Paseo: session/update is handled at session level)
|
||||||
|
private async runTurn(prompt: Parameters<ActiveSession["prompt"]>[0]): Promise<void> {
|
||||||
|
this.activeTurnId = this.turnId;
|
||||||
|
this.wakePump?.();
|
||||||
|
this.wakePump = null;
|
||||||
|
this.active!.prompt(prompt).catch(() => {
|
||||||
|
/* failures surface through nextUpdate() and pumpUpdates ends the turn */
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private endTurn(ev: ProviderEvent): void {
|
||||||
|
this.q.push(ev);
|
||||||
|
this.activeTurnId = null;
|
||||||
|
this.running = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read session/update for the whole lifetime of the session.
|
||||||
|
* It used to read only during a turn: the available_commands_update an Agent pushes after session/new and before the first message went unread,
|
||||||
|
* so the slash menu stayed empty. Now command updates are cached at any time; conversation content becomes timeline events only while a turn is in progress.
|
||||||
|
*/
|
||||||
|
private async pumpUpdates(): Promise<void> {
|
||||||
|
const session = this.active;
|
||||||
|
if (!session) return;
|
||||||
|
while (!this.closed) {
|
||||||
|
let msg: Awaited<ReturnType<typeof session.nextUpdate>>;
|
||||||
|
try {
|
||||||
|
msg = await session.nextUpdate();
|
||||||
|
} catch (e) {
|
||||||
|
if (this.closed) return;
|
||||||
|
const turnId = this.activeTurnId;
|
||||||
|
if (turnId) {
|
||||||
|
this.endTurn({ type: "turn_ended", turnId, status: "failed", error: String((e as Error)?.message ?? e) });
|
||||||
|
}
|
||||||
|
// After an error the queue keeps throwing the same error until the next prompt clears it: wait for the next turn before reading again
|
||||||
|
await new Promise<void>((r) => (this.wakePump = r));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (msg.kind === "session_update") {
|
||||||
|
const u = msg.update;
|
||||||
|
if (u.sessionUpdate === "available_commands_update") {
|
||||||
|
this.applyAvailableCommands(u.availableCommands ?? []);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!this.activeTurnId) continue; // Other updates outside a turn (e.g. mode change echoes) don't go to the timeline
|
||||||
|
for (const ev of mapSessionUpdate(u, this.mapCtx)) this.q.push(ev);
|
||||||
|
} else if (this.activeTurnId) {
|
||||||
|
this.endTurn(stopToTurnEnd(msg.stopReason, this.activeTurnId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async interrupt(): Promise<void> {
|
||||||
|
await this.ready();
|
||||||
|
if (!this.ctx || !this.active) return;
|
||||||
|
try {
|
||||||
|
await this.ctx.request(methods.agent.session.cancel, { sessionId: this.active.sessionId });
|
||||||
|
} catch (e) {
|
||||||
|
log("info", `ACP cancel: ${String(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async setModel(model: string | null): Promise<void> {
|
||||||
|
this.o.model = model;
|
||||||
|
await this.ready();
|
||||||
|
if (this.o.imagesFollowStartModel) {
|
||||||
|
// dsh answered initialize for the model it started on; another model may not take image blocks (it refuses the prompt)
|
||||||
|
this.promptCaps = model === this.startModel ? this.initCaps : { ...this.initCaps, image: false };
|
||||||
|
}
|
||||||
|
await this.applySessionModel(model);
|
||||||
|
}
|
||||||
|
|
||||||
|
async setMode(mode: Mode): Promise<void> {
|
||||||
|
this.o.mode = mode;
|
||||||
|
await this.ready();
|
||||||
|
await this.applySessionMode(mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
async setEffort(effort: string | null): Promise<void> {
|
||||||
|
this.o.effort = effort;
|
||||||
|
await this.ready();
|
||||||
|
await this.applySessionThought(effort);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listCommands(): Promise<SlashCommand[]> {
|
||||||
|
try {
|
||||||
|
await this.ready();
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
// Commands are pushed asynchronously after session/new: wait at most 10 s for the first batch (Agents that report none return empty after the timeout)
|
||||||
|
if (!this.slashCommands.length) {
|
||||||
|
await Promise.race([this.commandsReady, new Promise((r) => setTimeout(r, 10000))]);
|
||||||
|
}
|
||||||
|
return this.slashCommands;
|
||||||
|
}
|
||||||
|
|
||||||
|
async close(): Promise<void> {
|
||||||
|
this.closed = true;
|
||||||
|
this.wakePump?.();
|
||||||
|
this.settleCommands();
|
||||||
|
for (const r of this.permPending.values()) r({ cancelled: true });
|
||||||
|
this.permPending.clear();
|
||||||
|
try {
|
||||||
|
this.active?.dispose();
|
||||||
|
} catch {}
|
||||||
|
try {
|
||||||
|
this.conn?.close();
|
||||||
|
} catch {}
|
||||||
|
await killAcpChild(this.child);
|
||||||
|
this.child = null;
|
||||||
|
this.q.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
// How an ACP Agent reopens an old conversation: initialize → agentCapabilities.
|
||||||
|
// - loadSession (top-level): session/load — returns prior messages as session/update
|
||||||
|
// - sessionCapabilities.resume: session/resume — reconnects without replaying history
|
||||||
|
// Prefer load when both are advertised (OpenCode); resume when only resume (dsh);
|
||||||
|
// neither → the caller starts a new session and tells the user prior context wasn't restored.
|
||||||
|
export type AcpSessionOpen = { load: boolean; resume: boolean };
|
||||||
|
export type AcpReconnect = "load" | "resume" | "none";
|
||||||
|
|
||||||
|
/** Normalize an initialize response: missing/false/null means the Agent doesn't advertise that method */
|
||||||
|
export function sessionOpenFromInitialize(res: unknown): AcpSessionOpen {
|
||||||
|
const caps = (res as { agentCapabilities?: {
|
||||||
|
loadSession?: unknown;
|
||||||
|
sessionCapabilities?: { resume?: unknown } | null;
|
||||||
|
} | null } | null)?.agentCapabilities;
|
||||||
|
// ACP: omitted or null = no; {} (any object) = yes
|
||||||
|
const resume = caps?.sessionCapabilities?.resume != null && typeof caps.sessionCapabilities.resume === "object";
|
||||||
|
return { load: caps?.loadSession === true, resume };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pickReconnect(open: AcpSessionOpen): AcpReconnect {
|
||||||
|
if (open.load) return "load";
|
||||||
|
if (open.resume) return "resume";
|
||||||
|
return "none";
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { ChildProcess } from "node:child_process";
|
||||||
|
import { Readable, Writable } from "node:stream";
|
||||||
|
import { resolve as resolvePath } from "node:path";
|
||||||
|
import * as acp from "@agentclientprotocol/sdk";
|
||||||
|
import type { ResolveResult } from "../../util/bin.js";
|
||||||
|
import { killTree, spawnBin } from "../../util/bin.js";
|
||||||
|
|
||||||
|
export function spawnResolved(r: ResolveResult & { ok: true }, args: string[], o: { cwd?: string } = {}): ChildProcess {
|
||||||
|
// group: on non-Windows it gets its own process group so killTree also ends the tool processes it started
|
||||||
|
return spawnBin(r, args, {
|
||||||
|
cwd: o.cwd,
|
||||||
|
stdio: ["pipe", "pipe", "pipe"],
|
||||||
|
env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" },
|
||||||
|
group: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function acpStreamFromChild(child: ChildProcess): acp.Stream {
|
||||||
|
if (!child.stdin || !child.stdout) throw new Error("ACP 子进程缺少 stdio 管道");
|
||||||
|
const output = Writable.toWeb(child.stdin) as WritableStream<Uint8Array>;
|
||||||
|
const input = Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>;
|
||||||
|
return acp.ndJsonStream(output, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function absCwd(cwd: string): string {
|
||||||
|
return resolvePath(cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function killAcpChild(child: ChildProcess | null): Promise<void> {
|
||||||
|
await killTree(child);
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import type { ProviderCatalogEntry } from "../catalog.js";
|
||||||
|
import type { AcpProviderConfig } from "./provider.js";
|
||||||
|
import { cursorAcpCapabilities } from "./provider.js";
|
||||||
|
import { acpProbeModels, cursorProbeModels, dshProbeModels } from "./probe.js";
|
||||||
|
import { DSH_ACP_ARGS, dshAcpArgs } from "./dsh.js";
|
||||||
|
|
||||||
|
const ACP_IDS = new Set(["cursor", "devin", "opencode", "dsh", "pi", "copilot"]);
|
||||||
|
|
||||||
|
export function isAcpCatalogId(id: string): boolean {
|
||||||
|
return ACP_IDS.has(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Model lists and thinking levels always come from what the Agent reports over ACP (acpProbeModels), no longer from parsing each CLI's text output.
|
||||||
|
// modeMap: our permission modes → the Agent's real mode names (from what session/new actually reports); "" means keep the entry but send nothing.
|
||||||
|
export function acpConfigForEntry(entry: ProviderCatalogEntry, appVersion: string): AcpProviderConfig | null {
|
||||||
|
if (!ACP_IDS.has(entry.id)) return null;
|
||||||
|
const base: Omit<AcpProviderConfig, "acpArgs" | "fetchModels" | "flavor" | "capabilities"> = {
|
||||||
|
id: entry.id,
|
||||||
|
name: entry.name,
|
||||||
|
binName: entry.bins[0] ?? entry.id,
|
||||||
|
binCandidates: entry.bins,
|
||||||
|
installHint: entry.installHint,
|
||||||
|
appVersion,
|
||||||
|
};
|
||||||
|
|
||||||
|
switch (entry.id) {
|
||||||
|
case "cursor":
|
||||||
|
// Modes: agent / plan / ask (see cursorAcpCapabilities)
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
acpArgs: ["acp"],
|
||||||
|
flavor: "cursor",
|
||||||
|
capabilities: cursorAcpCapabilities,
|
||||||
|
// Each model's own thinking levels come from cursor/list_available_models (as Paseo does)
|
||||||
|
fetchModels: cursorProbeModels(["acp"], entry.id),
|
||||||
|
};
|
||||||
|
case "devin":
|
||||||
|
// Modes: Code(accept-edits) / Smart / Ask / Plan / Bypass Permissions
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
acpArgs: ["acp"],
|
||||||
|
fetchModels: acpProbeModels(["acp"], entry.id),
|
||||||
|
modeMap: { plan: "plan", default: "ask", acceptEdits: "accept-edits", bypassPermissions: "bypass" },
|
||||||
|
modeLabels: { plan: "Plan", default: "Ask", acceptEdits: "Code", bypassPermissions: "Bypass Permissions" },
|
||||||
|
};
|
||||||
|
case "opencode":
|
||||||
|
// Modes: build / plan; thinking level effort (low…ultra, including fast variants)
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
acpArgs: ["acp"],
|
||||||
|
fetchModels: acpProbeModels(["acp"], entry.id),
|
||||||
|
modeMap: { plan: "plan", default: "build" },
|
||||||
|
modeLabels: { plan: "Plan", default: "Build" },
|
||||||
|
};
|
||||||
|
case "copilot":
|
||||||
|
// As Paseo: Agent / Plan / Allow All. Allow All = agent mode + allow_all config on (autopilot is not used)
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
acpArgs: ["--acp"],
|
||||||
|
fetchModels: acpProbeModels(["--acp"], entry.id),
|
||||||
|
modeMap: { plan: "plan", default: "agent", bypassPermissions: "allow-all" },
|
||||||
|
modeLabels: { plan: "Plan", default: "Agent", bypassPermissions: "Allow All" },
|
||||||
|
};
|
||||||
|
case "pi":
|
||||||
|
// pi-acp has no mode options; thinking level thought_level (low…max)
|
||||||
|
return { ...base, acpArgs: [], fetchModels: acpProbeModels([], entry.id), modeMap: { default: "" } };
|
||||||
|
case "dsh":
|
||||||
|
// Started on the conversation's route (--patch), so its initialize advertises image input for that model (see dsh.ts)
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
acpArgs: DSH_ACP_ARGS,
|
||||||
|
argsFor: (model) => dshAcpArgs(model),
|
||||||
|
imagesFollowStartModel: true,
|
||||||
|
fetchModels: dshProbeModels(entry.id),
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/** Provider catalog (fixed, 8 entries).
|
||||||
|
* status: verified=accepted on a real machine | experimental=usable but not guaranteed | planned=integration not confirmed
|
||||||
|
* All 8 are currently verified; default toggle: verified ones are on by default (see enabled.ts). */
|
||||||
|
export type ProviderStatus = "verified" | "experimental" | "planned";
|
||||||
|
|
||||||
|
export type ProviderCatalogEntry = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
bins: string[];
|
||||||
|
installHint: string;
|
||||||
|
status: ProviderStatus;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PROVIDER_CATALOG: ProviderCatalogEntry[] = [
|
||||||
|
{ id: "claude", name: "Claude Code", bins: ["claude"], installHint: "npm i -g @anthropic-ai/claude-code", status: "verified" },
|
||||||
|
{ id: "codex", name: "Codex", bins: ["codex"], installHint: "见 OpenAI Codex CLI 安装说明", status: "verified" },
|
||||||
|
{ id: "cursor", name: "Cursor", bins: ["cursor-agent", "cursor"], installHint: "安装 Cursor 并确保 CLI 在 PATH", status: "verified" },
|
||||||
|
{ id: "copilot", name: "Copilot", bins: ["copilot"], installHint: "GitHub Copilot CLI 安装说明", status: "verified" },
|
||||||
|
{ id: "opencode", name: "OpenCode", bins: ["opencode"], installHint: "npm i -g opencode / 见 OpenCode 文档", status: "verified" },
|
||||||
|
{ id: "pi", name: "Pi", bins: ["pi-acp", "pi", "pi-coding-agent"], installHint: "npm i -g pi-acp(或 Pi coding agent + ACP 适配器)", status: "verified" },
|
||||||
|
{ id: "devin", name: "Devin CLI", bins: ["devin"], installHint: "Devin CLI 官方安装", status: "verified" },
|
||||||
|
{ id: "dsh", name: "dsh", bins: ["dsh"], installHint: "npm i -g @deepseek-ai/dsh", status: "verified" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function catalogById(id: string): ProviderCatalogEntry | undefined {
|
||||||
|
return PROVIDER_CATALOG.find((p) => p.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function providerCreatable(status: ProviderStatus): boolean {
|
||||||
|
return status !== "planned";
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
// The user's own `claude` CLI driven over its stream-json protocol (no SDK):
|
||||||
|
// claude -p --input-format stream-json --output-format stream-json --verbose --include-partial-messages
|
||||||
|
// --permission-prompt-tool stdio [--model m] [--permission-mode p] [--effort e] [--resume id]
|
||||||
|
// stdin and stdout carry one JSON object per line. Besides the conversation messages (user / assistant / system /
|
||||||
|
// stream_event / result), both sides send control messages:
|
||||||
|
// → {type:"control_request", request_id, request:{subtype:"initialize" | "interrupt" | "set_model" | "set_permission_mode", ...}}
|
||||||
|
// ← {type:"control_response", response:{subtype:"success" | "error", request_id, response? | error?}}
|
||||||
|
// ← {type:"control_request", request_id, request:{subtype:"can_use_tool", tool_name, input, tool_use_id, ...}}
|
||||||
|
// → {type:"control_response", response:{subtype:"success", request_id, response:{behavior:"allow", updatedInput} | {behavior:"deny", message, interrupt?}}}
|
||||||
|
// ← {type:"control_cancel_request", request_id} (the CLI no longer waits for that answer)
|
||||||
|
import type { ChildProcess } from "node:child_process";
|
||||||
|
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
|
||||||
|
import { AsyncQueue } from "../../util/queue.js";
|
||||||
|
|
||||||
|
export type ClaudeBin = ResolveResult & { ok: true };
|
||||||
|
export type Json = Record<string, unknown>;
|
||||||
|
|
||||||
|
export type ClaudeCliOpts = {
|
||||||
|
bin: ClaudeBin;
|
||||||
|
cwd: string;
|
||||||
|
model: string | null;
|
||||||
|
permissionMode: string;
|
||||||
|
effort: string | null;
|
||||||
|
resume: string | null;
|
||||||
|
env?: NodeJS.ProcessEnv;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PermissionDecision =
|
||||||
|
| { behavior: "allow"; updatedInput: Json }
|
||||||
|
| { behavior: "deny"; message: string; interrupt?: boolean };
|
||||||
|
|
||||||
|
export type ToolRequest = { toolName: string; input: Json; toolUseId?: string; signal: AbortSignal };
|
||||||
|
export type CanUseTool = (req: ToolRequest) => Promise<PermissionDecision>;
|
||||||
|
|
||||||
|
/** Session ids and model / mode / effort names become argv: plain tokens only, so nothing can turn into another flag. */
|
||||||
|
const SAFE_ARG = /^[A-Za-z0-9][A-Za-z0-9._:\[\]\/@+-]{0,199}$/;
|
||||||
|
|
||||||
|
export function claudeArgs(o: Pick<ClaudeCliOpts, "model" | "permissionMode" | "effort" | "resume">): string[] {
|
||||||
|
const args = [
|
||||||
|
"-p",
|
||||||
|
"--input-format", "stream-json",
|
||||||
|
"--output-format", "stream-json",
|
||||||
|
"--verbose",
|
||||||
|
"--include-partial-messages",
|
||||||
|
"--permission-prompt-tool", "stdio",
|
||||||
|
"--setting-sources", "user,project,local",
|
||||||
|
];
|
||||||
|
const put = (flag: string, v: string | null | undefined) => {
|
||||||
|
if (!v) return;
|
||||||
|
if (!SAFE_ARG.test(v)) throw new Error(`Refusing to pass an unexpected value to claude ${flag}: ${JSON.stringify(v).slice(0, 80)}`);
|
||||||
|
args.push(flag, v);
|
||||||
|
};
|
||||||
|
put("--permission-mode", o.permissionMode);
|
||||||
|
// claude only takes bypassPermissions when it is allowed at launch; it is not allowed otherwise (a later switch
|
||||||
|
// into it restarts the CLI with --resume)
|
||||||
|
if (o.permissionMode === "bypassPermissions") args.push("--allow-dangerously-skip-permissions");
|
||||||
|
put("--model", o.model);
|
||||||
|
put("--effort", o.effort);
|
||||||
|
put("--resume", o.resume);
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Pending = { resolve: (v: Json) => void; reject: (e: Error) => void; timer?: NodeJS.Timeout };
|
||||||
|
|
||||||
|
export class ClaudeCli {
|
||||||
|
/** Conversation messages (everything that is not a control message) */
|
||||||
|
readonly messages = new AsyncQueue<Json>();
|
||||||
|
readonly exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
|
||||||
|
/** The answer to initialize (commands, models, account …), null when it failed */
|
||||||
|
readonly initialized: Promise<Json | null>;
|
||||||
|
private child: ChildProcess;
|
||||||
|
private buf = "";
|
||||||
|
private seq = 0;
|
||||||
|
private pending = new Map<string, Pending>();
|
||||||
|
private cancels = new Map<string, AbortController>();
|
||||||
|
private stderrTail = "";
|
||||||
|
private dead = false;
|
||||||
|
private spawnError: Error | null = null;
|
||||||
|
|
||||||
|
constructor(private o: ClaudeCliOpts, private canUseTool: CanUseTool) {
|
||||||
|
const args = claudeArgs(o);
|
||||||
|
this.child = spawnBin(o.bin, args, {
|
||||||
|
cwd: o.cwd,
|
||||||
|
env: { ...(o.env ?? process.env), NO_COLOR: "1", FORCE_COLOR: "0" },
|
||||||
|
stdio: ["pipe", "pipe", "pipe"],
|
||||||
|
group: true,
|
||||||
|
});
|
||||||
|
this.child.stdout?.setEncoding("utf8");
|
||||||
|
this.child.stdout?.on("data", (d: string) => this.onData(d));
|
||||||
|
this.child.stderr?.on("data", (d: Buffer) => {
|
||||||
|
this.stderrTail = (this.stderrTail + d.toString()).slice(-4096);
|
||||||
|
});
|
||||||
|
this.child.stdin?.on("error", () => {}); // EPIPE after the CLI exits: reported through exited
|
||||||
|
this.exited = new Promise((resolve) => {
|
||||||
|
this.child.on("error", (e) => {
|
||||||
|
this.spawnError = e;
|
||||||
|
this.finish();
|
||||||
|
resolve({ code: null, signal: null });
|
||||||
|
});
|
||||||
|
this.child.on("close", (code, signal) => {
|
||||||
|
this.finish();
|
||||||
|
resolve({ code, signal });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
this.initialized = this.request({ subtype: "initialize" }, 60000).catch(() => null);
|
||||||
|
}
|
||||||
|
|
||||||
|
get stderr(): string {
|
||||||
|
return this.stderrTail;
|
||||||
|
}
|
||||||
|
|
||||||
|
get failure(): Error | null {
|
||||||
|
return this.spawnError;
|
||||||
|
}
|
||||||
|
|
||||||
|
get alive(): boolean {
|
||||||
|
return !this.dead;
|
||||||
|
}
|
||||||
|
|
||||||
|
private finish(): void {
|
||||||
|
if (this.dead) return;
|
||||||
|
this.dead = true;
|
||||||
|
for (const [, p] of this.pending) {
|
||||||
|
if (p.timer) clearTimeout(p.timer);
|
||||||
|
p.reject(new Error("claude exited"));
|
||||||
|
}
|
||||||
|
this.pending.clear();
|
||||||
|
for (const [, c] of this.cancels) c.abort();
|
||||||
|
this.cancels.clear();
|
||||||
|
this.messages.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private onData(d: string): void {
|
||||||
|
this.buf += d;
|
||||||
|
let i: number;
|
||||||
|
while ((i = this.buf.indexOf("\n")) >= 0) {
|
||||||
|
const line = this.buf.slice(0, i).trim();
|
||||||
|
this.buf = this.buf.slice(i + 1);
|
||||||
|
if (!line) continue;
|
||||||
|
let m: Json;
|
||||||
|
try {
|
||||||
|
m = JSON.parse(line);
|
||||||
|
} catch {
|
||||||
|
continue; // a stray non-JSON line (warnings some versions print) is not part of the protocol
|
||||||
|
}
|
||||||
|
if (m && typeof m === "object") this.onMessage(m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private onMessage(m: Json): void {
|
||||||
|
if (m.type === "control_response") {
|
||||||
|
const r = (m.response ?? {}) as Json;
|
||||||
|
const id = String(r.request_id ?? "");
|
||||||
|
const p = this.pending.get(id);
|
||||||
|
if (!p) return;
|
||||||
|
this.pending.delete(id);
|
||||||
|
if (p.timer) clearTimeout(p.timer);
|
||||||
|
if (r.subtype === "success") p.resolve((r.response ?? {}) as Json);
|
||||||
|
else p.reject(new Error(String(r.error ?? "control request failed")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (m.type === "control_request") {
|
||||||
|
void this.onControlRequest(String(m.request_id ?? ""), (m.request ?? {}) as Json);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (m.type === "control_cancel_request") {
|
||||||
|
const id = String(m.request_id ?? "");
|
||||||
|
this.cancels.get(id)?.abort();
|
||||||
|
this.cancels.delete(id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (m.type === "keep_alive") return;
|
||||||
|
this.messages.push(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async onControlRequest(id: string, req: Json): Promise<void> {
|
||||||
|
if (req.subtype !== "can_use_tool") {
|
||||||
|
// hooks, in-process MCP servers, elicitation …: none are registered, so say so instead of leaving the CLI waiting
|
||||||
|
this.write({ type: "control_response", response: { subtype: "error", request_id: id, error: `Unsupported control request: ${String(req.subtype)}` } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const ac = new AbortController();
|
||||||
|
this.cancels.set(id, ac);
|
||||||
|
try {
|
||||||
|
const decision = await this.canUseTool({
|
||||||
|
toolName: String(req.tool_name ?? ""),
|
||||||
|
input: (req.input && typeof req.input === "object" ? req.input : {}) as Json,
|
||||||
|
toolUseId: typeof req.tool_use_id === "string" ? req.tool_use_id : undefined,
|
||||||
|
signal: ac.signal,
|
||||||
|
});
|
||||||
|
if (ac.signal.aborted && !this.cancels.has(id)) return; // cancelled by the CLI: it no longer reads this answer
|
||||||
|
this.write({ type: "control_response", response: { subtype: "success", request_id: id, response: decision } });
|
||||||
|
} catch (e) {
|
||||||
|
this.write({ type: "control_response", response: { subtype: "error", request_id: id, error: String((e as Error)?.message ?? e) } });
|
||||||
|
} finally {
|
||||||
|
this.cancels.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private write(o: Json): boolean {
|
||||||
|
if (this.dead || !this.child.stdin || this.child.stdin.destroyed) return false;
|
||||||
|
try {
|
||||||
|
this.child.stdin.write(JSON.stringify(o) + "\n");
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Send one control request and wait for its answer */
|
||||||
|
request(request: Json, timeoutMs = 10000): Promise<Json> {
|
||||||
|
if (this.dead) return Promise.reject(new Error("claude is not running"));
|
||||||
|
const id = `ac_${++this.seq}_${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
return new Promise<Json>((resolve, reject) => {
|
||||||
|
const p: Pending = { resolve, reject };
|
||||||
|
p.timer = setTimeout(() => {
|
||||||
|
if (this.pending.delete(id)) reject(new Error(`claude did not answer ${String(request.subtype)} in ${Math.round(timeoutMs / 1000)} s`));
|
||||||
|
}, timeoutMs);
|
||||||
|
this.pending.set(id, p);
|
||||||
|
if (!this.write({ type: "control_request", request_id: id, request })) {
|
||||||
|
this.pending.delete(id);
|
||||||
|
clearTimeout(p.timer);
|
||||||
|
reject(new Error("claude is not running"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One user message into the conversation */
|
||||||
|
sendUser(content: unknown[], sessionId: string | null): boolean {
|
||||||
|
return this.write({ type: "user", message: { role: "user", content }, parent_tool_use_id: null, session_id: sessionId ?? "" });
|
||||||
|
}
|
||||||
|
|
||||||
|
interrupt(): Promise<Json> {
|
||||||
|
return this.request({ subtype: "interrupt" }, 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
setModel(model: string | null): Promise<Json> {
|
||||||
|
return this.request(model ? { subtype: "set_model", model } : { subtype: "set_model" });
|
||||||
|
}
|
||||||
|
|
||||||
|
setPermissionMode(mode: string): Promise<Json> {
|
||||||
|
return this.request({ subtype: "set_permission_mode", mode });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** End stdin (the CLI finishes and exits), then end the process tree if it lingers */
|
||||||
|
async close(graceMs = 2000): Promise<void> {
|
||||||
|
try {
|
||||||
|
this.child.stdin?.end();
|
||||||
|
} catch {}
|
||||||
|
const done = await Promise.race([this.exited.then(() => true), new Promise<boolean>((r) => setTimeout(() => r(false), graceMs))]);
|
||||||
|
if (!done) await killTree(this.child, { graceMs: 500 });
|
||||||
|
this.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
// One user message → the content blocks of a claude stream-json user message (Anthropic Messages content).
|
||||||
|
// - PNG / JPEG / GIF / WebP (Base64ImageSource's media types), up to 5 MB each: an image block
|
||||||
|
// - text files up to 1 MB: a document block with a plain-text source (DocumentBlockParam + PlainTextSource)
|
||||||
|
// - anything else, or too large: the file's absolute path in the text, which Claude Code can Read; with a warning
|
||||||
|
// for files that aren't images or text, so the user knows
|
||||||
|
import { readFile, stat } from "node:fs/promises";
|
||||||
|
import { basename } from "node:path";
|
||||||
|
import { resolveImagePath } from "../../util/attachmentRefs.js";
|
||||||
|
import { attachmentKind, baseMime, pathNote } from "../../util/attachmentKinds.js";
|
||||||
|
|
||||||
|
/** Anthropic's per-image limit */
|
||||||
|
export const CLAUDE_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
||||||
|
export const CLAUDE_MAX_TEXT_BYTES = 1024 * 1024;
|
||||||
|
|
||||||
|
type ImageMedia = "image/png" | "image/jpeg" | "image/gif" | "image/webp";
|
||||||
|
export type ClaudeBlock =
|
||||||
|
| { type: "text"; text: string }
|
||||||
|
| { type: "image"; source: { type: "base64"; media_type: ImageMedia; data: string } }
|
||||||
|
| { type: "document"; source: { type: "text"; media_type: "text/plain"; data: string }; title?: string; context?: string };
|
||||||
|
|
||||||
|
export async function buildClaudeContent(
|
||||||
|
text: string,
|
||||||
|
attachments: { path: string; mime: string }[],
|
||||||
|
): Promise<{ blocks: ClaudeBlock[]; warnings: string[] }> {
|
||||||
|
const media: ClaudeBlock[] = [];
|
||||||
|
const notes: string[] = [];
|
||||||
|
const warnings: string[] = [];
|
||||||
|
for (const a of attachments) {
|
||||||
|
let file: string;
|
||||||
|
let size: number;
|
||||||
|
try {
|
||||||
|
file = await resolveImagePath(a.path);
|
||||||
|
size = (await stat(file)).size;
|
||||||
|
} catch (e) {
|
||||||
|
warnings.push(`${a.path}: ${String((e as Error)?.message ?? e)}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kind = attachmentKind(a.mime);
|
||||||
|
try {
|
||||||
|
if (kind === "image" && size <= CLAUDE_MAX_IMAGE_BYTES) {
|
||||||
|
const data = (await readFile(file)).toString("base64");
|
||||||
|
media.push({ type: "image", source: { type: "base64", media_type: baseMime(a.mime) as ImageMedia, data } });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (kind === "text" && size <= CLAUDE_MAX_TEXT_BYTES) {
|
||||||
|
const data = await readFile(file, "utf8");
|
||||||
|
media.push({ type: "document", source: { type: "text", media_type: "text/plain", data }, title: basename(file), context: file });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
warnings.push(`${basename(file)}: ${String((e as Error)?.message ?? e)}`);
|
||||||
|
}
|
||||||
|
notes.push(pathNote(kind, file));
|
||||||
|
if (kind === "other") warnings.push(`${basename(file)} (${baseMime(a.mime) || "unknown type"}) is not an image or a text file; sent its path`);
|
||||||
|
else if (kind === "image" && size > CLAUDE_MAX_IMAGE_BYTES) warnings.push(`${basename(file)}: ${(size / 1024 / 1024).toFixed(1)} MB, over Claude's 5 MB image limit; sent its path`);
|
||||||
|
else if (kind === "text" && size > CLAUDE_MAX_TEXT_BYTES) warnings.push(`${basename(file)}: ${(size / 1024 / 1024).toFixed(1)} MB, too large to attach inline; sent its path`);
|
||||||
|
}
|
||||||
|
const fullText = [text, ...(notes.length ? [notes.join("\n")] : [])].filter(Boolean).join("\n\n");
|
||||||
|
// Media first, as before; the text block always comes last (claude needs at least one block)
|
||||||
|
return { blocks: [...media, { type: "text", text: fullText }], warnings };
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
// claude stream-json messages (and ~/.claude/projects jsonl lines) → ProviderEvent (§7.2.3). Ported from normalize in lib/agents/claude.mjs.
|
||||||
|
import type { ProviderEvent } from "../../timeline/types.js";
|
||||||
|
import { callInfo, todoItems } from "../../agents/kinds.js";
|
||||||
|
import { editDetail } from "../../agents/diff.js";
|
||||||
|
|
||||||
|
const MAX_OUTPUT = 20 * 1024;
|
||||||
|
const ANSI_RE = /\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07/g;
|
||||||
|
const clean = (s: string): string => String(s ?? "").replace(ANSI_RE, "");
|
||||||
|
|
||||||
|
export type MapState = {
|
||||||
|
blocks: Map<number, string>; // content_block_start index → block type
|
||||||
|
msgId: string; // Current streaming message.id
|
||||||
|
// Streaming block index → unified itemId (msgId:type:ordinal within type).
|
||||||
|
// claude's content_block index interleaves thinking/text, while the content array of the assistant event
|
||||||
|
// may be renumbered (when thinking is split into another message, text goes back to 0) — a bare index would make
|
||||||
|
// the delta and complete event itemIds diverge and the frontend render two duplicate replies. Align both sides by type + ordinal within type.
|
||||||
|
itemIdByBlock: Map<number, string>;
|
||||||
|
typeSeq: Map<string, number>; // Count of each block type in the current message (delta side)
|
||||||
|
sawInterrupt: boolean; // After interrupt() the next result counts as interrupted
|
||||||
|
};
|
||||||
|
|
||||||
|
export function newMapState(): MapState {
|
||||||
|
return { blocks: new Map(), msgId: "", itemIdByBlock: new Map(), typeSeq: new Map(), sawInterrupt: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Block type → short code and channel for itemIds; thinking/reasoning are one kind, text another; tool_use uses the tool id and doesn't go through here
|
||||||
|
const blockKind = (t: string): string =>
|
||||||
|
t === "thinking" || t === "redacted_thinking" ? "k" : t === "text" ? "t" : "x";
|
||||||
|
|
||||||
|
function itemIdFor(st: MapState, blockIdx: number, blkType: string): string {
|
||||||
|
const k = blockKind(blkType);
|
||||||
|
const n = st.typeSeq.get(k) ?? 0;
|
||||||
|
st.typeSeq.set(k, n + 1);
|
||||||
|
const id = `${st.msgId}:${k}${n}`;
|
||||||
|
st.itemIdByBlock.set(blockIdx, id);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rec = Record<string, unknown>;
|
||||||
|
const rec = (v: unknown): Rec => (v && typeof v === "object" ? (v as Rec) : {});
|
||||||
|
const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
|
||||||
|
|
||||||
|
// One stream-json message → 0..n unified events
|
||||||
|
export function mapSdkMessage(m: unknown, st: MapState, cwd: string): ProviderEvent[] {
|
||||||
|
const out: ProviderEvent[] = [];
|
||||||
|
if (!m || typeof m !== "object") return out;
|
||||||
|
const r = m as unknown as Rec;
|
||||||
|
|
||||||
|
if (r.type === "system") {
|
||||||
|
if (r.subtype === "init") {
|
||||||
|
const sid = str(r.session_id) ?? "";
|
||||||
|
if (sid) out.push({ type: "provider_session_id", id: sid });
|
||||||
|
}
|
||||||
|
// compact_boundary / status / api_retry etc. → lightweight notices
|
||||||
|
if (r.subtype === "api_retry") {
|
||||||
|
out.push({ type: "notice", level: "warn", message: `API 重试中(第 ${r.attempt ?? "?"} 次)` });
|
||||||
|
}
|
||||||
|
if (r.subtype === "compact_boundary") {
|
||||||
|
out.push({ type: "notice", level: "info", message: "上下文已压缩" });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (r.type === "stream_event") {
|
||||||
|
const e = rec(r.event);
|
||||||
|
if (e.type === "message_start") {
|
||||||
|
const mid = str(rec(e.message).id);
|
||||||
|
if (mid) st.msgId = mid;
|
||||||
|
st.blocks.clear();
|
||||||
|
st.itemIdByBlock.clear();
|
||||||
|
st.typeSeq.clear();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (e.type === "content_block_start") {
|
||||||
|
const idx = typeof e.index === "number" ? e.index : 0;
|
||||||
|
const bt = str(rec(e.content_block).type) ?? "";
|
||||||
|
st.blocks.set(idx, bt);
|
||||||
|
itemIdFor(st, idx, bt); // Register index → unified itemId
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (e.type === "content_block_delta") {
|
||||||
|
const idx = typeof e.index === "number" ? e.index : 0;
|
||||||
|
const d = rec(e.delta);
|
||||||
|
// Fallback when a delta arrives before its start: infer and register from the delta type
|
||||||
|
const itemId = st.itemIdByBlock.get(idx) ?? itemIdFor(st, idx, d.type === "thinking_delta" ? "thinking" : "text");
|
||||||
|
if (d.type === "text_delta" && typeof d.text === "string" && d.text) {
|
||||||
|
out.push({ type: "assistant_delta", itemId, text: d.text });
|
||||||
|
} else if (d.type === "thinking_delta") {
|
||||||
|
const t = str(d.thinking) ?? str(d.text);
|
||||||
|
if (t) out.push({ type: "reasoning_delta", itemId, text: t });
|
||||||
|
}
|
||||||
|
// Ignore input_json_delta: wait for the complete tool_use in the assistant message
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (r.type === "assistant") {
|
||||||
|
const mid = str(rec(r.message).id) ?? st.msgId ?? "";
|
||||||
|
const content = rec(r.message).content;
|
||||||
|
const parts = Array.isArray(content) ? content : [];
|
||||||
|
// Same rule as the streaming side: build itemIds from type + ordinal within type so they overwrite the matching deltas
|
||||||
|
const seqs = new Map<string, number>();
|
||||||
|
parts.forEach((p) => {
|
||||||
|
const blk = rec(p);
|
||||||
|
const t = str(blk.type) ?? "";
|
||||||
|
const k = blockKind(t);
|
||||||
|
const n = seqs.get(k) ?? 0;
|
||||||
|
seqs.set(k, n + 1);
|
||||||
|
const itemId = `${mid}:${k}${n}`;
|
||||||
|
if (blk.type === "text" && typeof blk.text === "string" && blk.text) {
|
||||||
|
out.push({ type: "assistant_message", itemId, text: blk.text });
|
||||||
|
} else if (blk.type === "thinking" || blk.type === "redacted_thinking") {
|
||||||
|
const t2 = str(blk.thinking) ?? str(blk.text);
|
||||||
|
if (t2) out.push({ type: "reasoning", itemId, text: t2 });
|
||||||
|
} else if (blk.type === "tool_use") {
|
||||||
|
out.push(...mapToolUse(blk, cwd));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (r.type === "user") {
|
||||||
|
const content = rec(r.message).content;
|
||||||
|
const parts = Array.isArray(content) ? content : [];
|
||||||
|
for (const p of parts) {
|
||||||
|
const blk = rec(p);
|
||||||
|
if (blk.type === "tool_result") {
|
||||||
|
const output = clean(contentText(blk.content));
|
||||||
|
out.push({
|
||||||
|
type: "tool_call",
|
||||||
|
itemId: str(blk.tool_use_id) ?? "",
|
||||||
|
kind: "other",
|
||||||
|
title: "",
|
||||||
|
status: blk.is_error ? "failed" : "ok",
|
||||||
|
output: output.length > MAX_OUTPUT ? output.slice(0, MAX_OUTPUT) : output,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (r.type === "result") {
|
||||||
|
const usage = rec(r.usage);
|
||||||
|
const num = (k: string): number => (typeof usage[k] === "number" ? (usage[k] as number) : 0);
|
||||||
|
out.push({
|
||||||
|
type: "usage",
|
||||||
|
inputTokens: num("input_tokens"),
|
||||||
|
outputTokens: num("output_tokens"),
|
||||||
|
cacheReadTokens: num("cache_read_input_tokens"),
|
||||||
|
costUsd: typeof r.total_cost_usd === "number" ? r.total_cost_usd : 0,
|
||||||
|
});
|
||||||
|
const subtype = str(r.subtype) ?? "";
|
||||||
|
const interrupted = st.sawInterrupt || /interrupt/i.test(subtype);
|
||||||
|
const isError = r.is_error === true;
|
||||||
|
out.push({
|
||||||
|
type: "turn_ended",
|
||||||
|
turnId: "", // The session fills in the current turnId
|
||||||
|
status: interrupted ? "interrupted" : isError ? "failed" : "completed",
|
||||||
|
durationMs: typeof r.duration_ms === "number" ? r.duration_ms : undefined,
|
||||||
|
error: isError && !interrupted ? str(r.result) ?? subtype : undefined,
|
||||||
|
filesChanged: typeof r.num_turns === "number" ? undefined : undefined,
|
||||||
|
});
|
||||||
|
st.sawInterrupt = false;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapToolUse(blk: Rec, cwd: string): ProviderEvent[] {
|
||||||
|
const input = rec(blk.input);
|
||||||
|
const name = str(blk.name) ?? "tool";
|
||||||
|
const id = str(blk.id) ?? "";
|
||||||
|
const info = callInfo(name, { ...input, _exists: true }, cwd);
|
||||||
|
let detail: unknown = info.detail;
|
||||||
|
if (info.kind === "edit" && (input.old_string !== undefined || Array.isArray(input.edits))) {
|
||||||
|
detail = editDetail({ path: (info.detail as Rec).path as string, old: input.old_string, new: input.new_string, edits: input.edits });
|
||||||
|
}
|
||||||
|
if (info.kind === "write" && typeof input.content === "string") {
|
||||||
|
const lines = input.content.split("\n");
|
||||||
|
detail = { path: (info.detail as Rec).path, lines: lines.slice(0, 200), totalLines: lines.length };
|
||||||
|
}
|
||||||
|
const out: ProviderEvent[] = [
|
||||||
|
{
|
||||||
|
type: "tool_call",
|
||||||
|
itemId: id,
|
||||||
|
kind: info.kind,
|
||||||
|
title: info.title,
|
||||||
|
status: "running",
|
||||||
|
input,
|
||||||
|
detail,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
if (name === "TodoWrite") {
|
||||||
|
out.push({ type: "todo", items: todoItems((input.todos as { content?: string; status?: string }[]) ?? []) });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function contentText(content: unknown): string {
|
||||||
|
if (typeof content === "string") return content;
|
||||||
|
if (Array.isArray(content)) return content.map((p) => str(rec(p).text) ?? "").join("");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
// Model list (§7.2.7): Claude Code has no model query API.
|
||||||
|
// Behind the magpie gateway, gateway models, the default model and thinking levels are filled in by providers/magpieGateway.ts;
|
||||||
|
// without magpie only "Default" is offered (the frontend always shows it; no empty-id placeholder is added here anymore).
|
||||||
|
import type { ModelInfo } from "../types.js";
|
||||||
|
|
||||||
|
export async function listClaudeModels(): Promise<ModelInfo[]> {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// Claude Provider (§7.2): detection + createSession(ClaudeSession).
|
||||||
|
import type { Provider, ProviderSession, DetectResult, ModelInfo, HistoryItem } from "../types.js";
|
||||||
|
import { resolveBin, killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
|
||||||
|
import { ClaudeSession } from "./session.js";
|
||||||
|
import { listClaudeModels } from "./models.js";
|
||||||
|
import { listClaudeHistory, readClaudeHistory } from "../../history/import.js";
|
||||||
|
import { mapSdkMessage, newMapState } from "./map.js";
|
||||||
|
import type { ProviderEvent } from "../../timeline/types.js";
|
||||||
|
import { tr } from "../../util/i18n.js";
|
||||||
|
|
||||||
|
const INSTALL_HINT = "npm i -g @anthropic-ai/claude-code";
|
||||||
|
|
||||||
|
export const claudeCapabilities = {
|
||||||
|
resume: true,
|
||||||
|
interrupt: true,
|
||||||
|
steer: false, // Claude doesn't support real steering — the manager queues instead (§7.2.2)
|
||||||
|
images: true,
|
||||||
|
plan: true,
|
||||||
|
questions: true,
|
||||||
|
cost: true,
|
||||||
|
effort: ["low", "medium", "high", "xhigh", "max"],
|
||||||
|
modes: ["plan", "default", "acceptEdits", "bypassPermissions"] as ("plan" | "default" | "acceptEdits" | "bypassPermissions")[],
|
||||||
|
};
|
||||||
|
|
||||||
|
function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 5000): Promise<string> {
|
||||||
|
return new Promise((resolvePromise, reject) => {
|
||||||
|
let out = "";
|
||||||
|
const p = spawnBin(r, args, { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" } });
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
void killTree(p, { graceMs: 500 }); // On Windows a .cmd wrapper must be killed together with its child processes
|
||||||
|
} catch {}
|
||||||
|
reject(new Error("timeout"));
|
||||||
|
}, timeoutMs);
|
||||||
|
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.on("error", reject);
|
||||||
|
p.on("close", (code) => {
|
||||||
|
clearTimeout(t);
|
||||||
|
if (code === 0) resolvePromise(out);
|
||||||
|
else reject(new Error("exit " + code));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createClaudeProvider(): Provider {
|
||||||
|
return {
|
||||||
|
id: "claude",
|
||||||
|
name: "Claude Code",
|
||||||
|
capabilities: claudeCapabilities,
|
||||||
|
async detect(): Promise<DetectResult> {
|
||||||
|
const bin = await resolveBin("claude");
|
||||||
|
if (!bin.ok) return { available: false, reason: bin.reason, installHint: INSTALL_HINT };
|
||||||
|
try {
|
||||||
|
const version = await runVersion(bin, ["--version"]);
|
||||||
|
return { available: true, bin: bin.display, version: version.trim().split("\n")[0] || "" };
|
||||||
|
} catch {
|
||||||
|
return { available: true, bin: bin.display, version: "" };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async listModels(): Promise<ModelInfo[]> {
|
||||||
|
return listClaudeModels();
|
||||||
|
},
|
||||||
|
async createSession(o): Promise<ProviderSession> {
|
||||||
|
const bin = await resolveBin("claude");
|
||||||
|
if (!bin.ok) throw new Error(tr("claude.notFound", { detail: bin.reason, hint: INSTALL_HINT }));
|
||||||
|
return new ClaudeSession({
|
||||||
|
threadId: o.threadId,
|
||||||
|
cwd: o.cwd,
|
||||||
|
model: o.model,
|
||||||
|
mode: o.mode,
|
||||||
|
effort: o.effort,
|
||||||
|
resumeId: o.resumeId,
|
||||||
|
bin,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// §7.6: jsonl sessions under ~/.claude/projects matched by cwd
|
||||||
|
async listHistory(cwd: string): Promise<HistoryItem[]> {
|
||||||
|
const items = await listClaudeHistory(cwd);
|
||||||
|
return items.map((i) => ({ provider: "claude", ...i, imported: false }));
|
||||||
|
},
|
||||||
|
async readHistory(sessionId: string, cwd: string): Promise<ProviderEvent[]> {
|
||||||
|
const msgs = await readClaudeHistory(sessionId, cwd);
|
||||||
|
const st = newMapState();
|
||||||
|
const out: ProviderEvent[] = [];
|
||||||
|
for (const m of msgs) {
|
||||||
|
const r = m as { type?: string; message?: { content?: unknown } };
|
||||||
|
// User text messages don't appear as events in claude's stream-json output (the manager writes user_message itself); emit them here
|
||||||
|
if (r.type === "user") {
|
||||||
|
const content = r.message?.content;
|
||||||
|
const text = typeof content === "string"
|
||||||
|
? content
|
||||||
|
: Array.isArray(content)
|
||||||
|
? (content as { type?: string; text?: string }[]).filter((b) => b.type === "text").map((b) => b.text ?? "").join("")
|
||||||
|
: "";
|
||||||
|
if (text.trim()) out.push({ type: "user_message", text });
|
||||||
|
else out.push(...mapSdkMessage(m as never, st, cwd)); // tool_result and the like still go through the mapping
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push(...mapSdkMessage(m as never, st, cwd));
|
||||||
|
}
|
||||||
|
// Finish: an imported session is closed
|
||||||
|
out.push({ type: "turn_ended", turnId: "", status: "completed" });
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,361 @@
|
|||||||
|
// Claude ProviderSession (§7.2.2/7.2.4/7.2.5/7.2.6): the user's own `claude` CLI over stream-json (./cli.ts),
|
||||||
|
// one process per conversation, streaming, permissions, interrupt, hot switching. No SDK.
|
||||||
|
import type { ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
|
||||||
|
import type { ProviderEvent } from "../../timeline/types.js";
|
||||||
|
import { AsyncQueue } from "../../util/queue.js";
|
||||||
|
import { callInfo } from "../../agents/kinds.js";
|
||||||
|
import { editDetail } from "../../agents/diff.js";
|
||||||
|
import { mapSdkMessage, newMapState, type MapState } from "./map.js";
|
||||||
|
import { log } from "../../log.js";
|
||||||
|
import { buildClaudeContent } from "./content.js";
|
||||||
|
import { tr } from "../../util/i18n.js";
|
||||||
|
import { classifyClaudeSlashCommand, sortSlashCommands } from "../slash.js";
|
||||||
|
import { ClaudeCli, type ClaudeBin, type PermissionDecision, type ToolRequest } from "./cli.js";
|
||||||
|
|
||||||
|
const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
||||||
|
const MODES = ["plan", "default", "acceptEdits", "bypassPermissions"];
|
||||||
|
const rid = () => Math.random().toString(36).slice(2, 10);
|
||||||
|
|
||||||
|
type PendingReq = {
|
||||||
|
kind: "permission" | "question";
|
||||||
|
resolve: (r: RespondAnswer) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ClaudeSessionOpts = {
|
||||||
|
threadId: string;
|
||||||
|
cwd: string;
|
||||||
|
model: string | null;
|
||||||
|
mode: Mode;
|
||||||
|
effort: string | null;
|
||||||
|
resumeId: string | null;
|
||||||
|
/** The user's claude, as resolveBin found it (a .cmd / .ps1 shim is started through cmd.exe / PowerShell by spawnBin) */
|
||||||
|
bin: ClaudeBin;
|
||||||
|
/** Environment for the CLI (tests point it at a stand-in); process.env when absent */
|
||||||
|
env?: NodeJS.ProcessEnv;
|
||||||
|
onModeChange?: (mode: Mode) => void; // Callback when a plan is approved → default (the manager updates meta)
|
||||||
|
};
|
||||||
|
|
||||||
|
export class ClaudeSession implements ProviderSession {
|
||||||
|
events: AsyncIterable<ProviderEvent>;
|
||||||
|
private q = new AsyncQueue<ProviderEvent>();
|
||||||
|
private cli: ClaudeCli | null = null;
|
||||||
|
private sessionId: string | null;
|
||||||
|
private turnId: string | null = null;
|
||||||
|
private turnNum = 0;
|
||||||
|
private st: MapState = newMapState();
|
||||||
|
private pending = new Map<string, PendingReq>();
|
||||||
|
private needsRestart = false;
|
||||||
|
private restarting: Promise<void> | null = null;
|
||||||
|
private closed = false;
|
||||||
|
private stopping = new WeakSet<ClaudeCli>();
|
||||||
|
private pumpDone: Promise<void> | null = null;
|
||||||
|
/** Mode the running CLI was started with (bypassPermissions has to be allowed at launch) */
|
||||||
|
private launchedMode: string | null = null;
|
||||||
|
|
||||||
|
constructor(private o: ClaudeSessionOpts) {
|
||||||
|
this.sessionId = o.resumeId;
|
||||||
|
this.events = this.q;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The CLI is only started before the first send (or a command list request)
|
||||||
|
private ensureCli(): ClaudeCli {
|
||||||
|
if (this.cli && !this.needsRestart) return this.cli;
|
||||||
|
this.st = newMapState();
|
||||||
|
const effort = this.o.effort && EFFORTS.includes(this.o.effort) ? this.o.effort : null;
|
||||||
|
const cli = new ClaudeCli(
|
||||||
|
{
|
||||||
|
bin: this.o.bin,
|
||||||
|
cwd: this.o.cwd,
|
||||||
|
model: this.o.model,
|
||||||
|
permissionMode: MODES.includes(this.o.mode) ? this.o.mode : "default",
|
||||||
|
effort,
|
||||||
|
resume: this.sessionId,
|
||||||
|
env: this.o.env,
|
||||||
|
},
|
||||||
|
(req) => this.canUseTool(req),
|
||||||
|
);
|
||||||
|
this.cli = cli;
|
||||||
|
this.launchedMode = this.o.mode;
|
||||||
|
this.needsRestart = false;
|
||||||
|
this.pumpDone = this.pump(cli);
|
||||||
|
return cli;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pump(cli: ClaudeCli): Promise<void> {
|
||||||
|
for await (const m of cli.messages) {
|
||||||
|
for (const ev of mapSdkMessage(m, this.st, this.o.cwd)) this.emit(ev);
|
||||||
|
}
|
||||||
|
const exit = await cli.exited;
|
||||||
|
// A CLI this session stopped on purpose (restart / close) is not a crash
|
||||||
|
if (this.closed || this.stopping.has(cli)) return;
|
||||||
|
const detail = cli.failure
|
||||||
|
? tr("claude.startFailed", { detail: String(cli.failure.message) })
|
||||||
|
: tr("claude.exited", { code: String(exit.code ?? exit.signal ?? "?") });
|
||||||
|
const tail = cli.stderr.trim().slice(-400);
|
||||||
|
this.emit({ type: "notice", level: "error", message: tail ? `${detail} — stderr: ${tail}` : detail });
|
||||||
|
if (this.turnId) this.emit({ type: "turn_ended", turnId: this.turnId, status: "failed", error: detail });
|
||||||
|
this.turnId = null;
|
||||||
|
// The event stream ended: an old CLI that restart() replaced must not close the event queue
|
||||||
|
if (this.cli === cli) {
|
||||||
|
this.needsRestart = true; // Rebuild with --resume on the next send
|
||||||
|
this.q.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private emit(ev: ProviderEvent): void {
|
||||||
|
if (ev.type === "turn_ended" && !ev.turnId) ev.turnId = this.turnId ?? "unknown";
|
||||||
|
if (ev.type === "turn_ended") this.turnId = null;
|
||||||
|
if (ev.type === "provider_session_id" && ev.id) this.sessionId = ev.id;
|
||||||
|
this.q.push(ev);
|
||||||
|
}
|
||||||
|
|
||||||
|
async send(input: SendInput): Promise<void> {
|
||||||
|
if (this.closed) throw new Error(tr("claude.closed"));
|
||||||
|
if (this.needsRestart) await this.restart();
|
||||||
|
const cli = this.ensureCli();
|
||||||
|
this.turnNum++;
|
||||||
|
this.turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum;
|
||||||
|
this.st.sawInterrupt = false; // A new turn clears the old interrupt flag
|
||||||
|
this.emit({
|
||||||
|
type: "turn_started",
|
||||||
|
turnId: this.turnId,
|
||||||
|
model: this.o.model,
|
||||||
|
mode: this.o.mode,
|
||||||
|
effort: this.o.effort,
|
||||||
|
});
|
||||||
|
const built = await buildClaudeContent(input.text, input.images ?? []);
|
||||||
|
for (const w of built.warnings) this.emit({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) });
|
||||||
|
if (!cli.sendUser(built.blocks, this.sessionId)) throw new Error(tr("claude.notRunning"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async restart(): Promise<void> {
|
||||||
|
if (this.restarting) return this.restarting;
|
||||||
|
this.restarting = (async () => {
|
||||||
|
const old = this.cli;
|
||||||
|
this.cli = null;
|
||||||
|
if (old) {
|
||||||
|
this.stopping.add(old);
|
||||||
|
await old.close().catch(() => {});
|
||||||
|
}
|
||||||
|
if (this.pumpDone) await this.pumpDone.catch(() => {});
|
||||||
|
try {
|
||||||
|
this.ensureCli();
|
||||||
|
} finally {
|
||||||
|
this.restarting = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return this.restarting;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- permissions (§7.2.4) ----
|
||||||
|
private canUseTool(req: ToolRequest): Promise<PermissionDecision> {
|
||||||
|
const { toolName, input, signal } = req;
|
||||||
|
const requestId = "perm_" + rid();
|
||||||
|
const opts = { toolUseID: req.toolUseId };
|
||||||
|
|
||||||
|
if (toolName === "ExitPlanMode") {
|
||||||
|
return this.handlePlanMode(requestId, input, signal, opts.toolUseID);
|
||||||
|
}
|
||||||
|
if (toolName === "AskUserQuestion" && Array.isArray(input.questions)) {
|
||||||
|
return this.handleQuestion(requestId, input, signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
const info = callInfo(toolName, { ...input, _exists: true }, this.o.cwd);
|
||||||
|
let detail: Record<string, unknown> = { ...(info.detail as Record<string, unknown>), toolName };
|
||||||
|
if (info.kind === "edit" && (input.old_string !== undefined || Array.isArray(input.edits))) {
|
||||||
|
detail = { ...editDetail({ path: info.detail.path as string, old: input.old_string, new: input.new_string, edits: input.edits }), toolName };
|
||||||
|
}
|
||||||
|
this.emit({
|
||||||
|
type: "permission_request",
|
||||||
|
requestId,
|
||||||
|
title: info.title,
|
||||||
|
kind: "tool",
|
||||||
|
detail,
|
||||||
|
options: [
|
||||||
|
{ id: "allow", label: "允许", kind: "allow_once" },
|
||||||
|
{ id: "allow_always", label: "本对话都允许", kind: "allow_always" },
|
||||||
|
{ id: "deny", label: "拒绝", kind: "reject_once" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return new Promise<PermissionDecision>((resolve) => {
|
||||||
|
this.pending.set(requestId, { kind: "permission", resolve: (a) => resolve(this.toPermissionDecision(a, input)) });
|
||||||
|
signal.addEventListener("abort", () => {
|
||||||
|
if (this.pending.delete(requestId)) {
|
||||||
|
this.emit({ type: "permission_resolved", requestId, cancelled: true });
|
||||||
|
resolve({ behavior: "deny", message: "已取消", interrupt: true });
|
||||||
|
}
|
||||||
|
}, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private toPermissionDecision(a: RespondAnswer, input: Record<string, unknown>): PermissionDecision {
|
||||||
|
if (a.cancelled || a.optionId === "deny") {
|
||||||
|
return { behavior: "deny", message: "用户拒绝了此操作", ...(a.cancelled ? { interrupt: true } : {}) };
|
||||||
|
}
|
||||||
|
return { behavior: "allow", updatedInput: input };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handlePlanMode(requestId: string, input: Record<string, unknown>, signal: AbortSignal, toolUseID?: string): Promise<PermissionDecision> {
|
||||||
|
const planText = typeof input.plan === "string" ? input.plan : "";
|
||||||
|
if (planText) {
|
||||||
|
this.emit({ type: "plan", itemId: toolUseID ?? requestId, markdown: planText });
|
||||||
|
}
|
||||||
|
this.emit({
|
||||||
|
type: "permission_request",
|
||||||
|
requestId,
|
||||||
|
title: "Agent 提交了计划",
|
||||||
|
kind: "plan",
|
||||||
|
detail: { plan: planText },
|
||||||
|
options: [
|
||||||
|
{ id: "implement", label: "实施", kind: "allow_once" },
|
||||||
|
{ id: "reject", label: "拒绝", kind: "reject_once" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const answer = await new Promise<RespondAnswer>((resolve) => {
|
||||||
|
this.pending.set(requestId, { kind: "permission", resolve: (a) => resolve(a as RespondAnswer) });
|
||||||
|
signal.addEventListener("abort", () => {
|
||||||
|
if (this.pending.delete(requestId)) {
|
||||||
|
this.emit({ type: "permission_resolved", requestId, cancelled: true });
|
||||||
|
resolve({ cancelled: true });
|
||||||
|
}
|
||||||
|
}, { once: true });
|
||||||
|
});
|
||||||
|
if (answer.cancelled || answer.optionId === "reject") {
|
||||||
|
return { behavior: "deny", message: "用户拒绝了计划,请根据反馈修改", ...(answer.cancelled ? { interrupt: true } : {}) };
|
||||||
|
}
|
||||||
|
// implement: switch back to default mode
|
||||||
|
try {
|
||||||
|
await this.cli?.setPermissionMode("default");
|
||||||
|
this.o.mode = "default";
|
||||||
|
this.o.onModeChange?.("default");
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "setPermissionMode(default) 失败", { err: String(e) });
|
||||||
|
}
|
||||||
|
return { behavior: "allow", updatedInput: input };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleQuestion(requestId: string, input: Record<string, unknown>, signal: AbortSignal): Promise<PermissionDecision> {
|
||||||
|
this.emit({ type: "question", requestId, questions: input.questions as unknown[] });
|
||||||
|
const answer = await new Promise<RespondAnswer>((resolve) => {
|
||||||
|
this.pending.set(requestId, { kind: "question", resolve: (a) => resolve(a as RespondAnswer) });
|
||||||
|
signal.addEventListener("abort", () => {
|
||||||
|
if (this.pending.delete(requestId)) {
|
||||||
|
this.emit({ type: "permission_resolved", requestId, cancelled: true });
|
||||||
|
resolve({ cancelled: true });
|
||||||
|
}
|
||||||
|
}, { once: true });
|
||||||
|
});
|
||||||
|
if (answer.cancelled) {
|
||||||
|
return { behavior: "deny", message: "用户取消了提问", interrupt: true };
|
||||||
|
}
|
||||||
|
// answers are keyed by the question text (Claude's AskUserQuestion schema keys answers by question text)
|
||||||
|
const questions = (input.questions as { question?: string; header?: string }[]) ?? [];
|
||||||
|
const normalized: Record<string, string> = {};
|
||||||
|
for (const ques of questions) {
|
||||||
|
const text = ques.question;
|
||||||
|
if (!text) continue;
|
||||||
|
const v = answer.answers?.[text] ?? (ques.header ? answer.answers?.[ques.header] : undefined);
|
||||||
|
if (v) normalized[text] = v;
|
||||||
|
}
|
||||||
|
return { behavior: "allow", updatedInput: { ...input, answers: normalized } };
|
||||||
|
}
|
||||||
|
|
||||||
|
respond(requestId: string, answer: RespondAnswer): void {
|
||||||
|
const p = this.pending.get(requestId);
|
||||||
|
if (p) {
|
||||||
|
this.pending.delete(requestId);
|
||||||
|
p.resolve(answer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async interrupt(): Promise<void> {
|
||||||
|
this.st.sawInterrupt = true;
|
||||||
|
// Cancel every pending permission/question
|
||||||
|
for (const [id, p] of this.pending) {
|
||||||
|
this.emit({ type: "permission_resolved", requestId: id, cancelled: true });
|
||||||
|
p.resolve({ cancelled: true });
|
||||||
|
}
|
||||||
|
this.pending.clear();
|
||||||
|
const cli = this.cli;
|
||||||
|
if (!cli || !cli.alive) return;
|
||||||
|
try {
|
||||||
|
await cli.interrupt();
|
||||||
|
} catch (e) {
|
||||||
|
// No answer: stop this CLI; the next send starts it again with --resume
|
||||||
|
log("warn", "claude interrupt failed", { err: String(e) });
|
||||||
|
this.stopping.add(cli);
|
||||||
|
this.needsRestart = true;
|
||||||
|
void cli.close(500);
|
||||||
|
if (this.turnId) this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async setModel(model: string | null): Promise<void> {
|
||||||
|
this.o.model = model;
|
||||||
|
if (!this.cli?.alive) return;
|
||||||
|
try {
|
||||||
|
await this.cli.setModel(model);
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "claude set_model failed", { err: String(e) });
|
||||||
|
this.needsRestart = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async setMode(mode: Mode): Promise<void> {
|
||||||
|
this.o.mode = mode;
|
||||||
|
if (!this.cli?.alive) return;
|
||||||
|
// bypassPermissions is only accepted by a CLI started with it allowed: restart into it (--resume keeps the context)
|
||||||
|
if (mode === "bypassPermissions" && this.launchedMode !== "bypassPermissions") {
|
||||||
|
this.needsRestart = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await this.cli.setPermissionMode(mode);
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "claude set_permission_mode failed", { err: String(e) });
|
||||||
|
this.needsRestart = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async setEffort(effort: string | null): Promise<void> {
|
||||||
|
this.o.effort = effort;
|
||||||
|
// --effort is a launch flag → restart (continued via --resume)
|
||||||
|
this.needsRestart = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async listCommands(): Promise<SlashCommand[]> {
|
||||||
|
try {
|
||||||
|
const init = await this.ensureCli().initialized;
|
||||||
|
const commands = Array.isArray(init?.commands) ? (init!.commands as { name?: string; description?: string; argumentHint?: string }[]) : [];
|
||||||
|
const map = new Map<string, SlashCommand>();
|
||||||
|
for (const cmd of commands) {
|
||||||
|
if (cmd?.name && !map.has(cmd.name)) {
|
||||||
|
map.set(cmd.name, {
|
||||||
|
name: cmd.name,
|
||||||
|
description: cmd.description ?? "",
|
||||||
|
argumentHint: cmd.argumentHint,
|
||||||
|
kind: classifyClaudeSlashCommand(cmd.name),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sortSlashCommands([...map.values()]);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async close(): Promise<void> {
|
||||||
|
this.closed = true;
|
||||||
|
for (const [, p] of this.pending) p.resolve({ cancelled: true });
|
||||||
|
this.pending.clear();
|
||||||
|
const cli = this.cli;
|
||||||
|
if (cli) {
|
||||||
|
this.stopping.add(cli);
|
||||||
|
await cli.close().catch(() => {});
|
||||||
|
}
|
||||||
|
if (this.pumpDone) {
|
||||||
|
await Promise.race([this.pumpDone.catch(() => {}), new Promise((r) => setTimeout(r, 3000))]);
|
||||||
|
}
|
||||||
|
this.q.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { ModelInfo, ThinkingOption } from "../types.js";
|
||||||
|
|
||||||
|
const BASE_LEVELS = ["low", "medium", "high", "max"] as const;
|
||||||
|
|
||||||
|
/** Claude: infer levels from the model id (default high; newer model families add xhigh) */
|
||||||
|
export function claudeThinkingForModel(modelId: string | null | undefined): Pick<ModelInfo, "thinkingOptions" | "defaultThinking"> {
|
||||||
|
const id = (modelId ?? "").toLowerCase();
|
||||||
|
const options: ThinkingOption[] = BASE_LEVELS.map((x) => ({ id: x, label: x }));
|
||||||
|
if (/opus|sonnet-4|fable|4\.5|4-5|5-|claude-4|haiku-4|xhigh/.test(id)) {
|
||||||
|
if (!options.some((o) => o.id === "xhigh")) options.push({ id: "xhigh", label: "xhigh" });
|
||||||
|
}
|
||||||
|
return { thinkingOptions: options, defaultThinking: "high" };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attachClaudeThinking(models: ModelInfo[]): ModelInfo[] {
|
||||||
|
return models.map((m) => {
|
||||||
|
const id = m.id && m.id !== "null" ? m.id : null;
|
||||||
|
return { ...m, ...claudeThinkingForModel(id) };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import { readdir, readFile, stat } from "node:fs/promises";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { basename, join } from "node:path";
|
||||||
|
import type { SlashCommand } from "../slash.js";
|
||||||
|
import { parseSlashInput, sortSlashCommands } from "../slash.js";
|
||||||
|
|
||||||
|
export type CodexSlashEntry = SlashCommand & { body: string };
|
||||||
|
|
||||||
|
function parseFrontMatter(raw: string): { meta: Record<string, string>; body: string } {
|
||||||
|
if (!raw.startsWith("---\n")) return { meta: {}, body: raw };
|
||||||
|
const end = raw.indexOf("\n---\n", 4);
|
||||||
|
if (end === -1) return { meta: {}, body: raw };
|
||||||
|
const fm = raw.slice(4, end);
|
||||||
|
const meta: Record<string, string> = {};
|
||||||
|
for (const line of fm.split(/\r?\n/)) {
|
||||||
|
const m = line.match(/^([a-zA-Z0-9_-]+):\s*(.+)$/);
|
||||||
|
if (m) meta[m[1]!] = m[2]!.trim().replace(/^["']|["']$/g, "");
|
||||||
|
}
|
||||||
|
return { meta, body: raw.slice(end + 5) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function firstLine(body: string): string {
|
||||||
|
for (const line of body.split(/\r?\n/)) {
|
||||||
|
const t = line.trim();
|
||||||
|
if (t && !t.startsWith("#")) return t.replace(/^#+\s*/, "").slice(0, 120);
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readPromptFiles(dir: string): Promise<CodexSlashEntry[]> {
|
||||||
|
const out: CodexSlashEntry[] = [];
|
||||||
|
let names: string[] = [];
|
||||||
|
try {
|
||||||
|
names = await readdir(dir);
|
||||||
|
} catch {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
for (const f of names) {
|
||||||
|
if (!f.endsWith(".md")) continue;
|
||||||
|
const path = join(dir, f);
|
||||||
|
try {
|
||||||
|
const st = await stat(path);
|
||||||
|
if (!st.isFile()) continue;
|
||||||
|
const raw = await readFile(path, "utf8");
|
||||||
|
const { meta, body } = parseFrontMatter(raw);
|
||||||
|
const name = basename(f, ".md");
|
||||||
|
out.push({
|
||||||
|
name,
|
||||||
|
description: meta.description || firstLine(body) || name,
|
||||||
|
argumentHint: meta.argumentHint || meta["argument-hint"],
|
||||||
|
kind: "command",
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* skip */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readSkillDirs(root: string): Promise<CodexSlashEntry[]> {
|
||||||
|
const out: CodexSlashEntry[] = [];
|
||||||
|
let dirs: string[] = [];
|
||||||
|
try {
|
||||||
|
dirs = await readdir(root);
|
||||||
|
} catch {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
for (const d of dirs) {
|
||||||
|
const skillPath = join(root, d, "SKILL.md");
|
||||||
|
try {
|
||||||
|
const st = await stat(skillPath);
|
||||||
|
if (!st.isFile()) continue;
|
||||||
|
const raw = await readFile(skillPath, "utf8");
|
||||||
|
const { meta, body } = parseFrontMatter(raw);
|
||||||
|
const name = meta.name || d;
|
||||||
|
out.push({
|
||||||
|
name,
|
||||||
|
description: meta.description || firstLine(body) || name,
|
||||||
|
argumentHint: meta.argumentHint,
|
||||||
|
kind: "skill",
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* skip */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadCodexSlashEntries(cwd: string, opts?: { skipHome?: boolean }): Promise<CodexSlashEntry[]> {
|
||||||
|
const home = homedir();
|
||||||
|
const parts = await Promise.all([
|
||||||
|
opts?.skipHome ? Promise.resolve([]) : readPromptFiles(join(home, ".codex", "prompts")),
|
||||||
|
readPromptFiles(join(cwd, ".codex", "prompts")),
|
||||||
|
opts?.skipHome ? Promise.resolve([]) : readSkillDirs(join(home, ".codex", "skills")),
|
||||||
|
readSkillDirs(join(cwd, ".codex", "skills")),
|
||||||
|
]);
|
||||||
|
const byName = new Map<string, CodexSlashEntry>();
|
||||||
|
for (const list of parts) {
|
||||||
|
for (const e of list) {
|
||||||
|
if (!byName.has(e.name)) byName.set(e.name, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sortSlashCommands([...byName.values()]) as CodexSlashEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function expandCodexSlash(text: string, entries: CodexSlashEntry[]): string {
|
||||||
|
const parsed = parseSlashInput(text);
|
||||||
|
if (!parsed) return text;
|
||||||
|
const hit = entries.find((e) => e.name === parsed.name);
|
||||||
|
if (!hit) return text;
|
||||||
|
return hit.body.replace(/\$ARGUMENTS/g, parsed.args);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function codexSlashCommandsFromEntries(entries: CodexSlashEntry[]): SlashCommand[] {
|
||||||
|
return entries.map(({ body: _b, ...rest }) => rest);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// One user message → Codex app-server UserInput items.
|
||||||
|
// Only PNG / JPEG / GIF / WebP go as localImage; every other attachment (text files included) is named by its
|
||||||
|
// absolute path in the text, which Codex opens with its own tools. Files that aren't images or text get a warning.
|
||||||
|
import { basename } from "node:path";
|
||||||
|
import { resolveImagePath } from "../../util/attachmentRefs.js";
|
||||||
|
import { attachmentKind, baseMime, pathNote } from "../../util/attachmentKinds.js";
|
||||||
|
|
||||||
|
export async function buildCodexInput(
|
||||||
|
text: string,
|
||||||
|
attachments: { path: string; mime: string }[],
|
||||||
|
): Promise<{ items: Record<string, unknown>[]; warnings: string[] }> {
|
||||||
|
const images: Record<string, unknown>[] = [];
|
||||||
|
const notes: string[] = [];
|
||||||
|
const warnings: string[] = [];
|
||||||
|
for (const a of attachments) {
|
||||||
|
let file: string;
|
||||||
|
try {
|
||||||
|
file = await resolveImagePath(a.path);
|
||||||
|
} catch (e) {
|
||||||
|
warnings.push(`${a.path}: ${String((e as Error)?.message ?? e)}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kind = attachmentKind(a.mime);
|
||||||
|
if (kind === "image") {
|
||||||
|
images.push({ type: "localImage", path: file });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
notes.push(pathNote(kind, file));
|
||||||
|
if (kind === "other") warnings.push(`${basename(file)} (${baseMime(a.mime) || "unknown type"}) is not an image or a text file; sent its path`);
|
||||||
|
}
|
||||||
|
const fullText = [text, ...(notes.length ? [notes.join("\n")] : [])].filter(Boolean).join("\n\n");
|
||||||
|
return { items: [{ type: "text", text: fullText }, ...images], warnings };
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
// Codex app-server notifications → ProviderEvent (§7.3.4). Method and field names follow the generated schema.
|
||||||
|
import type { ProviderEvent } from "../../timeline/types.js";
|
||||||
|
|
||||||
|
const MAX_OUTPUT = 20 * 1024;
|
||||||
|
const trunc = (s: string, n = 80): string => (s.length > n ? s.slice(0, n - 1) + "…" : s);
|
||||||
|
|
||||||
|
type Rec = Record<string, unknown>;
|
||||||
|
const rec = (v: unknown): Rec => (v && typeof v === "object" ? (v as Rec) : {});
|
||||||
|
const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
|
||||||
|
|
||||||
|
export type CodexMapState = {
|
||||||
|
currentTurnId: string | null;
|
||||||
|
filesChanged: number;
|
||||||
|
diffText: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function newCodexMapState(): CodexMapState {
|
||||||
|
return { currentTurnId: null, filesChanged: 0, diffText: "" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// One server notification → 0..n unified events. Server requests (approvals) don't go through here.
|
||||||
|
export function mapNotification(method: string, params: Rec, st: CodexMapState): ProviderEvent[] {
|
||||||
|
const out: ProviderEvent[] = [];
|
||||||
|
const turnId = str(params.turnId);
|
||||||
|
|
||||||
|
switch (method) {
|
||||||
|
case "turn/started": {
|
||||||
|
const turn = rec(params.turn);
|
||||||
|
const tid = str(turn.id);
|
||||||
|
if (tid) st.currentTurnId = tid;
|
||||||
|
st.filesChanged = 0;
|
||||||
|
st.diffText = "";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "item/agentMessage/delta": {
|
||||||
|
const itemId = str(params.itemId) ?? "";
|
||||||
|
const delta = str(params.delta) ?? "";
|
||||||
|
if (itemId && delta) out.push({ type: "assistant_delta", itemId, text: delta });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "item/plan/delta": {
|
||||||
|
// Incremental plan stream: wait for the plan item in item/completed to send the full plan
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "item/reasoning/summaryTextDelta":
|
||||||
|
case "item/reasoning/textDelta": {
|
||||||
|
const itemId = str(params.itemId) ?? "";
|
||||||
|
const delta = str(params.delta) ?? "";
|
||||||
|
if (itemId && delta) out.push({ type: "reasoning_delta", itemId, text: delta });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "item/commandExecution/outputDelta":
|
||||||
|
case "item/fileChange/outputDelta":
|
||||||
|
case "command/exec/outputDelta": {
|
||||||
|
const itemId = str(params.itemId) ?? "";
|
||||||
|
const delta = str(params.delta) ?? "";
|
||||||
|
if (itemId && delta) out.push({ type: "tool_output_delta", itemId, text: delta });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "item/started": {
|
||||||
|
const item = rec(params.item);
|
||||||
|
const type = str(item.type) ?? "";
|
||||||
|
const itemId = str(item.id) ?? "";
|
||||||
|
if (type === "commandExecution") {
|
||||||
|
const cmd = str(item.command) ?? "";
|
||||||
|
out.push({
|
||||||
|
type: "tool_call", itemId, kind: "bash",
|
||||||
|
title: `运行 ${trunc(cmd)}`, status: "running",
|
||||||
|
detail: { command: cmd, cwd: str(item.cwd) },
|
||||||
|
});
|
||||||
|
} else if (type === "fileChange") {
|
||||||
|
const changes = Array.isArray(item.changes) ? item.changes : [];
|
||||||
|
out.push({
|
||||||
|
type: "tool_call", itemId, kind: "edit",
|
||||||
|
title: `修改 ${changes.length} 个文件`, status: "running",
|
||||||
|
detail: { changes },
|
||||||
|
});
|
||||||
|
} else if (type === "mcpToolCall" || type === "dynamicToolCall") {
|
||||||
|
const tool = str(item.tool) ?? str(item.name) ?? "";
|
||||||
|
const server = str(item.server) ?? "";
|
||||||
|
out.push({
|
||||||
|
type: "tool_call", itemId, kind: "mcp",
|
||||||
|
title: `${server || "mcp"} · ${tool}`, status: "running",
|
||||||
|
});
|
||||||
|
} else if (type === "webSearch") {
|
||||||
|
out.push({
|
||||||
|
type: "tool_call", itemId, kind: "web",
|
||||||
|
title: `搜索网页 "${trunc(str(item.query) ?? "", 40)}"`, status: "running",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// agentMessage/reasoning/userMessage/plan etc.: wait for a delta or completed
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "item/completed": {
|
||||||
|
const item = rec(params.item);
|
||||||
|
const type = str(item.type) ?? "";
|
||||||
|
const itemId = str(item.id) ?? "";
|
||||||
|
if (type === "agentMessage") {
|
||||||
|
const text = str(item.text) ?? "";
|
||||||
|
if (text) out.push({ type: "assistant_message", itemId, text });
|
||||||
|
} else if (type === "reasoning") {
|
||||||
|
const summary = Array.isArray(item.summary) ? item.summary : [];
|
||||||
|
const text = summary.filter((s): s is string => typeof s === "string").join("\n");
|
||||||
|
if (text) out.push({ type: "reasoning", itemId, text });
|
||||||
|
} else if (type === "commandExecution") {
|
||||||
|
const cmd = str(item.command) ?? "";
|
||||||
|
const exitCode = typeof item.exitCode === "number" ? item.exitCode : undefined;
|
||||||
|
const output = str(item.aggregatedOutput) ?? "";
|
||||||
|
out.push({
|
||||||
|
type: "tool_call", itemId, kind: "bash",
|
||||||
|
title: `运行 ${trunc(cmd)}`,
|
||||||
|
status: exitCode === 0 ? "ok" : "failed",
|
||||||
|
output: output.length > MAX_OUTPUT ? output.slice(0, MAX_OUTPUT) : output,
|
||||||
|
exitCode,
|
||||||
|
durationMs: typeof item.durationMs === "number" ? item.durationMs : undefined,
|
||||||
|
});
|
||||||
|
} else if (type === "fileChange") {
|
||||||
|
const changes = Array.isArray(item.changes) ? item.changes : [];
|
||||||
|
const istatus = str(item.status);
|
||||||
|
st.filesChanged += changes.length;
|
||||||
|
out.push({
|
||||||
|
type: "tool_call", itemId, kind: "edit",
|
||||||
|
title: `修改 ${changes.length} 个文件`,
|
||||||
|
status: istatus === "failed" ? "failed" : "ok",
|
||||||
|
detail: { changes },
|
||||||
|
});
|
||||||
|
} else if (type === "mcpToolCall" || type === "dynamicToolCall") {
|
||||||
|
const tool = str(item.tool) ?? str(item.name) ?? "";
|
||||||
|
const server = str(item.server) ?? "";
|
||||||
|
const istatus = str(item.status);
|
||||||
|
const err = str(item.error);
|
||||||
|
out.push({
|
||||||
|
type: "tool_call", itemId, kind: "mcp",
|
||||||
|
title: `${server || "mcp"} · ${tool}`,
|
||||||
|
status: istatus === "failed" || err ? "failed" : "ok",
|
||||||
|
output: err ?? undefined,
|
||||||
|
});
|
||||||
|
} else if (type === "webSearch") {
|
||||||
|
out.push({
|
||||||
|
type: "tool_call", itemId, kind: "web",
|
||||||
|
title: `搜索网页 "${trunc(str(item.query) ?? "", 40)}"`, status: "ok",
|
||||||
|
});
|
||||||
|
} else if (type === "plan") {
|
||||||
|
const text = str(item.text) ?? "";
|
||||||
|
if (text) out.push({ type: "plan", itemId, markdown: text });
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "turn/plan/updated": {
|
||||||
|
const steps = Array.isArray(params.plan) ? params.plan : [];
|
||||||
|
const items = steps.map((s) => {
|
||||||
|
const step = rec(s);
|
||||||
|
const status = str(step.status) ?? "pending";
|
||||||
|
return {
|
||||||
|
text: str(step.step) ?? "",
|
||||||
|
status: status === "completed" ? "done" : status === "inProgress" || status === "in_progress" ? "in_progress" : "pending",
|
||||||
|
};
|
||||||
|
});
|
||||||
|
if (items.length) out.push({ type: "todo", items });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "turn/diff/updated": {
|
||||||
|
const diff = str(params.diff) ?? "";
|
||||||
|
if (diff) st.diffText = diff;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "thread/tokenUsage/updated": {
|
||||||
|
const usage = rec(params.tokenUsage);
|
||||||
|
const last = rec(usage.last) || usage;
|
||||||
|
const input = typeof last.inputTokens === "number" ? last.inputTokens : 0;
|
||||||
|
const output = typeof last.outputTokens === "number" ? last.outputTokens : 0;
|
||||||
|
const cached = typeof last.cachedInputTokens === "number" ? last.cachedInputTokens : 0;
|
||||||
|
out.push({
|
||||||
|
type: "usage",
|
||||||
|
inputTokens: input,
|
||||||
|
outputTokens: output,
|
||||||
|
cacheReadTokens: cached,
|
||||||
|
costUsd: 0,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "turn/completed": {
|
||||||
|
const turn = rec(params.turn);
|
||||||
|
const status = str(turn.status) ?? "completed";
|
||||||
|
const error = rec(turn.error);
|
||||||
|
out.push({
|
||||||
|
type: "turn_ended",
|
||||||
|
turnId: str(turn.id) ?? turnId ?? st.currentTurnId ?? "",
|
||||||
|
status: status === "completed" ? "completed" : status === "interrupted" ? "interrupted" : "failed",
|
||||||
|
durationMs: typeof turn.durationMs === "number" ? turn.durationMs : undefined,
|
||||||
|
error: str(error.message),
|
||||||
|
filesChanged: st.filesChanged || undefined,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "error": {
|
||||||
|
const msg = str(params.message) ?? "Codex 错误";
|
||||||
|
out.push({ type: "notice", level: "error", message: msg });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
// Codex Provider (§7.3): detect + listModels (temporary app-server → model/list, cached 10 minutes) + createSession.
|
||||||
|
import type { Provider, ProviderSession, DetectResult, ModelInfo, Capabilities, HistoryItem } from "../types.js";
|
||||||
|
import type { ProviderEvent } from "../../timeline/types.js";
|
||||||
|
import { listCodexHistory, readCodexHistory } from "../../history/codex.js";
|
||||||
|
import { argvFor, resolveBin, killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
|
||||||
|
import { CodexRpc, CodexProcessExitedError } from "./rpc.js";
|
||||||
|
import { CodexSession } from "./session.js";
|
||||||
|
import { log } from "../../log.js";
|
||||||
|
|
||||||
|
const INSTALL_HINT = "npm i -g @openai/codex";
|
||||||
|
|
||||||
|
export const codexCapabilities: Capabilities = {
|
||||||
|
resume: true,
|
||||||
|
interrupt: true,
|
||||||
|
steer: true,
|
||||||
|
images: true,
|
||||||
|
plan: true,
|
||||||
|
questions: true,
|
||||||
|
cost: false, // tokenUsage yes, cost no
|
||||||
|
effort: [], // effort values depend on the model — filled from model/list after detect
|
||||||
|
modes: ["plan", "default", "acceptEdits", "bypassPermissions"],
|
||||||
|
};
|
||||||
|
|
||||||
|
let modelCache: { at: number; models: ModelInfo[] } | null = null;
|
||||||
|
const MODEL_CACHE_MS = 10 * 60 * 1000;
|
||||||
|
|
||||||
|
function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 5000): Promise<string> {
|
||||||
|
return new Promise((resolvePromise, reject) => {
|
||||||
|
let out = "";
|
||||||
|
const p = spawnBin(r, args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
void killTree(p, { graceMs: 500 }); // On Windows a .cmd wrapper must be killed together with its child processes
|
||||||
|
} catch {}
|
||||||
|
reject(new Error("timeout"));
|
||||||
|
}, timeoutMs);
|
||||||
|
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||||
|
p.on("error", reject);
|
||||||
|
p.on("close", (code) => {
|
||||||
|
clearTimeout(t);
|
||||||
|
if (code === 0) resolvePromise(out);
|
||||||
|
else reject(new Error("exit " + code));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Normalize the level list to strings: accepts string[] and { reasoningEffort, description }[]; other shapes are dropped */
|
||||||
|
export function normalizeEfforts(raw: unknown[] | undefined): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const e of raw ?? []) {
|
||||||
|
const v = typeof e === "string" ? e : (e as { reasoningEffort?: unknown } | null)?.reasoningEffort;
|
||||||
|
if (typeof v === "string" && v && !out.includes(v)) out.push(v);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchModels(r: ResolveResult & { ok: true }, cwd: string): Promise<ModelInfo[]> {
|
||||||
|
const rpc = new CodexRpc(argvFor(r, ["app-server"]), { cwd });
|
||||||
|
try {
|
||||||
|
await rpc.request("initialize", {
|
||||||
|
clientInfo: { name: "agent-console", title: "Agent Console", version: "0" },
|
||||||
|
capabilities: { experimentalApi: true },
|
||||||
|
}, 15000);
|
||||||
|
rpc.notify("initialized", {});
|
||||||
|
const res = (await rpc.request("model/list", {}, 15000)) as {
|
||||||
|
data?: {
|
||||||
|
id?: string;
|
||||||
|
displayName?: string;
|
||||||
|
isDefault?: boolean;
|
||||||
|
// Newer app-server returns { reasoningEffort, description }[], older ones string[]
|
||||||
|
supportedReasoningEfforts?: unknown[];
|
||||||
|
defaultReasoningEffort?: string;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
const rows = res.data ?? [];
|
||||||
|
return rows
|
||||||
|
.filter((m) => typeof m.id === "string" && m.id)
|
||||||
|
.map((m) => {
|
||||||
|
const efforts = normalizeEfforts(m.supportedReasoningEfforts);
|
||||||
|
const thinkingOptions = efforts.map((e) => ({ id: e, label: e }));
|
||||||
|
const defaultThinking = (typeof m.defaultReasoningEffort === "string" ? m.defaultReasoningEffort : null) ?? thinkingOptions[0]?.id ?? null;
|
||||||
|
return {
|
||||||
|
id: m.id!,
|
||||||
|
name: m.displayName ?? m.id!,
|
||||||
|
isDefault: m.isDefault,
|
||||||
|
efforts,
|
||||||
|
thinkingOptions,
|
||||||
|
defaultThinking,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await rpc.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCodexProvider(version: string): Provider {
|
||||||
|
return {
|
||||||
|
id: "codex",
|
||||||
|
name: "Codex",
|
||||||
|
capabilities: codexCapabilities,
|
||||||
|
async detect(): Promise<DetectResult> {
|
||||||
|
const bin = await resolveBin("codex");
|
||||||
|
if (!bin.ok) {
|
||||||
|
return { available: false, reason: bin.reason, installHint: INSTALL_HINT };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const v = await runVersion(bin, ["--version"]);
|
||||||
|
return { available: true, bin: bin.display, version: v.trim().split("\n")[0] || "" };
|
||||||
|
} catch (e) {
|
||||||
|
return { available: true, bin: bin.display, version: "", reason: String(e) };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async listModels(): Promise<ModelInfo[]> {
|
||||||
|
if (modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models;
|
||||||
|
const bin = await resolveBin("codex");
|
||||||
|
if (!bin.ok) return [{ id: "", name: "默认" }];
|
||||||
|
try {
|
||||||
|
const models = await fetchModels(bin, process.cwd());
|
||||||
|
modelCache = { at: Date.now(), models };
|
||||||
|
return models;
|
||||||
|
} catch (e) {
|
||||||
|
// Gateway region errors etc. — the frontend shows a single "Default" entry (§7.3.6)
|
||||||
|
log("warn", "codex model/list 失败", { err: String(e) });
|
||||||
|
return [{ id: "", name: "默认" }];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async createSession(o): Promise<ProviderSession> {
|
||||||
|
const bin = await resolveBin("codex");
|
||||||
|
if (!bin.ok) throw new Error(`找不到 codex:${bin.reason}`);
|
||||||
|
return new CodexSession({
|
||||||
|
threadId: o.threadId,
|
||||||
|
cwd: o.cwd,
|
||||||
|
model: o.model,
|
||||||
|
mode: o.mode,
|
||||||
|
effort: o.effort,
|
||||||
|
resumeId: o.resumeId,
|
||||||
|
binCmd: bin.cmd,
|
||||||
|
binPrefixArgs: bin.prefixArgs,
|
||||||
|
binVia: bin.via,
|
||||||
|
binShim: bin.shim,
|
||||||
|
version,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// §7.6: ~/.codex/sessions/**/rollout-*.jsonl matched by cwd
|
||||||
|
async listHistory(cwd: string): Promise<HistoryItem[]> {
|
||||||
|
const items = await listCodexHistory(cwd);
|
||||||
|
return items.map((i) => ({ provider: "codex", ...i, imported: false }));
|
||||||
|
},
|
||||||
|
async readHistory(sessionId: string, cwd: string): Promise<ProviderEvent[]> {
|
||||||
|
return (await readCodexHistory(sessionId, cwd)) as unknown as ProviderEvent[];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
// JSON-RPC over stdio client for `codex app-server` (§7.3.2).
|
||||||
|
// stdout is parsed line by line: {id,result|error} → response; {id,method} → server request; {method} → notification.
|
||||||
|
import { spawn, type ChildProcess } from "node:child_process";
|
||||||
|
import { log } from "../../log.js";
|
||||||
|
import { killTree, trackTree, type Argv } from "../../util/bin.js";
|
||||||
|
|
||||||
|
export class CodexRpcError extends Error {
|
||||||
|
code?: number;
|
||||||
|
constructor(message: string, code?: number) {
|
||||||
|
super(message);
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CodexProcessExitedError extends CodexRpcError {
|
||||||
|
constructor() {
|
||||||
|
super("Codex 进程已退出");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServerRequestHandler = (method: string, params: Record<string, unknown>) => Promise<unknown>;
|
||||||
|
type NotificationHandler = (method: string, params: Record<string, unknown>) => void;
|
||||||
|
|
||||||
|
export class CodexRpc {
|
||||||
|
private proc: ChildProcess;
|
||||||
|
private nextId = 1;
|
||||||
|
private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
|
||||||
|
private buf = "";
|
||||||
|
private exited = false;
|
||||||
|
onServerRequest?: ServerRequestHandler;
|
||||||
|
onNotification?: NotificationHandler;
|
||||||
|
onExit?: (code: number | null) => void;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
argv: Argv,
|
||||||
|
opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {},
|
||||||
|
) {
|
||||||
|
this.proc = spawn(argv.cmd, argv.args, {
|
||||||
|
cwd: opts.cwd,
|
||||||
|
env: opts.env ?? process.env,
|
||||||
|
stdio: ["pipe", "pipe", "pipe"],
|
||||||
|
windowsHide: true,
|
||||||
|
...(argv.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
||||||
|
// Non-Windows: its own process group, so after a close() timeout killTree also ends the commands codex started
|
||||||
|
...(process.platform !== "win32" ? { detached: true } : {}),
|
||||||
|
});
|
||||||
|
trackTree(this.proc);
|
||||||
|
this.proc.stdout!.setEncoding("utf8");
|
||||||
|
this.proc.stdout!.on("data", (chunk: string) => this.onData(chunk));
|
||||||
|
this.proc.stderr!.setEncoding("utf8");
|
||||||
|
this.proc.stderr!.on("data", (chunk: string) => {
|
||||||
|
this.stderrTail = (this.stderrTail + chunk).slice(-4096);
|
||||||
|
});
|
||||||
|
this.proc.on("error", () => this.failAll());
|
||||||
|
this.proc.on("close", (code) => {
|
||||||
|
this.exited = true;
|
||||||
|
this.failAll();
|
||||||
|
this.onExit?.(code);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private stderrTail = "";
|
||||||
|
|
||||||
|
get stderr(): string {
|
||||||
|
return this.stderrTail;
|
||||||
|
}
|
||||||
|
|
||||||
|
get isExited(): boolean {
|
||||||
|
return this.exited;
|
||||||
|
}
|
||||||
|
|
||||||
|
private onData(chunk: string): void {
|
||||||
|
this.buf += chunk;
|
||||||
|
let i: number;
|
||||||
|
while ((i = this.buf.indexOf("\n")) >= 0) {
|
||||||
|
const line = this.buf.slice(0, i).trim();
|
||||||
|
this.buf = this.buf.slice(i + 1);
|
||||||
|
if (!line) continue;
|
||||||
|
let msg: Record<string, unknown>;
|
||||||
|
try {
|
||||||
|
msg = JSON.parse(line);
|
||||||
|
} catch {
|
||||||
|
log("warn", "codex rpc: 非 JSON 行", { line: line.slice(0, 200) });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
void this.dispatch(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async dispatch(msg: Record<string, unknown>): Promise<void> {
|
||||||
|
const hasId = msg.id !== undefined && msg.id !== null;
|
||||||
|
if (hasId && ("result" in msg || "error" in msg)) {
|
||||||
|
const id = Number(msg.id);
|
||||||
|
const p = this.pending.get(id);
|
||||||
|
if (p) {
|
||||||
|
this.pending.delete(id);
|
||||||
|
if (msg.error) {
|
||||||
|
const e = msg.error as { code?: number; message?: string };
|
||||||
|
p.reject(new CodexRpcError(e.message ?? "RPC error", e.code));
|
||||||
|
} else {
|
||||||
|
p.resolve(msg.result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (hasId && msg.method) {
|
||||||
|
// Server request → needs a response
|
||||||
|
const id = Number(msg.id);
|
||||||
|
try {
|
||||||
|
const result = this.onServerRequest
|
||||||
|
? await this.onServerRequest(String(msg.method), (msg.params as Record<string, unknown>) ?? {})
|
||||||
|
: undefined;
|
||||||
|
this.send({ id, result: result ?? null });
|
||||||
|
} catch (e) {
|
||||||
|
this.send({ id, error: { code: -32603, message: String((e as Error)?.message ?? e) } });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!hasId && msg.method) {
|
||||||
|
try {
|
||||||
|
this.onNotification?.(String(msg.method), (msg.params as Record<string, unknown>) ?? {});
|
||||||
|
} catch (e) {
|
||||||
|
log("warn", "codex rpc: 通知处理失败", { method: msg.method, err: String(e) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private send(obj: Record<string, unknown>): void {
|
||||||
|
if (this.exited) return;
|
||||||
|
try {
|
||||||
|
this.proc.stdin!.write(JSON.stringify(obj) + "\n");
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
request<T = unknown>(method: string, params?: Record<string, unknown>, timeoutMs = 60000): Promise<T> {
|
||||||
|
if (this.exited) return Promise.reject(new CodexProcessExitedError());
|
||||||
|
const id = this.nextId++;
|
||||||
|
return new Promise<T>((resolvePromise, reject) => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
this.pending.delete(id);
|
||||||
|
reject(new CodexRpcError(`请求超时:${method}`));
|
||||||
|
}, timeoutMs);
|
||||||
|
this.pending.set(id, {
|
||||||
|
resolve: (v) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolvePromise(v as T);
|
||||||
|
},
|
||||||
|
reject: (e) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
reject(e);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.send({ jsonrpc: "2.0", id, method, params: params ?? {} });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
notify(method: string, params?: Record<string, unknown>): void {
|
||||||
|
this.send({ jsonrpc: "2.0", method, params: params ?? {} });
|
||||||
|
}
|
||||||
|
|
||||||
|
private failAll(): void {
|
||||||
|
const err = new CodexProcessExitedError();
|
||||||
|
for (const [, p] of this.pending) p.reject(err);
|
||||||
|
this.pending.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
async close(): Promise<void> {
|
||||||
|
try {
|
||||||
|
this.proc.stdin?.end();
|
||||||
|
} catch {}
|
||||||
|
await new Promise<void>((resolvePromise) => {
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
void killTree(this.proc, { graceMs: 1500 });
|
||||||
|
resolvePromise();
|
||||||
|
}, 3000);
|
||||||
|
this.proc.on("close", () => {
|
||||||
|
clearTimeout(t);
|
||||||
|
resolvePromise();
|
||||||
|
});
|
||||||
|
if (this.exited) {
|
||||||
|
clearTimeout(t);
|
||||||
|
resolvePromise();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+114
@@ -0,0 +1,114 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"FileChange": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"content": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"add"
|
||||||
|
],
|
||||||
|
"title": "AddFileChangeType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"content",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "AddFileChange",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"content": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"delete"
|
||||||
|
],
|
||||||
|
"title": "DeleteFileChangeType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"content",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "DeleteFileChange",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"move_path": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"update"
|
||||||
|
],
|
||||||
|
"title": "UpdateFileChangeType",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"unified_diff": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type",
|
||||||
|
"unified_diff"
|
||||||
|
],
|
||||||
|
"title": "UpdateFileChange",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ThreadId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"callId": {
|
||||||
|
"description": "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"conversationId": {
|
||||||
|
"$ref": "#/definitions/ThreadId"
|
||||||
|
},
|
||||||
|
"fileChanges": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"$ref": "#/definitions/FileChange"
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"grantRoot": {
|
||||||
|
"description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"description": "Optional explanatory reason (e.g. request for extra write access).",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"callId",
|
||||||
|
"conversationId",
|
||||||
|
"fileChanges"
|
||||||
|
],
|
||||||
|
"title": "ApplyPatchApprovalParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+146
@@ -0,0 +1,146 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"NetworkPolicyAmendment": {
|
||||||
|
"properties": {
|
||||||
|
"action": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyRuleAction"
|
||||||
|
},
|
||||||
|
"host": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"action",
|
||||||
|
"host"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"NetworkPolicyRuleAction": {
|
||||||
|
"enum": [
|
||||||
|
"allow",
|
||||||
|
"deny"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"ReviewDecision": {
|
||||||
|
"description": "User's decision in response to an ExecApprovalRequest.",
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"description": "User has approved this command and the agent should execute it.",
|
||||||
|
"enum": [
|
||||||
|
"approved"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
|
||||||
|
"properties": {
|
||||||
|
"approved_execpolicy_amendment": {
|
||||||
|
"properties": {
|
||||||
|
"proposed_execpolicy_amendment": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"proposed_execpolicy_amendment"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"approved_execpolicy_amendment"
|
||||||
|
],
|
||||||
|
"title": "ApprovedExecpolicyAmendmentReviewDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.",
|
||||||
|
"enum": [
|
||||||
|
"approved_for_session"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User has approved this MCP tool call and wants to amend its policy so matching future calls are automatically approved across sessions.",
|
||||||
|
"enum": [
|
||||||
|
"approved_mcp_policy_amendment"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User chose to persist a network policy rule (allow/deny) for future requests to the same host.",
|
||||||
|
"properties": {
|
||||||
|
"network_policy_amendment": {
|
||||||
|
"properties": {
|
||||||
|
"network_policy_amendment": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyAmendment"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"network_policy_amendment"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"network_policy_amendment"
|
||||||
|
],
|
||||||
|
"title": "NetworkPolicyAmendmentReviewDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User has denied this command and the agent should not execute it, but it should continue the session and try something else.",
|
||||||
|
"properties": {
|
||||||
|
"denied": {
|
||||||
|
"properties": {
|
||||||
|
"rejection": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"rejection"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"denied"
|
||||||
|
],
|
||||||
|
"title": "DeniedReviewDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Automatic approval review timed out before reaching a decision.",
|
||||||
|
"enum": [
|
||||||
|
"timed_out"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User has denied this command and the agent should not do anything until the user's next command.",
|
||||||
|
"enum": [
|
||||||
|
"abort"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"decision": {
|
||||||
|
"$ref": "#/definitions/ReviewDecision"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"decision"
|
||||||
|
],
|
||||||
|
"title": "ApplyPatchApprovalResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+5
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"title": "AttestationGenerateParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"properties": {
|
||||||
|
"token": {
|
||||||
|
"description": "Opaque client attestation token.",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"token"
|
||||||
|
],
|
||||||
|
"title": "AttestationGenerateResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"ChatgptAuthTokensRefreshReason": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"description": "Codex attempted a backend request and received `401 Unauthorized`.",
|
||||||
|
"enum": [
|
||||||
|
"unauthorized"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"previousAccountId": {
|
||||||
|
"description": "Workspace/account identifier that Codex was previously using.\n\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\n\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"$ref": "#/definitions/ChatgptAuthTokensRefreshReason"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"reason"
|
||||||
|
],
|
||||||
|
"title": "ChatgptAuthTokensRefreshParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"properties": {
|
||||||
|
"accessToken": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"chatgptAccountId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"chatgptPlanType": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"accessToken",
|
||||||
|
"chatgptAccountId"
|
||||||
|
],
|
||||||
|
"title": "ChatgptAuthTokensRefreshResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"method": {
|
||||||
|
"enum": [
|
||||||
|
"initialized"
|
||||||
|
],
|
||||||
|
"title": "InitializedNotificationMethod",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"method"
|
||||||
|
],
|
||||||
|
"title": "InitializedNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "ClientNotification"
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
+648
@@ -0,0 +1,648 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"AdditionalFileSystemPermissions": {
|
||||||
|
"properties": {
|
||||||
|
"entries": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/FileSystemSandboxEntry"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"globScanMaxDepth": {
|
||||||
|
"format": "uint",
|
||||||
|
"minimum": 1.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"read": {
|
||||||
|
"description": "This will be removed in favor of `entries`.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"write": {
|
||||||
|
"description": "This will be removed in favor of `entries`.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AdditionalNetworkPermissions": {
|
||||||
|
"properties": {
|
||||||
|
"enabled": {
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AdditionalPermissionProfile": {
|
||||||
|
"properties": {
|
||||||
|
"fileSystem": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AdditionalFileSystemPermissions"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"network": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AdditionalNetworkPermissions"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Partial overlay used for per-command permission requests."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"CommandAction": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"command": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"read"
|
||||||
|
],
|
||||||
|
"title": "ReadCommandActionType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"command",
|
||||||
|
"name",
|
||||||
|
"path",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "ReadCommandAction",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"command": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"listFiles"
|
||||||
|
],
|
||||||
|
"title": "ListFilesCommandActionType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"command",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "ListFilesCommandAction",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"command": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"query": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"search"
|
||||||
|
],
|
||||||
|
"title": "SearchCommandActionType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"command",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "SearchCommandAction",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"command": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"unknown"
|
||||||
|
],
|
||||||
|
"title": "UnknownCommandActionType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"command",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "UnknownCommandAction",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"CommandExecutionApprovalDecision": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"description": "User approved the command.",
|
||||||
|
"enum": [
|
||||||
|
"accept"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
|
||||||
|
"enum": [
|
||||||
|
"acceptForSession"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.",
|
||||||
|
"properties": {
|
||||||
|
"acceptWithExecpolicyAmendment": {
|
||||||
|
"properties": {
|
||||||
|
"execpolicy_amendment": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"execpolicy_amendment"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"acceptWithExecpolicyAmendment"
|
||||||
|
],
|
||||||
|
"title": "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User chose a persistent network policy rule (allow/deny) for this host.",
|
||||||
|
"properties": {
|
||||||
|
"applyNetworkPolicyAmendment": {
|
||||||
|
"properties": {
|
||||||
|
"network_policy_amendment": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyAmendment"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"network_policy_amendment"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"applyNetworkPolicyAmendment"
|
||||||
|
],
|
||||||
|
"title": "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User denied the command. The agent will continue the turn.",
|
||||||
|
"enum": [
|
||||||
|
"decline"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User denied the command. The turn will also be immediately interrupted.",
|
||||||
|
"enum": [
|
||||||
|
"cancel"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"CommandExecutionApprovalKind": {
|
||||||
|
"description": "Distinguishes a command approval from input sent to an existing terminal.",
|
||||||
|
"enum": [
|
||||||
|
"command",
|
||||||
|
"writeStdin"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"FileSystemAccessMode": {
|
||||||
|
"enum": [
|
||||||
|
"read",
|
||||||
|
"write",
|
||||||
|
"deny"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"FileSystemPath": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"path": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"title": "PathFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"path",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "PathFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"pattern": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"glob_pattern"
|
||||||
|
],
|
||||||
|
"title": "GlobPatternFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"pattern",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "GlobPatternFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"special"
|
||||||
|
],
|
||||||
|
"title": "SpecialFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"value": {
|
||||||
|
"$ref": "#/definitions/FileSystemSpecialPath"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type",
|
||||||
|
"value"
|
||||||
|
],
|
||||||
|
"title": "SpecialFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"FileSystemSandboxEntry": {
|
||||||
|
"properties": {
|
||||||
|
"access": {
|
||||||
|
"$ref": "#/definitions/FileSystemAccessMode"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"$ref": "#/definitions/FileSystemPath"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"access",
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"FileSystemSpecialPath": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"root"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "RootFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"minimal"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "MinimalFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"project_roots"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"subpath": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "KindFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"tmpdir"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "TmpdirFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"slash_tmp"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "SlashTmpFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"unknown"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"subpath": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind",
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"LegacyAppPathString": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"NetworkApprovalContext": {
|
||||||
|
"properties": {
|
||||||
|
"host": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"protocol": {
|
||||||
|
"$ref": "#/definitions/NetworkApprovalProtocol"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"host",
|
||||||
|
"protocol"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"NetworkApprovalProtocol": {
|
||||||
|
"enum": [
|
||||||
|
"http",
|
||||||
|
"https",
|
||||||
|
"socks5Tcp",
|
||||||
|
"socks5Udp"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"NetworkPolicyAmendment": {
|
||||||
|
"properties": {
|
||||||
|
"action": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyRuleAction"
|
||||||
|
},
|
||||||
|
"host": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"action",
|
||||||
|
"host"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"NetworkPolicyRuleAction": {
|
||||||
|
"enum": [
|
||||||
|
"allow",
|
||||||
|
"deny"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"approvalId": {
|
||||||
|
"description": "Unique identifier for this specific approval callback.\n\nFor regular shell/unified_exec approvals, this is null.\n\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing. Stdin approvals also use a distinct callback id; inspect `kind` to distinguish them.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"command": {
|
||||||
|
"description": "The command to be executed.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"commandActions": {
|
||||||
|
"description": "Best-effort parsed command actions for friendly display.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/CommandAction"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"cwd": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "The command's working directory."
|
||||||
|
},
|
||||||
|
"environmentId": {
|
||||||
|
"default": null,
|
||||||
|
"description": "Environment in which the command will run.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"itemId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"kind": {
|
||||||
|
"allOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/CommandExecutionApprovalKind"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default": "command",
|
||||||
|
"description": "Kind of action under review. Defaults to `command` for older servers."
|
||||||
|
},
|
||||||
|
"networkApprovalContext": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/NetworkApprovalContext"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Optional context for a managed-network approval prompt."
|
||||||
|
},
|
||||||
|
"proposedExecpolicyAmendment": {
|
||||||
|
"description": "Optional proposed execpolicy amendment to allow similar commands without prompting.",
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"proposedNetworkPolicyAmendments": {
|
||||||
|
"description": "Optional proposed network policy amendments (allow/deny host) for future requests.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyAmendment"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"description": "Optional explanatory reason (e.g. request for network access).",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"startedAtMs": {
|
||||||
|
"description": "Unix timestamp (in milliseconds) when this approval request started.",
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"turnId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"itemId",
|
||||||
|
"startedAtMs",
|
||||||
|
"threadId",
|
||||||
|
"turnId"
|
||||||
|
],
|
||||||
|
"title": "CommandExecutionRequestApprovalParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+116
@@ -0,0 +1,116 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"CommandExecutionApprovalDecision": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"description": "User approved the command.",
|
||||||
|
"enum": [
|
||||||
|
"accept"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
|
||||||
|
"enum": [
|
||||||
|
"acceptForSession"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.",
|
||||||
|
"properties": {
|
||||||
|
"acceptWithExecpolicyAmendment": {
|
||||||
|
"properties": {
|
||||||
|
"execpolicy_amendment": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"execpolicy_amendment"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"acceptWithExecpolicyAmendment"
|
||||||
|
],
|
||||||
|
"title": "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User chose a persistent network policy rule (allow/deny) for this host.",
|
||||||
|
"properties": {
|
||||||
|
"applyNetworkPolicyAmendment": {
|
||||||
|
"properties": {
|
||||||
|
"network_policy_amendment": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyAmendment"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"network_policy_amendment"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"applyNetworkPolicyAmendment"
|
||||||
|
],
|
||||||
|
"title": "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User denied the command. The agent will continue the turn.",
|
||||||
|
"enum": [
|
||||||
|
"decline"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User denied the command. The turn will also be immediately interrupted.",
|
||||||
|
"enum": [
|
||||||
|
"cancel"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"NetworkPolicyAmendment": {
|
||||||
|
"properties": {
|
||||||
|
"action": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyRuleAction"
|
||||||
|
},
|
||||||
|
"host": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"action",
|
||||||
|
"host"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"NetworkPolicyRuleAction": {
|
||||||
|
"enum": [
|
||||||
|
"allow",
|
||||||
|
"deny"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"decision": {
|
||||||
|
"$ref": "#/definitions/CommandExecutionApprovalDecision"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"decision"
|
||||||
|
],
|
||||||
|
"title": "CommandExecutionRequestApprovalResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"properties": {
|
||||||
|
"arguments": true,
|
||||||
|
"callId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"namespace": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"tool": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"turnId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"arguments",
|
||||||
|
"callId",
|
||||||
|
"threadId",
|
||||||
|
"tool",
|
||||||
|
"turnId"
|
||||||
|
],
|
||||||
|
"title": "DynamicToolCallParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"DynamicToolCallOutputContentItem": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"text": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"inputText"
|
||||||
|
],
|
||||||
|
"title": "InputTextDynamicToolCallOutputContentItemType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"text",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "InputTextDynamicToolCallOutputContentItem",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"imageUrl": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"inputImage"
|
||||||
|
],
|
||||||
|
"title": "InputImageDynamicToolCallOutputContentItemType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"imageUrl",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "InputImageDynamicToolCallOutputContentItem",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"audioUrl": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"inputAudio"
|
||||||
|
],
|
||||||
|
"title": "InputAudioDynamicToolCallOutputContentItemType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"audioUrl",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "InputAudioDynamicToolCallOutputContentItem",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"contentItems": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/DynamicToolCallOutputContentItem"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"success": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"contentItems",
|
||||||
|
"success"
|
||||||
|
],
|
||||||
|
"title": "DynamicToolCallResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+165
@@ -0,0 +1,165 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"ParsedCommand": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"cmd": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"read"
|
||||||
|
],
|
||||||
|
"title": "ReadParsedCommandType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"cmd",
|
||||||
|
"name",
|
||||||
|
"path",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "ReadParsedCommand",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"cmd": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"list_files"
|
||||||
|
],
|
||||||
|
"title": "ListFilesParsedCommandType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"cmd",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "ListFilesParsedCommand",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"cmd": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"query": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"search"
|
||||||
|
],
|
||||||
|
"title": "SearchParsedCommandType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"cmd",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "SearchParsedCommand",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"cmd": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"unknown"
|
||||||
|
],
|
||||||
|
"title": "UnknownParsedCommandType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"cmd",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "UnknownParsedCommand",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ThreadId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"approvalId": {
|
||||||
|
"description": "Identifier for this specific approval callback.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"callId": {
|
||||||
|
"description": "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"command": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"conversationId": {
|
||||||
|
"$ref": "#/definitions/ThreadId"
|
||||||
|
},
|
||||||
|
"cwd": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"parsedCmd": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/ParsedCommand"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"callId",
|
||||||
|
"command",
|
||||||
|
"conversationId",
|
||||||
|
"cwd",
|
||||||
|
"parsedCmd"
|
||||||
|
],
|
||||||
|
"title": "ExecCommandApprovalParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+146
@@ -0,0 +1,146 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"NetworkPolicyAmendment": {
|
||||||
|
"properties": {
|
||||||
|
"action": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyRuleAction"
|
||||||
|
},
|
||||||
|
"host": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"action",
|
||||||
|
"host"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"NetworkPolicyRuleAction": {
|
||||||
|
"enum": [
|
||||||
|
"allow",
|
||||||
|
"deny"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"ReviewDecision": {
|
||||||
|
"description": "User's decision in response to an ExecApprovalRequest.",
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"description": "User has approved this command and the agent should execute it.",
|
||||||
|
"enum": [
|
||||||
|
"approved"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
|
||||||
|
"properties": {
|
||||||
|
"approved_execpolicy_amendment": {
|
||||||
|
"properties": {
|
||||||
|
"proposed_execpolicy_amendment": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"proposed_execpolicy_amendment"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"approved_execpolicy_amendment"
|
||||||
|
],
|
||||||
|
"title": "ApprovedExecpolicyAmendmentReviewDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.",
|
||||||
|
"enum": [
|
||||||
|
"approved_for_session"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User has approved this MCP tool call and wants to amend its policy so matching future calls are automatically approved across sessions.",
|
||||||
|
"enum": [
|
||||||
|
"approved_mcp_policy_amendment"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User chose to persist a network policy rule (allow/deny) for future requests to the same host.",
|
||||||
|
"properties": {
|
||||||
|
"network_policy_amendment": {
|
||||||
|
"properties": {
|
||||||
|
"network_policy_amendment": {
|
||||||
|
"$ref": "#/definitions/NetworkPolicyAmendment"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"network_policy_amendment"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"network_policy_amendment"
|
||||||
|
],
|
||||||
|
"title": "NetworkPolicyAmendmentReviewDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "User has denied this command and the agent should not execute it, but it should continue the session and try something else.",
|
||||||
|
"properties": {
|
||||||
|
"denied": {
|
||||||
|
"properties": {
|
||||||
|
"rejection": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"rejection"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"denied"
|
||||||
|
],
|
||||||
|
"title": "DeniedReviewDecision",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Automatic approval review timed out before reaching a decision.",
|
||||||
|
"enum": [
|
||||||
|
"timed_out"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User has denied this command and the agent should not do anything until the user's next command.",
|
||||||
|
"enum": [
|
||||||
|
"abort"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"decision": {
|
||||||
|
"$ref": "#/definitions/ReviewDecision"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"decision"
|
||||||
|
],
|
||||||
|
"title": "ExecCommandApprovalResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"properties": {
|
||||||
|
"grantRoot": {
|
||||||
|
"description": "[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"itemId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"description": "Optional explanatory reason (e.g. request for extra write access).",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"startedAtMs": {
|
||||||
|
"description": "Unix timestamp (in milliseconds) when this approval request started.",
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"turnId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"itemId",
|
||||||
|
"startedAtMs",
|
||||||
|
"threadId",
|
||||||
|
"turnId"
|
||||||
|
],
|
||||||
|
"title": "FileChangeRequestApprovalParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"FileChangeApprovalDecision": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"description": "User approved the file changes.",
|
||||||
|
"enum": [
|
||||||
|
"accept"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User approved the file changes and future changes to the same files should run without prompting.",
|
||||||
|
"enum": [
|
||||||
|
"acceptForSession"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User denied the file changes. The agent will continue the turn.",
|
||||||
|
"enum": [
|
||||||
|
"decline"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "User denied the file changes. The turn will also be immediately interrupted.",
|
||||||
|
"enum": [
|
||||||
|
"cancel"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"decision": {
|
||||||
|
"$ref": "#/definitions/FileChangeApprovalDecision"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"decision"
|
||||||
|
],
|
||||||
|
"title": "FileChangeRequestApprovalResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"properties": {
|
||||||
|
"cancellationToken": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"query": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"roots": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"query",
|
||||||
|
"roots"
|
||||||
|
],
|
||||||
|
"title": "FuzzyFileSearchParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"FuzzyFileSearchMatchType": {
|
||||||
|
"enum": [
|
||||||
|
"file",
|
||||||
|
"directory"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"FuzzyFileSearchResult": {
|
||||||
|
"description": "Superset of [`codex_file_search::FileMatch`]",
|
||||||
|
"properties": {
|
||||||
|
"file_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"indices": {
|
||||||
|
"items": {
|
||||||
|
"format": "uint32",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"match_type": {
|
||||||
|
"$ref": "#/definitions/FuzzyFileSearchMatchType"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"score": {
|
||||||
|
"format": "uint32",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"file_name",
|
||||||
|
"match_type",
|
||||||
|
"path",
|
||||||
|
"root",
|
||||||
|
"score"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"files": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/FuzzyFileSearchResult"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"files"
|
||||||
|
],
|
||||||
|
"title": "FuzzyFileSearchResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"properties": {
|
||||||
|
"sessionId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"sessionId"
|
||||||
|
],
|
||||||
|
"title": "FuzzyFileSearchSessionCompletedNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"FuzzyFileSearchMatchType": {
|
||||||
|
"enum": [
|
||||||
|
"file",
|
||||||
|
"directory"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"FuzzyFileSearchResult": {
|
||||||
|
"description": "Superset of [`codex_file_search::FileMatch`]",
|
||||||
|
"properties": {
|
||||||
|
"file_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"indices": {
|
||||||
|
"items": {
|
||||||
|
"format": "uint32",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"match_type": {
|
||||||
|
"$ref": "#/definitions/FuzzyFileSearchMatchType"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"score": {
|
||||||
|
"format": "uint32",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"file_name",
|
||||||
|
"match_type",
|
||||||
|
"path",
|
||||||
|
"root",
|
||||||
|
"score"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"files": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/FuzzyFileSearchResult"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"query": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"sessionId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"files",
|
||||||
|
"query",
|
||||||
|
"sessionId"
|
||||||
|
],
|
||||||
|
"title": "FuzzyFileSearchSessionUpdatedNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"JSONRPCErrorError": {
|
||||||
|
"properties": {
|
||||||
|
"code": {
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"data": true,
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"code",
|
||||||
|
"message"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"RequestId": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "A response to a request that indicates an error occurred.",
|
||||||
|
"properties": {
|
||||||
|
"error": {
|
||||||
|
"$ref": "#/definitions/JSONRPCErrorError"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"$ref": "#/definitions/RequestId"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"error",
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"title": "JSONRPCError",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"properties": {
|
||||||
|
"code": {
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"data": true,
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"code",
|
||||||
|
"message"
|
||||||
|
],
|
||||||
|
"title": "JSONRPCErrorError",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/JSONRPCRequest"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/JSONRPCNotification"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/JSONRPCResponse"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/JSONRPCError"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"definitions": {
|
||||||
|
"JSONRPCError": {
|
||||||
|
"description": "A response to a request that indicates an error occurred.",
|
||||||
|
"properties": {
|
||||||
|
"error": {
|
||||||
|
"$ref": "#/definitions/JSONRPCErrorError"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"$ref": "#/definitions/RequestId"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"error",
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"JSONRPCErrorError": {
|
||||||
|
"properties": {
|
||||||
|
"code": {
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"data": true,
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"code",
|
||||||
|
"message"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"JSONRPCNotification": {
|
||||||
|
"description": "A notification which does not expect a response.",
|
||||||
|
"properties": {
|
||||||
|
"method": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"params": true
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"method"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"JSONRPCRequest": {
|
||||||
|
"description": "A request that expects a response.",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"$ref": "#/definitions/RequestId"
|
||||||
|
},
|
||||||
|
"method": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"params": true,
|
||||||
|
"trace": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/W3cTraceContext"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Optional W3C Trace Context for distributed tracing."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"method"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"JSONRPCResponse": {
|
||||||
|
"description": "A successful (non-error) response to a request.",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"$ref": "#/definitions/RequestId"
|
||||||
|
},
|
||||||
|
"result": true
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"result"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"RequestId": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"W3cTraceContext": {
|
||||||
|
"properties": {
|
||||||
|
"traceparent": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"tracestate": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.",
|
||||||
|
"title": "JSONRPCMessage"
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"description": "A notification which does not expect a response.",
|
||||||
|
"properties": {
|
||||||
|
"method": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"params": true
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"method"
|
||||||
|
],
|
||||||
|
"title": "JSONRPCNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"RequestId": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"W3cTraceContext": {
|
||||||
|
"properties": {
|
||||||
|
"traceparent": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"tracestate": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "A request that expects a response.",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"$ref": "#/definitions/RequestId"
|
||||||
|
},
|
||||||
|
"method": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"params": true,
|
||||||
|
"trace": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/W3cTraceContext"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Optional W3C Trace Context for distributed tracing."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"method"
|
||||||
|
],
|
||||||
|
"title": "JSONRPCRequest",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"RequestId": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "A successful (non-error) response to a request.",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"$ref": "#/definitions/RequestId"
|
||||||
|
},
|
||||||
|
"result": true
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"result"
|
||||||
|
],
|
||||||
|
"title": "JSONRPCResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+651
@@ -0,0 +1,651 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"McpElicitationArrayType": {
|
||||||
|
"enum": [
|
||||||
|
"array"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"McpElicitationBooleanSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"default": {
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationBooleanType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationBooleanType": {
|
||||||
|
"enum": [
|
||||||
|
"boolean"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"McpElicitationConstOption": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"const": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"const",
|
||||||
|
"title"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationEnumSchema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationSingleSelectEnumSchema"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationMultiSelectEnumSchema"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationLegacyTitledEnumSchema"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"McpElicitationLegacyTitledEnumSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"default": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"enum": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"enumNames": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationStringType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"enum",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationMultiSelectEnumSchema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationUntitledMultiSelectEnumSchema"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationTitledMultiSelectEnumSchema"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"McpElicitationNumberSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"default": {
|
||||||
|
"format": "double",
|
||||||
|
"type": [
|
||||||
|
"number",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"maximum": {
|
||||||
|
"format": "double",
|
||||||
|
"type": [
|
||||||
|
"number",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"minimum": {
|
||||||
|
"format": "double",
|
||||||
|
"type": [
|
||||||
|
"number",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationNumberType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationNumberType": {
|
||||||
|
"enum": [
|
||||||
|
"number",
|
||||||
|
"integer"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"McpElicitationObjectType": {
|
||||||
|
"enum": [
|
||||||
|
"object"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"McpElicitationPrimitiveSchema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationEnumSchema"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationStringSchema"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationNumberSchema"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationBooleanSchema"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"McpElicitationSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "Typed form schema for MCP `elicitation/create` requests.\n\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.",
|
||||||
|
"properties": {
|
||||||
|
"$schema": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"$ref": "#/definitions/McpElicitationPrimitiveSchema"
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"required": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationObjectType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"properties",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationSingleSelectEnumSchema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationUntitledSingleSelectEnumSchema"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationTitledSingleSelectEnumSchema"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"McpElicitationStringFormat": {
|
||||||
|
"enum": [
|
||||||
|
"email",
|
||||||
|
"uri",
|
||||||
|
"date",
|
||||||
|
"date-time"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"McpElicitationStringSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"default": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"format": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/McpElicitationStringFormat"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"maxLength": {
|
||||||
|
"format": "uint32",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"minLength": {
|
||||||
|
"format": "uint32",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationStringType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationStringType": {
|
||||||
|
"enum": [
|
||||||
|
"string"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"McpElicitationTitledEnumItems": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"anyOf": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/McpElicitationConstOption"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"anyOf"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationTitledMultiSelectEnumSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"default": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/McpElicitationTitledEnumItems"
|
||||||
|
},
|
||||||
|
"maxItems": {
|
||||||
|
"format": "uint64",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"minItems": {
|
||||||
|
"format": "uint64",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationArrayType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"items",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationTitledSingleSelectEnumSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"default": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"oneOf": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/McpElicitationConstOption"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationStringType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"oneOf",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationUntitledEnumItems": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"enum": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationStringType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"enum",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationUntitledMultiSelectEnumSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"default": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/McpElicitationUntitledEnumItems"
|
||||||
|
},
|
||||||
|
"maxItems": {
|
||||||
|
"format": "uint64",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"minItems": {
|
||||||
|
"format": "uint64",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationArrayType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"items",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"McpElicitationUntitledSingleSelectEnumSchema": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"default": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"enum": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"$ref": "#/definitions/McpElicitationStringType"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"enum",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"_meta": true,
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"enum": [
|
||||||
|
"form"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"requestedSchema": {
|
||||||
|
"$ref": "#/definitions/McpElicitationSchema"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"message",
|
||||||
|
"mode",
|
||||||
|
"requestedSchema"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"_meta": true,
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"enum": [
|
||||||
|
"openai/form"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"requestedSchema": true
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"message",
|
||||||
|
"mode",
|
||||||
|
"requestedSchema"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"_meta": true,
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"enum": [
|
||||||
|
"openaiForm"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"requestedSchema": true
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"message",
|
||||||
|
"mode",
|
||||||
|
"requestedSchema"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"_meta": true,
|
||||||
|
"elicitationId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"enum": [
|
||||||
|
"url"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"url": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"elicitationId",
|
||||||
|
"message",
|
||||||
|
"mode",
|
||||||
|
"url"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"serverName": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"turnId": {
|
||||||
|
"description": "Active Codex turn when this elicitation was observed, if app-server could correlate one.\n\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"serverName",
|
||||||
|
"threadId"
|
||||||
|
],
|
||||||
|
"title": "McpServerElicitationRequestParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"McpServerElicitationAction": {
|
||||||
|
"enum": [
|
||||||
|
"accept",
|
||||||
|
"decline",
|
||||||
|
"cancel"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"_meta": {
|
||||||
|
"description": "Optional client metadata for form-mode action handling."
|
||||||
|
},
|
||||||
|
"action": {
|
||||||
|
"$ref": "#/definitions/McpServerElicitationAction"
|
||||||
|
},
|
||||||
|
"content": {
|
||||||
|
"description": "Structured user input for accepted elicitations, mirroring RMCP `CreateElicitationResult`.\n\nThis is nullable because decline/cancel responses have no content."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"action"
|
||||||
|
],
|
||||||
|
"title": "McpServerElicitationRequestResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+336
@@ -0,0 +1,336 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"AdditionalFileSystemPermissions": {
|
||||||
|
"properties": {
|
||||||
|
"entries": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/FileSystemSandboxEntry"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"globScanMaxDepth": {
|
||||||
|
"format": "uint",
|
||||||
|
"minimum": 1.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"read": {
|
||||||
|
"description": "This will be removed in favor of `entries`.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"write": {
|
||||||
|
"description": "This will be removed in favor of `entries`.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AdditionalNetworkPermissions": {
|
||||||
|
"properties": {
|
||||||
|
"enabled": {
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"FileSystemAccessMode": {
|
||||||
|
"enum": [
|
||||||
|
"read",
|
||||||
|
"write",
|
||||||
|
"deny"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"FileSystemPath": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"path": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"title": "PathFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"path",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "PathFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"pattern": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"glob_pattern"
|
||||||
|
],
|
||||||
|
"title": "GlobPatternFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"pattern",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "GlobPatternFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"special"
|
||||||
|
],
|
||||||
|
"title": "SpecialFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"value": {
|
||||||
|
"$ref": "#/definitions/FileSystemSpecialPath"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type",
|
||||||
|
"value"
|
||||||
|
],
|
||||||
|
"title": "SpecialFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"FileSystemSandboxEntry": {
|
||||||
|
"properties": {
|
||||||
|
"access": {
|
||||||
|
"$ref": "#/definitions/FileSystemAccessMode"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"$ref": "#/definitions/FileSystemPath"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"access",
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"FileSystemSpecialPath": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"root"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "RootFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"minimal"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "MinimalFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"project_roots"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"subpath": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "KindFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"tmpdir"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "TmpdirFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"slash_tmp"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "SlashTmpFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"unknown"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"subpath": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind",
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"LegacyAppPathString": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"RequestPermissionProfile": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"fileSystem": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AdditionalFileSystemPermissions"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"network": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AdditionalNetworkPermissions"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"cwd": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"environmentId": {
|
||||||
|
"default": null,
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"itemId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"$ref": "#/definitions/RequestPermissionProfile"
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"startedAtMs": {
|
||||||
|
"description": "Unix timestamp (in milliseconds) when this approval request started.",
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"turnId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"cwd",
|
||||||
|
"itemId",
|
||||||
|
"permissions",
|
||||||
|
"startedAtMs",
|
||||||
|
"threadId",
|
||||||
|
"turnId"
|
||||||
|
],
|
||||||
|
"title": "PermissionsRequestApprovalParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+322
@@ -0,0 +1,322 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"AdditionalFileSystemPermissions": {
|
||||||
|
"properties": {
|
||||||
|
"entries": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/FileSystemSandboxEntry"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"globScanMaxDepth": {
|
||||||
|
"format": "uint",
|
||||||
|
"minimum": 1.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"read": {
|
||||||
|
"description": "This will be removed in favor of `entries`.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"write": {
|
||||||
|
"description": "This will be removed in favor of `entries`.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AdditionalNetworkPermissions": {
|
||||||
|
"properties": {
|
||||||
|
"enabled": {
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"FileSystemAccessMode": {
|
||||||
|
"enum": [
|
||||||
|
"read",
|
||||||
|
"write",
|
||||||
|
"deny"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"FileSystemPath": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"path": {
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"title": "PathFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"path",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "PathFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"pattern": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"glob_pattern"
|
||||||
|
],
|
||||||
|
"title": "GlobPatternFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"pattern",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "GlobPatternFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"type": {
|
||||||
|
"enum": [
|
||||||
|
"special"
|
||||||
|
],
|
||||||
|
"title": "SpecialFileSystemPathType",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"value": {
|
||||||
|
"$ref": "#/definitions/FileSystemSpecialPath"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"type",
|
||||||
|
"value"
|
||||||
|
],
|
||||||
|
"title": "SpecialFileSystemPath",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"FileSystemSandboxEntry": {
|
||||||
|
"properties": {
|
||||||
|
"access": {
|
||||||
|
"$ref": "#/definitions/FileSystemAccessMode"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"$ref": "#/definitions/FileSystemPath"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"access",
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"FileSystemSpecialPath": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"root"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "RootFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"minimal"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "MinimalFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"project_roots"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"subpath": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "KindFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"tmpdir"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "TmpdirFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"slash_tmp"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind"
|
||||||
|
],
|
||||||
|
"title": "SlashTmpFileSystemSpecialPath",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"kind": {
|
||||||
|
"enum": [
|
||||||
|
"unknown"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"path": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"subpath": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/LegacyAppPathString"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"kind",
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"GrantedPermissionProfile": {
|
||||||
|
"properties": {
|
||||||
|
"fileSystem": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AdditionalFileSystemPermissions"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"network": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AdditionalNetworkPermissions"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"LegacyAppPathString": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"PermissionGrantScope": {
|
||||||
|
"enum": [
|
||||||
|
"turn",
|
||||||
|
"session"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"permissions": {
|
||||||
|
"$ref": "#/definitions/GrantedPermissionProfile"
|
||||||
|
},
|
||||||
|
"scope": {
|
||||||
|
"allOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/PermissionGrantScope"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default": "turn"
|
||||||
|
},
|
||||||
|
"strictAutoReview": {
|
||||||
|
"description": "Review every subsequent command in this turn before normal sandboxed execution.",
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"permissions"
|
||||||
|
],
|
||||||
|
"title": "PermissionsRequestApprovalResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "RequestId"
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+98
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"ToolRequestUserInputOption": {
|
||||||
|
"description": "EXPERIMENTAL. Defines a single selectable option for request_user_input.",
|
||||||
|
"properties": {
|
||||||
|
"description": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"label": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"description",
|
||||||
|
"label"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"ToolRequestUserInputQuestion": {
|
||||||
|
"description": "EXPERIMENTAL. Represents one request_user_input question and its required options.",
|
||||||
|
"properties": {
|
||||||
|
"header": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"isOther": {
|
||||||
|
"default": false,
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"isSecret": {
|
||||||
|
"default": false,
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/ToolRequestUserInputOption"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"question": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"header",
|
||||||
|
"id",
|
||||||
|
"question"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "EXPERIMENTAL. Params sent with a request_user_input event.",
|
||||||
|
"properties": {
|
||||||
|
"autoResolutionMs": {
|
||||||
|
"default": null,
|
||||||
|
"description": "@deprecated Use `isBlocking` to decide whether the request should block.",
|
||||||
|
"format": "uint64",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"isBlocking": {
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"itemId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"questions": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/ToolRequestUserInputQuestion"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"turnId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"isBlocking",
|
||||||
|
"itemId",
|
||||||
|
"questions",
|
||||||
|
"threadId",
|
||||||
|
"turnId"
|
||||||
|
],
|
||||||
|
"title": "ToolRequestUserInputParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"ToolRequestUserInputAnswer": {
|
||||||
|
"description": "EXPERIMENTAL. Captures a user's answer to a request_user_input question.",
|
||||||
|
"properties": {
|
||||||
|
"answers": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"answers"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "EXPERIMENTAL. Response payload mapping question ids to answers.",
|
||||||
|
"properties": {
|
||||||
|
"answers": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"$ref": "#/definitions/ToolRequestUserInputAnswer"
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"answers"
|
||||||
|
],
|
||||||
|
"title": "ToolRequestUserInputResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+27256
File diff suppressed because it is too large
Load Diff
+24969
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,88 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"ClientInfo": {
|
||||||
|
"properties": {
|
||||||
|
"name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"version": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"name",
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"InitializeCapabilities": {
|
||||||
|
"description": "Client-declared capabilities negotiated during initialize.",
|
||||||
|
"properties": {
|
||||||
|
"experimentalApi": {
|
||||||
|
"default": false,
|
||||||
|
"description": "Opt into receiving experimental API methods and fields.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"explicitGatewayOauth": {
|
||||||
|
"description": "Use explicit gateway OAuth login instead of automatic browser authorization. Applies to this app-server's gateway runtime; later connections cannot undo it.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"extensions": {
|
||||||
|
"additionalProperties": true,
|
||||||
|
"description": "MCP extension settings declared by the app-server client.",
|
||||||
|
"type": [
|
||||||
|
"object",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"mcpServerOpenaiFormElicitation": {
|
||||||
|
"description": "Legacy opt-in for the `openai/form` MCP extension.\n\nNew clients should declare `openai/form` in [`Self::extensions`].",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"optOutNotificationMethods": {
|
||||||
|
"description": "Exact notification method names that should be suppressed for this connection (for example `thread/started`).",
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"requestAttestation": {
|
||||||
|
"default": false,
|
||||||
|
"description": "Opt into `attestation/generate` requests for upstream `x-oai-attestation`.",
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"capabilities": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/InitializeCapabilities"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"clientInfo": {
|
||||||
|
"$ref": "#/definitions/ClientInfo"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"clientInfo"
|
||||||
|
],
|
||||||
|
"title": "InitializeParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"AbsolutePathBuf": {
|
||||||
|
"description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"codexHome": {
|
||||||
|
"allOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AbsolutePathBuf"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Absolute path to the server's $CODEX_HOME directory."
|
||||||
|
},
|
||||||
|
"platformFamily": {
|
||||||
|
"description": "Platform family for the running app-server target, for example `\"unix\"` or `\"windows\"`.",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"platformOs": {
|
||||||
|
"description": "Operating system for the running app-server target, for example `\"macos\"`, `\"linux\"`, or `\"windows\"`.",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"userAgent": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"codexHome",
|
||||||
|
"platformFamily",
|
||||||
|
"platformOs",
|
||||||
|
"userAgent"
|
||||||
|
],
|
||||||
|
"title": "InitializeResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"DesktopOnboardingEntrypoint": {
|
||||||
|
"enum": [
|
||||||
|
"life_sciences"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"error": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"loginId": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"onboardingEntrypoint": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/DesktopOnboardingEntrypoint"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"success": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"success"
|
||||||
|
],
|
||||||
|
"title": "AccountLoginCompletedNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+214
@@ -0,0 +1,214 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"CreditsSnapshot": {
|
||||||
|
"properties": {
|
||||||
|
"balance": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hasCredits": {
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"unlimited": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"hasCredits",
|
||||||
|
"unlimited"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"PlanType": {
|
||||||
|
"enum": [
|
||||||
|
"free",
|
||||||
|
"go",
|
||||||
|
"plus",
|
||||||
|
"pro",
|
||||||
|
"prolite",
|
||||||
|
"promax",
|
||||||
|
"team",
|
||||||
|
"self_serve_business_prolite",
|
||||||
|
"self_serve_business_usage_based",
|
||||||
|
"business",
|
||||||
|
"ent26",
|
||||||
|
"enterprise_cbp_automation",
|
||||||
|
"enterprise_cbp_usage_based",
|
||||||
|
"enterprise",
|
||||||
|
"edu",
|
||||||
|
"edu_plus",
|
||||||
|
"edu_pro",
|
||||||
|
"sci",
|
||||||
|
"sci_plus",
|
||||||
|
"unknown"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"RateLimitReachedType": {
|
||||||
|
"enum": [
|
||||||
|
"rate_limit_reached",
|
||||||
|
"workspace_owner_credits_depleted",
|
||||||
|
"workspace_member_credits_depleted",
|
||||||
|
"workspace_owner_usage_limit_reached",
|
||||||
|
"workspace_member_usage_limit_reached"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"RateLimitSnapshot": {
|
||||||
|
"properties": {
|
||||||
|
"credits": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/CreditsSnapshot"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"individualLimit": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/SpendControlLimitSnapshot"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"limitId": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"limitName": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"normalModelSlug": {
|
||||||
|
"description": "Normal model whose display name and reasoning options describe this quota alias.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"planType": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/PlanType"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"primary": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/RateLimitWindow"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"rateLimitReachedType": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/RateLimitReachedType"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"secondary": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/RateLimitWindow"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"spendControlReached": {
|
||||||
|
"description": "Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.",
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"RateLimitWindow": {
|
||||||
|
"properties": {
|
||||||
|
"resetsAt": {
|
||||||
|
"format": "int64",
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"usedPercent": {
|
||||||
|
"format": "int32",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"windowDurationMins": {
|
||||||
|
"format": "int64",
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"usedPercent"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"SpendControlLimitSnapshot": {
|
||||||
|
"properties": {
|
||||||
|
"limit": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"remainingPercent": {
|
||||||
|
"format": "int32",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"resetsAt": {
|
||||||
|
"format": "int64",
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"used": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"limit",
|
||||||
|
"remainingPercent",
|
||||||
|
"resetsAt",
|
||||||
|
"used"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "Sparse rolling rate-limit update.\n\nClients should merge available values into the most recent `account/rateLimits/read` response or refetch that snapshot. Nullable account metadata may be unavailable in a rolling update and does not clear a previously observed value.",
|
||||||
|
"properties": {
|
||||||
|
"rateLimits": {
|
||||||
|
"$ref": "#/definitions/RateLimitSnapshot"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"rateLimits"
|
||||||
|
],
|
||||||
|
"title": "AccountRateLimitsUpdatedNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"AuthMode": {
|
||||||
|
"description": "Authentication mode for OpenAI-backed providers.",
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"description": "OpenAI API key provided by the caller and stored by Codex.",
|
||||||
|
"enum": [
|
||||||
|
"apikey"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex).",
|
||||||
|
"enum": [
|
||||||
|
"chatgpt"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE.\n\nChatGPT auth tokens are supplied by an external host app and are only stored in memory. Token refresh must be handled by the external host app.",
|
||||||
|
"enum": [
|
||||||
|
"chatgptAuthTokens"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Backend auth supplied as request headers.",
|
||||||
|
"enum": [
|
||||||
|
"headers"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Programmatic Codex auth backed by a registered Agent Identity.",
|
||||||
|
"enum": [
|
||||||
|
"agentIdentity"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Programmatic Codex auth backed by a personal access token.",
|
||||||
|
"enum": [
|
||||||
|
"personalAccessToken"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Amazon Bedrock bearer token managed by Codex.",
|
||||||
|
"enum": [
|
||||||
|
"bedrockApiKey"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Amazon Bedrock AWS access keys managed by Codex.",
|
||||||
|
"enum": [
|
||||||
|
"bedrockAccessKeys"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"PlanType": {
|
||||||
|
"enum": [
|
||||||
|
"free",
|
||||||
|
"go",
|
||||||
|
"plus",
|
||||||
|
"pro",
|
||||||
|
"prolite",
|
||||||
|
"promax",
|
||||||
|
"team",
|
||||||
|
"self_serve_business_prolite",
|
||||||
|
"self_serve_business_usage_based",
|
||||||
|
"business",
|
||||||
|
"ent26",
|
||||||
|
"enterprise_cbp_automation",
|
||||||
|
"enterprise_cbp_usage_based",
|
||||||
|
"enterprise",
|
||||||
|
"edu",
|
||||||
|
"edu_plus",
|
||||||
|
"edu_pro",
|
||||||
|
"sci",
|
||||||
|
"sci_plus",
|
||||||
|
"unknown"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"properties": {
|
||||||
|
"authMode": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AuthMode"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"planType": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/PlanType"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"title": "AccountUpdatedNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"properties": {
|
||||||
|
"delta": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"itemId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"turnId": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"delta",
|
||||||
|
"itemId",
|
||||||
|
"threadId",
|
||||||
|
"turnId"
|
||||||
|
],
|
||||||
|
"title": "AgentMessageDeltaNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+288
@@ -0,0 +1,288 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"AppBranding": {
|
||||||
|
"description": "EXPERIMENTAL - app metadata returned by app-list APIs.",
|
||||||
|
"properties": {
|
||||||
|
"category": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"developer": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"isDiscoverableApp": {
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"privacyPolicy": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"termsOfService": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"website": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"isDiscoverableApp"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AppInfo": {
|
||||||
|
"description": "EXPERIMENTAL - app metadata returned by app-list APIs.",
|
||||||
|
"properties": {
|
||||||
|
"appMetadata": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AppMetadata"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"branding": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AppBranding"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"distributionChannel": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"iconAssets": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"object",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"iconDarkAssets": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"object",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"installUrl": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"isAccessible": {
|
||||||
|
"default": false,
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"isEnabled": {
|
||||||
|
"default": true,
|
||||||
|
"description": "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"labels": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"object",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"logoUrl": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"logoUrlDark": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"pluginDisplayNames": {
|
||||||
|
"default": [],
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"name"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AppMetadata": {
|
||||||
|
"properties": {
|
||||||
|
"categories": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"developer": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"firstPartyRequiresInstall": {
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"review": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AppReview"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"screenshots": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/AppScreenshot"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"seoDescription": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"showInComposerWhenUnlinked": {
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"subCategories": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"version": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"versionId": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"versionNotes": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AppReview": {
|
||||||
|
"properties": {
|
||||||
|
"status": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"status"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AppScreenshot": {
|
||||||
|
"properties": {
|
||||||
|
"fileId": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"url": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"userPrompt": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"userPrompt"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "EXPERIMENTAL - notification emitted when the app list changes.",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/AppInfo"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"data"
|
||||||
|
],
|
||||||
|
"title": "AppListUpdatedNotification",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"description": "Read the committed installed connector runtime snapshot.",
|
||||||
|
"properties": {
|
||||||
|
"forceRefresh": {
|
||||||
|
"description": "When true and Apps are permitted, refresh and publish the hosted connector runtime tool snapshot first.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"description": "Optional loaded thread id used to evaluate effective app configuration.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"title": "AppsInstalledParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
+48
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"InstalledApp": {
|
||||||
|
"description": "Installed connector runtime state.",
|
||||||
|
"properties": {
|
||||||
|
"callable": {
|
||||||
|
"description": "Whether the connector is enabled and has a non-synthetic, model-visible tool allowed by effective MCP and app/tool policy in the committed runtime snapshot.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"enabled": {
|
||||||
|
"description": "Effective enabled state after applying global, workspace, local, and managed configuration at read time.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"runtimeName": {
|
||||||
|
"description": "Best-effort name carried by the runtime tool catalog. Canonical app metadata remains owned by `app/read`.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"callable",
|
||||||
|
"enabled",
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "The installed connectors in one committed runtime snapshot.",
|
||||||
|
"properties": {
|
||||||
|
"apps": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/InstalledApp"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"apps"
|
||||||
|
],
|
||||||
|
"title": "AppsInstalledResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"description": "EXPERIMENTAL - list available apps/connectors.",
|
||||||
|
"properties": {
|
||||||
|
"cursor": {
|
||||||
|
"description": "Opaque pagination cursor returned by a previous call.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forceRefetch": {
|
||||||
|
"description": "When true, bypass app caches and fetch the latest data from sources.",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"description": "Optional page size; defaults to a reasonable server-side value.",
|
||||||
|
"format": "uint32",
|
||||||
|
"minimum": 0.0,
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"threadId": {
|
||||||
|
"description": "Optional thread id used to evaluate app feature gating from that thread's config.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"title": "AppsListParams",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
|
"definitions": {
|
||||||
|
"AppBranding": {
|
||||||
|
"description": "EXPERIMENTAL - app metadata returned by app-list APIs.",
|
||||||
|
"properties": {
|
||||||
|
"category": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"developer": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"isDiscoverableApp": {
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"privacyPolicy": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"termsOfService": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"website": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"isDiscoverableApp"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AppInfo": {
|
||||||
|
"description": "EXPERIMENTAL - app metadata returned by app-list APIs.",
|
||||||
|
"properties": {
|
||||||
|
"appMetadata": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AppMetadata"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"branding": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AppBranding"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"distributionChannel": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"iconAssets": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"object",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"iconDarkAssets": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"object",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"installUrl": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"isAccessible": {
|
||||||
|
"default": false,
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"isEnabled": {
|
||||||
|
"default": true,
|
||||||
|
"description": "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"labels": {
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"object",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"logoUrl": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"logoUrlDark": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"pluginDisplayNames": {
|
||||||
|
"default": [],
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"name"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AppMetadata": {
|
||||||
|
"properties": {
|
||||||
|
"categories": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"developer": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"firstPartyRequiresInstall": {
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"review": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AppReview"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"screenshots": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/AppScreenshot"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"seoDescription": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"showInComposerWhenUnlinked": {
|
||||||
|
"type": [
|
||||||
|
"boolean",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"subCategories": {
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"type": [
|
||||||
|
"array",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"version": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"versionId": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"versionNotes": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AppReview": {
|
||||||
|
"properties": {
|
||||||
|
"status": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"status"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"AppScreenshot": {
|
||||||
|
"properties": {
|
||||||
|
"fileId": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"url": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"userPrompt": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"userPrompt"
|
||||||
|
],
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "EXPERIMENTAL - app list response.",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/definitions/AppInfo"
|
||||||
|
},
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"nextCursor": {
|
||||||
|
"description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.",
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"data"
|
||||||
|
],
|
||||||
|
"title": "AppsListResponse",
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user