@vibecontrols/vibe-plugin-desk-windows 0.0.0-stage → 2026.1202.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +25 -0
- package/README.md +134 -2
- package/dist/backend.d.ts +83 -0
- package/dist/env.d.ts +22 -0
- package/dist/files.d.ts +45 -0
- package/dist/helper.d.ts +71 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +9 -0
- package/dist/keys.d.ts +41 -0
- package/helper/DeskWindowsHelper.cs +1586 -0
- package/helper/desk_windows_helper.ps1 +57 -0
- package/package.json +84 -4
- package/vibe-plugin.sig.json +21 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Burdenoff Consultancy Services Private Limited,
|
|
4
|
+
Algoshred Technologies Private Limited,
|
|
5
|
+
and all its sister companies.
|
|
6
|
+
|
|
7
|
+
Maintainer: Vignesh T.V <https://github.com/tvvignesh>
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is furnished
|
|
14
|
+
to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,135 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @vibecontrols/vibe-plugin-desk-windows
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Windows provider for BotManor Stewards desks. It lets a Steward use a person's own Windows PC through the VibeControls agent, behind the common desk API of [`@vibecontrols/vibe-plugin-desk`](https://github.com/Algoshred/vibe-plugin-desk). Actions reach the PC over the agent's command channel, so no public tunnel is needed.
|
|
4
|
+
|
|
5
|
+
Install it next to the desk meta plugin. The meta routes actions here and enforces fencing, idempotency, timeouts, the workspace folder, local consent and the kill switch. This plugin drives the desktop.
|
|
6
|
+
|
|
7
|
+
## Release and signing
|
|
8
|
+
|
|
9
|
+
This plugin hands a person's own machine to a Steward, so every release is signed (BOFF-16561, BotManor spec 10 §8 T7). The agent loads a desk plugin only with a valid `vibe-plugin.sig.json` from a key in its trust root.
|
|
10
|
+
|
|
11
|
+
- Every push to `main` runs `.github/workflows/release.yml`. It stamps the next free CalVer version, runs `boff sanity --force`, builds, signs the package with the `VIBE_PLUGIN_SIGNING_KEY` secret under the key id in the `VIBE_PLUGIN_SIGNING_KEY_ID` variable, checks the packed tarball the way the agent does, and publishes it to npm through npm trusted publishing (GitHub Actions OIDC, no npm token).
|
|
12
|
+
- npm trusts the calling file: `@vibecontrols/vibe-plugin-desk-windows` needs a trusted publisher for `Algoshred/vibe-plugin-desk-windows` and `release.yml`. A package that was never published needs its first publish by hand before the trusted publisher can be added.
|
|
13
|
+
- `npm-unpublish.yml` documents unpublish and deprecate; npm tokens can no longer perform them, so a maintainer runs them from their own npm session.
|
|
14
|
+
|
|
15
|
+
### First release (one-time, by hand)
|
|
16
|
+
|
|
17
|
+
The package has not been published yet, so the first release needs two people-only steps before the workflow can publish on its own. Do them in this order:
|
|
18
|
+
|
|
19
|
+
1. **Add the signing key.** A holder of the release key adds the repository secret `VIBE_PLUGIN_SIGNING_KEY`: the same Ed25519 PKCS#8 PEM, for key id `vc-plugins-2026-11`, that `vibe-plugin-desk-macos` uses (`gh secret set VIBE_PLUGIN_SIGNING_KEY -R Algoshred/vibe-plugin-desk-windows < key.pem`). Until it exists, every release run stops at "Sign the plugin package" with `PLUGIN_SIGNING_KEY is not set`. Do not clear the `VIBE_PLUGIN_SIGNING_KEY_ID` variable to get past it: desk plugins must be signed.
|
|
20
|
+
2. **Publish the first signed build.** A maintainer with publish rights on the `@vibecontrols` scope, signed in to npm with 2FA, publishes from a clean checkout of `main`. Never publish an unsigned tarball. Like the release workflow, the steps below build once, sign, pack once with `--ignore-scripts`, and publish that exact tarball with `--ignore-scripts`. A plain `npm publish` would run `prepublishOnly` and `prebuild`, delete and rebuild `dist/` after signing, and could ship files the signature does not cover.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
bun install --frozen-lockfile
|
|
24
|
+
npm version <next CalVer, e.g. 2026.1202.1> --no-git-tag-version
|
|
25
|
+
bun run build
|
|
26
|
+
export PLUGIN_SIGNING_KEY="$(cat key.pem)"
|
|
27
|
+
# Sign the built package, then pack it for real and verify the unpacked tarball.
|
|
28
|
+
bun .github/actions/ci-workflows/node-lib/sign-plugin/sign.ts sign --dir . --key-id vc-plugins-2026-11
|
|
29
|
+
bun .github/actions/ci-workflows/node-lib/sign-plugin/sign.ts verify --dir .
|
|
30
|
+
unset PLUGIN_SIGNING_KEY
|
|
31
|
+
# Pack the signed files once, confirm the signature is inside, and publish that tarball.
|
|
32
|
+
TARBALL="$(npm pack --ignore-scripts --json | jq -r '.[0].filename')"
|
|
33
|
+
tar -tzf "$TARBALL" | grep -x 'package/vibe-plugin.sig.json'
|
|
34
|
+
npm publish "./$TARBALL" --access public --ignore-scripts
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
3. **Register the trusted publisher.**
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm trust github @vibecontrols/vibe-plugin-desk-windows --file release.yml --repo Algoshred/vibe-plugin-desk-windows --allow-publish --yes
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
4. **Prove the workflow publishes.** Within two days, run the Release workflow from the Actions tab (`workflow_dispatch`). Check that it publishes the next version over OIDC, and that the finalize job tags the release and creates the GitHub Release.
|
|
44
|
+
|
|
45
|
+
Publishing does not offer the plugin to anyone. It is not in the agent's plugin catalog, and not in the desk meta's provider list. Enabling it is a separate change that:
|
|
46
|
+
|
|
47
|
+
1. catalogues the package in the agent as `trusted: false` with a pinned `integrity`;
|
|
48
|
+
2. adds it to the desk meta's `DESK_PROVIDERS` as opt-in, with no `defaultOn`.
|
|
49
|
+
|
|
50
|
+
## How it works
|
|
51
|
+
|
|
52
|
+
The plugin starts **one helper process** per desk and keeps it for as long as the agent runs. The helper is `helper/desk_windows_helper.ps1`. It runs in Windows PowerShell 5.1, compiles `helper/DeskWindowsHelper.cs` in memory, and speaks JSON over stdin and stdout, one object per line.
|
|
53
|
+
|
|
54
|
+
The helper:
|
|
55
|
+
|
|
56
|
+
- reads the screen through **UI Automation**;
|
|
57
|
+
- acts on a ref through **UI Automation** first: a left click uses the element's Invoke, Toggle or SelectionItem pattern, a scroll its Scroll pattern (or a scrollable ancestor's), and `type` focuses the element through UI Automation. This works when the window cannot come to the front or another window covers the element;
|
|
58
|
+
- falls back to **`SendInput`**, as a person's mouse and keyboard would, for points and windows, right and double clicks, keys, the text of `type` (UI Automation can only replace a whole value, not type at the caret), and any element without a fitting pattern;
|
|
59
|
+
- takes screenshots with the **GDI+ screen capture API** (`Graphics.CopyFromScreen`).
|
|
60
|
+
|
|
61
|
+
Starting PowerShell costs one to three seconds, so it happens once. A helper that stops answering, for example behind a hung application, is stopped and started again on the next action.
|
|
62
|
+
|
|
63
|
+
## Actions
|
|
64
|
+
|
|
65
|
+
| Action | What it does |
|
|
66
|
+
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
67
|
+
| `screenshot` | PNG of every monitor. Password fields and fields labelled as secrets are boxed out in black before the image leaves the helper. |
|
|
68
|
+
| `snapshot` | The windows, and the controls on screen, each with a ref (`e1`, `e2`, ...). Password values are never read. |
|
|
69
|
+
| `click` | Clicks a ref, a point or a window. Takes `button` and a double-click `count`. |
|
|
70
|
+
| `type` | Types text, after focusing a ref, point or window if one is given. Newline is Enter, tab is Tab. |
|
|
71
|
+
| `key` | Presses keys in Playwright syntax, for example `Enter`, `Control+a` or `Shift+ArrowDown`. |
|
|
72
|
+
| `scroll` | Turns the wheel by `dx`/`dy` pixels (100 pixels a notch), over a ref, point or window if one is given. |
|
|
73
|
+
| `focus_window` | Brings the front-most window of a process to the front. `app` is the process name (`notepad` or `notepad.exe`), `title` a part of the title. |
|
|
74
|
+
| `shell` | Runs a command with `cmd.exe /d /s /c` in the workspace folder. A command that overruns is ended with its whole process tree. |
|
|
75
|
+
| `read_file` | Reads a file in the workspace folder. |
|
|
76
|
+
| `write_file` | Writes a file in the workspace folder. |
|
|
77
|
+
|
|
78
|
+
`navigate` and `secret_fill` are browser actions. The meta refuses them for this provider.
|
|
79
|
+
|
|
80
|
+
**Coordinates.** Point targets and snapshot bounds are physical pixels of the screenshot. `(0, 0)` is the screenshot's top left corner, also with several monitors.
|
|
81
|
+
|
|
82
|
+
**Refs.**
|
|
83
|
+
|
|
84
|
+
- Refs come from the last `snapshot`.
|
|
85
|
+
- Before each use, a ref is checked again: its window is still open, and it is still on screen.
|
|
86
|
+
- A ref or window target that another window covers is refused.
|
|
87
|
+
- A failed check returns `TARGET_NOT_FOUND`: take a new snapshot.
|
|
88
|
+
|
|
89
|
+
**What Windows does not allow.**
|
|
90
|
+
|
|
91
|
+
- Input to windows of programs running as administrator is blocked by Windows (UIPI).
|
|
92
|
+
- Nothing can be driven while the screen is locked or a UAC prompt is showing.
|
|
93
|
+
|
|
94
|
+
Both return `DESK_OFFLINE`; they are not silently ignored.
|
|
95
|
+
|
|
96
|
+
**What the helper and commands inherit.** The helper and `shell` commands get a short allow-list of the agent's environment (`SystemRoot`, `PATH`, `TEMP`, `USERPROFILE`, ...), never the agent's own tokens.
|
|
97
|
+
|
|
98
|
+
## Configuration
|
|
99
|
+
|
|
100
|
+
Set with `vibe config set <key> <value>`:
|
|
101
|
+
|
|
102
|
+
| Key | Default | Meaning |
|
|
103
|
+
| ------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------- |
|
|
104
|
+
| `desk-windows.powershell` | `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe` | Windows PowerShell 5.1, as an absolute path to `powershell.exe` |
|
|
105
|
+
|
|
106
|
+
PowerShell 7 (`pwsh`) does not work: the helper needs the .NET Framework.
|
|
107
|
+
|
|
108
|
+
## When it does not start
|
|
109
|
+
|
|
110
|
+
On any platform but Windows, or when the helper cannot start, the plugin refuses to start with a clear error and registers nothing. The helper cannot start when:
|
|
111
|
+
|
|
112
|
+
- the agent runs as a service, with no signed-in desktop;
|
|
113
|
+
- PowerShell runs in Constrained Language mode;
|
|
114
|
+
- an application control policy blocks `Add-Type`.
|
|
115
|
+
|
|
116
|
+
## Development
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
bun install
|
|
120
|
+
bun run sanity # format, lint, type check, build, unit tests
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
The unit tests run anywhere. They replace the helper with a fake that speaks the same protocol (`src/__tests__/fixtures/fake-helper.ts`).
|
|
124
|
+
|
|
125
|
+
The common desk API tests drive the real helper against a small Windows Forms window (`src/__tests__/fixtures/test_app.ps1`). They need Windows with a signed-in desktop:
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
bun run test:windows
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
CI runs them on `windows-latest` (job `windows` in `.github/workflows/pr-check.yml`).
|
|
132
|
+
|
|
133
|
+
## License
|
|
134
|
+
|
|
135
|
+
MIT
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Windows desk backend (BOFF-16566): a person's own Windows PC, behind
|
|
3
|
+
* the common desk contract (`@vibecontrols/plugin-sdk/desk`).
|
|
4
|
+
*
|
|
5
|
+
* The `vibe-plugin-desk` meta wraps this backend in the SDK desk guard, so
|
|
6
|
+
* fencing, idempotency, workspace-folder confinement, timeouts, `UNTRUSTED`
|
|
7
|
+
* provenance, local consent and the kill switch are not handled here.
|
|
8
|
+
*
|
|
9
|
+
* Screen actions go to ONE long-lived helper process (`helper.ts`) that
|
|
10
|
+
* holds a UI Automation client. File and shell actions run here, on the
|
|
11
|
+
* paths the guard confined.
|
|
12
|
+
*
|
|
13
|
+
* - `snapshot` lists what is on screen from the UI Automation tree, each
|
|
14
|
+
* element with a ref (`e1`, `e2`, ...). Refs are the default target;
|
|
15
|
+
* points are the fallback, and `{ by: "window" }` picks a top-level window
|
|
16
|
+
* by process name and title. A ref lives in the helper until the next
|
|
17
|
+
* snapshot, and is checked again (still there, still on screen) before
|
|
18
|
+
* each use.
|
|
19
|
+
* - Input is `SendInput`: the pointer is placed on the target, then the
|
|
20
|
+
* button, wheel or keys are sent, as a person's would be.
|
|
21
|
+
* - `screenshot` captures every monitor with the screen capture API and
|
|
22
|
+
* boxes out password fields and fields labelled as secrets, found through
|
|
23
|
+
* UI Automation, before the image leaves the helper (spec §5.8). When UI
|
|
24
|
+
* Automation is unavailable the image is returned with a warning in
|
|
25
|
+
* `text`, so the gateway runs its own PII pass.
|
|
26
|
+
* - Coordinates are physical pixels of the screenshot: (0, 0) is its top
|
|
27
|
+
* left corner, which is the virtual screen's, also with several monitors.
|
|
28
|
+
*
|
|
29
|
+
* There is one screen, so every desk id served by one backend shares it.
|
|
30
|
+
*/
|
|
31
|
+
import type { ConfinedPaths, DeskAction, DeskActionType, DeskBackend, DeskBackendResult } from "@vibecontrols/plugin-sdk/desk";
|
|
32
|
+
import { type ShellLauncher } from "./files.js";
|
|
33
|
+
import { type HelperInfo, type HelperOptions, WindowsHelper } from "./helper.js";
|
|
34
|
+
export declare const WINDOWS_ACTIONS: readonly ["screenshot", "snapshot", "click", "type", "key", "scroll", "focus_window", "shell", "read_file", "write_file"];
|
|
35
|
+
/** Mirrors the limits in helper/DeskWindowsHelper.cs. */
|
|
36
|
+
export declare const WINDOWS_LIMITS: {
|
|
37
|
+
readonly maxElements: 500;
|
|
38
|
+
readonly maxText: 20000;
|
|
39
|
+
};
|
|
40
|
+
/** Starts the helper. Tests replace it. */
|
|
41
|
+
export type HelperStarter = (options: HelperOptions) => Promise<WindowsHelper>;
|
|
42
|
+
export interface WindowsDeskOptions {
|
|
43
|
+
/** Windows PowerShell 5.1 (default: %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe). */
|
|
44
|
+
powershell?: string;
|
|
45
|
+
/** Replaces the helper command entirely. Tests only. */
|
|
46
|
+
helperCommand?: readonly string[];
|
|
47
|
+
/** Environment the helper and shell commands start from (default: process.env, filtered). */
|
|
48
|
+
env?: NodeJS.ProcessEnv;
|
|
49
|
+
start?: HelperStarter;
|
|
50
|
+
startTimeoutMs?: number;
|
|
51
|
+
abortGraceMs?: number;
|
|
52
|
+
/** Replaces cmd.exe for `shell`. Tests only. */
|
|
53
|
+
shell?: ShellLauncher;
|
|
54
|
+
}
|
|
55
|
+
/** The `screenshot` warning when secret fields could not be masked. */
|
|
56
|
+
export declare const UNMASKED_WARNING = "secret fields were not masked: UI Automation is unavailable";
|
|
57
|
+
export declare class WindowsDeskBackend implements DeskBackend {
|
|
58
|
+
private readonly options;
|
|
59
|
+
readonly kind = "windows";
|
|
60
|
+
readonly actions: readonly DeskActionType[];
|
|
61
|
+
private helper;
|
|
62
|
+
private starting;
|
|
63
|
+
private closed;
|
|
64
|
+
private readonly env;
|
|
65
|
+
constructor(options?: WindowsDeskOptions);
|
|
66
|
+
/** The helper command line. */
|
|
67
|
+
get helperCommand(): readonly string[];
|
|
68
|
+
/**
|
|
69
|
+
* Start the helper now and report the screen. Throws
|
|
70
|
+
* WindowsUnavailableError when it cannot start; the plugin uses this to
|
|
71
|
+
* refuse to start.
|
|
72
|
+
*/
|
|
73
|
+
connect(): Promise<HelperInfo>;
|
|
74
|
+
act(action: DeskAction, context: {
|
|
75
|
+
deskId: string;
|
|
76
|
+
signal: AbortSignal;
|
|
77
|
+
paths: ConfinedPaths;
|
|
78
|
+
}): Promise<DeskBackendResult>;
|
|
79
|
+
/** Stop the helper. Safe to call twice; later actions are refused. */
|
|
80
|
+
close(): Promise<void>;
|
|
81
|
+
private ensureHelper;
|
|
82
|
+
private screenAction;
|
|
83
|
+
}
|
package/dist/env.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Variables a Windows desk process may inherit from the agent. */
|
|
2
|
+
export declare const PASSED_ENV: readonly ["SystemRoot", "SystemDrive", "windir", "ComSpec", "PATH", "PATHEXT", "TEMP", "TMP", "USERPROFILE", "USERNAME", "USERDOMAIN", "HOMEDRIVE", "HOMEPATH", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "CommonProgramFiles", "CommonProgramFiles(x86)", "CommonProgramW6432", "PUBLIC", "ALLUSERSPROFILE", "COMPUTERNAME", "OS", "PROCESSOR_ARCHITECTURE", "NUMBER_OF_PROCESSORS", "PSModulePath", "LANG", "TZ"];
|
|
3
|
+
/** The allow-listed variables of `env`, matched without regard to case. */
|
|
4
|
+
export declare function deskEnv(env: NodeJS.ProcessEnv): Record<string, string>;
|
|
5
|
+
/** `%SystemRoot%`, only when it is an absolute Windows path. */
|
|
6
|
+
export declare function systemRoot(env: Record<string, string>): string;
|
|
7
|
+
/**
|
|
8
|
+
* Windows PowerShell 5.1 by its absolute path, so a `powershell.exe` earlier
|
|
9
|
+
* on PATH cannot stand in for it. PowerShell 7 (`pwsh`) does not work: the
|
|
10
|
+
* helper needs the .NET Framework's JSON serializer.
|
|
11
|
+
*/
|
|
12
|
+
export declare function defaultPowerShell(env: Record<string, string>): string;
|
|
13
|
+
/** `cmd.exe` by its absolute path; `ComSpec` is not trusted. */
|
|
14
|
+
export declare function defaultCmd(env: Record<string, string>): string;
|
|
15
|
+
/** `taskkill.exe` by its absolute path, to end a `shell` command's process tree. */
|
|
16
|
+
export declare function defaultTaskkill(env: Record<string, string>): string;
|
|
17
|
+
/**
|
|
18
|
+
* The helper command line. `-ExecutionPolicy Bypass` applies to this one
|
|
19
|
+
* process only; the machine's policy is not changed. `-NoProfile` keeps the
|
|
20
|
+
* user's profile scripts out of the helper.
|
|
21
|
+
*/
|
|
22
|
+
export declare function helperCommand(powershell: string, script: string): readonly string[];
|
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { DeskBackendResult } from "@vibecontrols/plugin-sdk/desk";
|
|
2
|
+
export declare const FILE_LIMITS: {
|
|
3
|
+
/** Output of one `shell` command kept for the result (stdout and stderr together). */
|
|
4
|
+
readonly maxShellOutput: number;
|
|
5
|
+
};
|
|
6
|
+
/** Read up to `maxBytes` of a regular file as UTF-8 text. */
|
|
7
|
+
export declare function readConfinedFile(path: string | undefined, maxBytes: number): Promise<DeskBackendResult>;
|
|
8
|
+
/**
|
|
9
|
+
* Create or replace a file, creating missing folders. On Windows the file
|
|
10
|
+
* inherits the workspace folder's access list; the modes apply elsewhere.
|
|
11
|
+
*/
|
|
12
|
+
export declare function writeConfinedFile(path: string | undefined, content: string): Promise<DeskBackendResult>;
|
|
13
|
+
/** How a `shell` command is started and stopped. */
|
|
14
|
+
export interface ShellLauncher {
|
|
15
|
+
/** The program, its arguments and whether they go to it verbatim. */
|
|
16
|
+
spawnSpec(command: string, env: Record<string, string>): {
|
|
17
|
+
file: string;
|
|
18
|
+
args: string[];
|
|
19
|
+
verbatim: boolean;
|
|
20
|
+
};
|
|
21
|
+
/** Stop the command and everything it started. */
|
|
22
|
+
killTree(pid: number, env: Record<string, string>): void;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* `cmd.exe /d /s /c "<command>"`, as Node runs a shell command on Windows;
|
|
26
|
+
* `/d` skips AutoRun commands from the registry. A stopped command is ended
|
|
27
|
+
* with its whole process tree (`taskkill /T /F`).
|
|
28
|
+
*/
|
|
29
|
+
export declare const windowsShell: ShellLauncher;
|
|
30
|
+
export interface ShellRequest {
|
|
31
|
+
command: string;
|
|
32
|
+
/** Confined working folder. */
|
|
33
|
+
cwd: string | undefined;
|
|
34
|
+
timeoutMs: number;
|
|
35
|
+
env: Record<string, string>;
|
|
36
|
+
signal: AbortSignal;
|
|
37
|
+
launcher?: ShellLauncher;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Run `command` with `cmd.exe`. The result text is `exit <code>` on the
|
|
41
|
+
* first line, then the combined output. `ok` is true only for exit code 0.
|
|
42
|
+
* A command that outlives `timeoutMs` is ended with its whole process tree
|
|
43
|
+
* and returns TIMEOUT.
|
|
44
|
+
*/
|
|
45
|
+
export declare function runShell(request: ShellRequest): Promise<DeskBackendResult>;
|
package/dist/helper.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** Error codes the helper may answer with. Anything else reads as DESK_OFFLINE. */
|
|
2
|
+
export type HelperErrorCode = "TARGET_NOT_FOUND" | "DESK_OFFLINE";
|
|
3
|
+
/** A failed request, with the code the desk result should carry. */
|
|
4
|
+
export declare class HelperError extends Error {
|
|
5
|
+
readonly code: HelperErrorCode;
|
|
6
|
+
constructor(code: HelperErrorCode, message: string);
|
|
7
|
+
}
|
|
8
|
+
/** The helper could not start: not Windows, no PowerShell, no desktop session. */
|
|
9
|
+
export declare class WindowsUnavailableError extends Error {
|
|
10
|
+
constructor(message: string);
|
|
11
|
+
}
|
|
12
|
+
export interface HelperInfo {
|
|
13
|
+
/** Size of the virtual screen (every monitor), in physical pixels. */
|
|
14
|
+
width: number;
|
|
15
|
+
height: number;
|
|
16
|
+
/** Top-left corner of the virtual screen; screenshots start here. */
|
|
17
|
+
left: number;
|
|
18
|
+
top: number;
|
|
19
|
+
/** True when snapshots, refs and secret masking are available. */
|
|
20
|
+
uia: boolean;
|
|
21
|
+
/** Why UI Automation is unavailable, when it is. */
|
|
22
|
+
uiaError?: string;
|
|
23
|
+
}
|
|
24
|
+
export type HelperReply = Record<string, unknown>;
|
|
25
|
+
export interface HelperOptions {
|
|
26
|
+
/** The command that starts the helper, e.g. [powershell.exe, "-NoProfile", ..., "-File", script]. */
|
|
27
|
+
command: readonly string[];
|
|
28
|
+
/** Environment of the helper process. */
|
|
29
|
+
env: Record<string, string>;
|
|
30
|
+
/** How long the helper may take to compile, load UI Automation and say it is ready. */
|
|
31
|
+
startTimeoutMs?: number;
|
|
32
|
+
/** After an abort, how long to wait for the late answer before killing the helper. */
|
|
33
|
+
abortGraceMs?: number;
|
|
34
|
+
}
|
|
35
|
+
export declare const HELPER_LIMITS: {
|
|
36
|
+
/** Windows PowerShell compiles the helper at start: allow for a cold disk. */
|
|
37
|
+
readonly startTimeoutMs: 30000;
|
|
38
|
+
readonly abortGraceMs: 2000;
|
|
39
|
+
/** Longest stderr kept for an error message. */
|
|
40
|
+
readonly maxStderr: 2000;
|
|
41
|
+
/** Longest reply line accepted (a 4K screenshot is about 12 MB of base64). */
|
|
42
|
+
readonly maxLineBytes: number;
|
|
43
|
+
};
|
|
44
|
+
/** Where the packaged helper script is, from `src/` and from `dist/`. */
|
|
45
|
+
export declare function helperScriptPath(from?: string): string;
|
|
46
|
+
export declare class WindowsHelper {
|
|
47
|
+
private readonly options;
|
|
48
|
+
private child;
|
|
49
|
+
private nextId;
|
|
50
|
+
private readonly pending;
|
|
51
|
+
private buffered;
|
|
52
|
+
private bufferedBytes;
|
|
53
|
+
private stderr;
|
|
54
|
+
private exited;
|
|
55
|
+
private infoValue;
|
|
56
|
+
private onReady;
|
|
57
|
+
private constructor();
|
|
58
|
+
/** Start the helper and wait until UI Automation is loaded. */
|
|
59
|
+
static start(options: HelperOptions): Promise<WindowsHelper>;
|
|
60
|
+
get info(): HelperInfo;
|
|
61
|
+
/** False once the process exited or was stopped. */
|
|
62
|
+
get alive(): boolean;
|
|
63
|
+
private launch;
|
|
64
|
+
private onData;
|
|
65
|
+
private onLine;
|
|
66
|
+
private failAll;
|
|
67
|
+
/** Send one request. Rejects with HelperError on a refusal or a dead helper. */
|
|
68
|
+
request(op: string, args?: Record<string, unknown>, signal?: AbortSignal): Promise<HelperReply>;
|
|
69
|
+
/** Stop the helper. Pending requests fail with DESK_OFFLINE. */
|
|
70
|
+
kill(): void;
|
|
71
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { VibePluginFactory } from "@vibecontrols/plugin-sdk/contract";
|
|
2
|
+
import { type HelperStarter } from "./backend.js";
|
|
3
|
+
/** The provider type the `vibe-plugin-desk` meta routes to. */
|
|
4
|
+
export declare const DESK_PROVIDER_TYPE = "desk";
|
|
5
|
+
export declare const DESK_WINDOWS_CONFIG: {
|
|
6
|
+
readonly powershell: "desk-windows.powershell";
|
|
7
|
+
};
|
|
8
|
+
/** The plugin refuses to start anywhere but Windows. */
|
|
9
|
+
export declare class NotWindowsError extends Error {
|
|
10
|
+
constructor(platform: string);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The configured PowerShell, only when it is an absolute Windows path to a
|
|
14
|
+
* `powershell.exe`; anything else falls back to the default.
|
|
15
|
+
*/
|
|
16
|
+
export declare function parsePowerShell(value: string | undefined): string | undefined;
|
|
17
|
+
export interface DeskWindowsPluginOptions {
|
|
18
|
+
/** Replaces the helper starter. Tests only. */
|
|
19
|
+
start?: HelperStarter;
|
|
20
|
+
/** Replaces the helper command. Tests only. */
|
|
21
|
+
helperCommand?: readonly string[];
|
|
22
|
+
/** Environment the helper and shell commands start from. Tests only. */
|
|
23
|
+
env?: NodeJS.ProcessEnv;
|
|
24
|
+
/** Replaces `process.platform`. Tests only. */
|
|
25
|
+
platform?: NodeJS.Platform;
|
|
26
|
+
}
|
|
27
|
+
export declare function createDeskWindowsPlugin(options?: DeskWindowsPluginOptions): VibePluginFactory;
|
|
28
|
+
export declare const createPlugin: VibePluginFactory;
|
|
29
|
+
export default createPlugin;
|
|
30
|
+
export { UNMASKED_WARNING, WINDOWS_ACTIONS, WINDOWS_LIMITS, WindowsDeskBackend, } from "./backend.js";
|
|
31
|
+
export { defaultPowerShell, deskEnv, helperCommand, PASSED_ENV, } from "./env.js";
|
|
32
|
+
export { HelperError, type HelperInfo, WindowsHelper, WindowsUnavailableError, } from "./helper.js";
|
|
33
|
+
export { type KeyStroke, parseKeys } from "./keys.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{existsSync as existsSync2,readFileSync}from"fs";import{dirname as dirname3,join as joinPath,win32 as win322}from"path";import{fileURLToPath as fileURLToPath2}from"url";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
|
|
3
|
+
`);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(context)=>{if(onShutdown)await onShutdown(context)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var BoundLogger=class{logger;source;constructor(logger,source){this.logger=logger,this.source=source}info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};import{win32}from"path";var PASSED_ENV=["SystemRoot","SystemDrive","windir","ComSpec","PATH","PATHEXT","TEMP","TMP","USERPROFILE","USERNAME","USERDOMAIN","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","PROGRAMDATA","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","CommonProgramFiles(x86)","CommonProgramW6432","PUBLIC","ALLUSERSPROFILE","COMPUTERNAME","OS","PROCESSOR_ARCHITECTURE","NUMBER_OF_PROCESSORS","PSModulePath","LANG","TZ"],DEFAULT_SYSTEM_ROOT="C:\\Windows";function deskEnv(env){let byLowerName=new Map;for(let[key,value]of Object.entries(env))if(value!==void 0)byLowerName.set(key.toLowerCase(),value);let out={};for(let key of PASSED_ENV){let value=byLowerName.get(key.toLowerCase());if(value!==void 0)out[key]=value}if(!out.SystemRoot)out.SystemRoot=DEFAULT_SYSTEM_ROOT;return out}function systemRoot(env){let root=env.SystemRoot;return root&&win32.isAbsolute(root)&&!root.includes('"')?root:DEFAULT_SYSTEM_ROOT}function defaultPowerShell(env){return win32.join(systemRoot(env),"System32","WindowsPowerShell","v1.0","powershell.exe")}function defaultCmd(env){return win32.join(systemRoot(env),"System32","cmd.exe")}function defaultTaskkill(env){return win32.join(systemRoot(env),"System32","taskkill.exe")}function helperCommand(powershell,script){return[powershell,"-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",script]}import{spawn}from"child_process";import{constants}from"fs";import{lstat,mkdir,open}from"fs/promises";import{dirname}from"path";var FILE_LIMITS={maxShellOutput:65536},NO_FOLLOW=constants.O_NOFOLLOW??0,fail=(code,message)=>({ok:!1,error:{code,message}});function errnoOf(err){return typeof err==="object"&&err!==null&&"code"in err?String(err.code):void 0}function fileFailure(err,verb){switch(errnoOf(err)){case"ENOENT":return fail("TARGET_NOT_FOUND",`cannot ${verb}: no such file`);case"ELOOP":return fail("OUTSIDE_WORKSPACE_FOLDER",`cannot ${verb}: the path is a link`);case"EISDIR":return fail("TARGET_NOT_FOUND",`cannot ${verb}: the path is a folder`);case"EACCES":case"EPERM":case"EBUSY":return fail("TARGET_NOT_FOUND",`cannot ${verb}: access denied`);default:return fail("DESK_OFFLINE",`cannot ${verb}: ${errnoOf(err)??"file error"}`)}}async function refuseLink(path){try{if((await lstat(path)).isSymbolicLink())throw Object.assign(Error("the path is a link"),{code:"ELOOP"})}catch(err){if(errnoOf(err)==="ENOENT")return;throw err}}async function readConfinedFile(path,maxBytes){if(!path)return fail("OUTSIDE_WORKSPACE_FOLDER","no confined path was given");let handle;try{await refuseLink(path),handle=await open(path,constants.O_RDONLY|NO_FOLLOW)}catch(err){return fileFailure(err,"read the file")}try{let info=await handle.stat();if(!info.isFile())return fail("TARGET_NOT_FOUND","cannot read the file: not a regular file");let size=Math.max(0,Math.min(maxBytes,info.size)),buffer=Buffer.alloc(size),offset=0;while(offset<size){let{bytesRead}=await handle.read(buffer,offset,size-offset,offset);if(bytesRead===0)break;offset+=bytesRead}return{ok:!0,text:new TextDecoder("utf-8").decode(buffer.subarray(0,offset))}}catch(err){return fileFailure(err,"read the file")}finally{await handle.close()}}async function writeConfinedFile(path,content){if(!path)return fail("OUTSIDE_WORKSPACE_FOLDER","no confined path was given");let handle;try{await mkdir(dirname(path),{recursive:!0,mode:448}),await refuseLink(path),handle=await open(path,constants.O_WRONLY|constants.O_CREAT|constants.O_TRUNC|NO_FOLLOW,384)}catch(err){return fileFailure(err,"write the file")}try{let data=Buffer.from(content,"utf8");return await handle.writeFile(data),{ok:!0,text:`${data.length} bytes written`}}catch(err){return fileFailure(err,"write the file")}finally{await handle.close()}}var windowsShell={spawnSpec(command,env){return{file:defaultCmd(env),args:["/d","/s","/c",`"${command}"`],verbatim:!0}},killTree(pid,env){try{spawn(defaultTaskkill(env),["/PID",String(pid),"/T","/F"],{env,stdio:"ignore",windowsHide:!0}).on("error",()=>{})}catch{}}};function runShell(request){if(!request.cwd)return Promise.resolve(fail("OUTSIDE_WORKSPACE_FOLDER","no confined working folder was given"));if(request.signal.aborted)return Promise.resolve(fail("TIMEOUT","the action was aborted before it started"));let launcher=request.launcher??windowsShell,spec=launcher.spawnSpec(request.command,request.env);return new Promise((resolve)=>{let chunks=[],kept=0,truncated=!1,timedOut=!1,settled=!1,child=spawn(spec.file,spec.args,{cwd:request.cwd,env:request.env,stdio:["ignore","pipe","pipe"],windowsHide:!0,windowsVerbatimArguments:spec.verbatim}),stop=()=>{if(child.pid!==void 0)launcher.killTree(child.pid,request.env)},collect=(chunk)=>{if(kept>=FILE_LIMITS.maxShellOutput){truncated=!0;return}let room=FILE_LIMITS.maxShellOutput-kept;if(chunk.length>room)truncated=!0;let part=chunk.subarray(0,room);chunks.push(part),kept+=part.length};child.stdout?.on("data",collect),child.stderr?.on("data",collect);let timer=setTimeout(()=>{timedOut=!0,stop()},request.timeoutMs),onAbort=()=>stop();request.signal.addEventListener("abort",onAbort,{once:!0});let finish=(result)=>{if(settled)return;settled=!0,clearTimeout(timer),request.signal.removeEventListener("abort",onAbort),resolve(result)};child.on("error",(err)=>{finish(fail("DESK_OFFLINE",`cannot run the command: ${err.message}`))}),child.on("close",(code,signal)=>{if(timedOut){finish(fail("TIMEOUT",`the command did not finish in ${request.timeoutMs}ms`));return}if(request.signal.aborted){finish(fail("TIMEOUT","the command was stopped"));return}let output=Buffer.concat(chunks).toString("utf8"),status=code!==null?`exit ${code}`:`signal ${signal??"unknown"}`;finish({ok:code===0,text:`${status}
|
|
4
|
+
${output}${truncated?`
|
|
5
|
+
[output truncated]`:""}`})})})}import{spawn as spawn2}from"child_process";import{existsSync}from"fs";import{dirname as dirname2,join}from"path";import{fileURLToPath}from"url";class HelperError extends Error{code;constructor(code,message){super(message);this.code=code;this.name="HelperError"}}class WindowsUnavailableError extends Error{constructor(message){super(message);this.name="WindowsUnavailableError"}}var HELPER_LIMITS={startTimeoutMs:30000,abortGraceMs:2000,maxStderr:2000,maxLineBytes:67108864},HELPER_FILES={script:"desk_windows_helper.ps1",source:"DeskWindowsHelper.cs"};function helperScriptPath(from=dirname2(fileURLToPath(import.meta.url))){let candidates=[join(from,"..","helper",HELPER_FILES.script),join(from,"helper",HELPER_FILES.script)];return candidates.find((p)=>existsSync(p))??candidates[0]}var isRecord=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);class WindowsHelper{options;child=null;nextId=1;pending=new Map;buffered=[];bufferedBytes=0;stderr="";exited=!1;infoValue=null;onReady=null;constructor(options){this.options=options}static async start(options){let helper=new WindowsHelper(options);return await helper.launch(),helper}get info(){if(!this.infoValue)throw Error("the helper has not started");return this.infoValue}get alive(){return!this.exited}launch(){let[command,...args]=this.options.command;if(!command)return Promise.reject(new WindowsUnavailableError("no helper command"));let startTimeoutMs=this.options.startTimeoutMs??HELPER_LIMITS.startTimeoutMs;return new Promise((resolve,reject)=>{let done=!1,finish=(err)=>{if(done)return;if(done=!0,clearTimeout(timer),this.onReady=null,err)this.kill(),reject(err);else resolve()},timer=setTimeout(()=>finish(new WindowsUnavailableError(`the Windows desk helper did not start within ${startTimeoutMs}ms`)),startTimeoutMs);this.onReady=(line)=>{if(typeof line.fatal==="string"){finish(new WindowsUnavailableError(line.fatal));return}if(line.ready!==!0){finish(new WindowsUnavailableError("the Windows desk helper sent no ready line"));return}this.infoValue={width:Number(line.width),height:Number(line.height),left:Number(line.left??0),top:Number(line.top??0),uia:line.uia===!0,...typeof line.uiaError==="string"?{uiaError:line.uiaError}:{}},finish()};let child;try{child=spawn2(command,args,{env:this.options.env,stdio:["pipe","pipe","pipe"],windowsHide:!0})}catch(err){finish(new WindowsUnavailableError(`cannot start the Windows desk helper: ${err instanceof Error?err.message:String(err)}`));return}this.child=child,child.stdout?.on("data",(chunk)=>this.onData(chunk)),child.stderr?.on("data",(chunk)=>{this.stderr=(this.stderr+chunk.toString("utf8")).slice(-HELPER_LIMITS.maxStderr)}),child.stdin?.on("error",()=>{}),child.on("error",(err)=>{this.exited=!0,finish(new WindowsUnavailableError(`cannot start the Windows desk helper (${command}): ${err.message}`)),this.failAll("the Windows desk helper failed")}),child.on("exit",(code,signal)=>{this.exited=!0;let reason=this.stderr.trim().split(`
|
|
6
|
+
`).pop()?.trim();finish(new WindowsUnavailableError(`the Windows desk helper exited (${signal??`code ${code}`})${reason?`: ${reason.slice(0,300)}`:""}`)),this.failAll("the Windows desk helper stopped; it restarts on the next action")})})}onData(chunk){let start=0,newline=chunk.indexOf(10);while(newline!==-1){this.buffered.push(chunk.subarray(start,newline));let line=Buffer.concat(this.buffered).toString("utf8");this.buffered=[],this.bufferedBytes=0,this.onLine(line),start=newline+1,newline=chunk.indexOf(10,start)}if(start<chunk.length){if(this.buffered.push(chunk.subarray(start)),this.bufferedBytes+=chunk.length-start,this.bufferedBytes>HELPER_LIMITS.maxLineBytes)this.buffered=[],this.bufferedBytes=0,this.failAll("the Windows desk helper sent an oversized reply"),this.kill()}}onLine(line){if(!line.trim())return;let parsed;try{parsed=JSON.parse(line)}catch{return}if(!isRecord(parsed))return;if(this.onReady){this.onReady(parsed);return}let id=parsed.id;if(typeof id!=="number")return;let entry=this.pending.get(id);if(!entry)return;if(this.pending.delete(id),entry.settled)return;if(entry.settled=!0,parsed.ok===!0){let reply={...parsed};delete reply.id,delete reply.ok,entry.resolve(reply);return}let code=parsed.code==="TARGET_NOT_FOUND"?"TARGET_NOT_FOUND":"DESK_OFFLINE",message=typeof parsed.message==="string"?parsed.message.slice(0,500):"the Windows desk helper refused the request";entry.reject(new HelperError(code,message))}failAll(message){for(let[id,entry]of this.pending)if(this.pending.delete(id),!entry.settled)entry.settled=!0,entry.reject(new HelperError("DESK_OFFLINE",message))}request(op,args={},signal){let child=this.child;if(this.exited||!child?.stdin)return Promise.reject(new HelperError("DESK_OFFLINE","the Windows desk helper is not running"));if(signal?.aborted)return Promise.reject(new HelperError("DESK_OFFLINE","the action was aborted"));let id=this.nextId++;return new Promise((resolve,reject)=>{let onAbort,detach=()=>{if(onAbort)signal?.removeEventListener("abort",onAbort)},entry={resolve:(reply)=>{detach(),resolve(reply)},reject:(err)=>{detach(),reject(err)},settled:!1};if(this.pending.set(id,entry),signal)onAbort=()=>{if(entry.settled)return;entry.settled=!0,reject(new HelperError("DESK_OFFLINE","the action was aborted")),setTimeout(()=>{if(this.pending.has(id))this.failAll("the Windows desk helper stopped answering"),this.kill()},this.options.abortGraceMs??HELPER_LIMITS.abortGraceMs).unref?.()},signal.addEventListener("abort",onAbort,{once:!0});child.stdin?.write(`${JSON.stringify({...args,op,id})}
|
|
7
|
+
`)})}kill(){this.exited=!0,this.failAll("the Windows desk helper was stopped");let child=this.child;if(child&&child.exitCode===null&&child.signalCode===null)child.stdin?.end(),child.kill("SIGTERM"),setTimeout(()=>{if(child.exitCode===null&&child.signalCode===null)child.kill("SIGKILL")},1000).unref?.()}}var KEY_LIMITS={maxCombos:32,maxKeysPerCombo:6},vk=(code,ext=!1)=>({vk:code,ext}),NAMED_KEYS={enter:vk(13),return:vk(13),escape:vk(27),esc:vk(27),backspace:vk(8),tab:vk(9),delete:vk(46,!0),del:vk(46,!0),insert:vk(45,!0),home:vk(36,!0),end:vk(35,!0),pageup:vk(33,!0),page_up:vk(33,!0),pagedown:vk(34,!0),page_down:vk(34,!0),arrowup:vk(38,!0),up:vk(38,!0),arrowdown:vk(40,!0),down:vk(40,!0),arrowleft:vk(37,!0),left:vk(37,!0),arrowright:vk(39,!0),right:vk(39,!0),space:vk(32),control:vk(162),ctrl:vk(162),controlleft:vk(162),controlright:vk(163,!0),shift:vk(160),shiftleft:vk(160),shiftright:vk(161),alt:vk(164),altleft:vk(164),altright:vk(165,!0),altgraph:vk(165,!0),meta:vk(91,!0),metaleft:vk(91,!0),metaright:vk(92,!0),super:vk(91,!0),win:vk(91,!0),windows:vk(91,!0),cmd:vk(91,!0),command:vk(91,!0),capslock:vk(20),numlock:vk(144,!0),scrolllock:vk(145),printscreen:vk(44,!0),print:vk(44,!0),pause:vk(19),contextmenu:vk(93,!0),menu:vk(93,!0)},notFound=(message)=>new HelperError("TARGET_NOT_FOUND",message),quoted=(value)=>JSON.stringify(value).slice(0,40);function splitCombo(combo){if(combo==="+")return["+"];if(combo.endsWith("++")){let head=combo.slice(0,-2);return[...head?head.split("+"):[],"+"]}let parts=combo.split("+");if(parts.some((p)=>p===""))throw notFound(`malformed key combination ${quoted(combo)}`);return parts}function keyStroke(name){let named=NAMED_KEYS[name.toLowerCase()];if(named)return named;let fn=/^[Ff]([1-9]|1[0-9]|2[0-4])$/.exec(name);if(fn)return vk(111+Number(fn[1]));if([...name].length===1){let code=name.codePointAt(0)??0;if(code<32||code===127)throw notFound(`cannot press control character U+${code.toString(16).toUpperCase().padStart(4,"0")}`);if(/^[A-Za-z]$/.test(name))return vk(name.toUpperCase().charCodeAt(0));if(/^[0-9]$/.test(name))return vk(name.charCodeAt(0));return{char:name}}throw notFound(`unknown key ${quoted(name)}`)}function parseCombo(combo){let parts=splitCombo(combo);if(parts.length>KEY_LIMITS.maxKeysPerCombo)throw notFound(`key combination ${quoted(combo)} has more than ${KEY_LIMITS.maxKeysPerCombo} keys`);let strokes=parts.map(keyStroke);if(parts.length===1&&/^[A-Z]$/.test(parts[0]))return[NAMED_KEYS.shift,strokes[0]];return strokes}function parseKeys(keys){if(keys.length===0)throw notFound("no keys were given");if(keys.length>KEY_LIMITS.maxCombos)throw notFound(`more than ${KEY_LIMITS.maxCombos} key combinations`);return keys.map(parseCombo)}function checkTypedText(text){for(let char of text){let code=char.codePointAt(0)??0;if(code<32&&char!==`
|
|
8
|
+
`&&char!=="\r"&&char!=="\t"||code===127)throw notFound(`cannot type control character U+${code.toString(16).toUpperCase().padStart(4,"0")}`)}return text.replace(/\r\n?/g,`
|
|
9
|
+
`)}var SCROLL_STEP_PIXELS=100,MAX_SCROLL_NOTCHES=100;function scrollNotches(pixels){if(!Number.isFinite(pixels)||pixels===0)return 0;let notches=Math.round(pixels/SCROLL_STEP_PIXELS),atLeastOne=notches===0?Math.sign(pixels):notches;return Math.max(-MAX_SCROLL_NOTCHES,Math.min(MAX_SCROLL_NOTCHES,atLeastOne))}var WINDOWS_ACTIONS=["screenshot","snapshot","click","type","key","scroll","focus_window","shell","read_file","write_file"],WINDOWS_LIMITS={maxElements:500,maxText:20000},fail2=(code,message)=>({ok:!1,error:{code,message}});function targetArg(target){switch(target.by){case"ref":return{by:"ref",ref:target.ref};case"point":return{by:"point",x:target.x,y:target.y};case"window":return target.title===void 0?{by:"window",app:target.app}:{by:"window",app:target.app,title:target.title}}}var UNMASKED_WARNING="secret fields were not masked: UI Automation is unavailable";class WindowsDeskBackend{options;kind="windows";actions=WINDOWS_ACTIONS;helper=null;starting=null;closed=!1;env;constructor(options={}){this.options=options;this.env=deskEnv(options.env??process.env)}get helperCommand(){return this.options.helperCommand??helperCommand(this.options.powershell??defaultPowerShell(this.env),helperScriptPath())}async connect(){return(await this.ensureHelper()).info}async act(action,context){if(this.closed)return fail2("DESK_OFFLINE","the Windows desk is stopped");try{switch(action.type){case"read_file":return await readConfinedFile(context.paths.path,action.maxBytes);case"write_file":return await writeConfinedFile(context.paths.path,action.content);case"shell":return await runShell({command:action.command,cwd:context.paths.cwd,timeoutMs:action.timeoutMs,env:this.env,signal:context.signal,...this.options.shell?{launcher:this.options.shell}:{}});default:return await this.screenAction(action,context.signal)}}catch(err){if(err instanceof HelperError)return fail2(err.code,err.message);if(err instanceof WindowsUnavailableError)return fail2("DESK_OFFLINE",err.message);return fail2("DESK_OFFLINE",(err instanceof Error?err.message:String(err)).slice(0,200))}}async close(){this.closed=!0;let starting=this.starting;if(this.starting=null,this.helper?.kill(),this.helper=null,starting)try{(await starting).kill()}catch{}}ensureHelper(){if(this.closed)return Promise.reject(new WindowsUnavailableError("the Windows desk is stopped"));if(this.helper?.alive)return Promise.resolve(this.helper);if(this.helper=null,!this.starting){let start=this.options.start??WindowsHelper.start;this.starting=start({command:this.helperCommand,env:this.env,...this.options.startTimeoutMs!==void 0?{startTimeoutMs:this.options.startTimeoutMs}:{},...this.options.abortGraceMs!==void 0?{abortGraceMs:this.options.abortGraceMs}:{}}).then((helper)=>{if(this.closed)throw helper.kill(),new WindowsUnavailableError("the Windows desk is stopped");return this.helper=helper,helper}).finally(()=>{this.starting=null})}return this.starting}async screenAction(action,signal){let keys=action.type==="key"?parseKeys(action.keys):null,text=action.type==="type"?checkTypedText(action.text):null,helper=await this.ensureHelper(),call=(op,args={})=>helper.request(op,args,signal);switch(action.type){case"screenshot":{let reply=await call("screenshot"),png=typeof reply.png==="string"?reply.png:"";if(!png)return fail2("DESK_OFFLINE","the screenshot was empty");return{ok:!0,screenshotPng:new Uint8Array(Buffer.from(png,"base64")),...typeof reply.unmasked==="string"?{text:UNMASKED_WARNING}:{}}}case"snapshot":{let reply=await call("snapshot");return{ok:!0,snapshot:reply.snapshot,text:typeof reply.text==="string"?reply.text:""}}case"click":return await call("click",{target:targetArg(action.target),button:action.button??"left",count:action.count??1}),{ok:!0};case"type":return await call("type",{text,...action.target?{target:targetArg(action.target)}:{}}),{ok:!0};case"key":return await call("key",{combos:keys}),{ok:!0};case"scroll":return await call("scroll",{notchesX:scrollNotches(action.dx),notchesY:scrollNotches(action.dy),...action.target?{target:targetArg(action.target)}:{}}),{ok:!0};case"focus_window":{let reply=await call("focus_window",{app:action.app,...action.title!==void 0?{title:action.title}:{}});return{ok:!0,...typeof reply.title==="string"?{text:reply.title}:{}}}default:return fail2("DESK_OFFLINE",`a Windows desk cannot ${action.type}`)}}}var PLUGIN_NAME="desk-windows",PLUGIN_PACKAGE_NAME="@vibecontrols/vibe-plugin-desk-windows",PLUGIN_VERSION=getPluginVersion(),DESK_PROVIDER_TYPE="desk",DESK_WINDOWS_CONFIG={powershell:"desk-windows.powershell"};function getPluginVersion(){try{let dir=dirname3(fileURLToPath2(import.meta.url));for(let i=0;i<10&&dir&&dir!==dirname3(dir);i++){let pkgPath=joinPath(dir,"package.json");if(existsSync2(pkgPath))try{let pkg=JSON.parse(readFileSync(pkgPath,"utf8"));if(pkg.name===PLUGIN_PACKAGE_NAME&&typeof pkg.version==="string")return pkg.version}catch{}dir=dirname3(dir)}}catch{}return"0.0.0"}class NotWindowsError extends Error{constructor(platform){super(`desk-windows runs only on Windows (this is ${platform})`);this.name="NotWindowsError"}}function parsePowerShell(value){if(!value)return;if(!win322.isAbsolute(value)||value.includes('"'))return;return/(^|\\)powershell\.exe$/i.test(value)?value:void 0}function describeScreen(info){let accessibility=info.uia?"UI Automation on":`UI Automation off: ${info.uiaError??"unavailable"}`;return`${info.width}x${info.height} at (${info.left}, ${info.top}), ${accessibility}`}function createDeskWindowsPlugin(options={}){return(ctx)=>{let log=new BoundLogger(ctx.logger,PLUGIN_NAME),backend=null,lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"desk-windows.ready",onInit:async(host)=>{let platform=options.platform??process.platform;if(platform!=="win32"){let err=new NotWindowsError(platform);throw log.error(err.message),err}let configured=(await host.getConfig?.(DESK_WINDOWS_CONFIG.powershell))?.trim(),powershell=parsePowerShell(configured);if(configured&&!powershell)log.warn(`${DESK_WINDOWS_CONFIG.powershell} is not an absolute path to powershell.exe; using the default`);let candidate=new WindowsDeskBackend({...powershell?{powershell}:{},...options.env?{env:options.env}:{},...options.start?{start:options.start}:{},...options.helperCommand?{helperCommand:options.helperCommand}:{}}),info;try{info=await candidate.connect()}catch(err){await candidate.close();let reason=err instanceof Error?err.message:String(err);throw log.error(`Windows desk not started: ${reason}`),Error(`desk-windows cannot start: ${reason}`,{cause:err})}if(backend=candidate,host.serviceRegistry?.registerProvider?.(DESK_PROVIDER_TYPE,candidate,PLUGIN_NAME),log.info(`Windows desk registered (${describeScreen(info)})`),!info.uia)log.warn("snapshots and refs are unavailable without UI Automation; screenshots are returned unmasked with a warning")},onShutdown:async(context)=>{let current=backend;backend=null,await current?.close(),log.info(`Windows desk stopped (${context?.reason??"shutdown"})`)}});return{name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Steward desk provider: a Windows desktop driven through the desk API with UI Automation",tags:["backend","provider"],capabilities:{telemetry:!0},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}}}var createPlugin=createDeskWindowsPlugin(),src_default=createPlugin;export{DESK_PROVIDER_TYPE,DESK_WINDOWS_CONFIG,HelperError,NotWindowsError,PASSED_ENV,UNMASKED_WARNING,WINDOWS_ACTIONS,WINDOWS_LIMITS,WindowsDeskBackend,WindowsHelper,WindowsUnavailableError,createDeskWindowsPlugin,createPlugin,src_default as default,defaultPowerShell,deskEnv,helperCommand,parseKeys,parsePowerShell};
|
package/dist/keys.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** A virtual-key press, or a character the helper maps with `VkKeyScanW`. */
|
|
2
|
+
export type KeyStroke = {
|
|
3
|
+
vk: number;
|
|
4
|
+
ext: boolean;
|
|
5
|
+
} | {
|
|
6
|
+
char: string;
|
|
7
|
+
};
|
|
8
|
+
export declare const KEY_LIMITS: {
|
|
9
|
+
/** Combinations in one `key` action. */
|
|
10
|
+
readonly maxCombos: 32;
|
|
11
|
+
/** Keys in one combination. */
|
|
12
|
+
readonly maxKeysPerCombo: 6;
|
|
13
|
+
};
|
|
14
|
+
/** `Control+Shift+a` -> [Control, Shift, a]; a literal `+` key is kept. */
|
|
15
|
+
export declare function splitCombo(combo: string): string[];
|
|
16
|
+
/**
|
|
17
|
+
* One key name to a stroke. A single letter or digit is its virtual key
|
|
18
|
+
* (so `Control+a` is select-all whatever the keyboard layout); an upper
|
|
19
|
+
* case letter on its own adds Shift in {@link parseCombo}. Any other single
|
|
20
|
+
* character is left to the helper's keyboard layout.
|
|
21
|
+
*/
|
|
22
|
+
export declare function keyStroke(name: string): KeyStroke;
|
|
23
|
+
/** One combination to the strokes to press, held keys first. */
|
|
24
|
+
export declare function parseCombo(combo: string): KeyStroke[];
|
|
25
|
+
/** Every combination of a `key` action, checked before anything is pressed. */
|
|
26
|
+
export declare function parseKeys(keys: readonly string[]): KeyStroke[][];
|
|
27
|
+
/**
|
|
28
|
+
* Text for `type`: refuses control characters other than newline, carriage
|
|
29
|
+
* return and tab, which the helper presses as Enter and Tab (`\r\n` is one
|
|
30
|
+
* Enter).
|
|
31
|
+
*/
|
|
32
|
+
export declare function checkTypedText(text: string): string;
|
|
33
|
+
/** Pixels per wheel notch for `scroll`, as on the X11 desk. */
|
|
34
|
+
export declare const SCROLL_STEP_PIXELS = 100;
|
|
35
|
+
/** Most notches one `scroll` sends on each axis. */
|
|
36
|
+
export declare const MAX_SCROLL_NOTCHES = 100;
|
|
37
|
+
/**
|
|
38
|
+
* Pixels to wheel notches. Any movement is at least one notch, so a small
|
|
39
|
+
* scroll still scrolls. Positive is down (dy) or right (dx).
|
|
40
|
+
*/
|
|
41
|
+
export declare function scrollNotches(pixels: number): number;
|