diff --git a/.dsh-version.json b/.dsh-version.json index 069c761..6216aaf 100644 --- a/.dsh-version.json +++ b/.dsh-version.json @@ -1,7 +1,7 @@ { "comment": "The DeepSeek Harness version line this plugin pack is built and tested against. Plugins are shipped as alpha until the owner promotes them to stable. The installer pins this exact dsh version when driving the CLI. 'vendoredFrom' records the harness line whose client bundles dsh-rightbar / dsh-rightbar-files / dsh-open-in-app were forked from. dsh-vn-master is the pack's master: the bundle layer alone - the pack's final word per row, no browser half.", - "dsh": "0.2.0-rc.2", - "vendoredFrom": "0.2.0-rc.2", + "dsh": "0.2.2-rc.5", + "vendoredFrom": "0.2.2-rc.5", "platforms": [ "win32", "darwin", @@ -332,6 +332,41 @@ "NOTHING is vendored, downloaded or bundled: the engines are the machine's own (resolved from PATH or from the OS install), and lib/win-ocr.ps1 is written here" ] }, + "dsh-rea": { + "version": "0.1.0-alpha.1", + "rows": [ + "rea" + ], + "role": "Reverse engineering as a surface: five `rea_*` tools over the user's own REA installation (morluto/rea, MIT) - `rea_status` (the CLI, its version, the command names THIS build offers, and what a native provider still needs), `rea_inspect` (one command against one target, REA's `--json` stored as an investigation), `rea_read` (a stored investigation by summary or by line range), `rea_snapshot` (list/export/import one investigation as a JSON bundle) and `rea_report` (a Markdown evidence report in the workspace). A local target must resolve inside the session workspace or an `allowRoot` given per call; a URL needs `allowUrl:true`. Host-only: one row, no route, no browser half, zero npm dependencies, no engine bundled, nothing installed. See packages/dsh-rea/README.md.", + "uses": [ + "@deepseek-ai/dsh-tools (the registry the five tools are registered into)", + "REA on PATH (`rea`, from `npm install --global rea-agents`) or `DSH_REA_CLI`; the row never runs npx and never installs" + ], + "requires": [ + "REA installed by the user - `rea_status` names the command and stops when it is missing", + "a native provider (Hopper, Ghidra, IDA or Kuna) for deep analysis; static JavaScript and .NET need none" + ], + "vendors": [ + "NOTHING is vendored, downloaded or installed: REA is the user's program, and this package ships the argv builder, the scope guard, the store and the report writer" + ] + }, + "dsh-deckcraft": { + "version": "0.1.0-alpha.1", + "rows": [ + "deckcraft" + ], + "role": "Slides from the chat: four `deck_*` tools over the user's own DeckCraft CLI (storytold/deckcraft, MIT OR Apache-2.0, alpha) - `deck_status` (the CLI, its version, DeckCraft's settings folder), `deck_commands` (the dotted command ids THIS build offers, by prefix), `deck_run` (one `id=` batch saved as a `.deckcraft` in the workspace) and `deck_export` (`deckcraft-cli render` to PNG images the conversation can look at). DeckCraft's own contract is the API: every button is a command with a stable id, so nothing is hardcoded. Host-only: one row, no route, no browser half, zero npm dependencies, no engine bundled. See packages/dsh-deckcraft/README.md.", + "uses": [ + "@deepseek-ai/dsh-tools (the registry the four tools are registered into)", + "the DeckCraft CLI on PATH (`deckcraft-cli`) or `DSH_DECKCRAFT_CLI`; the row never installs" + ], + "requires": [ + "DeckCraft installed by the user (github.com/storytold/deckcraft releases) - `deck_status` names the source and stops when it is missing" + ], + "vendors": [ + "NOTHING is vendored, downloaded or installed: DeckCraft is the user's app, and this package ships the argv builder, the command-list parser and the output scope" + ] + }, "dsh-wsl": { "version": "0.1.0-alpha.1", "rows": [ @@ -449,7 +484,7 @@ ] }, "dsh-themes": { - "version": "0.1.0-alpha.31", + "version": "0.1.0-alpha.33", "rows": [ "themes" ], diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5db1cf6..30301e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,7 @@ name: CI # # There used to be three operating systems here, because there was a binary to build on # each. There is no binary: the pack is plain JavaScript with zero npm dependencies and the -# launchers are batch, PowerShell and POSIX sh over the pinned `dsh web`. A `node:22` +# the launchers are batch, PowerShell and POSIX sh over the pinned `dsh web`. A `node:24` # container is the whole toolchain, so one job on one runner covers every platform this # ships to - and the runtime the checks run on is the one `package.json` declares. # @@ -40,7 +40,7 @@ jobs: name: Node checks runs-on: ubuntu-latest timeout-minutes: 10 - container: node:22-bookworm + container: node:24-bookworm steps: # The image is Node and nothing else. `git` is the one addition, for two reasons that # are not optional: the checkout below IS git, and check-no-secrets reads the set diff --git a/AGENTS.md b/AGENTS.md index 3f9f383..e497751 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,7 @@ for its behaviour, `SECURITY.md` before touching credentials or the launcher, an starts on its own. Engines are vendored under `lib/vendor/` or resolved from the harness already on disk. 8. **CI proves the tree; the checks prove the change.** `.github/workflows/ci.yml` is - one job in a `node:22` container - the runtime `package.json` declares - running + one job in a `node:24` container - the runtime `package.json` declares - running `check-no-secrets.mjs` and `check-scripts.mjs` behind a Node floor assertion. There is no compiler, no build and no per-OS matrix, because nothing here is native. **A push to `main` starts no CI at all**: commits and pushes are free, and CI runs at the @@ -150,6 +150,12 @@ for its behaviour, `SECURITY.md` before touching credentials or the launcher, an order including egui/eframe/wgpu apps; every cargo call is `--offline` unless `fetch: true`, nothing is installed, and a build is never called read-only because `build.rs` runs — host-only, zero npm dependencies), + `dsh-rea` (reverse engineering over the user's own REA install: five `rea_*` + tools, a workspace-scoped target, stored investigations, an evidence report, + five skills; host-only, zero npm dependencies, nothing installed), + `dsh-deckcraft` (slides over the user's own DeckCraft CLI: `deck_status`, + `deck_commands`, `deck_run`, `deck_export`, three skills; host-only, zero npm + dependencies, nothing installed), `dsh-browser`, `dsh-themes`, `dsh-cmdbar`, `dsh-modal`, `dsh-skills`, `dsh-ui-state`, `dsh-open-in-app`. - A package may carry its OWN checks under `packages//checks/`, run with diff --git a/README.md b/README.md index 4ab3f4e..4a69f87 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ # vn-code

- Language: JavaScript Runtime: Node.js License: AGPL-3.0-only Platforms: Windows | macOS | Linux DeepSeek Harness 0.2.0-rc.2 + Language: JavaScript Runtime: Node.js License: AGPL-3.0-only Platforms: Windows | macOS | Linux DeepSeek Harness 0.2.2-rc.5

@@ -20,7 +20,7 @@ -![vncode: the plugin pack, a Node application - the vncode README header](./assets/vncode-banner5.png) +![vncode: the plugin pack, a Node application - the vncode README header](./assets/vncode-banner6.png) Cross-platform Node ADE with core [DSH](https://www.deepseek.com/harness/en/) for professional Engineering and Design: every plugin is **Node.js** (plain JavaScript bundles, zero npm dependencies), and so is every launcher - there is no native code in this repository and nothing to compile. The launchers run on **Windows, macOS and Linux**. @@ -59,6 +59,7 @@ way and what it touches. The exact versions are in | [`dsh-audio`](packages/dsh-audio/README.md) | A waveform surface for WAV, AIFF and FLAC: one track per channel, dBFS, selection and playback. It also draws the Media panel, which lists every audio, image, video and GIF file in the workspace. No microphone, no device list, no output routing. | | [`dsh-browser`](packages/dsh-browser/README.md) | The Browser tab, replacing the shipped iframe one: a page rendered on the host in a disposable engine behind an https-only egress gate. It answers with a screenshot, post-script text and measured styles, for the tab and for three `browser_*` tools. Built and shipped but turned OFF, because the master layer disables the row. | | [`dsh-cmdbar`](packages/dsh-cmdbar/README.md) | The command bar: the agent's own commands in a bottom dock, as a read-only transcript of the conversation log. It follows whichever conversation is on screen. | +| [`dsh-deckcraft`](packages/dsh-deckcraft/README.md) | Slides from the chat: four `deck_*` tools over the DeckCraft CLI (MIT OR Apache-2.0). `deck_commands` lists the command ids the build offers, `deck_run` saves a `.deckcraft` in the workspace, `deck_export` renders the slides to PNG so you can look at them. Nothing is hardcoded: DeckCraft's "every button is a command" contract is the API. | | [`dsh-diagrams`](packages/dsh-diagrams/README.md) | Mermaid, TikZ and the Diagram Design kit as tabs and as seven `diagram_*` tools. The kit 204 examples and 44 documented types are vendored at a pinned commit and browsable on the index page. Every write, including a self-contained HTML document, is validated before it is stored. | | [`dsh-docker`](packages/dsh-docker/README.md) | Docker or Podman as a surface: nine `docker_*` tools over the machine's own CLI, argv-only, with every removal confirmed by repeating the target. `docker_start` launches Docker Desktop or a podman machine and waits for the **daemon**. A Docker tab lists containers and images with their logs, and there is no `exec`, no `system prune` and no free-form `run`. | | [`dsh-editor`](packages/dsh-editor/README.md) | Text and code tabs over a vendored CodeMirror 6, with save/create and a Markdown preview. Every extension is mapped through a guard, so an older engine opens the document unhighlighted instead of killing the tab. It also backs the `.scd`, diagram-source and research-document editors. | @@ -73,6 +74,7 @@ way and what it touches. The exact versions are in | [`dsh-open-in-app`](packages/dsh-open-in-app/README.md) | The file-manager half of *Open In…*, patched to open the OS file browser directly. `explorer.exe` on Windows, `open` on macOS, `xdg-open` elsewhere, WSL-aware. | | [`dsh-pdf`](packages/dsh-pdf/README.md) | PDF as a surface the agent can read: `pdf_info`, `pdf_read`, `pdf_find`, `pdf_render` and `pdf_scan` over vendored pdf.js. A reader tab adds thumbnails and bookmarks. A scanned page is reported as a scan rather than returned empty. | | [`dsh-proto-lab`](packages/dsh-proto-lab/README.md) | A prototyping lab the agent fills: five `lab_*` tools write a run into the workspace own `lab///`. p5.js sketches open in a browser, and openFrameworks runs are three real C++ files built with your own projectGenerator and `make`. A runtime registry makes a third language one module and one line, and verification is a ladder that names the tier it reached. | +| [`dsh-rea`](packages/dsh-rea/README.md) | Reverse engineering as a surface, over your own REA install (MIT): `rea_status`, `rea_inspect` (a target becomes a stored investigation), `rea_read` (walk it by line range), `rea_snapshot` (export/import one JSON bundle) and `rea_report` (a Markdown evidence report). The target is scoped to the workspace or an `allowRoot`; a URL needs an explicit opt-in, and nothing is ever installed. | | [`dsh-research`](packages/dsh-research/README.md) | Research as a folder you keep: `RUN.json` plus a `passport.json` that records your instruction and every gate answer in your own words. Nine `rs_*` tools work over an append-only claim and source ledger, where numbers are data and a method record screening counts cannot increase. A disclosure record must be complete before the submission folder prints it, and two frame gates are answered by a person. Eight skills teach the tool surface, the method layer and the ethics layer. | | [`dsh-rightbar`](packages/dsh-rightbar/README.md) | The right bar: tab strip, docking panel, expand button, Start page, and the `sidebarRight` service every tab type registers into. It is a generated fork of the shipped bar, so its layer disables the original rows. | | [`dsh-rightbar-files`](packages/dsh-rightbar-files/README.md) | The Files tab type on that bar: a fork of the shipped file tree with open, rename and delete. It hands a file to the editor, image, audio or video tab that owns it. | @@ -82,7 +84,7 @@ way and what it touches. The exact versions are in | [`dsh-skills`](packages/dsh-skills/README.md) | The Skills browser: a header button opens every skill this conversation loads, with its markdown and inline editing. It reads the same registry the agent does, so what you see is what is in effect. | | [`dsh-sql-server`](packages/dsh-sql-server/README.md) | Seven `sql_*` tools over a container this row owns or the `sqlcmd` already on PATH. It keeps apart the four facts that fail independently: a server, a client, a listening port and the machine-wide ODBC driver. `sql_server start` waits until the server answers a statement, and `sql_script` loads a dump with BOM-aware code pages. | | [`dsh-supercollider`](packages/dsh-supercollider/README.md) | SuperCollider the agent can play: eleven `sc_*` tools over one warm `sclang` session (about 31 ms a call, with state kept) and a hand-written OSC client to `scsynth`. The installed `.schelp` reference is indexed for `sc_help`, and the `.scd` workflow opens in the editor. Five skills teach the language, SynthDefs and live coding, and every example in them is compiled by a check. | -| [`dsh-themes`](packages/dsh-themes/README.md) | Header controls for themes (Nord, Monokai, Hacker, Cyber), screenshot and page zoom, plus the Markdown paper and the pack branding. It also hides the shipped account-menu Feedback row. | +| [`dsh-themes`](packages/dsh-themes/README.md) | Header controls for themes (Nord, Monokai, Hacker, Cyber), screenshot and page zoom, the Markdown paper and the pack branding, and the app-wide scrollbars (24px on both axes, with a thumb that reads on the light page). It also hides the shipped account-menu Feedback row. | | [`dsh-ui-state`](packages/dsh-ui-state/README.md) | The pack's own UI state, remembered host-side: zoom, theme, dock and column widths. It outlives the process, so a restart keeps the layout you left. | | [`dsh-video`](packages/dsh-video/README.md) | A player tab that streams and seeks any container the browser can decode. An ffprobe facts panel names codec, size and frame rate, and one click remuxes when the browser cannot decode it. | | [`dsh-vn-master`](packages/dsh-vn-master/README.md) | The pack's final layer: it installs last, so its row decisions win. It disables the four feedback/telemetry rows and the pack's own `browser` row, which is built and shipped deliberately off. Pack-wide row patches belong here. | @@ -109,6 +111,7 @@ upstream `LICENSE` beside its bytes. | **shader-skills** — 20 GLSL modules, 11 templates, 11 gallery pieces, 14 references, MIT, [`gokayfem/shader-skills`](https://github.com/gokayfem/shader-skills) | `dsh-shaders` | `node packages/dsh-shaders/vendor/shader-skills/build.mjs --check` re-derives the dependency closure offline, and the catalogue records which gallery piece proves each template | | **awesome-glsl** — a 48-link curated index (**no shader code**), MIT, [`vanrez-nez/awesome-glsl`](https://github.com/vanrez-nez/awesome-glsl) | `dsh-shaders` | `node packages/dsh-shaders/vendor/glsl-links/build.mjs --check` proves `links.json` still matches the vendored markdown | | **p5.js** 1.11.13 (`lib/vendor/p5.min.js`, LGPL-2.1) | `dsh-proto-lab` | `node packages/dsh-proto-lab/vendor/build.mjs --check` re-hashes the recorded bytes offline. 1.x on purpose: it is the last line with a self-contained classic-script browser build, which is what a run opened straight off the filesystem needs | +| **Academic presentation best practices** — David Hirshleifer's checklist (PDF) plus a distilled reference, MIT, [`Gabberflast/academic-pptx-skill`](https://github.com/Gabberflast/academic-pptx-skill) | `dsh-deckcraft` | `node packages/dsh-deckcraft/checks/check-deck.mjs` re-hashes the committed PDF against `reference/SOURCE.md` and asserts the distillation still cites the source | | **CodeMirror 6** (`lib/vendor/cm6.min.js`) and the forked shipped client bundles | `dsh-editor`, `dsh-rightbar`, `dsh-open-in-app` | the bundle's own version marker and the forked trees' hashes, both asserted by `scripts/checks/` | A vendored tree names its pin in a `SOURCE.json`/`VERSION.json` and — where the diff --git a/SECURITY.md b/SECURITY.md index c2c7221..4504985 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -28,7 +28,7 @@ download below. ## Supported versions Supported: `main`, and the harness line pinned in `.dsh-version.json` -(**0.2.0-rc.2**); any other published line is **not** tested and not claimed. +(**0.2.2-rc.5**); any other published line is **not** tested and not claimed. `dsh-rightbar`, `dsh-rightbar-files` and `dsh-open-in-app` are forks of that line's client bundles, so a line bump is deliberate: bump the pin, run `scripts/tools/sync-vendored.ps1`, re-verify. The pack targets the **web profile only**, @@ -199,7 +199,7 @@ should be read as such: ## Lock it down 1. **Keep it on loopback**: the pack's launcher or - `npx @deepseek-ai/dsh@0.2.0-rc.2 web`, no `--host`, no `--trusted-host`. Loopback + `npx @deepseek-ai/dsh@0.2.2-rc.5 web`, no `--host`, no `--trusted-host`. Loopback traffic does not cross a firewall, so no firewall rule "fixes" an exposed bind. 2. **Treat the printed URL as a password**, and stop the harness when you are not using it. diff --git a/assets/vncode-banner5.png b/assets/vncode-banner5.png deleted file mode 100644 index 750bf53..0000000 Binary files a/assets/vncode-banner5.png and /dev/null differ diff --git a/assets/vncode-banner6.png b/assets/vncode-banner6.png new file mode 100644 index 0000000..6bd660c Binary files /dev/null and b/assets/vncode-banner6.png differ diff --git a/docs/BUILD.md b/docs/BUILD.md index e4ce014..f06f7cc 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -6,7 +6,7 @@ ships. The harness is run through `npx` and the pack is loaded from this folder link, so a change is a file save. That is the rule behind every other page here: a change is proved by RUNNING it, not by -compiling it, and the only toolchain any machine needs is **Node.js >= 22**. +compiling it, and the only toolchain any machine needs is **Node.js >= 24.9**. The one exception is a vendored engine: each keeps its own `vendor/build.mjs` and the tracked hashes in its `lib/vendor/VERSION.json`. Regenerate those, never hand-edit them. diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md index ff0fe73..4b8ec59 100644 --- a/docs/COMPATIBILITY.md +++ b/docs/COMPATIBILITY.md @@ -11,10 +11,10 @@ person's own browser, which the launcher finds (Chrome first, the OS opener as t | | | |---|---| -| `@deepseek-ai/dsh` | `0.2.0-rc.2` (`.dsh-version.json`'s `dsh`) | -| Forked from | the same `0.2.0-rc.2` line (`.dsh-version.json`'s `vendoredFrom`) | +| `@deepseek-ai/dsh` | `0.2.2-rc.5` (`.dsh-version.json`'s `dsh`) | +| Forked from | the same `0.2.2-rc.5` line (`.dsh-version.json`'s `vendoredFrom`) | | Install target | the web profile only (`$DSH_HOME/profiles/web`; `$DSH_HOME` defaults to `~/.dsh`) | -| Host platforms | Windows (PowerShell 5.1 or 7) and macOS / Linux (POSIX shell plus Node.js 22+ with npm/npx - never PowerShell) | +| Host platforms | Windows (PowerShell 5.1 or 7) and macOS / Linux (POSIX shell plus Node.js 24.9+ with npm/npx - never PowerShell) | | Distribution | one artefact, `vncode-.zip` - the repository at the tag. Nothing is compiled, so nothing is per-OS | | Plugin code | plain JavaScript and OS-neutral; the only per-OS code is a launcher choosing the host command | @@ -41,18 +41,31 @@ person's own browser, which the launcher finds (Chrome first, the OS opener as t | `dsh-modal` | `modal` | the shared `modals` dialog surface | | `dsh-ui-state` | `ui-state` | durable UI state on the host: page zoom, theme, dock height and the two column widths | | `dsh-open-in-app` | `native-open-in-app` | the OS file browser; disables `ui-open-in-app` | +| `dsh-rea` | `rea` | reverse engineering over the user's own REA CLI: five `rea_*` tools, a workspace-scoped target, stored investigations and an evidence report | +| `dsh-deckcraft` | `deckcraft` | slides over the user's own DeckCraft CLI: `deck_commands` / `deck_run` / `deck_export`, with outputs scoped to the workspace | The shipped document preview row stays enabled: it consumes `sidebarRightTabs` and the keyed seat, so its previews keep working inside the pack's bar. ## Upgrading the pack when DSH moves -1. Bump `dsh` in `.dsh-version.json`. +1. Bump `dsh` **and** `vendoredFrom` in `.dsh-version.json` (the launcher reads the pin at + run time, so `run-web.bat` itself needs no change). 2. Re-run `scripts/tools/sync-vendored.ps1` and review the diff: a patched fork fails - loudly when the core code it patches has moved. -3. Re-run the installer with `-Force` to re-add the bundles under the new pin. + loudly when the core code it patches has moved. Two measured facts about that diff: + - The bundle names itself in two spellings - `id: ""` up to 0.2.0-rc.2 and a + template literal (`id:` + backtick) from the 0.2.1 line on; the script accepts both + and keeps the source's spelling. + - The client bundles are re-minified per line, so JS anchors move even when the logic + does not. Measured on 0.2.0-rc.2 -> 0.2.2-rc.5: 12 of the right bar's 14 patches and + both `dsh-open-in-app` patches needed re-anchoring; the two patches that match CSS + text survived unchanged. Budget for re-anchoring, not for a version bump. +3. Re-run the installer with `-Force` to re-add the bundles under the new pin (on a + machine whose profile is already installed this is a no-op re-registration). 4. If a core API moved (registry shape, seat names, route registration), adapt - the affected package and bump its alpha version. + the affected package and bump its alpha version. 0.2.2-rc.5 added a THIRD apply-time + service to the forked `dsh-open-in-app` (`ctx.contextMenus`, five menus) and declares + Node.js >= 24.9. 5. Re-run the uninstaller first on machines that should drop the old version. ## Alpha policy diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index fc82370..e3c0ed9 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -6,7 +6,7 @@ steps, [RELEASE.md](RELEASE.md) how a release is cut and [BUILD.md](BUILD.md) ho **A distribution is this repository.** There is no second thing to deploy beside it: the pack, the launchers and the docs are the same files on every platform, they need Node.js -22+ with `npx` and nothing else, and there is nothing to build or ship. +24.9+ with `npx` and nothing else, and there is nothing to build or ship. ## What the distribution gets right @@ -57,7 +57,7 @@ pack is not made self-contained by copying it: moving it does not move the insta the cache grows about **223 MB per pin, per user**. Installing needs the network twice - `npx @deepseek-ai/dsh@` downloads that closure on first run, and the installer bootstraps pnpm into `./tools` with the npm that ships with Node.js, because -`dsh plugin add` runs pnpm underneath. The target machine needs **Node.js 22+**, and +`dsh plugin add` runs pnpm underneath. The target machine needs **Node.js 24.9+**, and Windows needs PowerShell, which ships with it. The launcher sets what it can of this. A portable folder points `npm_config_cache` at diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 4d741d8..8017d09 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -18,7 +18,7 @@ uninstall, with their workers), `console/` (the shared console layer), `tools/` | | | |---|---| -| Requirements | **Node.js 22+** on every platform, with `npx`. **Windows** runs the launcher on Windows PowerShell 5.1 (shipped) or PowerShell 7; **macOS / Linux** uses a POSIX shell and never PowerShell | +| Requirements | **Node.js 24.9+** on every platform, with `npx`. **Windows** runs the launcher on Windows PowerShell 5.1 (shipped) or PowerShell 7; **macOS / Linux** uses a POSIX shell and never PowerShell | | Install target | the **web profile** only, `$DSH_HOME/profiles/web` (`$DSH_HOME` = env var, else the portable root below, else `~/.dsh`). Overrides: `-DshHome `, `-ProfileName ` | | State | the DeepSeek key in `$DSH_HOME/.env` or `$DSH_HOME/.credentials.yaml`; sessions, settings, attachments and the pack's own caches under the same home | diff --git a/docs/RELEASE.md b/docs/RELEASE.md index 2c63a91..1cc81ac 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -10,7 +10,7 @@ installation on Windows, macOS and Linux alike, with no second archive and no sh `.github/workflows/release.yml`, on `v*` (or `workflow_dispatch` with an existing tag): 1. **gate** - calls `ci.yml` through `workflow_call`, the same workflow a pull request - runs. One job, `ubuntu-latest`, a `node:22` container: `git` installed, then + runs. One job, `ubuntu-latest`, a `node:24` container: `git` installed, then `check-no-secrets.mjs` and `check-scripts.mjs`. A red gate stops the release **before** anything is published. 2. **archive** - the tag itself is archived into `vncode-.zip` and attached. The diff --git a/package.json b/package.json index 5a1b2c7..1f6dde5 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,6 @@ "banner": "node scripts/tools/logo/banner.mjs" }, "engines": { - "node": ">=22" + "node": ">=24.9" } } diff --git a/packages/dsh-deckcraft/README.md b/packages/dsh-deckcraft/README.md new file mode 100644 index 0000000..0ba6ade --- /dev/null +++ b/packages/dsh-deckcraft/README.md @@ -0,0 +1,69 @@ +# dsh-deckcraft + +Slides from the chat, over the user's own [DeckCraft](https://github.com/storytold/deckcraft) +CLI (MIT OR Apache-2.0, alpha). Four tools, three skills, no engine bundled. + +## Why the CLI and not an MCP bridge + +DeckCraft ships an MCP server too, and a harness can mount it. But DeckCraft is +alpha and its surface is 200+ commands that move between builds. This row takes +the CLI, whose contract is the one thing the app promises not to break: **every +button is a command with a stable id**. Discovery, execution, proof — three +verbs — is a smaller and sturdier integration than a bridge whose tool set has to +be re-verified at every release. + +## The tools + +| Tool | What it answers | +|---|---| +| `deck_status` | Is the CLI installed, which version, where DeckCraft keeps its settings and logs. Names the install source; installs nothing. | +| `deck_commands` | The command ids this build offers (`deckcraft-cli commands [prefix]`), with summaries. Prefixes keep the list small: `slide.`, `format.`, `theme.`, `export.`. | +| `deck_run` | One command or a batch (`id=` each, in order, in one document), saved as a `.deckcraft` in the workspace. `sample:true` writes DeckCraft's sample deck. | +| `deck_export` | `deckcraft-cli render --all --scale

` → PNG images in the workspace, so the slides can be looked at. | + +## The rules this row keeps + +- **Argv, never a shell**: a title with a quote or a path with a space is one + argument. +- **Outputs are scoped**: the save path and the render directory must resolve + inside the session workspace, or inside a folder the user authorised for that + call (`allowRoot`). A command cannot write a deck over the user's documents. +- **Nothing is hardcoded**: an id this build does not offer fails at the CLI with + its own message, and `deck_commands` is how the model finds one that works. +- **Nothing is installed**: DeckCraft is the user's app; `deck_status` names the + source and stops. + +## Skills + +`deckcraft-deck` (layouts, placeholders, themes — why content goes into a layout +and not into a text box), `deckcraft-commands` (the command contract, batching, +what to do when one entry fails), `deckcraft-export` (render/PDF/PPTX, and the +checks that make a deck "done"). + +## Vendored reference + +`skills/deckcraft-deck/reference/academic-presentation-best-practices.pdf` is +David Hirshleifer's *Best Practices for Academic Presentations* (28 Feb 2026, +built with Claude), MIT, Copyright (c) 2026 Gabberflast, from +[`Gabberflast/academic-pptx-skill`](https://github.com/Gabberflast/academic-pptx-skill). +It is stored **byte-identical** with its `UPSTREAM-LICENSE.txt`, and +`reference/SOURCE.md` records the URL and the SHA-256. `academic-presentations.md` +beside it distils the document into the checks a deck is built against; +`npm run check` re-hashes the PDF and asserts the distillation still cites the +source. + +## Requirements + +- DeckCraft, with its CLI: the per-OS `deckcraft-cli` archive from the + [releases](https://github.com/storytold/deckcraft/releases). `DSH_DECKCRAFT_CLI` + pins a binary PATH does not carry. +- No other dependency. The row is Node-only and declared dependency-free. + +## Check + +```sh +npm run check # node checks/check-deck.mjs — 54 assertions, no DeckCraft needed +``` + +The live probe runs `deckcraft-cli --version` when a binary is present and says +loudly when it is not. diff --git a/packages/dsh-deckcraft/checks/check-deck.mjs b/packages/dsh-deckcraft/checks/check-deck.mjs new file mode 100644 index 0000000..32fd39f --- /dev/null +++ b/packages/dsh-deckcraft/checks/check-deck.mjs @@ -0,0 +1,159 @@ +// check-deck.mjs - dsh-deckcraft's own contract, driven directly. +// +// The row is an argv builder, a command-id parser and an output scope; none of +// that needs DeckCraft installed, so the whole check runs anywhere. The live half +// drives `deckcraft-cli --version` when a binary is present and says so when not. +// +// Run: node checks/check-deck.mjs +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { createHash } from 'node:crypto' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { + assertOutputAllowed, + buildProbeArgs, + buildRenderArgs, + buildRunArgs, + isCommandId, + parseCommandList, + resolveDeckCli, + runDeck, + settingsDir, +} from '../lib/deck.js' +import { buildTools } from '../lib/tools.js' +import { PLUGIN_VERSION, __internals } from '../lib/index.js' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const pkg = JSON.parse(readFileSync(path.join(here, '..', 'package.json'), 'utf8')) + +let checks = 0 +let failures = 0 +const check = (label, actual, expected) => { + checks += 1 + const ok = expected === undefined ? Boolean(actual) : actual === expected + if (!ok) failures += 1 + console.log((ok ? 'ok ' : 'FAIL ') + label.padEnd(52) + (expected === undefined ? '' : ' ' + JSON.stringify(actual))) + return ok +} + +console.log('# dsh-deckcraft') + +// --------------------------------------------------------------- the row +check('the package names the row', pkg.name, 'dsh-deckcraft') +check('the marker matches package.json', PLUGIN_VERSION, pkg.version) +check('the bundle points at its patch', pkg.dsh.bundle.patch, './cordis.patch.yml') +check('no npm dependency is declared', Object.keys(pkg.dependencies ?? {}).length, 0) +check('the patch inserts one row', /id:\s*deckcraft\b/.test(readFileSync(path.join(here, '..', 'cordis.patch.yml'), 'utf8'))) + +// --------------------------------------------------------------- the tools +const tools = buildTools({ ctx: {}, env: {}, platform: 'win32' }) +check('four tools are registered', tools.length, 4) +check( + 'their names are the documented surface', + tools.map((tool) => tool.name).join(','), + 'deck_status,deck_commands,deck_run,deck_export', +) +for (const tool of tools) { + check(tool.name + ': has a schema', Boolean(tool.parameters && tool.parameters.type === 'object')) + check(tool.name + ': answers text and a view', Boolean(tool.output && tool.output.schema && tool.output.schema.required.join(',') === 'text,view')) + check(tool.name + ': describes itself', typeof tool.description === 'string' && tool.description.length > 80) + check(tool.name + ': is executed by a function', typeof tool.execute === 'function') +} + +// --------------------------------------------------------------- the ids +check('a dotted id is a command', isCommandId('slide.new') && isCommandId('format.paragraph'), true) +check('a bare word is not a command', isCommandId('new'), false) +check('a flag-shaped id is not a command', isCommandId('--save'), false) +check('an id with a space is not a command', isCommandId('slide. new'), false) + +const listed = parseCommandList('slide.new Create a slide\nformat.paragraph Set paragraph format\n\n2 commands\n') +check('the list parser keeps the ids', listed.map((row) => row.id).join(','), 'slide.new,format.paragraph') +check('the list parser keeps the summary', listed[0].summary, 'Create a slide') +check('a header line is skipped', parseCommandList('Commands:\nslide.new x').length, 1) + +// --------------------------------------------------------------- the argv +check( + 'a run names each command and saves', + buildRunArgs({ commands: ['slide.new={"layout":"titleOnly"}', 'slide.duplicate'], save: 'decks/a.deckcraft' }).join(' '), + 'run --cmd slide.new={"layout":"titleOnly"} --cmd slide.duplicate --save decks/a.deckcraft', +) +check('a sample run is its own shape', buildRunArgs({ sample: true, save: 'decks/a.deckcraft' }).join(' '), 'run --sample --save decks/a.deckcraft') +check('a bad id is refused before the CLI runs', (() => { try { buildRunArgs({ commands: ['--save=1'] }); return 'accepted' } catch { return 'refused' } })(), 'refused') +check('a bad JSON argument is refused', (() => { try { buildRunArgs({ commands: ['slide.new={nope}'] }); return 'accepted' } catch { return 'refused' } })(), 'refused') +check('an empty batch is refused', (() => { try { buildRunArgs({ commands: [] }); return 'accepted' } catch { return 'refused' } })(), 'refused') +check('an oversized batch is refused', (() => { try { buildRunArgs({ commands: Array.from({ length: 201 }, () => 'slide.new') }); return 'accepted' } catch { return 'refused' } })(), 'refused') +check( + 'a render names the deck, --all, the scale and the directory', + buildRenderArgs({ deck: 'decks/a.deckcraft', out: 'renders/a', scale: 2 }).join(' '), + 'render decks/a.deckcraft --all --scale 2 renders/a', +) +check('a render without a scale omits it', buildRenderArgs({ deck: 'a.deckcraft', out: 'r' }).join(' '), 'render a.deckcraft --all r') +check('probes are version/commands/help', [buildProbeArgs('version'), buildProbeArgs('commands'), buildProbeArgs('help')].map((a) => a.join(' ')).join('|'), '--version|commands|--help') + +// --------------------------------------------------------------- the scope +const ws = path.resolve('/work/project') +check('a save inside the workspace is allowed', assertOutputAllowed({ target: path.join(ws, 'decks', 'a.deckcraft'), workspace: ws, platform: 'linux', realpath: false }), path.join(ws, 'decks', 'a.deckcraft')) +check('a save outside it is refused', (() => { try { assertOutputAllowed({ target: '/home/me/Documents/a.deckcraft', workspace: ws, platform: 'linux', realpath: false }); return 'allowed' } catch { return 'refused' } })(), 'refused') +check('a named allowRoot is honoured', (() => { try { return assertOutputAllowed({ target: '/opt/decks/a.deckcraft', workspace: ws, allowRoot: '/opt/decks', platform: 'linux', realpath: false }) } catch { return 'refused' } })(), path.resolve('/opt/decks/a.deckcraft')) +check('a sibling prefix is not "inside"', (() => { try { assertOutputAllowed({ target: '/work/project-evil/x', workspace: ws, platform: 'linux', realpath: false }); return 'allowed' } catch { return 'refused' } })(), 'refused') +check('no workspace refuses everything', (() => { try { assertOutputAllowed({ target: path.join(ws, 'a'), workspace: '', platform: 'linux', realpath: false }); return 'allowed' } catch { return 'refused' } })(), 'refused') + +// --------------------------------------------------------------- discovery +check('no PATH entry resolves to nothing', resolveDeckCli({ PATH: '', DSH_DECKCRAFT_CLI: '' }, 'linux').command, '') +check('a missing binary is said in one line', Boolean(__internals.activationLine({ command: '', source: 'missing' }).includes('storytold/deckcraft')), true) +const settings = settingsDir({ XDG_CONFIG_HOME: '/tmp/cfg' }, 'linux') +check('the settings folder is DeckCraft\'s documented one', settings, path.join('/tmp/cfg', 'deckcraft')) + +// --------------------------------------------------------------- the skills +const skillsRoot = path.join(here, '..', 'skills') +const skills = ['deckcraft-deck', 'deckcraft-commands', 'deckcraft-export'] +check('three skills ship', skills.every((name) => existsSync(path.join(skillsRoot, name, 'SKILL.md'))), true) +for (const name of skills) { + const text = readFileSync(path.join(skillsRoot, name, 'SKILL.md'), 'utf8') + const front = /^---\nname: ([\w-]+)\ndescription: (.+)\nwhenToUse: (.+)\n---/m.exec(text) + check(name + ': frontmatter is complete', Boolean(front)) + check(name + ': names itself', front ? front[1] : '', name) +} + +// ------------------------------------------------------- the vendored reference +// The academic checklist is a PDF we did not write: the source must stay +// byte-identical to what SOURCE.md records, its MIT licence must be beside it, +// and the distillation the skill actually reads must still name where it came +// from. A copied reference that drifts from its citation is worse than none. +{ + const reference = path.join(skillsRoot, 'deckcraft-deck', 'reference') + const pdf = path.join(reference, 'academic-presentation-best-practices.pdf') + const source = path.join(reference, 'SOURCE.md') + const distilled = path.join(reference, 'academic-presentations.md') + const licence = path.join(reference, 'UPSTREAM-LICENSE.txt') + check('the reference PDF ships', existsSync(pdf), true) + if (existsSync(pdf) && existsSync(source)) { + const recorded = /SHA-256 \| `([0-9a-f]{64})`/.exec(readFileSync(source, 'utf8')) + const actual = createHash('sha256').update(readFileSync(pdf)).digest('hex') + check('the PDF matches the hash SOURCE.md records', recorded ? recorded[1] : '(no hash in SOURCE.md)', actual) + check('SOURCE.md names the repository', readFileSync(source, 'utf8').includes('github.com/Gabberflast/academic-pptx-skill'), true) + } + check('the upstream MIT licence is beside it', existsSync(licence) && readFileSync(licence, 'utf8').includes('MIT License'), true) + check('the distillation cites the source', existsSync(distilled) && readFileSync(distilled, 'utf8').includes('github.com/Gabberflast/academic-pptx-skill'), true) + const skillText = readFileSync(path.join(skillsRoot, 'deckcraft-deck', 'SKILL.md'), 'utf8') + check('the skill points at the distillation', skillText.includes('reference/academic-presentations.md'), true) + check('the skill carries the top rules', skillText.includes('ghost deck test') && skillText.includes('One exhibit per slide'), true) +} + +// --------------------------------------------------------------- live half +const live = resolveDeckCli(process.env, process.platform) +if (live.command === '') { + console.log('skip the live DeckCraft probe (no `deckcraft-cli` on PATH; the pure half above is the contract)') +} else { + const version = await runDeck(live.command, buildProbeArgs('version'), { timeoutMs: 20_000 }) + check('the live CLI answers --version', version.code, 0) +} + +console.log('') +if (failures > 0) { + console.log(failures + ' check(s) FAILED of ' + checks) + process.exit(1) +} +console.log('all ' + checks + ' checks passed') diff --git a/packages/dsh-deckcraft/cordis.patch.yml b/packages/dsh-deckcraft/cordis.patch.yml new file mode 100644 index 0000000..e9e2956 --- /dev/null +++ b/packages/dsh-deckcraft/cordis.patch.yml @@ -0,0 +1,18 @@ +# dsh-deckcraft bundle layer (alpha). +# +# One row ('deckcraft') owns the whole plugin: its Node half registers FOUR tools +# that drive the user's own DeckCraft CLI (storytold/deckcraft, MIT OR +# Apache-2.0) - `deck_status`, `deck_commands`, `deck_run` and `deck_export`. +# Host-only: a deck is a file in the workspace and the answer is prose plus paths, +# so there is no route to serve and no browser half to load. +# +# Nothing shipped is patched and no core row is disabled: DSH has no slide +# surface, and DeckCraft is a program the user installs, not an engine this +# package vendors or downloads. +# +# Nothing for scripts/sync-vendored.ps1: no engine is vendored or forked. The +# `deckcraft-cli` binary is the user's, and this package ships the argv builder, +# the command-name parser and the output scope. +- insert: + - id: deckcraft + name: 'dsh-deckcraft' diff --git a/packages/dsh-deckcraft/lib/deck.js b/packages/dsh-deckcraft/lib/deck.js new file mode 100644 index 0000000..55e68cc --- /dev/null +++ b/packages/dsh-deckcraft/lib/deck.js @@ -0,0 +1,209 @@ +/** + * dsh-deckcraft - the engine. + * + * DeckCraft's contract, as its README states it: every action is a command with + * a stable id, so people, scripts and agents use the same verbs. This row drives + * that contract from the CLI rather than hardcoding 200 tool wrappers: + * + * deckcraft-cli commands [prefix] list the command ids + * deckcraft-cli run --cmd 'id={json}' run one or more, in order + * deckcraft-cli run --save deck.deckcraft + * deckcraft-cli render --all --scale 1 + * deckcraft-cli mcp [--connect 7990] stdio MCP, or drive the open app + * + * TWO RULES. + * 1. ARGV, NEVER A SHELL: a title, a path or a JSON argument is one argv element. + * 2. OUTPUTS ARE SCOPED: `--save` and the render directory must resolve inside + * the session workspace or a root the caller authorised for that call, so a + * command cannot write a deck over the user's documents. + */ + +import { spawn } from 'node:child_process' +import { existsSync, realpathSync, statSync } from 'node:fs' +import { homedir } from 'node:os' +import path from 'node:path' + +/** One call's default deadline and its ceiling. */ +export const DEFAULT_TIMEOUT_MS = 180_000 +export const MAX_TIMEOUT_MS = 900_000 +/** How much of one stream is kept for the answer. */ +export const MAX_STREAM_BYTES = 2 * 1024 * 1024 + +/** A command id: `format.paragraph`, `slide.new`, `view.zoom` - dotted, lower case. */ +const COMMAND_ID = /^[a-z][a-z0-9-]*(?:\.[a-z0-9-]+)+$/ + +/** Resolve the DeckCraft CLI: the caller's override, then `deckcraft-cli`. */ +export function resolveDeckCli(env = process.env, platform = process.platform) { + const override = env.DSH_DECKCRAFT_CLI + if (override && override !== '') { + return existsSync(override) ? { command: override, source: 'DSH_DECKCRAFT_CLI' } : { command: '', source: 'missing-override' } + } + const dirs = String(env.PATH ?? env.Path ?? '').split(path.delimiter).filter((dir) => dir !== '') + const exts = platform === 'win32' ? ['', '.cmd', '.exe', '.bat'] : [''] + for (const dir of dirs) { + for (const ext of exts) { + const candidate = path.join(dir, 'deckcraft-cli' + ext) + if (!existsSync(candidate)) continue + try { + if (statSync(candidate).isFile()) return { command: candidate, source: 'PATH' } + } catch { + // an unreadable PATH entry is not a candidate + } + } + } + return { command: '', source: 'missing' } +} + +/** Whether a string is a DeckCraft command id. */ +export function isCommandId(value) { + return typeof value === 'string' && value.length <= 80 && COMMAND_ID.test(value) +} + +/** + * Parse `deckcraft-cli commands` output into `{ id, summary }` rows. + * + * The CLI prints one command per line, `id` then its summary - the column split + * is whitespace, and a line that does not start with a command id is a header or + * a note and is skipped rather than guessed at. + */ +export function parseCommandList(text) { + const rows = [] + for (const raw of String(text ?? '').split('\n')) { + const line = raw.trim() + if (line === '') continue + const match = /^([a-z][a-z0-9-]*(?:\.[a-z0-9-]+)+)\s*(.*)$/.exec(line) + if (!match) continue + rows.push({ id: match[1], summary: match[2].trim() }) + } + return rows +} + +/** Build the argv for a run: one `--cmd` per entry, then the save path. */ +export function buildRunArgs({ commands, save, sample = false, open = false } = {}) { + if (sample) return ['run', '--sample', ...(save ? ['--save', save] : [])] + if (!Array.isArray(commands) || commands.length === 0) throw new Error('no commands given') + if (commands.length > 200) throw new Error('too many commands in one run (200)') + const args = ['run'] + for (const entry of commands) { + const [id, ...rest] = String(entry).split('=') + if (!isCommandId(id)) throw new Error('not a DeckCraft command id: ' + JSON.stringify(id)) + const body = rest.join('=') + if (body !== '') { + try { + JSON.parse(body) + } catch { + throw new Error('the argument of ' + id + ' is not JSON: ' + body.slice(0, 120)) + } + } + args.push('--cmd', body === '' ? id : id + '=' + body) + } + if (save) args.push('--save', save) + if (open) args.push('--open') + return args +} + +/** Build the argv for a render. */ +export function buildRenderArgs({ deck, out, all = true, scale }) { + if (typeof deck !== 'string' || deck === '') throw new Error('no deck given') + if (typeof out !== 'string' || out === '') throw new Error('no output directory given') + const args = ['render', deck] + if (all) args.push('--all') + if (typeof scale === 'number' && Number.isFinite(scale) && scale > 0) args.push('--scale', String(scale)) + args.push(out) + return args +} + +/** Build the argv for a probe. */ +export function buildProbeArgs(kind) { + if (kind === 'version') return ['--version'] + if (kind === 'commands') return ['commands'] + if (kind === 'help') return ['--help'] + throw new Error('unknown probe: ' + String(kind)) +} + +/** True for an http(s) URL (a render target can be one in the web build). */ +export function isUrl(value) { + return /^https?:\/\//i.test(String(value)) +} + +/** + * The output scope. A save path or a render directory must resolve inside the + * workspace (or an allowed root). Symlinks are resolved first so a link inside + * the workspace cannot point the write elsewhere. + */ +export function assertOutputAllowed({ target, workspace, allowRoot, platform = process.platform, realpath = true }) { + if (typeof target !== 'string' || target.trim() === '') throw new Error('no output path given') + if (!workspace) throw new Error('refused: no session workspace is known, so no output can be scoped') + const fold = (value) => (platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value)) + const resolveOne = (value) => { + const absolute = path.resolve(value) + if (!realpath) return absolute + try { + return realpathSync(absolute) + } catch { + return absolute + } + } + const inside = (candidate, root) => { + const a = fold(resolveOne(candidate)) + const b = fold(resolveOne(root)) + return a === b || a.startsWith(b + path.sep) + } + if (inside(target, workspace)) return resolveOne(target) + if (allowRoot && allowRoot !== '' && inside(target, allowRoot)) return resolveOne(target) + throw new Error( + 'refused: ' + + path.resolve(target) + + ' is outside the session workspace (' + + path.resolve(workspace) + + '). Write the deck or the render inside the workspace, or pass allowRoot for this call.', + ) +} + +/** Run one argv array. Never a shell; never a command string. */ +export function runDeck(command, args, { timeoutMs = DEFAULT_TIMEOUT_MS, cwd, env = process.env, maxBytes = MAX_STREAM_BYTES } = {}) { + return new Promise((resolve) => { + const child = spawn(command, args, { cwd, env, windowsHide: true, shell: false }) + let stdout = Buffer.alloc(0) + let stderr = Buffer.alloc(0) + let timedOut = false + const collect = (chunk, which) => { + const current = which === 'out' ? stdout : stderr + if (current.length >= maxBytes) return + const room = maxBytes - current.length + const next = Buffer.concat([current, chunk.subarray(0, room)]) + if (which === 'out') stdout = next + else stderr = next + } + child.stdout.on('data', (chunk) => collect(chunk, 'out')) + child.stderr.on('data', (chunk) => collect(chunk, 'err')) + const timer = setTimeout(() => { + timedOut = true + try { + child.kill('SIGKILL') + } catch { + // already gone + } + }, Math.min(Math.max(1_000, timeoutMs), MAX_TIMEOUT_MS)) + child.on('error', (error) => { + clearTimeout(timer) + resolve({ code: -1, stdout: '', stderr: String(error && error.message ? error.message : error), timedOut: false }) + }) + child.on('close', (code) => { + clearTimeout(timer) + resolve({ code: typeof code === 'number' ? code : -1, stdout: stdout.toString('utf8'), stderr: stderr.toString('utf8'), timedOut }) + }) + }) +} + +/** Where decks and renders belong when the caller names neither. */ +export function defaultDeckPath(workspace, name = 'deck') { + return path.join(workspace, 'decks', name + '.deckcraft') +} + +/** The settings folder DeckCraft documents, for `deck_status` to point at. */ +export function settingsDir(env = process.env, platform = process.platform) { + if (platform === 'win32') return path.join(env.APPDATA ?? path.join(homedir(), 'AppData', 'Roaming'), 'DeckCraft') + if (platform === 'darwin') return path.join(homedir(), 'Library', 'Application Support', 'DeckCraft') + return path.join(env.XDG_CONFIG_HOME ?? path.join(homedir(), '.config'), 'deckcraft') +} diff --git a/packages/dsh-deckcraft/lib/index.js b/packages/dsh-deckcraft/lib/index.js new file mode 100644 index 0000000..945255c --- /dev/null +++ b/packages/dsh-deckcraft/lib/index.js @@ -0,0 +1,69 @@ +/** + * dsh-deckcraft - Node half. + * + * One row, four tools, no browser surface and no route: a deck is a file in the + * workspace and a render is a directory of images, so there is nothing for the + * right bar to draw and nothing to serve over HTTP. + * + * WHY IT EXISTS: DeckCraft (storytold/deckcraft, MIT OR Apache-2.0, alpha) is a + * Rust presentation app whose every button is a command with a stable id, and + * whose CLI can run those commands headlessly. That is the whole integration: + * discover the ids, run a batch, save a `.deckcraft`, render it to images the + * conversation can look at. No 200 tool wrappers, no MCP bridge to keep in step + * with a fast-moving alpha. + * + * WHAT IT IS NOT: not an installer, not a `.pptx` converter of its own (DeckCraft + * does that), and not a way to write outside the workspace - a save path or a + * render directory must resolve inside it, or inside a root the user authorised + * for that call. + */ + +import { resolveDeckCli } from './deck.js' +import { buildTools } from './tools.js' + +export const name = 'dsh-deckcraft' +export const inject = ['tools'] + +/** Kept in step with package.json by the tracked check. */ +export const PLUGIN_VERSION = '0.1.0-alpha.1' + +/** + * The row's shared dependencies, one per boot. + * @param ctx - the plugin context (inject: tools). + * @param options - `{ platform, env }`, for the checks. + */ +export function createDeps(ctx, options = {}) { + return { + ctx, + platform: options.platform ?? process.platform, + env: options.env ?? process.env, + log: { + warn: (text) => ctx.logger?.warn?.('[dsh-deckcraft] ' + text), + info: (text) => ctx.logger?.info?.('[dsh-deckcraft] ' + text), + }, + } +} + +/** The one activation line: is the CLI on PATH, and nothing more. */ +export function activationLine(found) { + if (!found || found.command === '') { + return 'The DeckCraft CLI is not on PATH; the deck_* tools will name the install source until it is (github.com/storytold/deckcraft releases).' + } + return 'DeckCraft CLI: ' + found.command + ' (' + found.source + ').' +} + +/** The one activation line. */ +export function apply(ctx) { + const deps = createDeps(ctx) + deps.log.info(activationLine(resolveDeckCli(deps.env, deps.platform))) + for (const tool of buildTools(deps)) { + ctx.effect(() => ctx.tools.register(tool), 'dsh-deckcraft: tool ' + tool.name) + } +} + +/** Exported for the tracked checks: the parts of this row worth driving directly. */ +export const __internals = { + buildTools, + createDeps, + activationLine, +} diff --git a/packages/dsh-deckcraft/lib/tools.js b/packages/dsh-deckcraft/lib/tools.js new file mode 100644 index 0000000..01a12ac --- /dev/null +++ b/packages/dsh-deckcraft/lib/tools.js @@ -0,0 +1,281 @@ +/** + * dsh-deckcraft - the four tools. + * + * DeckCraft's own contract is the API here: every button is a command with a + * stable id, so the tools are discovery (`deck_commands`), execution + * (`deck_run`), proof (`deck_export`) and readiness (`deck_status`). Nothing is + * hardcoded: a command id that this build does not offer fails at the CLI with + * its own message, and `deck_commands` is how the model finds one that does. + */ + +import { existsSync, readdirSync, mkdirSync } from 'node:fs' +import path from 'node:path' + +import { + DEFAULT_TIMEOUT_MS, + MAX_TIMEOUT_MS, + assertOutputAllowed, + buildProbeArgs, + buildRenderArgs, + buildRunArgs, + defaultDeckPath, + parseCommandList, + resolveDeckCli, + runDeck, + settingsDir, +} from './deck.js' + +const OUTPUT = { + schema: { + type: 'object', + properties: { text: { type: 'string' }, view: { type: 'object' } }, + required: ['text', 'view'], + }, + render: (_args, value) => [{ type: 'text', text: value.text }], + presentationMeta: (_args, value) => value.view, +} + +const ANSWER_CHARS = 16_000 + +function clip(text, max = ANSWER_CHARS) { + const value = String(text === undefined || text === null ? '' : text) + if (value.length <= max) return value + return value.slice(0, max) + '\n\u2026 [' + (value.length - max) + ' more characters; the answer is cut]' +} + +function sessionOf(exec) { + const session = exec && exec.agent ? exec.agent.session : undefined + return session && typeof session.id === 'string' ? session.id : '' +} + +function workspaceOf(ctx, exec, sessionId) { + const header = exec && exec.agent && exec.agent.session ? exec.agent.session.header : undefined + if (header && typeof header.cwd === 'string' && header.cwd !== '') return header.cwd + try { + const sessions = typeof ctx.get === 'function' ? ctx.get('sessions') : undefined + const live = sessions && typeof sessions.get === 'function' && sessionId !== '' ? sessions.get(sessionId) : undefined + const cwd = live && live.header ? live.header.cwd : undefined + if (typeof cwd === 'string' && cwd !== '') return cwd + } catch { + // fall through + } + return '' +} + +function refuse(text, view = {}) { + return { text, view: { ok: false, ...view } } +} + +/** Build the tools. @param deps - `{ ctx, env, platform, log }` from the row. */ +export function buildTools(deps) { + const env = deps.env ?? process.env + const platform = deps.platform ?? process.platform + + const status = { + name: 'deck_status', + description: [ + 'Report whether the DeckCraft CLI is installed, its version, and where DeckCraft keeps its settings and logs.', + 'Call it before `deck_commands` or `deck_run` when a call fails: a missing CLI is the difference between "the command id is wrong" and "DeckCraft is not installed".', + 'It installs nothing. If the CLI is missing it names what to install (DeckCraft from storytold/deckcraft, or its `deckcraft-cli` release) and stops.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + probe: { type: 'boolean', description: 'Run `deckcraft-cli --version` (a few hundred ms).' }, + }, + }, + output: OUTPUT, + presentCall: () => ({ card: 'generic', title: 'DeckCraft status', kind: 'other' }), + presentResult: (_args, result) => ({ card: 'generic', title: 'DeckCraft status', content: result && result.text ? result.text : '' }), + async execute(args) { + const found = resolveDeckCli(env, platform) + const settings = settingsDir(env, platform) + if (found.command === '') { + return refuse( + [ + 'The DeckCraft CLI is not installed (no `deckcraft-cli` on PATH).', + 'Install DeckCraft from https://github.com/storytold/deckcraft/releases (the `deckcraft-cli` archive per OS), or point DSH_DECKCRAFT_CLI at a binary.', + 'This row installs nothing itself: DeckCraft is your app, not an engine this package ships.', + ].join('\n'), + { found: false }, + ) + } + const lines = ['DeckCraft CLI: ' + found.command + ' (' + found.source + ')', 'settings: ' + settings + (existsSync(settings) ? '' : ' (not created yet)')] + let version = '' + if (args.probe === true) { + const probe = await runDeck(found.command, buildProbeArgs('version'), { env, timeoutMs: 20_000 }) + version = (probe.stdout || probe.stderr).trim().split('\n')[0] ?? '' + lines.push('version: ' + (version === '' ? '(no answer)' : version)) + } + lines.push('', 'DeckCraft is alpha: command ids move between builds, so `deck_commands` is the source of truth for this one.') + return { text: lines.join('\n'), view: { ok: true, found: true, command: found.command, version, settings } } + }, + } + + const commands = { + name: 'deck_commands', + description: [ + 'List the command ids this DeckCraft build offers (`deckcraft-cli commands [prefix]`), with each command\'s summary.', + 'Use a prefix to keep the list small (`slide.`, `format.`, `view.`). The ids are what `deck_run` takes; do not invent one - a command this build does not have fails at the CLI.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + prefix: { type: 'string', description: 'Only ids starting with this prefix, e.g. "slide." or "format.paragraph".' }, + limit: { type: 'number', description: 'How many rows to return. Default 120, at most 400.' }, + }, + }, + output: OUTPUT, + presentCall: (args) => ({ card: 'generic', title: 'DeckCraft commands', kind: 'other', summary: String(args && args.prefix ? args.prefix : '') }), + presentResult: (_args, result) => ({ card: 'generic', title: 'DeckCraft commands', content: result && result.text ? result.text : '' }), + async execute(args) { + const found = resolveDeckCli(env, platform) + if (found.command === '') return refuse('The DeckCraft CLI is not installed. Call `deck_status`.') + const argv = ['commands'] + if (typeof args.prefix === 'string' && args.prefix !== '') { + if (!/^[a-z][a-z0-9.-]{0,40}$/.test(args.prefix)) return refuse('A prefix is letters, digits and dots (e.g. "slide.").') + argv.push(args.prefix) + } + const run = await runDeck(found.command, argv, { env, timeoutMs: 60_000 }) + if (run.code !== 0) return refuse('`deckcraft-cli commands` exited with code ' + run.code + '.\n' + clip(run.stderr || run.stdout, 4_000)) + const rows = parseCommandList(run.stdout) + if (rows.length === 0) return { text: clip(run.stdout, 6_000), view: { ok: true, count: 0 } } + const limit = Math.max(1, Math.min(400, typeof args.limit === 'number' ? args.limit : 120)) + const shown = rows.slice(0, limit) + const lines = shown.map((row) => row.id + (row.summary ? ' ' + row.summary : '')) + if (rows.length > limit) lines.push('... ' + (rows.length - limit) + ' more; use a prefix or raise limit (max 400)') + return { text: lines.join('\n'), view: { ok: true, count: rows.length, shown: shown.length } } + }, + } + + const run = { + name: 'deck_run', + description: [ + 'Build or edit a deck by running DeckCraft commands and saving a `.deckcraft` file in the workspace.', + '`commands` is a list like `["slide.new={\\"layout\\":\\"titleOnly\\",\\"title\\":\\"Hello\\"}", "slide.new={\\"layout\\":\\"titleOnly\\",\\"title\\":\\"World\\"}"]` - the id first, then its JSON argument after `=`. They run in order, in one document.', + 'The save path defaults to `decks/deck.deckcraft` in the workspace and must resolve inside it (or inside an `allowRoot` the user authorised). `sample:true` writes DeckCraft\'s built-in sample deck instead, which is the shortest way to prove the CLI works.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + commands: { type: 'array', items: { type: 'string' }, description: 'Command ids, each optionally followed by =.' }, + sample: { type: 'boolean', description: 'Write the built-in sample deck instead of running commands.' }, + save: { type: 'string', description: 'Workspace-relative .deckcraft path. Default decks/deck.deckcraft.' }, + allowRoot: { type: 'string', description: 'A folder authorised for THIS call when the save path is outside the workspace.' }, + timeoutMs: { type: 'number', description: 'Deadline. Default ' + DEFAULT_TIMEOUT_MS + ', at most ' + MAX_TIMEOUT_MS + '.' }, + }, + }, + output: OUTPUT, + presentCall: () => ({ card: 'generic', title: 'Build a deck', kind: 'other' }), + presentResult: (_args, result) => ({ card: 'generic', title: 'DeckCraft', content: result && result.text ? result.text : '' }), + async execute(args, exec) { + const found = resolveDeckCli(env, platform) + if (found.command === '') return refuse('The DeckCraft CLI is not installed. Call `deck_status`.') + const sessionId = sessionOf(exec) + const workspace = workspaceOf(deps.ctx, exec, sessionId) + if (!workspace) return refuse('No session workspace is known, so the deck has nowhere allowed to go.') + const wanted = typeof args.save === 'string' && args.save !== '' ? args.save : defaultDeckPath(workspace) + let savePath + try { + savePath = assertOutputAllowed({ target: path.isAbsolute(wanted) ? wanted : path.resolve(workspace, wanted), workspace, allowRoot: args.allowRoot, platform }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + let argv + try { + argv = buildRunArgs({ commands: args.commands, sample: args.sample === true, save: savePath }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + mkdirSync(path.dirname(savePath), { recursive: true }) + const timeoutMs = typeof args.timeoutMs === 'number' ? args.timeoutMs : DEFAULT_TIMEOUT_MS + const result = await runDeck(found.command, argv, { env, cwd: workspace, timeoutMs }) + if (result.timedOut) return refuse('DeckCraft did not finish within ' + timeoutMs + ' ms and was killed. Narrow the command batch or raise timeoutMs.') + if (result.code !== 0) return refuse('DeckCraft exited with code ' + result.code + '.\n' + clip(result.stderr || result.stdout, 6_000)) + const exists = existsSync(savePath) + return { + text: [ + 'saved: ' + savePath + (exists ? '' : ' (the CLI did not create it - check the command ids with `deck_commands`)'), + clip(result.stdout || result.stderr, 4_000), + ].join('\n'), + view: { ok: true, path: savePath, exists }, + } + }, + } + + const exporter = { + name: 'deck_export', + description: [ + 'Render a deck to PNG images in the workspace (`deckcraft-cli render --all --scale `), which is how a deck becomes something a person can look at in the conversation.', + 'The deck must be inside the workspace; the output directory defaults to `renders//`. `scale:2` doubles the pixels for a retina screen.', + 'PDF export is a DeckCraft command (`deck_commands` with the "export." prefix) - use `deck_run` for it, and this tool for the slide images.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + required: ['deck'], + properties: { + deck: { type: 'string', description: 'A .deckcraft path inside the workspace (relative or absolute).' }, + out: { type: 'string', description: 'Output directory, workspace-relative. Default renders//.' }, + scale: { type: 'number', description: 'Pixel scale, e.g. 1 or 2.' }, + allowRoot: { type: 'string', description: 'A folder authorised for this call when the deck or the output is outside the workspace.' }, + timeoutMs: { type: 'number', description: 'Deadline. Default ' + DEFAULT_TIMEOUT_MS + ', at most ' + MAX_TIMEOUT_MS + '.' }, + }, + }, + output: OUTPUT, + presentCall: (args) => ({ card: 'generic', title: 'Render a deck', kind: 'other', summary: String(args && args.deck ? args.deck : '') }), + presentResult: (_args, result) => ({ card: 'generic', title: 'Rendered slides', content: result && result.text ? result.text : '' }), + async execute(args, exec) { + const found = resolveDeckCli(env, platform) + if (found.command === '') return refuse('The DeckCraft CLI is not installed. Call `deck_status`.') + const sessionId = sessionOf(exec) + const workspace = workspaceOf(deps.ctx, exec, sessionId) + if (!workspace) return refuse('No session workspace is known, so no render can be written.') + const deckWanted = String(args.deck ?? '') + if (deckWanted === '') return refuse('`deck` is required.') + let deckPath + let outDir + try { + deckPath = assertOutputAllowed({ target: path.isAbsolute(deckWanted) ? deckWanted : path.resolve(workspace, deckWanted), workspace, allowRoot: args.allowRoot, platform }) + const name = path.basename(deckPath).replace(/\.deckcraft$/i, '') + const outWanted = typeof args.out === 'string' && args.out !== '' ? args.out : path.join('renders', name) + outDir = assertOutputAllowed({ target: path.resolve(workspace, outWanted), workspace, allowRoot: args.allowRoot, platform }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + if (!existsSync(deckPath)) return refuse('No such deck: ' + deckPath + '. `deck_run` writes one.') + mkdirSync(outDir, { recursive: true }) + let argv + try { + argv = buildRenderArgs({ deck: deckPath, out: outDir, all: true, scale: args.scale }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + const timeoutMs = typeof args.timeoutMs === 'number' ? args.timeoutMs : DEFAULT_TIMEOUT_MS + const result = await runDeck(found.command, argv, { env, cwd: workspace, timeoutMs }) + if (result.timedOut) return refuse('The render did not finish within ' + timeoutMs + ' ms and was killed.') + if (result.code !== 0) return refuse('DeckCraft exited with code ' + result.code + '.\n' + clip(result.stderr || result.stdout, 6_000)) + let files = [] + try { + files = readdirSync(outDir).filter((name) => /\.(png|jpe?g)$/i.test(name)).sort().map((name) => path.join(outDir, name)) + } catch { + // the directory may not exist if the CLI printed a different path + } + return { + text: [ + 'rendered ' + files.length + ' slide image(s) in ' + outDir, + ...files.slice(0, 40), + files.length === 0 ? clip(result.stdout || result.stderr, 3_000) : '', + ] + .filter((line) => line !== '') + .join('\n'), + view: { ok: true, dir: outDir, files: files.length }, + } + }, + } + + return [status, commands, run, exporter] +} diff --git a/packages/dsh-deckcraft/package.json b/packages/dsh-deckcraft/package.json new file mode 100644 index 0000000..bc8e0bd --- /dev/null +++ b/packages/dsh-deckcraft/package.json @@ -0,0 +1,29 @@ +{ + "name": "dsh-deckcraft", + "version": "0.1.0-alpha.1", + "description": "Slides from the chat: four `deck_*` tools over the user's own DeckCraft CLI (storytold/deckcraft, MIT OR Apache-2.0) - `deck_status` (the CLI, its version, and whether a running DeckCraft answers the control channel), `deck_commands` (the command ids this build offers, so nothing is hardcoded), `deck_run` (one command or a batch, saved as a `.deckcraft` file in the workspace) and `deck_export` (render slides to PNG into the workspace). Host-only, argv-only, outputs scoped to the session workspace. Zero npm dependencies, no engine bundled, no network egress of its own.", + "type": "module", + "main": "lib/index.js", + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "files": [ + "lib", + "skills", + "checks", + "cordis.patch.yml" + ], + "scripts": { + "check": "node checks/check-deck.mjs" + }, + "engines": { + "node": ">=22" + }, + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "license": "AGPL-3.0-only" +} diff --git a/packages/dsh-deckcraft/skills/deckcraft-commands/SKILL.md b/packages/dsh-deckcraft/skills/deckcraft-commands/SKILL.md new file mode 100644 index 0000000..4c0e957 --- /dev/null +++ b/packages/dsh-deckcraft/skills/deckcraft-commands/SKILL.md @@ -0,0 +1,61 @@ +--- +name: deckcraft-commands +description: The DeckCraft command contract - every button is a command with a stable id, `deck_commands` lists the ids this build offers, `deck_run` takes `id=` entries and runs them in order in one document, and `deck_status` tells you whether the CLI is there at all. Covers discovering ids by prefix, the JSON argument shape, batching and undo, saving, and why a command id must never be invented. +whenToUse: Use before running any DeckCraft command, when a command fails with "unknown command" or a schema error, when the user asks for something the obvious id does not cover, or when a batch has to be split because one entry failed. +--- + +# The command contract + +DeckCraft's README states it directly: every action is a command with a stable +id, so people, scripts and AI agents use the same verbs. That is the API this +row drives, and it is the reason the plugin does not wrap 200 tools. + +## Discover, do not guess + +`deck_commands` runs `deckcraft-cli commands [prefix]` and parses the list. Use a +prefix to keep it small: + +- `slide.` - creating, deleting, reordering, duplicating slides +- `format.` - text and paragraph formatting +- `theme.` - applying a theme or a colour/font scheme +- `view.` - zoom, view mode, presenter view +- `export.` - PDF, PNG, the outline +- `file.` - open, save, recent + +A command id that is not in that list does not exist in this build. Do not try a +plausible spelling: DeckCraft is alpha and ids move, and a failed command is a +wasted step in a conversation. + +## The run shape + +`deck_run` builds: + +```text +deckcraft-cli run --cmd 'slide.new={"layout":"titleOnly","title":"Hello"}' --cmd 'slide.new={"layout":"titleOnly","title":"World"}' --save decks/hello.deckcraft +``` + +- The id comes first, then `=`, then the JSON argument. The argument is + validated as JSON before it is passed, so a typo fails here rather than + halfway through a deck. +- All entries run in ONE document, in order. That is also one undo unit. +- `--save` is the deck file; it must resolve inside the workspace. +- `sample:true` writes DeckCraft's built-in sample deck - the shortest proof + that the CLI and the row are working before a real batch. + +## When one entry fails + +DeckCraft stops at the failing command and its stderr names it. Read that line, +then: + +- re-check the id with `deck_commands `; +- re-check the argument against the command's own schema (the failure usually + says which field is missing or the wrong type); +- split the batch: run the first half, save, then the second - a long batch that + fails at entry 30 leaves you guessing which deck state you have. + +## What is not a command + +Reading a deck back, measuring a slide, or deciding what "looks good" are not +commands. The file is the state: re-open it with `file.` commands, render it with +`deck_export`, and look at the images. A command batch that cannot be seen is a +guess about the result. diff --git a/packages/dsh-deckcraft/skills/deckcraft-deck/SKILL.md b/packages/dsh-deckcraft/skills/deckcraft-deck/SKILL.md new file mode 100644 index 0000000..e144696 --- /dev/null +++ b/packages/dsh-deckcraft/skills/deckcraft-deck/SKILL.md @@ -0,0 +1,81 @@ +--- +name: deckcraft-deck +description: Build a deck in DeckCraft from the chat - the document model (slides, masters, the eleven layouts, placeholders that inherit position and formatting), the eight themes and their colour and font schemes, sections and notes, and how to choose a layout per slide instead of drawing a rectangle where a title belongs. Covers the shape of a command batch that produces a real deck rather than a pile of text boxes. +whenToUse: Use when the user asks for a presentation, a slide deck, a pitch, a talk, a report as slides, or an edit to an existing deck; when a deck has to match a theme or a template; or when a deck looks wrong because content was placed as shapes instead of into a layout's placeholders. +--- + +# Building a deck that behaves like a deck + +DeckCraft is a presentation app, not a canvas with slides on it. The difference +is the LAYOUT: a slide chooses one of eleven layouts, and each layout carries +placeholders - title, subtitle, body, picture, chart - whose position and +formatting come from the master and the theme. Text put into a placeholder +stays right when the theme changes, when the slide size changes, and when a +person edits it later. A text box dropped at x=120,y=80 does not. + +## The order that produces a real deck + +1. **A theme first.** `deck_run` a command that applies one (`commands` with a + `theme.` prefix lists them). A deck built before a theme is applied looks + like a default and then reflows when the theme arrives. +2. **A slide per idea, with its layout named.** `slide.new` takes the layout + (`titleOnly`, `titleAndContent`, `sectionHeader`, `twoContent`, ...). Pick + the layout that has the placeholders the content needs; do not pick + `titleOnly` and add shapes. +3. **Content into placeholders**, not shapes. The commands that set a title, a + subtitle or a body address the placeholder, so the master keeps controlling + the look. +4. **Sections when the deck has parts.** A section header slide per part is + cheaper to navigate than 20 slides in a row. +5. **Notes on the slides that need a script.** The note is where the talk goes; + the slide is for the audience. +6. **Save once, at the end of the batch**, into the workspace. + +## What a good batch looks like + +- one command per slide (`slide.new` with its layout and title), not a `run` + per slide - the batch is one undo unit and one save; +- JSON arguments are small and literal: a title, a layout id, a level; +- an id you have not seen in `deck_commands` is not run "to see what happens" - + look it up, then run it; +- the save path is inside the workspace (`decks/.deckcraft` by default). + +## Academic talks, seminars, defences, grant briefings + +Build these against `reference/academic-presentations.md` - this pack's checklist +distilled from David Hirshleifer's *Best Practices for Academic Presentations* +(28 Feb 2026, built with Claude), vendored beside it as +`reference/academic-presentation-best-practices.pdf` from + (MIT, Copyright (c) 2026 +Gabberflast; `reference/UPSTREAM-LICENSE.txt` and `reference/SOURCE.md` carry the +licence and the provenance). + +The five rules that change a command batch most: + +1. **Every title is a sentence stating the takeaway**, not a topic label + ("Prior work leaves the mechanism unexplained", never "Literature Review"). +2. **Write the titles first, as a list** and read them in order: they must tell + the whole argument (the ghost deck test). Repair the list before building any + slide. +3. **One exhibit per slide**, and mark the finding on it - an arrow, a highlight, + an annotation - so the slide works without the narration. +4. **~40 words of body text per slide**; methods detail, robustness and extra + data belong in the appendix. One sans-serif face; body >= 20pt, titles 24-28pt. +5. **Cite every borrowed claim or figure** at the bottom of its slide (~14pt), + and end on a **References** slide plus a **Conclusions** slide that stays up + during Q&A - never a "Thank You" slide. + +The reference also carries the required deck architecture, the timing budget +(one slide per minute, maximum), and the eleven common mistakes as a final pass. + +## When the user wants it to look like something + +Ask which deck/theme is the reference, then apply that theme and those layouts. +Do not imitate a deck by hand-placing rectangles: the reference's look comes from +its master and theme, and a hand-placed copy breaks on the first edit. + +## The deck is a file + +A `.deckcraft` file is the deliverable. After building it, offer the render +(`deck_export`) so the user can see the slides, and name the file path - a +conversation that describes a deck without a file has not made one. diff --git a/packages/dsh-deckcraft/skills/deckcraft-deck/reference/SOURCE.md b/packages/dsh-deckcraft/skills/deckcraft-deck/reference/SOURCE.md new file mode 100644 index 0000000..f741770 --- /dev/null +++ b/packages/dsh-deckcraft/skills/deckcraft-deck/reference/SOURCE.md @@ -0,0 +1,23 @@ +# Source + +Vendored reference for `deckcraft-deck`. + +| | | +|---|---| +| Document | *Best Practices for Academic Presentations - A practical checklist for conference talks, seminar presentations, and research briefings* | +| Author | David Hirshleifer (built with Claude), 28 Feb 2026 | +| Repository | https://github.com/Gabberflast/academic-pptx-skill | +| File | `Academic_Presentation_Best_Practices_DH_built_with_Claude_2_2026.pdf` | +| Fetched from | https://raw.githubusercontent.com/Gabberflast/academic-pptx-skill/main/Academic_Presentation_Best_Practices_DH_built_with_Claude_2_2026.pdf | +| Licence | MIT, Copyright (c) 2026 Gabberflast - see `UPSTREAM-LICENSE.txt` | +| Bytes | 194343 | +| SHA-256 | `ad89e2b8e4f276d9e9f25f7f090706906e5aac499a6e8acbd2b712d4094f9945` | + +The PDF is stored **byte-identical**; `academic-presentations.md` beside it is this +pack's distillation of it into the checks a deck is built against, and it names +the same source. `checks/check-deck.mjs` re-hashes the PDF and asserts that the +distillation still cites the repository, so neither can drift silently. + +The document's own sources are listed on its last page (Naegle 2021 in PLOS +Computational Biology, Minto's *Pyramid Principle*, University of Hull, University +of Chicago, Purdue OWL, and others). diff --git a/packages/dsh-deckcraft/skills/deckcraft-deck/reference/UPSTREAM-LICENSE.txt b/packages/dsh-deckcraft/skills/deckcraft-deck/reference/UPSTREAM-LICENSE.txt new file mode 100644 index 0000000..cdef61b --- /dev/null +++ b/packages/dsh-deckcraft/skills/deckcraft-deck/reference/UPSTREAM-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Gabberflast + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/dsh-deckcraft/skills/deckcraft-deck/reference/academic-presentation-best-practices.pdf b/packages/dsh-deckcraft/skills/deckcraft-deck/reference/academic-presentation-best-practices.pdf new file mode 100644 index 0000000..4911aef Binary files /dev/null and b/packages/dsh-deckcraft/skills/deckcraft-deck/reference/academic-presentation-best-practices.pdf differ diff --git a/packages/dsh-deckcraft/skills/deckcraft-deck/reference/academic-presentations.md b/packages/dsh-deckcraft/skills/deckcraft-deck/reference/academic-presentations.md new file mode 100644 index 0000000..b777a62 --- /dev/null +++ b/packages/dsh-deckcraft/skills/deckcraft-deck/reference/academic-presentations.md @@ -0,0 +1,141 @@ +# Academic presentations - the checks a deck is built against + +Distilled from David Hirshleifer's *Best Practices for Academic Presentations* +(28 Feb 2026, built with Claude), vendored beside this file as +`academic-presentation-best-practices.pdf` from + (MIT). Read the PDF for the +full argument; this page is the checklist `deck_run` batches are written against. + +Use it for conference talks, seminar slides, thesis defences and grant briefings. +For a product deck the same rules mostly hold, but the argument format below is +the academic one. + +## The argument comes before the design + +The hierarchy is **argument structure > data > layout > aesthetics**. A visually +plain deck with a clear argument beats a beautiful deck with none, and that is +the order to fix things in: if the argument is wrong, no theme saves it. + +- Decide the presentation **type** first: structured argument (the academic + default), or narrative/visual (public engagement, non-specialist funding + pitch). The type decides how much framing the audience needs. +- **One central claim** for the whole deck. Researchers try to present the whole + paper; resist it. Choose the part the time can carry. +- State the claim or question in the **first two or three slides**. +- Give every slide **one job**. A slide doing two things is two slides. +- Narrative spine: *Situation -> Complication -> Resolution*, or *context -> + gap -> approach -> findings -> implications*. +- Each slide should make the next feel like a consequence. + +## Titles are sentences + +The single highest-impact rule: **every slide title states the takeaway**, not a +topic. + +```text +WRONG: "Results" RIGHT: "Treatment effect holds in all three cohorts" +WRONG: "Literature Review" RIGHT: "Prior work leaves the mechanism unexplained" +WRONG: "Methods" RIGHT: "Difference-in-differences on 12 quarters of filings" +``` + +- One or two lines. Longer means the point is not sharp yet. +- **Ghost deck test**: read only the titles in order. They must tell the whole + argument. If they do not, repair the logic before touching the design. + +## One exhibit, one insight + +- One chart, table, diagram or equation per slide, and it must support that + slide's action title. If it does not, change the title or the exhibit. +- **Self-sufficient slide test**: the key point must be clear to someone who + cannot hear the narration. Add a call-out, an annotation box, or highlight the + data point. +- Prefer **graphs over tables** for results; tables are hard to parse under time + pressure. +- Figure left, explanatory text right (reading direction). +- Mark the finding **on the chart** - arrow, colour, annotation - do not make the + audience find it. +- No decorative icons, stock images or clip art. If a visual carries no + analytical content, it is noise. +- Do not paste figures from the paper: rebuild them at projection resolution. +- Only include an exhibit you will explicitly discuss. + +## Text is not a document + +- Complete sentences belong in **titles only**; body text is short parallel + bullets, one idea each. +- **~40 words of body text per slide, maximum.** Detail goes to the appendix. +- One sans-serif typeface throughout. Body >= 20pt, titles 24-28pt, citations and + footnotes ~14pt. +- Slides may drop articles and filler: `Intervention reduced costs by 23% + (p < 0.01)` beats `Our study found that the intervention reduced costs.` +- Bold and italic for key terms, never for decoration. + +## Design that gets out of the way + +- At most **three colours**: one primary, one accent, one for emphasis/alerts. + Academic default: white background, dark grey text, one accent. No decorative + gradients. +- One typeface; hierarchy comes from weight and size. +- Left-align body text; centre only titles and axis labels. One grid, one margin. +- White space is **analytical signal**: a dense slide reads as unclear thinking. +- 16:9 for screen presentations; confirm the venue's aspect ratio. + +## Citations (academic-specific) + +- Cite every claim, figure and exhibit that is not your own work. Academic + integrity applies to slides exactly as to papers; an uncited borrowed figure is + a plagiarism risk. +- In-text citations in the field's format - (Author, Year) for sciences/social + sciences, footnotes/superscripts for humanities - at the **bottom of the slide, + ~14pt**. +- A **References slide** at the end with full citations for everything cited. +- A reproduced figure carries an attribution caption beneath it *and* a full + reference. Publisher permission is often required; conference use is usually + fair use, but check. +- Say the source before showing it: "Smith et al. (2022) showed..." rather than a + silent parenthetical. + +## Deck architecture for an academic talk + +| Slide | What it must do | +|---|---| +| Title | full title as a statement or question; authors, affiliations, venue, date | +| Motivation / context | why the problem matters; the real gap in the literature | +| Research question / hypothesis | stated precisely and early | +| Methods (1-2 slides) | only what the audience needs to evaluate the findings; the rest is appendix | +| Results | one finding per slide; figures over tables; the result marked on the chart | +| Discussion / implications | interpret, state limitations, connect back to the question | +| Conclusions | one slide, the 2-3 takeaways - **stay on screen during Q&A** | +| References | full citations | +| Appendix | pre-built answers to likely questions, method detail, sensitivity analyses | + +Do not end on "Thank You" or a blank slide: the conclusions slide is what the +audience anchors questions to. + +## Timing and delivery + +- **One slide per minute, maximum.** A 15-minute slot is 12-14 content slides + (excluding title and references). +- Practise out loud to time, aiming to finish 1-2 minutes under: nerves speed + delivery up, and going over is a professional misstep at a conference. +- Practise to a specialist *and* a non-specialist; the second reveals where the + argument loses the room. +- Pre-build appendix slides for the 3-5 most likely questions. +- Invite "questions or feedback", not only questions. +- Contact details, and a QR code or short URL to the slides/preprint, on the + final slide. +- Two formats and two locations for the file; test on the venue hardware. + +## The common mistakes, as a final pass + +1. Topic labels as titles. +2. Presenting the whole paper. +3. Reading the paper aloud. +4. Evidence with no "so what". +5. Uncited borrowed figures or data. +6. Dense slides, small text. +7. Inconsistent formatting, mixed fonts, mixed citation styles. +8. Unreferenced content - if you will not discuss it, remove it. +9. Going over time. +10. Burying the research question. +11. Ending on a blank or "Thank You" slide. diff --git a/packages/dsh-deckcraft/skills/deckcraft-export/SKILL.md b/packages/dsh-deckcraft/skills/deckcraft-export/SKILL.md new file mode 100644 index 0000000..bb66c2a --- /dev/null +++ b/packages/dsh-deckcraft/skills/deckcraft-export/SKILL.md @@ -0,0 +1,61 @@ +--- +name: deckcraft-export +description: Get a deck out of DeckCraft - render slides to PNG with `deck_export` (scale, output directory, what a render actually proves), the PDF/PNG/outline export commands, opening and saving .pptx and .ppt, and the fidelity limits of an alpha presentation app. Covers the check that a deck looks right before it is called done. +whenToUse: Use after building or editing a deck, when the user asks to see the slides, when a deck has to be delivered as PDF or PowerPoint, when a render comes out empty or at the wrong size, or before saying a deck is finished. +--- + +# Getting the deck out + +A `.deckcraft` file is the source; a render is the proof. Neither replaces the +other: the file is what the user keeps editing, the images are what you and the +user look at. + +## The render + +`deck_export` runs: + +```text +deckcraft-cli render --all --scale +``` + +- `--all` renders every slide; the output directory defaults to + `renders//` inside the workspace. +- `scale:2` doubles the pixels - use it when the images will be looked at + closely, and 1 for a quick check. +- A render with zero images means the command failed or the deck is empty. The + tool returns the CLI's own output in that case; read it instead of assuming. + +Then LOOK at the images. A deck that compiles is not a deck that reads: a title +that overflows its placeholder, a two-column slide with one column empty, a +chart with no data - all of those render fine and look wrong. Describe what you +see, and fix the deck rather than the screenshot. + +## The document formats + +DeckCraft exports PDF (slides, notes pages, handouts with selectable text), +PNG/JPEG, an animated GIF and an outline. Those are commands - `deck_commands` +with the `export.` prefix lists the ids for this build, and `deck_run` runs them +with an output path inside the workspace. `.pptx` is the exchange format: open +and save a presentation, and import PowerPoint 97-2003 `.ppt/.pot/.pps` +(import only). + +## The fidelity caveats to state, not hide + +DeckCraft is alpha. When a deck leaves it: + +- say which build produced the file (`deck_status --probe`), because command ids + and export behaviour move between builds; +- a `.pptx` round-trip through another app can reflow text: the layouts and + masters are DeckCraft's own, and the receiving app has its own; +- a PDF is the safest deliverable for "it must look like this", a `.pptx` for + "they must be able to edit it"; +- fonts: DeckCraft embeds its presentation fonts, but a PDF opened on a machine + without them still renders - the embedded file is the one to send. + +## Done means + +- the file exists in the workspace and the path is named in the answer; +- the render was looked at, and the slides that were wrong were fixed; +- the export format matches what the user will do with it (present, edit, + print); +- the build/version is recorded when the deck leaves the machine. diff --git a/packages/dsh-open-in-app/lib/client.js b/packages/dsh-open-in-app/lib/client.js index c95ef17..f00ba69 100644 --- a/packages/dsh-open-in-app/lib/client.js +++ b/packages/dsh-open-in-app/lib/client.js @@ -1,6 +1,6 @@ // GENERATED - do not edit by hand. // -// Fork of @deepseek-ai/dsh-client-ui-open-in-app@0.2.0-rc.2 (lib/client.js): the module-table id is +// Fork of @deepseek-ai/dsh-client-ui-open-in-app@0.2.2-rc.5 (lib/client.js): the module-table id is // rewritten to "dsh-open-in-app", and these patches from scripts\sync-vendored.ps1 // are applied on top: // - declare the pack launcher route and the file-manager catalog ids @@ -8,904 +8,11 @@ // The pack's bundle layer disables the core row, so this copy is the one that // runs. Re-sync with: powershell -NoProfile -ExecutionPolicy Bypass -File scripts\sync-vendored.ps1 // -window.__ModuleLoader__.load({ - id: "dsh-open-in-app", - factory: (require) => { - var module = { exports: {} }; - var exports = module.exports; - Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); - let react = require("react"); - let _deepseek_ai_dsh_client_store = require("@deepseek-ai/dsh-client-store"); - let react_jsx_runtime = require("react/jsx-runtime"); - let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives"); - /** Browser-relative form of {@link OPEN_IN_APP_APPS_PATH}. */ - const OPEN_IN_APP_APPS_ROUTE = "/open-in-app/apps".slice(1); - /** Browser-relative form of {@link OPEN_IN_APP_ICON_PREFIX_PATH}. */ - const OPEN_IN_APP_ICON_PREFIX_ROUTE = "/open-in-app/icon".slice(1); - /** Browser-relative form of {@link OPEN_IN_APP_OPEN_PATH}. */ - const OPEN_IN_APP_OPEN_ROUTE = "/open-in-app/open".slice(1); - /** dsh-open-in-app: the pack's own cross-platform file-browser route. */ - const NATIVE_OPEN_ROUTE = "/api/dsh-open-in-app/open"; - /** Catalog ids whose launch is a file manager, not an editor or terminal. */ - const NATIVE_FILE_MANAGER_APPS = new Set(["finder", "explorer", "filemanager"]); - //#endregion - //#region lib/types/client/applications.js - /** Label keys for applications supported by this client. */ - const APP_LABEL_KEY = { - finder: "app.finder", - explorer: "app.explorer", - filemanager: "app.filemanager", - cursor: "app.cursor", - vscode: "app.vscode", - vscodeinsiders: "app.vscodeinsiders", - windsurf: "app.windsurf", - zed: "app.zed", - sublimetext: "app.sublimetext", - xcode: "app.xcode", - androidstudio: "app.androidstudio", - intellij: "app.intellij", - pycharm: "app.pycharm", - webstorm: "app.webstorm", - phpstorm: "app.phpstorm", - goland: "app.goland", - rider: "app.rider", - rustrover: "app.rustrover", - fork: "app.fork", - sourcetree: "app.sourcetree", - github: "app.github", - tower: "app.tower", - gitkraken: "app.gitkraken", - smartgit: "app.smartgit", - sublimemerge: "app.sublimemerge", - ghostty: "app.ghostty", - warp: "app.warp", - iterm: "app.iterm", - kitty: "app.kitty", - terminal: "app.terminal", - windowsterminal: "app.windowsterminal", - gitbash: "app.gitbash", - gnometerminal: "app.gnometerminal", - konsole: "app.konsole" - }; - //#endregion - //#region lib/types/client/controller.js - /** Browser availability/choice state and the launch carrier for the split button. */ - /** - * Owns the once-per-page availability read, the persisted last choice, and - * the launch POST. Availability and choice publish through uSES-safe sources - * so every Session header shares one truth. - */ - var OpenInAppController = class { - fetcher; - /** Installed app ids in host menu order; null until the host answered. */ - apps = (0, _deepseek_ai_dsh_client_store.createSnapshotStore)(null); - /** Last chosen app id, or empty before the first choice, shared across sessions and browser restarts. */ - choice = (0, _deepseek_ai_dsh_client_store.createSnapshotStore)("", { persist: { name: "dsh.open-in-app.choice" } }); - /** Current launch, shared by pointer and keyboard gestures. */ - operation = (0, _deepseek_ai_dsh_client_store.createSnapshotStore)({ - phase: "idle", - path: null - }); - /** - * Resolve the remembered nameable installed application, with the button's first-app fallback. - * @returns the installed app id, or undefined while unavailable. - */ - currentApp() { - const apps = (this.apps.getSnapshot() ?? []).filter((id) => APP_LABEL_KEY[id] !== void 0); - const choice = this.choice.getSnapshot(); - return apps.includes(choice) ? choice : apps[0]; - } - loading; - /** - * @param fetcher - HTTP carrier for the apps read and the launch POST. - */ - constructor(fetcher = (input, init) => fetch(input, init)) { - this.fetcher = fetcher; - } - /** - * Read availability once per controller life; concurrent calls share the read. - * A failed read publishes an empty list, which renders no button at all. - * @returns after availability is published. - */ - load() { - this.loading ??= this.run(); - return this.loading; - } - /** - * Remember one picked app id. - * @param appId - catalog id from the availability list. - */ - choose(appId) { - if (this.operation.getSnapshot().phase !== "busy") this.choice.set(appId); - } - /** - * Launch one installed app on a workspace directory. - * @param appId - catalog id from the availability list. - * @param path - the session's absolute workspace directory. - * Concurrent gestures are ignored until the current Host request settles. - * @returns after the host acknowledged the launch; rejects on any failure. - */ - async launch(appId, path) { - if (this.operation.getSnapshot().phase === "busy") return; - this.operation.set({ - phase: "busy", - path - }); - const body = { - app: appId, - path - }; - try { - const route = NATIVE_FILE_MANAGER_APPS.has(appId) ? NATIVE_OPEN_ROUTE : OPEN_IN_APP_OPEN_ROUTE; - const response = await this.fetcher(route, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(body) - }); - if (!response.ok) throw new Error(`open failed: HTTP ${String(response.status)}`); - this.operation.set({ - phase: "idle", - path - }); - } catch (error) { - this.operation.set({ - phase: "error", - path - }); - throw error; - } - } - async run() { - let apps = []; - try { - const response = await this.fetcher(OPEN_IN_APP_APPS_ROUTE, { headers: { accept: "application/json" } }); - if (response.ok) { - const payload = await response.json(); - if (Array.isArray(payload.apps)) apps = payload.apps.filter((id) => typeof id === "string"); - } - } catch {} - this.apps.set(apps); - } - }; - //#endregion - //#region lib/types/client/open-failure-toast.js - /** Per-control failure banner for path gestures. */ - /** - * Transient failure banner owned by the control that initiated the gesture, - * so one failed request announces once, from the control the user pressed. - * @returns `toast` owned by the control and `show` to announce one - * failure with resolved copy; announcing again replays the banner. - */ - function useOpenFailureToast() { - const seq = (0, react.useRef)(0); - const [banner, setBanner] = (0, react.useState)(null); - const dismiss = (0, react.useCallback)(() => { - setBanner(null); - }, []); - return { - toast: banner === null ? null : (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Toast, { - text: banner.text, - icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconWarningOutlineRegular, {}), - onDone: dismiss - }, banner.seq), - show: (text) => { - seq.current += 1; - setBanner({ - seq: seq.current, - text - }); - } - }; - } - //#endregion - //#region \0dsh-css:/home/runner/work/deepseek-harness/deepseek-harness/packages/client/ui-open-in-app/src/client/OpenTargetButton.module.css.mjs - const css = ".OMoRSG_menuAnchor{flex:none;align-self:center;display:inline-flex}.OMoRSG_split{box-sizing:border-box;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-sm);height:24px;font-family:var(--dsw-font-family);align-items:stretch;display:inline-flex;overflow:hidden}.OMoRSG_main,.OMoRSG_chevron{color:var(--dsw-alias-label-primary);white-space:nowrap;cursor:pointer;background:0 0;border:0;justify-content:center;align-items:center;font-size:11px;line-height:16px;display:inline-flex}.OMoRSG_main{gap:4px;padding:3px 5px}.OMoRSG_chevron{border-left:.5px solid var(--dsw-alias-border-l4);color:var(--dsw-alias-label-secondary);padding:3px 4px 3px 3px}.OMoRSG_main:hover:not(:disabled),.OMoRSG_main:focus-visible,.OMoRSG_chevron:hover:not(:disabled),.OMoRSG_chevron:focus-visible{background:var(--dsw-alias-interactive-bg-hover)}.OMoRSG_main:disabled,.OMoRSG_chevron:disabled{cursor:default}.OMoRSG_appIcon{object-fit:contain}.OMoRSG_split[data-size=large]{border-radius:var(--dsw-radius-md);border-color:var(--dsw-alias-border-l2);height:36px}.OMoRSG_split[data-size=large] .OMoRSG_main{gap:6px;padding:6px 14px;font-size:14px}.OMoRSG_split[data-size=large] .OMoRSG_chevron{padding:6px 10px}.OMoRSG_skeleton{border-radius:var(--dsw-radius-xs);background:var(--dsw-alias-interactive-bg-hover);flex:none;display:inline-block}"; - const tagId = "@deepseek-ai/dsh-client-ui-open-in-app/OpenTargetButton.module.css"; - if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) { - const tag = document.createElement("style"); - tag.dataset.plugin = "@deepseek-ai/dsh-client-ui-open-in-app"; - tag.dataset.pluginCss = tagId; - tag.textContent = css; - document.head.appendChild(tag); - } - var OpenTargetButton_module_css_default = { - "appIcon": "OMoRSG_appIcon", - "chevron": "OMoRSG_chevron", - "main": "OMoRSG_main", - "menuAnchor": "OMoRSG_menuAnchor", - "skeleton": "OMoRSG_skeleton", - "split": "OMoRSG_split" - }; - //#endregion - //#region lib/types/client/OpenTargetButton.js - /** Shared file and directory opener: one default action, application menu, and per-gesture feedback. */ - /** - * Serialize gestures and announce their failures through the initiating control's toast. - * @param execute - target adapter that returns the failure to announce, or null. - * @param t - localized control copy. - * @returns the pending state, feedback, and guarded action callback. - */ - function useOpenTargetGesture(execute, t) { - const [pending, setPending] = (0, react.useState)(false); - const inFlight = (0, react.useRef)(false); - const { toast, show } = useOpenFailureToast(); - return { - pending, - toast, - act: (operation) => { - if (inFlight.current) return; - inFlight.current = true; - setPending(true); - execute(operation).then((failure) => { - if (failure !== null) show(t(`path.${failure}`)); - }).finally(() => { - inFlight.current = false; - setPending(false); - }); - } - }; - } - /** One application image with a per-image fallback, shared by main and menu buttons. */ - function ApplicationIcon({ source, size = 14 }) { - const [failed, setFailed] = (0, react.useState)(false); - return source === null || failed ? (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconRightUpOutlineRegular, { size }) : (0, react_jsx_runtime.jsx)("img", { - src: source, - width: size, - height: size, - className: OpenTargetButton_module_css_default.appIcon, - alt: "", - draggable: false, - onError: () => { - setFailed(true); - } - }); - } - /** - * Render identical split buttons for files and directories. File reveal always - * stays last; it is the default only when no application is registered. - * @param props - target applications, default selection, and operations. - * @returns the control and its transient failure feedback. - */ - function OpenTargetButton(props) { - const { applications, defaultId, kind, t } = props; - const [menuOpen, setMenuOpen] = (0, react.useState)(false); - const { pending, toast, act } = useOpenTargetGesture(props.execute, t); - const preferred = kind === "file" ? applications.find((app) => app.id === defaultId) ?? applications[0] : applications.find((app) => app.id === defaultId); - const disabled = pending || props.busy === true || props.loading === true; - const hasMenu = props.loading === true || props.failed || applications.length + (kind === "file" ? 1 : 0) > 1; - const revealDefault = kind === "file" && preferred === void 0 && props.loading !== true; - const primaryLabel = preferred === void 0 ? t("path.reveal") : t("open.title", { app: preferred.name }); - const run = (operation) => { - setMenuOpen(false); - act(operation); - }; - const primary = () => { - if (revealDefault) { - run({ kind: "reveal" }); - return; - } - if (preferred !== void 0 && preferred.id !== defaultId) { - run({ - kind: "application", - id: preferred.id - }); - return; - } - run({ kind: "default" }); - }; - const icon = props.loading === true && preferred === void 0 ? (0, react_jsx_runtime.jsx)("span", { - className: OpenTargetButton_module_css_default.skeleton, - "data-open-target-skeleton": true, - "aria-hidden": "true", - style: { - width: props.prominent ? 18 : 13, - height: props.prominent ? 18 : 13 - } - }) : revealDefault ? (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutlineRegular, { size: props.prominent ? 18 : 13 }) : (0, react_jsx_runtime.jsx)(ApplicationIcon, { - source: preferred?.icon ?? null, - size: props.prominent ? 18 : 13 - }, preferred?.icon); - return (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, { - className: OpenTargetButton_module_css_default.menuAnchor, - open: menuOpen && !disabled && hasMenu, - autoFocus: true, - portal: true, - dense: true, - align: "end", - onClose: () => { - setMenuOpen(false); - }, - items: [...applications.map((app) => ({ - id: `app:${app.id}`, - icon: (0, react_jsx_runtime.jsx)(ApplicationIcon, { source: app.icon }, app.icon), - label: app.id === preferred?.id ? t("path.appDefault", { app: app.name }) : app.name - })), ...props.failed ? [{ - id: "unavailable", - label: t("path.appsError"), - disabled: true - }] : []], - footer: kind === "file" ? [{ - id: "reveal", - icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutlineRegular, {}), - label: revealDefault ? t("path.appDefault", { app: t("path.reveal") }) : t("path.reveal") - }] : [], - onSelect: (id) => { - run(id === "reveal" ? { kind: "reveal" } : { - kind: "application", - id: id.slice(4) - }); - }, - anchor: (0, react_jsx_runtime.jsxs)("div", { - className: OpenTargetButton_module_css_default.split, - "data-open-target": kind, - "data-size": props.prominent ? "large" : "compact", - "data-open-path": kind === "file" && !props.prominent ? "" : void 0, - "data-state": disabled ? "busy" : "idle", - children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, { - portal: true, - label: primaryLabel, - shortcutKeys: props.shortcut?.keys, - side: "bottom", - delayMs: 500, - children: (0, react_jsx_runtime.jsxs)("button", { - type: "button", - className: OpenTargetButton_module_css_default.main, - disabled, - "aria-label": props.prominent ? void 0 : primaryLabel, - "aria-keyshortcuts": props.shortcut?.aria, - "data-open-path-open": kind === "file" && !props.prominent ? "" : void 0, - "data-open-path-unpreviewable": props.prominent ? "" : void 0, - onClick: primary, - children: [icon, props.prominent && (revealDefault ? t("path.reveal") : t("path.open"))] - }) - }), hasMenu && (0, react_jsx_runtime.jsx)("button", { - type: "button", - className: OpenTargetButton_module_css_default.chevron, - disabled, - "aria-haspopup": "menu", - "aria-expanded": menuOpen && !disabled, - "aria-label": t("path.more"), - "data-open-path-more": kind === "file" && !props.prominent ? "" : void 0, - onClick: () => { - if (!menuOpen) props.refresh?.(); - setMenuOpen((value) => !value); - }, - children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconChevronDownOutlineRegular, { size: props.prominent ? 14 : 10 }) - })] - }) - }), toast] }); - } - //#endregion - //#region lib/types/client/OpenInAppAction.js - /** - * Adapt the installed directory catalog to the shared opening control. - * @param props - displayed directory, installed catalog, and launch operations. - * @returns the shared control, or null without an eligible application. - */ - function OpenInAppAction(props) { - const { absolutePath, useOpenInAppApps, useOpenInAppChoice, t } = props; - const available = useOpenInAppApps((apps) => apps); - const choice = useOpenInAppChoice((id) => id); - const operation = props.useOpenInAppLaunch((value) => value); - const shortcut = props.useShortcuts((rows) => rows.find((row) => row.id === "workspace.openLocal")); - const apps = (available ?? []).flatMap((id) => { - const key = APP_LABEL_KEY[id]; - return key === void 0 ? [] : [{ - id, - name: t(key), - icon: props.iconUrl(id) - }]; - }); - const preferred = apps.find((app) => app.id === choice) ?? apps[0]; - if (preferred === void 0) return null; - return (0, react_jsx_runtime.jsx)(OpenTargetButton, { - kind: "directory", - applications: apps, - defaultId: preferred.id, - failed: false, - t, - busy: operation.phase === "busy", - shortcut, - execute: async (operation) => { - const id = operation.kind === "application" ? operation.id : preferred.id; - try { - await props.launch(id, absolutePath); - } catch (_error) { - return "openError"; - } - if (operation.kind === "application") props.choose(id); - return null; - } - }, absolutePath); - } - //#endregion - //#region lib/types/client/open-path.js - /** - * Host desktop availability, file associations, and open/reveal actions over the Session Remote. - * The desktop answer is read once per page; a failed read renders no control. - */ - /** Page-lifetime desktop availability and the open/reveal carrier shared by every path control. */ - var OpenInAppPathController = class { - remote; - /** Whether the Host desktop can open paths; null until the Host answered, false also after a failed read. */ - desktop = (0, _deepseek_ai_dsh_client_store.createSnapshotStore)(null); - loading; - /** - * @param remote - the Session Remote namespace answering availability and running gestures. - */ - constructor(remote) { - this.remote = remote; - } - /** - * Read desktop availability once per controller life; concurrent calls share the read. - * @returns after availability is published. - */ - load() { - this.loading ??= this.run(); - return this.loading; - } - /** - * Open one Host path in its default application, or reveal it in the file manager. - * @param path - absolute path on the Host, as the file's metadata reports it. - * @param action - default application open, or file-manager reveal. - * @param application - registered application path for an explicit open. - * @returns the failure kind to announce, or `null` once the Host acknowledged. - */ - async openPath(path, action, application) { - const request = action === "reveal" ? { - path, - action - } : { - path, - ...application === void 0 ? {} : { application } - }; - let ok = false; - try { - ok = (await this.remote.session.openWorkspacePath(request)).ok; - } catch {} - return ok ? null : action === "open" ? "openError" : "revealError"; - } - /** - * Refresh the file's OS associations; failures remain distinct from an empty handler list. - * @param path - file path reported by the Host. - * @param signal - lifetime of the requesting preview. - * @returns application metadata, or null when the query fails. - */ - async applications(path, signal) { - let result; - try { - result = await this.remote.session.workspacePathApplications({ path }, signal); - } catch (_error) { - return null; - } - return result.ok ? result.value : null; - } - async run() { - let available = false; - try { - const result = await this.remote.session.canOpenWorkspacePath(); - available = result.ok && result.value; - } catch {} - this.desktop.set(available); - } - }; - //#endregion - //#region lib/types/client/file-applications.js - /** File association reads shared by mounted controls using the same reader and target. */ - const EMPTY = { - apps: [], - loading: true, - failed: false - }; - const readers = /* @__PURE__ */ new WeakMap(); - /** Each mounted consumer retains the query; the last release cancels and discards it. */ - function subscribe(query, target, listener) { - let targets = readers.get(query); - if (targets === void 0) { - targets = /* @__PURE__ */ new Map(); - readers.set(query, targets); - } - let entry = targets.get(target); - const initial = entry === void 0; - if (entry === void 0) { - const created = { - state: (0, _deepseek_ai_dsh_client_store.createSnapshotStore)(EMPTY), - users: 0, - controller: null, - refresh: () => { - created.controller?.abort(); - const controller = new AbortController(); - created.controller = controller; - query(target, controller.signal).then((apps) => { - if (!controller.signal.aborted) created.state.set({ - apps: apps ?? [], - loading: false, - failed: apps === null - }); - }); - } - }; - entry = created; - targets.set(target, entry); - } - const retained = entry; - retained.users += 1; - const release = retained.state.subscribe(listener); - if (initial) retained.refresh(); - return () => { - release(); - retained.users -= 1; - if (retained.users === 0) { - retained.controller?.abort(); - targets.delete(target); - } - }; - } - /** - * Share associations and refreshes across mounted controls for the same file and reader. - * @param target - path or authenticated route identifying the current file. - * @param query - stable reader scoped to the serving Host; failures resolve to null. - * @param enabled - whether a native desktop is available. - * @returns metadata, initial loading state, failure state, and a shared refresh callback. - */ - function useFileApplications(target, query, enabled) { - const retain = (0, react.useCallback)((listener) => enabled ? subscribe(query, target, listener) : () => {}, [ - enabled, - query, - target - ]); - const snapshot = (0, react.useCallback)(() => enabled ? readers.get(query)?.get(target)?.state.getSnapshot() ?? EMPTY : EMPTY, [ - enabled, - query, - target - ]); - const state = (0, react.useSyncExternalStore)(retain, snapshot, snapshot); - const refresh = (0, react.useCallback)(() => { - readers.get(query)?.get(target)?.refresh(); - }, [query, target]); - return { - ...state, - refresh - }; - } - //#endregion - //#region lib/types/client/OpenPathAction.js - /** File association adapter for the shared file/directory opening control. */ - /** - * Resolve file associations and adapt operations without embedding platform behavior in the control. - * @param props - verified file path, desktop query, native operations, and display variant. - * @returns the shared opening control, or null without a desktop. - */ - function FileOpenTarget(props) { - const desktop = props.useOpenInAppDesktop((value) => value); - const association = useFileApplications(props.absolutePath, props.applications, desktop === true); - (0, react.useEffect)(() => { - if (desktop === null) props.loadDesktop(); - }, [desktop, props.loadDesktop]); - if (desktop !== true) return null; - const { apps } = association; - return (0, react_jsx_runtime.jsx)(OpenTargetButton, { - kind: "file", - applications: apps, - defaultId: apps.find((app) => app.default)?.id, - loading: association.loading, - failed: association.failed, - prominent: props.empty === true, - t: props.t, - refresh: association.refresh, - execute: (operation) => props.openPath(props.absolutePath, operation.kind === "reveal" ? "reveal" : "open", operation.kind === "application" ? operation.id : void 0) - }, props.absolutePath); - } - /** - * Render the file adapter in the document header. - * @param props - document owner inputs and injected opening capabilities. - * @returns the shared split button. - */ - function OpenPathAction(props) { - return (0, react_jsx_runtime.jsx)(FileOpenTarget, { ...props }); - } - //#endregion - //#region ../../util/native-command/src/types.ts - /** - * Validate file association metadata received from a native process or authenticated Host. - * @param value - decoded application list. - * @returns validated application metadata. - * @throws Error for malformed entries or unsupported icon URLs. - */ - function parseNativeFileApplications(value) { - if (!Array.isArray(value)) throw new Error("Invalid native application list"); - const applications = []; - const entries = value; - for (const entry of entries) { - if (typeof entry !== "object" || entry === null || !("id" in entry) || !("name" in entry) || !("default" in entry) || !("icon" in entry) || typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.name !== "string" || typeof entry.default !== "boolean" || !(entry.icon === null || typeof entry.icon === "string" && /^data:image\/(?:png|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(entry.icon))) throw new Error("Invalid native application entry"); - applications.push({ - id: entry.id, - name: entry.name, - default: entry.default, - icon: entry.icon - }); - } - return applications; - } - //#endregion - //#region lib/types/client/FileRouteAction.js - async function queryRoute(url, signal) { - try { - const response = await fetch(url, { signal }); - if (!response.ok) return null; - return parseNativeFileApplications(await response.json()); - } catch (_error) { - return null; - } - } - /** - * Render file actions without bypassing the owning Session's authorization route. - * @param props - authenticated route, desktop availability, and native gesture callback. - * @returns the shared compact control, or null without a desktop. - */ - function FileRouteAction(props) { - const association = useFileApplications(props.actionUrl, queryRoute, props.available); - if (!props.available) return null; - return (0, react_jsx_runtime.jsx)(OpenTargetButton, { - kind: "file", - applications: association.apps, - defaultId: association.apps.find((app) => app.default)?.id, - failed: association.failed, - loading: association.loading, - busy: props.pending, - refresh: association.refresh, - t: props.t, - execute: async (operation) => { - return props.onAction(operation.kind === "reveal" ? "reveal" : "open", operation.kind === "application" ? operation.id : void 0); - } - }, props.actionUrl); - } - //#endregion - //#region lib/types/client/OpenPathEmptyAction.js - /** - * Render the shared file opening menu with a larger labeled main button. - * @param props - unpreviewable file and injected opening capabilities. - * @returns the shared file opening action. - */ - function OpenPathEmptyAction(props) { - return (0, react_jsx_runtime.jsx)(FileOpenTarget, { - ...props, - empty: true - }); - } - //#endregion - //#region lib/types/client/locales.js - /** `open-in-app` namespace dictionaries: the workspace split button and the document-preview path controls. */ - /** Dictionary namespace owned by this plugin. */ - const NS = "open-in-app"; - /** Application labels shared verbatim by both dictionaries (product names). */ - const PRODUCT_NAMES = { - "app.cursor": "Cursor", - "app.vscode": "VS Code", - "app.vscodeinsiders": "VS Code Insiders", - "app.windsurf": "Windsurf", - "app.zed": "Zed", - "app.sublimetext": "Sublime Text", - "app.xcode": "Xcode", - "app.androidstudio": "Android Studio", - "app.intellij": "IntelliJ IDEA", - "app.pycharm": "PyCharm", - "app.webstorm": "WebStorm", - "app.phpstorm": "PhpStorm", - "app.goland": "GoLand", - "app.rider": "Rider", - "app.rustrover": "RustRover", - "app.fork": "Fork", - "app.sourcetree": "Sourcetree", - "app.github": "GitHub Desktop", - "app.tower": "Tower", - "app.gitkraken": "GitKraken", - "app.smartgit": "SmartGit", - "app.sublimemerge": "Sublime Merge", - "app.ghostty": "Ghostty", - "app.warp": "Warp", - "app.iterm": "iTerm2", - "app.kitty": "kitty", - "app.windowsterminal": "Windows Terminal", - "app.gitbash": "Git Bash", - "app.gnometerminal": "GNOME Terminal", - "app.konsole": "Konsole" - }; - /** Simplified Chinese dictionary (the key-set source of truth). */ - const zh = { - "open.title": "用 {app} 打开", - "path.appDefault": "{app}(默认)", - "path.appsError": "无法获取应用列表", - "shortcut.busy": "正在打开工作区", - "shortcut.unavailable": "当前工作区或本地应用不可用", - "open.tooltip": "在本地打开", - "path.open": "打开", - "path.more": "更多打开方式", - "path.reveal": "显示文件位置", - "path.openError": "打开失败,请重试", - "path.revealError": "无法显示文件位置,请重试", - ...PRODUCT_NAMES, - "app.finder": "访达", - "app.explorer": "文件资源管理器", - "app.filemanager": "文件管理器", - "app.terminal": "终端" - }; - /** English dictionary, key-identical to the Chinese source of truth. */ - const en = { - "open.title": "Open in {app}", - "path.appDefault": "{app} (default)", - "path.appsError": "Could not load applications", - "shortcut.busy": "Opening workspace", - "shortcut.unavailable": "Current workspace or local application unavailable", - "open.tooltip": "Open locally", - "path.open": "Open", - "path.more": "More ways to open", - "path.reveal": "Show file location", - "path.openError": "Could not open. Try again.", - "path.revealError": "Could not show the file location. Try again.", - ...PRODUCT_NAMES, - "app.finder": "Finder", - "app.explorer": "File Explorer", - "app.filemanager": "Files", - "app.terminal": "Terminal" - }; - //#endregion - //#region lib/types/client/index.js - /** - * Shared native opening controls for workspace directories, document previews, - * delivery cards, and changed-file review. Directory choices persist in the browser; - * file defaults and application lists come from the serving Host desktop. - */ - /** Required services: sessions, layout selection, the slot registry, copy, Remote calls, and shortcuts. */ - const inject = [ - "sessions", - "slots", - "locale", - "remote", - "remote.session", - "shortcuts", - "layout" - ]; - /** - * Client plugin body: register dictionaries, workspace directory controls, and - * document preview path controls. - * @param ctx - client root context. - */ - function apply(ctx) { - const controller = new OpenInAppController(); - controller.load(); - const paths = new OpenInAppPathController(ctx.remote); - ctx.effect(() => ctx.locale.register(NS, { - zh, - en - }), "open-in-app: dictionaries"); - const t = ctx.locale.bind(NS); - const target = () => { - if (ctx.layout.panelInfo.getSnapshot().activePanelId !== null) return void 0; - const session = Object.values(ctx.sessions.list.getSnapshot().byId).find((row) => (row.retainedBy.mainView ?? 0) > 0); - const appId = controller.currentApp(); - return session?.cwd && appId !== void 0 ? { - appId, - path: session.cwd - } : void 0; - }; - ctx.effect(() => ctx.shortcuts.register({ - id: "workspace.openLocal", - label: () => t("open.tooltip"), - aliases: ["open workspace locally", "open in app"], - defaults: { - "desktop:macos": { - code: "KeyO", - modifiers: ["primary", "alt"] - }, - "desktop:windows": { - code: "KeyO", - modifiers: ["primary", "alt"] - }, - "desktop:linux": { - code: "KeyO", - modifiers: ["primary", "alt"] - }, - "web:macos": { - code: "KeyO", - modifiers: ["primary", "shift"] - }, - "web:windows": { - code: "KeyO", - modifiers: ["primary", "shift"] - } - }, - regions: ["page", "editable"], - modals: [], - resolve: () => { - if (controller.operation.getSnapshot().phase === "busy") return { - status: "blocked", - reason: t("shortcut.busy") - }; - const selected = target(); - if (selected === void 0) return { - status: "blocked", - reason: t("shortcut.unavailable") - }; - return { - status: "handled", - run: () => { - controller.launch(selected.appId, selected.path).catch((error) => { - console.warn("workspace open rejected:", error); - }); - } - }; - } - }), "open-in-app: workspace command"); - const directoryInjected = () => ({ - hooks: { - openInAppApps: controller.apps, - openInAppChoice: controller.choice, - openInAppLaunch: controller.operation, - shortcuts: ctx.shortcuts.catalog - }, - launch: (appId, path) => controller.launch(appId, path), - choose: (appId) => { - controller.choose(appId); - }, - iconUrl: (appId) => `${OPEN_IN_APP_ICON_PREFIX_ROUTE}/${appId}` - }); - function SessionOpenInAppAction(props) { - const { sessionId, useSessions } = props; - const cwd = useSessions((state) => state.byId[sessionId]?.cwd); - return cwd ? (0, react.createElement)(OpenInAppAction, { - ...props, - absolutePath: cwd - }) : null; - } - ctx.slots.inject("conversation.session.header.utilities", () => ctx.slots.register({ - name: "conversation.session.header.utilities", - id: "open-in-app", - order: -10, - locale: NS, - inject: directoryInjected - }, SessionOpenInAppAction)); - ctx.slots.inject("sidebar.right.tab.files.actions", () => ctx.slots.register({ - name: "sidebar.right.tab.files.actions", - id: "open-in-app", - locale: NS, - inject: directoryInjected - }, OpenInAppAction)); - const applications = (path, signal) => paths.applications(path, signal); - const pathInjected = () => ({ - hooks: { openInAppDesktop: paths.desktop }, - loadDesktop: () => paths.load(), - openPath: (path, action, application) => paths.openPath(path, action, application), - applications - }); - ctx.slots.inject("sidebar.right.tab.document.actions", () => ctx.slots.register({ - name: "sidebar.right.tab.document.actions", - id: "open-in-app", - locale: NS, - inject: pathInjected - }, OpenPathAction)); - ctx.slots.inject("sidebar.right.tab.document.unpreviewable", () => ctx.slots.register({ - name: "sidebar.right.tab.document.unpreviewable", - id: "open-in-app", - locale: NS, - inject: pathInjected - }, OpenPathEmptyAction)); - ctx.slots.inject("deliverables.file.actions", () => ctx.slots.register({ - name: "deliverables.file.actions", - id: "open-in-app", - locale: NS - }, FileRouteAction)); - ctx.slots.inject("deliverables.review.file.actions", () => ctx.slots.register({ - name: "deliverables.review.file.actions", - id: "open-in-app", - locale: NS - }, FileRouteAction)); - } - //#endregion - exports.apply = apply; - exports.inject = inject; - return module.exports; - } -}); +window.__ModuleLoader__.load({id:`dsh-open-in-app`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _deepseek_ai_dsh_client_ui_primitives=require("@deepseek-ai/dsh-client-ui-primitives");let react_jsx_runtime=require("react/jsx-runtime");let react=require("react");let _deepseek_ai_dsh_client_store=require("@deepseek-ai/dsh-client-store");const FILE_ADDRESS_PREFIX=`dsh-resource://file/`;function encodeSegment(segment){return encodeURIComponent(segment).replace(/%3A/gi,`:`)}function encodePath(path){return path.split(`/`).map(encodeSegment).join(`/`)}function sessionFileAddress(sessionId,path){const normalized=path.replace(/\\/g,`/`).replace(/^(?:\.\/)+/,``);return`${FILE_ADDRESS_PREFIX}session/${encodeSegment(sessionId)}/${encodePath(normalized)}`}function isWindowsStylePath(value){return/^[A-Za-z]:[/\\]/.test(value)||value.startsWith(`\\\\`)}function isAbsoluteWorkspacePath(path){return path.startsWith(`/`)||isWindowsStylePath(path)}function resolveWorkspacePath(cwd,path){if(isAbsoluteWorkspacePath(path))return path;if(cwd===void 0||cwd===``)return path;const separator=isWindowsStylePath(cwd)&&cwd.includes(`\\`)?`\\`:`/`;return`${cwd.replace(/[/\\]+$/,``)}${separator}${path.replace(/^(?:\.?[/\\])+/,``)}`}function fileAddressFor(sessionId,cwd,path){const normalized=path.replace(/\\/g,`/`);if(!isAbsoluteWorkspacePath(normalized))return sessionFileAddress(sessionId,normalized);const root=cwd===void 0?``:cwd.replace(/\\/g,`/`).replace(/\/+$/,``);if(root!==``&&normalized===root)return sessionFileAddress(sessionId,``);if(root!==``&&normalized.startsWith(`${root}/`))return sessionFileAddress(sessionId,normalized.slice(root.length+1));return sessionFileAddress(sessionId,normalized)}const FIRST_ANSWER_WAIT_MS=300;function settleWithin(pending,ms,signal){return new Promise(settle=>{const done=()=>{clearTimeout(timer);signal.removeEventListener(`abort`,done);settle()};const timer=setTimeout(done,ms);signal.addEventListener(`abort`,done,{once:true});pending.then(done)})}function registerContextMenus(ctx,paths,t,directories,report){const fileManager=()=>t(directories.apps.getSnapshot()?.includes(`finder`)?`menu.finder`:`menu.reveal`);const open=async(path,action,application)=>{report(await paths.openPath(path,action,application))};const resolvePath=async(sessionId,path,signal)=>{try{const result=await ctx.remote.workspaceFiles.stat(sessionId,path,signal);return result.ok?result.value.absolutePath:void 0}catch(_error){signal.throwIfAborted();return}};ctx.effect(()=>ctx.contextMenus.register({id:`open-in-app.workspace`,target:`workspace`,order:200,resolve:async({path},signal)=>{await directories.load();signal.throwIfAborted();const manager=directories.apps.getSnapshot()?.find(id=>[`finder`,`explorer`,`filemanager`].includes(id));return[{id:`reveal`,icon:{key:`open-in-app.reveal`},label:fileManager(),disabled:manager===void 0,failureLabel:t(`path.revealError`),...manager===void 0?{}:{run:async()=>{const outcome=await directories.launch(manager,path);report(outcome.kind===`failed`?{kind:`failed`,failure:`revealError`}:outcome)}}}]}}),`open-in-app: Workspace context menu`);ctx.effect(()=>ctx.contextMenus.register({id:`open-in-app.directory`,target:`directory`,order:100,resolve:async({sessionId,path},signal)=>{await paths.load();const cwd=ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd;const absolutePath=resolveWorkspacePath(cwd,path);signal.throwIfAborted();return[{id:`reveal`,icon:{key:`open-in-app.reveal`},label:fileManager(),disabled:paths.desktop.getSnapshot()!==true,run:()=>open(absolutePath,`reveal`)},{id:`copyPath`,icon:{key:`open-in-app.copy`},label:t(`menu.copyDirectoryPath`),failureLabel:t(`menu.copyFailed`),run:async()=>{await navigator.clipboard.writeText(absolutePath);ctx.contextMenus.notify(t(`menu.copied`),true)}}]}}),`open-in-app: directory context menu`);const fileMenu=(target,absolutePath)=>{const{sessionId,path,line}=target;const available=absolutePath!==void 0;const desktop=paths.desktop.getSnapshot()===true&&available;const apps=desktop?paths.cachedApplications(absolutePath):[];const application=apps?.find(app=>app.default);const openApplication=absolutePath===void 0||!desktop?void 0:application!==void 0?()=>open(absolutePath,`open`,application.id):apps===void 0?()=>open(absolutePath,`open`):void 0;const openIn=destination=>()=>{const cwd=ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd;ctx.sidebarRight.openResourceIn(sessionId,fileAddressFor(sessionId,cwd,path),{destination,...line===void 0?{}:{params:{line}}})};return[{id:`sidebar`,icon:{key:`open-in-app.sidebar`},label:t(`menu.openInSidebar`),disabled:!available,run:openIn(`sidebar`)},{id:`float`,icon:{key:`open-in-app.float`},label:t(`menu.openInFloat`),disabled:!available,run:openIn(`float`)},{id:`reveal`,icon:{key:`open-in-app.reveal`},label:fileManager(),disabled:!desktop,...absolutePath===void 0?{}:{run:()=>open(absolutePath,`reveal`)}},{id:`open`,label:application?t(`open.title`,{app:application.name}):t(`menu.defaultApp`),icon:{key:`open-in-app.application`,...application?.icon?{src:application.icon}:{}},disabled:openApplication===void 0,...openApplication===void 0?{}:{run:openApplication}},{id:`copyPath`,icon:{key:`open-in-app.copy`},failureLabel:t(`menu.copyFailed`),label:t(`menu.copyPath`),run:async()=>{const cwd=ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd;await navigator.clipboard.writeText(absolutePath??resolveWorkspacePath(cwd,path));ctx.contextMenus.notify(t(`menu.copied`),true)}}]};const verified=new WeakMap;let answering;ctx.effect(()=>ctx.contextMenus.register({id:`open-in-app.file`,target:`file`,order:100,observe:target=>[{getSnapshot:paths.associations.getSnapshot.bind(paths.associations),subscribe:listener=>{let applied;return paths.associations.subscribe(()=>{const verification=verified.get(target);if(verification===void 0)return;const applications=paths.cachedApplications(verification.absolutePath);if(applications===(applied?.verification===verification?applied.applications:verification.shown))return;applied={verification,applications};answering=target;try{listener()}finally{answering=void 0}})}}],resolve:(target,signal)=>{const reused=answering===target?verified.get(target):void 0;if(reused!==void 0)return fileMenu(target,reused.absolutePath);verified.delete(target);return(async()=>{await paths.load();const absolutePath=await resolvePath(target.sessionId,target.path,signal);signal.throwIfAborted();if(absolutePath===void 0)return fileMenu(target,void 0);if(paths.desktop.getSnapshot()===true){const unanswered=paths.cachedApplications(absolutePath)===void 0;const refreshed=paths.refreshApplications(absolutePath);if(unanswered){await settleWithin(refreshed,FIRST_ANSWER_WAIT_MS,signal);signal.throwIfAborted()}}verified.set(target,{absolutePath,shown:paths.cachedApplications(absolutePath)});return fileMenu(target,absolutePath)})()}}),`open-in-app: file context menu`);ctx.effect(()=>ctx.contextMenus.register({id:`open-in-app.url`,target:`url`,order:100,resolve:({sessionId,url})=>[{id:`sidebar`,icon:{key:`open-in-app.sidebar`},label:t(`menu.openInSidebar`),disabled:ctx.sidebarRightTabs.get(`browser`)===void 0,run:()=>{ctx.sidebarRight.openTabIn(sessionId,`browser`,{params:{url}})}},{id:`external`,label:t(`menu.external`),run:()=>{window.open(url,`_blank`,`noopener,noreferrer`)}},{id:`copy`,icon:{key:`open-in-app.copy`},failureLabel:t(`menu.copyFailed`),label:t(`menu.copyLink`),run:async()=>{await navigator.clipboard.writeText(url);ctx.contextMenus.notify(t(`menu.copied`),true)}}]}),`open-in-app: URL context menu`);ctx.effect(()=>ctx.contextMenus.register({id:`open-in-app.image`,target:`image`,order:200,resolve:async(target,signal)=>{const{sessionId,path}=target;await paths.load();const local=path!==void 0&&sessionId!==void 0&&paths.desktop.getSnapshot()===true?await resolvePath(sessionId,path,signal):void 0;signal.throwIfAborted();return[{id:`reveal`,icon:{key:`open-in-app.reveal`},label:fileManager(),disabled:local===void 0,...local!==void 0?{run:()=>open(local,`reveal`)}:{}}]}}),`open-in-app: image context menu`)}function ContextMenuApplicationIcon({icon}){const[failedSource,setFailedSource]=(0,react.useState)();return icon.src&&icon.src!==failedSource?(0,react_jsx_runtime.jsx)(`img`,{src:icon.src,width:14,height:14,alt:``,draggable:false,onError:()=>{setFailedSource(icon.src)}}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconRightUpOutlineRegular,{})}const OPEN_IN_APP_APPS_PATH=`/open-in-app/apps`;const OPEN_IN_APP_APPS_ROUTE=OPEN_IN_APP_APPS_PATH.slice(1);const OPEN_IN_APP_ICON_PREFIX_PATH=`/open-in-app/icon`;const OPEN_IN_APP_ICON_PREFIX_ROUTE=OPEN_IN_APP_ICON_PREFIX_PATH.slice(1);const OPEN_IN_APP_OPEN_PATH=`/open-in-app/open`;const OPEN_IN_APP_OPEN_ROUTE=OPEN_IN_APP_OPEN_PATH.slice(1); +/** dsh-open-in-app: the pack's own cross-platform file-browser route. */ +const NATIVE_OPEN_ROUTE="/api/dsh-open-in-app/open"; +/** Catalog ids whose launch is a file manager, not an editor or terminal. */ +const NATIVE_FILE_MANAGER_APPS=new Set(["finder","explorer","filemanager"]);const APP_LABEL_KEY={finder:`app.finder`,explorer:`app.explorer`,filemanager:`app.filemanager`,cursor:`app.cursor`,vscode:`app.vscode`,vscodeinsiders:`app.vscodeinsiders`,windsurf:`app.windsurf`,zed:`app.zed`,sublimetext:`app.sublimetext`,xcode:`app.xcode`,androidstudio:`app.androidstudio`,intellij:`app.intellij`,pycharm:`app.pycharm`,webstorm:`app.webstorm`,phpstorm:`app.phpstorm`,goland:`app.goland`,rider:`app.rider`,rustrover:`app.rustrover`,fork:`app.fork`,sourcetree:`app.sourcetree`,github:`app.github`,tower:`app.tower`,gitkraken:`app.gitkraken`,smartgit:`app.smartgit`,sublimemerge:`app.sublimemerge`,ghostty:`app.ghostty`,warp:`app.warp`,iterm:`app.iterm`,kitty:`app.kitty`,terminal:`app.terminal`,windowsterminal:`app.windowsterminal`,gitbash:`app.gitbash`,gnometerminal:`app.gnometerminal`,konsole:`app.konsole`};var OpenInAppController=class{fetcher;apps=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(null);choice=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(``,{persist:{name:`dsh.open-in-app.choice`}});operation=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)({phase:`idle`,path:null});currentApp(){const apps=(this.apps.getSnapshot()??[]).filter(id=>APP_LABEL_KEY[id]!==void 0);const choice=this.choice.getSnapshot();return apps.includes(choice)?choice:apps[0]}loading;constructor(fetcher=(input,init)=>fetch(input,init)){this.fetcher=fetcher}load(){this.loading??=this.run();return this.loading}choose(appId){if(this.operation.getSnapshot().phase!==`busy`)this.choice.set(appId)}async launch(appId,path){if(this.operation.getSnapshot().phase===`busy`)return{kind:`skipped`};this.operation.set({phase:`busy`,path});const body={app:appId,path};try{const route=NATIVE_FILE_MANAGER_APPS.has(appId)?NATIVE_OPEN_ROUTE:OPEN_IN_APP_OPEN_ROUTE; +const response=await this.fetcher(route,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(body)});if(!response.ok)throw new Error(`open failed: HTTP ${String(response.status)}`);this.operation.set({phase:`idle`,path});return{kind:`opened`}}catch(_error){this.operation.set({phase:`error`,path});return{kind:`failed`,failure:`openError`}}}async run(){let apps=[];try{const response=await this.fetcher(OPEN_IN_APP_APPS_ROUTE,{headers:{accept:`application/json`}});if(response.ok){const payload=await response.json();if(Array.isArray(payload.apps))apps=payload.apps.filter(id=>typeof id===`string`)}}catch(_error){}this.apps.set(apps)}};function registerSessionOpenWith(ctx,controller,t,report){const resolve=({sessionId})=>{const directory=ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd;const applications=(controller.apps.getSnapshot()??[]).flatMap(id=>{const key=APP_LABEL_KEY[id];return key===void 0?[]:[{id,name:t(key)}]});if(!directory||applications.length===0)return[];const disabled=controller.operation.getSnapshot().phase===`busy`;return[{id:`openWith`,label:t(`menu.openIn`),icon:{key:`open-in-app.application`},disabled,children:applications.map(({id,name})=>({id:`app:${id}`,label:name,disabled,icon:{key:`open-in-app.application`,src:`${OPEN_IN_APP_ICON_PREFIX_ROUTE}/${id}`},run:async()=>{const outcome=await controller.launch(id,directory);if(outcome.kind===`opened`)controller.choose(id);report(outcome)}}))}]};for(const target of[`session`,`sessionHeader`])ctx.effect(()=>ctx.contextMenus.register({id:`open-in-app.openWith`,target,order:500,observe:()=>[controller.apps,controller.operation,ctx.sessions.list,ctx.locale],resolve:value=>resolve(value).map(action=>target===`sessionHeader`?{...action,separatorBefore:true}:action)}),`open-in-app: ${target} directory menu`)}const css=`.OMoRSG_menuAnchor{flex:none;align-self:center;display:inline-flex}.OMoRSG_split{box-sizing:border-box;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-sm);height:24px;font-family:var(--dsw-font-family);align-items:stretch;display:inline-flex;overflow:hidden}.OMoRSG_main,.OMoRSG_chevron{color:var(--dsw-alias-label-primary);white-space:nowrap;cursor:pointer;background:0 0;border:0;justify-content:center;align-items:center;font-size:11px;line-height:16px;display:inline-flex}.OMoRSG_main{gap:4px;padding:3px 5px}.OMoRSG_chevron{border-left:.5px solid var(--dsw-alias-border-l4);color:var(--dsw-alias-label-secondary);padding:3px 4px 3px 3px}.OMoRSG_main:focus-visible,.OMoRSG_chevron:focus-visible{background:var(--dsw-alias-interactive-bg-hover)}@media (hover:hover){.OMoRSG_main:hover:not(:disabled),.OMoRSG_chevron:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}}.OMoRSG_main:disabled,.OMoRSG_chevron:disabled{cursor:default}.OMoRSG_appIcon{object-fit:contain}.OMoRSG_split[data-size=large]{border-radius:var(--dsw-radius-md);border-color:var(--dsw-alias-border-l2);height:36px}.OMoRSG_split[data-size=large] .OMoRSG_main{gap:6px;padding:6px 14px;font-size:14px}.OMoRSG_split[data-size=large] .OMoRSG_chevron{padding:6px 10px}.OMoRSG_skeleton{border-radius:var(--dsw-radius-xs);background:var(--dsw-alias-interactive-bg-hover);flex:none;display:inline-block}`;const tagId=`@deepseek-ai/dsh-client-ui-open-in-app/OpenTargetButton.module.css`;if(typeof document!==`undefined`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(tagId)+`]`)===null){const tag=document.createElement(`style`);tag.dataset.plugin=`@deepseek-ai/dsh-client-ui-open-in-app`;tag.dataset.pluginCss=tagId;tag.textContent=css;document.head.appendChild(tag)}var OpenTargetButton_module_css_default={"appIcon":`OMoRSG_appIcon`,"chevron":`OMoRSG_chevron`,"main":`OMoRSG_main`,"menuAnchor":`OMoRSG_menuAnchor`,"skeleton":`OMoRSG_skeleton`,"split":`OMoRSG_split`};function useOpenTargetGesture(execute,report){const[pending,setPending]=(0,react.useState)(false);const inFlight=(0,react.useRef)(false);return{pending,act:operation=>{if(inFlight.current)return;inFlight.current=true;setPending(true);execute(operation).then(report).finally(()=>{inFlight.current=false;setPending(false)})}}}function ApplicationIcon({source,size=14}){const[failed,setFailed]=(0,react.useState)(false);return source===null||failed?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconRightUpOutlineRegular,{size}):(0,react_jsx_runtime.jsx)(`img`,{src:source,width:size,height:size,className:OpenTargetButton_module_css_default.appIcon,alt:``,draggable:false,onError:()=>{setFailed(true)}})}function OpenTargetButton(props){const{applications,defaultId,kind,t}=props;const[menuOpen,setMenuOpen]=(0,react.useState)(false);const{pending,act}=useOpenTargetGesture(props.execute,props.report);const preferred=kind===`file`?applications.find(app=>app.id===defaultId)??applications[0]:applications.find(app=>app.id===defaultId);const disabled=pending||props.busy===true||props.loading===true;const hasMenu=props.loading===true||props.failed||applications.length+(kind===`file`?1:0)>1;const revealDefault=kind===`file`&&preferred===void 0&&props.loading!==true;const primaryLabel=preferred===void 0?t(`path.reveal`):t(`open.title`,{app:preferred.name});const run=operation=>{setMenuOpen(false);act(operation)};const primary=()=>{if(revealDefault){run({kind:`reveal`});return}if(preferred!==void 0&&preferred.id!==defaultId){run({kind:`application`,id:preferred.id});return}run({kind:`default`})};const icon=props.loading===true&&preferred===void 0?(0,react_jsx_runtime.jsx)(`span`,{className:OpenTargetButton_module_css_default.skeleton,"data-open-target-skeleton":true,"aria-hidden":`true`,style:{width:props.prominent?18:13,height:props.prominent?18:13}}):revealDefault?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutlineRegular,{size:props.prominent?18:13}):(0,react_jsx_runtime.jsx)(ApplicationIcon,{source:preferred?.icon??null,size:props.prominent?18:13},preferred?.icon);return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu,{className:OpenTargetButton_module_css_default.menuAnchor,open:menuOpen&&!disabled&&hasMenu,autoFocus:true,portal:true,dense:true,align:`end`,onClose:()=>{setMenuOpen(false)},items:[...applications.map(app=>({id:`app:${app.id}`,icon:(0,react_jsx_runtime.jsx)(ApplicationIcon,{source:app.icon},app.icon),label:app.id===preferred?.id?t(`path.appDefault`,{app:app.name}):app.name})),...props.failed?[{id:`unavailable`,label:t(`path.appsError`),disabled:true}]:[]],footer:kind===`file`?[{id:`reveal`,icon:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutlineRegular,{}),label:revealDefault?t(`path.appDefault`,{app:t(`path.reveal`)}):t(`path.reveal`)}]:[],onSelect:id=>{run(id===`reveal`?{kind:`reveal`}:{kind:`application`,id:id.slice(4)})},anchor:(0,react_jsx_runtime.jsxs)(`div`,{className:OpenTargetButton_module_css_default.split,"data-open-target":kind,"data-size":props.prominent?`large`:`compact`,"data-open-path":kind===`file`&&!props.prominent?``:void 0,"data-state":disabled?`busy`:`idle`,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip,{portal:true,label:primaryLabel,shortcutKeys:props.shortcut?.keys,side:`bottom`,delayMs:500,children:(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:OpenTargetButton_module_css_default.main,disabled,"aria-label":props.prominent?void 0:primaryLabel,"aria-keyshortcuts":props.shortcut?.aria,"data-open-path-open":kind===`file`&&!props.prominent?``:void 0,"data-open-path-unpreviewable":props.prominent?``:void 0,onClick:primary,children:[icon,props.prominent&&(revealDefault?t(`path.reveal`):t(`path.open`))]})}),hasMenu&&(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:OpenTargetButton_module_css_default.chevron,disabled,"aria-haspopup":`menu`,"aria-expanded":menuOpen&&!disabled,"aria-label":t(`path.more`),"data-open-path-more":kind===`file`&&!props.prominent?``:void 0,onClick:()=>{if(!menuOpen)props.refresh?.();setMenuOpen(value=>!value)},children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconChevronDownOutlineRegular,{size:props.prominent?14:10})})]})})}function OpenInAppAction(props){const{absolutePath,useOpenInAppApps,useOpenInAppChoice,t}=props;const available=useOpenInAppApps(apps=>apps);const choice=useOpenInAppChoice(id=>id);const operation=props.useOpenInAppLaunch(value=>value);const shortcut=props.useShortcuts(rows=>rows.find(row=>row.id===`workspace.openLocal`));const apps=(available??[]).flatMap(id=>{const key=APP_LABEL_KEY[id];return key===void 0?[]:[{id,name:t(key),icon:props.iconUrl(id)}]});const preferred=apps.find(app=>app.id===choice)??apps[0];if(preferred===void 0)return null;return(0,react_jsx_runtime.jsx)(OpenTargetButton,{kind:`directory`,applications:apps,defaultId:preferred.id,failed:false,t,busy:operation.phase===`busy`,shortcut,report:props.report,execute:async operation=>{const id=operation.kind===`application`?operation.id:preferred.id;const outcome=await props.launch(id,absolutePath);if(outcome.kind===`opened`&&operation.kind===`application`)props.choose(id);return outcome}},absolutePath)}function associationKey(path){const name=path.slice(Math.max(path.lastIndexOf(`/`),path.lastIndexOf(`\\`))+1);const dot=name.lastIndexOf(`.`);return dot>0&&dot{const other=right[index];return other!==void 0&&APPLICATION_FIELDS.every(field=>app[field]===other[field])})}var OpenInAppPathController=class{remote;desktop=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(null);answers=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(new Map);associations=this.answers;loading;lifetime=new AbortController;refresh;answeredBy=new Map;icons=new Map;queries=0;constructor(remote){this.remote=remote}load(){this.loading??=this.run();return this.loading}async openPath(path,action,application){const request=action===`reveal`?{path,action}:{path,...application===void 0?{}:{application}};let ok=false;try{ok=(await this.remote.session.openWorkspacePath(request)).ok}catch{}if(ok)return{kind:action===`reveal`?`revealed`:`opened`};return{kind:`failed`,failure:action===`open`?`openError`:`revealError`}}async applications(path,signal){const order=++this.queries;let result;try{result=await this.remote.session.workspacePathApplications({path},signal)}catch(_error){return null}if(!result.ok)return null;this.record(associationKey(path),order,result.value);return result.value}cachedApplications(path){return this.answers.getSnapshot().get(associationKey(path))}refreshApplications(path){if(this.lifetime.signal.aborted)return Promise.resolve();this.refresh?.abort();const refresh=new AbortController;this.refresh=refresh;return this.applications(path,AbortSignal.any([this.lifetime.signal,refresh.signal])).then(()=>{})}dispose(){this.lifetime.abort()}record(key,order,applications){if((this.answeredBy.get(key)??0)>order)return;this.answeredBy.set(key,order);const answers=this.answers.getSnapshot();const previous=answers.get(key);if(previous!==void 0&&sameApplications(previous,applications))return;const next=new Map(answers);next.set(key,applications.map(app=>{if(app.icon===null)return app;const icon=this.icons.get(app.id);if(icon===app.icon)return{...app,icon};this.icons.set(app.id,app.icon);return app}));this.answers.set(next)}async run(){let available=false;try{const result=await this.remote.session.canOpenWorkspacePath();available=result.ok&&result.value}catch{}this.desktop.set(available)}};const EMPTY={apps:[],loading:true,failed:false};const readers=new WeakMap;function subscribe(query,target,listener){let targets=readers.get(query);if(targets===void 0){targets=new Map;readers.set(query,targets)}let entry=targets.get(target);const initial=entry===void 0;if(entry===void 0){const created={state:(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(EMPTY),users:0,controller:null,refresh:()=>{created.controller?.abort();const controller=new AbortController;created.controller=controller;query(target,controller.signal).then(apps=>{if(!controller.signal.aborted)created.state.set({apps:apps??[],loading:false,failed:apps===null})})}};entry=created;targets.set(target,entry)}const retained=entry;retained.users+=1;const release=retained.state.subscribe(listener);if(initial)retained.refresh();return()=>{release();retained.users-=1;if(retained.users===0){retained.controller?.abort();targets.delete(target)}}}function useFileApplications(target,query,enabled){const retain=(0,react.useCallback)(listener=>enabled?subscribe(query,target,listener):()=>{},[enabled,query,target]);const snapshot=(0,react.useCallback)(()=>enabled?readers.get(query)?.get(target)?.state.getSnapshot()??EMPTY:EMPTY,[enabled,query,target]);const state=(0,react.useSyncExternalStore)(retain,snapshot,snapshot);const refresh=(0,react.useCallback)(()=>{readers.get(query)?.get(target)?.refresh()},[query,target]);return{...state,refresh}}function FileOpenTarget(props){const desktop=props.useOpenInAppDesktop(value=>value);const association=useFileApplications(props.absolutePath,props.applications,desktop===true);(0,react.useEffect)(()=>{if(desktop===null)props.loadDesktop()},[desktop,props.loadDesktop]);if(desktop!==true)return null;const{apps}=association;return(0,react_jsx_runtime.jsx)(OpenTargetButton,{kind:`file`,applications:apps,defaultId:apps.find(app=>app.default)?.id,loading:association.loading,failed:association.failed,prominent:props.empty===true,t:props.t,refresh:association.refresh,report:props.report,execute:operation=>props.openPath(props.absolutePath,operation.kind===`reveal`?`reveal`:`open`,operation.kind===`application`?operation.id:void 0)},props.absolutePath)}function OpenPathAction(props){return(0,react_jsx_runtime.jsx)(FileOpenTarget,{...props})}function parseNativeFileApplications(value){if(!Array.isArray(value))throw new Error(`Invalid native application list`);const applications=[];const entries=value;for(const entry of entries){if(typeof entry!==`object`||entry===null||!(`id`in entry)||!(`name`in entry)||!(`default`in entry)||!(`icon`in entry)||typeof entry.id!==`string`||entry.id.length===0||typeof entry.name!==`string`||typeof entry.default!==`boolean`||!(entry.icon===null||typeof entry.icon===`string`&&/^data:image\/(?:png|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(entry.icon)))throw new Error(`Invalid native application entry`);applications.push({id:entry.id,name:entry.name,default:entry.default,icon:entry.icon})}return applications}async function queryRoute(url,signal){try{const response=await fetch(url,{signal});if(!response.ok)return null;return parseNativeFileApplications(await response.json())}catch(_error){return null}}function FileRouteAction(props){const association=useFileApplications(props.actionUrl,queryRoute,props.available);if(!props.available)return null;return(0,react_jsx_runtime.jsx)(OpenTargetButton,{kind:`file`,applications:association.apps,defaultId:association.apps.find(app=>app.default)?.id,failed:association.failed,loading:association.loading,busy:props.pending,refresh:association.refresh,t:props.t,report:props.report,execute:operation=>props.onAction(operation.kind===`reveal`?`reveal`:`open`,operation.kind===`application`?operation.id:void 0)},props.actionUrl)}function OpenPathEmptyAction(props){return(0,react_jsx_runtime.jsx)(FileOpenTarget,{...props,empty:true})}const NS=`open-in-app`;const PRODUCT_NAMES={"app.cursor":`Cursor`,"app.vscode":`VS Code`,"app.vscodeinsiders":`VS Code Insiders`,"app.windsurf":`Windsurf`,"app.zed":`Zed`,"app.sublimetext":`Sublime Text`,"app.xcode":`Xcode`,"app.androidstudio":`Android Studio`,"app.intellij":`IntelliJ IDEA`,"app.pycharm":`PyCharm`,"app.webstorm":`WebStorm`,"app.phpstorm":`PhpStorm`,"app.goland":`GoLand`,"app.rider":`Rider`,"app.rustrover":`RustRover`,"app.fork":`Fork`,"app.sourcetree":`Sourcetree`,"app.github":`GitHub Desktop`,"app.tower":`Tower`,"app.gitkraken":`GitKraken`,"app.smartgit":`SmartGit`,"app.sublimemerge":`Sublime Merge`,"app.ghostty":`Ghostty`,"app.warp":`Warp`,"app.iterm":`iTerm2`,"app.kitty":`kitty`,"app.windowsterminal":`Windows Terminal`,"app.gitbash":`Git Bash`,"app.gnometerminal":`GNOME Terminal`,"app.konsole":`Konsole`};const zh={"menu.openIn":`在应用中打开`,"menu.openInSidebar":`在侧边栏打开`,"menu.openInFloat":`在浮窗中打开`,"menu.finder":`在 Finder 中显示`,"menu.reveal":`在文件夹显示`,"menu.defaultApp":`使用默认应用打开`,"menu.external":`外部浏览器打开`,"menu.copyLink":`复制链接地址`,"menu.copyPath":`复制文件路径`,"menu.copyDirectoryPath":`复制文件夹路径`,"menu.copied":`已复制`,"menu.copyFailed":`无法复制,请检查内容是否可用后重试`,"open.title":`用 {app} 打开`,"path.appDefault":`{app}(默认)`,"path.appsError":`无法获取应用列表`,"shortcut.busy":`正在打开工作区`,"shortcut.unavailable":`当前工作区或本地应用不可用`,"open.tooltip":`在本地打开`,"path.open":`打开`,"path.more":`更多打开方式`,"path.reveal":`显示文件位置`,"path.opened":`已在其它设备打开`,"path.revealed":`已在其它设备显示文件位置`,"path.openError":`打开失败,请重试`,"path.revealError":`无法显示文件位置,请重试`,...PRODUCT_NAMES,"app.finder":`访达`,"app.explorer":`文件资源管理器`,"app.filemanager":`文件管理器`,"app.terminal":`终端`};const en={"menu.openIn":`Open in`,"menu.openInSidebar":`Open in sidebar`,"menu.openInFloat":`Open in floating panel`,"menu.finder":`Show in Finder`,"menu.reveal":`Show in folder`,"menu.defaultApp":`Open in default application`,"menu.external":`Open in external browser`,"menu.copyLink":`Copy link address`,"menu.copyPath":`Copy file path`,"menu.copyDirectoryPath":`Copy folder path`,"menu.copied":`Copied`,"menu.copyFailed":`Could not copy. Check that the content is available, then retry.`,"open.title":`Open in {app}`,"path.appDefault":`{app} (default)`,"path.appsError":`Could not load applications`,"shortcut.busy":`Opening workspace`,"shortcut.unavailable":`Current workspace or local application unavailable`,"open.tooltip":`Open locally`,"path.open":`Open`,"path.more":`More ways to open`,"path.reveal":`Show file location`,"path.opened":`Opened on another device`,"path.revealed":`File location shown on another device`,"path.openError":`Could not open. Try again.`,"path.revealError":`Could not show the file location. Try again.`,...PRODUCT_NAMES,"app.finder":`Finder`,"app.explorer":`File Explorer`,"app.filemanager":`Files`,"app.terminal":`Terminal`};const ja={"menu.openIn":`アプリケーションで開く`,"menu.openInSidebar":`サイドバーで開く`,"menu.openInFloat":`フローティングパネルで開く`,"menu.finder":`Finder に表示`,"menu.reveal":`フォルダーに表示`,"menu.defaultApp":`既定のアプリで開く`,"menu.external":`外部ブラウザーで開く`,"menu.copyLink":`リンクアドレスをコピー`,"menu.copyPath":`ファイルパスをコピー`,"menu.copyDirectoryPath":`フォルダーパスをコピー`,"menu.copied":`コピーしました`,"menu.copyFailed":`コピーできません。内容を確認して再試行してください。`,...PRODUCT_NAMES,"open.title":`{app}で開く`,"path.appDefault":`{app}(デフォルト)`,"path.appsError":`アプリケーションを読み込めませんでした`,"shortcut.busy":`ワークスペースを開いています`,"shortcut.unavailable":`現在のワークスペースまたはローカルアプリケーションを利用できません`,"open.tooltip":`ローカルで開く`,"path.open":`開く`,"path.more":`その他の開き方`,"path.reveal":`ファイルの場所を表示`,"path.opened":`別のデバイスで開きました`,"path.revealed":`別のデバイスでファイルの場所を表示しました`,"path.openError":`開けませんでした。もう一度お試しください。`,"path.revealError":`ファイルの場所を表示できませんでした。もう一度お試しください。`,"app.finder":`Finder`,"app.explorer":`エクスプローラー`,"app.filemanager":`ファイル`,"app.terminal":`ターミナル`};const es={"menu.openIn":`Abrir con`,"menu.openInSidebar":`Abrir en la barra lateral`,"menu.openInFloat":`Abrir en un panel flotante`,"menu.finder":`Mostrar en Finder`,"menu.reveal":`Mostrar en la carpeta`,"menu.defaultApp":`Abrir en la aplicación predeterminada`,"menu.external":`Abrir en un navegador externo`,"menu.copyLink":`Copiar dirección del enlace`,"menu.copyPath":`Copiar ruta del archivo`,"menu.copyDirectoryPath":`Copiar ruta de la carpeta`,"menu.copied":`Copiado`,"menu.copyFailed":`No se pudo copiar. Compruebe que el contenido esté disponible e inténtelo de nuevo.`,"open.title":`Abrir en {app}`,"path.appDefault":`{app} (predeterminado)`,"path.appsError":`No se pudieron cargar aplicaciones`,"shortcut.busy":`Abrir espacio de trabajo`,"shortcut.unavailable":`El espacio de trabajo actual o la aplicación local no están disponibles`,"open.tooltip":`Abierto localmente`,"path.open":`Abrir`,"path.more":`Más formas de abrir`,"path.reveal":`Mostrar ubicación del archivo`,"path.opened":`Abierto en otro dispositivo`,"path.revealed":`Ubicación del archivo mostrada en otro dispositivo`,"path.openError":`No se pudo abrir. Intentar otra vez.`,"path.revealError":`No se pudo mostrar la ubicación del archivo. Intentar otra vez.`,...PRODUCT_NAMES,"app.finder":`Finder`,"app.explorer":`Explorador de archivos`,"app.filemanager":`Archivos`,"app.terminal":`terminales`};const fr={"menu.openIn":`Ouvrir avec`,"menu.openInSidebar":`Ouvrir dans la barre latérale`,"menu.openInFloat":`Ouvrir dans un panneau flottant`,"menu.finder":`Afficher dans le Finder`,"menu.reveal":`Afficher dans le dossier`,"menu.defaultApp":`Ouvrir dans l’application par défaut`,"menu.external":`Ouvrir dans un navigateur externe`,"menu.copyLink":`Copier l’adresse du lien`,"menu.copyPath":`Copier le chemin du fichier`,"menu.copyDirectoryPath":`Copier le chemin du dossier`,"menu.copied":`Copié`,"menu.copyFailed":`Impossible de copier. Vérifiez que le contenu est disponible, puis réessayez.`,"open.title":`Ouvrir dans {app}`,"path.appDefault":`{app} (par défaut)`,"path.appsError":`Impossible de charger les applications`,"shortcut.busy":`Ouverture de l'espace de travail`,"shortcut.unavailable":`Espace de travail actuel ou application locale indisponible`,"open.tooltip":`Ouvrir localement`,"path.open":`Ouvrir`,"path.more":`Plus de façons d'ouvrir`,"path.reveal":`Afficher l'emplacement du fichier`,"path.opened":`Ouvert sur un autre appareil`,"path.revealed":`Emplacement du fichier affiché sur un autre appareil`,"path.openError":`Impossible d'ouvrir. Essayer à nouveau.`,"path.revealError":`Impossible d'afficher l'emplacement du fichier. Essayer à nouveau.`,...PRODUCT_NAMES,"app.finder":`Finder`,"app.explorer":`Explorateur de fichiers`,"app.filemanager":`Fichiers`,"app.terminal":`Borne`};const de={"menu.openIn":`Öffnen mit`,"menu.openInSidebar":`In der Seitenleiste öffnen`,"menu.openInFloat":`In schwebendem Panel öffnen`,"menu.finder":`Im Finder anzeigen`,"menu.reveal":`Im Ordner anzeigen`,"menu.defaultApp":`In der Standardanwendung öffnen`,"menu.external":`In einem externen Browser öffnen`,"menu.copyLink":`Linkadresse kopieren`,"menu.copyPath":`Dateipfad kopieren`,"menu.copyDirectoryPath":`Ordnerpfad kopieren`,"menu.copied":`Kopiert`,"menu.copyFailed":`Kopieren fehlgeschlagen. Prüfen Sie, ob der Inhalt verfügbar ist, und versuchen Sie es erneut.`,"open.title":`In {app} öffnen`,"path.appDefault":`{app} (Standard)`,"path.appsError":`Anwendungen konnten nicht geladen werden`,"shortcut.busy":`Arbeitsbereich öffnen`,"shortcut.unavailable":`Aktueller Arbeitsbereich oder lokale Anwendung nicht verfügbar`,"open.tooltip":`Vor Ort geöffnet`,"path.open":`Öffnen`,"path.more":`Mehr Möglichkeiten zum Öffnen`,"path.reveal":`Dateispeicherort anzeigen`,"path.opened":`Auf einem anderen Gerät geöffnet`,"path.revealed":`Dateispeicherort auf einem anderen Gerät angezeigt`,"path.openError":`Konnte nicht geöffnet werden. Versuchen Sie es erneut.`,"path.revealError":`Der Dateispeicherort konnte nicht angezeigt werden. Versuchen Sie es erneut.`,...PRODUCT_NAMES,"app.finder":`Finder`,"app.explorer":`Datei-Explorer`,"app.filemanager":`Dateien`,"app.terminal":`Terminal`};const ru={"menu.openIn":`Открыть с помощью`,"menu.openInSidebar":`Открыть на боковой панели`,"menu.openInFloat":`Открыть на плавающей панели`,"menu.finder":`Показать в Finder`,"menu.reveal":`Показать в папке`,"menu.defaultApp":`Открыть в приложении по умолчанию`,"menu.external":`Открыть во внешнем браузере`,"menu.copyLink":`Копировать адрес ссылки`,"menu.copyPath":`Копировать путь к файлу`,"menu.copyDirectoryPath":`Копировать путь к папке`,"menu.copied":`Скопировано`,"menu.copyFailed":`Не удалось скопировать. Проверьте доступность содержимого и повторите попытку.`,"open.title":`Открыть в {app}`,"path.appDefault":`{app} (по умолчанию)`,"path.appsError":`Не удалось загрузить приложения`,"shortcut.busy":`Открытие рабочей области`,"shortcut.unavailable":`Текущая рабочая область или локальное приложение недоступно.`,"open.tooltip":`Открыть локально`,"path.open":`Открыть`,"path.more":`Больше способов открыть`,"path.reveal":`Показать местоположение файла`,"path.opened":`Открыто на другом устройстве`,"path.revealed":`Местоположение файла показано на другом устройстве`,"path.openError":`Не удалось открыть. Попробуйте еще раз.`,"path.revealError":`Не удалось показать местоположение файла. Попробуйте еще раз.`,...PRODUCT_NAMES,"app.finder":`Finder`,"app.explorer":`Проводник файлов`,"app.filemanager":`Файлы`,"app.terminal":`Терминал`};const pt={"menu.openIn":`Abrir com`,"menu.openInSidebar":`Abrir na barra lateral`,"menu.openInFloat":`Abrir em painel flutuante`,"menu.finder":`Mostrar no Finder`,"menu.reveal":`Mostrar na pasta`,"menu.defaultApp":`Abrir no aplicativo padrão`,"menu.external":`Abrir em um navegador externo`,"menu.copyLink":`Copiar endereço do link`,"menu.copyPath":`Copiar caminho do arquivo`,"menu.copyDirectoryPath":`Copiar caminho da pasta`,"menu.copied":`Copiado`,"menu.copyFailed":`Não foi possível copiar. Verifique se o conteúdo está disponível e tente novamente.`,"open.title":`Abrir em {app}`,"path.appDefault":`{app} (padrão)`,"path.appsError":`Não foi possível carregar aplicativos`,"shortcut.busy":`Abrindo espaço de trabalho`,"shortcut.unavailable":`Espaço de trabalho atual ou aplicativo local indisponível`,"open.tooltip":`Abrir localmente`,"path.open":`Abrir`,"path.more":`Mais maneiras de abrir`,"path.reveal":`Mostrar localização do arquivo`,"path.opened":`Aberto em outro dispositivo`,"path.revealed":`Localização do arquivo exibida em outro dispositivo`,"path.openError":`Não foi possível abrir. Tente novamente.`,"path.revealError":`Não foi possível mostrar o local do arquivo. Tente novamente.`,...PRODUCT_NAMES,"app.finder":`Finder`,"app.explorer":`Explorador de arquivos`,"app.filemanager":`Arquivos`,"app.terminal":`Terminais`};function createOpenInAppToastSource(){const store=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(null);let seq=0;return{hooks:{toast:store},report:outcome=>{if(outcome.kind===`skipped`)return;if(outcome.kind!==`failed`&&!(0,_deepseek_ai_dsh_client_ui_primitives.isMobileDevice)())return;seq+=1;store.set({...outcome,seq})},dismiss:()=>{store.set(null)}}}function OpenInAppToast({useToast,dismiss,t}){const toast=useToast(current=>current);if(toast===null)return null;const key=`open-in-app-${String(toast.seq)}`;if(toast.kind===`failed`)return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Toast,{text:t(toast.failure===`revealError`?`path.revealError`:`path.openError`),icon:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconWarningOutlineRegular,{}),onDone:dismiss},key);return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Toast,{text:t(toast.kind===`opened`?`path.opened`:`path.revealed`),tone:`success`,onDone:dismiss},key)}const inject=[`contextMenus`,`sidebarRight`,`sidebarRightTabs`,`sessions`,`slots`,`locale`,`remote`,`remote.session`,`remote.workspaceFiles`,`shortcuts`,`layout`];function apply(ctx){const controller=new OpenInAppController;controller.load();const paths=new OpenInAppPathController(ctx.remote);ctx.effect(()=>()=>{paths.dispose()},`open-in-app: association refreshes`);ctx.effect(()=>ctx.locale.register(NS,{zh,en,ja,es,fr,de,ru,pt}),`open-in-app: dictionaries`);const t=ctx.locale.bind(NS);const announcement=createOpenInAppToastSource();ctx.slots.inject(`contextMenu.icon`,function*(){for(const[key,Icon]of Object.entries({"open-in-app.reveal":_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutlineRegular,"open-in-app.copy":_deepseek_ai_dsh_client_ui_primitives.IconCopyOutlineRegular,"open-in-app.sidebar":_deepseek_ai_dsh_client_ui_primitives.IconPanelLeftOutlineRegular,"open-in-app.float":_deepseek_ai_dsh_client_ui_primitives.IconRightUpOutlineRegular}))yield ctx.slots.register({name:`contextMenu.icon`,key},Icon);yield ctx.slots.register({name:`contextMenu.icon`,key:`open-in-app.application`},ContextMenuApplicationIcon)});registerContextMenus(ctx,paths,t,controller,announcement.report);registerSessionOpenWith(ctx,controller,t,announcement.report);ctx.slots.inject(`shell.overlay`,()=>ctx.slots.register({name:`shell.overlay`,id:`open-in-app.toast`,locale:NS,inject:()=>({hooks:announcement.hooks,dismiss:announcement.dismiss})},OpenInAppToast));const target=()=>{if(ctx.layout.panelInfo.getSnapshot().activePanelId!==null)return void 0;const session=Object.values(ctx.sessions.list.getSnapshot().byId).find(row=>(row.retainedBy.mainView??0)>0);const appId=controller.currentApp();return session?.cwd&&appId!==void 0?{appId,path:session.cwd}:void 0};ctx.effect(()=>ctx.shortcuts.register({id:`workspace.openLocal`,label:()=>t(`open.tooltip`),aliases:[`open workspace locally`,`open in app`],defaults:{"desktop:macos":{code:`KeyO`,modifiers:[`primary`,`alt`]},"desktop:windows":{code:`KeyO`,modifiers:[`primary`,`alt`]},"desktop:linux":{code:`KeyO`,modifiers:[`primary`,`alt`]},"web:macos":{code:`KeyO`,modifiers:[`primary`,`shift`]},"web:windows":{code:`KeyO`,modifiers:[`primary`,`shift`]}},regions:[`page`,`editable`],modals:[],resolve:()=>{if(controller.operation.getSnapshot().phase===`busy`)return{status:`blocked`,reason:t(`shortcut.busy`)};const selected=target();if(selected===void 0)return{status:`blocked`,reason:t(`shortcut.unavailable`)};return{status:`handled`,run:()=>{controller.launch(selected.appId,selected.path).then(announcement.report)}}}}),`open-in-app: workspace command`);const directoryInjected=()=>({hooks:{openInAppApps:controller.apps,openInAppChoice:controller.choice,openInAppLaunch:controller.operation,shortcuts:ctx.shortcuts.catalog},launch:(appId,path)=>controller.launch(appId,path),report:announcement.report,choose:appId=>{controller.choose(appId)},iconUrl:appId=>`${OPEN_IN_APP_ICON_PREFIX_ROUTE}/${appId}`});ctx.slots.inject(`sidebar.right.tab.files.actions`,()=>ctx.slots.register({name:`sidebar.right.tab.files.actions`,id:`open-in-app`,locale:NS,inject:directoryInjected},OpenInAppAction));const applications=(path,signal)=>paths.applications(path,signal);const pathInjected=()=>({hooks:{openInAppDesktop:paths.desktop},loadDesktop:()=>paths.load(),openPath:(path,action,application)=>paths.openPath(path,action,application),applications,report:announcement.report});ctx.slots.inject(`sidebar.right.tab.document.actions`,()=>ctx.slots.register({name:`sidebar.right.tab.document.actions`,id:`open-in-app`,locale:NS,inject:pathInjected},OpenPathAction));ctx.slots.inject(`sidebar.right.tab.document.unpreviewable`,()=>ctx.slots.register({name:`sidebar.right.tab.document.unpreviewable`,id:`open-in-app`,locale:NS,inject:pathInjected},OpenPathEmptyAction));const routeInjected=()=>({report:announcement.report});ctx.slots.inject(`deliverables.file.actions`,()=>ctx.slots.register({name:`deliverables.file.actions`,id:`open-in-app`,locale:NS,inject:routeInjected},FileRouteAction));ctx.slots.inject(`deliverables.review.file.actions`,()=>ctx.slots.register({name:`deliverables.review.file.actions`,id:`open-in-app`,locale:NS,inject:routeInjected},FileRouteAction))}exports.apply=apply;exports.inject=inject;return module.exports}}); //# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/packages/dsh-rea/README.md b/packages/dsh-rea/README.md new file mode 100644 index 0000000..fa52e92 --- /dev/null +++ b/packages/dsh-rea/README.md @@ -0,0 +1,73 @@ +# dsh-rea + +Reverse engineering as a surface, over the user's own [REA](https://github.com/morluto/rea) +installation (MIT). Five `rea_*` tools give the agent a target, an evidence +store and a report — without wrapping REA's forty MCP tools one by one, and +without installing anything. + +## Why a plugin at all + +REA already speaks MCP, and a harness can mount that server directly. What a +conversation needs on top of it is the shape of an investigation: one question, +one target, one stored report, a slice to read it in, and a document a person +keeps. That is the whole of this row — and it is the part that lets the agent say +*which* evidence a claim rests on. + +## The tools + +| Tool | What it answers | +|---|---| +| `rea_status` | Is REA installed, which version, which commands THIS installation offers (`help:true`), and what a native analysis still needs (Hopper / Ghidra / IDA / Kuna are the user's own). Names the install command; installs nothing. | +| `rea_inspect` | One REA command against one target → REA's `--json`, stored as an investigation. Returns a summary and an id. | +| `rea_read` | A stored investigation: `summary` (what it is, its top-level shape) or `raw` with a 1-based line range, so a megabyte report is walked, not swallowed. | +| `rea_snapshot` | `list`, `export` (one JSON bundle into the workspace) or `import` (store one from a bundle), so a finding is reproducible elsewhere. | +| `rea_report` | A Markdown evidence report in the workspace: the question, the target, the top-level findings, the investigation id, and the limits. | + +## The rules this row keeps + +- **The target is scoped.** A local path must be inside the session workspace, + or inside a folder the user authorised for that call (`allowRoot`). A URL is + refused unless the call passes `allowUrl:true` — this package starts no + network egress of its own. +- **Argv, never a shell.** `spawn(command, args)`: a path with a space, a quote + or a `;` is one argument. +- **Output is bounded.** 2 MB per captured stream, 32 MB per stored report, a + timeout with a kill. An oversized report is refused by name. +- **Nothing is installed.** REA, its providers and their licences are the + user's. `rea_status` says what to run and stops. +- **The report carries its limits.** A decompiler prints pseudocode; a static + pass sees code, not behaviour. Every report repeats that, names the provider, + and keeps the claims that are readings apart from the ones that are + observations. + +## Skills + +Five, and they teach the loop rather than the flags: `rea-investigate` (the +order and the scope), `rea-native` (providers, one function at a time, what to +quote), `rea-javascript` (app/asar/website, the three Electron boundaries, +static vs observed), `rea-rebuild` (a recovered rule → code + tests, with the +level of agreement stated), `rea-ethics` (the three permissions — target, tool, +output — and what to refuse). + +## What it deliberately does not do + +- No MCP server of its own, no engine vendored, no provider installed. +- No analysis of a target the user has not scoped. +- No claim that a finding is behaviour: that is a test, and it belongs to + `rea-rebuild`. + +## Requirements + +- REA: `npm install --global rea-agents` (or `npx rea-agents@latest setup` to + register its MCP with an agent). `DSH_REA_CLI` pins a binary PATH does not + carry. +- Native analysis: a provider you own. Static JavaScript and .NET need none. + +## Check + +```sh +npm run check # node checks/check-rea.mjs — 73 assertions, no REA needed +``` + +The live probe runs `rea --version` when a binary is present and says loudly +when it is not. diff --git a/packages/dsh-rea/checks/check-rea.mjs b/packages/dsh-rea/checks/check-rea.mjs new file mode 100644 index 0000000..6b418d1 --- /dev/null +++ b/packages/dsh-rea/checks/check-rea.mjs @@ -0,0 +1,158 @@ +// check-rea.mjs - dsh-rea's own contract, driven directly. +// +// The row is an argv builder, a scope guard and a store; none of that needs REA +// installed, so the whole check runs on any machine. What it cannot prove is +// what REA prints - that is the live half, and it says so by driving the binary +// when one is present. +// +// Run: node checks/check-rea.mjs +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { + MAX_REPORT_BYTES, + assertTargetAllowed, + buildInspectArgs, + buildProbeArgs, + investigationDir, + isCommandName, + listInvestigations, + newInvestigationId, + parseReaJson, + readInvestigation, + resolveRea, + sliceReport, + storeInvestigation, + summarize, +} from '../lib/rea.js' +import { buildTools } from '../lib/tools.js' +import { PLUGIN_VERSION, __internals } from '../lib/index.js' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const pkg = JSON.parse(readFileSync(path.join(here, '..', 'package.json'), 'utf8')) + +let checks = 0 +let failures = 0 +const check = (label, actual, expected) => { + checks += 1 + const ok = expected === undefined ? Boolean(actual) : actual === expected + if (!ok) failures += 1 + console.log((ok ? 'ok ' : 'FAIL ') + label.padEnd(52) + (expected === undefined ? '' : ' ' + JSON.stringify(actual))) + return ok +} + +console.log('# dsh-rea') + +// --------------------------------------------------------------- the row +check('the package names the row', pkg.name, 'dsh-rea') +check('the marker matches package.json', PLUGIN_VERSION, pkg.version) +check('the bundle points at its patch', pkg.dsh.bundle.patch, './cordis.patch.yml') +check('no npm dependency is declared', Object.keys(pkg.dependencies ?? {}).length, 0) +check('the patch inserts one row', /id:\s*rea\b/.test(readFileSync(path.join(here, '..', 'cordis.patch.yml'), 'utf8'))) + +// --------------------------------------------------------------- the tools +const tools = buildTools({ ctx: {}, env: {}, platform: 'win32' }) +check('five tools are registered', tools.length, 5) +check( + 'their names are the documented surface', + tools.map((tool) => tool.name).join(','), + 'rea_status,rea_inspect,rea_read,rea_snapshot,rea_report', +) +for (const tool of tools) { + check(tool.name + ': has a schema', Boolean(tool.parameters && tool.parameters.type === 'object')) + check(tool.name + ': answers text and a view', Boolean(tool.output && tool.output.schema && tool.output.schema.required.join(',') === 'text,view')) + check(tool.name + ': describes itself', typeof tool.description === 'string' && tool.description.length > 80) + check(tool.name + ': is executed by a function', typeof tool.execute === 'function') +} + +// --------------------------------------------------------------- the argv +check('the javascript command is the default shape', buildInspectArgs({ command: 'analyze-javascript-application', target: '/work/app' }).join(' '), 'analyze-javascript-application /work/app --json') +check('a provider is passed through', buildInspectArgs({ command: 'analyze-native-binary', target: '/work/x', provider: 'ghidra' }).join(' '), 'analyze-native-binary /work/x --json --provider ghidra') +check('a flag-shaped command is refused', (() => { try { buildInspectArgs({ command: '--help', target: '/work/x' }); return 'accepted' } catch { return 'refused' } })(), 'refused') +check('a flag-shaped provider is refused', (() => { try { buildInspectArgs({ command: 'analyze-native-binary', target: '/work/x', provider: '--out' }); return 'accepted' } catch { return 'refused' } })(), 'refused') +check('an empty target is refused', (() => { try { buildInspectArgs({ command: 'analyze-javascript-application', target: '' }); return 'accepted' } catch { return 'refused' } })(), 'refused') +check('a target with spaces stays ONE argument', buildInspectArgs({ command: 'analyze-javascript-application', target: '/work/my app' }).length, 3) +check('command names are shape-checked', isCommandName('analyze-javascript-application') && !isCommandName('rm -rf') && !isCommandName('a'), true) +check('probing is version or help only', buildProbeArgs('version').join(' ') + '|' + buildProbeArgs('help').join(' '), '--version|--help') + +// --------------------------------------------------------------- the scope +const ws = path.resolve('/work/project') +check('a target inside the workspace is allowed', assertTargetAllowed({ target: path.join(ws, 'app', 'main.js'), workspace: ws, platform: 'linux', realpath: false }), path.join(ws, 'app', 'main.js')) +check('a target outside it is refused', (() => { try { assertTargetAllowed({ target: '/etc/passwd', workspace: ws, platform: 'linux', realpath: false }); return 'allowed' } catch { return 'refused' } })(), 'refused') +check('a named allowRoot is honoured', (() => { try { return assertTargetAllowed({ target: '/opt/target/bin', workspace: ws, allowRoot: '/opt/target', platform: 'linux', realpath: false }) } catch { return 'refused' } })(), path.resolve('/opt/target/bin')) +check('a URL needs the opt-in', (() => { try { assertTargetAllowed({ target: 'https://example.com', workspace: ws, platform: 'linux' }); return 'allowed' } catch { return 'refused' } })(), 'refused') +check('the URL opt-in allows it', assertTargetAllowed({ target: 'https://example.com', workspace: ws, allowUrl: true, platform: 'linux' }), 'https://example.com') +check('a sibling prefix is not "inside"', (() => { try { assertTargetAllowed({ target: '/work/project-evil/x', workspace: ws, platform: 'linux', realpath: false }); return 'allowed' } catch { return 'refused' } })(), 'refused') +check('no workspace refuses a local target', (() => { try { assertTargetAllowed({ target: '/work/project/x', workspace: '', platform: 'linux', realpath: false }); return 'allowed' } catch { return 'refused' } })(), 'refused') + +// --------------------------------------------------------------- the JSON +check('a plain JSON object parses', parseReaJson('{"a":1}').ok, true) +check('a banner before the JSON does not stop it', parseReaJson('rea 4.1.0\nwarning: provider not set\n{"modules":[1,2]}').ok, true) +check('that answer keeps the object', JSON.stringify(parseReaJson('banner\n{"modules":[1,2]}').value), '{"modules":[1,2]}') +check('an empty answer is not JSON', parseReaJson(' ').ok, false) +check('garbage is not JSON', parseReaJson('no json here').ok, false) +check('an unterminated object is not JSON', parseReaJson('{"a":1').ok, false) +check('a top-level array parses', JSON.stringify(parseReaJson('ok\n[{"x":1}]').value), '[{"x":1}]') + +// --------------------------------------------------------------- the store +const home = mkdtempSync(path.join(tmpdir(), 'dsh-rea-')) +try { + const env = { DSH_HOME: home } + const id = newInvestigationId('/work/project/app', new Date('2026-11-27T12:00:00Z')) + check('an id is sortable and readable', id.startsWith('20261127-120000') && id.includes('-app-'), true) + check('a traversal id is refused', (() => { try { investigationDir('../../x', env); return 'accepted' } catch { return 'refused' } })(), 'refused') + const stored = storeInvestigation({ id, target: '/work/project/app', command: 'analyze-javascript-application', payload: { modules: [1, 2, 3] }, env }) + check('the report is written', existsSync(path.join(stored.dir, 'report.json')), true) + check('the meta is written', existsSync(path.join(stored.dir, 'meta.json')), true) + const read = readInvestigation(id, env) + check('it reads back', read.meta.command, 'analyze-javascript-application') + check('it is listed', listInvestigations(env).length, 1) + const big = { blob: 'x'.repeat(MAX_REPORT_BYTES + 10) } + check('an oversized report is refused', (() => { try { storeInvestigation({ id: id + '-big', target: '/x', command: 'c', payload: big, env }); return 'accepted' } catch { return 'refused' } })(), 'refused') + + const slice = sliceReport(read.raw, { offset: 2, limit: 2 }) + check('a slice names its range', slice.start + '-' + slice.end + '/' + slice.total, '2-3/' + read.raw.split('\n').length) + check('a slice past the end is clamped', sliceReport('a\nb', { offset: 99 }).start, 2) + const summary = summarize({ modules: [1], nested: { a: 1 }, name: 'x' }) + check('a summary counts arrays', summary[0].includes('modules: 1 item(s)'), true) + check('a summary names nested keys', summary[1].includes('nested: {a}'), true) +} finally { + rmSync(home, { recursive: true, force: true }) +} + +// --------------------------------------------------------------- activation +check('a missing binary is said in one line', Boolean(__internals.activationLine({ command: '', source: 'missing' }).includes('npm install --global rea-agents')), true) +const resolved = resolveRea({ PATH: '', DSH_REA_CLI: '' }, 'linux') +check('no PATH entry resolves to nothing', resolved.command, '') + +// --------------------------------------------------------------- the skills +const skillsRoot = path.join(here, '..', 'skills') +const skills = ['rea-investigate', 'rea-native', 'rea-javascript', 'rea-rebuild', 'rea-ethics'] +check('five skills ship', skills.every((name) => existsSync(path.join(skillsRoot, name, 'SKILL.md'))), true) +for (const name of skills) { + const file = path.join(skillsRoot, name, 'SKILL.md') + if (!existsSync(file)) continue + const text = readFileSync(file, 'utf8') + const front = /^---\nname: ([\w-]+)\ndescription: (.+)\nwhenToUse: (.+)\n---/m.exec(text) + check(name + ': frontmatter is complete', Boolean(front)) + check(name + ': names itself', front ? front[1] : '', name) +} + +// --------------------------------------------------------------- live half +const live = resolveRea(process.env, process.platform) +if (live.command === '') { + console.log('skip the live REA probe (no `rea` on PATH; the pure half above is the contract)') +} else { + const { runRea } = await import('../lib/rea.js') + const version = await runRea(live.command, ['--version'], { timeoutMs: 20_000 }) + check('the live REA answers --version', version.code, 0) +} + +console.log('') +if (failures > 0) { + console.log(failures + ' check(s) FAILED of ' + checks) + process.exit(1) +} +console.log('all ' + checks + ' checks passed') diff --git a/packages/dsh-rea/cordis.patch.yml b/packages/dsh-rea/cordis.patch.yml new file mode 100644 index 0000000..8fac192 --- /dev/null +++ b/packages/dsh-rea/cordis.patch.yml @@ -0,0 +1,19 @@ +# dsh-rea bundle layer (alpha). +# +# One row ('rea') owns the whole plugin: its Node half registers FIVE tools that +# drive the user's own REA installation (morluto/rea, MIT) - `rea_status`, +# `rea_inspect`, `rea_read`, `rea_snapshot` and `rea_report`. Host-only: an +# investigation is JSON stored on disk and prose for the model, so there is no +# route to serve and no browser half to load - the package declares no +# dsh.client, and the boot graph gains one row. +# +# Nothing shipped is patched and no core row is disabled: DSH has no reverse +# engineering surface, and REA is a program the user installs, not an engine this +# package vendors or downloads. +# +# Nothing for scripts/sync-vendored.ps1: no engine is vendored or forked. The +# `rea` binary is the user's (or `npx rea-agents`), and this package ships the +# argv builder, the scope guard and the report writer. +- insert: + - id: rea + name: 'dsh-rea' diff --git a/packages/dsh-rea/lib/index.js b/packages/dsh-rea/lib/index.js new file mode 100644 index 0000000..78ba724 --- /dev/null +++ b/packages/dsh-rea/lib/index.js @@ -0,0 +1,75 @@ +/** + * dsh-rea - Node half. + * + * One row, five tools, no browser surface and no route: an investigation is JSON + * on disk and prose for the model, so there is nothing for the right bar to draw + * and nothing to serve over HTTP. + * + * WHY IT EXISTS: REA (morluto/rea, MIT) gives a coding agent the tools to inspect + * a program it cannot read the source of - a native binary, an Electron app, a + * .NET assembly, a website. It ships an MCP server and a CLI. This row takes the + * CLI, because a tool call that can be argued about (which command, which target, + * which slice of the report) is worth more in a conversation than forty MCP tools + * the model has to choose from blind. REA is the user's program: nothing here + * installs, venders or downloads it. + * + * WHAT IT IS NOT: not an installer (`rea_status` names the command and stops), + * not a licence for the native providers a deep analysis needs (Hopper, Ghidra, + * IDA, Kuna are the user's own), and not a way to analyse somebody else's + * machine: a target is scoped to the session workspace or a root the caller + * names, and a URL needs an explicit opt-in. + */ + +import { resolveRea } from './rea.js' +import { buildTools } from './tools.js' + +export const name = 'dsh-rea' +export const inject = ['tools'] + +/** Kept in step with package.json by the tracked check. */ +export const PLUGIN_VERSION = '0.1.0-alpha.1' + +/** + * The row's shared dependencies, one per boot. + * @param ctx - the plugin context (inject: tools). + * @param options - `{ platform, env }`, for the checks. + */ +export function createDeps(ctx, options = {}) { + return { + ctx, + platform: options.platform ?? process.platform, + env: options.env ?? process.env, + log: { + warn: (text) => ctx.logger?.warn?.('[dsh-rea] ' + text), + info: (text) => ctx.logger?.info?.('[dsh-rea] ' + text), + }, + } +} + +/** + * The one activation line. It says whether REA is on PATH and nothing more: + * running `rea --version` at every harness start is a cost with no picture to + * show for it, and `rea_status` is the tool that asks. + */ +export function activationLine(found) { + if (!found || found.command === '') { + return 'REA is not on PATH; the rea_* tools will name the install command until it is (npm install --global rea-agents).' + } + return 'REA: ' + found.command + ' (' + found.source + ').' +} + +/** The one activation line. */ +export function apply(ctx) { + const deps = createDeps(ctx) + deps.log.info(activationLine(resolveRea(deps.env, deps.platform))) + for (const tool of buildTools(deps)) { + ctx.effect(() => ctx.tools.register(tool), 'dsh-rea: tool ' + tool.name) + } +} + +/** Exported for the tracked checks: the parts of this row worth driving directly. */ +export const __internals = { + buildTools, + createDeps, + activationLine, +} diff --git a/packages/dsh-rea/lib/rea.js b/packages/dsh-rea/lib/rea.js new file mode 100644 index 0000000..f58fb95 --- /dev/null +++ b/packages/dsh-rea/lib/rea.js @@ -0,0 +1,341 @@ +/** + * dsh-rea - the engine. + * + * Everything a tool needs that is NOT a tool: where the REA binary is, how one + * argv array is run, what a target is allowed to be, where an investigation is + * stored and how a stored one is summarised. Kept free of `ctx` so the tracked + * check can drive every rule on a machine that has no REA at all. + * + * THREE RULES THIS FILE ENFORCES. + * + * 1. ARGV, NEVER A SHELL. `spawn(command, args)` with an array: a target path + * with a space, a quote or a `;` is one argument, not syntax. The same rule + * the rest of the pack's host tools hold. + * 2. A TARGET IS SCOPED. An investigation reads a program the user pointed at, + * so the path must be inside the session workspace or inside a root the + * caller named for that one call. A URL needs `allowUrl` because REA would + * then reach the network on the user's behalf - this package starts no + * egress of its own, and the opt-in is per call. + * 3. OUTPUT IS BOUNDED. Captures are capped per stream and the stored JSON has + * a ceiling; a 200 MB asar dump is refused by name instead of filling the + * disk. `rea_read` is how a large investigation is walked, in slices. + */ + +import { spawn } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs' +import { homedir } from 'node:os' +import path from 'node:path' + +/** How much of one stream is kept for the answer / the stored report. */ +export const MAX_STREAM_BYTES = 2 * 1024 * 1024 +/** The ceiling on one stored report. Above this an inspect is refused by name. */ +export const MAX_REPORT_BYTES = 32 * 1024 * 1024 +/** One inspect's default deadline, and the ceiling a caller may ask for. */ +export const DEFAULT_TIMEOUT_MS = 120_000 +export const MAX_TIMEOUT_MS = 600_000 +/** The commands REA's own help must name before `rea_inspect` will run one. */ +const COMMAND_SHAPE = /^[a-z][a-z0-9-]{2,63}$/ + +/** The directory this row keeps its investigations under. */ +export function storeRoot(env = process.env) { + const home = env.DSH_HOME && env.DSH_HOME !== '' ? env.DSH_HOME : path.join(homedir(), '.dsh') + return path.join(home, 'dsh-rea') +} + +/** + * Resolve the REA program without running it: the caller's override first, then + * `rea` on PATH. No `npx` fallback on purpose - `npx rea-agents` would download + * on first use, and a tool that silently installs something is the one thing + * this pack does not ship. + * @returns `{ command, source }` or `{ command: '', source: 'missing' }`. + */ +export function resolveRea(env = process.env, platform = process.platform) { + const override = env.DSH_REA_CLI + if (override && override !== '') { + return existsSync(override) ? { command: override, source: 'DSH_REA_CLI' } : { command: '', source: 'missing-override' } + } + const names = platform === 'win32' ? ['rea.cmd', 'rea.exe', 'rea'] : ['rea'] + const dirs = String(env.PATH ?? env.Path ?? '').split(path.delimiter).filter((dir) => dir !== '') + const exts = platform === 'win32' ? String(env.PATHEXT ?? '.CMD;.EXE;.BAT').split(';') : [''] + for (const dir of dirs) { + for (const name of names) { + const candidate = path.join(dir, name) + if (existsSync(candidate)) { + try { + if (statSync(candidate).isFile()) return { command: candidate, source: 'PATH' } + } catch { + // an unreadable PATH entry is not a candidate + } + } + if (platform === 'win32' && name !== 'rea') continue + for (const ext of exts) { + if (ext === '') continue + const withExt = path.join(dir, 'rea' + ext) + if (existsSync(withExt)) { + try { + if (statSync(withExt).isFile()) return { command: withExt, source: 'PATH' } + } catch { + // as above + } + } + } + } + } + return { command: '', source: 'missing' } +} + +/** + * Whether one REA command name is well formed. A name is data, but it is still + * matched to a shape so a caller cannot smuggle a flag into the command slot. + */ +export function isCommandName(name) { + return typeof name === 'string' && COMMAND_SHAPE.test(name) +} + +/** Build the argv for one inspect. Pure: the check drives this directly. */ +export function buildInspectArgs({ command, target, json = true, provider, out } = {}) { + if (!isCommandName(command)) throw new Error('not a REA command name: ' + JSON.stringify(command)) + if (typeof target !== 'string' || target.trim() === '') throw new Error('no target given') + const args = [command, target] + if (json) args.push('--json') + if (provider !== undefined && provider !== '') { + if (!/^[a-z][a-z0-9-]{2,31}$/.test(provider)) throw new Error('not a provider name: ' + JSON.stringify(provider)) + args.push('--provider', provider) + } + if (out !== undefined && out !== '') args.push('--out', out) + return args +} + +/** The argv for one help / version call. */ +export function buildProbeArgs(kind) { + if (kind === 'help') return ['--help'] + if (kind === 'version') return ['--version'] + throw new Error('unknown probe: ' + String(kind)) +} + +/** True when the string is an http(s) URL. */ +export function isUrl(target) { + return /^https?:\/\//i.test(String(target)) +} + +/** + * The scope guard. A local target must resolve INSIDE the workspace or inside an + * explicitly allowed root; a URL needs `allowUrl`. Symlinks are resolved first, + * so a link inside the workspace cannot point the analysis somewhere else. + * @returns the resolved absolute path (or the URL, unchanged). + */ +export function assertTargetAllowed({ target, workspace, allowRoot, allowUrl = false, platform = process.platform, realpath = true }) { + if (typeof target !== 'string' || target.trim() === '') throw new Error('no target given') + if (isUrl(target)) { + if (!allowUrl) { + throw new Error( + 'refused: ' + target + ' is a URL, and this row starts no network egress on its own. Pass allowUrl:true for this call if the user asked for that page.', + ) + } + return target + } + if (!workspace) throw new Error('refused: no session workspace is known, so no local target can be scoped') + const fold = (value) => (platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value)) + const resolveOne = (value) => { + const absolute = path.resolve(value) + if (!realpath) return absolute + try { + return realpathSync(absolute) + } catch { + return absolute + } + } + const inside = (candidate, root) => { + const a = fold(resolveOne(candidate)) + const b = fold(resolveOne(root)) + return a === b || a.startsWith(b + path.sep) + } + if (inside(target, workspace)) return resolveOne(target) + if (allowRoot && allowRoot !== '' && inside(target, allowRoot)) return resolveOne(target) + throw new Error( + 'refused: ' + + path.resolve(target) + + ' is outside the session workspace (' + + path.resolve(workspace) + + '). Move the target into the workspace, or pass allowRoot with the folder the user authorised for this call.', + ) +} + +/** Run one argv array. Never a shell; never a command string. */ +export function runRea(command, args, { timeoutMs = DEFAULT_TIMEOUT_MS, cwd, env = process.env, maxBytes = MAX_STREAM_BYTES } = {}) { + return new Promise((resolve) => { + const child = spawn(command, args, { cwd, env, windowsHide: true, shell: false }) + let stdout = Buffer.alloc(0) + let stderr = Buffer.alloc(0) + let cutOut = false + let cutErr = false + let timedOut = false + const collect = (chunk, into, flag) => { + if (into === 'out') { + if (stdout.length >= maxBytes) { + cutOut = true + return + } + const room = maxBytes - stdout.length + stdout = Buffer.concat([stdout, chunk.subarray(0, room)]) + if (chunk.length > room) cutOut = true + } else { + if (stderr.length >= maxBytes) { + cutErr = true + return + } + const room = maxBytes - stderr.length + stderr = Buffer.concat([stderr, chunk.subarray(0, room)]) + if (chunk.length > room) cutErr = true + } + void flag + } + child.stdout.on('data', (chunk) => collect(chunk, 'out')) + child.stderr.on('data', (chunk) => collect(chunk, 'err')) + const timer = setTimeout(() => { + timedOut = true + try { + child.kill('SIGKILL') + } catch { + // already gone + } + }, Math.min(Math.max(1_000, timeoutMs), MAX_TIMEOUT_MS)) + child.on('error', (error) => { + clearTimeout(timer) + resolve({ code: -1, stdout: '', stderr: String(error && error.message ? error.message : error), timedOut: false, cutOut: false, cutErr: false }) + }) + child.on('close', (code) => { + clearTimeout(timer) + resolve({ + code: typeof code === 'number' ? code : -1, + stdout: stdout.toString('utf8'), + stderr: stderr.toString('utf8'), + timedOut, + cutOut, + cutErr, + }) + }) + }) +} + +/** Parse a `--json` answer defensively: REA may print a banner before the JSON. */ +export function parseReaJson(text) { + const value = String(text ?? '').trim() + if (value === '') return { ok: false, error: 'empty output' } + try { + return { ok: true, value: JSON.parse(value) } + } catch { + // fall through: find the first object/array and parse from there + } + const object = value.indexOf('{') + const array = value.indexOf('[') + const start = object < 0 ? array : array < 0 ? object : Math.min(object, array) + if (start < 0) return { ok: false, error: 'no JSON in the output' } + const end = Math.max(value.lastIndexOf('}'), value.lastIndexOf(']')) + if (end <= start) return { ok: false, error: 'no complete JSON value in the output' } + try { + return { ok: true, value: JSON.parse(value.slice(start, end + 1)) } + } catch (error) { + return { ok: false, error: String(error && error.message ? error.message : error) } + } +} + +/** A filesystem-safe slug, short enough to keep an id readable. */ +export function slugOf(target) { + const base = String(target).replace(/^https?:\/\//i, '').replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '') + return (base === '' ? 'target' : base).slice(0, 40).toLowerCase() +} + +/** A sortable, unique-enough investigation id. */ +export function newInvestigationId(target, now = new Date()) { + const stamp = now.toISOString().replace(/[-:]/g, '').replace(/\..+$/, '').replace('T', '-') + const digest = Buffer.from(String(target)).toString('base64url').replace(/[^A-Za-z0-9]/g, '').slice(0, 6) + return stamp + '-' + slugOf(target) + '-' + digest +} + +/** `investigations//` under the store root. */ +export function investigationDir(id, env = process.env) { + if (typeof id !== 'string' || !/^[A-Za-z0-9._-]{1,120}$/.test(id)) throw new Error('not an investigation id: ' + JSON.stringify(id)) + return path.join(storeRoot(env), 'investigations', id) +} + +/** Every stored investigation, newest first. */ +export function listInvestigations(env = process.env) { + const dir = path.join(storeRoot(env), 'investigations') + if (!existsSync(dir)) return [] + const rows = [] + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (!entry.isDirectory()) continue + const metaPath = path.join(dir, entry.name, 'meta.json') + try { + rows.push({ id: entry.name, ...JSON.parse(readFileSync(metaPath, 'utf8')) }) + } catch { + rows.push({ id: entry.name, target: '', kind: 'unknown', created: '' }) + } + } + return rows.sort((a, b) => String(b.created).localeCompare(String(a.created))) +} + +/** + * Store one investigation: the meta a person reads and the report as REA + * returned it. A report over MAX_REPORT_BYTES is refused rather than written. + */ +export function storeInvestigation({ id, target, command, provider, payload, text, code, env = process.env, now = new Date() }) { + const raw = payload === undefined ? String(text ?? '') : JSON.stringify(payload, null, 2) + const bytes = Buffer.byteLength(raw, 'utf8') + if (bytes > MAX_REPORT_BYTES) { + throw new Error('refused: the report is ' + Math.round(bytes / 1024 / 1024) + ' MB, over the ' + MAX_REPORT_BYTES / 1024 / 1024 + ' MB ceiling; narrow the target and inspect again') + } + const dir = investigationDir(id, env) + mkdirSync(dir, { recursive: true }) + writeFileSync(path.join(dir, 'report.json'), raw, 'utf8') + writeFileSync( + path.join(dir, 'meta.json'), + JSON.stringify({ id, target, command, provider: provider ?? null, created: now.toISOString(), bytes, exitCode: code ?? null }, null, 2), + 'utf8', + ) + return { id, dir, bytes } +} + +/** Read one stored investigation. */ +export function readInvestigation(id, env = process.env) { + const dir = investigationDir(id, env) + const meta = JSON.parse(readFileSync(path.join(dir, 'meta.json'), 'utf8')) + const raw = readFileSync(path.join(dir, 'report.json'), 'utf8') + return { meta, raw } +} + +/** + * The summary a model reads first: counts and the top-level keys REA returned, + * never the whole document. A shape this row does not recognise is reported as + * keys rather than guessed at. + */ +export function summarize(payload, { maxKeys = 24 } = {}) { + if (payload === null || payload === undefined) return ['(no JSON payload)'] + if (Array.isArray(payload)) return ['array of ' + payload.length + ' item(s)'] + if (typeof payload !== 'object') return ['scalar: ' + JSON.stringify(payload)] + const lines = [] + const keys = Object.keys(payload) + for (const key of keys.slice(0, maxKeys)) { + const value = payload[key] + if (Array.isArray(value)) lines.push(' ' + key + ': ' + value.length + ' item(s)') + else if (value !== null && typeof value === 'object') lines.push(' ' + key + ': {' + Object.keys(value).slice(0, 8).join(', ') + '}') + else lines.push(' ' + key + ': ' + JSON.stringify(value)) + } + if (keys.length > maxKeys) lines.push(' ... ' + (keys.length - maxKeys) + ' more top-level key(s)') + return lines +} + +/** A bounded slice of a stored report, by 1-based line range. */ +export function sliceReport(raw, { offset = 1, limit = 120 } = {}) { + const lines = String(raw).split('\n') + const start = Math.max(1, Math.min(lines.length || 1, Math.floor(offset))) + const count = Math.max(1, Math.min(2_000, Math.floor(limit))) + const slice = lines.slice(start - 1, start - 1 + count) + return { + text: slice.join('\n'), + start, + end: start + slice.length - 1, + total: lines.length, + } +} diff --git a/packages/dsh-rea/lib/tools.js b/packages/dsh-rea/lib/tools.js new file mode 100644 index 0000000..42bbe79 --- /dev/null +++ b/packages/dsh-rea/lib/tools.js @@ -0,0 +1,468 @@ +/** + * dsh-rea - the five tools. + * + * The surface is small on purpose. REA itself has dozens of MCP tools; what a + * conversation needs is the shape of a proper investigation: + * + * rea_status what is installed, which commands THIS REA offers, what a + * native provider needs (and never installs anything); + * rea_inspect one target -> one stored investigation (REA's --json); + * rea_read a bounded slice of a stored investigation (the report can be + * megabytes, so the model walks it instead of swallowing it); + * rea_snapshot list / export / import an investigation, so a finding is + * reproducible on another machine; + * rea_report a Markdown evidence report in the workspace - the artefact a + * person keeps after the conversation ends. + * + * Every failure is a sentence, not a stack: a missing binary, a target outside + * the scope, a JSON answer REA did not print. + */ + +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' + +import { + DEFAULT_TIMEOUT_MS, + MAX_TIMEOUT_MS, + assertTargetAllowed, + buildInspectArgs, + investigationDir, + listInvestigations, + newInvestigationId, + parseReaJson, + readInvestigation, + resolveRea, + runRea, + sliceReport, + storeInvestigation, + summarize, +} from './rea.js' + +/** The output shape every tool here returns. */ +const OUTPUT = { + schema: { + type: 'object', + properties: { text: { type: 'string' }, view: { type: 'object' } }, + required: ['text', 'view'], + }, + render: (_args, value) => [{ type: 'text', text: value.text }], + presentationMeta: (_args, value) => value.view, +} + +/** How much of a help text or an error is echoed. */ +const ANSWER_CHARS = 16_000 + +/** Cut a string for the answer, saying that it was cut. */ +function clip(text, max = ANSWER_CHARS) { + const value = String(text === undefined || value === null ? '' : text) + if (value.length <= max) return value + return value.slice(0, max) + '\n\u2026 [' + (value.length - max) + ' more characters; the answer is cut]' +} + +/** The session id one call belongs to. */ +function sessionOf(exec) { + const session = exec && exec.agent ? exec.agent.session : undefined + return session && typeof session.id === 'string' ? session.id : '' +} + +/** The workspace folder for a session, or '' when the host cannot name one. */ +function workspaceOf(ctx, exec, sessionId) { + const header = exec && exec.agent && exec.agent.session ? exec.agent.session.header : undefined + if (header && typeof header.cwd === 'string' && header.cwd !== '') return header.cwd + try { + const sessions = typeof ctx.get === 'function' ? ctx.get('sessions') : undefined + const live = sessions && typeof sessions.get === 'function' && sessionId !== '' ? sessions.get(sessionId) : undefined + const cwd = live && live.header ? live.header.cwd : undefined + if (typeof cwd === 'string' && cwd !== '') return cwd + } catch { + // fall through + } + return '' +} + +/** A refusal in the shape every tool returns. */ +function refuse(text, view = {}) { + return { text, view: { ok: false, ...view } } +} + +/** Build the tools. @param deps - `{ ctx, env, platform, log }` from the row. */ +export function buildTools(deps) { + const env = deps.env ?? process.env + const platform = deps.platform ?? process.platform + + /** `rea_status`: what exists here, and what it can do. */ + const status = { + name: 'rea_status', + description: [ + 'Report whether REA is installed on this machine, which version, and - with `help` - the command names THIS installation actually offers.', + 'Call this BEFORE `rea_inspect`: REA\'s command set is the source of truth (the javascript command is `analyze-javascript-application`, native analysis has its own names, and they have changed between lines). `rea_inspect` refuses a command it has not seen here.', + 'It never installs anything. If REA is missing it names the install command (`npm install --global rea-agents`, or `npx rea-agents@latest setup` for an agent MCP setup) and stops.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + probe: { type: 'boolean', description: 'Run `rea --version` (a few hundred ms) instead of only resolving the binary.' }, + help: { type: 'boolean', description: 'Also run `rea --help` and return its clipped text - the command list.' }, + }, + }, + output: OUTPUT, + presentCall: () => ({ card: 'generic', title: 'REA status', kind: 'other' }), + presentResult: (_args, result) => ({ card: 'generic', title: 'REA status', content: result && result.text ? result.text : '' }), + async execute(args) { + const found = resolveRea(env, platform) + if (found.command === '') { + return refuse( + [ + 'REA is not installed (no `rea` on PATH' + (env.DSH_REA_CLI ? ', and DSH_REA_CLI does not point at a file' : '') + ').', + 'Install it with `npm install --global rea-agents`, or run `npx rea-agents@latest setup` to register it with an agent, then restart the harness.', + 'This row installs nothing itself: REA is your program, not an engine this package ships.', + ].join('\n'), + { found: false }, + ) + } + const lines = ['REA: ' + found.command + ' (' + found.source + ')'] + let version = '' + if (args.probe === true || args.help === true) { + const probe = await runRea(found.command, ['--version'], { env, timeoutMs: 20_000 }) + version = (probe.stdout || probe.stderr).trim().split('\n')[0] ?? '' + lines.push('version: ' + (version === '' ? '(no answer)' : version)) + } + if (args.help === true) { + const help = await runRea(found.command, ['--help'], { env, timeoutMs: 30_000 }) + lines.push('', '--- rea --help ---', clip(help.stdout || help.stderr, 8_000)) + } + lines.push( + '', + 'Native analysis needs a provider you already own (Hopper, Ghidra, IDA or Kuna); static JavaScript and .NET inspection need none.', + 'The target scope is the session workspace or an `allowRoot` given per call; a URL needs allowUrl:true.', + ) + return { text: lines.join('\n'), view: { ok: true, found: true, command: found.command, source: found.source, version } } + }, + } + + /** `rea_inspect`: one target, one stored investigation. */ + const inspect = { + name: 'rea_inspect', + description: [ + 'Run ONE REA analysis command against ONE target and store the result as an investigation.', + 'The target must be inside the session workspace, or inside a folder the user allowed for this call (`allowRoot`). A URL needs `allowUrl:true` - this row starts no network egress on its own.', + '`command` defaults to `analyze-javascript-application`; for anything else, call `rea_status` with help:true first and use a name that listing printed. The answer is a summary plus an investigation id; `rea_read` walks the rest.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + required: ['target'], + properties: { + target: { type: 'string', description: 'An absolute path (or a workspace-relative one) to an app folder, an .asar, a binary, or an http(s) URL with allowUrl:true.' }, + command: { type: 'string', description: 'A REA command name, e.g. analyze-javascript-application. Defaults to that one.' }, + provider: { type: 'string', description: 'A native-analysis provider name for REA (`--provider`), when the command takes one.' }, + json: { type: 'boolean', description: 'Ask REA for --json (default true). Without it the raw text is stored as a .txt-like report and summarised as text.' }, + allowRoot: { type: 'string', description: 'A folder the user authorised for THIS call, used when the target is outside the session workspace.' }, + allowUrl: { type: 'boolean', description: 'Allow an http(s) target. Default false: the row does not reach the network unasked.' }, + timeoutMs: { type: 'number', description: 'Deadline for the analysis. Default ' + DEFAULT_TIMEOUT_MS + ', at most ' + MAX_TIMEOUT_MS + '.' }, + }, + }, + output: OUTPUT, + presentCall: (args) => ({ card: 'generic', title: 'Inspect with REA', kind: 'other', summary: String(args && args.target ? args.target : '') }), + presentResult: (_args, result) => ({ card: 'generic', title: 'REA investigation', content: result && result.text ? result.text : '' }), + async execute(args, exec) { + const found = resolveRea(env, platform) + if (found.command === '') return refuse('REA is not installed. Call `rea_status` for the install command.') + const command = typeof args.command === 'string' && args.command !== '' ? args.command : 'analyze-javascript-application' + const json = args.json !== false + const sessionId = sessionOf(exec) + const workspace = workspaceOf(deps.ctx, exec, sessionId) + let target + try { + target = assertTargetAllowed({ + target: args.target, + workspace, + allowRoot: args.allowRoot, + allowUrl: args.allowUrl === true, + platform, + }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + let argv + try { + argv = buildInspectArgs({ command, target, json, provider: args.provider }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + const timeoutMs = typeof args.timeoutMs === 'number' ? args.timeoutMs : DEFAULT_TIMEOUT_MS + const run = await runRea(found.command, argv, { env, cwd: workspace || undefined, timeoutMs }) + if (run.timedOut) { + return refuse('REA did not finish within ' + timeoutMs + ' ms and was killed. Narrow the target or raise timeoutMs (max ' + MAX_TIMEOUT_MS + ').') + } + if (run.code !== 0) { + return refuse( + [ + 'REA exited with code ' + run.code + '.', + clip(run.stderr || run.stdout, 4_000), + 'If the command name is wrong, `rea_status` with help:true prints the names this installation knows.', + ].join('\n'), + { exitCode: run.code }, + ) + } + const parsed = json ? parseReaJson(run.stdout) : { ok: false, error: 'text mode' } + const id = newInvestigationId(target) + let stored + try { + stored = storeInvestigation({ + id, + target, + command, + provider: args.provider, + payload: parsed.ok ? parsed.value : undefined, + text: parsed.ok ? undefined : run.stdout, + code: run.code, + env, + }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + const lines = [ + 'investigation ' + id, + 'target: ' + target, + 'command: ' + command + (args.provider ? ' (provider ' + args.provider + ')' : ''), + 'stored: ' + stored.dir + ' (' + stored.bytes + ' bytes)', + '', + ] + if (parsed.ok) { + lines.push('top-level shape:') + lines.push(...summarize(parsed.value)) + } else { + lines.push('REA did not print a JSON object (' + parsed.error + '); the raw output is stored and summarised below:') + lines.push('', clip(run.stdout, 6_000)) + } + lines.push('', 'Use `rea_read` with this id to walk the report, and `rea_report` to write the evidence into the workspace.') + return { + text: lines.join('\n'), + view: { ok: true, id, target, command, bytes: stored.bytes, json: parsed.ok }, + } + }, + } + + /** `rea_read`: a bounded slice of a stored investigation. */ + const read = { + name: 'rea_read', + description: [ + 'Read a stored investigation: `summary` lists what it is and its top-level shape; `raw` returns a 1-based line range of the stored report.', + 'Use `raw` with offset/limit to walk a large report without loading it whole. The byte ceiling and the total line count are reported with every slice.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + required: ['id'], + properties: { + id: { type: 'string', description: 'An investigation id, as `rea_inspect` returned it.' }, + section: { type: 'string', enum: ['summary', 'raw'], description: 'summary (default) or raw.' }, + offset: { type: 'number', description: 'For raw: the first line, 1-based. Default 1.' }, + limit: { type: 'number', description: 'For raw: how many lines. Default 120, at most 2000.' }, + }, + }, + output: OUTPUT, + presentCall: (args) => ({ card: 'generic', title: 'Read an investigation', kind: 'other', summary: String(args && args.id ? args.id : '') }), + presentResult: (_args, result) => ({ card: 'generic', title: 'Investigation', content: result && result.text ? result.text : '' }), + async execute(args) { + const id = typeof args.id === 'string' ? args.id : '' + if (id === '') return refuse('`id` is required; `rea_snapshot` with action:list prints the ids that exist.') + let stored + try { + stored = readInvestigation(id, env) + } catch { + return refuse('No stored investigation "' + id + '". `rea_snapshot` with action:list prints the ids that exist.') + } + const section = args.section === 'raw' ? 'raw' : 'summary' + if (section === 'summary') { + const lines = [ + 'investigation ' + stored.meta.id, + 'target: ' + stored.meta.target, + 'command: ' + stored.meta.command, + 'created: ' + stored.meta.created, + 'bytes: ' + stored.meta.bytes, + '', + ] + const parsed = parseReaJson(stored.raw) + if (parsed.ok) lines.push('top-level shape:', ...summarize(parsed.value)) + else lines.push('the report is not JSON; read it with section:raw.') + return { text: lines.join('\n'), view: { ok: true, id, section } } + } + const slice = sliceReport(stored.raw, { offset: args.offset, limit: args.limit }) + return { + text: 'investigation ' + id + ' lines ' + slice.start + '-' + slice.end + ' of ' + slice.total + '\n\n' + slice.text, + view: { ok: true, id, section, start: slice.start, end: slice.end, total: slice.total }, + } + }, + } + + /** `rea_snapshot`: list, export, import. */ + const snapshot = { + name: 'rea_snapshot', + description: [ + 'Make an investigation portable: `list` (ids, targets, dates), `export` (write one investigation as a single JSON bundle into the workspace) or `import` (store a bundle from the workspace under a new id).', + 'Use it when a finding has to survive another machine, or when the same target is inspected twice and the two reports are compared.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + required: ['action'], + properties: { + action: { type: 'string', enum: ['list', 'export', 'import'] }, + id: { type: 'string', description: 'For export: the investigation id. For import: the id to store it under (default: from the bundle).' }, + path: { type: 'string', description: 'For export: the bundle path (workspace-relative, default rea/.json). For import: the bundle to read.' }, + allowRoot: { type: 'string', description: 'For import: a folder authorised for this call when the bundle is outside the workspace.' }, + }, + }, + output: OUTPUT, + presentCall: (args) => ({ card: 'generic', title: 'REA snapshots', kind: 'other', summary: String(args && args.action ? args.action : 'list') }), + presentResult: (_args, result) => ({ card: 'generic', title: 'Investigations', content: result && result.text ? result.text : '' }), + async execute(args, exec) { + const action = args.action + if (action === 'list') { + const rows = listInvestigations(env) + if (rows.length === 0) return { text: 'No investigations stored yet. `rea_inspect` creates one.', view: { ok: true, count: 0 } } + const lines = rows.map((row) => row.id + ' ' + row.created + ' ' + row.command + ' ' + row.target) + return { text: lines.join('\n'), view: { ok: true, count: rows.length } } + } + const sessionId = sessionOf(exec) + const workspace = workspaceOf(deps.ctx, exec, sessionId) + if (action === 'export') { + const id = typeof args.id === 'string' ? args.id : '' + if (id === '') return refuse('`id` is required for export.') + let stored + try { + stored = readInvestigation(id, env) + } catch { + return refuse('No stored investigation "' + id + '".') + } + if (!workspace) return refuse('No session workspace is known, so there is nowhere allowed to write the bundle.') + const wanted = typeof args.path === 'string' && args.path !== '' ? args.path : path.join('rea', id + '.json') + let out + try { + out = assertTargetAllowed({ target: path.resolve(workspace, wanted), workspace, platform }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + const bundle = { format: 'dsh-rea/snapshot@1', meta: stored.meta, report: parseReaJson(stored.raw) } + mkdirSync(path.dirname(out), { recursive: true }) + writeFileSync(out, JSON.stringify(bundle, null, 2), 'utf8') + return { text: 'exported ' + id + ' -> ' + out, view: { ok: true, id, path: out } } + } + if (action === 'import') { + const value = typeof args.path === 'string' ? args.path : '' + if (value === '') return refuse('`path` is required for import.') + if (!workspace) return refuse('No session workspace is known, so no bundle can be scoped.') + let file + try { + file = assertTargetAllowed({ target: path.resolve(workspace, value), workspace, allowRoot: args.allowRoot, platform }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + if (!existsSync(file)) return refuse('No such bundle: ' + file) + let bundle + try { + bundle = JSON.parse(readFileSync(file, 'utf8')) + } catch (error) { + return refuse('That file is not a JSON bundle: ' + String(error && error.message ? error.message : error)) + } + if (!bundle || bundle.format !== 'dsh-rea/snapshot@1' || !bundle.report) { + return refuse('Not a dsh-rea snapshot bundle (format ' + JSON.stringify(bundle && bundle.format) + ').') + } + const id = typeof args.id === 'string' && args.id !== '' ? args.id : bundle.meta && bundle.meta.id ? bundle.meta.id : newInvestigationId(file) + try { + const stored = storeInvestigation({ + id, + target: bundle.meta ? bundle.meta.target : '', + command: bundle.meta ? bundle.meta.command : '', + payload: bundle.report.ok ? bundle.report.value : undefined, + text: bundle.report.ok ? undefined : String(bundle.report), + env, + }) + return { text: 'imported ' + id + ' (' + stored.bytes + ' bytes) from ' + file, view: { ok: true, id, path: file } } + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + } + return refuse('Unknown action ' + JSON.stringify(action) + '; use list, export or import.') + }, + } + + /** `rea_report`: the artefact a person keeps. */ + const report = { + name: 'rea_report', + description: [ + 'Write a Markdown evidence report for one stored investigation into the workspace (default `rea/.md`).', + 'The report holds the question, the target, what REA reported at the top level, the investigation id it came from, and the limits of the finding - so a reader can re-run the investigation instead of trusting the prose.', + 'Pass `question` with the user\'s own words: the report is much less useful without the question it answers.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + required: ['id'], + properties: { + id: { type: 'string', description: 'The investigation id.' }, + question: { type: 'string', description: 'The question this investigation answers, in the user\'s words.' }, + path: { type: 'string', description: 'Workspace-relative report path. Default rea/.md.' }, + allowRoot: { type: 'string', description: 'A folder authorised for this call when the report belongs outside the workspace.' }, + }, + }, + output: OUTPUT, + presentCall: (args) => ({ card: 'generic', title: 'REA report', kind: 'other', summary: String(args && args.id ? args.id : '') }), + presentResult: (_args, result) => ({ card: 'generic', title: 'Evidence report', content: result && result.text ? result.text : '' }), + async execute(args, exec) { + const id = typeof args.id === 'string' ? args.id : '' + if (id === '') return refuse('`id` is required.') + let stored + try { + stored = readInvestigation(id, env) + } catch { + return refuse('No stored investigation "' + id + '".') + } + const sessionId = sessionOf(exec) + const workspace = workspaceOf(deps.ctx, exec, sessionId) + if (!workspace) return refuse('No session workspace is known, so the report has nowhere allowed to go.') + const wanted = typeof args.path === 'string' && args.path !== '' ? args.path : path.join('rea', id + '.md') + let out + try { + out = assertTargetAllowed({ target: path.resolve(workspace, wanted), workspace, allowRoot: args.allowRoot, platform }) + } catch (error) { + return refuse(String(error && error.message ? error.message : error)) + } + const parsed = parseReaJson(stored.raw) + const lines = [ + '# Reverse-engineering report', + '', + 'Question: ' + (typeof args.question === 'string' && args.question !== '' ? args.question : '(not recorded)'), + '', + 'Target: `' + stored.meta.target + '`', + 'Investigation: `' + id + '` \\u00b7 command `' + stored.meta.command + '`', + 'Created: ' + stored.meta.created, + '', + '## What the tool reported (top level)', + '', + '```text', + ...(parsed.ok ? summarize(parsed.value) : ['(the stored report is not JSON; read it with rea_read, section:raw)']), + '```', + '', + '## Evidence', + '', + '- The report is stored verbatim at the investigation directory above; `rea_read` with section:raw returns it line by line.', + '- `rea_snapshot` action:export writes it as one JSON bundle, so this finding can be re-opened elsewhere.', + '- Nothing in this report is a claim about the target beyond what REA returned: a decompiler prints pseudocode, and a static pass sees code, not behaviour.', + '', + '## Limits', + '', + '- Authorised targets only: software you own or are allowed to examine.', + '- A native finding depends on the provider that produced it (Hopper, Ghidra, IDA, Kuna); name it when the finding leaves this machine.', + ] + mkdirSync(path.dirname(out), { recursive: true }) + writeFileSync(out, lines.join('\n') + '\n', 'utf8') + return { text: 'wrote ' + out + '\n\n' + clip(lines.join('\n'), 3_000), view: { ok: true, id, path: out } } + }, + } + + return [status, inspect, read, snapshot, report] +} diff --git a/packages/dsh-rea/package.json b/packages/dsh-rea/package.json new file mode 100644 index 0000000..16c5c81 --- /dev/null +++ b/packages/dsh-rea/package.json @@ -0,0 +1,29 @@ +{ + "name": "dsh-rea", + "version": "0.1.0-alpha.1", + "description": "Reverse engineering as a surface: five `rea_*` tools over the user's own REA installation (morluto/rea, MIT) - `rea_status` (what is installed, which commands this REA actually offers, which native providers it can reach), `rea_inspect` (one target -> REA's `--json`, stored as an investigation), `rea_read` (a bounded slice of a stored investigation), `rea_snapshot` (list/export/import an investigation so it is reproducible) and `rea_report` (a Markdown evidence report in the workspace). Host-only, argv-only, target-scoped to the session workspace or an explicitly allowed root. Zero npm dependencies, no engine bundled, no network egress of its own.", + "type": "module", + "main": "lib/index.js", + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "files": [ + "lib", + "skills", + "checks", + "cordis.patch.yml" + ], + "scripts": { + "check": "node checks/check-rea.mjs" + }, + "engines": { + "node": ">=22" + }, + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "license": "AGPL-3.0-only" +} diff --git a/packages/dsh-rea/skills/rea-ethics/SKILL.md b/packages/dsh-rea/skills/rea-ethics/SKILL.md new file mode 100644 index 0000000..cf95149 --- /dev/null +++ b/packages/dsh-rea/skills/rea-ethics/SKILL.md @@ -0,0 +1,60 @@ +--- +name: rea-ethics +description: The boundary around reverse engineering with an agent - analyse only software you own or are authorised to examine, keep commercial decompiler licences in their terms, do not bypass protections or share keys, keep findings about behaviour rather than copying assets, and say what you did not do. Also what to do when the request is for something on the wrong side of that line. +whenToUse: Use at the start of any investigation whose target is not clearly the user's own software, before quoting a decompiler's output in something that ships, before touching a licence check or an anti-tamper path, and when a user asks for a feature "exactly like" a commercial product. +--- + +# The line, and how to stay on it + +REA itself is MIT. The thing you point it at is not covered by that licence, and +the decompiler is a commercial product with its own terms. Three separate +permissions are in play, and an investigation needs all three. + +## The three permissions + +1. **The target.** Software you own, or are authorised to examine. Interoperability, + security research on your own systems, education, preservation and analysis of + your own files are the ordinary cases. Somebody else's machine, a rented app + you are not licensed to inspect, or a target the user cannot name as theirs is + not. +2. **The tool.** Hopper, IDA, JEB and Hex-Rays are licensed per user; a trial has + its own restrictions on automation and output sharing. Having REA installed + does not grant a decompiler licence, and a cracked copy is not a shortcut - + it is a different problem. +3. **The output.** A recovered rule is a fact about behaviour. The artwork, + icons, fonts, strings and code you read are still somebody's copyrighted work. + Rebuilding the RULE is the point; copying the ASSETS into a product is not. + +## What this looks like in practice + +- **Ask whose software it is** when the target is not obviously the user's. One + sentence, before the first `rea_inspect`, not after. +- **Refuse the anti-tamper path.** A request to find and disable a licence check, + a DRM, an integrity check or a telemetry block is not an investigation of + behaviour; it is a request to break a protection. Say what you will not do and + offer the legitimate alternative (a plugin API, an export, the vendor's own + automation hook). +- **Do not exfiltrate.** REA analyses locally. Do not upload a target, a + decompiler dump or a credential to anywhere, and do not paste a report that + contains a key, a token or personal data into a commit. +- **Keep the provenance.** The report names the target, the build, the provider + and the date. A finding that cannot say what it was derived from is also a + finding nobody can retract. + +## When the answer is no + +State the line, then offer the nearest legitimate thing: + +| Request | Answer | +|---|---| +| "make my app behave like " | analyse the behaviour the user can observe, rebuild the RULE, do not lift assets | +| "find the licence check and remove it" | no; offer the vendor's plugin/export/automation API instead | +| "inspect this app for me" (not theirs) | ask for authorisation; without it, no | +| "share the decompiler dump with the team" | share the report and the investigation id, not the vendor's output en masse | + +## Saying what you did not do + +The report's Limits section is part of the artefact, not a disclaimer to hide: +which provider, which build, which claims are readings rather than observations, +and anything you declined to do. A professional reverse-engineering note is +useful precisely because it is bounded. diff --git a/packages/dsh-rea/skills/rea-investigate/SKILL.md b/packages/dsh-rea/skills/rea-investigate/SKILL.md new file mode 100644 index 0000000..8c13456 --- /dev/null +++ b/packages/dsh-rea/skills/rea-investigate/SKILL.md @@ -0,0 +1,71 @@ +--- +name: rea-investigate +description: Run one reverse-engineering investigation with the rea_* tools - scope the target, ask ONE question, let REA answer it, read the evidence as slices, then explain or rebuild. Covers the tool order (rea_status, rea_inspect, rea_read, rea_report), what a target may be, what an investigation id is for, and the difference between what REA returns (code, pseudocode, references) and what you may claim (behaviour you verified). +whenToUse: Use when the user asks how a program, app, game or website does something, when they want a feature from another product rebuilt, when a binary or an .asar has to be understood without its source, or when a previous investigation has to be reopened or handed to somebody else. +--- + +# Investigating something with REA + +REA is a program on the user's machine that inspects other programs: native +binaries, JavaScript and Electron apps, .NET assemblies, websites, and recorded +runtime traffic. It returns code, pseudocode, references and the limits of what +it could see. This skill is the loop around it. + +## The order, and why it is that order + +1. **`rea_status` first, with `help:true`.** REA's command names are not + stable across its releases. The listing `rea_status` returns is the only + source of truth for the installation in front of you; `rea_inspect` refuses a + command it has not seen. Do not guess `analyze-native-binary` - read it. +2. **One question, one target.** "Why does the dinosaur speed up?" is a target + (the game's script) and a question (the speed rule). "Tell me about this app" + is neither, and produces a report nobody can check. +3. **`rea_inspect`** with the narrowest target that can answer the question: one + file, one module, one function's caller, not the whole install directory. + The answer is a summary and an investigation id. +4. **`rea_read`** the stored investigation in slices. The report is often + megabytes; `section:raw` with `offset`/`limit` is how you walk it. Read the + part the question is about, not the whole document. +5. **`rea_report`** with the user's own question, so the finding leaves a + Markdown file that names its evidence and its limits. + +## Scope, before anything runs + +A local target must be inside the session workspace. Anything else is refused by +name unless the user authorised a folder for that call: pass `allowRoot` with +the folder they named. A URL is refused unless `allowUrl:true` - this row starts +no network egress of its own, and a page is the user's target, not yours. + +Never widen the scope to "make it work". If the target is outside the workspace, +ask for the folder and pass it. + +## Evidence, not vibes + +REA returns artefacts. When you write the answer: + +- quote the recovered code or the decompiler's output, and say which + investigation it came from (`rea_read`, id, line range); +- separate **what the tool showed** from **what you inferred**. "The handler + compares the operator against 0x5c and 0x5b" is evidence. "So the % key means + 10% of the first number" is your reading of it - say so, and say what would + falsify it; +- if you rebuilt the behaviour, run the rebuild against the original's + observations (see `rea-rebuild`); +- state the provider: a native finding from Hopper, Ghidra, IDA or Kuna is not + the same evidence as a static JavaScript pass. + +## What to do when REA says no + +| Answer | What it means | +|---|---| +| `rea_status` finds nothing | REA is not installed. Name the install command (`npm install --global rea-agents`) and stop; do not install it for the user. | +| a target is refused | it is outside the workspace (pass `allowRoot`) or a URL (pass `allowUrl` only if the user asked for that page) | +| REA exits non-zero | the command name or the target kind is wrong; re-read `rea_status` help, and the stderr names the reason | +| the JSON is empty or not JSON | the report is still stored; `rea_read` `section:raw` shows what it printed | +| the analysis times out | narrow the target or raise `timeoutMs` (the ceiling is 10 minutes) | + +## Handing it over + +`rea_report` writes the Markdown; `rea_snapshot` action:export writes one JSON +bundle. A report that cannot be re-run is an anecdote, so the report names the +command, the target, the provider and the investigation id. diff --git a/packages/dsh-rea/skills/rea-javascript/SKILL.md b/packages/dsh-rea/skills/rea-javascript/SKILL.md new file mode 100644 index 0000000..e8d7737 --- /dev/null +++ b/packages/dsh-rea/skills/rea-javascript/SKILL.md @@ -0,0 +1,59 @@ +--- +name: rea-javascript +description: Inspecting JavaScript, Electron and website targets through REA - an app directory or .asar, the renderer/preload/main boundary, source maps and bundled modules, and how to attach to a RUNNING page instead of reading it statically. Covers when static is enough, when runtime observation is the only honest answer, and what the recovered modules do not tell you. +whenToUse: Use when the target is an Electron app, a packaged JavaScript desktop app, a .asar archive, a website or a minified script bundle, when a static read cannot answer a question about runtime behaviour, or when a recovered module has to be mapped back to the source the user sees in devtools. +--- + +# JavaScript and Electron targets + +Static JavaScript analysis needs no native provider: the code is right there, +minified and bundled, and REA recovers modules, imports and the Electron +boundary between renderer, preload and main. That is often enough. It is not +enough for anything that depends on runtime values. + +## Before you start + +- An **app directory** is better than an `.asar`: REA reads the archive, but the + app may load unpacked files beside it (`app.asar.unpacked`, sidecar binaries, + native modules). Inspect the directory that contains both. +- The **entry points** are named in the app's `package.json` (`main`, + `renderer`, preload scripts). Start there instead of grepping 40 MB of bundle. +- A **website** is a different target: the served page plus its scripts. If the + question is about a computed value, the static read of the script is not the + answer - the running page is. + +## The three boundaries that explain most Electron bugs + +1. **renderer -> preload**: `contextBridge.exposeInMainWorld` defines exactly + what the page may call. If a method is missing there, the page cannot use it. +2. **preload -> main**: `ipcRenderer.invoke/send` names a channel; the main + process has a handler for that channel. A channel with no handler fails at + runtime, not at build time. +3. **main -> OS**: the actual file, clipboard, shell, notification call. That is + where behaviour leaves the app, and where a question about "how does it + copy X" is answered. + +Read the preload for the exposed surface, then the main handler for the +behaviour, then the renderer for what the user triggers. Quote the channel name +and the handler - that pair is the evidence. + +## Static versus observed + +| Question | Static read answers it? | +|---|---| +| which module owns this command | yes | +| what the default setting is | yes (the literal) | +| why this value came out at runtime | no - observe the running target | +| why it only happens on one OS | no - the branch depends on the runtime | + +If you need the running target, say so and ask the user for the local debugging +endpoint; the tool refuses a URL without `allowUrl:true`, and that opt-in is a +decision the user makes, not you. + +## Minified code is still code + +`a.b(c)` in a bundle is not anonymous: the module table, the imports at the top +of the chunk and the source map (when shipped) recover the names. When no source +map ships, name the recovered module by its path and the function by its line +range, and keep the identifier as it appears. Do not invent a name and then +quote it as if the code had one. diff --git a/packages/dsh-rea/skills/rea-native/SKILL.md b/packages/dsh-rea/skills/rea-native/SKILL.md new file mode 100644 index 0000000..f4f1916 --- /dev/null +++ b/packages/dsh-rea/skills/rea-native/SKILL.md @@ -0,0 +1,63 @@ +--- +name: rea-native +description: Native-binary analysis through REA - which provider (Hopper, Ghidra, IDA, Kuna) can open which format, what a decompiler's pseudocode is and is not, how to choose the function to look at, how to read a call graph against its callers, and how to state a finding so the provider and its limits travel with it. +whenToUse: Use when the target is an executable, a shared library, a .NET assembly, a firmware image or an Android package, when a previous native finding has to be checked or reproduced, or when a native provider is missing and the user needs to know which one would answer the question. +--- + +# Native analysis with REA + +A native target is a file the user owns and is authorised to examine: `.exe`, +`.dll`, `.so`, `.dylib`, an app bundle's Mach-O, a firmware image, an APK's +`.dex`. REA drives a decompiler the user already has installed, so the answer +depends on which provider is available. + +## Providers, and what each is for + +| Provider | Opens | The cost that is not in the tool | +|---|---|---| +| Hopper | Mach-O, PE, some ELF | a commercial licence; REA can install a trial with approval | +| Ghidra | almost everything, via a headless project | free, slower, needs a JRE | +| IDA / Hex-Rays | PE, ELF, Mach-O | a commercial licence and a decompiler add-on | +| Kuna | its own formats | the user's own | + +Never install a provider for the user. `rea_status` reports what REA can reach; +if nothing can open the format, say which provider would and stop. + +## The unit of work is ONE function + +"Do what this program does" is not an analysis, it is a rewrite. Start from a +behaviour the user can see - a menu item, a hotkey, a value on screen - and find +the function behind it: + +1. the strings near the behaviour (a label, a format string, an error message); +2. the references to those strings; +3. the function that owns the reference; +4. its callers, to see which input reaches it. + +Then read that function's pseudocode and its disassembly side by side. The +pseudocode is a rendering of the instructions, not the original source: it +invents variable names, it flattens inlined code, and it can be wrong about +types. When the two disagree, the instructions win. + +## What to quote + +- the address range you read (`0x180124945`-`0x180124a34`), so the reader can + find it again in the same provider and version; +- the instructions that carry the decision (the `CMP`/`JZ` pair, the constants); +- the provider and its version. A Hopper pseudocode and an IDA pseudocode of the + same function are different artefacts, and a finding is only reproducible with + the one that produced it. + +## Behaviour is a separate claim + +Static analysis shows what the code CAN do. A rule that "gives 220 for 200+10%" +is a claim about behaviour, and it needs one of: the original run observed, a +test that calls the recovered function, or the reference implementation the +vendor publishes. Say which one you have. If you have none, the claim is a +reading of the code, and it is written as one. + +## Portability + +Record the file's hash (`rea_inspect`'s target plus the report's metadata) before +quoting addresses: an updated build moves every address, and a finding without +the build it came from is unverifiable next month. diff --git a/packages/dsh-rea/skills/rea-rebuild/SKILL.md b/packages/dsh-rea/skills/rea-rebuild/SKILL.md new file mode 100644 index 0000000..cbcedd2 --- /dev/null +++ b/packages/dsh-rea/skills/rea-rebuild/SKILL.md @@ -0,0 +1,65 @@ +--- +name: rea-rebuild +description: Turn a recovered rule into working code - the second half of an investigation. Covers writing the reference behaviour down as a testable rule, choosing an implementation shape that keeps the recovered constants visible, checking the rebuild against the original's own observations, and saying exactly how far the reproduction was verified. +whenToUse: Use after rea-investigate or rea-native has produced a rule, when the user asked for a feature "like that app", when a recovered calculation has to be proved correct rather than plausible, or when a reproduction is about to be called finished. +--- + +# Rebuilding what was recovered + +A rule you can quote is not yet a rule you can ship. The gap is closed by: + +1. **writing the rule down as a function with the recovered constants named**, +2. **finding observations to check it against**, and +3. **stating the level of agreement** - exact, within a tolerance, or unverified. + +## The rule, with its numbers visible + +Keep the recovered constants as named values. A rebuild that folds `0x5c` into +`if (op === 'multiply')` is friendlier, but it hides the evidence that ties the +implementation to the finding. Name them, comment the address or the module they +came from, and keep the mapping one-to-one: + +```text +// recovered: 0x5c == IDC_MUL, 0x64 == 100 +rule.percentAfterPlus = (previous, current) => (current * previous) / 100 +rule.percentAfterMultiply = (current) => current / 100 +``` + +## Observations to check against + +In order of strength: + +1. **the original's own outputs** for a set of inputs (the strongest: it is the + behaviour itself); +2. **a vendor reference implementation** (the calculator's public source), which + is evidence about intent, not about the build; +3. **a model of the original** derived from the same instructions (weakest - it + can repeat your misreading). + +If you have only (3), say so. A reproduction checked against its own reading is +a hypothesis with a test, not a verified port. + +## Write the test before the port is declared done + +A test that only covers the happy input proves nothing about the branch you +recovered. Cover: the branch you found, the branch beside it, and the boundary +value (the constant itself, one below, one above). + +## What "done" sounds like + +- "the rebuild matches the original on 3,205 recorded cases" - a measurement; +- "the rebuild matches the published reference for + and ×" - a weaker claim, + and it names its reference; +- "the rebuild implements the rule as recovered" - honest, and says it is + unverified against the running original. + +Never upgrade the third to the first in the summary. The user can run the +original; you cannot, and the difference is the whole value of saying which one +you have. + +## Where the rewrite stops being a rewrite + +If the recovered rule depends on data you do not have (a table, a font, an +asset), the rebuild is the rule plus a note about what is missing. Do not +fabricate the missing data to make the demo work: a reproduction that silently +invents its inputs is worse than one that names the gap. diff --git a/packages/dsh-rightbar-files/lib/client.js b/packages/dsh-rightbar-files/lib/client.js index 01f3970..58bb050 100644 --- a/packages/dsh-rightbar-files/lib/client.js +++ b/packages/dsh-rightbar-files/lib/client.js @@ -1,1033 +1,10 @@ // GENERATED - do not edit by hand. // -// Byte-for-byte fork of @deepseek-ai/dsh-client-ui-sidebar-files@0.2.0-rc.2 +// Byte-for-byte fork of @deepseek-ai/dsh-client-ui-sidebar-files@0.2.2-rc.5 // (lib/client.js) with only the module-table id rewritten to "dsh-rightbar-files". // The pack's bundle layer disables the core row, so this copy is the one that // runs. Re-sync with: powershell -NoProfile -ExecutionPolicy Bypass -File scripts\sync-vendored.ps1 // -window.__ModuleLoader__.load({ - id: "dsh-rightbar-files", - factory: (require) => { - var module = { exports: {} }; - var exports = module.exports; - Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); - let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives"); - require("@deepseek-ai/cordis"); - let react_jsx_runtime = require("react/jsx-runtime"); - let react = require("react"); - let _deepseek_ai_dsh_client_store = require("@deepseek-ai/dsh-client-store"); - //#region lib/types/client/definition.js - /** The tab kind this package owns. */ - const FILES_KIND = "files"; - /** This implementation's identity in the tab system, and the key its body registers under. */ - const FILES_ID = "@deepseek-ai/dsh-client-ui-sidebar-files"; - /** - * The files type's registry definition. - * @param t - namespace-bound translate, read fresh on every label call. - * @returns the definition to register. - */ - function filesDefinition(t) { - return { - id: FILES_ID, - kind: FILES_KIND, - priority: "builtin", - title: () => t("type.label"), - guide: [{ - id: "workspace", - commandId: "workspace.files", - order: 10, - title: () => t("guide.title"), - description: () => t("guide.description"), - icon: _deepseek_ai_dsh_client_ui_primitives.GuideArtworkFiles - }] - }; - } - //#endregion - //#region ../../typert/protocol/src/remote-error.ts - /** - * One Remote call failure: a real Error carrying its stable code and typed - * details. Owners throw it at the failure point; the Host Gateway encodes it - * onto the wire unchanged; the Client face rebuilds an instance for the - * `RemoteResult` error branch, so `throw result.error` keeps throw semantics. - * Discrimination is always by `code`, never by instanceof. - */ - var RemoteError = class extends Error { - code; - details; - /** Structural marker: cross-realm/bundle identification never uses instanceof. */ - isDSHRemoteError = true; - /** - * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}. - * @param message - human diagnostic carried across the wire. - * @param details - structured payload typed by the code. - * @param options - standard Error options (`cause` survives in-process only). - */ - constructor(code, message, details, options) { - super(message, options); - this.code = code; - this.details = details; - this.name = "RemoteError"; - } - }; - //#endregion - //#region ../../typert/protocol/src/index.ts - /** - * Remote decorators and explicit Gateway bindings backed by versioned - * descriptors carried on decorated class prototypes. Strict reflection - * remains a Typert compiler responsibility. - * @module @deepseek-ai/dsh-typert-protocol - */ - //#endregion - //#region lib/types/client/directory-node.js - /** One open directory and its active child nodes; cached view preferences live in the store. */ - var DirectoryNode = class DirectoryNode { - path; - load; - watch; - failed; - restore; - /** Open direct-child directories, keyed by absolute path. */ - children = /* @__PURE__ */ new Map(); - controller = new AbortController(); - signal; - task; - reading; - dirty = false; - initialized = false; - automatic = true; - constructor(path, load, watch, failed, lifetime, restore = []) { - this.path = path; - this.load = load; - this.watch = watch; - this.failed = failed; - this.restore = restore; - this.signal = AbortSignal.any([lifetime, this.controller.signal]); - } - /** - * Start observation once; readiness triggers the initial listing. - * @returns this node. - */ - open() { - this.task ??= this.follow(); - return this; - } - /** - * Find an active node in this subtree. - * @param path - absolute directory path. - * @returns the matching node, or undefined when that directory is closed. - */ - find(path) { - if (path === this.path) return this; - for (const child of this.children.values()) { - const found = child.find(path); - if (found !== void 0) return found; - } - } - /** - * Update the expansion preferences used by pending directory listings. - * @param expanded - latest expansion preferences from the store. - */ - setExpanded(expanded) { - this.restore = expanded; - for (const child of this.children.values()) child.setExpanded(expanded); - } - /** - * Open a direct child using this node's lifetime and automatic-refresh setting. - * @param path - absolute direct-child directory path. - * @param restore - descendant expansion preferences to restore after listing. - * @returns the active child, or undefined after cancellation. - */ - expand(path, restore = []) { - if (this.signal.aborted) return void 0; - let child = this.children.get(path); - if (child === void 0) { - child = new DirectoryNode(path, this.load, this.watch, this.failed, this.signal, restore); - child.automatic = this.automatic; - this.children.set(path, child); - } - return child.open(); - } - /** - * Remove a child and its pending restoration preferences. - * @param path - absolute direct-child directory path. - * @returns once the child subtree's reads and watches have ended. - */ - async collapse(path) { - this.restore = this.restore.filter((value) => value !== path && !value.startsWith(`${path}/`)); - const child = this.children.get(path); - this.children.delete(path); - await child?.close(); - } - /** - * Control subtree rereads without ending subscriptions. - * @param enabled - refresh dirty nodes automatically. - */ - setAutomatic(enabled) { - this.automatic = enabled; - if (enabled && this.dirty) this.refresh(); - for (const child of this.children.values()) child.setAutomatic(enabled); - } - /** Queue a reread, coalescing with active work. @returns completion of the active read and its coalesced rereads. */ - refresh() { - this.dirty = true; - this.reading ??= this.read(); - return this.reading; - } - /** Refresh this node and its open descendants. @returns once their listings settle. */ - async refreshTree() { - await this.refresh(); - await Promise.all([...this.children.values()].map((child) => child.refreshTree())); - } - /** Cancel the active subtree. @returns once all owned reads and watches have ended. */ - async close() { - this.controller.abort(); - await Promise.all([ - this.task, - this.reading, - ...[...this.children.values()].map((child) => child.close()) - ]); - this.children.clear(); - } - async follow() { - try { - for await (const _event of this.watch(this.path, this.signal)) { - this.dirty = true; - if (!this.initialized || this.automatic) this.refresh(); - } - } catch (error) { - if (!this.signal.aborted) { - if (!this.initialized) await this.refresh(); - if (!(typeof error === "object" && error !== null && "code" in error && error.code === "workspace-file/watch-unsupported")) this.failed(this.path, error); - } - } - } - async read() { - const readAgain = () => this.dirty && this.automatic && !this.signal.aborted; - try { - do { - this.dirty = false; - const level = await this.load(this.path, this.signal); - if (this.signal.aborted || level === void 0) return; - this.initialized = true; - const directories = new Set(level.entries.filter((entry) => entry.type === "directory").map((entry) => `${this.path.replace(/[/\\]+$/, "")}/${entry.name}`)); - for (const path of this.children.keys()) if (!directories.has(path)) await this.collapse(path); - for (const path of directories) if (this.restore.includes(path)) this.expand(path, this.restore); - this.restore = []; - } while (readAgain()); - } finally { - this.reading = void 0; - } - } - }; - //#endregion - //#region lib/types/client/face.js - /** - * Bind directory observation to the Remote stream supervisor. - * @param remote - Client Remote with workspace file streams. - * @returns a watcher that awaits stream disposal when its node ends. - */ - function createWatch(remote) { - return async function* (sessionId, path, signal) { - const aborted = () => signal.aborted; - if (aborted()) return; - const stream = remote.$stream({ - name: `directory ${path}`, - open: (lifetime) => remote.workspaceFiles.changes(sessionId, path, lifetime), - ended: () => /* @__PURE__ */ new Error(`Directory watch ended: ${path}`) - }); - const abort = () => { - stream.dispose(); - }; - signal.addEventListener("abort", abort, { once: true }); - try { - for await (const item of stream) { - if (aborted()) return; - if (item.value.kind === "ready") item.accept(); - yield item.value.kind; - } - } finally { - signal.removeEventListener("abort", abort); - await stream.dispose(); - } - }; - } - /** - * Bind the listing to one Remote face, keeping only what the tree stores. - * @param remote - the Client Remote face carrying the `workspaceFiles` namespace. - * @returns the listing the tree's face performs. - */ - function createList(remote) { - return async (sessionId, path, signal) => { - const result = await remote.workspaceFiles.list(sessionId, path, signal); - if (!result.ok) return result; - return { - ok: true, - value: { - entries: result.value.entries, - truncated: result.value.truncated - } - }; - }; - } - /** - * The absolute path of one child entry. - * - * Joined with `/` whatever the parent's separators: the Host resolves mixed - * separators, and the tree only needs a stable key. - * @param parent - absolute path of the listed directory. - * @param name - the entry's basename. - * @returns the child's absolute path. - */ - function childPath(parent, name) { - return `${parent.replace(/[/\\]+$/, "")}/${name}`; - } - /** - * Bind the tree's face to one directory listing. - * @param list - the bound `workspaceFiles.list` call. - * @param watch - target-scoped directory observation. - * @returns the Slot `inject` factory: session and bound actions in, face out. - */ - function filesFace(list, watch) { - return (sessionId, actions) => { - /** Per tab, per absolute path: the listing generation a settlement must match; the latest request wins. */ - const generations = /* @__PURE__ */ new Map(); - const roots = /* @__PURE__ */ new Map(); - const nextGeneration = (tabId, path) => { - const byPath = generations.get(tabId) ?? /* @__PURE__ */ new Map(); - generations.set(tabId, byPath); - const generation = (byPath.get(path) ?? 0) + 1; - byPath.set(path, generation); - return generation; - }; - const load = async (tabId, path, signal) => { - if (signal.aborted) return; - const generation = nextGeneration(tabId, path); - actions.loading(tabId, path); - return list(sessionId, path, signal).then((result) => { - if (signal.aborted || generations.get(tabId)?.get(path) !== generation) return; - if (result.ok) actions.loaded(tabId, path, result.value); - else actions.failed(tabId, path, result.error); - return result.ok ? result.value : void 0; - }); - }; - return { - refresh: (tabId) => { - roots.get(tabId)?.refreshTree(); - }, - setAutoRefresh: (tabId, enabled) => { - actions.autoRefresh(tabId, enabled); - roots.get(tabId)?.setAutomatic(enabled); - }, - start(tabId, root, signal) { - actions.start(tabId, root); - signal.addEventListener("abort", () => { - roots.get(tabId)?.close(); - roots.delete(tabId); - generations.delete(tabId); - actions.forget(tabId); - }, { once: true }); - roots.set(tabId, new DirectoryNode(root, (path, lifetime) => load(tabId, path, lifetime), (path, lifetime) => watch(sessionId, path, lifetime), (path, error) => { - if (!signal.aborted) actions.failed(tabId, path, new RemoteError("gateway/internal", error instanceof Error ? error.message : String(error), {})); - }, signal).open()); - }, - load: (tabId, path, signal) => { - load(tabId, path, signal); - }, - toggle(tabId, parentPath, path, expanded, signal) { - if (signal.aborted) return; - const root = roots.get(tabId); - if (root === void 0) return; - const parent = root.find(parentPath); - if (parent === void 0 && !expanded.includes(parentPath)) return; - const collapsing = expanded.includes(path); - const next = collapsing ? expanded.filter((value) => value !== path) : [...expanded, path]; - root.setExpanded(next); - if (collapsing) parent?.collapse(path); - else parent?.expand(path, next); - actions.toggled(tabId, path); - } - }; - }; - } - //#endregion - //#region ../../../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs - function r(e) { - var t, f, n = ""; - if ("string" == typeof e || "number" == typeof e) n += e; - else if ("object" == typeof e) if (Array.isArray(e)) { - var o = e.length; - for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f); - } else for (f in e) e[f] && (n && (n += " "), n += f); - return n; - } - function clsx() { - for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t); - return n; - } - //#endregion - //#region ../../util/workspace-path/src/file-address.ts - /** The scheme and type every file address opens with. */ - const FILE_ADDRESS_PREFIX = "dsh-resource://file/"; - /** Component-encode one id or path segment, keeping `:` literal for drive letters. */ - function encodeSegment(segment) { - return encodeURIComponent(segment).replace(/%3A/gi, ":"); - } - /** Encode a `/`-separated path segment by segment. */ - function encodePath(path) { - return path.split("/").map(encodeSegment).join("/"); - } - /** - * Build the address of a file read through one Session. - * @param sessionId - the Session whose Host workspace resolves the path. - * @param path - absolute or workspace-relative path; backslashes are normalized to `/`, and leading `./` prefixes are dropped. - * @returns the `dsh-resource://file/session//` address. - */ - function sessionFileAddress(sessionId, path) { - const normalized = path.replace(/\\/g, "/").replace(/^(?:\.\/)+/, ""); - return `${FILE_ADDRESS_PREFIX}session/${encodeSegment(sessionId)}/${encodePath(normalized)}`; - } - //#endregion - //#region ../../util/workspace-path/src/index.ts - /** - * Browser-safe Workspace path and display helpers. - * @module @deepseek-ai/dsh-util-workspace-path - */ - /** Whether a path uses a Windows drive or UNC prefix. */ - function isWindowsStylePath(value) { - return /^[A-Za-z]:[/\\]/.test(value) || value.startsWith("\\\\"); - } - /** - * Whether a path is absolute in either spelling the Host accepts: POSIX (`/a/b`) or Windows drive or UNC. - * @param path - the path to classify. - * @returns `true` for an absolute path; `false` for a Workspace-relative one. - */ - function isAbsoluteWorkspacePath(path) { - return path.startsWith("/") || isWindowsStylePath(path); - } - /** - * The address for a path as a caller holds it: a relative path, or an absolute - * path inside the Session's workspace, becomes a `session`-scoped address; an - * absolute path outside it, or one whose workspace root is unknown, keeps its - * absolute path in that Session's address. - * @param sessionId - the Session the path is read in. - * @param cwd - that Session's workspace root, when known. - * @param path - absolute or workspace-relative path, in either separator spelling. - * @returns the `dsh-resource://file/…` address. - */ - function fileAddressFor(sessionId, cwd, path) { - const normalized = path.replace(/\\/g, "/"); - if (!isAbsoluteWorkspacePath(normalized)) return sessionFileAddress(sessionId, normalized); - const root = cwd === void 0 ? "" : cwd.replace(/\\/g, "/").replace(/\/+$/, ""); - if (root !== "" && normalized === root) return sessionFileAddress(sessionId, ""); - if (root !== "" && normalized.startsWith(`${root}/`)) return sessionFileAddress(sessionId, normalized.slice(root.length + 1)); - return sessionFileAddress(sessionId, normalized); - } - //#endregion - //#region \0dsh-css:/home/runner/work/deepseek-harness/deepseek-harness/packages/client/ui-sidebar-files/src/client/FilesBody.module.css.mjs - const css = ".k-1LKG_root{height:100%;min-height:0;color:var(--dsw-alias-label-primary);font-size:var(--dsh-content-font-size-secondary,13px);flex-direction:column;flex:auto;line-height:1.5;display:flex}.k-1LKG_header{box-sizing:border-box;border-bottom:.5px solid var(--dsw-alias-border-l3);flex:none;align-items:center;gap:4px;height:38px;padding:0 6px 0 16px;display:flex}.k-1LKG_path{margin-right:12px}.k-1LKG_body{scrollbar-gutter:stable;flex:auto;min-height:0;margin-right:2px;padding:8px 0 8px 8px;overflow:auto}.k-1LKG_body::-webkit-scrollbar-track{margin:2px}.k-1LKG_level{margin:0;padding:0;list-style:none}.k-1LKG_level .k-1LKG_level{padding-left:18px}.k-1LKG_item{margin:0;padding:0}.k-1LKG_row{width:100%;min-width:0;color:inherit;font:inherit;text-align:left;border-radius:var(--dsw-radius-md);cursor:pointer;background:0 0;border:0;align-items:center;gap:6px;padding:5px 10px;display:flex}.k-1LKG_row:hover{background:var(--dsw-alias-interactive-bg-hover)}.k-1LKG_icon{color:var(--dsw-alias-label-tertiary);flex:none}.k-1LKG_fileIcon{flex:none}.k-1LKG_name{white-space:nowrap;text-overflow:ellipsis;min-width:0;overflow:hidden}.k-1LKG_other{color:var(--dsw-alias-label-tertiary);cursor:default}.k-1LKG_other:hover{background:0 0}.k-1LKG_note{color:var(--dsw-alias-label-tertiary);margin:0;padding:3px 10px;font-size:12px}.k-1LKG_status{flex-direction:column;padding:12px 10px;display:flex}.k-1LKG_statusLine{color:var(--dsw-alias-label-secondary);font-size:var(--dsh-content-font-size-secondary,13px);margin:0;line-height:1.6}.k-1LKG_tool{width:28px;height:28px;color:var(--dsw-alias-label-secondary);border-radius:var(--dsw-radius-sm);cursor:pointer;background:0 0;border:none;flex:none;justify-content:center;align-items:center;padding:6px;line-height:1;display:inline-flex}.k-1LKG_tool svg{width:15px;height:15px}.k-1LKG_tool:hover,.k-1LKG_tool[aria-pressed=true]{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}.k-1LKG_titleIcon{flex:none}"; - const tagId = "@deepseek-ai/dsh-client-ui-sidebar-files/FilesBody.module.css"; - if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) { - const tag = document.createElement("style"); - tag.dataset.plugin = "@deepseek-ai/dsh-client-ui-sidebar-files"; - tag.dataset.pluginCss = tagId; - tag.textContent = css; - document.head.appendChild(tag); - } - var FilesBody_module_css_default = { - "body": "k-1LKG_body", - "fileIcon": "k-1LKG_fileIcon", - "header": "k-1LKG_header", - "icon": "k-1LKG_icon", - "item": "k-1LKG_item", - "level": "k-1LKG_level", - "name": "k-1LKG_name", - "note": "k-1LKG_note", - "other": "k-1LKG_other", - "path": "k-1LKG_path", - "root": "k-1LKG_root", - "row": "k-1LKG_row", - "status": "k-1LKG_status", - "statusLine": "k-1LKG_statusLine", - "titleIcon": "k-1LKG_titleIcon", - "tool": "k-1LKG_tool" - }; - //#endregion - //#region lib/types/client/FilesBody.js - /** - * The file tree's body: the session's workspace root, listed one level at a time. - * - * Everything the tree keeps lives in its store, keyed by tab; everything it asks - * for goes through its injected face. The component itself only decides what to - * draw for each absolute path and what a click means: a directory toggles, a - * file opens through the owner's `tabActions` for a `file:` viewer to claim, and - * anything else is shown but refuses to open. The header uses the shared - * PathLabel for the root, followed by reload and workspace directory actions. - */ - /** Natural, case-insensitive name order, so `file2` precedes `file10`. */ - const byName = new Intl.Collator(void 0, { - numeric: true, - sensitivity: "base" - }); - /** - * Order one level's entries for display: directories first, then everything - * else, each group by name. The endpoint's order is a listing fact; this is the - * reader's. - * @param entries - the listing as the endpoint returned it. - * @returns a new array, directories first, then by name within each group. - */ - function orderEntries(entries) { - return [...entries].sort((left, right) => { - const group = Number(right.type === "directory") - Number(left.type === "directory"); - return group !== 0 ? group : byName.compare(left.name, right.name); - }); - } - /** - * Say why a directory could not be listed, in terms of the directory. - * @param t - namespace-bound translate. - * @param failure - the settled Remote failure. - * @returns the line to show under the directory. - */ - function failureLine(t, failure) { - switch (failure.code) { - case "workspace-file/not-found": return t("error.notFound"); - case "workspace-file/outside-workspace": return t("error.outsideWorkspace"); - case "workspace-file/not-directory": return t("error.notDirectory"); - default: return t("error.unavailable", { message: failure.message }); - } - } - /** One entry's row, and its children when it is an expanded directory. */ - function Entry({ parent, entry, tree }) { - const path = childPath(parent, entry.name); - if (entry.type === "directory") { - const expanded = tree.state.expanded.includes(path); - return (0, react_jsx_runtime.jsxs)("li", { - className: FilesBody_module_css_default.item, - "data-files-entry": "directory", - "data-files-path": path, - children: [(0, react_jsx_runtime.jsxs)("button", { - type: "button", - className: FilesBody_module_css_default.row, - "aria-expanded": expanded, - onClick: () => { - tree.onToggle(parent, path); - }, - children: [expanded ? (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenRegular, { className: FilesBody_module_css_default.icon }) : (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderCloseRegular, { className: FilesBody_module_css_default.icon }), (0, react_jsx_runtime.jsx)("span", { - className: FilesBody_module_css_default.name, - children: entry.name - })] - }), expanded && (0, react_jsx_runtime.jsx)("ul", { - className: FilesBody_module_css_default.level, - children: (0, react_jsx_runtime.jsx)(Level, { - path, - tree - }) - })] - }); - } - if (entry.type === "file") return (0, react_jsx_runtime.jsx)("li", { - className: FilesBody_module_css_default.item, - "data-files-entry": "file", - "data-files-path": path, - children: (0, react_jsx_runtime.jsxs)("button", { - type: "button", - className: FilesBody_module_css_default.row, - onClick: () => { - tree.onOpen(path); - }, - children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.FileTypeIcon, { - kind: (0, _deepseek_ai_dsh_client_ui_primitives.classifyFileType)(entry.name), - size: 16, - className: FilesBody_module_css_default.fileIcon - }), (0, react_jsx_runtime.jsx)("span", { - className: FilesBody_module_css_default.name, - children: entry.name - })] - }) - }); - return (0, react_jsx_runtime.jsx)("li", { - className: FilesBody_module_css_default.item, - "data-files-entry": "other", - "data-files-path": path, - children: (0, react_jsx_runtime.jsx)("span", { - className: clsx(FilesBody_module_css_default.row, FilesBody_module_css_default.other), - "aria-disabled": "true", - title: tree.t("entry.other"), - children: (0, react_jsx_runtime.jsx)("span", { - className: FilesBody_module_css_default.name, - children: entry.name - }) - }) - }); - } - /** One directory's rows: its state while listing, its entries once listed. */ - function Level({ path, tree }) { - const { state, t } = tree; - const level = state.levels[path]; - if (level === void 0 || level.kind === "loading") return (0, react_jsx_runtime.jsx)("li", { - className: FilesBody_module_css_default.note, - "data-files-row": "loading", - children: t("loading") - }); - if (level.kind === "failed") return (0, react_jsx_runtime.jsx)("li", { - className: FilesBody_module_css_default.note, - "data-files-row": "failed", - "data-files-code": level.failure.code, - children: failureLine(t, level.failure) - }); - const entries = orderEntries(level.level.entries); - return (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ - level.failure !== void 0 && (0, react_jsx_runtime.jsx)("li", { - className: FilesBody_module_css_default.note, - "data-files-row": "failed", - children: failureLine(t, level.failure) - }), - entries.length === 0 && (0, react_jsx_runtime.jsx)("li", { - className: FilesBody_module_css_default.note, - "data-files-row": "empty", - children: t("empty") - }), - entries.map((entry) => (0, react_jsx_runtime.jsx)(Entry, { - parent: path, - entry, - tree - }, entry.name)), - level.level.truncated && (0, react_jsx_runtime.jsx)("li", { - className: FilesBody_module_css_default.note, - "data-files-row": "truncated", - children: t("truncated") - }) - ] }); - } - /** The file tree's body: the workspace root and whatever the reader has opened under it. */ - function FilesBody({ useTabInfo, sessionId, useSessions, useStore, actions, start, refresh, setAutoRefresh, toggle, t, renderSlot }) { - const { tab } = useTabInfo(); - (0, react.useEffect)(() => tab.actions.bindCommands({ refresh: () => { - refresh(tab.id); - } }), [ - tab.actions, - tab.id, - refresh - ]); - const { signal, actions: tabActions } = tab; - const cwd = useSessions((sessions) => sessions.byId[sessionId]?.cwd); - const state = useStore((store) => store.byTab[tab.id]); - const bodyRef = (0, react.useRef)(null); - const scrollTopRef = (0, react.useRef)(0); - const seeded = state !== void 0; - (0, react.useLayoutEffect)(() => { - const body = bodyRef.current; - if (seeded && body !== null) { - body.scrollTop = state.scrollTop; - scrollTopRef.current = body.scrollTop; - } - }, [seeded]); - (0, react.useEffect)(() => () => { - if (seeded && !signal.aborted) actions.scrolled(tab.id, scrollTopRef.current); - }, [ - seeded, - signal, - tab.id, - actions - ]); - (0, react.useEffect)(() => { - if (state !== void 0 || cwd === void 0 || signal.aborted) return; - start(tab.id, cwd, signal); - }, [ - state, - cwd, - tab.id, - signal, - start - ]); - if (cwd === void 0) return (0, react_jsx_runtime.jsx)("div", { - className: FilesBody_module_css_default.status, - "data-files-state": "no-workspace", - children: (0, react_jsx_runtime.jsx)("p", { - className: FilesBody_module_css_default.statusLine, - children: t("noWorkspace") - }) - }); - if (state === void 0) return null; - const tree = { - state, - onToggle: (parent, path) => { - toggle(tab.id, parent, path, state.expanded, signal); - }, - onOpen: (path) => { - tabActions.openResource(fileAddressFor(sessionId, state.root, path)); - }, - t - }; - const reload = () => { - refresh(tab.id); - }; - return (0, react_jsx_runtime.jsxs)("div", { - className: FilesBody_module_css_default.root, - "data-files-state": "tree", - "data-files-root": state.root, - children: [(0, react_jsx_runtime.jsxs)("div", { - className: FilesBody_module_css_default.header, - children: [ - (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.PathLabel, { - path: state.root, - className: FilesBody_module_css_default.path, - "data-files-path": true - }), - (0, react_jsx_runtime.jsx)("span", { - hidden: true, - children: (0, react_jsx_runtime.jsx)("button", { - type: "button", - className: FilesBody_module_css_default.tool, - "aria-label": t("autoRefresh"), - "aria-pressed": state.autoRefresh, - "data-files-auto-refresh": true, - title: t(state.autoRefresh ? "autoRefresh.disable" : "autoRefresh.enable"), - onClick: () => { - setAutoRefresh(tab.id, !state.autoRefresh); - }, - children: state.autoRefresh ? (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPauseOutlineRegular, {}) : (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPlayOutlineRegular, {}) - }) - }), - (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, { - label: t("reload"), - shortcutKeys: tab.refreshShortcut?.keys, - side: "bottom", - delayMs: 500, - children: (0, react_jsx_runtime.jsx)("button", { - type: "button", - className: FilesBody_module_css_default.tool, - "aria-label": t("reload"), - "aria-keyshortcuts": tab.refreshShortcut?.aria, - "data-files-reload": true, - onClick: reload, - children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconRefreshOutlineRegular, {}) - }) - }), - renderSlot("sidebar.right.tab.files.actions", { absolutePath: state.root }) - ] - }), (0, react_jsx_runtime.jsx)("div", { - ref: bodyRef, - className: FilesBody_module_css_default.body, - "data-files-body": true, - onScroll: (event) => { - scrollTopRef.current = event.currentTarget.scrollTop; - }, - children: (0, react_jsx_runtime.jsx)("ul", { - className: FilesBody_module_css_default.level, - children: (0, react_jsx_runtime.jsx)(Level, { - path: state.root, - tree - }) - }) - })] - }); - } - //#endregion - //#region lib/types/client/FilesTitle.js - /** - * The title as the chip and a floating panel's header show it. - * @param props - the tab information hook. - * @returns the folder sheet followed by the tab's title text. - */ - function FilesTitle({ useTabInfo }) { - const { tab } = useTabInfo(); - return (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.FileTypeIcon, { - kind: "folder", - size: 16, - className: FilesBody_module_css_default.titleIcon - }), tab.title] }); - } - //#endregion - //#region lib/types/client/locales.js - /** Simplified Chinese dictionary and key-set source of truth. */ - const zh = { - "shortcut.noSession": "请先选择会话", - "type.label": "文件", - "guide.title": "工作区文件", - "guide.description": "浏览会话工作区的文件", - loading: "正在读取…", - empty: "空目录", - truncated: "条目太多,只显示了一部分。", - noWorkspace: "这个会话没有工作区目录。", - reload: "重新读取", - autoRefresh: "自动刷新", - "autoRefresh.enable": "开启自动刷新", - "autoRefresh.disable": "关闭自动刷新", - "entry.other": "这不是文件或目录,没法打开。", - "error.notFound": "这个目录不在了。可能已被移动或删除。", - "error.outsideWorkspace": "这个目录在工作区之外,侧栏不会读取它。", - "error.notDirectory": "这不是一个目录。", - "error.unavailable": "读取失败:{message}" - }; - /** English dictionary, checked against the Chinese key set. */ - const en = { - "shortcut.noSession": "Select a session first", - "type.label": "Files", - "guide.title": "Workspace files", - "guide.description": "Browse files in this session's workspace", - loading: "Reading…", - empty: "Empty directory", - truncated: "Too many entries, showing only some of them.", - noWorkspace: "This session has no workspace directory.", - reload: "Reload", - autoRefresh: "Auto refresh", - "autoRefresh.enable": "Enable auto refresh", - "autoRefresh.disable": "Disable auto refresh", - "entry.other": "Not a file or a directory, so it cannot be opened.", - "error.notFound": "That directory is gone. It may have been moved or deleted.", - "error.outsideWorkspace": "That directory is outside the workspace, so the sidebar will not read it.", - "error.notDirectory": "That is not a directory.", - "error.unavailable": "Read failed: {message}" - }; - //#endregion - //#region lib/types/client/store.js - /** - * The file tree's view state: which directories are expanded, what each - * loaded level contains, and where the body is scrolled to. - * - * The tree is not one resource. A directory listing per level, expanded lazily, - * is state the type owns — so it lives in a Slot-standard exclusive store - * (one instance per session), bucketed by tab id because two tabs of this kind - * in one session expand independently. - * - * Writers run between `start` and `forget`: the owner's `signal` is what ends a - * bucket's life, and the face stops dispatching once it aborts. - */ - /** - * One tab's bucket, which every writer after `start` relies on: the face only - * dispatches while the record's signal is live, and `forget` runs on its abort. - * @param state - the draft. - * @param tabId - the tab being written. - * @returns the tab's tree. - */ - function bucket(state, tabId) { - const tree = state.byTab[tabId]; - if (tree === void 0) throw new Error(`ui-sidebar-files: no tree for tab "${tabId}"`); - return tree; - } - /** - * Declare the file tree's store. - * - * A factory rather than a shared handle: the registration declares it as an - * exclusive store, so the framework mints one instance per session. - * @returns the store handle to declare on the registration. - */ - function createFilesStore() { - return (0, _deepseek_ai_dsh_client_store.defineStore)({ - init: () => ({ byTab: {} }), - actions: { - autoRefresh: (d, tabId, enabled) => { - bucket(d, tabId).autoRefresh = enabled; - }, - /** - * Seed one tab's tree at its workspace root, with the root expanded. - * @param d - draft state. - * @param tabId - the tab being drawn. - * @param root - absolute path of the workspace root. - */ - start: (d, tabId, root) => { - d.byTab[tabId] = { - root, - levels: {}, - expanded: [root], - scrollTop: 0, - autoRefresh: true - }; - }, - /** - * Mark one directory as being listed. - * @param d - draft state. - * @param tabId - the tab being drawn. - * @param path - absolute directory path. - */ - loading: (d, tabId, path) => { - const state = bucket(d, tabId); - if (state.levels[path]?.kind !== "ready") state.levels[path] = { kind: "loading" }; - }, - /** - * Record one directory's contents. - * @param d - draft state. - * @param tabId - the tab being drawn. - * @param path - absolute directory path. - * @param level - the listing to show under it. - */ - loaded: (d, tabId, path, level) => { - const state = bucket(d, tabId); - const previous = state.levels[path]; - if (previous?.kind === "ready") { - const directories = new Set(level.entries.filter((entry) => entry.type === "directory").map((entry) => entry.name)); - for (const entry of previous.level.entries) { - if (entry.type !== "directory" || directories.has(entry.name)) continue; - const removed = `${path.replace(/[/\\]+$/, "")}/${entry.name}`; - state.expanded = state.expanded.filter((value) => value !== removed && !value.startsWith(`${removed}/`)); - state.levels = Object.fromEntries(Object.entries(state.levels).filter(([key]) => key !== removed && !key.startsWith(`${removed}/`))); - } - } - state.levels[path] = { - kind: "ready", - level - }; - }, - /** - * Record why one directory could not be listed. - * @param d - draft state. - * @param tabId - the tab being drawn. - * @param path - absolute directory path. - * @param failure - the settled Remote failure. - */ - failed: (d, tabId, path, failure) => { - const level = bucket(d, tabId).levels[path]; - bucket(d, tabId).levels[path] = level?.kind === "ready" ? { - ...level, - failure - } : { - kind: "failed", - failure - }; - }, - /** - * Open a collapsed directory, or collapse an open one. - * - * A collapsed level keeps what it loaded, so reopening it draws at once. - * @param d - draft state. - * @param tabId - the tab being drawn. - * @param path - absolute directory path. - */ - toggled: (d, tabId, path) => { - const state = bucket(d, tabId); - const at = state.expanded.indexOf(path); - if (at >= 0) state.expanded.splice(at, 1); - else state.expanded.push(path); - }, - /** - * Record where one tab's body is scrolled to. - * @param d - draft state. - * @param tabId - the tab being drawn. - * @param scrollTop - the body's scroll offset, in px. - */ - scrolled: (d, tabId, scrollTop) => { - bucket(d, tabId).scrollTop = scrollTop; - }, - /** - * Drop every loaded level, keeping what is expanded. - * - * This is the reload gesture's first half: the expanded set says which - * levels to fetch again. - * @param d - draft state. - * @param tabId - the tab being drawn. - */ - reset: (d, tabId) => { - bucket(d, tabId).levels = {}; - }, - /** - * Forget one tab's tree, for a tab record that is gone. - * @param d - draft state. - * @param tabId - the tab that went away. - */ - forget: (d, tabId) => { - d.byTab = Object.fromEntries(Object.entries(d.byTab).filter(([id]) => id !== tabId)); - } - } - }); - } - //#endregion - //#region lib/types/client/index.js - /** This package's copy namespace. */ - const NS = "sidebarFiles"; - /** - * Required browser services: the tab registry, the keyed seat, the Remote - * carrier and its namespace, and copy. - */ - const inject = [ - "slots", - "locale", - "sidebarRightTabs", - "sidebarRight", - "remote", - "remote.workspaceFiles" - ]; - /** - * Client plugin body: register the type, its dictionaries, its body, and its chip title. - * @param ctx - client root context carrying the registry, the slots, and the Remote face. - */ - function apply(ctx) { - const t = ctx.locale.bind(NS); - ctx.inject(["shortcuts"], (ctx) => { - ctx.effect(() => ctx.shortcuts.register({ - id: "workspace.files", - label: () => t("guide.title"), - aliases: ["workspace files", "files"], - defaults: { - "desktop:macos": { - code: "KeyP", - modifiers: ["primary"] - }, - "desktop:windows": { - code: "KeyP", - modifiers: ["primary"] - }, - "desktop:linux": { - code: "KeyP", - modifiers: ["primary"] - }, - "web:macos": { - code: "KeyP", - modifiers: ["primary", "alt"] - }, - "web:windows": { - code: "KeyP", - modifiers: ["primary", "alt"] - } - }, - regions: [ - "page", - "editable", - "terminal" - ], - modals: [], - resolve: ({ target: element }) => { - const target = ctx.sidebarRight.commandTarget(element); - if (target === void 0) return { - status: "blocked", - reason: t("shortcut.noSession") - }; - return { - status: "handled", - run: () => { - ctx.sidebarRight.openTabFromTarget("files", target); - } - }; - } - }), "ui-sidebar-files: shortcut"); - }); - ctx.effect(() => ctx.sidebarRightTabs.register(filesDefinition(t)), "ui-sidebar-files: files type"); - ctx.effect(() => ctx.locale.register(NS, { - zh, - en - }), "ui-sidebar-files: dictionaries"); - const store = createFilesStore(); - const inject = filesFace(createList(ctx.remote), createWatch(ctx.remote)); - ctx.effect(() => ctx.slots.inject("sidebar.right.pane.tab", () => ctx.slots.register({ - name: "sidebar.right.pane.tab", - key: FILES_ID, - locale: NS, - store, - inject, - children: { "sidebar.right.tab.files.actions": { - kind: "list", - scope: "session" - } } - }, FilesBody)), "ui-sidebar-files: files tab body"); - ctx.effect(() => ctx.slots.inject("sidebar.right.pane.tab.title", () => ctx.slots.register({ - name: "sidebar.right.pane.tab.title", - key: FILES_ID - }, FilesTitle)), "ui-sidebar-files: files tab title"); - } - //#endregion - exports.apply = apply; - exports.inject = inject; - return module.exports; - } -}); +window.__ModuleLoader__.load({id:`dsh-rightbar-files`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _deepseek_ai_dsh_client_store=require("@deepseek-ai/dsh-client-store");let _deepseek_ai_dsh_client_ui_primitives=require("@deepseek-ai/dsh-client-ui-primitives");require("@deepseek-ai/cordis");let react_jsx_runtime=require("react/jsx-runtime");let react=require("react");const FILES_KIND=`files`;const FILES_ID=`@deepseek-ai/dsh-client-ui-sidebar-files`;function filesDefinition(t){return{id:FILES_ID,kind:FILES_KIND,priority:`builtin`,title:()=>t(`type.label`),guide:[{id:`workspace`,commandId:`workspace.files`,order:10,title:()=>t(`guide.title`),description:()=>t(`guide.description`),icon:_deepseek_ai_dsh_client_ui_primitives.GuideArtworkFiles}]}}const FILE_ADDRESS_PREFIX=`dsh-resource://file/`;function encodeSegment(segment){return encodeURIComponent(segment).replace(/%3A/gi,`:`)}function encodePath(path){return path.split(`/`).map(encodeSegment).join(`/`)}function isDriveSegment(segment){return segment!==void 0&&/^[A-Za-z]:$/.test(segment)}function sessionFileAddress(sessionId,path){const normalized=path.replace(/\\/g,`/`).replace(/^(?:\.\/)+/,``);return`${FILE_ADDRESS_PREFIX}session/${encodeSegment(sessionId)}/${encodePath(normalized)}`}function parseFileAddress(address){try{if(!address.startsWith(FILE_ADDRESS_PREFIX))return void 0;const end=address.search(/[?#]/);const[scope,...rest]=address.slice(20,end===-1?void 0:end).split(`/`);if(scope===`session`){const[id,...segments]=rest;if(id===void 0||id===``||segments.length===0)return void 0;return{scope,sessionId:decodeURIComponent(id),path:segments.map(decodeURIComponent).join(`/`)}}if(scope===`absolute`){const unc=rest[0]===``&&rest.length>1;const segments=(unc?rest.slice(1):rest).map(decodeURIComponent);if(segments.length===0||segments[0]===``)return void 0;if(unc)return{scope,path:`//${segments.join(`/`)}`};return{scope,path:isDriveSegment(segments[0])?segments.join(`/`):`/${segments.join(`/`)}`}}return}catch{return}}function isWindowsStylePath(value){return/^[A-Za-z]:[/\\]/.test(value)||value.startsWith(`\\\\`)}function isAbsoluteWorkspacePath(path){return path.startsWith(`/`)||isWindowsStylePath(path)}function fileAddressFor(sessionId,cwd,path){const normalized=path.replace(/\\/g,`/`);if(!isAbsoluteWorkspacePath(normalized))return sessionFileAddress(sessionId,normalized);const root=cwd===void 0?``:cwd.replace(/\\/g,`/`).replace(/\/+$/,``);if(root!==``&&normalized===root)return sessionFileAddress(sessionId,``);if(root!==``&&normalized.startsWith(`${root}/`))return sessionFileAddress(sessionId,normalized.slice(root.length+1));return sessionFileAddress(sessionId,normalized)}const DEFAULT_NAVIGATOR_WIDTH=260;const NAVIGATOR_MINIMUM=180;const ROW_REMAINDER=120;const PUSH_FROM=560;function navigatorGeometry(available,width){if(available===void 0){const drawn=Math.max(NAVIGATOR_MINIMUM,width);return{minimum:NAVIGATOR_MINIMUM,maximum:drawn,width:drawn}}const maximum=Math.max(0,available-(available>=560?336:ROW_REMAINDER));const minimum=Math.min(NAVIGATOR_MINIMUM,maximum);return{minimum,maximum,width:Math.min(Math.max(minimum,width),maximum)}}function childPath(parent,name){return`${parent.replace(/[/\\]+$/,``)}/${name}`}function windowsRoot(root){const path=root.replace(/\\/g,`/`);return/^[A-Za-z]:\//.test(path)||path.startsWith(`//`)}function locateFile(tree,relativePath){const caseless=windowsRoot(tree.root);const parts=relativePath.split(`/`);const ancestors=[];let parent=tree.root;for(const[index,part]of parts.entries()){const level=tree.levels[parent];if(level?.kind!==`ready`)return{ancestors,current:void 0,pending:level===void 0||level.kind===`loading`};const type=index===parts.length-1?`file`:`directory`;const candidates=level.level.entries.filter(entry=>entry.type===type);const entry=candidates.find(candidate=>candidate.name===part)??(caseless?candidates.find(candidate=>candidate.name.toLowerCase()===part.toLowerCase()):void 0);if(entry===void 0)return{ancestors,current:void 0,pending:level.refreshing===true};const path=childPath(parent,entry.name);if(type===`directory`)ancestors.push({parent,path});parent=path}return{ancestors,current:parent,pending:false}}function relativeFileOf(address,sessionId,root){const file=parseFileAddress(address);if(file?.scope!==`session`||file.sessionId!==sessionId)return void 0;const path=file.path.replace(/\\/g,`/`);const normalized=isAbsoluteWorkspacePath(path)?underRoot(path,root):path;if(normalized===void 0||normalized===``||isAbsoluteWorkspacePath(normalized))return void 0;return normalized.split(`/`).some(part=>part===``||part===`.`||part===`..`)?void 0:normalized}function underRoot(path,root){const prefix=`${root.replace(/\\/g,`/`).replace(/\/+$/,``)}/`;const head=path.slice(0,prefix.length);return(windowsRoot(prefix)?head.toLowerCase()===prefix.toLowerCase():head===prefix)?path.slice(prefix.length):void 0}function pane(state,paneId){state.byPane[paneId]??={open:void 0,width:260,tree:void 0,query:``,searchBarOpen:false,search:void 0};return state.byPane[paneId]}function tree(state,paneId){const started=state.byPane[paneId]?.tree;if(started===void 0)throw new Error(`ui-sidebar-files: no tree for pane "${paneId}"`);return started}function createFilesStore(){return(0,_deepseek_ai_dsh_client_store.defineStore)({init:()=>({byPane:{}}),actions:{autoRefresh:(d,paneId,enabled)=>{tree(d,paneId).autoRefresh=enabled},start:(d,paneId,root)=>{pane(d,paneId).tree={root,levels:{},expanded:[root],autoRefresh:true}},loading:(d,paneId,path)=>{const state=tree(d,paneId);const level=state.levels[path];if(level?.kind!==`ready`)state.levels[path]={kind:`loading`};else if(level.refreshing!==true)state.levels[path]={...level,refreshing:true}},loaded:(d,paneId,path,level)=>{const state=tree(d,paneId);const previous=state.levels[path];if(previous?.kind===`ready`){const directories=new Set(level.entries.filter(entry=>entry.type===`directory`).map(entry=>entry.name));for(const entry of previous.level.entries){if(entry.type!==`directory`||directories.has(entry.name))continue;const removed=childPath(path,entry.name);state.expanded=state.expanded.filter(value=>value!==removed&&!value.startsWith(`${removed}/`));state.levels=Object.fromEntries(Object.entries(state.levels).filter(([key])=>key!==removed&&!key.startsWith(`${removed}/`)))}}state.levels[path]={kind:`ready`,level}},failed:(d,paneId,path,failure)=>{const state=tree(d,paneId);const level=state.levels[path];state.levels[path]=level?.kind===`ready`?{kind:`ready`,level:level.level,failure}:{kind:`failed`,failure};const below=`${path.replace(/[/\\]+$/,``)}/`;for(const[key,kept]of Object.entries(state.levels)){if(!key.startsWith(below)||kept.kind!==`ready`||kept.refreshing!==true)continue;state.levels[key]=kept.failure===void 0?{kind:`ready`,level:kept.level}:{kind:`ready`,level:kept.level,failure:kept.failure}}},toggled:(d,paneId,path)=>{const state=tree(d,paneId);const at=state.expanded.indexOf(path);if(at>=0)state.expanded.splice(at,1);else state.expanded.push(path)},shown:(d,paneId,open)=>{pane(d,paneId).open=open},searchBarShown:(d,paneId,open)=>{pane(d,paneId).searchBarOpen=open},resized:(d,paneId,width)=>{pane(d,paneId).width=width},forget:(d,paneId)=>{d.byPane=Object.fromEntries(Object.entries(d.byPane).filter(([id])=>id!==paneId))},queried:(d,paneId,query)=>{const state=pane(d,paneId);state.query=query;if(query.trim()===``)state.search=void 0},searching:(d,paneId)=>{const state=d.byPane[paneId];const result=state?.search?.result;if(state!==void 0&&state.query.trim()!==``)state.search={pending:true,result:result?.kind===`failed`?void 0:result}},searched:(d,paneId,result)=>{const state=d.byPane[paneId];if(state!==void 0&&state.query.trim()!==``)state.search={pending:false,result}},searchToggled:(d,paneId,path)=>{const result=d.byPane[paneId]?.search?.result;if(result?.kind!==`found`)return;const at=result.tree.expanded.indexOf(path);if(at>=0)result.tree.expanded.splice(at,1);else result.tree.expanded.push(path)}}})}var RemoteError=class extends Error{code;details;isDSHRemoteError=true;constructor(code,message,details,options){super(message,options);this.code=code;this.details=details;this.name=`RemoteError`}};var DirectoryNode=class DirectoryNode{path;load;watch;failed;restore;children=new Map;controller=new AbortController;signal;task;reading;dirty=false;initialized=false;automatic=true;constructor(path,load,watch,failed,lifetime,restore=[]){this.path=path;this.load=load;this.watch=watch;this.failed=failed;this.restore=restore;this.signal=AbortSignal.any([lifetime,this.controller.signal])}open(){this.task??=this.follow();return this}find(path){if(path===this.path)return this;for(const child of this.children.values()){const found=child.find(path);if(found!==void 0)return found}}setExpanded(expanded){this.restore=expanded;for(const child of this.children.values())child.setExpanded(expanded)}expand(path,restore=[]){if(this.signal.aborted)return void 0;let child=this.children.get(path);if(child===void 0){child=new DirectoryNode(path,this.load,this.watch,this.failed,this.signal,restore);child.automatic=this.automatic;this.children.set(path,child)}return child.open()}async collapse(path){this.restore=this.restore.filter(value=>value!==path&&!value.startsWith(`${path}/`));const child=this.children.get(path);this.children.delete(path);await child?.close()}setAutomatic(enabled){this.automatic=enabled;if(enabled&&this.dirty)this.refresh();for(const child of this.children.values())child.setAutomatic(enabled)}refresh(){this.dirty=true;this.reading??=this.read();return this.reading}async refreshTree(){await this.refresh();await Promise.all([...this.children.values()].map(child=>child.refreshTree()))}async close(){this.controller.abort();await Promise.all([this.task,this.reading,...[...this.children.values()].map(child=>child.close())]);this.children.clear()}async follow(){try{for await(const _event of this.watch(this.path,this.signal)){this.dirty=true;if(!this.initialized||this.automatic)this.refresh()}}catch(error){if(!this.signal.aborted){if(!this.initialized)await this.refresh();if(!(typeof error===`object`&&error!==null&&`code`in error&&error.code===`workspace-file/watch-unsupported`))this.failed(this.path,error)}}}async read(){const readAgain=()=>this.dirty&&this.automatic&&!this.signal.aborted;try{do{this.dirty=false;const level=await this.load(this.path,this.signal);if(this.signal.aborted||level===void 0)return;this.initialized=true;const directories=new Set(level.entries.filter(entry=>entry.type===`directory`).map(entry=>`${this.path.replace(/[/\\]+$/,``)}/${entry.name}`));for(const path of this.children.keys())if(!directories.has(path))await this.collapse(path);for(const path of directories)if(this.restore.includes(path))this.expand(path,this.restore);this.restore=[]}while(readAgain())}finally{this.reading=void 0}}};const FULLSCREEN_QUERY=`(width < 768px)`;const DEFAULT_EXCLUDED_PATHS=[`.git`,`.hg`,`.next`,`.pnpm-store`,`.svn`,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`,`.DS_Store`,`.Spotlight-V100`,`.Trashes`,`.fseventsd`,`Thumbs.db`,`desktop.ini`,`$RECYCLE.BIN`,`System Volume Information`];const GLOB=/[*?[\]{}!]/;function normalizeRulePath(input){const slashed=input.trim().replace(/\\/g,`/`);if(slashed===``)return{kind:`invalid`,reason:`empty`};if(slashed.includes(`\0`))return{kind:`invalid`,reason:`nul`};const relative=slashed.replace(/\/{2,}/g,`/`).replace(/^(?:\s|\.\/)+/,``);if(slashed.startsWith(`/`)||/^(?:\/|~|[A-Za-z]:)/.test(relative))return{kind:`invalid`,reason:`absolute`};const path=relative.replace(/^(.*[^\s/])?[\s/]*$/s,`$1`);if(GLOB.test(path))return{kind:`invalid`,reason:`glob`};if(path===``)return{kind:`invalid`,reason:`empty`};if(path.split(`/`).some(segment=>segment===`.`||segment===`..`))return{kind:`invalid`,reason:`parent`};return{kind:`ok`,path}}function defaultRules(){return DEFAULT_EXCLUDED_PATHS.map(path=>({path,enabled:true}))}function defaultSearchPreferences(){return{rules:defaultRules(),showHidden:false,respectGitignore:true}}function addRule(rules,input){const normalized=normalizeRulePath(input);if(normalized.kind===`invalid`)return normalized;const{path}=normalized;return{kind:`ok`,rules:[{path,enabled:true},...rules.filter(rule=>rule.path!==path)]}}function removeRule(rules,path){return rules.filter(rule=>rule.path!==path)}function setRuleEnabled(rules,path,enabled){return rules.map(rule=>rule.path===path&&rule.enabled!==enabled?{path,enabled}:rule)}function enabledPaths(rules){return rules.filter(rule=>rule.enabled).map(rule=>rule.path)}function isDefaultRules(rules){return rules.length===DEFAULT_EXCLUDED_PATHS.length&&rules.every((rule,index)=>rule.path===DEFAULT_EXCLUDED_PATHS[index]&&rule.enabled)}function readSearchPreferences(value){const defaults=defaultSearchPreferences();if(typeof value!==`object`||value===null||Array.isArray(value))return defaults;const field=name=>Object.hasOwn(value,name)?Object.getOwnPropertyDescriptor(value,name)?.value:void 0;const rules=field(`rules`);const showHidden=field(`showHidden`);const respectGitignore=field(`respectGitignore`);return{rules:Array.isArray(rules)?readRules(rules):defaults.rules,showHidden:typeof showHidden===`boolean`?showHidden:defaults.showHidden,respectGitignore:typeof respectGitignore===`boolean`?respectGitignore:defaults.respectGitignore}}function readRules(rules){const parsed=[];for(const rule of rules){if(typeof rule!==`object`||rule===null||!(`path`in rule)||!(`enabled`in rule))continue;const{path,enabled}=rule;if(typeof path!==`string`||typeof enabled!==`boolean`)continue;const normalized=normalizeRulePath(path);if(normalized.kind===`invalid`||parsed.some(kept=>kept.path===normalized.path))continue;parsed.push({path:normalized.path,enabled})}return parsed}function changedSearchPreferences(preferences){const defaults=defaultSearchPreferences();const changed={};if(!isDefaultRules(preferences.rules))changed.rules=preferences.rules.map(rule=>({path:rule.path,enabled:rule.enabled}));if(preferences.showHidden!==defaults.showHidden)changed.showHidden=preferences.showHidden;if(preferences.respectGitignore!==defaults.respectGitignore)changed.respectGitignore=preferences.respectGitignore;return Object.keys(changed).length===0?void 0:changed}function isHiddenEntry(entry){return entry.name.startsWith(`.`)}function buildSearchTree(root,entries){const children=new Map([[root,new Map]]);const directory=path=>{const names=children.get(path)??new Map;children.set(path,names);return names};for(const entry of entries){const parts=entry.path.split(`/`);let parent=root;for(const[index,name]of parts.entries()){const type=index===parts.length-1?entry.type:`directory`;const names=directory(parent);if(type===`directory`||!names.has(name))names.set(name,type);parent=childPath(parent,name);if(type===`directory`)directory(parent)}}const levels={};for(const[path,names]of children)levels[path]={kind:`ready`,level:{entries:[...names].map(([name,type])=>({name,type})),truncated:false}};return{autoRefresh:false,root,levels,expanded:[...children.keys()]}}function matchRanges(name,query){if(query===``)return[];const pattern=new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`giu`);return[...name.matchAll(pattern)].map(match=>[match.index,match.index+match[0].length])}function layoutParent(element){let parent=element.parentElement;while(parent!==null&&getComputedStyle(parent).display===`contents`)parent=parent.parentElement;return parent}function createWatch(remote){return async function*(sessionId,path,signal){const aborted=()=>signal.aborted;if(aborted())return;const stream=remote.$stream({name:`directory ${path}`,open:lifetime=>remote.workspaceFiles.changes(sessionId,path,lifetime),ended:()=>new Error(`Directory watch ended: ${path}`)});const abort=()=>{stream.dispose()};signal.addEventListener(`abort`,abort,{once:true});try{for await(const item of stream){if(aborted())return;if(item.value.kind===`ready`)item.accept();yield item.value.kind}}finally{signal.removeEventListener(`abort`,abort);await stream.dispose()}}}function createList(remote){return async(sessionId,path,signal)=>{const result=await remote.workspaceFiles.list(sessionId,path,signal);if(!result.ok)return result;return{ok:true,value:{entries:result.value.entries,truncated:result.value.truncated}}}}function canOpenOf(registry){let seen=registry.entries();let check=address=>registry.candidates(address).length>0;return{getSnapshot:()=>{const entries=registry.entries();if(entries!==seen){seen=entries;check=address=>registry.candidates(address).length>0}return check},subscribe:listener=>registry.subscribe(listener)}}const REQUESTED={target:`search`};function filesFace(list,watch,canOpen,navigationOf,search,preferences){return(sessionId,store,place)=>{const{actions}=store;const panes=new Map;const record=paneId=>{let pane=panes.get(paneId);if(pane===void 0){pane={lifetime:void 0,mounts:0,tabs:new Set,holds:0,root:void 0,scrollTop:0,searchScrollTop:0,searchQuery:``,following:void 0,searching:void 0,input:void 0,revealed:void 0,revealing:void 0,drawn:void 0,current:void 0,scrollToCurrent:false,focus:void 0,show:false,width:(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(void 0),navigator:void 0,closable:false,unobserve:void 0,toggle:void 0};panes.set(paneId,pane)}return pane};const homes=new Map;const forget=(paneId,pane)=>{pane.lifetime?.abort();pane.root?.close();pane.root=void 0;pane.unobserve?.();endSearch(pane);panes.delete(paneId);actions.forget(paneId)};const settle=(paneId,pane)=>{if(pane.mounts>0||pane.tabs.size>0)return;queueMicrotask(()=>{if(pane.mounts===0&&pane.tabs.size===0&&panes.get(paneId)===pane)forget(paneId,pane)})};const leave=(tabId,home)=>{home.pane.tabs.delete(tabId);settle(home.paneId,home.pane)};const load=async(paneId,path,signal)=>{const aborted=()=>signal.aborted;if(aborted())return void 0;actions.loading(paneId,path);const result=await list(sessionId,path,signal);if(aborted())return void 0;if(result.ok)actions.loaded(paneId,path,result.value);else actions.failed(paneId,path,result.error);return result.ok?result.value:void 0};let batching=false;const batch=write=>{batching=true;try{write()}finally{batching=false}};const relisting=(paneId,paths)=>{for(const path of paths)if(store.getSnapshot().byPane[paneId]?.tree?.levels[path]?.kind===`ready`)actions.loading(paneId,path)};const drop=paneId=>{const pane=panes.get(paneId);if(pane!==void 0&&pane.lifetime===void 0)settle(paneId,pane)};const expand=(paneId,parentPath,path,expanded,manual)=>{const pane=panes.get(paneId);const root=pane?.root;if(pane===void 0||root===void 0)return;const parent=root.find(parentPath);if(parent===void 0&&!expanded.includes(parentPath))return;const collapsing=expanded.includes(path);if(manual&&collapsing&&pane.revealing!==void 0){pane.revealed=pane.revealing;pane.revealing=void 0}const next=collapsing?expanded.filter(value=>value!==path):[...expanded,path];root.setExpanded(next);if(collapsing)parent?.collapse(path);else parent?.expand(path,next);batch(()=>{actions.toggled(paneId,path);if(!collapsing)relisting(paneId,next.filter(value=>value===path||value.startsWith(childPath(path,``))))});reveal()};const resultsShown=paneId=>store.getSnapshot().byPane[paneId]?.search!==void 0;const endSearch=pane=>{pane.searchQuery=``;pane.searchScrollTop=0;pane.following?.stop();pane.following=void 0;pane.searching?.abort();pane.searching=void 0};const runSearch=(paneId,pane,cwd)=>{pane.searching?.abort();const controller=new AbortController;pane.searching=controller;const query=pane.searchQuery;const{rules,showHidden,respectGitignore}=preferences.source(cwd).getSnapshot();const excludedPaths=enabledPaths(rules);actions.searching(paneId);const settle=result=>{if(pane.searching!==controller)return;pane.searching=void 0;pane.searchScrollTop=0;if(pane.drawn!==void 0)pane.drawn.body.scrollTop=0;actions.searched(paneId,result)};search(sessionId,{query,excludedPaths,includeHidden:showHidden,respectGitignore},controller.signal).then(answer=>{settle(answer.ok?{kind:`found`,query,tree:buildSearchTree(cwd,answer.value.matches),count:answer.value.matches.length,truncated:answer.value.truncated,incomplete:answer.value.incomplete,hiddenLeftOut:!showHidden,excluded:excludedPaths.length>0,ignored:respectGitignore}:{kind:`failed`,query,failure:answer.error})}).catch(error=>{settle({kind:`failed`,query,failure:new RemoteError(`gateway/internal`,error instanceof Error?error.message:String(error),{})})})};const searchAgain=paneId=>{const pane=panes.get(paneId);if(pane?.following===void 0)return;runSearch(paneId,pane,pane.following.cwd)};const follow=(paneId,pane,cwd)=>{if(pane.following?.cwd===cwd)return;pane.following?.stop();const source=preferences.source(cwd);let seen=source.getSnapshot();pane.following={cwd,stop:source.subscribe(()=>{const now=source.getSnapshot();if(now===seen)return;seen=now;runSearch(paneId,pane,cwd)})}};const focusInput=pane=>{pane.focus=void 0;queueMicrotask(()=>{pane.input?.focus()})};const focusTree=pane=>{const handoff={target:`tree`};pane.focus=handoff;queueMicrotask(()=>{if(pane.focus!==handoff)return;pane.focus=void 0;(pane.current??pane.drawn?.body)?.focus()})};const step=(paneId,pane)=>{const address=pane.revealing;const tree=store.getSnapshot().byPane[paneId]?.tree;if(address===void 0||tree===void 0||pane.root===void 0)return;const path=relativeFileOf(address,sessionId,tree.root);const location=path===void 0?void 0:locateFile(tree,path);const next=location?.ancestors.find(ancestor=>!tree.expanded.includes(ancestor.path));if(next!==void 0){expand(paneId,next.parent,next.path,tree.expanded,false);return}if(location?.pending===true)return;pane.revealing=void 0;pane.revealed=address;if(location?.current===void 0)return;if(pane.current===void 0)pane.scrollToCurrent=true;else pane.current.scrollIntoView({block:`nearest`,inline:`nearest`})};const reveal=()=>{for(const[paneId,pane]of panes)if(pane.revealing!==void 0)step(paneId,pane)};store.subscribe(()=>{if(!batching)reveal()});const open=(paneId,pane,signal,root)=>{if(pane.root?.path===root)return;pane.root?.close();const tree=store.getSnapshot().byPane[paneId]?.tree;const kept=tree?.root===root?tree:void 0;if(kept===void 0){actions.start(paneId,root);pane.scrollTop=0;pane.revealed=void 0;pane.revealing=pane.drawn?.address}const node=new DirectoryNode(root,(path,lifetime)=>load(paneId,path,lifetime),(path,lifetime)=>watch(sessionId,path,lifetime),(path,error)=>{if(pane.root===node)actions.failed(paneId,path,new RemoteError(`gateway/internal`,error instanceof Error?error.message:String(error),{}))},signal,kept?.expanded);if(kept!==void 0)node.setAutomatic(kept.autoRefresh);pane.root=node;node.open();if(kept!==void 0)batch(()=>{relisting(paneId,kept.expanded)});step(paneId,pane)};const answerNavigation=home=>{if(home.mounts===0)return;const navigation=home.navigation.getSnapshot();if(navigation.revision<=home.revision)return;const{pane,paneId}=home;if(store.getSnapshot().byPane[paneId]?.open!==true){home.revision=navigation.revision;return}const navigator=pane.navigator;if(navigator===void 0||pane.drawn?.address!==navigation.address)return;const row=layoutParent(navigator);if(row===null)return;home.revision=navigation.revision;const window=row.ownerDocument.defaultView;if(pane.closable&&(row.getBoundingClientRect().width<400||typeof window?.matchMedia===`function`&&window.matchMedia(`(width < 768px)`).matches))face.hide(paneId)};const answerDrawn=pane=>{for(const home of homes.values())if(home.pane===pane)answerNavigation(home)};const face={attach(paneId,tabId,tabSignal){if(tabSignal.aborted){drop(paneId);return()=>{}}const pane=record(paneId);pane.lifetime??=new AbortController;if(pane.show){pane.show=false;if(pane.navigator===void 0||pane.closable)actions.shown(paneId,true);else actions.searchBarShown(paneId,true)}pane.mounts+=1;let home=homes.get(tabId);if(home===void 0){const first={paneId,pane,mounts:0,revision:0,navigation:navigationOf(sessionId,tabId)};home=first;homes.set(tabId,first);const unsubscribe=first.navigation.subscribe(()=>{answerNavigation(first)});tabSignal.addEventListener(`abort`,()=>{unsubscribe();homes.delete(tabId);leave(tabId,first)},{once:true})}else if(home.pane!==pane){leave(tabId,home);home.paneId=paneId;home.pane=pane}home.mounts+=1;pane.tabs.add(tabId);answerNavigation(home);let attached=true;return()=>{if(!attached)return;attached=false;pane.mounts-=1;home.mounts-=1;settle(paneId,pane)}},placeBeside:tabId=>place(tabId,face),hold(paneId,root){const pane=panes.get(paneId);if(pane?.lifetime===void 0)return()=>{};pane.holds+=1;open(paneId,pane,pane.lifetime.signal,root);let held=true;return()=>{if(!held)return;held=false;pane.holds-=1;queueMicrotask(()=>{if(pane.holds>0)return;pane.root?.close();pane.root=void 0})}},refresh:paneId=>{panes.get(paneId)?.root?.refreshTree();searchAgain(paneId)},setAutoRefresh:(paneId,enabled)=>{actions.autoRefresh(paneId,enabled);panes.get(paneId)?.root?.setAutomatic(enabled)},toggle:(paneId,parentPath,path,expanded)=>{expand(paneId,parentPath,path,expanded,true)},scrolled:(paneId,scrollTop)=>{const pane=panes.get(paneId);if(pane?.lifetime===void 0)return;if(resultsShown(paneId))pane.searchScrollTop=scrollTop;else pane.scrollTop=scrollTop},hide(paneId){const pane=panes.get(paneId);if(pane?.lifetime===void 0)return;const navigator=pane.navigator;const held=pane.focus!==void 0||navigator?.contains(navigator.ownerDocument.activeElement)===true;pane.focus=void 0;actions.shown(paneId,false);if(held)queueMicrotask(()=>{panes.get(paneId)?.toggle?.focus()})},focus(paneId){const pane=panes.get(paneId);if(pane===void 0)return;if(pane.lifetime===void 0)pane.show=true;else if(pane.navigator===void 0||pane.closable)actions.shown(paneId,true);else actions.searchBarShown(paneId,true);if(pane.input===void 0)pane.focus=REQUESTED;else focusInput(pane)},setQuery(paneId,cwd,query){const pane=panes.get(paneId);if(pane?.lifetime===void 0)return;actions.queried(paneId,query);const trimmed=query.trim();if(trimmed===``){endSearch(pane);return}if(pane.searchQuery===trimmed&&pane.following?.cwd===cwd)return;pane.searchQuery=trimmed;follow(paneId,pane,cwd);runSearch(paneId,pane,cwd)},toggleSearch:(paneId,path)=>{actions.searchToggled(paneId,path)},retrySearch:searchAgain,setSearchPreferences:(cwd,patch)=>{preferences.update(cwd,patch)},searchDrawn(paneId,input){if(input===null){const pane=panes.get(paneId);if(pane===void 0)return;const gone=pane.input;pane.input=void 0;if(gone===void 0||gone.ownerDocument.activeElement!==gone)return;const handoff={target:`search`};pane.focus=handoff;queueMicrotask(()=>{if(pane.focus===handoff)pane.focus=void 0});return}const pane=record(paneId);pane.input=input;if(pane.focus?.target===`search`)focusInput(pane)},bodyDrawn(paneId,address,body){if(body===null){const pane=panes.get(paneId);if(pane===void 0)return;const gone=pane.drawn?.body;pane.drawn=void 0;pane.revealing=void 0;pane.scrollToCurrent=false;drop(paneId);if(gone?.contains(gone.ownerDocument.activeElement)!==true)return;const handoff={target:`tree`};pane.focus=handoff;queueMicrotask(()=>{if(pane.focus===handoff)pane.focus=void 0});return}const pane=record(paneId);pane.drawn={body,address};body.scrollTop=resultsShown(paneId)?pane.searchScrollTop:pane.scrollTop;if(pane.focus?.target===`tree`)focusTree(pane);pane.revealing=pane.revealed===address?void 0:address;step(paneId,pane)},currentDrawn(paneId,row){if(row===null){const pane=panes.get(paneId);if(pane!==void 0)pane.current=void 0;drop(paneId);return}const pane=record(paneId);pane.current=row;if(!pane.scrollToCurrent)return;pane.scrollToCurrent=false;row.scrollIntoView({block:`nearest`,inline:`nearest`})},navigatorDrawn(paneId,navigator,closable){const pane=navigator===null?panes.get(paneId):record(paneId);if(pane===void 0)return;pane.unobserve?.();pane.unobserve=void 0;pane.navigator=navigator??void 0;pane.closable=closable;if(navigator===null){drop(paneId);return}const row=layoutParent(navigator);if(row===null)return;const document=row.ownerDocument;let edge;const handOff=()=>{const held=edge;if(held===void 0)return;const active=document.activeElement;if(active!==held&&active!==document.body&&active!==null){edge=void 0;return}if(held.isConnected&&getComputedStyle(held).display!==`none`){if(active!==held)edge=void 0;return}edge=void 0;focusTree(pane)};const focusin=event=>{edge=event.target instanceof Element&&event.target.hasAttribute(`data-files-navigator-resize`)?event.target:void 0};const focusout=event=>{if(event.relatedTarget===null)queueMicrotask(handOff);else edge=void 0};const viewport=closable&&typeof matchMedia===`function`?matchMedia(FULLSCREEN_QUERY):void 0;let filling=false;const hidden=element=>getComputedStyle(element).visibility===`hidden`;let covered;const release=event=>{const target=event.target;covered=event.relatedTarget===null&&target instanceof Element&&!navigator.contains(target)&&hidden(target)?target:void 0};const forget=()=>{covered=void 0};const measure=()=>{const active=document.activeElement;const blurred=covered;covered=void 0;const width=row.getBoundingClientRect().width;const fills=closable&&(width<400||viewport?.matches===true);const entering=fills&&!filling;filling=fills;pane.width.set(width);answerDrawn(pane);const inContent=active!==null&&row.contains(active)&&!navigator.contains(active);const blurredByFill=blurred!==void 0&&(active===null||active===document.body)&&row.contains(blurred)&&hidden(blurred);if(entering&&store.getSnapshot().byPane[paneId]?.open===true&&(inContent||blurredByFill)&&pane.focus===void 0)focusTree(pane);if(edge!==void 0)queueMicrotask(handOff)};const close=event=>{if(event.key!==`Escape`||event.defaultPrevented||event.isComposing||event.altKey||event.ctrlKey||event.metaKey||event.shiftKey)return;if(!(event.target instanceof Node)||!row.contains(event.target))return;event.preventDefault();pane.toggle?.focus();actions.shown(paneId,false)};measure();const observer=new ResizeObserver(measure);observer.observe(row);viewport?.addEventListener(`change`,measure);if(closable){document.addEventListener(`keydown`,close);row.addEventListener(`focusout`,release);document.addEventListener(`focusin`,forget,true);document.addEventListener(`pointerdown`,forget,true);window.addEventListener(`blur`,forget)}navigator.addEventListener(`focusin`,focusin);navigator.addEventListener(`focusout`,focusout);pane.unobserve=()=>{observer.disconnect();viewport?.removeEventListener(`change`,measure);document.removeEventListener(`keydown`,close);row.removeEventListener(`focusout`,release);document.removeEventListener(`focusin`,forget,true);document.removeEventListener(`pointerdown`,forget,true);window.removeEventListener(`blur`,forget);navigator.removeEventListener(`focusin`,focusin);navigator.removeEventListener(`focusout`,focusout)}},toggleDrawn(paneId,toggle){if(toggle!==null){record(paneId).toggle=toggle;return}const pane=panes.get(paneId);if(pane!==void 0)pane.toggle=void 0;drop(paneId)},hooks:{canOpen},keyedHooks:{rowWidth:paneId=>record(paneId).width,searchPreferences:cwd=>preferences.source(cwd)}};return face}}function createSearch(remote){return(sessionId,request,signal)=>remote.workspaceFiles.search(sessionId,request,signal)}function r(e){var t,f,n=``;if(`string`==typeof e||`number`==typeof e)n+=e;else if(`object`==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t({entry,kind:entry.meta?.kind??(groups.has(entry.path)?`directory`:`file`)})));return levels}function orderOf(level){return level.map((node,index)=>({node,index})).sort(({node:left},{node:right})=>{const group=Number(right.kind===`directory`)-Number(left.kind===`directory`);return group!==0?group:byName.compare(left.entry.name,right.entry.name)}).map(({index})=>index)}function Name({name,highlight}){const ranges=highlight===void 0?[]:matchRanges(name,highlight);if(ranges.length===0)return(0,react_jsx_runtime.jsx)(`span`,{className:FileTree_module_css_default.name,children:name});const parts=[];let at=0;for(const[start,end]of ranges){if(start>at)parts.push(name.slice(at,start));parts.push((0,react_jsx_runtime.jsx)(`mark`,{className:FileTree_module_css_default.match,children:name.slice(start,end)},start));at=end}if(at