@devries-cameron20 / composio Mirror · read-only / commits / f9bc32519
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

feat(cli): add experimental Windows x64 support (#5306)

## Summary Windows x64 users can install, run, and upgrade the standalone CLI without WSL. Windows support is **experimental**: it is built and checked natively on every CLI release, but a failed Windows check does not block the release. ```powershell irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex ``` Designated PR reviewer: [@jkomyno](mailto:alberto@composio.dev). ## Changes - Publish `composio-windows-x64.zip` with `composio.exe` and the complete companion bundle. - Install with a PowerShell one-liner. `install.ps1` verifies the SHA-256 checksum, adds the bundle to the User PATH and the current session, and preserves existing credentials and configuration. It is configured through `COMPOSIO_INSTALL_VERSION`, `COMPOSIO_INSTALL_DIR`, and `COMPOSIO_INSTALL_SHELL=none`, like `install.sh`. - Use native filesystem paths and support running-executable replacement, companion execution, and repair on Windows. - Announce new versions on Windows, link the CLI skill with a junction (no Developer Mode or administrator rights needed), and make `composio install` explain that shell setup is unavailable. - Add a Windows Credential Manager keyring backend (`bun:ffi` into `advapi32.dll`), so the opt-in `keychain` security modes work on Windows. The default stays the same as on macOS and Linux. - Locate agent CLIs on `PATH` on Windows and run npm's `.cmd` shims through a shell, so `composio setup` finds an npm-installed `claude` or `codex`. - Suggest a PowerShell command when a pending login is missing or expired. - Cross-compile with the locked toolchain on Ubuntu, then test that exact archive on `windows-2025`. If that check fails, the release ships without the Windows archive and the post-release Windows installation test is skipped. - Define release targets once for the CLI build scripts and share the compile step. ## Type of change - [x] New feature - [x] Documentation - [ ] Breaking change ## How Has This Been Tested? - Native Windows verification [passed on commit `30d6fcc`](https://github.com/ComposioHQ/composio/actions/runs/42932100812). It runs the documented `irm … | iex` flow against a local release server and covers: - a pinned install from Windows PowerShell 5.1 into a path with spaces, and a reinstall from 32-bit PowerShell that keeps user data; - rejection of a corrupt checksum, and a default (latest stable) install that lands on PATH exactly once; - `--version`, `--help`, inline and file `composio run`, two self-upgrades with executable replacement, a locked backup blocking both upgrade paths, and companion repair; - `composio setup skill claude` twice (junction), `composio setup` against a `claude.cmd` shim in a path with spaces, a Credential Manager roundtrip, and `composio install`. - `pnpm typecheck` and `pnpm lint:effect` for the CLI: no errors. - `pnpm test` for the CLI: 2961 tests passed. - `pnpm test:release-workflow`: passed, including a release without the unverified Windows archive and rejection of a missing archive when Windows was verified. - `pnpm test:install-sh`: passed under `sh` and `dash`. - The refactored build scripts cross-compiled and packaged a Windows x64 archive locally. The Vercel docs preview fails on an inherited check that is unrelated to this change. ## Screenshots (if applicable) Not applicable: CLI binaries and release workflows. ## Checklist - [ ] I have read the Code of Conduct and this PR adheres to it - [ ] I have read and understand every line of this diff - [x] Any third-party docs links follow the repository policy - [x] I ran relevant linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests for changed behavior - [x] Changeset applicability checked: the private CLI is ignored by Changesets ## Additional context Bun [supports Windows x64 compiled executables](https://bun.sh/docs/compiler/executables). GitHub's standard [`windows-2025` runner is free for public repositories](https://docs.github.com/en/actions/reference/runners/github-hosted-runners), including this repository. Windows support requires Windows 10 1809+ and an SSE4.2-capable x64 CPU. Known limitations: - Shell completions support only zsh, bash, and fish. - Commands other than those listed above are not exercised on Windows. New runtime boundary: `src/effects/install-skill.ts` imports `symlink` from `node:fs/promises`, because Effect's `FileSystem.symlink` cannot create a junction. It is registered in `lint-boundaries.json`. ARM64 distribution is outside this change. A `composio.dev/install.ps1` redirect would shorten the install command; it lives outside this repository. <!-- sdk-release-note-exempt: CLI-only platform support, release automation, installation, and documentation changes do not alter the published SDKs. -->

Alberto Schiabel committed Nov 13, 2026 at 11:36 UTC f9bc325195228618d9600bc3eb1d711dbd004e5e
51 files changed +1634 -275
.agents/skills/cli-release/references/release-workflow.md
+3 -2
@@ -71,12 +71,13 @@ gh release view "$BETA_TAG" \
71 --jq '{tagName,isDraft,isPrerelease,publishedAt,targetCommitish,assets:[.assets[] | {name,state}]}'
72 ```
73
74 -The beta must have `isDraft: false`, `isPrerelease: true`, and these six assets in `uploaded` state:
74 +The beta must have `isDraft: false`, `isPrerelease: true`, and these seven assets in `uploaded` state:
75
76 - `composio-linux-x64.zip`
77 - `composio-linux-aarch64.zip`
78 - `composio-darwin-x64.zip`
79 - `composio-darwin-aarch64.zip`
80 +- `composio-windows-x64.zip` (experimental: absent when the `Windows x64` job failed, which does not block the release)
81 - `composio-skill.zip`
82 - `checksums.txt`
83
@@ -164,7 +165,7 @@ Do not call the release complete until all of these are true:
165
166 1. `Build CLI Binaries` completed successfully.
167 2. The stable release is published with `isDraft: false` and `isPrerelease: false`.
167 -3. All six canonical assets are present and uploaded.
168 +3. All seven canonical assets are present and uploaded, or six when the experimental `Windows x64` job failed.
169 4. The workflow's installation-test matrix passed.
170
171 ```bash
.github/scripts/cli-release/create-or-resume-draft.sh
+9
@@ -28,6 +28,15 @@ fi
28 # its assets. Refuse to mutate a tag that is already published.
29 if gh release view "$RELEASE_TAG" --json isDraft --jq '.isDraft' 2>/dev/null | grep -qx true; then
30 echo "Draft $RELEASE_TAG already exists — re-uploading assets with --clobber"
31 + # An earlier attempt may have attached an asset this run does not ship, such as a Windows
32 + # archive that has since failed its checks. The new checksums.txt does not cover it, so
33 + # remove it instead of publishing it.
34 + while IFS= read -r asset; do
35 + if [[ ! -e "$binaries_dir/$asset" ]]; then
36 + echo "Removing stale asset $asset from draft $RELEASE_TAG"
37 + gh release delete-asset "$RELEASE_TAG" "$asset" --yes
38 + fi
39 + done < <(gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name')
40 gh release upload "$RELEASE_TAG" \
41 "$binaries_dir"/*.zip \
42 "$binaries_dir/checksums.txt" --clobber
.github/scripts/cli-release/test-windows.ps1 new
+266
@@ -0,0 +1,266 @@
1 +# Checks a Windows x64 CLI archive on a real Windows machine: the documented installer
2 +# one-liner, the native binary, companion modules, self-upgrade, and repair.
3 +# A local server stands in for GitHub and serves install.ps1 plus the archive under test.
4 +param(
5 + [Parameter(Mandatory)][string]$ArchivePath,
6 + [Parameter(Mandatory)][string]$ExpectedVersion
7 +)
8 +$ErrorActionPreference = 'Stop'
9 +$ArchivePath = (Resolve-Path -LiteralPath $ArchivePath).Path
10 +$testRoot = Join-Path ([IO.Path]::GetTempPath()) "composio windows $([Guid]::NewGuid())"
11 +$envNames = @(
12 + 'BUN_BE_BUN', 'COMPOSIO_CACHE_DIR', 'COMPOSIO_DISABLE_TELEMETRY', 'COMPOSIO_GITHUB_API_BASE_URL', 'COMPOSIO_INSTALL_DIR',
13 + 'COMPOSIO_INSTALL_SHELL', 'COMPOSIO_INSTALL_VERSION', 'COMPOSIO_USER_API_KEY', 'COMPOSIO_WINDOWS_SMOKE_ARCHIVE',
14 + 'COMPOSIO_WINDOWS_SMOKE_INSTALLER', 'COMPOSIO_WINDOWS_SMOKE_PORT', 'COMPOSIO_WINDOWS_SMOKE_SKILL', 'COMPOSIO_WINDOWS_SMOKE_TAG',
15 + 'USERPROFILE'
16 +)
17 +$savedEnv = @{}
18 +foreach ($name in $envNames) { $savedEnv[$name] = [Environment]::GetEnvironmentVariable($name) }
19 +$savedUserPath = [Environment]::GetEnvironmentVariable('Path', 'User')
20 +$server = $null
21 +
22 +function Assert([bool]$Condition, [string]$Message) {
23 + if (-not $Condition) { throw $Message }
24 +}
25 +
26 +# Runs the documented one-liner in a fresh shell. COMPOSIO_INSTALL_* variables configure it.
27 +function Invoke-Installer([string]$Shell = 'powershell', [string]$Then = '') {
28 + & $Shell -NoProfile -Command "irm $baseUrl/install.ps1 | iex; $Then"
29 +}
30 +
31 +function Invoke-Cli([string[]]$Arguments) {
32 + $output = & $binary @Arguments
33 + Assert ($LASTEXITCODE -eq 0) "CLI failed ($LASTEXITCODE): $Arguments"
34 + return ($output -join "`n").Trim()
35 +}
36 +
37 +function Get-Sha256([string]$Path) {
38 + return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash
39 +}
40 +
41 +New-Item -ItemType Directory -Path $testRoot | Out-Null
42 +try {
43 + # The compiled CLI doubles as a Bun runtime (BUN_BE_BUN), so it can serve its own release.
44 + # The first path segment of the API base URL selects a scenario:
45 + # /stable lists a stable release behind a newer beta, for the default (latest) install
46 + # /corrupt publishes a checksum that does not match the archive
47 + # /skill adds the CLI skill bundle to the release
48 + $source = Join-Path $testRoot 'source'
49 + Expand-Archive -LiteralPath $ArchivePath -DestinationPath $source
50 + $serverFile = Join-Path $testRoot 'release-server.mjs'
51 + $portFile = Join-Path $testRoot 'port.txt'
52 + @'
53 +const archive = Bun.file(process.env.COMPOSIO_WINDOWS_SMOKE_ARCHIVE);
54 +const hash = new Bun.CryptoHasher('sha256').update(await archive.arrayBuffer()).digest('hex');
55 +const tag = process.env.COMPOSIO_WINDOWS_SMOKE_TAG;
56 +const text = body => new Response(body, {headers: {'content-type': 'text/plain; charset=utf-8'}});
57 +const server = Bun.serve({
58 + hostname: '127.0.0.1', port: 0,
59 + async fetch(request) {
60 + const {origin, pathname} = new URL(request.url);
61 + if (pathname === '/install.ps1') return text(await Bun.file(process.env.COMPOSIO_WINDOWS_SMOKE_INSTALLER).text());
62 + if (pathname === '/cli.zip') return new Response(archive);
63 + if (pathname === '/skill.zip') return new Response(Bun.file(process.env.COMPOSIO_WINDOWS_SMOKE_SKILL));
64 + if (pathname === '/checksums.txt') return text(`${hash} composio-windows-x64.zip\n`);
65 + if (pathname === '/corrupt-checksums.txt') return text(`${'0'.repeat(64)} composio-windows-x64.zip\n`);
66 + const release = (tagName, checksums = 'checksums.txt') => ({
67 + tag_name: tagName, name: tagName, draft: false, prerelease: tagName.includes('-beta.'),
68 + assets: [
69 + {name: 'composio-windows-x64.zip', size: archive.size, browser_download_url: `${origin}/cli.zip`},
70 + {name: 'checksums.txt', browser_download_url: `${origin}/${checksums}`}
71 + ]});
72 + if (pathname.startsWith('/corrupt/')) return Response.json(release(tag, 'corrupt-checksums.txt'));
73 + if (pathname.startsWith('/skill/')) {
74 + const withSkill = release(tag);
75 + withSkill.assets.push({name: 'composio-skill.zip', browser_download_url: `${origin}/skill.zip`});
76 + return Response.json(withSkill);
77 + }
78 + if (pathname.includes('/releases/tags/')) return Response.json(release(tag));
79 + if (pathname.startsWith('/stable/')) return Response.json([release('@composio/cli@9.9.9-beta.1'), release('@composio/cli@1.2.3')]);
80 + if (pathname.endsWith('/releases')) return Response.json([release(tag)]);
81 + return new Response('not found', {status: 404});
82 + }
83 +});
84 +await Bun.write(process.env.COMPOSIO_WINDOWS_SMOKE_PORT, String(server.port));
85 +'@ | Set-Content -LiteralPath $serverFile
86 + $env:COMPOSIO_WINDOWS_SMOKE_ARCHIVE = $ArchivePath
87 + $env:COMPOSIO_WINDOWS_SMOKE_INSTALLER = (Resolve-Path -LiteralPath "$PSScriptRoot/../../../install.ps1").Path
88 + $env:COMPOSIO_WINDOWS_SMOKE_PORT = $portFile
89 + $skillSource = Join-Path $testRoot 'skill/composio-cli'
90 + New-Item -ItemType Directory -Path $skillSource -Force | Out-Null
91 + Set-Content -LiteralPath (Join-Path $skillSource 'SKILL.md') -Value '# fixture skill'
92 + $env:COMPOSIO_WINDOWS_SMOKE_SKILL = Join-Path $testRoot 'composio-skill.zip'
93 + Compress-Archive -Path $skillSource -DestinationPath $env:COMPOSIO_WINDOWS_SMOKE_SKILL
94 + $env:COMPOSIO_WINDOWS_SMOKE_TAG = "@composio/cli@$ExpectedVersion"
95 + $env:BUN_BE_BUN = '1'
96 + $server = Start-Process -FilePath (Join-Path $source 'composio-windows-x64/composio.exe') -ArgumentList @('"' + $serverFile + '"') -PassThru -RedirectStandardError (Join-Path $testRoot 'server.err')
97 + Remove-Item Env:BUN_BE_BUN
98 + for ($attempt = 0; $attempt -lt 100 -and -not (Test-Path -LiteralPath $portFile); $attempt++) {
99 + if ($server.HasExited) { throw "Release fixture server failed: $(Get-Content -LiteralPath (Join-Path $testRoot 'server.err') -Raw)" }
100 + Start-Sleep -Milliseconds 100
101 + }
102 + Assert (Test-Path -LiteralPath $portFile) 'Release fixture server did not start.'
103 + $baseUrl = "http://127.0.0.1:$(Get-Content -LiteralPath $portFile)"
104 +
105 + $installDir = Join-Path $testRoot 'installed CLI'
106 + $binary = Join-Path $installDir 'composio.exe'
107 + $env:COMPOSIO_GITHUB_API_BASE_URL = $baseUrl
108 + $env:COMPOSIO_CACHE_DIR = Join-Path $testRoot 'isolated config'
109 + $env:COMPOSIO_DISABLE_TELEMETRY = '1'
110 + $env:COMPOSIO_USER_API_KEY = 'test-dummy-api-key-for-ci'
111 + $env:COMPOSIO_INSTALL_DIR = $installDir
112 + $env:COMPOSIO_INSTALL_VERSION = $ExpectedVersion
113 + $env:COMPOSIO_INSTALL_SHELL = 'none'
114 +
115 + # Install a pinned version from Windows PowerShell 5.1, into a path with spaces.
116 + Invoke-Installer | Out-Host
117 + Assert ($LASTEXITCODE -eq 0) 'Windows PowerShell installation failed.'
118 + Assert ((Invoke-Cli @('--version')) -eq $ExpectedVersion) 'Unexpected baked CLI version.'
119 + Invoke-Cli @('--help') | Out-Host
120 + Assert ((Invoke-Cli @('run', 'console.log("windows-inline-ok")')) -eq 'windows-inline-ok') 'Inline companion execution failed.'
121 + $scriptFile = Join-Path $testRoot 'script with spaces.ts'
122 + Set-Content -LiteralPath $scriptFile -Value 'console.log("windows-file-ok");'
123 + Assert ((Invoke-Cli @('run', '--file', $scriptFile)) -eq 'windows-file-ok') 'File companion execution failed.'
124 + $expectedBinaryHash = Get-Sha256 $binary
125 +
126 + # Reinstalling keeps user data. 32-bit PowerShell on x64 Windows is a supported host.
127 + $userData = Join-Path $installDir 'user_data.json'
128 + Set-Content -LiteralPath $userData -Value 'preserve credentials'
129 + Invoke-Installer -Shell (Join-Path $env:WINDIR 'SysWOW64/WindowsPowerShell/v1.0/powershell.exe') | Out-Host
130 + Assert ($LASTEXITCODE -eq 0) '32-bit PowerShell reinstallation failed.'
131 + Assert ((Get-Content -LiteralPath $userData) -eq 'preserve credentials') 'Reinstallation did not preserve user data.'
132 + Assert ((Get-Sha256 $binary) -eq $expectedBinaryHash) 'Reinstallation did not restore the executable.'
133 +
134 + # A checksum mismatch aborts before the installation is touched.
135 + Set-Content -LiteralPath $binary -Value 'installed before the corrupt download'
136 + $env:COMPOSIO_GITHUB_API_BASE_URL = "$baseUrl/corrupt"
137 + $output = Invoke-Installer 2>&1 | Out-String
138 + Assert ($LASTEXITCODE -ne 0 -and $output -like '*Checksum mismatch*') "Expected a checksum mismatch, got: $output"
139 + Assert ((Get-Content -LiteralPath $binary) -eq 'installed before the corrupt download') 'A corrupt download modified the executable.'
140 +
141 + # A remote server must use HTTPS: it supplies both the archive and its checksum.
142 + foreach ($untrusted in 'http://example.com', 'https://user:secret@example.com') {
143 + $env:COMPOSIO_GITHUB_API_BASE_URL = $untrusted
144 + $output = Invoke-Installer 2>&1 | Out-String
145 + Assert ($LASTEXITCODE -ne 0 -and $output -like '*Refusing to download*') "Expected $untrusted to be refused, got: $output"
146 + }
147 +
148 + # With no version, the installer picks the latest stable release and puts it on PATH,
149 + # both for the current session and, exactly once, for the user.
150 + $latestDir = Join-Path $testRoot 'latest install'
151 + $env:COMPOSIO_GITHUB_API_BASE_URL = "$baseUrl/stable"
152 + $env:COMPOSIO_INSTALL_DIR = $latestDir
153 + Remove-Item Env:COMPOSIO_INSTALL_VERSION, Env:COMPOSIO_INSTALL_SHELL
154 + foreach ($attempt in 1..2) {
155 + $output = Invoke-Installer -Then 'composio --version'
156 + Assert ($LASTEXITCODE -eq 0) "Default installation failed: $output"
157 + Assert (($output -join "`n") -like '*Installed @composio/cli@1.2.3*') 'The installer did not pick the latest stable release.'
158 + Assert ($output[-1].Trim() -eq $ExpectedVersion) 'composio was not on PATH after installation.'
159 + }
160 + $userPathEntries = [Environment]::GetEnvironmentVariable('Path', 'User') -split ';'
161 + Assert (@($userPathEntries | Where-Object { $_ -eq $latestDir }).Count -eq 1) 'The User PATH entry is missing or duplicated.'
162 +
163 + $env:COMPOSIO_GITHUB_API_BASE_URL = $baseUrl
164 + $env:COMPOSIO_INSTALL_DIR = $installDir
165 + $env:COMPOSIO_INSTALL_VERSION = $ExpectedVersion
166 + $env:COMPOSIO_INSTALL_SHELL = 'none'
167 + Invoke-Installer | Out-Host
168 + Assert ($LASTEXITCODE -eq 0) 'Reinstallation after a corrupt download failed.'
169 +
170 + # `composio upgrade` resolves the Windows asset, verifies it, and replaces the executable
171 + # that is currently running, keeping the previous one as composio.exe.old.
172 + foreach ($upgrade in 1..2) {
173 + Invoke-Cli @('upgrade', $ExpectedVersion) | Out-Host
174 + Assert ((Invoke-Cli @('--version')) -eq $ExpectedVersion) "CLI failed after upgrade $upgrade."
175 + Assert ((Get-Sha256 "$binary.old") -eq $expectedBinaryHash) "Upgrade $upgrade did not replace the running executable."
176 + if ($upgrade -eq 1) {
177 + # The replaced executable stays locked until its process has fully exited.
178 + for ($attempt = 0; $attempt -lt 50; $attempt++) {
179 + try { Set-Content -LiteralPath "$binary.old" -Value 'stale backup'; break } catch {
180 + if ($attempt -eq 0) {
181 + Write-Host 'composio.exe.old is locked. Processes running from the install directory:'
182 + Get-Process | Where-Object { $_.Path -like "$installDir*" } | Format-Table Id, ProcessName, StartTime, Path | Out-Host
183 + }
184 + Start-Sleep -Milliseconds 200
185 + }
186 + }
187 + Write-Host "composio.exe.old became writable after $attempt retries."
188 + }
189 + }
190 +
191 + # While another process holds composio.exe.old, neither upgrade path may modify the installation.
192 + $companionPath = Join-Path $installDir 'run-helpers-runtime.mjs'
193 + $tagPath = Join-Path $installDir 'release-tag.txt'
194 + $originalCompanion = [IO.File]::ReadAllText($companionPath)
195 + $originalTag = [IO.File]::ReadAllText($tagPath)
196 + $markerCompanion = $originalCompanion + "`n// retained while backup is locked`n"
197 + $markerTag = '@composio/cli@0.0.0-beta.999999'
198 + [IO.File]::WriteAllText($companionPath, $markerCompanion)
199 + [IO.File]::WriteAllText($tagPath, $markerTag)
200 + $lockedBackup = [IO.File]::Open("$binary.old", 'Open', 'Read', 'Read')
201 + try {
202 + foreach ($action in @({ & $binary upgrade $ExpectedVersion }, { Invoke-Installer })) {
203 + & $action 2>&1 | Out-Host
204 + Assert ($LASTEXITCODE -ne 0) 'Expected a locked backup to block replacement.'
205 + Assert ([IO.File]::ReadAllText($companionPath) -eq $markerCompanion) 'A blocked upgrade modified the support files.'
206 + Assert ([IO.File]::ReadAllText($tagPath) -eq $markerTag) 'A blocked upgrade modified the release metadata.'
207 + Assert ((Get-Sha256 $binary) -eq $expectedBinaryHash) 'A blocked upgrade modified the executable.'
208 + }
209 + } finally {
210 + $lockedBackup.Dispose()
211 + [IO.File]::WriteAllText($companionPath, $originalCompanion)
212 + [IO.File]::WriteAllText($tagPath, $originalTag)
213 + }
214 +
215 + # A missing companion module is downloaded again on demand.
216 + $companion = Join-Path $installDir 'services/generation-runtime.mjs'
217 + Remove-Item -LiteralPath $companion
218 + Assert ((Invoke-Cli @('run', 'console.log("windows-repair-ok")')) -eq 'windows-repair-ok') 'Companion repair failed.'
219 + Assert (Test-Path -LiteralPath $companion) 'Companion was not restored.'
220 +
221 + # The CLI skill is linked into the agent's directory with a junction, which needs no
222 + # elevated rights. Installing twice must replace the link without emptying its target.
223 + $env:USERPROFILE = Join-Path $testRoot 'home'
224 + New-Item -ItemType Directory -Path $env:USERPROFILE | Out-Null
225 + $env:COMPOSIO_GITHUB_API_BASE_URL = "$baseUrl/skill"
226 + $linkedSkill = Join-Path $env:USERPROFILE '.claude/skills/composio-cli'
227 + foreach ($attempt in 1..2) {
228 + Invoke-Cli @('setup', 'skill', 'claude') | Out-Host
229 + Assert ((Get-Item -LiteralPath $linkedSkill).LinkType -eq 'Junction') 'The skill was not linked with a junction.'
230 + Assert (Test-Path -LiteralPath (Join-Path $linkedSkill 'SKILL.md')) 'The linked skill is empty.'
231 + }
232 +
233 + # An npm-installed agent CLI is a .cmd shim. Setup must find and run it, here from a
234 + # directory with spaces, and get as far as asking for approval.
235 + $shimDir = Join-Path $testRoot 'npm global bin'
236 + New-Item -ItemType Directory -Path $shimDir | Out-Null
237 + @'
238 +@echo off
239 +if "%~1"=="--version" (echo 9.9.9& exit /b 0)
240 +echo %* | findstr /c:"--help" >nul && (echo --json Print JSON& exit /b 0)
241 +echo []
242 +'@ | Set-Content -LiteralPath (Join-Path $shimDir 'claude.cmd')
243 + $pathBeforeShim = $env:Path
244 + $env:Path = "$shimDir;$env:Path"
245 + try { $output = & $binary setup --target claude 2>&1 | Out-String } finally { $env:Path = $pathBeforeShim }
246 + Assert ($output -notlike '*not available on PATH*') "Setup did not find the claude.cmd shim: $output"
247 + Assert ($output -like '*--yes*') "Setup did not reach the approval step: $output"
248 +
249 + # Credentials can be kept in Windows Credential Manager. The compiled CLI doubles as the
250 + # Bun runtime for the store's roundtrip check.
251 + $env:BUN_BE_BUN = '1'
252 + try { & $binary (Join-Path $PSScriptRoot '../../../ts/packages/cli-keyring/test/windows-credential.smoke.ts') | Out-Host } finally { Remove-Item Env:BUN_BE_BUN }
253 + Assert ($LASTEXITCODE -eq 0) 'The Windows Credential Manager roundtrip failed.'
254 +
255 + # Shell setup has nothing to do on Windows and says so.
256 + $output = & $binary install 2>&1 | Out-String
257 + Assert ($LASTEXITCODE -ne 0 -and $output -like '*Windows*') "Expected composio install to explain itself, got: $output"
258 + Write-Host 'Windows installation, run, repeated upgrade, repair, agent setup, and credential storage passed.'
259 +} finally {
260 + if ($server -and -not $server.HasExited) { Stop-Process -Id $server.Id -Force; $server.WaitForExit() }
261 + foreach ($name in $envNames) { [Environment]::SetEnvironmentVariable($name, $savedEnv[$name]) }
262 + [Environment]::SetEnvironmentVariable('Path', $savedUserPath, 'User')
263 + Remove-Item -LiteralPath $testRoot -Recurse -Force
264 +}
265 +# The last native command above fails on purpose; do not let its exit code become the script's.
266 +exit 0
.github/scripts/cli-release/verify-assets.sh
+19 -3
@@ -6,10 +6,12 @@
6 # bounded retry while uploads settle.
7 #
8 # Inputs (env): RELEASE_TAG, GH_TOKEN
9 +# WINDOWS_VERIFIED (optional): "false" when the experimental Windows build failed
10 +# its native checks, so the release ships without the Windows archive
11 # VERIFY_ATTEMPTS / VERIFY_SLEEP_SECONDS (optional, for fast tests)
12 set -euo pipefail
13
12 -# Keep this list in lock-step with the build matrix in build-cli-binaries.yml (4 platforms)
14 +# Keep this list in lock-step with build-cli-binaries.yml and cli.windows.yml (5 platforms)
15 # plus the skill bundle and checksums. Adding a platform to the matrix must extend this list.
16 expected=(
17 composio-linux-x64.zip
@@ -19,6 +21,9 @@ expected=(
21 composio-skill.zip
22 checksums.txt
23 )
24 +if [[ "${WINDOWS_VERIFIED:-true}" != "false" ]]; then
25 + expected+=(composio-windows-x64.zip)
26 +fi
27
28 attempts="${VERIFY_ATTEMPTS:-10}"
29 sleep_seconds="${VERIFY_SLEEP_SECONDS:-15}"
@@ -27,13 +32,24 @@ for attempt in $(seq 1 "$attempts"); do
32 # Single snapshot per attempt — querying names and state separately would open a
33 # time-of-check/time-of-use gap in the very gate meant to close one.
34 payload=$(gh release view "$RELEASE_TAG" --json assets)
30 - mapfile -t uploaded < <(jq -r '.assets[] | select(.state == "uploaded") | .name' <<<"$payload" | sort)
35 + uploaded=$(jq -r '.assets[] | select(.state == "uploaded") | .name' <<<"$payload" | sort)
36
37 missing=()
38 for want in "${expected[@]}"; do
34 - printf '%s\n' "${uploaded[@]}" | grep -qxF "$want" || missing+=("$want")
39 + printf '%s\n' "$uploaded" | grep -qxF "$want" || missing+=("$want")
40 done
41
42 + # An asset outside the expected set is not covered by checksums.txt, for example a Windows
43 + # archive left on a resumed draft. Waiting cannot fix that, so fail at once.
44 + unexpected=()
45 + while IFS= read -r have; do
46 + [[ -z "$have" ]] || printf '%s\n' "${expected[@]}" | grep -qxF "$have" || unexpected+=("$have")
47 + done < <(jq -r '.assets[].name' <<<"$payload")
48 + if [[ ${#unexpected[@]} -gt 0 ]]; then
49 + echo "::error::Release $RELEASE_TAG has unexpected assets: ${unexpected[*]}"
50 + exit 1
51 + fi
52 +
53 if [[ ${#missing[@]} -eq 0 ]]; then
54 echo "✅ All ${#expected[@]} expected assets present and uploaded."
55 exit 0
.github/workflows/build-cli-binaries.yml
+41 -7
@@ -8,6 +8,8 @@ on:
8 - '.github/actions/setup-node-pnpm-bun/action.yml'
9 - '.github/scripts/cli-release/**'
10 - '.github/workflows/build-cli-binaries.yml'
11 + - '.github/workflows/cli.windows.yml'
12 + - 'install.ps1'
13 - 'install.sh'
14 - 'install/**'
15 - 'mise.toml'
@@ -176,15 +178,23 @@ jobs:
178 path: ts/packages/cli/dist/binaries/${{ matrix.artifact }}.zip
179 retention-days: 7
180
181 + windows:
182 + name: Windows x64
183 + needs: prepare
184 + uses: ./.github/workflows/cli.windows.yml
185 + with:
186 + release_tag: ${{ needs.prepare.outputs.release_tag }}
187 +
188 release:
189 name: Release (draft → verify → publish)
181 - needs: [prepare, build]
190 + needs: [prepare, build, windows]
191 runs-on: ubuntu-latest
192 permissions:
193 contents: write # create/edit the GitHub Release and upload assets
185 - # fail-fast: false on the build matrix ⇒ this is `success` only if ALL platforms built,
186 - # so a partial set can never reach the release path.
187 - if: needs.build.result == 'success'
194 + # fail-fast: false on the build matrix ⇒ this is `success` only if ALL platforms built.
195 + # Windows is experimental, so a failed Windows job does not block the release: it ships
196 + # without the Windows archive instead (see "Drop unverified Windows archive").
197 + if: ${{ !cancelled() && needs.build.result == 'success' }}
198 # Serialize runs that target the SAME release tag (e.g. two quick pushes, or a re-run
199 # racing the original) so they cannot interleave uploads. Keyed on the resolved tag so
200 # unrelated beta builds are not serialized behind each other. Job-level concurrency may
@@ -220,6 +230,14 @@ jobs:
230 path: ts/packages/cli/dist/binaries
231 merge-multiple: true
232
233 + # The Windows build job uploads its archive before the native checks run, so a failed
234 + # check leaves an unverified archive behind. Never publish that one.
235 + - name: Drop unverified Windows archive
236 + if: needs.windows.result != 'success'
237 + run: |
238 + echo "::warning::Windows x64 verification did not pass. Releasing without composio-windows-x64.zip."
239 + rm -f ts/packages/cli/dist/binaries/composio-windows-x64.zip
240 +
241 # Package skills BEFORE generating checksums so composio-skill.zip is included in
242 # checksums.txt alongside the platform binaries (generate-checksums hashes every .zip
243 # in dist/binaries).
@@ -264,6 +282,8 @@ jobs:
282 # An asset can appear in the list while still processing (`state != "uploaded"`), which is
283 # exactly how a release ends up serving 404s, so we require state == "uploaded".
284 - name: Verify all release assets are present and uploaded
285 + env:
286 + WINDOWS_VERIFIED: ${{ needs.windows.result == 'success' && 'true' || 'false' }}
287 run: bash "$RELEASE_HELPERS_DIR/verify-assets.sh"
288
289 # Publishing is the ONLY step that exposes the release. Do not edit the body here: a known
@@ -274,11 +294,12 @@ jobs:
294
295 test-installation:
296 name: Test Installation
277 - needs: [prepare, release]
297 + needs: [prepare, windows, release]
298 if: always() && !cancelled() && needs.release.result == 'success'
299 uses: ./.github/workflows/cli.test-installation.yml
300 with:
301 version: ${{ needs.prepare.outputs.release_tag }}
302 + windows: ${{ needs.windows.result == 'success' && 'true' || 'false' }}
303
304 create-install-instructions:
305 name: Create Install Instructions
@@ -307,6 +328,20 @@ jobs:
328 directory to `PATH` in that shell's startup file. Re-running the installer
329 never duplicates the entry.
330
331 + ### Windows x64 (experimental)
332 +
333 + Run in PowerShell:
334 +
335 + ```powershell
336 + $env:COMPOSIO_INSTALL_VERSION = "RELEASE_TAG_PLACEHOLDER"; irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex
337 + ```
338 +
339 + This verifies the archive, installs the complete bundle in
340 + `$HOME\.composio`, and adds it to your User PATH. No administrator
341 + access is needed. Keep `composio.exe` with its support files.
342 + Windows support is experimental: commands other than `run`,
343 + `upgrade`, and `setup` may not work yet.
344 +
345 ### Install without shell setup
346
347 ```bash
@@ -364,8 +399,7 @@ jobs:
399 - macOS x64 (Intel)
400 - macOS ARM64 (Apple Silicon)
401
367 - **Not supported:**
368 - - Windows: use [WSL](https://learn.microsoft.com/windows/wsl/install) and run the installer inside your WSL distribution
402 + - Windows: x64, experimental (Windows 10 1809+), installed with PowerShell. Requires an SSE4.2-capable CPU.
403 EOF
404 sed -i.bak "s|RELEASE_TAG_PLACEHOLDER|$RELEASE_TAG|g" INSTALL.md && rm -f INSTALL.md.bak
405
.github/workflows/cli.test-installation.yml
+46 -2
@@ -14,6 +14,7 @@ on:
14 pull_request:
15 paths:
16 - 'install.sh'
17 + - 'install.ps1'
18 - 'install/**'
19 - 'test/install-sh-*.test.sh'
20 - '.github/workflows/cli.test-installation.yml'
@@ -29,6 +30,11 @@ on:
30 required: false
31 default: 'latest'
32 type: string
33 + windows:
34 + description: "Set to 'false' when the release ships without the experimental Windows archive"
35 + required: false
36 + default: 'true'
37 + type: string
38
39 permissions:
40 contents: read
@@ -582,6 +588,34 @@ jobs:
588
589 rm test-install.sh
590
591 + test-windows-installation:
592 + name: Test Windows Installation
593 + if: github.event_name != 'pull_request' && inputs.windows != 'false'
594 + runs-on: windows-2025
595 + steps:
596 + - name: Checkout
597 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
598 +
599 + - name: Install and verify published Windows release
600 + shell: pwsh
601 + env:
602 + VERSION_INPUT: ${{ inputs.version || github.ref_name }}
603 + COMPOSIO_CLI_TELEMETRY_DISABLED: '1'
604 + run: |
605 + $ErrorActionPreference = 'Stop'
606 + if ($env:VERSION_INPUT -and $env:VERSION_INPUT -ne 'latest') {
607 + $env:COMPOSIO_INSTALL_VERSION = $env:VERSION_INPUT
608 + }
609 + # The documented flow: pipe the script into Invoke-Expression.
610 + Get-Content -Raw ./install.ps1 | Invoke-Expression
611 + $expectedVersion = (Get-Content -LiteralPath "$HOME/.composio/release-tag.txt" -Raw).Trim() -replace '^@composio/cli@', ''
612 + $actualVersion = (& composio --version | Out-String).Trim()
613 + if ($LASTEXITCODE -ne 0 -or $actualVersion -ne $expectedVersion) {
614 + throw "Expected Windows CLI $expectedVersion, got $actualVersion"
615 + }
616 + & composio --help
617 + if ($LASTEXITCODE -ne 0) { throw 'Installed Windows CLI help failed.' }
618 +
619 summary:
620 name: Installation Test Summary
621 needs:
@@ -590,6 +624,7 @@ jobs:
624 test-install-script,
625 test-architecture-detection,
626 test-prerequisites,
627 + test-windows-installation,
628 ]
629 runs-on: ubuntu-latest
630 if: always() && github.event_name != 'pull_request'
@@ -630,5 +665,14 @@ jobs:
665 echo "- **Linux ARM64**: Ubuntu 22.04, 24.04 (via Depot)" >> $GITHUB_STEP_SUMMARY
666 echo "- **macOS x64**: macOS 15 (Intel)" >> $GITHUB_STEP_SUMMARY
667 echo "- **macOS ARM64**: macOS 15, macOS 26 (Apple Silicon)" >> $GITHUB_STEP_SUMMARY
633 - echo "- **Shells**: Bash and Zsh" >> $GITHUB_STEP_SUMMARY
634 - echo "- **Total platforms**: 4 architectures across 15+ environments" >> $GITHUB_STEP_SUMMARY
668 + echo "- **Windows x64**: Windows Server 2025" >> $GITHUB_STEP_SUMMARY
669 + echo "- **Shells**: Bash, Zsh, and PowerShell" >> $GITHUB_STEP_SUMMARY
670 +
671 + case "${{ needs.test-windows-installation.result }}" in
672 + success) echo "✅ **Windows Installation**: PASSED" >> $GITHUB_STEP_SUMMARY ;;
673 + skipped) echo "⏭️ **Windows Installation**: SKIPPED (release has no Windows archive)" >> $GITHUB_STEP_SUMMARY ;;
674 + *)
675 + echo "❌ **Windows Installation**: FAILED" >> $GITHUB_STEP_SUMMARY
676 + exit 1
677 + ;;
678 + esac
.github/workflows/cli.windows.yml new
+103
@@ -0,0 +1,103 @@
1 +name: CLI Windows x64
2 +
3 +on:
4 + pull_request:
5 + paths:
6 + - 'ts/packages/cli/**'
7 + - 'ts/packages/cli-keyring/**'
8 + - 'ts/packages/core/**'
9 + - 'ts/packages/ts-builders/**'
10 + - 'ts/packages/json-schema-to-effect-schema/**'
11 + - '.github/actions/setup-node-pnpm-bun/action.yml'
12 + - '.github/scripts/cli-release/**'
13 + - '.github/workflows/cli.windows.yml'
14 + - '.github/workflows/build-cli-binaries.yml'
15 + - 'install.ps1'
16 + - 'package.json'
17 + - 'pnpm-lock.yaml'
18 + - 'pnpm-workspace.yaml'
19 + - 'mise.toml'
20 + - 'mise.lock'
21 + workflow_call:
22 + inputs:
23 + release_tag:
24 + description: 'Exact CLI release tag to embed and verify'
25 + type: string
26 + required: false
27 + default: '@composio/cli@0.0.0-beta.0'
28 +
29 +permissions:
30 + contents: read
31 +
32 +env:
33 + RELEASE_TAG: ${{ inputs.release_tag || '@composio/cli@0.0.0-beta.0' }}
34 + TURBO_TELEMETRY_DEBUG: 1
35 +
36 +jobs:
37 + build:
38 + name: Build Windows archive
39 + runs-on: ubuntu-latest
40 + steps:
41 + - name: Checkout
42 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
43 + with:
44 + ref: ${{ github.sha }}
45 +
46 + - name: Setup Node.js, pnpm, Bun
47 + uses: ./.github/actions/setup-node-pnpm-bun
48 + with:
49 + cache-save: ${{ github.event_name != 'pull_request' && 'true' || 'false' }}
50 +
51 + - name: Install dependencies
52 + run: pnpm install --frozen-lockfile --ignore-scripts
53 +
54 + - name: Build packages
55 + run: pnpm build:packages
56 +
57 + - name: Cross-compile Windows x64
58 + working-directory: ts/packages/cli
59 + env:
60 + COMPOSIO_POSTHOG_PROJECT_API_KEY: ${{ vars.COMPOSIO_POSTHOG_PROJECT_API_KEY }}
61 + run: pnpm build:binary:cross --target bun-windows-x64
62 +
63 + - name: Package Windows archive
64 + working-directory: ts/packages/cli
65 + run: pnpm build:binary:package
66 +
67 + - name: Verify release metadata and companion layout
68 + env:
69 + ARCHIVE: ts/packages/cli/dist/binaries/composio-windows-x64.zip
70 + ARTIFACT: composio-windows-x64
71 + run: |
72 + unzip -p "$ARCHIVE" "$ARTIFACT/release-tag.txt" | grep -Fx "$RELEASE_TAG"
73 + bash .github/scripts/cli-release/verify-archive-companions.sh
74 +
75 + - name: Upload Windows archive
76 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
77 + with:
78 + name: composio-windows-x64
79 + path: ts/packages/cli/dist/binaries/composio-windows-x64.zip
80 + retention-days: 7
81 +
82 + test:
83 + name: Native Windows installation and runtime
84 + needs: build
85 + # Standard GitHub-hosted Windows runners are free for public repositories.
86 + runs-on: windows-2025
87 + steps:
88 + - name: Checkout
89 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
90 + with:
91 + ref: ${{ github.sha }}
92 +
93 + - name: Download Windows archive
94 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
95 + with:
96 + name: composio-windows-x64
97 + path: windows-artifact
98 +
99 + - name: Test installer, native binary, companions, and upgrades
100 + shell: pwsh
101 + run: |
102 + $expectedVersion = $env:RELEASE_TAG -replace '^@composio/cli@', ''
103 + ./.github/scripts/cli-release/test-windows.ps1 -ArchivePath ./windows-artifact/composio-windows-x64.zip -ExpectedVersion $expectedVersion
INSTALL.md
+26 -3
@@ -1,6 +1,6 @@
1 # Composio CLI installation
2
3 -Install the CLI bundle in `~/.composio` and its entry point in `~/.local/bin`:
3 +On Linux or macOS, install the CLI bundle in `~/.composio` and its entry point in `~/.local/bin`:
4
5 ```bash
6 curl -fsSL https://composio.dev/install | sh
@@ -12,6 +12,28 @@ If your shell is not recognized, or shell setup fails, the binary install still
12
13 Official releases must pass SHA-256 verification against the release's `checksums.txt`: a missing manifest, a manifest with no entry for your platform's archive, a malformed entry, or a mismatch aborts the install with `Refusing to install`. On systems with no `sha256sum` or `shasum`, the installer warns that verification was skipped and continues.
14
15 +## Windows x64 (experimental)
16 +
17 +Run in PowerShell:
18 +
19 +```powershell
20 +irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex
21 +```
22 +
23 +The installer verifies the release's SHA-256 checksum, installs `composio.exe` and its support files in `$HOME\.composio`, and adds that directory to your User PATH. Then run `composio login`. You don't need administrator access.
24 +
25 +To install a specific stable or beta release, set `COMPOSIO_INSTALL_VERSION` first:
26 +
27 +```powershell
28 +$env:COMPOSIO_INSTALL_VERSION = "X.Y.Z"; irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex
29 +```
30 +
31 +Set `COMPOSIO_INSTALL_DIR` to choose the bundle directory, or `COMPOSIO_INSTALL_SHELL` to `none` to leave PATH unchanged. Keep the complete bundle together when moving it.
32 +
33 +Windows support is experimental. Installation, `composio run`, `composio upgrade`, and `composio setup` are tested on Windows; other commands may not work yet. `composio install` and shell completions support only zsh, bash, and fish: the PowerShell installer sets PATH for you.
34 +
35 +Windows requires Windows 10 version 1809 or newer and an x64 CPU with SSE4.2. Windows ARM64 is not supported. For a fully supported setup, run the Linux installer inside [WSL](https://learn.microsoft.com/windows/wsl/install).
36 +
37 ## Choose or skip shell setup
38
39 Set `COMPOSIO_INSTALL_SHELL` to force a specific shell, or to skip shell configuration entirely:
@@ -59,8 +81,9 @@ Download the archive for your platform from [GitHub Releases](https://github.com
81 - `composio-linux-aarch64.zip`
82 - `composio-darwin-x64.zip`
83 - `composio-darwin-aarch64.zip`
84 +- `composio-windows-x64.zip`
85
63 -Extract and install the complete bundle. The CLI loads support files beside the executable, so do not copy only the nested `composio` file.
86 +Extract and install the complete bundle. The CLI loads support files beside the executable, so do not copy only the nested `composio` or `composio.exe` file.
87
88 ```bash
89 bundle=composio-linux-x64
@@ -120,4 +143,4 @@ To purge credentials, configuration, caches, and every other CLI file, run `rm -
143 - Linux ARM64
144 - macOS Intel
145 - macOS Apple Silicon
123 -- Windows: use [WSL](https://learn.microsoft.com/windows/wsl/install) and run the installer inside your WSL distribution
146 +- Windows: x64, experimental (Windows 10 1809+), installed with PowerShell. Requires an SSE4.2-capable CPU.
docs/content/docs/cli.mdx
+24 -2
@@ -14,7 +14,7 @@ When no human is available to log in, `composio login --agent` provisions or reu
14
15 ## Install
16
17 -Install the CLI with one command:
17 +On Linux or macOS, install the CLI with one command:
18
19 ```bash
20 curl -fsSL https://composio.dev/install | sh
@@ -47,6 +47,28 @@ composio setup skill claude
47 composio setup skill codex
48 ```
49
50 +### Windows x64 (experimental)
51 +
52 +Run in PowerShell:
53 +
54 +```powershell
55 +irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex
56 +```
57 +
58 +The installer verifies the release's SHA-256 checksum, installs `composio.exe` and its support files in `$HOME\.composio`, and adds that directory to your User PATH. Then run `composio login`. You don't need administrator access.
59 +
60 +To install a specific stable or beta release, set `COMPOSIO_INSTALL_VERSION` first:
61 +
62 +```powershell
63 +$env:COMPOSIO_INSTALL_VERSION = "X.Y.Z"; irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex
64 +```
65 +
66 +Set `COMPOSIO_INSTALL_DIR` to choose the bundle directory, or `COMPOSIO_INSTALL_SHELL` to `none` to leave PATH unchanged. Keep the complete bundle together when moving it.
67 +
68 +Windows support is experimental. Installation, `composio run`, `composio upgrade`, and `composio setup` are tested on Windows; other commands may not work yet. `composio install` and shell completions support only zsh, bash, and fish: the PowerShell installer sets PATH for you.
69 +
70 +Windows requires Windows 10 version 1809 or newer and an x64 CPU with SSE4.2. Windows ARM64 is not supported. For a fully supported setup, run the Linux installer inside [WSL](https://learn.microsoft.com/windows/wsl/install).
71 +
72 ### Backend and Dashboard configuration
73
74 The CLI uses the backend recorded by `composio login`. `COMPOSIO_BASE_URL` and `COMPOSIO_ENVIRONMENT` override that backend. If an override sends your stored key to a different backend, the CLI warns on stderr. If your key is rejected, follow the printed command to log in again.
@@ -133,7 +155,7 @@ composio --version
155 which composio
156 ```
157
136 -The installer supports Linux x64, Linux ARM64, macOS Intel, and macOS Apple Silicon. On Windows, install and run it inside [WSL](https://learn.microsoft.com/windows/wsl/install).
158 +The CLI supports Linux x64, Linux ARM64, macOS Intel, and macOS Apple Silicon. Windows x64 support is experimental: use the [PowerShell installer](#windows-x64-experimental).
159
160 ### Update
161
install.ps1 new
+131
@@ -0,0 +1,131 @@
1 +# Composio CLI installer for Windows x64 (experimental).
2 +#
3 +# irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex
4 +#
5 +# Configure it with environment variables, like install.sh:
6 +# COMPOSIO_INSTALL_VERSION Release to install, such as 0.3.1 or 0.3.1-beta.329. Default: latest stable.
7 +# COMPOSIO_INSTALL_DIR Directory for the CLI bundle. Default: ~\.composio
8 +# COMPOSIO_INSTALL_SHELL Set to "none" to leave PATH unchanged.
9 +
10 +# The script block keeps variables and preferences out of the caller's session under `iex`.
11 +& {
12 + $ErrorActionPreference = 'Stop'
13 + # Windows PowerShell redraws its progress bar per chunk, which slows downloads to a crawl.
14 + $ProgressPreference = 'SilentlyContinue'
15 +
16 + # A 32-bit PowerShell on 64-bit Windows reports the real architecture in PROCESSOR_ARCHITEW6432.
17 + $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
18 + if ($env:OS -ne 'Windows_NT' -or $arch -ne 'AMD64') {
19 + throw 'This installer requires Windows x64. On Linux, macOS, or WSL, run: curl -fsSL https://composio.dev/install | sh'
20 + }
21 +
22 + # The checksum only proves the archive matches checksums.txt, and both come from the same
23 + # server. So every download must use HTTPS; plain HTTP is accepted from this machine only.
24 + function Assert-TrustedUrl([string]$Url) {
25 + $uri = $Url -as [uri]
26 + $trusted = $uri -and $uri.IsAbsoluteUri -and -not $uri.UserInfo -and
27 + ($uri.Scheme -eq 'https' -or ($uri.Scheme -eq 'http' -and $uri.IsLoopback))
28 + if (-not $trusted) { throw "Refusing to download from `"$Url`". The URL must use HTTPS and carry no credentials." }
29 + }
30 +
31 + $archiveName = 'composio-windows-x64.zip'
32 + $installDir = if ($env:COMPOSIO_INSTALL_DIR) { $env:COMPOSIO_INSTALL_DIR } else { Join-Path $HOME '.composio' }
33 + $installDir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($installDir)
34 +
35 + # Find the release: the requested version, or the newest stable one that ships a Windows archive.
36 + $api = if ($env:COMPOSIO_GITHUB_API_BASE_URL) { $env:COMPOSIO_GITHUB_API_BASE_URL.TrimEnd('/') } else { 'https://api.github.com' }
37 + Assert-TrustedUrl $api
38 + $releasesUrl = "$api/repos/ComposioHQ/composio/releases"
39 + $release = $null
40 + if ($env:COMPOSIO_INSTALL_VERSION) {
41 + $version = $env:COMPOSIO_INSTALL_VERSION -replace '^@composio/cli@', ''
42 + if ($version -notmatch '^\d+\.\d+\.\d+(-beta\.\d+)?$') {
43 + throw "Invalid Composio CLI version `"$env:COMPOSIO_INSTALL_VERSION`". Expected X.Y.Z or X.Y.Z-beta.N."
44 + }
45 + $release = Invoke-RestMethod "$releasesUrl/tags/$([uri]::EscapeDataString("@composio/cli@$version"))"
46 + } else {
47 + Write-Host 'Finding latest stable CLI release...'
48 + for ($page = 1; $page -le 5 -and -not $release; $page++) {
49 + # Assign before piping: Windows PowerShell emits the JSON array as a single object.
50 + $candidates = Invoke-RestMethod "${releasesUrl}?per_page=100&page=$page"
51 + if (-not $candidates) { break }
52 + $release = $candidates | Where-Object {
53 + $_.tag_name -match '^@composio/cli@\d+\.\d+\.\d+$' -and -not $_.draft -and -not $_.prerelease -and
54 + $_.assets.name -contains $archiveName
55 + } | Select-Object -First 1
56 + }
57 + if (-not $release) { throw 'No stable CLI release with a Windows x64 archive was found. Set COMPOSIO_INSTALL_VERSION to choose one.' }
58 + }
59 + $tag = $release.tag_name
60 + $archiveUrl = ($release.assets | Where-Object { $_.name -eq $archiveName }).browser_download_url
61 + $checksumsUrl = ($release.assets | Where-Object { $_.name -eq 'checksums.txt' }).browser_download_url
62 + if (-not $archiveUrl) { throw "Release $tag has no Windows x64 archive." }
63 + if (-not $checksumsUrl) { throw "Release $tag has no checksums.txt, so it cannot be verified. Refusing to install." }
64 + Assert-TrustedUrl $archiveUrl
65 + Assert-TrustedUrl $checksumsUrl
66 +
67 + $tempDir = Join-Path ([IO.Path]::GetTempPath()) "composio-install-$([Guid]::NewGuid())"
68 + New-Item -ItemType Directory -Path $tempDir | Out-Null
69 + try {
70 + Write-Host "Installing Composio CLI $tag for windows-x64"
71 + $archivePath = Join-Path $tempDir $archiveName
72 + $checksumsPath = Join-Path $tempDir 'checksums.txt'
73 + Invoke-WebRequest $archiveUrl -OutFile $archivePath -UseBasicParsing
74 + Invoke-WebRequest $checksumsUrl -OutFile $checksumsPath -UseBasicParsing
75 +
76 + $entry = Select-String -LiteralPath $checksumsPath -Pattern '^([0-9a-f]{64})\s+\*?composio-windows-x64\.zip$' | Select-Object -First 1
77 + if (-not $entry) { throw "checksums.txt has no entry for $archiveName. Refusing to install." }
78 + if ((Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash -ne $entry.Matches[0].Groups[1].Value) {
79 + throw "Checksum mismatch for $archiveName. Refusing to install."
80 + }
81 +
82 + Expand-Archive -LiteralPath $archivePath -DestinationPath $tempDir
83 + $bundle = Join-Path $tempDir 'composio-windows-x64'
84 + if (-not (Test-Path -LiteralPath (Join-Path $bundle 'composio.exe') -PathType Leaf)) {
85 + throw 'The archive has no composio.exe. Refusing to install.'
86 + }
87 +
88 + # Windows cannot overwrite a running executable, but it can rename one. Copy the new
89 + # executable next to the current one first, so the only step that leaves the directory
90 + # without composio.exe is a pair of renames. Everything else in that directory
91 + # (credentials, configuration) stays untouched.
92 + New-Item -ItemType Directory -Path $installDir -Force | Out-Null
93 + $exe = Join-Path $installDir 'composio.exe'
94 + $stagedExe = "$exe.new"
95 + $previousExe = "$exe.old"
96 + try {
97 + if (Test-Path -LiteralPath $previousExe) { Remove-Item -LiteralPath $previousExe -Force }
98 + } catch {
99 + throw "Could not remove $previousExe. Close other Composio processes and retry. $($_.Exception.Message)"
100 + }
101 + Copy-Item -LiteralPath (Join-Path $bundle 'composio.exe') -Destination $stagedExe -Force
102 + Get-ChildItem -LiteralPath $bundle -Force | Where-Object { $_.Name -ne 'composio.exe' } |
103 + Copy-Item -Destination $installDir -Recurse -Force
104 +
105 + $hadExe = Test-Path -LiteralPath $exe
106 + if ($hadExe) { Move-Item -LiteralPath $exe -Destination $previousExe }
107 + try {
108 + Move-Item -LiteralPath $stagedExe -Destination $exe
109 + } catch {
110 + if ($hadExe) { Move-Item -LiteralPath $previousExe -Destination $exe -Force }
111 + throw
112 + }
113 + # Fails only while the previous executable is still running; the next install removes it.
114 + Remove-Item -LiteralPath $previousExe -Force -ErrorAction SilentlyContinue
115 + } finally {
116 + Remove-Item -LiteralPath $tempDir -Recurse -Force -ErrorAction SilentlyContinue
117 + }
118 +
119 + if ($env:COMPOSIO_INSTALL_SHELL -ne 'none') {
120 + $userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
121 + if (($userPath -split ';') -notcontains $installDir) {
122 + [Environment]::SetEnvironmentVariable('Path', ((@($installDir, $userPath) | Where-Object { $_ }) -join ';'), 'User')
123 + }
124 + # Also update this session, so `composio` works without opening a new terminal.
125 + if (($env:Path -split ';') -notcontains $installDir) { $env:Path = "$installDir;$env:Path" }
126 + }
127 +
128 + Write-Host "Installed $tag in $installDir"
129 + Write-Host 'Windows support is experimental. Report problems at https://github.com/ComposioHQ/composio/issues'
130 + Write-Host 'Run "composio login" to connect your account.'
131 +}
install.sh
+1 -1
@@ -198,7 +198,7 @@ detect_target() {
198 platform=$(uname -ms)
199 case $platform in
200 'MINGW64'* | 'MSYS'* | 'CYGWIN'*)
201 - error 'Windows is not supported. Use WSL (https://learn.microsoft.com/windows/wsl/install) and run this script inside your WSL distribution.'
201 + error 'Run this installer inside WSL, or try the experimental native build from PowerShell: irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex'
202 ;;
203 'Darwin x86_64') target=darwin-x64 ;;
204 'Darwin arm64') target=darwin-aarch64 ;;
test/install-sh-release-resolution.test.sh
+1 -1
@@ -148,7 +148,7 @@ for interpreter in "$(command -v sh)"; do
148 if windows_output=$(env PATH="$windows_bin:$PATH" HOME="$windows_home" "$interpreter" "$repo_root/install.sh" 2>&1); then
149 fail 'Windows-like platforms must fail'
150 fi
151 - assert_contains "$windows_output" 'Windows is not supported. Use WSL' 'Windows guidance'
151 + assert_contains "$windows_output" 'Run this installer inside WSL' 'Windows guidance'
152 done
153
154 platform=$(uname -ms)
test/release-workflow.test.ts
+143 -12
@@ -52,8 +52,8 @@ const buildCliWorkflow = readFileSync(
52 new URL('../.github/workflows/build-cli-binaries.yml', import.meta.url),
53 'utf8'
54 );
55 -const buildAllCliBinariesScript = readFileSync(
56 - new URL('../ts/packages/cli/scripts/build-all-binaries.ts', import.meta.url),
55 +const cliBuildSharedScript = readFileSync(
56 + new URL('../ts/packages/cli/scripts/_shared.ts', import.meta.url),
57 'utf8'
58 );
59 const installGuide = readFileSync(new URL('../INSTALL.md', import.meta.url), 'utf8');
@@ -672,12 +672,8 @@ const generatedWindowsInstallGuidance = requireMatch(
672 'generated Windows install guidance'
673 );
674
675 -if (
676 - !canonicalWindowsInstallGuidance.includes(
677 - '[WSL](https://learn.microsoft.com/windows/wsl/install)'
678 - )
679 -) {
680 - throw new Error('INSTALL.md must direct Windows users to the canonical WSL instructions');
675 +if (!canonicalWindowsInstallGuidance.includes('PowerShell')) {
676 + throw new Error('INSTALL.md must document native Windows x64 PowerShell installation');
677 }
678 if (generatedWindowsInstallGuidance !== canonicalWindowsInstallGuidance) {
679 throw new Error(
@@ -745,6 +741,143 @@ if (!verifyAssetsScript.includes('select(.state == "uploaded")')) {
741 throw new Error('verify-assets.sh must require assets be fully uploaded (state == "uploaded")');
742 }
743
744 +// Windows must be uploaded before a release becomes public, just like existing platforms.
745 +{
746 + const fixtureDir = mkdtempSync(join(tmpdir(), 'composio-windows-release-assets-'));
747 + try {
748 + const fakeBin = join(fixtureDir, 'bin');
749 + mkdirSync(fakeBin);
750 + const fixturePath = join(fixtureDir, 'assets.json');
751 + const ghPath = join(fakeBin, 'gh');
752 + writeFileSync(ghPath, '#!/bin/sh\ncat "$CLI_RELEASE_ASSETS_FIXTURE"\n');
753 + chmodSync(ghPath, 0o755);
754 + const assets = [
755 + 'composio-linux-x64.zip',
756 + 'composio-linux-aarch64.zip',
757 + 'composio-darwin-x64.zip',
758 + 'composio-darwin-aarch64.zip',
759 + 'composio-windows-x64.zip',
760 + 'composio-skill.zip',
761 + 'checksums.txt',
762 + ].map(name => ({ name, state: 'uploaded' }));
763 + const verify = (rows, extraEnv = {}) => {
764 + writeFileSync(fixturePath, JSON.stringify({ assets: rows }));
765 + return spawnSync(
766 + 'bash',
767 + [new URL('../.github/scripts/cli-release/verify-assets.sh', import.meta.url).pathname],
768 + {
769 + encoding: 'utf8',
770 + env: {
771 + ...process.env,
772 + PATH: `${fakeBin}:${process.env.PATH}`,
773 + CLI_RELEASE_ASSETS_FIXTURE: fixturePath,
774 + RELEASE_TAG: '@composio/cli@1.2.3',
775 + VERIFY_ATTEMPTS: '1',
776 + VERIFY_SLEEP_SECONDS: '0',
777 + ...extraEnv,
778 + },
779 + }
780 + );
781 + };
782 + const complete = verify(assets);
783 + if (complete.status !== 0) {
784 + throw new Error(`complete CLI release must pass verification: ${complete.stderr}`);
785 + }
786 + const withoutWindows = assets.filter(asset => asset.name !== 'composio-windows-x64.zip');
787 + const missing = verify(withoutWindows);
788 + // Windows is experimental: when its native checks fail, the release ships without it.
789 + const unverified = verify(withoutWindows, { WINDOWS_VERIFIED: 'false' });
790 + if (unverified.status !== 0) {
791 + throw new Error(
792 + `a release without the unverified Windows archive must pass: ${unverified.stdout}`
793 + );
794 + }
795 + // A Windows archive left on a resumed draft has no checksum entry, so it must not ship.
796 + const stale = verify(assets, { WINDOWS_VERIFIED: 'false' });
797 + if (stale.status === 0 || !stale.stdout.includes('unexpected assets')) {
798 + throw new Error('CLI release verification must reject an unverified Windows archive');
799 + }
800 + const pending = verify(
801 + assets.map(asset =>
802 + asset.name === 'composio-windows-x64.zip' ? { ...asset, state: 'new' } : asset
803 + )
804 + );
805 + for (const result of [missing, pending]) {
806 + if (result.status === 0 || !result.stdout.includes('composio-windows-x64.zip')) {
807 + throw new Error(
808 + 'CLI release verification must reject a missing or pending Windows archive'
809 + );
810 + }
811 + }
812 + } finally {
813 + rmSync(fixtureDir, { recursive: true, force: true });
814 + }
815 +}
816 +
817 +// Resuming a draft must remove assets the current run does not ship: the regenerated
818 +// checksums.txt no longer covers them.
819 +{
820 + const fixtureDir = mkdtempSync(join(tmpdir(), 'composio-resume-draft-'));
821 + try {
822 + const fakeBin = join(fixtureDir, 'bin');
823 + const binariesDir = join(fixtureDir, 'binaries');
824 + mkdirSync(fakeBin);
825 + mkdirSync(binariesDir);
826 + for (const name of ['composio-linux-x64.zip', 'checksums.txt']) {
827 + writeFileSync(join(binariesDir, name), '');
828 + }
829 + const ghLog = join(fixtureDir, 'gh.log');
830 + const ghPath = join(fakeBin, 'gh');
831 + writeFileSync(
832 + ghPath,
833 + [
834 + '#!/bin/sh',
835 + 'echo "$*" >> "$GH_LOG"',
836 + 'case "$*" in',
837 + ' *isDraft*) echo true ;;',
838 + ' *assets*) printf "%s\\n" composio-linux-x64.zip composio-windows-x64.zip checksums.txt ;;',
839 + 'esac',
840 + '',
841 + ].join('\n')
842 + );
843 + chmodSync(ghPath, 0o755);
844 + const resumed = spawnSync(
845 + 'bash',
846 + [
847 + new URL('../.github/scripts/cli-release/create-or-resume-draft.sh', import.meta.url)
848 + .pathname,
849 + ],
850 + {
851 + encoding: 'utf8',
852 + env: {
853 + ...process.env,
854 + PATH: `${fakeBin}:${process.env.PATH}`,
855 + GH_LOG: ghLog,
856 + BINARIES_DIR: binariesDir,
857 + RELEASE_TAG: '@composio/cli@1.2.3',
858 + RELEASE_NAME: 'CLI 1.2.3',
859 + CHECKOUT_REF: 'abc123',
860 + PRERELEASE: 'false',
861 + },
862 + }
863 + );
864 + const deletions = readFileSync(ghLog, 'utf8')
865 + .split('\n')
866 + .filter(line => line.startsWith('release delete-asset'));
867 + if (
868 + resumed.status !== 0 ||
869 + deletions.length !== 1 ||
870 + !deletions[0].includes('composio-windows-x64.zip')
871 + ) {
872 + throw new Error(
873 + `a resumed draft must drop only the assets this run does not ship: ${resumed.stderr}${deletions}`
874 + );
875 + }
876 + } finally {
877 + rmSync(fixtureDir, { recursive: true, force: true });
878 + }
879 +}
880 +
881 // Beta status must survive the draft→publish flip (regression: the old single create set
882 // --prerelease at creation; the new flow must set it on the draft).
883 if (!createDraftScript.includes('flags+=(--prerelease)')) {
@@ -880,11 +1013,9 @@ if (!buildCliWorkflow.includes('RELEASE_TAG: ${{ needs.prepare.outputs.release_t
1013 throw new Error('CLI binary builds must receive the resolved GitHub release tag');
1014 }
1015 if (
883 - !buildAllCliBinariesScript.includes(
884 - '...buildCliReleaseVersionDefineArgs(process.env.RELEASE_TAG)'
885 - )
1016 + !cliBuildSharedScript.includes('...buildCliReleaseVersionDefineArgs(process.env.RELEASE_TAG)')
1017 ) {
887 - throw new Error('the all-target CLI build must embed the resolved GitHub release version');
1018 + throw new Error('CLI binary compilation must embed the resolved GitHub release version');
1019 }
1020 if (
1021 !buildCliWorkflow.includes(
ts/packages/cli-keyring/README.md
+10 -7
@@ -24,7 +24,8 @@ src/
24 ├── macos-security-ffi.ts # direct Security.framework via bun:ffi (fast path)
25 ├── macos-security-subprocess.ts# /usr/bin/security subprocess fallback
26 ├── linux-secret-tool.ts # secret-tool subprocess
27 - ├── unsupported.ts # Windows / BSD / … — throws NoStorageAccess
27 + ├── windows-credential-ffi.ts # Credential Manager via bun:ffi (advapi32.dll)
28 + ├── unsupported.ts # BSD, Windows outside Bun, … — throws NoStorageAccess
29 └── shared.ts # subprocess helpers + base64 on-disk encoding
30 ```
31
@@ -32,12 +33,14 @@ The core is intentionally Promise-based and depends on neither Effect nor any ot
33
34 ## Backends and runtime dispatch
35
35 -| platform | runtime | backend | read latency |
36 -| ----------- | ------- | ------------------------------------ | ------------ |
37 -| macOS | Bun | `SecItem*` via `bun:ffi` | **~1.4ms** |
38 -| macOS | Node | `/usr/bin/security` subprocess | ~22ms |
39 -| Linux | both | `secret-tool` subprocess (libsecret) | ~15–40ms |
40 -| Windows/BSD | both | throws `NoStorageAccess` | — |
36 +| platform | runtime | backend | read latency |
37 +| -------- | ------- | ------------------------------------ | ------------ |
38 +| macOS | Bun | `SecItem*` via `bun:ffi` | **~1.4ms** |
39 +| macOS | Node | `/usr/bin/security` subprocess | ~22ms |
40 +| Linux | both | `secret-tool` subprocess (libsecret) | ~15–40ms |
41 +| Windows | Bun | `Cred*` via `bun:ffi` | not measured |
42 +| Windows | Node | throws `NoStorageAccess` | — |
43 +| BSD | both | throws `NoStorageAccess` | — |
44
45 The Composio CLI ships as a compiled Bun binary, so production reads always hit the FFI path. Node is the fallback for vitest-under-Node, dev tools, and anyone importing the package outside the CLI's runtime.
46
ts/packages/cli-keyring/src/index.ts
+15 -3
@@ -15,6 +15,8 @@
15 * subprocess. Same semantics, ~25ms reads.
16 * - **Linux**: `secret-tool` subprocess against the freedesktop
17 * Secret Service API, with keyring-rs-compatible attribute names.
18 + * - **Windows (Bun runtime)**: Credential Manager via `bun:ffi`
19 + * calls into `advapi32.dll`. There is no Node fallback.
20 *
21 * Typical usage:
22 *
@@ -52,8 +54,10 @@ import { UnsupportedPlatformStore } from './stores/unsupported';
54 * macOS under Bun this resolves to the fast FFI backend; under Node
55 * (typically tests or tools that import this package without Bun) it
56 * falls back to the `/usr/bin/security` subprocess backend. On Linux
55 - * it always returns the `secret-tool` subprocess backend. Unsupported
56 - * platforms return a store whose operations throw `NoStorageAccess`.
57 + * it always returns the `secret-tool` subprocess backend. On Windows
58 + * under Bun it returns the Credential Manager backend. Unsupported
59 + * platforms, and Windows under Node, return a store whose operations
60 + * throw `NoStorageAccess`.
61 *
62 * Call this once at process startup, pass the result to
63 * `setDefaultStore`, and use `new Entry(service, user)` everywhere.
@@ -66,13 +70,21 @@ export async function createDefaultStore(
70 return await createMacOSStore(options.macOSBackend ?? 'auto');
71 case 'linux':
72 return new LinuxSecretToolStore();
73 + case 'win32': {
74 + if (typeof (globalThis as { Bun?: unknown }).Bun === 'undefined') {
75 + return new UnsupportedPlatformStore('win32 without Bun');
76 + }
77 + const mod = await import('./stores/windows-credential-ffi');
78 + return new mod.WindowsCredentialFFIStore();
79 + }
80 default:
81 return new UnsupportedPlatformStore(process.platform);
82 }
83 }
84
85 /**
75 - * Synchronous fallback that never returns the FFI macOS backend —
86 + * Synchronous fallback that never returns an FFI backend, so Windows is
87 + * unsupported here —
88 * useful for callers that can't await at construction time (e.g. the
89 * Effect.ts `Layer.sync` variant) and are willing to accept the
90 * subprocess overhead. The async `createDefaultStore()` is strongly
ts/packages/cli-keyring/src/stores/unsupported.ts
+2 -2
@@ -1,5 +1,5 @@
1 /**
2 - * Fallback store used on unsupported platforms (Windows, BSDs, …).
2 + * Fallback store used on unsupported platforms (BSDs, Windows outside Bun, …).
3 *
4 * Every operation throws `KeyringError({ kind: 'NoStorageAccess' })`
5 * so the CLI can fall back to the legacy on-disk config without the
@@ -37,7 +37,7 @@ export class UnsupportedPlatformStore implements CredentialStore {
37 kind: 'NoStorageAccess',
38 cause: new Error(
39 `@composio/cli-keyring does not yet support ${this.vendor}. ` +
40 - 'Only macOS (Keychain via /usr/bin/security) and Linux (Secret Service via secret-tool) are implemented.'
40 + 'Only macOS (Keychain), Linux (Secret Service via secret-tool), and Windows under Bun (Credential Manager) are implemented.'
41 ),
42 });
43 }
ts/packages/cli-keyring/src/stores/windows-credential-ffi.ts new
+193
@@ -0,0 +1,193 @@
1 +/**
2 + * Windows Credential Manager store backed by `advapi32.dll` via `bun:ffi`.
3 + *
4 + * Each credential is a generic credential (`CRED_TYPE_GENERIC`) whose target
5 + * name is `{user}.{service}`, the convention keyring-rs uses on Windows. The
6 + * secret is stored as the raw credential blob, which Windows encrypts with
7 + * the signed-in user's key; other users of the machine cannot read it.
8 + *
9 + * There is no subprocess fallback: Windows ships no tool that reads a generic
10 + * credential back. This module must not be imported from Node, because it
11 + * depends on `bun:ffi`; `createDefaultStore` loads it only under Bun.
12 + */
13 +
14 +import { dlopen, FFIType, ptr, toArrayBuffer } from 'bun:ffi';
15 +import type { CredentialStore, EntryModifiers } from '../core/store';
16 +import { CredentialPersistence } from '../core/persistence';
17 +import { KeyringError } from '../core/errors';
18 +
19 +const CRED_TYPE_GENERIC = 1;
20 +/** Kept across sign-ins on this machine, and not roamed to other machines. */
21 +const CRED_PERSIST_LOCAL_MACHINE = 2;
22 +/** `CRED_MAX_CREDENTIAL_BLOB_SIZE` from wincred.h. */
23 +const MAX_SECRET_BYTES = 5 * 512;
24 +const ERROR_NOT_FOUND = 1168;
25 +
26 +/**
27 + * Field offsets of `CREDENTIALW` on 64-bit Windows:
28 + *
29 + * 0 DWORD Flags
30 + * 4 DWORD Type
31 + * 8 LPWSTR TargetName
32 + * 16 LPWSTR Comment
33 + * 24 FILETIME LastWritten
34 + * 32 DWORD CredentialBlobSize
35 + * 40 LPBYTE CredentialBlob
36 + * 48 DWORD Persist
37 + * 52 DWORD AttributeCount
38 + * 56 PCREDENTIAL_ATTRIBUTEW Attributes
39 + * 64 LPWSTR TargetAlias
40 + * 72 LPWSTR UserName
41 + */
42 +const CREDENTIAL_SIZE = 80;
43 +const OFFSET_TYPE = 4;
44 +const OFFSET_TARGET_NAME = 8;
45 +const OFFSET_BLOB_SIZE = 32;
46 +const OFFSET_BLOB = 40;
47 +const OFFSET_PERSIST = 48;
48 +const OFFSET_USER_NAME = 72;
49 +
50 +const advapi32 = dlopen('advapi32.dll', {
51 + CredWriteW: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.i32 },
52 + CredReadW: {
53 + args: [FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.ptr],
54 + returns: FFIType.i32,
55 + },
56 + CredDeleteW: { args: [FFIType.ptr, FFIType.u32, FFIType.u32], returns: FFIType.i32 },
57 + CredFree: { args: [FFIType.u64], returns: FFIType.void },
58 +});
59 +
60 +const kernel32 = dlopen('kernel32.dll', {
61 + GetLastError: { args: [], returns: FFIType.u32 },
62 +});
63 +
64 +/** Encode a JS string as a NUL-terminated UTF-16 buffer (`LPCWSTR`). */
65 +function wstr(value: string): Uint16Array {
66 + const buffer = new Uint16Array(value.length + 1);
67 + for (let i = 0; i < value.length; i++) buffer[i] = value.charCodeAt(i);
68 + return buffer;
69 +}
70 +
71 +function targetName(service: string, user: string): string {
72 + return `${user}.${service}`;
73 +}
74 +
75 +function validateSpecifier(service: string, user: string): void {
76 + for (const [param, value] of [
77 + ['service', service],
78 + ['user', user],
79 + ] as const) {
80 + if (value.length === 0) {
81 + throw new KeyringError({
82 + kind: 'Invalid',
83 + param,
84 + reason: `${param} must be a non-empty string`,
85 + });
86 + }
87 + if (value.includes('\0')) {
88 + throw new KeyringError({ kind: 'Invalid', param, reason: 'must not contain NUL bytes' });
89 + }
90 + }
91 +}
92 +
93 +/**
94 + * Map a failed `Cred*` call to a `KeyringError`. A lookup that fails without
95 + * an error code is treated as a missing entry: the runtime can reset the
96 + * thread's last-error value between the failing call and `GetLastError`.
97 + */
98 +function lookupError(operation: string): KeyringError {
99 + const code = kernel32.symbols.GetLastError();
100 + if (code === ERROR_NOT_FOUND || code === 0) {
101 + return new KeyringError({ kind: 'NoEntry' });
102 + }
103 + return platformFailure(operation, code);
104 +}
105 +
106 +function platformFailure(operation: string, code: number): KeyringError {
107 + return new KeyringError({
108 + kind: 'PlatformFailure',
109 + cause: new Error(`${operation} failed with Windows error ${code}`),
110 + });
111 +}
112 +
113 +export class WindowsCredentialFFIStore implements CredentialStore {
114 + readonly id = 'windows-credential-ffi';
115 + readonly vendor = 'Windows Credential Manager (via bun:ffi Cred*)';
116 +
117 + persistence(): CredentialPersistence {
118 + return CredentialPersistence.UntilDelete;
119 + }
120 +
121 + async setSecret(
122 + service: string,
123 + user: string,
124 + secret: Uint8Array,
125 + _modifiers: EntryModifiers
126 + ): Promise<void> {
127 + validateSpecifier(service, user);
128 + if (secret.byteLength > MAX_SECRET_BYTES) {
129 + throw new KeyringError({ kind: 'TooLong', attr: 'secret', limit: MAX_SECRET_BYTES });
130 + }
131 +
132 + // These buffers are referenced by address from the struct, so they must
133 + // stay alive until CredWriteW returns.
134 + const target = wstr(targetName(service, user));
135 + const userName = wstr(user);
136 + const blob = Uint8Array.from(secret);
137 +
138 + const credential = new Uint8Array(CREDENTIAL_SIZE);
139 + const view = new DataView(credential.buffer);
140 + view.setUint32(OFFSET_TYPE, CRED_TYPE_GENERIC, true);
141 + view.setBigUint64(OFFSET_TARGET_NAME, BigInt(ptr(target)), true);
142 + view.setUint32(OFFSET_BLOB_SIZE, blob.byteLength, true);
143 + view.setBigUint64(OFFSET_BLOB, blob.byteLength === 0 ? 0n : BigInt(ptr(blob)), true);
144 + view.setUint32(OFFSET_PERSIST, CRED_PERSIST_LOCAL_MACHINE, true);
145 + view.setBigUint64(OFFSET_USER_NAME, BigInt(ptr(userName)), true);
146 +
147 + // CredWriteW replaces an existing credential with the same target name.
148 + const written = advapi32.symbols.CredWriteW(credential, 0);
149 + if (written === 0) {
150 + throw platformFailure('CredWriteW', kernel32.symbols.GetLastError());
151 + }
152 + }
153 +
154 + async getSecret(service: string, user: string, _modifiers: EntryModifiers): Promise<Uint8Array> {
155 + validateSpecifier(service, user);
156 +
157 + // CredReadW writes a PCREDENTIALW into this 8-byte slot.
158 + const credentialOut = new BigUint64Array(1);
159 + const found = advapi32.symbols.CredReadW(
160 + wstr(targetName(service, user)),
161 + CRED_TYPE_GENERIC,
162 + 0,
163 + credentialOut
164 + );
165 + if (found === 0) {
166 + throw lookupError('CredReadW');
167 + }
168 +
169 + const credential = credentialOut[0] ?? 0n;
170 + try {
171 + const view = new DataView(toArrayBuffer(Number(credential) as never, 0, CREDENTIAL_SIZE));
172 + const size = view.getUint32(OFFSET_BLOB_SIZE, true);
173 + const blob = view.getBigUint64(OFFSET_BLOB, true);
174 + if (size === 0 || blob === 0n) return new Uint8Array(0);
175 + // Copy: the memory belongs to Windows and is released by CredFree below.
176 + return new Uint8Array(toArrayBuffer(Number(blob) as never, 0, size)).slice();
177 + } finally {
178 + advapi32.symbols.CredFree(credential);
179 + }
180 + }
181 +
182 + async deleteCredential(service: string, user: string, _modifiers: EntryModifiers): Promise<void> {
183 + validateSpecifier(service, user);
184 + const deleted = advapi32.symbols.CredDeleteW(
185 + wstr(targetName(service, user)),
186 + CRED_TYPE_GENERIC,
187 + 0
188 + );
189 + if (deleted === 0) {
190 + throw lookupError('CredDeleteW');
191 + }
192 + }
193 +}
ts/packages/cli-keyring/test/windows-credential.smoke.ts new
+44
@@ -0,0 +1,44 @@
1 +/**
2 + * Roundtrip check of the Windows Credential Manager store against the real
3 + * credential store. It needs `bun:ffi` and Windows, so it is a plain script
4 + * rather than a vitest suite:
5 + *
6 + * bun test/windows-credential.smoke.ts
7 + *
8 + * The native Windows CI job runs it with the compiled CLI as the Bun runtime.
9 + */
10 +
11 +import assert from 'node:assert/strict';
12 +import { randomUUID } from 'node:crypto';
13 +import { Entry } from '../src/core/entry';
14 +import { KeyringError } from '../src/core/errors';
15 +import { createDefaultStore, setDefaultStore } from '../src/index';
16 +
17 +const store = await createDefaultStore();
18 +assert.equal(store.id, 'windows-credential-ffi');
19 +setDefaultStore(store);
20 +
21 +const isNoEntry = (error: unknown) => error instanceof KeyringError && error.kind === 'NoEntry';
22 +const entry = new Entry(`com.composio.cli.test.${randomUUID()}`, 'default');
23 +
24 +await assert.rejects(entry.getPassword(), isNoEntry, 'a missing credential reads as NoEntry');
25 +
26 +await entry.setPassword('first');
27 +await entry.setPassword('second: ünïcödé ✓');
28 +assert.equal(await entry.getPassword(), 'second: ünïcödé ✓', 'the last write wins');
29 +
30 +const bytes = Uint8Array.from({ length: 256 }, (_, index) => index);
31 +await entry.setSecret(bytes);
32 +assert.deepEqual(Array.from(await entry.getSecret()), Array.from(bytes), 'binary roundtrip');
33 +
34 +await assert.rejects(
35 + entry.setSecret(new Uint8Array(4096)),
36 + (error: unknown) => error instanceof KeyringError && error.kind === 'TooLong',
37 + 'an oversized secret is rejected'
38 +);
39 +
40 +await entry.deleteCredential();
41 +await assert.rejects(entry.getPassword(), isNoEntry, 'a deleted credential reads as NoEntry');
42 +await assert.rejects(entry.deleteCredential(), isNoEntry, 'deleting twice reports NoEntry');
43 +
44 +console.log('Windows Credential Manager roundtrip passed.');
ts/packages/cli/CHANGELOG.md
+6
@@ -37,6 +37,12 @@
37
38 ### Minor Changes
39
40 +- Add experimental native Windows x64 CLI binaries, installed from PowerShell
41 + with a checksum-verified one-liner. Installation, `composio run`, and
42 + `composio upgrade` are checked on Windows in the beta and stable release
43 + workflows; other commands may not work yet. Windows requires Windows 10 1809
44 + or newer and an SSE4.2-capable x64 CPU.
45 +
46 - A signal now ends each command the way its work ends. A one-shot command,
47 `composio login` and `composio upgrade` stopped with Ctrl-C (SIGINT), SIGTERM
48 or a closed terminal (SIGHUP) exit 130, 143 or 129. They used to exit 0, so a
ts/packages/cli/README.md
+10
@@ -13,6 +13,16 @@ The CLI is built using:
13 - [Bun](https://bun.sh/)
14 - [Vitest](https://vitest.dev/)
15
16 +## Windows x64 (experimental)
17 +
18 +Run in PowerShell:
19 +
20 +```powershell
21 +irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex
22 +```
23 +
24 +See [INSTALL.md](../../../INSTALL.md#windows-x64-experimental) for options, requirements, and known limitations.
25 +
26 ## 🧑‍💻 Usage
27
28 ```
ts/packages/cli/lint-boundaries.json
+7
@@ -1,4 +1,11 @@
1 {
2 + "src/effects/install-skill.ts": [
3 + {
4 + "rule": "no-restricted-imports",
5 + "reason": "FileSystem.symlink cannot create a Windows junction, the only directory link that works without Developer Mode or administrator rights.",
6 + "target": "import { symlink } from 'node:fs/promises';"
7 + }
8 + ],
9 "src/services/composio-clients.ts": [
10 {
11 "rule": "no-restricted-imports",
ts/packages/cli/scripts/_release-artifacts.ts
+20 -7
@@ -8,14 +8,27 @@
8 import { RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS } from '../src/services/run-companion-modules';
9
10 /**
11 - * Known binary artifact names (without extension).
11 + * Every published platform: the Bun cross-compilation target and the artifact it produces.
12 */
13 -export const ARTIFACT_NAMES: ReadonlyArray<string> = [
14 - 'composio-darwin-aarch64',
15 - 'composio-darwin-x64',
16 - 'composio-linux-x64',
17 - 'composio-linux-aarch64',
18 -];
13 +export const RELEASE_TARGETS = [
14 + { bunTarget: 'bun-darwin-arm64', artifact: 'composio-darwin-aarch64' },
15 + { bunTarget: 'bun-darwin-x64', artifact: 'composio-darwin-x64' },
16 + { bunTarget: 'bun-linux-x64', artifact: 'composio-linux-x64' },
17 + { bunTarget: 'bun-linux-arm64', artifact: 'composio-linux-aarch64' },
18 + { bunTarget: 'bun-windows-x64', artifact: 'composio-windows-x64' },
19 +] as const;
20 +
21 +export type ReleaseTarget = (typeof RELEASE_TARGETS)[number];
22 +
23 +const isWindowsArtifact = (artifact: string): boolean => artifact.startsWith('composio-windows-');
24 +
25 +/** File name of the compiled binary in `dist/binaries/`. */
26 +export const compiledBinaryFileName = (artifact: string): string =>
27 + isWindowsArtifact(artifact) ? `${artifact}.exe` : artifact;
28 +
29 +/** Name of the executable inside the published archive. */
30 +export const archiveExecutableName = (artifact: string): string =>
31 + isWindowsArtifact(artifact) ? 'composio.exe' : 'composio';
32
33 export type ArchiveCompanionEntryKind = 'copy' | 'placeholder';
34
ts/packages/cli/scripts/_shared.ts
+55 -1
@@ -2,10 +2,14 @@ import { builtinModules } from 'node:module';
2 import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
3 import * as path from 'node:path';
4 import process from 'node:process';
5 -import { Effect } from 'effect';
5 +import { Console, Effect, Stream } from 'effect';
6 +import { ChildProcess as Command } from 'effect/process';
7 import { RUN_COMPANION_MODULE_BASENAMES } from '../src/services/run-companion-modules';
8 import { buildCliReleaseVersionDefineArgs } from '../src/utils/cli-release-version';
9
10 +import { BinaryBuildError } from './build-error';
11 +import { compiledBinaryFileName, type ReleaseTarget } from './_release-artifacts';
12 +
13 export { teardown } from './_teardown';
14
15 const RUN_COMPANION_SERVICE_ENTRY_MAP = Object.fromEntries(
@@ -355,3 +359,53 @@ export const buildCompanionModules = (outputDir: string) =>
359 yield* Effect.tryPromise(() => assertBundledRuntimeFiles(outputDir));
360 yield* Effect.tryPromise(() => assertExecutableExcludesCompanionModules());
361 });
362 +
363 +/**
364 + * Cross-compile the CLI for one release target. Returns the path of the compiled binary.
365 + */
366 +export const compileBinary = ({ bunTarget, artifact }: ReleaseTarget) =>
367 + Effect.gen(function* () {
368 + const outfile = `./dist/binaries/${compiledBinaryFileName(artifact)}`;
369 + const args = [
370 + 'build',
371 + './src/bin.ts',
372 + '--env',
373 + 'DEBUG_OVERRIDE_*',
374 + ...posthogBakeArgs(),
375 + ...buildCliReleaseVersionDefineArgs(process.env.RELEASE_TAG),
376 + '--compile',
377 + '--production',
378 + '--target',
379 + bunTarget,
380 + '--outfile',
381 + outfile,
382 + ];
383 + yield* Effect.logDebug(`Running bun ${args.join(' ')}`);
384 +
385 + const child = yield* Command.make('bun', args);
386 + const { exitCode } = yield* Effect.all(
387 + {
388 + exitCode: child.exitCode,
389 + output: Stream.merge(
390 + Stream.decodeText(child.stdout, { encoding: 'utf-8' }),
391 + Stream.decodeText(child.stderr, { encoding: 'utf-8' }),
392 + { haltStrategy: 'left' }
393 + ).pipe(
394 + Stream.tap(chunk => Console.log(chunk)),
395 + Stream.runDrain
396 + ),
397 + },
398 + { concurrency: 'unbounded' }
399 + );
400 +
401 + if (exitCode !== 0) {
402 + // `teardown` exits with this code.
403 + process.exitCode = exitCode;
404 + return yield* new BinaryBuildError({
405 + message: `Failed to build binary for ${bunTarget}`,
406 + target: bunTarget,
407 + exitCode,
408 + });
409 + }
410 + return outfile;
411 + });
ts/packages/cli/scripts/build-all-binaries.ts
+9 -71
@@ -5,86 +5,24 @@
5 *
6 * Usage: `bun scripts/build-all-binaries.ts`
7 *
8 - * Builds all 4 targets sequentially:
9 - * composio-darwin-aarch64, composio-darwin-x64,
10 - * composio-linux-x64, composio-linux-aarch64
8 + * Builds every target in `RELEASE_TARGETS` sequentially.
9 *
10 * Output: `dist/binaries/composio-*`
11 */
12
15 -import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, References } from 'effect';
16 -import { ChildProcess as Command } from 'effect/process';
13 +import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
14 import * as BunServices from '@effect/platform-bun/BunServices';
15 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
19 -import { buildCompanionModules, posthogBakeArgs, teardown } from './_shared';
20 -import { BinaryBuildError } from './build-error';
21 -import { buildCliReleaseVersionDefineArgs } from '../src/utils/cli-release-version';
22 -
23 -/**
24 - * All cross-compilation targets and their artifact names.
25 - */
26 -const TARGETS = [
27 - { target: 'bun-darwin-arm64', artifact: 'composio-darwin-aarch64' },
28 - { target: 'bun-darwin-x64', artifact: 'composio-darwin-x64' },
29 - { target: 'bun-linux-x64', artifact: 'composio-linux-x64' },
30 - { target: 'bun-linux-arm64', artifact: 'composio-linux-aarch64' },
31 -] as const;
32 -
33 -function runBunBuild(target: string, outfile: string) {
34 - return Effect.gen(function* () {
35 - const args = [
36 - 'bun',
37 - 'build',
38 - './src/bin.ts',
39 - '--env',
40 - 'DEBUG_OVERRIDE_*',
41 - ...posthogBakeArgs(),
42 - ...buildCliReleaseVersionDefineArgs(process.env.RELEASE_TAG),
43 - '--compile',
44 - '--production',
45 - '--target',
46 - target,
47 - '--outfile',
48 - outfile,
49 - ] as const satisfies ReadonlyArray<string>;
50 -
51 - const child = yield* Command.make(args[0], args.slice(1));
52 -
53 - const { exitCode } = yield* Effect.all(
54 - {
55 - exitCode: child.exitCode,
56 - output: Stream.merge(
57 - Stream.decodeText(child.stdout, { encoding: 'utf-8' }),
58 - Stream.decodeText(child.stderr, { encoding: 'utf-8' }),
59 - { haltStrategy: 'left' }
60 - ).pipe(
61 - Stream.tap(chunk => Console.log(chunk)),
62 - Stream.runDrain
63 - ),
64 - },
65 - {
66 - concurrency: 'unbounded',
67 - }
68 - );
69 -
70 - if (exitCode !== 0) {
71 - return yield* new BinaryBuildError({
72 - message: `Failed to build binary for ${target}`,
73 - target,
74 - exitCode,
75 - });
76 - }
77 - });
78 -}
16 +import { buildCompanionModules, compileBinary, teardown } from './_shared';
17 +import { RELEASE_TARGETS } from './_release-artifacts';
18
19 export function buildAllBinaries() {
20 return Effect.gen(function* () {
82 - yield* Console.log(`Building ${TARGETS.length} platform binaries...`);
21 + yield* Console.log(`Building ${RELEASE_TARGETS.length} platform binaries...`);
22
84 - for (const { target, artifact } of TARGETS) {
85 - const outfile = `./dist/binaries/${artifact}`;
86 - yield* Console.log(`\nBuilding ${artifact} (${target})...`);
87 - yield* runBunBuild(target, outfile);
23 + for (const target of RELEASE_TARGETS) {
24 + yield* Console.log(`\nBuilding ${target.artifact} (${target.bunTarget})...`);
25 + const outfile = yield* compileBinary(target);
26 yield* Console.log(`Built: ${outfile}`);
27 }
28
@@ -92,7 +30,7 @@ export function buildAllBinaries() {
30 yield* Console.log(`\nBuilding run companion modules in ${companionOutputDir}...`);
31 yield* buildCompanionModules(companionOutputDir);
32
95 - yield* Console.log(`\nAll ${TARGETS.length} binaries built successfully.`);
33 + yield* Console.log(`\nAll ${RELEASE_TARGETS.length} binaries built successfully.`);
34 });
35 }
36
ts/packages/cli/scripts/build-binary-cross.ts
+23 -89
@@ -5,113 +5,47 @@
5 *
6 * Usage: `bun scripts/build-binary-cross.ts --target <target>`
7 *
8 - * Valid targets:
9 - * bun-darwin-arm64 → composio-darwin-aarch64
10 - * bun-darwin-x64 → composio-darwin-x64
11 - * bun-linux-x64 → composio-linux-x64
12 - * bun-linux-arm64 → composio-linux-aarch64
8 + * Valid targets are the `bunTarget` values of `RELEASE_TARGETS`.
9 *
14 - * Output: `dist/binaries/<artifact-name>`
10 + * Output: `dist/binaries/<artifact-name>` (`.exe` on Windows)
11 */
12
13 import process from 'node:process';
18 -import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, References } from 'effect';
19 -import { ChildProcess as Command } from 'effect/process';
14 +import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
15 import * as BunServices from '@effect/platform-bun/BunServices';
16 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
22 -import { buildCompanionModules, posthogBakeArgs, teardown } from './_shared';
23 -import { BinaryBuildError } from './build-error';
24 -import { buildCliReleaseVersionDefineArgs } from '../src/utils/cli-release-version';
17 +import { buildCompanionModules, compileBinary, teardown } from './_shared';
18 +import { RELEASE_TARGETS, type ReleaseTarget } from './_release-artifacts';
19
26 -/**
27 - * Maps Bun cross-compilation targets to Composio artifact names.
28 - */
29 -const TARGET_MAP: Record<string, string> = {
30 - 'bun-darwin-arm64': 'composio-darwin-aarch64',
31 - 'bun-darwin-x64': 'composio-darwin-x64',
32 - 'bun-linux-x64': 'composio-linux-x64',
33 - 'bun-linux-arm64': 'composio-linux-aarch64',
34 -};
35 -
36 -const VALID_TARGETS = Object.keys(TARGET_MAP);
37 -
38 -function parseTarget(): { target: string; artifact: string } {
20 +function parseTarget(): ReleaseTarget {
21 const targetIdx = process.argv.indexOf('--target');
40 - if (targetIdx === -1 || !process.argv[targetIdx + 1]) {
41 - process.stderr.write(`Usage: bun scripts/build-binary-cross.ts --target <target>\n`);
42 - process.stderr.write(`Valid targets: ${VALID_TARGETS.join(', ')}\n`);
43 - process.exit(1);
44 - }
45 -
46 - const target = process.argv[targetIdx + 1];
47 - const artifact = TARGET_MAP[target];
48 - if (!artifact) {
49 - process.stderr.write(`Invalid target: ${target}\n`);
50 - process.stderr.write(`Valid targets: ${VALID_TARGETS.join(', ')}\n`);
22 + const requested = targetIdx === -1 ? undefined : process.argv[targetIdx + 1];
23 + const target = RELEASE_TARGETS.find(({ bunTarget }) => bunTarget === requested);
24 + if (!target) {
25 + process.stderr.write(
26 + requested
27 + ? `Invalid target: ${requested}\n`
28 + : `Usage: bun scripts/build-binary-cross.ts --target <target>\n`
29 + );
30 + process.stderr.write(
31 + `Valid targets: ${RELEASE_TARGETS.map(({ bunTarget }) => bunTarget).join(', ')}\n`
32 + );
33 process.exit(1);
34 }
53 -
54 - return { target, artifact };
35 + return target;
36 }
37
38 export function buildBinaryCross() {
58 - const { target, artifact } = parseTarget();
39 + const target = parseTarget();
40
41 return Effect.gen(function* () {
61 - const cwd = process.cwd();
62 - yield* Effect.logDebug(`Cross-compiling binary in ${cwd} for target ${target}`);
63 -
64 - const outfile = `./dist/binaries/${artifact}`;
65 -
66 - const args = [
67 - 'bun',
68 - 'build',
69 - './src/bin.ts',
70 - '--env',
71 - 'DEBUG_OVERRIDE_*',
72 - ...posthogBakeArgs(),
73 - ...buildCliReleaseVersionDefineArgs(process.env.RELEASE_TAG),
74 - '--compile',
75 - '--production',
76 - '--target',
77 - target,
78 - '--outfile',
79 - outfile,
80 - ] as const satisfies ReadonlyArray<string>;
81 -
82 - const child = yield* Command.make(args[0], args.slice(1));
83 -
84 - yield* Effect.logDebug('Running build command with', args.join(' '), '');
85 -
86 - const { exitCode } = yield* Effect.all(
87 - {
88 - exitCode: child.exitCode,
89 - output: Stream.merge(
90 - Stream.decodeText(child.stdout, { encoding: 'utf-8' }),
91 - Stream.decodeText(child.stderr, { encoding: 'utf-8' }),
92 - { haltStrategy: 'left' }
93 - ).pipe(
94 - Stream.tap(chunk => Console.log(chunk)),
95 - Stream.runDrain
96 - ),
97 - },
98 - {
99 - concurrency: 'unbounded',
100 - }
42 + yield* Effect.logDebug(
43 + `Cross-compiling binary in ${process.cwd()} for target ${target.bunTarget}`
44 );
45
103 - process.exitCode = exitCode;
104 -
105 - if (exitCode !== 0) {
106 - return yield* new BinaryBuildError({
107 - message: `Failed to cross-compile binary for ${target}`,
108 - target,
109 - exitCode,
110 - });
111 - }
46 + const outfile = yield* compileBinary(target);
47
113 - const companionOutputDir = './dist/binaries/companions';
114 - yield* buildCompanionModules(companionOutputDir);
48 + yield* buildCompanionModules('./dist/binaries/companions');
49
50 yield* Console.log(`Binary cross-compiled: ${outfile}`);
51 });
ts/packages/cli/scripts/package-binaries.ts
+13 -6
@@ -6,9 +6,9 @@
6 * Usage: `bun scripts/package-binaries.ts`
7 *
8 * Creates a nested directory structure inside each zip:
9 - * composio-<target>/composio
9 + * composio-<target>/composio (composio.exe on Windows)
10 *
11 - * This matches the structure expected by `install.sh`.
11 + * This matches the structure expected by `install.sh` and `install.ps1`.
12 *
13 * Input: `dist/binaries/composio-{platform-arch}` (raw binaries)
14 * Output: `dist/binaries/composio-{platform-arch}.zip`
@@ -23,7 +23,12 @@ import { $ } from 'bun';
23 import { readdir, stat, writeFile } from 'node:fs/promises';
24 import path from 'node:path';
25 import { collectExpectedRunCompanionAssetRelativePaths } from '../src/services/run-companion-modules';
26 -import { archiveCompanionEntries, ARTIFACT_NAMES } from './_release-artifacts';
26 +import {
27 + archiveCompanionEntries,
28 + archiveExecutableName,
29 + compiledBinaryFileName,
30 + RELEASE_TARGETS,
31 +} from './_release-artifacts';
32
33 const BINARIES_DIR = './dist/binaries';
34 const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');
@@ -33,7 +38,9 @@ export function packageBinaries() {
38 return Effect.gen(function* () {
39 const entries = yield* Effect.tryPromise(() => readdir(BINARIES_DIR));
40
36 - const binaries = entries.filter(entry => ARTIFACT_NAMES.includes(entry));
41 + const binaries = RELEASE_TARGETS.map(({ artifact }) => artifact).filter(artifact =>
42 + entries.includes(compiledBinaryFileName(artifact))
43 + );
44
45 if (binaries.length === 0) {
46 yield* Console.error('No binaries found in dist/binaries/. Run build:binary:all first.');
@@ -63,7 +70,7 @@ export function packageBinaries() {
70 const companionEntries = archiveCompanionEntries(liveCompanionRelativePaths);
71
72 for (const binary of binaries) {
66 - const binaryPath = path.join(BINARIES_DIR, binary);
73 + const binaryPath = path.join(BINARIES_DIR, compiledBinaryFileName(binary));
74 const zipPath = path.join(BINARIES_DIR, `${binary}.zip`);
75 const absoluteZipPath = path.resolve(zipPath);
76
@@ -75,7 +82,7 @@ export function packageBinaries() {
82 await $`rm -f ${zipPath}`.quiet();
83 await $`rm -rf ${tempDir}`.quiet();
84 await $`mkdir -p ${nestedDir}`.quiet();
78 - await $`cp ${binaryPath} ${nestedDir}/composio`.quiet();
85 + await $`cp ${binaryPath} ${path.join(nestedDir, archiveExecutableName(binary))}`.quiet();
86 for (const { relativePath, kind } of companionEntries) {
87 const destinationPath = path.join(nestedDir, relativePath);
88 await $`mkdir -p ${path.dirname(destinationPath)}`.quiet();
ts/packages/cli/src/commands/install/install.handler.ts
+7
@@ -465,6 +465,13 @@ export const installShellIntegration = (params: {
465
466 yield* ui.intro(INSTALL_INTRO);
467
468 + if (os.platform === 'win32') {
469 + return yield* abortShellSetup(
470 + report,
471 + 'Shell setup is not available on Windows. The PowerShell installer already adds the CLI to your PATH.'
472 + );
473 + }
474 +
475 // Resolve the entry-point bin dir: explicit env, then a ~/.local/bin/composio
476 // that is this executable, then the runtime executable's own directory.
477 const envBinDir = yield* APP_CONFIG.BIN_DIR.pipe(Effect.orDie);
ts/packages/cli/src/commands/run/run.handler.ts
+2 -1
@@ -31,6 +31,7 @@ import { invocationRunId } from 'src/invocation/command-identity';
31 import {
32 repairMissingInstalledRunCompanionModules,
33 resolveRunCompanionModulePath,
34 + isBunVirtualPath,
35 } from 'src/services/run-companion-modules';
36 import {
37 appendCliSessionHistory,
@@ -66,7 +67,7 @@ export const inferCliInvocationPrefix = (
67 // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be
68 // re-executed as a real filesystem path. In that case the binary itself is
69 // the CLI entrypoint.
69 - if (entrypoint.startsWith('/$bunfs/')) {
70 + if (isBunVirtualPath(entrypoint)) {
71 return [process.execPath];
72 }
73
ts/packages/cli/src/effects/detect-platform.ts
+7 -2
@@ -5,7 +5,7 @@ import { NodeOs } from '../services/node-os';
5 * Platform and architecture detection types
6 */
7 export type PlatformArch = {
8 - platform: 'darwin' | 'linux';
8 + platform: 'darwin' | 'linux' | 'windows';
9 arch: 'x64' | 'aarch64';
10 };
11
@@ -23,9 +23,14 @@ export const detectPlatform: Effect.Effect<PlatformArch, UnsupportedPlatformErro
23 const rawPlatform = nodeOs.platform;
24 const rawArch: string = nodeOs.arch;
25
26 - const platform: NodeJS.Platform = yield* Match.value(rawPlatform).pipe(
26 + const platform: PlatformArch['platform'] = yield* Match.value(rawPlatform).pipe(
27 Match.when('darwin', () => Effect.succeed('darwin' as const)),
28 Match.when('linux', () => Effect.succeed('linux' as const)),
29 + Match.when('win32', () =>
30 + rawArch === 'x64'
31 + ? Effect.succeed('windows' as const)
32 + : Effect.fail(new UnsupportedPlatformError({ platform: rawPlatform, arch: rawArch }))
33 + ),
34 Match.orElse(() =>
35 Effect.fail(new UnsupportedPlatformError({ platform: rawPlatform, arch: rawArch }))
36 )
ts/packages/cli/src/effects/install-skill.ts
+16 -2
@@ -1,3 +1,5 @@
1 +// eslint-disable-next-line no-restricted-imports -- FileSystem.symlink cannot create a Windows junction, the only directory link that works without Developer Mode or administrator rights.
2 +import { symlink } from 'node:fs/promises';
3 import { Data, Effect, FileSystem, Path } from 'effect';
4 import { HttpClient } from 'effect/http';
5 import { NodeOs } from 'src/services/node-os';
@@ -241,8 +243,20 @@ export const installSkill = (options?: {
243
244 yield* fs.makeDirectory(path.dirname(targetSkillPath), { recursive: true });
245 yield* fs.remove(targetSkillPath, { recursive: true, force: true });
244 - const relativeTarget = path.relative(path.dirname(targetSkillPath), agentSkillDir);
245 - yield* fs.symlink(relativeTarget, targetSkillPath);
246 + yield* os.platform === 'win32'
247 + ? Effect.tryPromise({
248 + try: () => symlink(agentSkillDir, targetSkillPath, 'junction'),
249 + catch: cause =>
250 + new SkillInstallError({
251 + cause,
252 + message: `Failed to link the skill into ${targetSkillPath}`,
253 + phase: 'extract',
254 + }),
255 + })
256 + : fs.symlink(
257 + path.relative(path.dirname(targetSkillPath), agentSkillDir),
258 + targetSkillPath
259 + );
260 }).pipe(Effect.uninterruptible);
261 }).pipe(
262 Effect.ensuring(fs.remove(tmpDir, { recursive: true, force: true }).pipe(Effect.orDie))
ts/packages/cli/src/invocation/live.ts
+3 -6
@@ -3,7 +3,6 @@
3 * `cli-main.ts` provides it; tests provide `TestLive` instead.
4 */
5 import { Layer, Logger } from 'effect';
6 -import * as Path from 'effect/Path';
6 import { CliConfig } from 'effect/cli';
7 import { FetchHttpClient } from 'effect/http';
8 import * as BunServices from '@effect/platform-bun/BunServices';
@@ -73,7 +72,7 @@ export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
72
73 export const UpgradeBinaryLive = Layer.provide(
74 UpgradeBinary.Default,
76 - Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
75 + Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer, NodeOs.Default)
76 ) satisfies RequiredLayer;
77
78 export const TriggersRealtimeLive = Layer.provide(
@@ -128,11 +127,9 @@ export const CommandLifecycleTelemetryLive = Layer.provide(
127 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, TerminalUILive)
128 ) satisfies RequiredLayer;
129
131 -// `Path.layer`, not `BunPath.layer`: the update notice and the plugin hint have always resolved
132 -// their state files with Effect's own path implementation.
130 export const UpdateNoticeLive = Layer.provide(
131 UpdateNotice.Default,
135 - Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
132 + Layer.mergeAll(TerminalUILive, BunFileSystem.layer, BunPath.layer, NodeOs.Default)
133 ) satisfies RequiredLayer;
134
135 export const PluginHintLive = Layer.provide(
@@ -141,7 +138,7 @@ export const PluginHintLive = Layer.provide(
138 TerminalUILive,
139 CommandLifecycleTelemetryLive,
140 BunFileSystem.layer,
144 - Path.layer,
141 + BunPath.layer,
142 NodeOs.Default
143 )
144 ) satisfies RequiredLayer;
ts/packages/cli/src/services/composio-clients-cached.ts
+2 -1
@@ -1,3 +1,4 @@
1 +import * as BunPath from '@effect/platform-bun/BunPath';
2 import { Cache, Effect, Option, Schema, Layer, Array as Arr } from 'effect';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
@@ -146,7 +147,7 @@ function createCachedEffect<T, E, R>(
147 // This ensures the returned effect has the same error type as the original computation
148 // by providing all the required cache services
149 return cacheEffect.pipe(
149 - Effect.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer, NodeOs.Default))
150 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default))
151 ) as Effect.Effect<T, E, R>;
152 }
153
ts/packages/cli/src/services/js-package-manager-detector.ts
+2 -1
@@ -1,3 +1,4 @@
1 +import * as BunPath from '@effect/platform-bun/BunPath';
2 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 import { Context, Data, Effect, Layer, Option, Schema, pipe } from 'effect';
4 import * as FileSystem from 'effect/FileSystem';
@@ -160,5 +161,5 @@ export class JsPackageManagerDetector extends Context.Service<
161 static readonly Default: Layer.Layer<JsPackageManagerDetector> = Layer.effect(
162 JsPackageManagerDetector,
163 makeJsPackageManagerDetector
163 - ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));
164 + ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)));
165 }
ts/packages/cli/src/services/known-toolkit-slugs.ts
+2 -1
@@ -1,3 +1,4 @@
1 +import * as BunPath from '@effect/platform-bun/BunPath';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
@@ -47,7 +48,7 @@ const KnownToolkitSlugsJSON = JSONTransformSchema(KnownToolkitSlugs);
48 const provideFileSystem = <A, E>(
49 effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | NodeOs>
50 ): Effect.Effect<A, E> =>
50 - effect.pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer, NodeOs.Default)));
51 + effect.pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)));
52
53 const knownToolkitSlugsPath = Effect.gen(function* () {
54 const path = yield* Path.Path;
ts/packages/cli/src/services/pending-login-session.ts
+7 -2
@@ -66,6 +66,11 @@ const makePendingLoginSession = Effect.gen(function* () {
66 const path = yield* Path.Path;
67 const os = yield* NodeOs;
68
69 + // A login without a terminal on stdin is what caches a pending login. PowerShell has no
70 + // `<` redirection, so it gets an empty pipeline instead.
71 + const headlessLoginCommand =
72 + os.platform === 'win32' ? '$null | composio login' : 'composio login < /dev/null';
73 +
74 // Resolved on every call: the cache directory comes from configuration read at call time.
75 const filePath = setupCacheDir.pipe(
76 Effect.map(cacheDir => path.join(cacheDir, PENDING_LOGIN_FILE_NAME)),
@@ -98,7 +103,7 @@ const makePendingLoginSession = Effect.gen(function* () {
103 exists => exists,
104 () =>
105 new PendingLoginError({
101 - message: 'No pending login found. Run `composio login < /dev/null` first.',
106 + message: `No pending login found. Run \`${headlessLoginCommand}\` first.`,
107 reason: 'missing',
108 })
109 )
@@ -128,7 +133,7 @@ const makePendingLoginSession = Effect.gen(function* () {
133 if (isExpired(session.cachedAt, now)) {
134 yield* clear;
135 return yield* new PendingLoginError({
131 - message: 'Pending login expired. Run `composio login < /dev/null` again.',
136 + message: `Pending login expired. Run \`${headlessLoginCommand}\` again.`,
137 reason: 'expired',
138 });
139 }
ts/packages/cli/src/services/project-context.ts
+2 -1
@@ -1,3 +1,4 @@
1 +import * as BunPath from '@effect/platform-bun/BunPath';
2 import { Effect, Option, Context, Layer } from 'effect';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
@@ -155,6 +156,6 @@ export class ProjectContext extends Context.Service<ProjectContext, ProjectConte
156 'services/ProjectContext'
157 ) {
158 static readonly Default = Layer.effect(ProjectContext, makeProjectContext).pipe(
158 - Layer.provide(Path.layer)
159 + Layer.provide(BunPath.layer)
160 );
161 }
ts/packages/cli/src/services/project-environment-detector.ts
+2 -1
@@ -1,3 +1,4 @@
1 +import * as BunPath from '@effect/platform-bun/BunPath';
2 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
@@ -603,5 +604,5 @@ export class ProjectEnvironmentDetector extends Context.Service<
604 static readonly Default = Layer.effect(
605 ProjectEnvironmentDetector,
606 makeProjectEnvironmentDetector
606 - ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));
607 + ).pipe(Layer.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)));
608 }
ts/packages/cli/src/services/run-companion-modules.ts
+9 -3
@@ -67,6 +67,10 @@ const isImportGraphFile = (relativePath: string) => /\.(?:m?js|ts)$/.test(relati
67 const fileExists = (fs: FileSystem.FileSystem, filePath: string) =>
68 fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
69
70 +export const isBunVirtualPath = (filePath: string): boolean =>
71 + /^(?:\/?[A-Za-z]:)?[/\\]\$bunfs[/\\]/.test(filePath) ||
72 + /^\/?[A-Za-z]:[/\\]~BUN[/\\]/.test(filePath);
73 +
74 const filePathFromUrl = (path: Path.Path, url: string): Effect.Effect<string> =>
75 Schema.decodeUnknownEffect(Schema.URLFromString)(url).pipe(
76 Effect.flatMap(path.fromFileUrl),
@@ -157,7 +161,7 @@ export const collectExpectedRunCompanionAssetRelativePaths = (
161 return [...collected].sort();
162 });
163
160 -const resolveBinaryAssetName = ({
164 +export const resolveBinaryAssetName = ({
165 platform = process.platform,
166 arch = process.arch,
167 }: {
@@ -173,6 +177,8 @@ const resolveBinaryAssetName = ({
177 return 'composio-linux-x64.zip';
178 case 'linux-arm64':
179 return 'composio-linux-aarch64.zip';
180 + case 'win32-x64':
181 + return 'composio-windows-x64.zip';
182 default:
183 return undefined;
184 }
@@ -428,7 +434,7 @@ export const repairMissingInstalledRunCompanionModules = ({
434 const path = yield* Path.Path;
435
436 const currentFilePath = yield* filePathFromUrl(path, callerImportMetaUrl);
431 - if (!currentFilePath.startsWith('/$bunfs/')) {
437 + if (!isBunVirtualPath(currentFilePath)) {
438 return { repaired: false as const };
439 }
440
@@ -608,7 +614,7 @@ export const resolveRunCompanionModulePath = ({
614
615 const found = yield* Effect.findFirst(candidates, candidate => fileExists(fs, candidate));
616 return Option.getOrElse(found, () =>
611 - currentFilePath.startsWith('/$bunfs/')
617 + isBunVirtualPath(currentFilePath)
618 ? path.resolve(executableDirectory, `${baseName}.mjs`)
619 : path.resolve(currentDirectory, `${baseName}.mjs`)
620 );
ts/packages/cli/src/services/run-helpers-runtime.ts
+2 -1
@@ -1,3 +1,4 @@
1 +import * as BunPath from '@effect/platform-bun/BunPath';
2 import { cliRequestHeaders } from './client-provenance';
3 // This module is preloaded into the user's spawned child process, where no Effect
4 // runtime or @effect/platform layers are provided, so it uses sync Node builtins.
@@ -865,7 +866,7 @@ export const installRunHelpers = async ({
866 // This preload runs in the user's child process, outside the CLI runtime.
867 // Resolve the live services once at that boundary and keep all writes centralized.
868 const terminal = Effect.runSync(TerminalUI.pipe(Effect.provide(TerminalUILive)));
868 - const path = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));
869 + const path = Effect.runSync(Path.Path.pipe(Effect.provide(BunPath.layer)));
870 const nodeOs = Effect.runSync(NodeOs.pipe(Effect.provide(NodeOs.Default)));
871 const writeError = (line: string) => Effect.runSync(terminal.error(line));
872
ts/packages/cli/src/services/setup.ts
+25 -2
@@ -16,6 +16,8 @@ import {
16 } from './agent-host';
17 import { probeHostInstallation } from './agent-host-env';
18 import { CommandRunner, type CommandResult } from './command-runner';
19 +import { NodeOs } from './node-os';
20 +import { resolveWindowsExecutable } from './windows-executable';
21 import { SetupCommandError } from './setup-command-error';
22 import { SetupSkillInstaller } from './setup-skill-installer';
23 import { cliInvocationContext } from './runtime-cli-context';
@@ -272,6 +274,27 @@ const pluginState = (
274 const commandText = (executable: string, args: ReadonlyArray<string>) =>
275 [executable, ...args].join(' ');
276
277 +/**
278 + * The command that runs an agent host's CLI. On Windows the executable is located first:
279 + * an npm-installed host is a `.cmd` shim, which has to run through a shell. Its arguments
280 + * are fixed by `ADAPTERS` and contain nothing a shell would interpret.
281 + */
282 +const hostCommand = (adapter: SetupTargetAdapter, args: ReadonlyArray<string>) =>
283 + Effect.gen(function* () {
284 + const os = yield* NodeOs;
285 + const resolved =
286 + os.platform === 'win32' ? yield* resolveWindowsExecutable(adapter.executable) : Option.none();
287 + return Option.match(resolved, {
288 + // Not found, or not Windows: spawning by name reports a missing executable as usual.
289 + onNone: () => Command.make(adapter.executable, args),
290 + onSome: executable =>
291 + executable.needsShell
292 + ? // A shell takes one command line, not an argument list.
293 + Command.make([`"${executable.path}"`, ...args].join(' '), [], { shell: true })
294 + : Command.make(executable.path, args),
295 + });
296 + });
297 +
298 const capture = (
299 adapter: SetupTargetAdapter,
300 args: ReadonlyArray<string>,
@@ -279,7 +302,7 @@ const capture = (
302 ) =>
303 Effect.gen(function* () {
304 const runner = yield* CommandRunner;
282 - return yield* runner.capture(Command.make(adapter.executable, args)).pipe(
305 + return yield* runner.capture(yield* hostCommand(adapter, args)).pipe(
306 Effect.timeoutOrElse({
307 duration: SETUP_COMMAND_TIMEOUT,
308 orElse: () =>
@@ -629,7 +652,7 @@ const runRequired = (
652 ) =>
653 Effect.gen(function* () {
654 const runner = yield* CommandRunner;
632 - const result = yield* runner.capture(Command.make(adapter.executable, args)).pipe(
655 + const result = yield* runner.capture(yield* hostCommand(adapter, args)).pipe(
656 Effect.timeoutOrElse({
657 duration: SETUP_COMMAND_TIMEOUT,
658 orElse: () =>
ts/packages/cli/src/services/update-check.ts
+5 -15
@@ -1,3 +1,4 @@
1 +import * as BunPath from '@effect/platform-bun/BunPath';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
@@ -8,8 +9,8 @@ import { GITHUB_CONFIG } from 'src/config';
9 import { captureServices } from 'src/effects/capture-services';
10 import { APP_VERSION } from '../constants';
11 import type { InvocationHookShape } from './invocation-hook';
11 -import { NodeOs, type NodeOsShape } from './node-os';
12 -import { resolveRunningCliVersion } from './run-companion-modules';
12 +import { NodeOs } from './node-os';
13 +import { resolveBinaryAssetName, resolveRunningCliVersion } from './run-companion-modules';
14 import { TerminalUI } from './terminal-ui';
15
16 /**
@@ -97,17 +98,6 @@ const defaultStateFile = Effect.gen(function* () {
98 return path.join(os.homedir, '.composio', 'update-check.json');
99 });
100
100 -function getCurrentBinaryAssetName(os: Pick<NodeOsShape, 'platform' | 'arch'>): string | undefined {
101 - const { platform } = os;
102 - const rawArch: string = os.arch;
103 - if (platform !== 'darwin' && platform !== 'linux') return undefined;
104 -
105 - const arch = rawArch === 'arm64' || rawArch === 'aarch64' ? 'aarch64' : rawArch;
106 - if (arch !== 'x64' && arch !== 'aarch64') return undefined;
107 -
108 - return `composio-${platform}-${arch}.zip`;
109 -}
110 -
101 const defaultConfig = (stateFile: string) =>
102 Effect.gen(function* () {
103 const os = yield* NodeOs;
@@ -118,7 +108,7 @@ const defaultConfig = (stateFile: string) =>
108 currentVersion,
109 checkIntervalMs: CHECK_INTERVAL_MS,
110 releasesUrl: `${github.apiBaseUrl}/repos/${github.owner}/${github.repo}/releases?per_page=100`,
121 - binaryAssetName: getCurrentBinaryAssetName(os),
111 + binaryAssetName: resolveBinaryAssetName({ platform: os.platform, arch: os.arch }),
112 accessToken: github.accessToken,
113 fetchFn: fetch,
114 } satisfies UpdateCheckConfig;
@@ -336,7 +326,7 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
326
327 // ── Public API (production defaults, fire-and-forget) ───────────────────
328
339 -const DefaultConfigLayers = Layer.mergeAll(Path.layer, NodeOs.Default, BunFileSystem.layer);
329 +const DefaultConfigLayers = Layer.mergeAll(BunPath.layer, NodeOs.Default, BunFileSystem.layer);
330
331 export type UpdateNoticeShape = InvocationHookShape;
332
ts/packages/cli/src/services/upgrade-binary.ts
+37 -8
@@ -1,3 +1,4 @@
1 +import * as BunPath from '@effect/platform-bun/BunPath';
2 import {
3 Data,
4 Effect,
@@ -5,6 +6,7 @@ import {
6 Option,
7 Predicate,
8 Record as EffectRecord,
9 + Schedule,
10 Scope,
11 Stream,
12 Context,
@@ -25,7 +27,7 @@ import { atomicReplaceFile, type AtomicReplaceError } from 'src/utils/atomic-rep
27 import { extractZipSafely } from 'src/utils/extract-zip-safely';
28 import { renderPrettyError } from './utils/pretty-error';
29 import { TerminalUI } from './terminal-ui';
28 -import type { NodeOs } from './node-os';
30 +import { NodeOs } from './node-os';
31 import { recordLatestStableRelease } from './update-check';
32 import {
33 collectExpectedRunCompanionAssetRelativePaths,
@@ -60,6 +62,7 @@ interface UpgradeBinaryContext {
62 readonly fs: FileSystem.FileSystem;
63 readonly path: Path.Path;
64 readonly githubConfig: GitHubConfig;
65 + readonly platform: NodeJS.Platform;
66 }
67
68 /**
@@ -403,7 +406,7 @@ const verifyChecksum = (
406 * Extract binary from zip archive using FileSystem
407 */
408 const extractBinary = (
406 - { fs, path }: UpgradeBinaryContext,
409 + { fs, path, platform }: UpgradeBinaryContext,
410 { name, data }: { name: string; data: Uint8Array },
411 tempDir: string
412 ): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
@@ -411,7 +414,10 @@ const extractBinary = (
414 const zipPath = path.join(tempDir, name);
415 const extractDir = path.join(tempDir, 'extract');
416 const packageDir = path.join(extractDir, path.parse(name).name);
414 - const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
417 + const binaryPath = path.join(
418 + packageDir,
419 + platform === 'win32' ? `${CLI_BINARY_NAME}.exe` : CLI_BINARY_NAME
420 + );
421
422 yield* Effect.logDebug(`Download zip to ${extractDir}`);
423
@@ -509,7 +515,7 @@ const mapAtomicReplaceError = (message: string) => (error: AtomicReplaceError) =
515 });
516
517 const replaceBinary = (
512 - ctx: Pick<UpgradeBinaryContext, 'fs' | 'path'>,
518 + ctx: Pick<UpgradeBinaryContext, 'fs' | 'path' | 'platform'>,
519 sourcePath: string,
520 targetPath: string,
521 options: {
@@ -520,6 +526,22 @@ const replaceBinary = (
526 const { fs, path } = ctx;
527 yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
528
529 + if (ctx.platform === 'win32') {
530 + // Windows keeps the previous executable locked until its process has fully exited,
531 + // which can be a moment after an upgrade that just ran returns.
532 + yield* fs.remove(`${targetPath}.old`, { force: true }).pipe(
533 + Effect.retry({ times: 10, schedule: Schedule.spaced('200 millis') }),
534 + Effect.mapError(
535 + cause =>
536 + new UpgradeBinaryError({
537 + cause,
538 + message:
539 + 'Could not remove the previous executable backup. Close other Composio processes and retry.',
540 + })
541 + )
542 + );
543 + }
544 +
545 const sourceDirectory = path.dirname(sourcePath);
546 const targetDirectory = path.dirname(targetPath);
547 const companionRelativePaths = yield* provideFsAndPath(
@@ -604,9 +626,15 @@ const replaceBinary = (
626 ).pipe(Effect.mapError(mapAtomicReplaceError('Failed to update installed release metadata')));
627 }
628
607 - yield* provideFsAndPath(ctx, atomicReplaceFile({ sourcePath, targetPath, mode: 0o755 })).pipe(
608 - Effect.mapError(mapAtomicReplaceError('Failed to replace binary'))
609 - );
629 + yield* provideFsAndPath(
630 + ctx,
631 + atomicReplaceFile({
632 + sourcePath,
633 + targetPath,
634 + mode: 0o755,
635 + backupPath: ctx.platform === 'win32' ? `${targetPath}.old` : undefined,
636 + })
637 + ).pipe(Effect.mapError(mapAtomicReplaceError('Failed to replace binary')));
638
639 const legacyLocalToolsPath = path.join(targetDirectory, LEGACY_LOCAL_TOOLS_DIRNAME);
640 yield* fs
@@ -728,6 +756,7 @@ const makeUpgradeBinary = Effect.gen(function* () {
756 fs: yield* FileSystem.FileSystem,
757 path: yield* Path.Path,
758 githubConfig: yield* GITHUB_CONFIG,
759 + platform: (yield* NodeOs).platform,
760 };
761
762 return {
@@ -741,6 +770,6 @@ export class UpgradeBinary extends Context.Service<UpgradeBinary, UpgradeBinaryS
770 'services/UpgradeBinary'
771 ) {
772 static readonly Default = Layer.effect(UpgradeBinary, makeUpgradeBinary).pipe(
744 - Layer.provide(Path.layer)
773 + Layer.provide(BunPath.layer)
774 );
775 }
ts/packages/cli/src/services/windows-executable.ts new
+42
@@ -0,0 +1,42 @@
1 +import { Config, Effect, FileSystem, Option, Path } from 'effect';
2 +
3 +/** How Windows runs a command found on `PATH`. */
4 +export interface WindowsExecutable {
5 + readonly path: string;
6 + /** `.cmd` and `.bat` files, such as npm's command shims, only run through `cmd.exe`. */
7 + readonly needsShell: boolean;
8 +}
9 +
10 +// Windows looks up the extension-less name `claude` as `claude.exe`, `claude.cmd`, and so on.
11 +const EXECUTABLE_EXTENSIONS = ['.exe', '.cmd', '.bat'] as const;
12 +
13 +// The variable is spelled `Path` on Windows, and environment snapshots keep that spelling.
14 +const WINDOWS_PATH = Config.all([
15 + Config.option(Config.String('Path')),
16 + Config.option(Config.String('PATH')),
17 +]).pipe(Config.map(([path, upperCasePath]) => Option.orElse(path, () => upperCasePath)));
18 +
19 +/**
20 + * Finds `name` the way `cmd.exe` would: in each `PATH` directory, with each executable
21 + * extension. Process spawning does not do this itself, and refuses to run a `.cmd` file directly.
22 + */
23 +export const resolveWindowsExecutable = (
24 + name: string
25 +): Effect.Effect<Option.Option<WindowsExecutable>, never, FileSystem.FileSystem | Path.Path> =>
26 + Effect.gen(function* () {
27 + const fs = yield* FileSystem.FileSystem;
28 + const path = yield* Path.Path;
29 + const pathEnv = Option.getOrElse(yield* Effect.orDie(WINDOWS_PATH), () => '');
30 + const candidates = pathEnv
31 + .split(';')
32 + .filter(directory => directory.length > 0)
33 + .flatMap(directory =>
34 + EXECUTABLE_EXTENSIONS.map(extension => ({
35 + path: path.join(directory, `${name}${extension}`),
36 + needsShell: extension !== '.exe',
37 + }))
38 + );
39 + return yield* Effect.findFirst(candidates, candidate =>
40 + fs.exists(candidate.path).pipe(Effect.orElseSucceed(() => false))
41 + );
42 + });
ts/packages/cli/src/utils/atomic-replace.ts
+26 -1
@@ -10,12 +10,15 @@ type AtomicReplaceFileOptions = {
10 readonly sourcePath: string;
11 readonly targetPath: string;
12 readonly mode?: number;
13 + /** Move an in-use Windows executable aside before installing its replacement. */
14 + readonly backupPath?: string;
15 };
16
17 export const atomicReplaceFile = ({
18 sourcePath,
19 targetPath,
20 mode,
21 + backupPath,
22 }: AtomicReplaceFileOptions): Effect.Effect<
23 void,
24 AtomicReplaceError,
@@ -34,7 +37,29 @@ export const atomicReplaceFile = ({
37 if (mode !== undefined) {
38 yield* fs.chmod(stagedPath, mode);
39 }
37 - yield* fs.rename(stagedPath, targetPath);
40 + if (backupPath === undefined || !(yield* fs.exists(targetPath))) {
41 + yield* fs.rename(stagedPath, targetPath);
42 + return;
43 + }
44 +
45 + // A loaded Windows executable cannot be overwritten. Keep its old image
46 + // until the next upgrade, when the process using it has exited.
47 + yield* fs.remove(backupPath, { force: true });
48 + yield* Effect.uninterruptible(
49 + fs
50 + .rename(targetPath, backupPath)
51 + .pipe(
52 + Effect.andThen(
53 + fs
54 + .rename(stagedPath, targetPath)
55 + .pipe(
56 + Effect.catch(cause =>
57 + fs.rename(backupPath, targetPath).pipe(Effect.andThen(Effect.fail(cause)))
58 + )
59 + )
60 + )
61 + )
62 + );
63 }).pipe(
64 Effect.mapError(
65 cause =>
ts/packages/cli/test/__utils__/services/test-layer.ts
+1 -1
@@ -483,7 +483,7 @@ export const TestLayer = (input?: TestLiveInput) =>
483
484 const UpgradeBinaryTest = Layer.provide(
485 UpgradeBinary.Default,
486 - Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
486 + Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer, NodeOsTest)
487 );
488
489 const StdinTest = Layer.succeed(
ts/packages/cli/test/src/commands/run/run.cmd.test.ts
+12 -4
@@ -7,6 +7,7 @@ import { describe, expect, layer } from '@effect/vitest';
7 import { assertDefined } from '@effect/vitest/utils';
8 import * as BunServices from '@effect/platform-bun/BunServices';
9 import * as Path from 'effect/Path';
10 +import * as FileSystem from 'effect/FileSystem';
11 import {
12 Cause,
13 ConfigProvider,
@@ -843,13 +844,20 @@ describe('buildRunHelpersSource', () => {
844
845 describe('inferCliInvocationPrefix', () => {
846 layer(BunServices.layer)(it => {
846 - it.effect(
847 - '[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only',
848 - () =>
847 + it.effect.each([
848 + '/$bunfs/root/composio',
849 + 'B:\\$bunfs\\root\\composio.exe',
850 + 'B:/~BUN/root/composio.exe',
851 + 'B:\\~BUN\\root\\composio.exe',
852 + ])(
853 + '[Given] a compiled entrypoint %s [Then] it falls back to the binary path only',
854 + entrypoint =>
855 Effect.gen(function* () {
856 const pathService = yield* Path.Path;
857 expect(
852 - yield* inferCliInvocationPrefix(pathService, ['node', '/$bunfs/root/composio'])
858 + yield* inferCliInvocationPrefix(pathService, ['node', entrypoint]).pipe(
859 + Effect.provide(FileSystem.layerNoop({ exists: () => Effect.succeed(true) }))
860 + )
861 ).toEqual([process.execPath]);
862 })
863 );
ts/packages/cli/test/src/effects/detect-platform.test.ts
+14 -1
@@ -88,9 +88,22 @@ describe('detect-platform.ts', () => {
88 );
89 });
90
91 + it.effect('maps Windows x64 to the Windows release asset platform', () =>
92 + Effect.gen(function* () {
93 + expect(yield* detectPlatform).toEqual({ platform: 'windows', arch: 'x64' });
94 + }).pipe(Effect.provide(createMockNodeOs('win32', 'x64')))
95 + );
96 +
97 + it.effect('rejects Windows ARM64 without a published binary', () =>
98 + Effect.gen(function* () {
99 + const error = yield* Effect.flip(detectPlatform);
100 + expect(error).toBeInstanceOf(UnsupportedPlatformError);
101 + expect(error.arch).toBe('arm64');
102 + }).pipe(Effect.provide(createMockNodeOs('win32', 'arm64')))
103 + );
104 +
105 describe('Unsupported Platforms', () => {
106 const unsupportedPlatforms = [
93 - 'win32',
107 'freebsd',
108 'openbsd',
109 'sunos',
ts/packages/cli/test/src/services/run-companion-modules.test.ts
+15
@@ -2,6 +2,7 @@ import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 import * as BunServices from '@effect/platform-bun/BunServices';
5 +import * as BunPath from '@effect/platform-bun/BunPath';
6 import { afterEach, describe, expect, it, layer } from '@effect/vitest';
7 import { ConfigProvider, Effect } from 'effect';
8 import { vi } from 'vitest';
@@ -13,6 +14,7 @@ import {
14 RUN_COMPANION_MODULE_BASENAMES,
15 RUN_COMPANION_MODULE_FILENAMES,
16 RUN_COMPANION_RELEASE_TAG_FILENAME,
17 + resolveRunCompanionModulePath,
18 } from 'src/services/run-companion-modules';
19
20 const extractZipMock = vi.hoisted(() => vi.fn());
@@ -535,3 +537,16 @@ describe('loadInstalledCompanionModule', () => {
537 );
538 });
539 });
540 +
541 +describe('Windows compiled companion resolution', () => {
542 + it.effect('falls back beside the executable for a Windows Bun virtual module', () =>
543 + Effect.gen(function* () {
544 + const result = yield* resolveRunCompanionModulePath({
545 + callerImportMetaUrl: 'file:///B:/~BUN/root/commands.mjs',
546 + execPath: 'C:\\Users\\Example User\\.composio\\composio.exe',
547 + relativeNoExtensionFromCaller: '../../services/run-helpers-runtime',
548 + });
549 + expect(result).toBe('C:\\Users\\Example User\\.composio\\run-helpers-runtime.mjs');
550 + }).pipe(Effect.provide(BunPath.layerWin32), Effect.provide(BunServices.layer))
551 + );
552 +});
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+65 -2
@@ -85,7 +85,8 @@ type UpgradeOptions = {
85 const makeUpgradeEffect = (
86 configEntries: ReadonlyArray<[string, string]>,
87 options?: UpgradeOptions,
88 - fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = BunFileSystem.layer
88 + fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = BunFileSystem.layer,
89 + nodeOsLayer: Layer.Layer<NodeOs> = NodeOsTest
90 ) =>
91 Effect.gen(function* () {
92 const service = yield* UpgradeBinary;
@@ -95,7 +96,7 @@ const makeUpgradeEffect = (
96 Effect.provide(FetchHttpClient.layer),
97 Effect.provide(fileSystemLayer),
98 Effect.provide(TerminalUINoop),
98 - Effect.provide(NodeOsTest),
99 + Effect.provide(nodeOsLayer),
100 Effect.provideService(
101 ConfigProvider.ConfigProvider,
102 ConfigProvider.fromEnv({ env: Object.fromEntries(configEntries) })
@@ -508,6 +509,68 @@ describe('UpgradeBinary', () => {
509 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
510 });
511
512 + // Live clock: the upgrade waits out a briefly locked backup before giving up.
513 + it.live('preserves the Windows bundle when a previous executable backup is locked', () => {
514 + vi.stubGlobal('Bun', { which: vi.fn(() => null) });
515 +
516 + return Effect.gen(function* () {
517 + const fs = yield* FileSystem.FileSystem;
518 + const path = yield* Path.Path;
519 + const installDir = yield* fs.makeTempDirectoryScoped();
520 + const sourceDir = yield* fs.makeTempDirectoryScoped();
521 + const fakeExecPath = path.join(installDir, 'composio.exe');
522 + const sourceBinaryPath = path.join(sourceDir, 'composio.exe');
523 + const backupPath = `${fakeExecPath}.old`;
524 + const releaseTagPath = path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME);
525 + yield* fs.writeFileString(fakeExecPath, 'old-binary');
526 + yield* fs.writeFileString(sourceBinaryPath, 'new-binary');
527 + yield* fs.writeFileString(backupPath, 'locked-previous-binary');
528 + yield* fs.writeFileString(releaseTagPath, '@composio/cli@0.2.31\n');
529 + const companions = yield* collectExpectedRunCompanionAssetRelativePaths(sourceDir);
530 + yield* writeCompanionFiles(sourceDir, companions, 'new-support');
531 + yield* writeCompanionFiles(installDir, companions, 'old-support');
532 + vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
533 + const lockedFileSystem = Layer.succeed(
534 + FileSystem.FileSystem,
535 + FileSystem.make({
536 + ...fs,
537 + remove: (target, options) =>
538 + target === backupPath
539 + ? Effect.fail(
540 + PlatformError.systemError({
541 + _tag: 'Busy',
542 + module: 'FileSystem',
543 + method: 'remove',
544 + pathOrDescriptor: target,
545 + })
546 + )
547 + : fs.remove(target, options),
548 + })
549 + );
550 + const windowsOs = Layer.succeed(
551 + NodeOs,
552 + NodeOs.of({
553 + homedir: testHomedir,
554 + tmpdir: '/tmp',
555 + platform: 'win32',
556 + arch: 'x64',
557 + })
558 + );
559 + const error = yield* makeUpgradeEffect(
560 + [['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath]],
561 + { tag: '@composio/cli@0.3.0' },
562 + lockedFileSystem,
563 + windowsOs
564 + ).pipe(Effect.flip);
565 +
566 + expect(yield* fs.readFileString(fakeExecPath)).toBe('old-binary');
567 + expect(yield* fs.readFileString(releaseTagPath)).toBe('@composio/cli@0.2.31\n');
568 + expect(yield* fs.readFileString(path.join(installDir, companions[0]!))).toBe('old-support');
569 + expect(error).toBeInstanceOf(UpgradeBinaryError);
570 + expect(error.message).toContain('Close other Composio processes');
571 + }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
572 + });
573 +
574 it.effect('commits companions and release metadata before replacing the binary', () => {
575 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
576
ts/packages/cli/test/src/services/windows-executable.test.ts new
+54
@@ -0,0 +1,54 @@
1 +import * as BunServices from '@effect/platform-bun/BunServices';
2 +import { describe, expect, it } from '@effect/vitest';
3 +import { ConfigProvider, Effect, FileSystem, Option, Path } from 'effect';
4 +import { resolveWindowsExecutable } from 'src/services/windows-executable';
5 +
6 +const withPath = (entries: Record<string, string>) =>
7 + Effect.provideService(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env: entries }));
8 +
9 +describe('resolveWindowsExecutable', () => {
10 + it.effect('finds an npm command shim and marks it as needing a shell', () =>
11 + Effect.gen(function* () {
12 + const fs = yield* FileSystem.FileSystem;
13 + const path = yield* Path.Path;
14 + const empty = yield* fs.makeTempDirectoryScoped();
15 + const npmBin = yield* fs.makeTempDirectoryScoped();
16 + yield* fs.writeFileString(path.join(npmBin, 'claude.cmd'), '@echo off');
17 +
18 + const resolved = yield* resolveWindowsExecutable('claude').pipe(
19 + withPath({ Path: `${empty};${npmBin}` })
20 + );
21 +
22 + expect(resolved).toEqual(
23 + Option.some({ path: path.join(npmBin, 'claude.cmd'), needsShell: true })
24 + );
25 + }).pipe(Effect.provide(BunServices.layer))
26 + );
27 +
28 + it.effect('prefers a native executable over a shim in the same directory', () =>
29 + Effect.gen(function* () {
30 + const fs = yield* FileSystem.FileSystem;
31 + const path = yield* Path.Path;
32 + const bin = yield* fs.makeTempDirectoryScoped();
33 + yield* fs.writeFileString(path.join(bin, 'claude.cmd'), '@echo off');
34 + yield* fs.writeFileString(path.join(bin, 'claude.exe'), '');
35 +
36 + const resolved = yield* resolveWindowsExecutable('claude').pipe(withPath({ PATH: bin }));
37 +
38 + expect(resolved).toEqual(
39 + Option.some({ path: path.join(bin, 'claude.exe'), needsShell: false })
40 + );
41 + }).pipe(Effect.provide(BunServices.layer))
42 + );
43 +
44 + it.effect('finds nothing when the command is not on PATH', () =>
45 + Effect.gen(function* () {
46 + const fs = yield* FileSystem.FileSystem;
47 + const empty = yield* fs.makeTempDirectoryScoped();
48 +
49 + const resolved = yield* resolveWindowsExecutable('claude').pipe(withPath({ Path: empty }));
50 +
51 + expect(Option.isNone(resolved)).toBe(true);
52 + }).pipe(Effect.provide(BunServices.layer))
53 + );
54 +});
ts/packages/cli/test/src/utils/atomic-replace.test.ts
+55
@@ -49,6 +49,61 @@ describe('atomic replace', () => {
49 })
50 );
51
52 + it.effect('keeps the old executable beside the new one and replaces a previous backup', () =>
53 + Effect.gen(function* () {
54 + const fs = yield* FileSystem.FileSystem;
55 + const path = yield* Path.Path;
56 + const directory = yield* fs.makeTempDirectoryScoped();
57 + const sourcePath = path.join(directory, 'source');
58 + const targetPath = path.join(directory, 'composio.exe');
59 + const backupPath = `${targetPath}.old`;
60 + yield* fs.writeFileString(sourcePath, 'new binary');
61 + yield* fs.writeFileString(targetPath, 'old binary');
62 + yield* fs.writeFileString(backupPath, 'previous backup');
63 +
64 + yield* Effect.scoped(atomicReplaceFile({ sourcePath, targetPath, backupPath }));
65 +
66 + expect(yield* fs.readFileString(targetPath)).toBe('new binary');
67 + expect(yield* fs.readFileString(backupPath)).toBe('old binary');
68 + expect((yield* fs.readDirectory(directory)).sort()).toEqual([
69 + 'composio.exe',
70 + 'composio.exe.old',
71 + 'source',
72 + ]);
73 + })
74 + );
75 +
76 + it.effect('restores the old executable when placing its staged replacement fails', () =>
77 + Effect.gen(function* () {
78 + const fs = yield* FileSystem.FileSystem;
79 + const path = yield* Path.Path;
80 + const directory = yield* fs.makeTempDirectoryScoped();
81 + const sourcePath = path.join(directory, 'source');
82 + const targetPath = path.join(directory, 'composio.exe');
83 + const backupPath = `${targetPath}.old`;
84 + yield* fs.writeFileString(sourcePath, 'new binary');
85 + yield* fs.writeFileString(targetPath, 'old binary');
86 + const failingFs = FileSystem.make({
87 + ...fs,
88 + rename: (from, to) => {
89 + return from.includes('.composio-atomic-replace-') && to === targetPath
90 + ? fs.rename(path.join(directory, 'missing'), to)
91 + : fs.rename(from, to);
92 + },
93 + });
94 +
95 + const error = yield* Effect.flip(
96 + Effect.scoped(atomicReplaceFile({ sourcePath, targetPath, backupPath })).pipe(
97 + Effect.provideService(FileSystem.FileSystem, failingFs)
98 + )
99 + );
100 +
101 + expect(error).toBeInstanceOf(AtomicReplaceError);
102 + expect(yield* fs.readFileString(targetPath)).toBe('old binary');
103 + expect(yield* fs.exists(backupPath)).toBe(false);
104 + })
105 + );
106 +
107 it.effect('preserves the target and cleans staging when the source is missing', () =>
108 Effect.gen(function* () {
109 const fs = yield* FileSystem.FileSystem;