Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 98f4d8f647 fix(plugins): detect missing tunnel CLIs and run tunnel tests on Windows
On Windows a bare name that is not on PATH runs through cmd.exe, which exits
9009 instead of failing the spawn with ENOENT. The providers reported a
missing tailscale as "not running". Treat exit 9009 as not installed.

The fake CLIs were shebang scripts, which Windows does not run, and the
tests relied on SIGTERM handlers that a Windows force kill skips. The fakes
now get a .cmd launcher on Windows, and the tests check that the fake
process is gone instead of a handler side effect.
2026-11-27 11:25:25 +01:00
Mohamed Boudra 514f8adab6 fix(plugins): ship cloudflared with quick tunnels only
A named Cloudflare tunnel routes through ingress set in the Cloudflare
dashboard, so its URL never served the exposure target. Two exposures for
different targets both reported ready at the same URL. Named tunnels return
later with per-target routing.

Also mark the tunnel-provider example as requiring 0.18.0-beta.1, like the
notifications example, so the example build test loads it.
2026-11-27 11:03:03 +01:00
Mohamed Boudra 3570916360 fix(plugins): keep tunnel exposures from reporting wrong URLs or outliving Paseo
- cloudflared: the quick-tunnel URL pattern matched api.trycloudflare.com in
  provisioning errors, so an offline open reported ready with the API endpoint.
- tailscale-funnel: `funnel --bg` stored the Funnel in tailscaled, so a crashed
  plugin or daemon left the target public with no owner. Run the Funnel in the
  foreground instead; tailscaled drops it when the CLI exits.
- tailscale-funnel: a failed `funnel status` counted as "no ports in use" and
  could replace and later remove the user's own handler. Fail the open instead.
- Add the Chinese translation of the tunnel providers reference section.
2026-11-27 11:00:28 +01:00
Mohamed Boudra 7dea42a88c feat(plugins): add tunnel provider plugins with cloudflared and tailscale funnel built-ins
Plugins can now register a tunnel provider that turns a local HTTP host:port
into a public HTTPS URL. The daemon's TunnelManager owns exposures and their
lifecycle, so a provider only reports state through report() and stops when
its signal aborts. Exposures close when the owning plugin stops, reloads, is
disabled, or crashes, and when the daemon shuts down.

This is the shared primitive that later work uses to expose MCP servers and
workspace services. Clients gate on server_info.features.tunnelProviders.
2026-11-27 10:50:40 +01:00
70 changed files with 4002 additions and 543 deletions
-19
View File
@@ -1,24 +1,5 @@
# Changelog
## 0.18.0 - 2026-11-27
- **Remote workspace browser proxy:** Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote `localhost` servers open directly in Paseo. ([#10944](https://github.com/getpaseo/paseo/pull/10944) by [@airon-assustadus](https://github.com/airon-assustadus))
- **Per-device notification preferences:** Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps. ([#10888](https://github.com/getpaseo/paseo/pull/10888))
- **Agent profile system prompts:** Save an optional system prompt on an agent profile to apply it to new agents started from that profile. ([#10996](https://github.com/getpaseo/paseo/pull/10996))
- **More syntax highlighting:** Syntax highlighting now covers diff and patch files along with Ruby, Kotlin, TOML, SQL, Lua, Protobuf, PowerShell, Groovy, Gradle, Scala, CMake, Properties, INI, R, Perl, and LaTeX. ([#11026](https://github.com/getpaseo/paseo/pull/11026) by [@hmalaspina](https://github.com/hmalaspina), [@kukicola](https://github.com/kukicola), [@MaximeConan](https://github.com/MaximeConan), [@singleton11](https://github.com/singleton11), [@chandlerok](https://github.com/chandlerok))
### Changed
- Changed ACP providers to cache model catalogs across daemon restarts instead of probing in the background, and cleaned up Antigravity ACP flags and metadata. Requires [Antigravity CLI 1.5.1 or later](https://paseo.sh/docs/supported-providers/antigravity) ([#10992](https://github.com/getpaseo/paseo/pull/10992))
### Fixed
- Fixed Paseo iOS crashing shortly after connecting when an enabled client plugin imports `react-native` ([#11011](https://github.com/getpaseo/paseo/pull/11011))
- Fixed OpenCode v2 agents staying stuck in running after Stop when stream events were missed or chat history was large ([#10955](https://github.com/getpaseo/paseo/pull/10955))
- Fixed steering a Pi agent during a run it started on its own aborting the run instead of steering it ([#10977](https://github.com/getpaseo/paseo/pull/10977) by [@viiqswim](https://github.com/viiqswim))
- Fixed creating a workspace from a pull request in a fork clone checking out the fork's pull request with the same number ([#10987](https://github.com/getpaseo/paseo/pull/10987))
- Fixed dropping images or files onto the composer leaving the input unfocused ([#11022](https://github.com/getpaseo/paseo/pull/11022))
## 0.17.6 - 2026-11-27
### Improved
-19
View File
@@ -1,24 +1,5 @@
# Changelog
## 0.18.0 - 2026-11-27
- **远程工作区浏览器代理**:远程工作区中的桌面端浏览器标签页现在会通过该工作区的 daemon 转发流量,远程 `localhost` 服务可以直接在 Paseo 中打开。([#10944](https://github.com/getpaseo/paseo/pull/10944),贡献者:[@airon-assustadus](https://github.com/airon-assustadus))
- **按设备配置通知偏好**:每台设备都可以分别选择哪些 Agent、终端和插件事件发送通知,插件现在也可以发送通知并处理点击。([#10888](https://github.com/getpaseo/paseo/pull/10888))
- **智能体配置文件系统提示词**:在智能体配置文件中保存可选的系统提示词,以便在通过该配置启动新 Agent 时应用。([#10996](https://github.com/getpaseo/paseo/pull/10996))
- **更多语法高亮语言**:语法高亮现已支持 diff 和 patch 文件,以及 Ruby、Kotlin、TOML、SQL、Lua、Protobuf、PowerShell、Groovy、Gradle、Scala、CMake、Properties、INI、R、Perl 和 LaTeX。([#11026](https://github.com/getpaseo/paseo/pull/11026),贡献者:[@hmalaspina](https://github.com/hmalaspina), [@kukicola](https://github.com/kukicola), [@MaximeConan](https://github.com/MaximeConan), [@singleton11](https://github.com/singleton11), [@chandlerok](https://github.com/chandlerok))
### 变更
- ACP Provider 现在会在 daemon 重启间将已发现的模型目录缓存到磁盘,不再在后台轮询,同时清理了多余的 Antigravity ACP 参数和元数据。需要 [Antigravity CLI 1.5.1 或更高版本](https://paseo.sh/zh-CN/docs/supported-providers/antigravity) ([#10992](https://github.com/getpaseo/paseo/pull/10992))
### 修复
- 修复已启用的客户端插件导入 `react-native` 时,Paseo iOS 在连接后不久崩溃的问题 ([#11011](https://github.com/getpaseo/paseo/pull/11011))
- 修复流事件丢失或对话历史较大时,OpenCode v2 Agent 在点击停止后仍停留在运行中的问题 ([#10955](https://github.com/getpaseo/paseo/pull/10955))
- 修复在 Pi Agent 运行其自行启动的轮次时发送引导消息会中止该轮次而不是引导它的问题 ([#10977](https://github.com/getpaseo/paseo/pull/10977),贡献者:[@viiqswim](https://github.com/viiqswim))
- 修复在 fork 克隆中根据 PR 创建工作区时,检出到 fork 中同编号 PR 的问题 ([#10987](https://github.com/getpaseo/paseo/pull/10987))
- 修复向 Composer 拖放图片或文件后输入框未获得焦点的问题 ([#11022](https://github.com/getpaseo/paseo/pull/11022))
## 0.17.6 - 2026-11-27
### 改进
+7
View File
@@ -103,6 +103,13 @@ The `worktree-include` built-in copies gitignored files selected by
[`.worktreeinclude`](../public-docs/worktrees.md#copy-local-files-with-worktreeinclude)
before setup and agents, through `worktree.create.after`.
The `cloudflared-tunnel` and `tailscale-funnel` built-ins register tunnel providers through
`server.registerTunnelProvider()`. Both start without installed binaries or credentials and report
availability through `status()`. `cloudflared-tunnel` runs quick tunnels only, with `--url` set to
the exposure target. Named Cloudflare tunnels are not supported: the Cloudflare dashboard sets
their routing, so their URL does not serve the exposure target. `tailscale-funnel` runs `tailscale funnel` in the foreground: with
`--bg`, tailscaled keeps the Funnel public after a crash with no owner.
Desktop packaging ships the entire built-in plugin directory as an external resource,
including declarations. The external esbuild compiler cannot read Electron's `app.asar`
filesystem, and packaging dependencies excludes `.d.ts` files needed for import validation.
-3
View File
@@ -340,9 +340,6 @@ See the [public usage source reference](../public-docs/plugins/reference.md#usag
contract, account and window identity, provider-derived period names, login fallback, and
read-only credential rules. Usage adapters own the interpretation of provider fields; the app
renders their names and resolves pins without provider-specific duration guesses.
Claude's OAuth usage endpoint is undocumented. Extra-usage amounts are reported in minor currency
units and displayed only for USD; the balance contract does not represent other currencies.
Codex individual spending limits provide percentages, not dollar amounts.
---
+67 -94
View File
@@ -4,41 +4,29 @@ All workspaces share one version and release together.
## Two steps
A release has two steps. The agent runs Preparation before approval, and the user authorizes Ship.
A release has exactly two steps. The agent does the first, the user authorizes the second.
### Preparation
**Preparation** (reversible — agent does this on the release branch):
Preparation is reversible and runs on the release branch before the user authorizes shipping.
- resolve the [release base](#release-base-and-source) and get the [release inventory](#release-inventory) approved when one applies
- classify the diff from the previous stable to the release source as patch or minor, then show the
target version and rationale to the user
- draft `CHANGELOG.md` and `CHANGELOG.zh-CN.md`, show the draft to the user, and wait for review
- run the pre-release sanity check (stable only) and surface findings to the user
- commit the approved changelog and any requested ACP update, run format, lint, and typecheck, then
run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag
- push the `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` branch and confirm its `CI` and
`Desktop Packages` runs pass (never wait on `main` CI)
- run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
1. Resolve the [release base](#release-base-and-source) and get the [release inventory](#release-inventory) approved when one applies.
2. Classify the diff from the previous stable release to the release source as patch or minor, then show the target version and rationale to the user.
3. Draft `CHANGELOG.md` and `CHANGELOG.zh-CN.md`, show the draft to the user, and wait for approval.
4. Run the [pre-release sanity check](#pre-release-sanity-check) for stable releases, and report any findings to the user.
5. Commit the approved changelog and any requested ACP update, then run `npm run format`, `npm run lint`, and `npm run typecheck`.
6. Run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag.
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` and wait for `CI` and `Desktop Packages` on that branch to pass (never wait on `main` CI).
8. Run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
**Go-ahead** (user says "go ahead"):
### Ship
Ship starts after the user says "go ahead". All tag-triggered GitHub Actions workflows and EAS workflows build from the checked-out tag commit with local workspace packages, so none of them install `@getpaseo/*` from the public npm registry.
1. Run `npm run release:push` first to verify the clean release branch and push `vX.Y.Z` or `vX.Y.Z-beta.N`. Pushing the tag takes a few seconds and starts `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and (for stable tags) `Deploy App` on GitHub Actions, plus `Release Mobile` (stable) or `Release iOS Beta` (beta) on EAS. (`Deploy Website` runs later on the `release: published` event when `Desktop Release` publishes the stable GitHub Release.)
2. Run `npm run release:publish` (stable) or `npm run release:publish:beta` (beta) in parallel with the remote builds. `scripts/publish-release-packages.mjs` publishes the seven `@getpaseo/*` packages in dependency waves and polls npm visibility between packages to avoid `E409` or `E404` propagation races.
3. Open the [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N` right after `npm run release:push` finishes, so its CI run overlaps with npm publication and the release builds.
4. Create the release heartbeat immediately with `create_heartbeat` to track every ship step to completion.
### Sync gates
Wait until every gate below passes before deleting the remote release branch or reporting the release as shipped:
- All seven `@getpaseo/*` npm packages are visible on `latest` (stable) or `beta` (beta), and on stable the `beta` dist-tag points to the shipped version unless an active newer beta exists.
- All tag-triggered GitHub Actions workflows are green (`Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and `Deploy App` for stable), and `Deploy Website` ran after stable publication.
- The GitHub Release is published and non-draft (marked prerelease for beta) with the synced changelog body, all macOS, Linux, and Windows assets, the Android APK asset, and all three channel manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml` for stable; `beta-mac.yml`, `beta-linux.yml`, `beta.yml` for beta).
- The matching EAS workflow is green (`Release Mobile` with all six build, distribution, screenshot, and review-submission jobs for stable; `Release iOS Beta` for beta).
- The reconcile PR is merged into `main`.
Once all sync gates pass, delete the remote release branch (`git push origin --delete release/vX.Y.Z` or `release/vX.Y.Z-beta.N`), delete the heartbeat, and report the release as shipped.
- run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta), which publishes npm
with retry and registry visibility checks, advances the `beta` dist-tag on stable when newer, and
pushes the tag on the already-verified commit
- create the release heartbeat immediately and babysit it to completion
- open the [reconcile `main`](#reconcile-main) PR right away so its CI runs in parallel with release
builds, then delete the remote release branch once the PR merges
Rules that apply to both steps:
@@ -122,20 +110,18 @@ An explicit user instruction can select another base.
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
6. After go-ahead, push the tag first with `npm run release:push` so remote builds start right away.
Because the release branch is already pushed at `HEAD`, no second branch CI run starts, and only
the tag release workflows run.
7. Immediately in parallel after `npm run release:push` finishes: publish npm packages with
`npm run release:publish` (stable) or `npm run release:publish:beta` (beta), start
[Reconcile `main`](#reconcile-main) so its PR checks overlap with desktop and EAS builds, and
create the release heartbeat. (`npm run release:ship` and `npm run release:ship:beta` also run
`release:push` before `release:publish`, so tag builds never wait behind npm.)
6. After go-ahead, run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta). This
publishes to npm and pushes the `v*` tag on the already-verified commit. Because the release
branch is already pushed at `HEAD`, no second CI run starts and only the tag release workflows
run.
7. Start [Reconcile `main`](#reconcile-main) immediately so its PR checks overlap with desktop and
EAS builds.
When promoting or branching from a tag created before `release:prep:*`, `release:ship`, and the
`release/**` workflow triggers existed (for example `v0.17.0-beta.1`), either cherry-pick the
release-tooling commit onto the release branch (leaving product code unchanged) or follow the
older tag's scripts (`version:all:*`, manual `gh workflow run ci.yml --ref <branch>`,
`release:push`, and `release:publish`) until the next tag carries the new tooling.
`release:publish`, and `release:push`) until the next tag carries the new tooling.
A stable hotfix can take the version a patch beta line would promote to, such as `0.13.3`
shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version. Continue the line
@@ -144,7 +130,7 @@ computes that from a prerelease, so run `npm run release:check`, bump with
`npm version 0.13.4-beta.1 --include-workspace-root --no-git-tag-version && git commit -m "chore(release): cut 0.13.4-beta.1"`,
push the release branch for `CI` and `Desktop Packages`, and complete the
[pre-release dependency checks](#pre-release-dependency-checks) before shipping with
`npm run release:push` and `npm run release:publish:beta` (or `npm run release:ship:beta`).
`npm run release:ship:beta`.
Record the tested beta tag as its source so its soak still counts for the unchanged content.
## Release inventory
@@ -173,7 +159,8 @@ For a promotion, every item defaults to defer.
## Reconcile main
Right after `npm run release:push` pushes the tag (in parallel with npm publication and all desktop, APK, Docker, and EAS builds), open a PR into `main` from a fresh branch off `origin/main` named `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`. Reconcile reads only the tagged git commit, so it does not wait for npm or any release build:
Right after the tag push (in parallel with desktop and EAS builds), open a PR into `main` from a
fresh branch off `origin/main` named `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`:
```bash
git fetch origin --tags
@@ -193,10 +180,10 @@ hunks from the release base:
- Leaves unshipped work on `main` untouched and makes no claims about unshipped work in the
changelog entry.
Commit, open the PR into `main`, and merge once its checks pass. Delete the remote release branch
(`git push origin --delete release/vX.Y.Z` or `release/vX.Y.Z-beta.N`) only after the reconcile PR
merges and every [sync gate](#sync-gates) passes. The tag is the record of shipped source, and
Paseo maintains no release track besides `main`.
Commit, open the PR into `main`, and merge once its checks pass. After the reconcile PR merges and
the release completes, delete the remote release branch (`git push origin --delete release/vX.Y.Z`
or `release/vX.Y.Z-beta.N`). The tag is the record of shipped source; Paseo maintains no release
track besides `main`.
## ACP catalog updates
@@ -253,30 +240,24 @@ npm run release:prep:minor
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead and green release-branch checks: push the tag first to start builds.
npm run release:push
# 4. Run these in parallel immediately after step 3:
npm run release:publish
# Also open the reconcile/vX.Y.Z PR into main and create the release heartbeat.
# (`npm run release:ship` runs `release:push` before `release:publish` if used standalone.)
# 3. After go-ahead and green release-branch checks: publish npm and push the tag.
npm run release:ship
```
`scripts/push-current-release-tag.mjs` refuses non-`release/*` branches, checks that `HEAD` matches `origin/release/*`, tags `HEAD` with `vX.Y.Z`, and pushes the tag. Because `HEAD` is already on the pushed release branch, no second branch CI run starts.
`release:ship` runs `scripts/publish-release-packages.mjs` and `scripts/push-current-release-tag.mjs`:
`scripts/publish-release-packages.mjs` publishes the seven `@getpaseo/*` packages in dependency-wave order:
- Publishes all seven `@getpaseo/*` packages in dependency order, skips versions already on npm,
retries transient 429/5xx/network errors, and waits until each version is visible on npm before
continuing.
- Checks `npm view @getpaseo/cli dist-tags` and moves npm's `beta` dist-tag to the new stable
version across all seven packages whenever the stable version is newer than `beta` (leaving
`beta` untouched during a stable hotfix on an older line).
- Refuses non-`release/*` branches, tags `HEAD` with `vX.Y.Z`, and pushes the tag. Because `HEAD`
is already on the release branch, no second CI run starts.
1. Wave 1: `@getpaseo/highlight`, `@getpaseo/relay`, and `@getpaseo/protocol` (no `@getpaseo/*` dependencies).
2. Wave 2: `@getpaseo/client` (depends on `@getpaseo/protocol` and `@getpaseo/relay`).
3. Wave 3: `@getpaseo/plugin` (depends on `@getpaseo/client` and `@getpaseo/protocol`).
4. Wave 4: `@getpaseo/server` (depends on `@getpaseo/client`, `@getpaseo/highlight`, `@getpaseo/plugin`, `@getpaseo/protocol`, and `@getpaseo/relay`).
5. Wave 5: `@getpaseo/cli` (depends on `@getpaseo/client`, `@getpaseo/protocol`, and `@getpaseo/server`).
The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. The workflows create the GitHub Release as a draft while builds and release-note sync run. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`.
After each `npm publish`, the script polls `npm view` (up to 12 checks, 5 seconds apart) until the published version is visible on npm before moving to the next package. Waiting for registry visibility prevents dependent publishes and manual retries from hitting `E409` conflicts or `E404` propagation lag. On stable releases, the script also checks `npm view @getpaseo/cli dist-tags` and moves npm's `beta` dist-tag to the new stable version across all seven packages whenever the stable version is newer than `beta` (leaving `beta` untouched during a stable hotfix on an older line).
The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and `Deploy App` (`app.paseo.sh`, stable tags only) on GitHub Actions. `Desktop Release` and `Release Notes Sync` create the GitHub Release as a draft while builds and release-note sync run. `Deploy Website` triggers later on `release: published` when `Desktop Release` publishes the non-draft stable GitHub Release. EAS picks up the same tag through the EAS GitHub app and starts `Release Mobile` (iOS and Android store builds) in parallel, with no mobile-release workflow under `.github/workflows`. None of these workflows install `@getpaseo/*` from the public npm registry because all of them build from the checked-out tag commit and workspace packages.
Confirm that `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
Verify `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (cancelling superseded `main` runs). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
@@ -295,10 +276,8 @@ npm run version:all:minor
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:push # Create tag vX.Y.Z on HEAD and push (starts release builds)
# In parallel right after release:push:
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat.
npm run release:push # Create tag vX.Y.Z on HEAD and push (triggers release workflows)
```
## Beta flow
@@ -315,19 +294,15 @@ npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead: push the tag first, then run npm publish, reconcile, and heartbeat in parallel:
npm run release:push
npm run release:publish:beta
# (Or run `npm run release:ship:beta` in one shell while opening reconcile/vX.Y.Z-beta.N.)
# 3. After go-ahead:
npm run release:ship:beta
# Later, after soak, promote on release/vX.Y.Z:
npm run release:prep:promote
git push -u origin HEAD
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:push
npm run release:publish
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat in parallel.
npm run release:ship
```
- Beta tags are published GitHub prereleases like `v0.1.41-beta.1`
@@ -586,8 +561,9 @@ To confirm the submission landed, inspect the EAS workflow with `npx eas workflo
## Release completion and heartbeat
A release is in progress once the tag is pushed. Report it as shipped only after every applicable
[sync gate](#sync-gates) and completion checklist item passes.
A release is **in progress** after npm publication and tag push. Report it as
**shipped** only after every applicable build, publication, asset, manifest, and
store submission passes the completion checklist.
Immediately after every beta, stable, or promotion tag push, create a heartbeat
that resumes the release in the current conversation. Create it automatically
@@ -596,10 +572,9 @@ the completion checklist or finds a failure that needs new user authority.
Each heartbeat checks the release tag commit, `CI` and `Desktop Packages` for the release branch,
every tag-triggered GitHub Actions run (`Desktop Release`, `Android APK Release`, `Docker`,
`Release Notes Sync`, and `Deploy App` for stable), `Deploy Website` after stable release
publication, npm dist-tags, the GitHub Release body and assets, desktop updater manifests, the
published Docker image, the applicable EAS workflow, the reconcile PR, and remote release branch
cleanup. Inspect the GitHub Release itself and confirm that the macOS, Linux,
`Release Notes Sync`), npm dist-tags, the GitHub Release body and assets, desktop updater
manifests, the published Docker image, the applicable EAS workflow, the reconcile PR, and remote
release branch cleanup. Inspect the GitHub Release itself and confirm that the macOS, Linux,
Windows, and Android APK assets are present along with the channel manifests
(`latest-mac.yml`, `latest-linux.yml`, and `latest.yml` for stable;
`beta-mac.yml`, `beta-linux.yml`, and `beta.yml` for beta).
@@ -622,7 +597,7 @@ Pattern:
"timezone": "UTC",
"maxRuns": 120,
"expiresIn": "24h",
"prompt": "Resume the vX.Y.Z release babysit for commit <sha>. Check npm tags; CI and Desktop Packages on release/vX.Y.Z; every tag-triggered GitHub Actions run (Desktop Release, Android APK Release, Docker, Release Notes Sync, and Deploy App on stable) plus Deploy Website after release publish; the published GitHub Release body, expected desktop/APK assets, and channel manifests; the Docker image; the matching EAS workflow; and the reconcile PR into main. Completion requires every applicable checklist item. For stable, require build_ios, distribute_ios (Paseo Beta external distribution and Beta App Review submission), submit_ios_for_review, build_android, submit_android, and upload_android_screenshots to succeed. For beta, require the beta TestFlight distribution and Beta App Review path. If work is pending, wait for the next heartbeat. If a failure can be retried safely for the same version, follow the failed-release procedure; otherwise report the blocker. When every applicable completion-checklist item passes and the reconcile PR is merged, delete origin/release/vX.Y.Z, delete THIS heartbeat, report shipped, and stop.",
"prompt": "Resume the vX.Y.Z release babysit for commit <sha>. Check npm tags; CI and Desktop Packages on release/vX.Y.Z; every tag-triggered GitHub Actions run; the published GitHub Release body, expected desktop/APK assets, and channel manifests; the Docker image; the matching EAS workflow; and the reconcile PR into main. Completion requires every applicable checklist item. For stable, require build_ios, distribute_ios (Paseo Beta external distribution and Beta App Review submission), submit_ios_for_review, build_android, and submit_android to succeed. For beta, require the beta TestFlight distribution and Beta App Review path. If work is pending, wait for the next heartbeat. If a failure can be retried safely for the same version, follow the failed-release procedure; otherwise report the blocker. When every applicable completion-checklist item passes and the reconcile PR is merged, delete origin/release/vX.Y.Z, delete THIS heartbeat, report shipped, and stop.",
}
```
@@ -647,8 +622,6 @@ The GitHub Release body is populated automatically by the `Release Notes Sync` w
**NEVER bump the version to fix a build problem.** New versions are reserved for meaningful product changes (features, fixes, improvements). Build/CI failures are fixed on the current version.
If `npm run release:publish` or `npm run release:publish:beta` fails after `npm run release:push` pushed the tag, fix the npm authentication, OTP, or local build issue and rerun the publish command on the same commit. Do not move or force-push the `v*` tag, because `scripts/publish-release-packages.mjs` skips packages already visible on npm and resumes from the remaining packages.
**Do not rely on `workflow_dispatch` for tagged code fixes.** The `workflow_dispatch` trigger runs the workflow file from the default branch but checks out the code at the tag ref (`ref: ${{ inputs.tag }}`). That means fixes committed to `main` won't change the tagged source tree being built. `workflow_dispatch` only helps when the fix lives in the workflow file itself.
For Docker-only retries, **do not push or force-push a `v*` release tag**.
@@ -733,7 +706,9 @@ intentionally unavailable to desktop updater clients.
- The npm `version` lifecycle regenerates F-Droid changelog files from `CHANGELOG.md` for stable releases only (`npm run fdroid:changelogs`) and stages them, so the release commit and tag carry them. Betas are a no-op. A stable run **aborts the release** if `CHANGELOG.md` has no entry for the version being cut — commit the changelog entry first. See [docs/android.md](android.md) for why these files are generated per ABI.
- `release:prepare` refreshes workspace `node_modules` links to prevent stale types.
- `npm run dev:desktop` and `npm run build:desktop` target the Electron desktop package in `packages/desktop`.
- `release:publish` and `release:publish:beta` run `scripts/publish-release-packages.mjs`. They publish the seven `@getpaseo/*` packages in dependency waves, skip versions already visible on npm, retry transient registry errors, and poll `npm view` between packages so dependents do not hit `E409` or `E404` propagation lag. `release:ship` and `release:ship:beta` run `release:push` before `release:publish` or `release:publish:beta`.
- `release:publish` and `release:publish:beta` run `scripts/publish-release-packages.mjs`: if a run
fails partway through, re-running skips versions already published on npm, retries transient
registry errors, and waits for each version to become visible on npm before continuing.
- The website uses GitHub's latest published release API for download links, so published beta prereleases do not replace the stable download target.
## Changelog format
@@ -994,8 +969,8 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run, while `npm run release:publish:beta`, the `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
- [ ] All seven `@getpaseo/*` npm packages show the version under the `beta` dist-tag, not `latest`
- [ ] After go-ahead, `npm run release:ship:beta` published npm and pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*-beta.N` tag is green
- [ ] The GitHub prerelease contains `beta-mac.yml`, `beta-linux.yml`, and `beta.yml`
@@ -1003,7 +978,7 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] GitHub `Docker` workflow is green and the versioned beta image is published without moving `latest`
- [ ] GitHub `Release Notes Sync` mirrored the beta entry into the prerelease body
- [ ] EAS `Release iOS Beta` completed its build, TestFlight distribution, external beta group, and Beta App Review path
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main` and merged before cleanup, and `origin/release/vX.Y.Z-beta.N` was deleted after all sync gates passed
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main`, and `origin/release/vX.Y.Z-beta.N` was deleted
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
### Stable release (or promotion)
@@ -1013,13 +988,13 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory)
- [ ] A promotion ships the tested beta's product content after its soak, unless the user explicitly overrode either default
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes, not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z` tag without triggering a second CI run, while `npm run release:publish`, the `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
- [ ] All seven `@getpaseo/*` npm packages show `latest` at the new stable, and `beta` at the new stable too unless an active newer beta holds `beta`
- [ ] After go-ahead, `npm run release:ship` published npm, updated dist-tags, and pushed the `vX.Y.Z` tag without triggering a second CI run
- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta`
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
- [ ] The GitHub Release contains `latest-mac.yml`, `latest-linux.yml`, and `latest.yml`
@@ -1027,13 +1002,11 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] GitHub `Android APK Release` workflow for the same tag is green
- [ ] GitHub `Docker` workflow is green and both the versioned and `latest` images are published
- [ ] GitHub `Release Notes Sync` is green and the release body matches the stable changelog entry
- [ ] GitHub `Deploy App` workflow for the same tag is green, and `Deploy Website` succeeded after the release published
- [ ] EAS `Release Mobile` workflow for the same tag is green
- [ ] EAS iOS `build_ios` completes for the same tag
- [ ] EAS iOS `distribute_ios` succeeds, uploading the binary once, distributing it to `Paseo Beta`, and submitting it for Beta App Review
- [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review
- [ ] EAS Android `build_android` completes for the same tag
- [ ] EAS Android `submit_android` succeeds, putting the build on its Play Store track
- [ ] EAS Android `upload_android_screenshots` succeeds for the same tag
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries, F-Droid changelogs, and version into `main` and merged before cleanup, and `origin/release/vX.Y.Z` was deleted after all sync gates passed
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries, F-Droid changelogs, and version into `main`, and `origin/release/vX.Y.Z` was deleted
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
@@ -1,4 +0,0 @@
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
Full notes: https://paseo.sh/changelog
@@ -1,4 +0,0 @@
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
Full notes: https://paseo.sh/changelog
@@ -1,4 +0,0 @@
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
Full notes: https://paseo.sh/changelog
@@ -1,4 +0,0 @@
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-SZV3WTKLb+JhxWNo/jWyx+2sipzfL93YbbqQSihd3Wo=
sha256-kzMT9+KlfYhaEa643XUTzxOA4Y8+zdpdXEs2QguED7w=
+29 -29
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.18.0",
"version": "0.17.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.18.0",
"version": "0.17.6",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37541,7 +37541,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.18.0",
"version": "0.17.6",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39694,13 +39694,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.18.0",
"@getpaseo/protocol": "0.18.0",
"@getpaseo/server": "0.18.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/server": "0.17.6",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39947,11 +39947,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.18.0",
"@getpaseo/relay": "0.18.0",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39963,7 +39963,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40206,7 +40206,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.18.0",
"version": "0.17.6",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40252,7 +40252,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40282,7 +40282,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40290,8 +40290,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.18.0",
"@getpaseo/protocol": "0.18.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40301,8 +40301,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.18.0",
"@getpaseo/protocol": "0.18.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40324,7 +40324,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40351,7 +40351,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.18.0",
"version": "0.17.6",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40367,7 +40367,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40589,17 +40589,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.18.0",
"@getpaseo/highlight": "0.18.0",
"@getpaseo/plugin": "0.18.0",
"@getpaseo/protocol": "0.18.0",
"@getpaseo/relay": "0.18.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/highlight": "0.17.6",
"@getpaseo/plugin": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -41550,7 +41550,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.18.0",
"version": "0.17.6",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43161,7 +43161,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.18.0",
"version": "0.17.6",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.18.0",
"version": "0.17.6",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -124,8 +124,8 @@
"release:publish": "node scripts/publish-release-packages.mjs",
"release:publish:beta": "node scripts/publish-release-packages.mjs --beta",
"release:push": "node scripts/push-current-release-tag.mjs",
"release:ship": "npm run release:push && npm run release:publish",
"release:ship:beta": "npm run release:push && npm run release:publish:beta",
"release:ship": "node scripts/push-current-release-tag.mjs --check && npm run release:publish && npm run release:push",
"release:ship:beta": "node scripts/push-current-release-tag.mjs --check && npm run release:publish:beta && npm run release:push",
"release:reconcile": "node scripts/reconcile-release.mjs"
},
"devDependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.18.0",
"version": "0.17.6",
"private": true,
"main": "index.ts",
"scripts": {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.18.0",
"version": "0.17.6",
"description": "Paseo CLI - control your AI coding agents from the command line",
"license": "Apache-2.0",
"bin": {
@@ -29,9 +29,9 @@
},
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.18.0",
"@getpaseo/protocol": "0.18.0",
"@getpaseo/server": "0.18.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/server": "0.17.6",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.18.0",
"version": "0.17.6",
"description": "Paseo client SDK package",
"license": "Apache-2.0",
"files": [
@@ -49,8 +49,8 @@
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
},
"dependencies": {
"@getpaseo/protocol": "0.18.0",
"@getpaseo/relay": "0.18.0",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.18.0",
"version": "0.17.6",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.18.0",
"version": "0.17.6",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.18.0",
"version": "0.17.6",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.18.0",
"version": "0.17.6",
"description": "Paseo plugin SDK package",
"license": "Apache-2.0",
"files": [
@@ -83,8 +83,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.18.0",
"@getpaseo/protocol": "0.18.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -94,8 +94,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.18.0",
"@getpaseo/protocol": "0.18.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
+73
View File
@@ -779,3 +779,76 @@ describe("plugin notifications SDK boundary", () => {
).toEqual([]);
});
});
describe("tunnel provider SDK boundary", () => {
it("types tunnel provider registration, status union, lifecycle events, and cleanup", () => {
expect(
typeErrors(`
import type {
PluginServerContext,
TunnelEvent,
TunnelOpenContext,
TunnelProviderRegistration,
TunnelProviderStatus,
TunnelStability,
TunnelStatusContext,
TunnelTarget,
} from "@getpaseo/plugin/server";
export default function contribute(server: PluginServerContext) {
const provider: TunnelProviderRegistration = {
id: "acme-tunnel",
label: "Acme Tunnel",
description: "Expose local HTTP targets through Acme.",
docsUrl: "https://example.com/docs/tunnel",
async status({ paseo, signal }: TunnelStatusContext): Promise<TunnelProviderStatus> {
void paseo;
if (signal.aborted) {
return {
status: "unavailable",
reason: "Probe aborted",
installUrl: "https://example.com/install",
fixHint: "Retry the probe.",
};
}
return { status: "available", detail: "v1.0.0" };
},
async open(target: TunnelTarget, { paseo, signal, report }: TunnelOpenContext) {
const id: string = target.id;
const host: string = target.host;
const port: number = target.port;
const label: string | undefined = target.label;
const slug: string | undefined = target.slug;
void [id, host, port, label, slug, paseo];
// @ts-expect-error target fields are read-only
target.port = 8080;
const stability: TunnelStability = "ephemeral";
const connecting: TunnelEvent = { type: "connecting" };
const ready: TunnelEvent = {
type: "ready",
url: "https://demo.example.com",
stability,
};
const reconnecting: TunnelEvent = { type: "reconnecting", reason: "network changed" };
const error: TunnelEvent = { type: "error", message: "dropped", recoverable: true };
const closed: TunnelEvent = { type: "closed", reason: "aborted" };
report(connecting);
report(ready);
report(reconnecting);
report(error);
report(closed);
// @ts-expect-error ready event requires a url
report({ type: "ready" });
// @ts-expect-error status requires a valid discriminant
const badStatus: TunnelProviderStatus = { available: true };
void badStatus;
void signal;
},
};
const dispose: () => void = server.registerTunnelProvider(provider);
return dispose;
}
`),
).toEqual([]);
});
});
+2
View File
@@ -6,6 +6,7 @@ import type { ProviderRegistration } from "./provider.js";
import type { UsageSourceRegistration } from "./usage.js";
import type { PluginLifecycleRegistration } from "./lifecycle.js";
import type { PluginNotifications } from "./notifications.js";
import type { TunnelProviderRegistration } from "./tunnel.js";
import type { WorktreeManagerRegistration } from "./worktree.js";
export interface PluginHandlerContext {
@@ -67,6 +68,7 @@ export interface PluginServerContext extends PluginLifecycleRegistration {
registerProvider(provider: ProviderRegistration): void;
registerUsageSource(source: UsageSourceRegistration): void;
registerWorktreeManager(manager: WorktreeManagerRegistration): () => void;
registerTunnelProvider(provider: TunnelProviderRegistration): () => void;
notifications: PluginNotifications;
}
+9
View File
@@ -45,6 +45,15 @@ export type {
PluginNotificationSendResult,
PluginNotificationOpenTarget,
} from "./notifications.js";
export type {
TunnelEvent,
TunnelOpenContext,
TunnelProviderRegistration,
TunnelProviderStatus,
TunnelStability,
TunnelStatusContext,
TunnelTarget,
} from "./tunnel.js";
export type {
PluginWorktreeContext,
PluginWorktreeCreateInput,
+50
View File
@@ -0,0 +1,50 @@
import type { PaseoApi } from "@getpaseo/client";
export type TunnelStability = "ephemeral" | "stable";
export interface TunnelTarget {
readonly id: string;
readonly host: string;
readonly port: number;
readonly label?: string;
readonly slug?: string;
}
export type TunnelProviderStatus =
| {
status: "available";
detail?: string;
}
| {
status: "unavailable";
reason: string;
installUrl?: string;
fixHint?: string;
};
export type TunnelEvent =
| { type: "connecting"; detail?: string }
| { type: "ready"; url: string; stability?: TunnelStability; detail?: string }
| { type: "reconnecting"; reason?: string }
| { type: "error"; message: string; recoverable?: boolean }
| { type: "closed"; reason?: string };
export interface TunnelStatusContext {
readonly paseo: PaseoApi;
readonly signal: AbortSignal;
}
export interface TunnelOpenContext {
readonly paseo: PaseoApi;
readonly signal: AbortSignal;
report(event: TunnelEvent): void;
}
export interface TunnelProviderRegistration {
readonly id: string;
readonly label: string;
readonly description?: string;
readonly docsUrl?: string;
status(context: TunnelStatusContext): Promise<TunnelProviderStatus>;
open(target: TunnelTarget, context: TunnelOpenContext): Promise<void>;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.18.0",
"version": "0.17.6",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
+23
View File
@@ -19,6 +19,18 @@ import {
HostsRouteFrameSchema,
HostsRouteClosedSchema,
} from "./hosts.js";
import {
TunnelProvidersListRequestSchema,
TunnelProvidersListResponseSchema,
TunnelExposuresListRequestSchema,
TunnelExposuresListResponseSchema,
TunnelExposureChangedSchema,
TunnelExposureOpenRequestSchema,
TunnelExposureOpenResponseSchema,
TunnelExposureCloseRequestSchema,
TunnelExposureCloseResponseSchema,
} from "./tunnels.js";
export * from "./tunnels.js";
import {
PluginRegistryIdSchema,
PluginRegistryIdentitySchema,
@@ -3607,6 +3619,10 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
HostsRouteOpenRequestSchema,
HostsRouteFrameRequestSchema,
HostsRouteCloseRequestSchema,
TunnelProvidersListRequestSchema,
TunnelExposuresListRequestSchema,
TunnelExposureOpenRequestSchema,
TunnelExposureCloseRequestSchema,
NetworkTunnelCreateTicketRequestSchema,
BrowserHostRegisterRequestSchema,
@@ -4110,6 +4126,8 @@ export const ServerInfoStatusPayloadSchema = z
pluginSubscriptions: z.boolean().optional(),
// COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01.
pluginNotifications: z.boolean().optional(),
// COMPAT(tunnelProviders): added in v0.18.0, remove gate after 2027-06-01.
tunnelProviders: z.boolean().optional(),
// COMPAT(skillManagement): added in v0.4.0, remove gate after 2027-08-16.
skillManagement: z.boolean().optional(),
// COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26.
@@ -7799,6 +7817,11 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
HostsRouteOpenResponseSchema,
HostsRouteFrameSchema,
HostsRouteClosedSchema,
TunnelProvidersListResponseSchema,
TunnelExposuresListResponseSchema,
TunnelExposureChangedSchema,
TunnelExposureOpenResponseSchema,
TunnelExposureCloseResponseSchema,
NetworkTunnelCreateTicketResponseSchema,
BrowserHostRegisterResponseSchema,
+108
View File
@@ -0,0 +1,108 @@
import { describe, expect, it } from "vitest";
import {
ServerInfoStatusPayloadSchema,
SessionInboundMessageSchema,
SessionOutboundMessageSchema,
} from "./messages.js";
describe("tunnel protocol schemas", () => {
it("accepts tunnel inbound requests and outbound responses/events", () => {
const providerListReq = SessionInboundMessageSchema.parse({
type: "tunnel.providers.list.request",
requestId: "req-1",
});
expect(providerListReq.type).toBe("tunnel.providers.list.request");
const openReq = SessionInboundMessageSchema.parse({
type: "tunnel.exposure.open.request",
requestId: "req-2",
providerId: "cloudflared",
host: "127.0.0.1",
port: 4321,
label: "External MCP",
slug: "mcp",
});
expect(openReq.type).toBe("tunnel.exposure.open.request");
const closeReq = SessionInboundMessageSchema.parse({
type: "tunnel.exposure.close.request",
requestId: "req-3",
exposureId: "tun_1",
});
expect(closeReq.type).toBe("tunnel.exposure.close.request");
const exposure = {
id: "tun_1",
providerId: "cloudflared",
target: { host: "127.0.0.1", port: 4321, label: "External MCP", slug: "mcp" },
state: "ready" as const,
url: "https://demo.trycloudflare.com",
stability: "ephemeral" as const,
detail: null,
error: null,
createdAt: "2026-11-27T10:00:00.000Z",
updatedAt: "2026-11-27T10:00:01.000Z",
};
const listRes = SessionOutboundMessageSchema.parse({
type: "tunnel.exposures.list.response",
payload: {
requestId: "req-4",
exposures: [exposure],
subscriptionId: "sub-1",
},
});
expect(listRes.type).toBe("tunnel.exposures.list.response");
const changed = SessionOutboundMessageSchema.parse({
type: "tunnel.exposure.changed",
payload: {
subscriptionId: "sub-1",
exposure,
},
});
expect(changed.type).toBe("tunnel.exposure.changed");
const providersRes = SessionOutboundMessageSchema.parse({
type: "tunnel.providers.list.response",
payload: {
requestId: "req-1",
providers: [
{
id: "cloudflared",
pluginId: "cloudflared-tunnel",
label: "Cloudflare Tunnel",
availability: { status: "available", detail: "cloudflared 2026.1.0" },
},
{
id: "tailscale-funnel",
pluginId: "tailscale-funnel",
label: "Tailscale Funnel",
availability: {
status: "unavailable",
reason: "tailscale CLI is not installed",
installUrl: "https://tailscale.com/download",
},
},
],
},
});
expect(providersRes.type).toBe("tunnel.providers.list.response");
});
it("exposes optional server_info.features.tunnelProviders while remaining backward compatible", () => {
const base = {
status: "server_info" as const,
serverId: "srv_1",
hostname: "devbox",
version: "0.17.6",
};
expect(
ServerInfoStatusPayloadSchema.parse({ ...base, features: { tunnelProviders: true } }).features
?.tunnelProviders,
).toBe(true);
expect(
ServerInfoStatusPayloadSchema.parse({ ...base, features: {} }).features?.tunnelProviders,
).toBeUndefined();
});
});
+130
View File
@@ -0,0 +1,130 @@
import { z } from "zod";
export const TunnelStabilitySchema = z.enum(["ephemeral", "stable"]);
export const TunnelExposureStateSchema = z.enum([
"connecting",
"ready",
"reconnecting",
"error",
"closed",
]);
export const TunnelProviderAvailabilitySchema = z.discriminatedUnion("status", [
z.object({
status: z.literal("available"),
detail: z.string().optional(),
}),
z.object({
status: z.literal("unavailable"),
reason: z.string(),
installUrl: z.string().optional(),
fixHint: z.string().optional(),
}),
]);
export const TunnelProviderInfoSchema = z.object({
id: z.string(),
pluginId: z.string(),
label: z.string(),
description: z.string().optional(),
docsUrl: z.string().optional(),
availability: TunnelProviderAvailabilitySchema,
});
export const TunnelExposureTargetSchema = z.object({
host: z.string(),
port: z.number().int().min(1).max(65535),
label: z.string().optional(),
slug: z.string().optional(),
});
export const TunnelExposureSchema = z.object({
id: z.string(),
providerId: z.string(),
target: TunnelExposureTargetSchema,
state: TunnelExposureStateSchema,
url: z.string().nullable(),
stability: TunnelStabilitySchema.nullable(),
detail: z.string().nullable(),
error: z.string().nullable(),
createdAt: z.string(),
updatedAt: z.string(),
});
export type TunnelStabilityWire = z.infer<typeof TunnelStabilitySchema>;
export type TunnelExposureState = z.infer<typeof TunnelExposureStateSchema>;
export type TunnelProviderAvailability = z.infer<typeof TunnelProviderAvailabilitySchema>;
export type TunnelProviderInfo = z.infer<typeof TunnelProviderInfoSchema>;
export type TunnelExposureTarget = z.infer<typeof TunnelExposureTargetSchema>;
export type TunnelExposure = z.infer<typeof TunnelExposureSchema>;
export const TunnelProvidersListRequestSchema = z.object({
type: z.literal("tunnel.providers.list.request"),
requestId: z.string(),
});
export const TunnelProvidersListResponseSchema = z.object({
type: z.literal("tunnel.providers.list.response"),
payload: z.object({
requestId: z.string(),
providers: z.array(TunnelProviderInfoSchema),
}),
});
export const TunnelExposuresListRequestSchema = z.object({
type: z.literal("tunnel.exposures.list.request"),
requestId: z.string(),
observe: z.boolean().optional(),
});
export const TunnelExposuresListResponseSchema = z.object({
type: z.literal("tunnel.exposures.list.response"),
payload: z.object({
requestId: z.string(),
exposures: z.array(TunnelExposureSchema),
subscriptionId: z.string().optional(),
}),
});
export const TunnelExposureChangedSchema = z.object({
type: z.literal("tunnel.exposure.changed"),
payload: z.object({
subscriptionId: z.string(),
exposure: TunnelExposureSchema,
}),
});
export const TunnelExposureOpenRequestSchema = z.object({
type: z.literal("tunnel.exposure.open.request"),
requestId: z.string(),
providerId: z.string().min(1).max(256),
host: z.string().min(1).max(256),
port: z.number().int().min(1).max(65535),
id: z.string().min(1).max(256).optional(),
label: z.string().max(256).optional(),
slug: z.string().max(256).optional(),
});
export const TunnelExposureOpenResponseSchema = z.object({
type: z.literal("tunnel.exposure.open.response"),
payload: z.object({
requestId: z.string(),
exposure: TunnelExposureSchema,
}),
});
export const TunnelExposureCloseRequestSchema = z.object({
type: z.literal("tunnel.exposure.close.request"),
requestId: z.string(),
exposureId: z.string().min(1).max(256),
});
export const TunnelExposureCloseResponseSchema = z.object({
type: z.literal("tunnel.exposure.close.response"),
payload: z.object({
requestId: z.string(),
exposureId: z.string(),
closed: z.boolean(),
}),
});
@@ -1,6 +1,6 @@
{
"name": "react-native-enriched-markdown",
"version": "0.18.0",
"version": "0.17.6",
"private": true,
"description": "Markdown-based Rich Text solution for React Native",
"main": "./lib/module/index",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.18.0",
"version": "0.17.6",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.18.0",
"version": "0.17.6",
"description": "Paseo backend server",
"license": "Apache-2.0",
"files": [
@@ -109,11 +109,11 @@
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.18.0",
"@getpaseo/highlight": "0.18.0",
"@getpaseo/plugin": "0.18.0",
"@getpaseo/protocol": "0.18.0",
"@getpaseo/relay": "0.18.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/highlight": "0.17.6",
"@getpaseo/plugin": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -10,6 +10,10 @@ const INBOUND_PERMISSION = {
"hosts.add.request": "tunnel.manage",
"hosts.update.request": "tunnel.manage",
"hosts.remove.request": "tunnel.manage",
"tunnel.providers.list.request": ["daemon.read", "tunnel.manage"],
"tunnel.exposures.list.request": ["daemon.read", "tunnel.manage"],
"tunnel.exposure.open.request": "tunnel.manage",
"tunnel.exposure.close.request": "tunnel.manage",
"hosts.link.open.request": null,
"hosts.link.ack.request": null,
"hosts.route.open.request": null,
@@ -254,6 +258,11 @@ const OUTBOUND_PERMISSION = {
"hosts.add.response": "tunnel.manage",
"hosts.update.response": "tunnel.manage",
"hosts.remove.response": "tunnel.manage",
"tunnel.providers.list.response": ["daemon.read", "tunnel.manage"],
"tunnel.exposures.list.response": ["daemon.read", "tunnel.manage"],
"tunnel.exposure.changed": ["daemon.read", "tunnel.manage"],
"tunnel.exposure.open.response": "tunnel.manage",
"tunnel.exposure.close.response": "tunnel.manage",
"hosts.link.open.response": null,
"hosts.route.open.response": null,
"hosts.route.frame": null,
+12
View File
@@ -215,6 +215,7 @@ import {
} from "./hub/relationship-remote.js";
import { DaemonExecutions } from "./hub/daemon-executions.js";
import { PluginService } from "./plugins/index.js";
import { TunnelManager } from "./tunnels/index.js";
import { BuiltinPluginLoader } from "./plugins/builtin/index.js";
import { ManagedPluginSources } from "./plugins/managed-source.js";
@@ -460,6 +461,7 @@ export interface PaseoDaemon {
agentStorage: AgentStorage;
terminalManager: TerminalManager;
serviceProxy: ServiceProxySubsystem;
tunnelManager: TunnelManager;
scriptRuntimeStore: WorkspaceScriptRuntimeStore;
browserToolsBroker: BrowserToolsBroker;
start(): Promise<void>;
@@ -646,7 +648,9 @@ export async function createPaseoDaemon(
});
const browserToolsPolicy = new DaemonConfigBrowserToolsPolicy(daemonConfigStore);
const browserToolsBroker = new BrowserToolsBroker({});
const tunnelManager = new TunnelManager({ logger });
const pluginRuntime: PluginService = new PluginService(logger, daemonConfigStore, daemonVersion, {
tunnelManager,
usageAgents: {
hasAgent: (id) => agentManager.getAgent(id) !== null,
usageSession: (id) => agentManager.usageSession(id),
@@ -1955,6 +1959,7 @@ export async function createPaseoDaemon(
workspaceLabelService,
workspaceArchiveOperations,
config.pushNotifications,
tunnelManager,
);
pluginRuntime.bindPaseoSessionHost(wsServer);
await pluginRuntime.start();
@@ -2023,6 +2028,7 @@ export async function createPaseoDaemon(
localCredential = null;
await deleteLocalCredential(config.paseoHome);
unsubscribePluginProviders();
await tunnelManager.closeAll().catch(() => undefined);
await pluginRuntime.stopAllPlugins().catch(() => undefined);
await serviceProxy.stopStandalone().catch(() => undefined);
await agentProviderRuntime.shutdown().catch(() => undefined);
@@ -2085,6 +2091,11 @@ export async function createPaseoDaemon(
);
await agentStorage.flush().catch(() => undefined);
}
await withTimeout({
promise: tunnelManager.closeAll(),
timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
label: "close active tunnels",
}).catch((error) => logger.warn({ err: error }, "Failed to close active tunnels"));
await pluginRuntime.stopAllPlugins();
try {
if (keepTerminals) {
@@ -2134,6 +2145,7 @@ export async function createPaseoDaemon(
agentStorage,
terminalManager,
serviceProxy,
tunnelManager,
scriptRuntimeStore,
browserToolsBroker,
start,
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
export const builtinPlugins = [
"antigravity-provider",
"claude-usage-source",
"cloudflared-tunnel",
"codex-usage-source",
"copilot-usage-source",
"cursor-usage-source",
@@ -18,6 +19,7 @@ export const builtinPlugins = [
"muse-provider",
"opencode-go-usage-source",
"openrouter-host-usage-source",
"tailscale-funnel",
"worktree-include",
"zai-usage-source",
] as const;
+95 -2
View File
@@ -30,14 +30,16 @@ import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js";
import type {
PluginProviderInstallationMetadata,
PluginProviderMetadata,
PluginTunnelProviderMetadata,
PluginUsageSourceMetadata,
} from "./plugin-process-protocol.js";
import type { RegisteredTunnelProvider, TunnelManager } from "../tunnels/index.js";
import { readPluginProviderIcon } from "./provider-icon.js";
import {
type AgentUsageLookup,
type ListUsageReportsOptions,
UsageSourceRegistry,
} from "./usage-sources/index.js";
import type { PluginUsageSourceMetadata } from "./plugin-process-protocol.js";
const BUILTIN_PROVIDER_ID_SET: ReadonlySet<string> = new Set(BUILTIN_PROVIDER_IDS);
@@ -60,6 +62,9 @@ interface PluginRuntimePort {
clearLogs(pluginId: string): void;
getProviderRegistrations?(pluginId: string): readonly PluginProviderMetadata[];
getUsageSourceRegistrations(pluginId: string): readonly PluginUsageSourceMetadata[];
getTunnelProviderRegistrations?(pluginId: string): readonly PluginTunnelProviderMetadata[];
getTunnelProviderStatus?: PluginRuntime["getTunnelProviderStatus"];
openTunnel?: PluginRuntime["openTunnel"];
fetchUsage: PluginRuntime["fetchUsage"];
discoverUsage: PluginRuntime["discoverUsage"];
connectProvider: PluginRuntime["connectProvider"];
@@ -79,6 +84,7 @@ interface PluginRuntimePort {
interface PluginServiceDependencies {
usageAgents?: AgentUsageLookup;
tunnelManager?: TunnelManager;
settingsDirectory?: string;
runtime?: PluginRuntimePort;
managedSources?: ManagedPluginSources;
@@ -110,6 +116,8 @@ export class PluginService {
private readonly providers = new Map<string, ProviderRegistration>();
private readonly usageSources: UsageSourceRegistry;
private readonly usageSourceIdsByPlugin = new Map<string, string[]>();
private readonly tunnelManager: TunnelManager | null;
private readonly tunnelProviderIdsByPlugin = new Map<string, string[]>();
private readonly providerIdsByPlugin = new Map<string, readonly string[]>();
private readonly providerListeners = new Set<() => void>();
private lifecycle = Promise.resolve();
@@ -134,6 +142,7 @@ export class PluginService {
this.logger,
dependencies.usageAgents,
);
this.tunnelManager = dependencies.tunnelManager ?? null;
this.runtime =
dependencies.runtime ??
new PluginRuntime(logger, daemonVersion, {
@@ -141,6 +150,14 @@ export class PluginService {
onSettingsChanged: (pluginId, settingsId) => {
for (const listener of this.settingsListeners) listener(pluginId, settingsId);
},
onTunnelProvidersChanged: (pluginId) => {
void this.syncTunnelProviders(pluginId).catch((error) => {
this.logger.warn(
{ err: error, pluginId },
"Failed to synchronize plugin tunnel providers",
);
});
},
});
this.managedSources = dependencies.managedSources ?? null;
this.builtinPlugins = dependencies.builtinPlugins ?? new BuiltinPluginLoader(undefined, []);
@@ -148,6 +165,7 @@ export class PluginService {
this.runtime.subscribe((pluginId, error) => {
this.removeProviderRegistrations(pluginId);
this.removeUsageSources(pluginId);
void this.removeTunnelProviders(pluginId);
if (error) this.errors.set(pluginId, error);
this.notify(pluginId);
});
@@ -277,6 +295,7 @@ export class PluginService {
await this.runtime.startBuiltinPlugin?.(plugin);
await this.publishProviderRegistrations(plugin.id, plugin.directory);
this.publishUsageSources(plugin.id);
this.publishTunnelProviders(plugin.id);
} catch (error) {
this.logger.error({ err: error, pluginId: plugin.id }, "Failed to start built-in plugin");
}
@@ -678,10 +697,12 @@ export class PluginService {
try {
await this.publishProviderRegistrations(pluginId, sourcePath);
this.publishUsageSources(pluginId);
this.publishTunnelProviders(pluginId);
} catch (error) {
try {
this.removeProviderRegistrations(pluginId);
this.removeUsageSources(pluginId);
await this.removeTunnelProviders(pluginId);
} finally {
await this.runtime.stopPluginById(pluginId);
}
@@ -689,9 +710,10 @@ export class PluginService {
}
}
private stopPlugin(pluginId: string): Promise<boolean> {
private async stopPlugin(pluginId: string): Promise<boolean> {
this.removeProviderRegistrations(pluginId);
this.removeUsageSources(pluginId);
await this.removeTunnelProviders(pluginId);
return this.runtime.stopPluginById(pluginId);
}
@@ -707,9 +729,80 @@ export class PluginService {
this.removeProviderRegistrations(pluginId);
}
for (const pluginId of this.usageSourceIdsByPlugin.keys()) this.removeUsageSources(pluginId);
await Promise.all(
[...this.tunnelProviderIdsByPlugin.keys()].map((pluginId) =>
this.removeTunnelProviders(pluginId),
),
);
await this.runtime.stopAll();
}
private buildTunnelProviders(pluginId: string): RegisteredTunnelProvider[] {
const metadata = this.runtime.getTunnelProviderRegistrations?.(pluginId) ?? [];
return metadata.map((provider) => {
const entry: RegisteredTunnelProvider = {
id: provider.id,
pluginId,
label: provider.label,
description: provider.description,
docsUrl: provider.docsUrl,
status: (options) => {
if (!this.runtime.getTunnelProviderStatus) {
throw new Error("Plugin runtime cannot query tunnel provider status");
}
return this.runtime.getTunnelProviderStatus(pluginId, provider.id, options);
},
open: (exposureId, target, callbacks) => {
if (!this.runtime.openTunnel) {
throw new Error("Plugin runtime cannot open tunnels");
}
return this.runtime.openTunnel(pluginId, provider.id, exposureId, target, callbacks);
},
};
return entry;
});
}
private publishTunnelProviders(pluginId: string): void {
if (!this.tunnelManager) return;
const providers = this.buildTunnelProviders(pluginId);
const registered: string[] = [];
try {
for (const provider of providers) {
this.tunnelManager.registerProvider(provider);
registered.push(provider.id);
}
} catch (error) {
for (const id of registered) {
void this.tunnelManager.unregisterProvider(id);
}
throw error;
}
if (registered.length > 0) {
this.tunnelProviderIdsByPlugin.set(pluginId, registered);
}
}
private async syncTunnelProviders(pluginId: string): Promise<void> {
if (!this.tunnelManager) return;
const providers = this.buildTunnelProviders(pluginId);
await this.tunnelManager.syncPluginProviders(pluginId, providers);
if (providers.length > 0) {
this.tunnelProviderIdsByPlugin.set(
pluginId,
providers.map((provider) => provider.id),
);
} else {
this.tunnelProviderIdsByPlugin.delete(pluginId);
}
}
private async removeTunnelProviders(pluginId: string): Promise<void> {
this.tunnelProviderIdsByPlugin.delete(pluginId);
if (!this.tunnelManager) return;
await this.tunnelManager.unregisterPlugin(pluginId);
}
private publishUsageSources(pluginId: string): void {
const metadata = this.runtime.getUsageSourceRegistrations(pluginId);
const registered: string[] = [];
@@ -1,5 +1,11 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginHookAgent, PluginNotificationSendResult } from "@getpaseo/plugin/server";
import type {
PluginHookAgent,
PluginNotificationSendResult,
TunnelEvent,
TunnelProviderStatus,
TunnelTarget,
} from "@getpaseo/plugin/server";
import { UsageScopeSchema, type UsageScope } from "@getpaseo/plugin/server/usage";
import type {
ProviderCatalogOptions,
@@ -57,6 +63,79 @@ export interface PluginWorktreeManagerCapabilities {
hasRestore: boolean;
}
export interface PluginTunnelProviderMetadata {
id: string;
label: string;
description?: string;
docsUrl?: string;
}
export const TunnelTargetSchema: z.ZodType<TunnelTarget> = z
.object({
id: z.string().min(1),
host: z.string().min(1),
port: z.number().int().min(1).max(65535),
label: z.string().optional(),
slug: z.string().optional(),
})
.strict();
export const TunnelProviderStatusSchema: z.ZodType<TunnelProviderStatus> = z.discriminatedUnion(
"status",
[
z
.object({
status: z.literal("available"),
detail: z.string().optional(),
})
.strict(),
z
.object({
status: z.literal("unavailable"),
reason: z.string().min(1),
installUrl: z.string().optional(),
fixHint: z.string().optional(),
})
.strict(),
],
);
export const TunnelEventSchema: z.ZodType<TunnelEvent> = z.discriminatedUnion("type", [
z
.object({
type: z.literal("connecting"),
detail: z.string().optional(),
})
.strict(),
z
.object({
type: z.literal("ready"),
url: z.string().min(1),
stability: z.enum(["ephemeral", "stable"]).optional(),
detail: z.string().optional(),
})
.strict(),
z
.object({
type: z.literal("reconnecting"),
reason: z.string().optional(),
})
.strict(),
z
.object({
type: z.literal("error"),
message: z.string().min(1),
recoverable: z.boolean().optional(),
})
.strict(),
z
.object({
type: z.literal("closed"),
reason: z.string().optional(),
})
.strict(),
]);
export type PluginProcessRequest =
| { type: "tool.call"; requestId: string; agent: PluginHookAgent; name: string; input: unknown }
| { type: "tool.cancel"; requestId: string }
@@ -100,6 +179,10 @@ export type PluginProcessRequest =
| { type: "worktree.remove"; requestId: string; request: unknown }
| { type: "worktree.restore"; requestId: string; request: unknown }
| { type: "worktree.cancel"; requestId: string }
| { type: "tunnel.status"; requestId: string; providerId: string }
| { type: "tunnel.status.cancel"; requestId: string }
| { type: "tunnel.open"; exposureId: string; providerId: string; target: TunnelTarget }
| { type: "tunnel.close"; exposureId: string }
| { type: "usage.fetch"; requestId: string; sourceId: string; input: unknown }
| { type: "usage.discover"; requestId: string; sourceId: string; scope: UsageScope }
| { type: "invoke"; requestId: string; method: string; input: unknown }
@@ -137,6 +220,10 @@ export type PluginProcessMessage =
type: "worktree_manager.changed";
worktreeManager: PluginWorktreeManagerCapabilities | null;
}
| {
type: "tunnel_providers.changed";
tunnelProviders: PluginTunnelProviderMetadata[];
}
| {
type: "ready";
methods: string[];
@@ -145,7 +232,10 @@ export type PluginProcessMessage =
usageSources?: PluginUsageSourceMetadata[];
hooks?: string[];
worktreeManager?: PluginWorktreeManagerCapabilities | null;
tunnelProviders?: PluginTunnelProviderMetadata[];
}
| { type: "tunnel.event"; exposureId: string; event: TunnelEvent }
| { type: "tunnel.closed"; exposureId: string; error?: string }
| { type: "result"; requestId: string; output: unknown }
| { type: "error"; requestId: string; error: string }
| { type: "provider.installation.report"; requestId: string; report: ProviderUpdateReport }
@@ -180,6 +270,15 @@ const worktreeManagerCapabilitiesSchema = z
})
.strict();
const tunnelProviderMetadataSchema = z
.object({
id: z.string().min(1),
label: z.string().min(1),
description: z.string().optional(),
docsUrl: z.string().optional(),
})
.strict();
const providerMetadataSchema = z
.object({
id: z.string().min(1),
@@ -337,6 +436,23 @@ export const PluginProcessRequestSchema: z.ZodType<PluginProcessRequest> = z.dis
})
.strict(),
z.object({ type: z.literal("worktree.cancel"), requestId: z.string().min(1) }).strict(),
z
.object({
type: z.literal("tunnel.status"),
requestId: z.string().min(1),
providerId: z.string().min(1),
})
.strict(),
z.object({ type: z.literal("tunnel.status.cancel"), requestId: z.string().min(1) }).strict(),
z
.object({
type: z.literal("tunnel.open"),
exposureId: z.string().min(1),
providerId: z.string().min(1),
target: TunnelTargetSchema,
})
.strict(),
z.object({ type: z.literal("tunnel.close"), exposureId: z.string().min(1) }).strict(),
z
.object({
type: z.literal("usage.fetch"),
@@ -428,6 +544,12 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
worktreeManager: worktreeManagerCapabilitiesSchema.nullable(),
})
.strict(),
z
.object({
type: z.literal("tunnel_providers.changed"),
tunnelProviders: z.array(tunnelProviderMetadataSchema),
})
.strict(),
z
.object({
type: z.literal("ready"),
@@ -437,6 +559,21 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
usageSources: z.array(usageSourceMetadataSchema).optional(),
hooks: hooksSchema.optional(),
worktreeManager: worktreeManagerCapabilitiesSchema.nullable().optional(),
tunnelProviders: z.array(tunnelProviderMetadataSchema).optional(),
})
.strict(),
z
.object({
type: z.literal("tunnel.event"),
exposureId: z.string().min(1),
event: TunnelEventSchema,
})
.strict(),
z
.object({
type: z.literal("tunnel.closed"),
exposureId: z.string().min(1),
error: z.string().optional(),
})
.strict(),
z
@@ -3,8 +3,11 @@ import { PluginHookHandlers } from "./lifecycle/index.js";
import { evaluateBundle } from "./bundle-evaluator.js";
import {
PluginProcessRequestSchema,
TunnelEventSchema,
TunnelProviderStatusSchema,
type PluginProcessMessage,
type PluginProcessRequest,
type PluginTunnelProviderMetadata,
} from "./plugin-process-protocol.js";
import type { UsageSourceRegistration } from "@getpaseo/plugin/server/usage";
import type {
@@ -22,6 +25,7 @@ import type {
PluginWorktreeCreateInput,
PluginWorktreeRemoveRequest,
PluginWorktreeRestoreRequest,
TunnelProviderRegistration,
WorktreeManagerRegistration,
} from "@getpaseo/plugin/server";
import { randomUUID } from "node:crypto";
@@ -124,8 +128,20 @@ export function createPluginWorker(options: {
const subscriptions = new PluginSubscriptionHandlers({ send, sendAndWait });
const providers = new Map<string, ProviderRegistration>();
const usageSources = new Map<string, UsageSourceRegistration>();
const tunnelProviders = new Map<string, TunnelProviderRegistration>();
const tunnelStatusRequests = new Map<string, AbortController>();
const activeTunnels = new Map<
string,
{
providerId: string;
controller: AbortController;
abortedByHost: boolean;
done: Promise<void>;
}
>();
let worktreeManager: WorktreeManagerRegistration | null = null;
const worktreeRequests = new Map<string, AbortController>();
let readySent = false;
const providerConnections = new Map<
string,
{ connection: ProviderConnection; unsubscribe: () => void; closing?: Promise<void> }
@@ -290,6 +306,67 @@ export function createPluginWorker(options: {
};
}
function tunnelProviderCatalog(): PluginTunnelProviderMetadata[] {
return [...tunnelProviders.values()]
.sort((left, right) => left.id.localeCompare(right.id))
.map((provider) => {
const entry: PluginTunnelProviderMetadata = {
id: provider.id,
label: provider.label,
};
if (provider.description !== undefined) entry.description = provider.description;
if (provider.docsUrl !== undefined) entry.docsUrl = provider.docsUrl;
return entry;
});
}
function registerTunnelProvider(provider: TunnelProviderRegistration): () => void {
const id = typeof provider?.id === "string" ? provider.id.trim() : "";
if (!/^[a-z][a-z0-9._-]*$/.test(id)) {
throw new Error(`Invalid tunnel provider ID: ${provider?.id}`);
}
if (typeof provider.label !== "string" || !provider.label.trim()) {
throw new Error(`Tunnel provider ${id} requires a label`);
}
if (typeof provider.status !== "function") {
throw new Error(`Tunnel provider ${id} must implement status()`);
}
if (typeof provider.open !== "function") {
throw new Error(`Tunnel provider ${id} must implement open()`);
}
if (
provider.docsUrl !== undefined &&
(typeof provider.docsUrl !== "string" || !isHttpUrl(provider.docsUrl))
) {
throw new Error(`Tunnel provider ${id} docsUrl must be an http(s) URL`);
}
if (tunnelProviders.has(id)) {
throw new Error(`Duplicate tunnel provider ID: ${id}`);
}
const registered: TunnelProviderRegistration = {
...provider,
id,
label: provider.label.trim(),
};
tunnelProviders.set(id, registered);
if (readySent && !stopping) {
send({ type: "tunnel_providers.changed", tunnelProviders: tunnelProviderCatalog() });
}
return () => {
if (tunnelProviders.get(id) !== registered) return;
tunnelProviders.delete(id);
for (const active of activeTunnels.values()) {
if (active.providerId === id) {
active.abortedByHost = true;
active.controller.abort(new Error(`Tunnel provider unregistered: ${id}`));
}
}
if (readySent && !stopping) {
send({ type: "tunnel_providers.changed", tunnelProviders: tunnelProviderCatalog() });
}
};
}
const notifications: PluginNotifications = {
send(input: PluginNotificationSendInput): Promise<PluginNotificationSendResult> {
if (stopping) {
@@ -525,6 +602,7 @@ export function createPluginWorker(options: {
registerProvider,
registerUsageSource,
registerWorktreeManager,
registerTunnelProvider,
registerSettings,
notifications,
addHook: hooks.addHook,
@@ -554,11 +632,13 @@ export function createPluginWorker(options: {
subscriptions: subscriptions.catalog(),
hooks: hooks.catalog(),
worktreeManager: worktreeManagerCapabilities(),
tunnelProviders: tunnelProviderCatalog(),
providers: [...providers.values()]
.sort((left, right) => left.id.localeCompare(right.id))
.map(providerMetadata),
usageSources: usageSourceMetadata,
});
readySent = true;
}
async function shutdown(): Promise<void> {
@@ -574,6 +654,16 @@ export function createPluginWorker(options: {
for (const request of installationRequests.values())
request.abort(new Error("Plugin is stopping"));
for (const request of worktreeRequests.values()) request.abort(new Error("Plugin is stopping"));
for (const request of tunnelStatusRequests.values())
request.abort(new Error("Plugin is stopping"));
const closingTunnels: Promise<void>[] = [];
for (const active of activeTunnels.values()) {
active.abortedByHost = true;
active.controller.abort(new Error("Plugin is stopping"));
closingTunnels.push(active.done);
}
await Promise.allSettled(closingTunnels);
tunnelProviders.clear();
for (const pending of notificationRequests.values())
pending.reject(new Error("Plugin is stopping"));
notificationRequests.clear();
@@ -622,9 +712,20 @@ export function createPluginWorker(options: {
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore" ||
message.type === "tunnel.status" ||
message.type === "subscribe"
) {
send({ type: "error", requestId: message.requestId, error: "Plugin is stopping" });
} else if (message.type === "tunnel.open") {
send({
type: "tunnel.closed",
exposureId: message.exposureId,
error: "Plugin is stopping",
});
} else if (message.type === "tunnel.close") {
if (!activeTunnels.has(message.exposureId)) {
send({ type: "tunnel.closed", exposureId: message.exposureId });
}
} else if (message.type === "provider.connect") {
send({
type: "provider.connect_failed",
@@ -839,6 +940,10 @@ export function createPluginWorker(options: {
handleWorktreeMessage(message);
return;
}
if (isTunnelMessage(message)) {
handleTunnelMessage(message);
return;
}
if (message.type === "invoke") invoke(message);
else handleSubscriptionMessage(message);
}
@@ -986,6 +1091,164 @@ export function createPluginWorker(options: {
)
.finally(() => worktreeRequests.delete(message.requestId));
}
function isTunnelMessage(
message: PluginProcessRequest,
): message is Extract<
PluginProcessRequest,
{ type: "tunnel.status" | "tunnel.status.cancel" | "tunnel.open" | "tunnel.close" }
> {
return (
message.type === "tunnel.status" ||
message.type === "tunnel.status.cancel" ||
message.type === "tunnel.open" ||
message.type === "tunnel.close"
);
}
function handleTunnelMessage(
message: Extract<
PluginProcessRequest,
{ type: "tunnel.status" | "tunnel.status.cancel" | "tunnel.open" | "tunnel.close" }
>,
): void {
if (message.type === "tunnel.status.cancel") {
tunnelStatusRequests.get(message.requestId)?.abort(new Error("Tunnel status canceled"));
return;
}
if (message.type === "tunnel.close") {
const active = activeTunnels.get(message.exposureId);
if (!active) {
send({ type: "tunnel.closed", exposureId: message.exposureId });
return;
}
active.abortedByHost = true;
active.controller.abort(new Error("Tunnel closed"));
return;
}
if (!paseo) {
if (message.type === "tunnel.status") {
send({
type: "error",
requestId: message.requestId,
error: "Plugin Paseo API is unavailable",
});
} else {
send({
type: "tunnel.closed",
exposureId: message.exposureId,
error: "Plugin Paseo API is unavailable",
});
}
return;
}
const provider = tunnelProviders.get(message.providerId);
if (!provider) {
if (message.type === "tunnel.status") {
send({
type: "error",
requestId: message.requestId,
error: `Unknown tunnel provider: ${message.providerId}`,
});
} else {
send({
type: "tunnel.closed",
exposureId: message.exposureId,
error: `Unknown tunnel provider: ${message.providerId}`,
});
}
return;
}
if (message.type === "tunnel.status") {
const controller = new AbortController();
tunnelStatusRequests.set(message.requestId, controller);
void Promise.resolve()
.then(() => provider.status({ paseo: paseo!, signal: controller.signal }))
.then((raw) => {
const parsed = TunnelProviderStatusSchema.parse(jsonTransportValue(raw));
if (
parsed.status === "unavailable" &&
parsed.installUrl !== undefined &&
!isHttpUrl(parsed.installUrl)
) {
throw new Error(`Tunnel provider ${provider.id} installUrl must be an http(s) URL`);
}
send({ type: "result", requestId: message.requestId, output: parsed });
return undefined;
})
.catch((error) => {
send({ type: "error", requestId: message.requestId, error: describeError(error) });
return undefined;
})
.finally(() => {
tunnelStatusRequests.delete(message.requestId);
});
return;
}
if (activeTunnels.has(message.exposureId)) {
send({
type: "tunnel.closed",
exposureId: message.exposureId,
error: `Duplicate tunnel exposure: ${message.exposureId}`,
});
return;
}
const controller = new AbortController();
let settled = false;
let reportFailure: string | undefined;
const entry = {
providerId: provider.id,
controller,
abortedByHost: false,
done: Promise.resolve(),
};
const report = (rawEvent: unknown) => {
if (settled) return;
try {
const event = TunnelEventSchema.parse(jsonTransportValue(rawEvent));
if (event.type === "ready" && !isHttpUrl(event.url)) {
throw new Error(`Tunnel provider ${provider.id} reported invalid URL: ${event.url}`);
}
send({ type: "tunnel.event", exposureId: message.exposureId, event });
} catch (error) {
reportFailure = describeError(error);
controller.abort(error);
}
};
const done = Promise.resolve()
.then(() =>
provider.open(structuredClone(message.target), {
paseo: paseo!,
signal: controller.signal,
report,
}),
)
.then(
() => {
settled = true;
activeTunnels.delete(message.exposureId);
send({
type: "tunnel.closed",
exposureId: message.exposureId,
...(reportFailure ? { error: reportFailure } : {}),
});
return undefined;
},
(error) => {
settled = true;
activeTunnels.delete(message.exposureId);
const failure = reportFailure ?? (entry.abortedByHost ? undefined : describeError(error));
send({
type: "tunnel.closed",
exposureId: message.exposureId,
...(failure ? { error: failure } : {}),
});
return undefined;
},
);
entry.done = done;
activeTunnels.set(message.exposureId, entry);
}
return { shutdown };
}
@@ -2231,6 +2231,7 @@ const examples = (await readdir(examplesDirectory, { withFileTypes: true }))
const exampleDaemonVersions: Record<string, string> = {
"sidebar-views": "0.16.0",
notifications: "0.18.0-beta.1",
"tunnel-provider": "0.18.0-beta.1",
};
it.each(examples)("builds and loads the %s plugin example", async (example) => {
+155 -1
View File
@@ -25,6 +25,9 @@ import type {
PluginWorktreeCreateInput,
PluginWorktreeRemoveRequest,
PluginWorktreeRestoreRequest,
TunnelEvent,
TunnelProviderStatus,
TunnelTarget,
} from "@getpaseo/plugin/server";
import { z } from "zod";
import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js";
@@ -49,10 +52,14 @@ import type {
PluginProcessMessage,
PluginProcessRequest,
PluginProviderMetadata,
PluginTunnelProviderMetadata,
PluginUsageSourceMetadata,
PluginWorktreeManagerCapabilities,
} from "./plugin-process-protocol.js";
import { PluginProcessMessageSchema } from "./plugin-process-protocol.js";
import {
PluginProcessMessageSchema,
TunnelProviderStatusSchema,
} from "./plugin-process-protocol.js";
import {
BufferedPluginSubscription,
type PluginRuntimeSubscription,
@@ -148,11 +155,13 @@ interface LoadedPlugin {
worktreeManager: PluginWorktreeManagerCapabilities | null;
providers: readonly PluginProviderMetadata[];
usageSources: readonly PluginUsageSourceMetadata[];
tunnelProviders: readonly PluginTunnelProviderMetadata[];
child: PluginChild | null;
outputCapture: PluginOutputCapture | null;
pending: Map<string, PendingInvocation>;
providerConnections: Map<string, RemoteProviderConnection>;
providerConnectionTombstones: Set<string>;
tunnelExposures: Map<string, RemoteTunnelExposure>;
sessionSocket: PluginSessionSocket | null;
sessionClosed: Promise<void> | null;
}
@@ -194,9 +203,18 @@ interface RemoteProviderConnection {
rejectClosed(error: Error): void;
}
interface RemoteTunnelExposure {
onEvent(event: TunnelEvent): void;
onClosed(error?: string): void;
closed: boolean;
closedPromise: Promise<void>;
resolveClosed(): void;
}
interface PluginRuntimeDependencies {
settingsDirectory?: string;
onSettingsChanged?: (pluginId: string, settingsId: string) => void;
onTunnelProvidersChanged?: (pluginId: string) => void;
spawnChild?: () => PluginChild;
sessionHost?: PluginPaseoSessionHost;
}
@@ -493,6 +511,101 @@ export class PluginRuntime {
return this.plugins.get(pluginId)?.usageSources ?? [];
}
getTunnelProviderRegistrations(pluginId: string): readonly PluginTunnelProviderMetadata[] {
return this.plugins.get(pluginId)?.tunnelProviders ?? [];
}
async getTunnelProviderStatus(
pluginId: string,
providerId: string,
options?: { signal?: AbortSignal },
): Promise<TunnelProviderStatus> {
const loaded = this.plugins.get(pluginId);
if (!loaded) throw new Error(`Plugin is not available: ${pluginId}`);
if (!loaded.tunnelProviders.some((provider) => provider.id === providerId)) {
throw new Error(`Plugin ${pluginId} does not contribute tunnel provider ${providerId}`);
}
return TunnelProviderStatusSchema.parse(
await this.request(
loaded,
{ type: "tunnel.status", requestId: randomUUID(), providerId },
{ signal: options?.signal },
),
);
}
openTunnel(
pluginId: string,
providerId: string,
exposureId: string,
target: TunnelTarget,
callbacks: {
onEvent(event: TunnelEvent): void;
onClosed(error?: string): void;
},
): { close(): Promise<void> } {
const loaded = this.plugins.get(pluginId);
if (!loaded?.child) throw new Error(`Plugin is not available: ${pluginId}`);
if (!loaded.tunnelProviders.some((provider) => provider.id === providerId)) {
throw new Error(`Plugin ${pluginId} does not contribute tunnel provider ${providerId}`);
}
if (loaded.tunnelExposures.has(exposureId)) {
throw new Error(`Duplicate tunnel exposure: ${exposureId}`);
}
let resolveClosed!: () => void;
const closedPromise = new Promise<void>((resolve) => {
resolveClosed = resolve;
});
const state: RemoteTunnelExposure = {
onEvent: callbacks.onEvent,
onClosed: callbacks.onClosed,
closed: false,
closedPromise,
resolveClosed,
};
const finish = (error?: string) => {
if (state.closed) return;
state.closed = true;
loaded.tunnelExposures.delete(exposureId);
state.resolveClosed();
state.onClosed(error);
};
loaded.tunnelExposures.set(exposureId, state);
void send(loaded.child, {
type: "tunnel.open",
exposureId,
providerId,
target,
}).catch((error) => {
finish(describeError(error));
});
return {
close: async () => {
if (state.closed) return;
if (loaded.child?.connected) {
await send(loaded.child, { type: "tunnel.close", exposureId }).catch(() => undefined);
} else {
finish();
return;
}
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
state.closedPromise,
new Promise<void>((resolve) => {
timer = setTimeout(() => {
finish();
resolve();
}, 5_000);
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
},
};
}
fetchUsage(pluginId: string, sourceId: string, input: unknown): Promise<unknown> {
const loaded = this.plugins.get(pluginId);
if (!loaded) throw new Error(`Plugin is not available: ${pluginId}`);
@@ -989,6 +1102,8 @@ export class PluginRuntime {
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
if (isInstallationRequest(message))
void send(child, { type: "provider.installation.cancel", requestId }).catch(() => {});
if (message.type === "tunnel.status")
void send(child, { type: "tunnel.status.cancel", requestId }).catch(() => {});
signal?.removeEventListener("abort", cancel);
reject(signal?.reason ?? new Error("Plugin request canceled"));
};
@@ -1016,6 +1131,8 @@ export class PluginRuntime {
void send(child, { type: "provider.installation.cancel", requestId }).catch(
() => {},
);
if (message.type === "tunnel.status")
void send(child, { type: "tunnel.status.cancel", requestId }).catch(() => {});
reject(new Error(`Plugin RPC timed out: ${pluginId}.${message.type}`));
}, timeoutMs);
signal?.addEventListener("abort", cancel, { once: true });
@@ -1075,11 +1192,13 @@ export class PluginRuntime {
worktreeManager: null,
providers: [],
usageSources: [],
tunnelProviders: [],
child: null,
outputCapture: null,
pending: new Map(),
providerConnections: new Map(),
providerConnectionTombstones: new Set(),
tunnelExposures: new Map(),
sessionSocket: null,
sessionClosed: null,
};
@@ -1208,11 +1327,13 @@ export class PluginRuntime {
worktreeManager: ready.worktreeManager ?? null,
providers: ready.providers ?? [],
usageSources: ready.usageSources ?? [],
tunnelProviders: ready.tunnelProviders ?? [],
child,
outputCapture,
pending,
providerConnections: new Map(),
providerConnectionTombstones: new Set(),
tunnelExposures: new Map(),
sessionSocket: session.socket,
sessionClosed: sessionAttachment.closed,
};
@@ -1292,6 +1413,7 @@ export class PluginRuntime {
loaded.worktreeManager = message.worktreeManager;
return;
}
if (this.handleTunnelMessage(loaded, message)) return;
if (message.type === "settings.changed") {
this.dependencies.onSettingsChanged?.(loaded.id, message.settingsId);
return;
@@ -1327,6 +1449,30 @@ export class PluginRuntime {
else pending.reject(new Error(message.error));
}
private handleTunnelMessage(loaded: LoadedPlugin, message: PluginProcessMessage): boolean {
if (message.type === "tunnel_providers.changed") {
loaded.tunnelProviders = message.tunnelProviders;
this.dependencies.onTunnelProvidersChanged?.(loaded.id);
return true;
}
if (message.type === "tunnel.event") {
const exposure = loaded.tunnelExposures.get(message.exposureId);
if (exposure && !exposure.closed) exposure.onEvent(message.event);
return true;
}
if (message.type === "tunnel.closed") {
const exposure = loaded.tunnelExposures.get(message.exposureId);
if (exposure && !exposure.closed) {
exposure.closed = true;
loaded.tunnelExposures.delete(message.exposureId);
exposure.resolveClosed();
exposure.onClosed(message.error);
}
return true;
}
return false;
}
private async handleNotificationSend(
loaded: LoadedPlugin,
message: Extract<PluginProcessMessage, { type: "notification.send" }>,
@@ -1652,6 +1798,14 @@ export class PluginRuntime {
this.failRemoteProviderConnection(state, new Error(`Plugin process exited: ${loaded.id}`));
}
loaded.providerConnections.clear();
const exposures = [...loaded.tunnelExposures.values()];
loaded.tunnelExposures.clear();
for (const exposure of exposures) {
if (exposure.closed) continue;
exposure.closed = true;
exposure.resolveClosed();
exposure.onClosed(`Plugin process exited: ${loaded.id}`);
}
await loaded.sessionClosed;
if (wasPublished) this.notify(loaded.id, `Plugin process exited: ${loaded.id}`);
}
@@ -0,0 +1,436 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type {
SessionInboundMessage,
SessionOutboundMessage,
TunnelExposure,
TunnelProviderInfo,
} from "@getpaseo/protocol/messages";
import { afterEach, describe, expect, test } from "vitest";
import { resolveDaemonVersion } from "../daemon-version.js";
import { BuiltinPluginLoader } from "./builtin/index.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
async function writeTunnelPlugin(options: {
pluginId: string;
providerId: string;
markerFile: string;
}): Promise<string> {
const dir = await mkdtemp(path.join(tmpdir(), `paseo-${options.pluginId}-`));
roots.push(dir);
await writeFile(
path.join(dir, "paseo-plugin.json"),
JSON.stringify({
id: options.pluginId,
requirements: { paseo: `>=${resolveDaemonVersion(import.meta.url)}` },
}),
);
await writeFile(
path.join(dir, "index.server.ts"),
`import { appendFileSync } from "node:fs";
import type { PluginServerContext } from "@getpaseo/plugin/server";
const markerFile = ${JSON.stringify(options.markerFile)};
export default function contribute(server: PluginServerContext) {
return server.registerTunnelProvider({
id: ${JSON.stringify(options.providerId)},
label: "Custom Tunnel",
description: "Subprocess test tunnel provider.",
docsUrl: "https://example.test/docs/tunnel",
async status() {
return { status: "available", detail: "ready-v1" };
},
async open(target, { report, signal }) {
appendFileSync(markerFile, "open:" + target.id + ":" + target.host + ":" + target.port + "\\n");
report({ type: "connecting" });
await new Promise((resolve) => setTimeout(resolve, 20));
if (signal.aborted) {
report({ type: "closed", reason: "aborted-early" });
return;
}
report({
type: "ready",
url: "https://" + (target.slug ?? target.id) + ".custom-tunnel.test",
stability: "ephemeral",
});
await new Promise<void>((resolve) => {
if (signal.aborted) {
resolve();
return;
}
signal.addEventListener("abort", () => resolve(), { once: true });
});
appendFileSync(markerFile, "aborted:" + target.id + "\\n");
report({ type: "closed", reason: "aborted" });
},
});
}
`,
);
return dir;
}
function sendRpc<TResponseType extends SessionOutboundMessage["type"]>(
client: DaemonClient,
message: SessionInboundMessage & { requestId: string },
expectedType: TResponseType,
): Promise<Extract<SessionOutboundMessage, { type: TResponseType }>["payload"]> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
unsubscribe();
reject(new Error(`Timed out waiting for ${expectedType} (${message.requestId})`));
}, 15_000);
const unsubscribe = client.subscribeRawMessages((outbound) => {
if (outbound.type === "rpc_error" && outbound.payload.requestId === message.requestId) {
clearTimeout(timer);
unsubscribe();
const error = new Error(outbound.payload.error) as Error & { code?: string };
error.code = outbound.payload.code;
reject(error);
return;
}
if (
outbound.type === expectedType &&
"payload" in outbound &&
"requestId" in outbound.payload &&
outbound.payload.requestId === message.requestId
) {
clearTimeout(timer);
unsubscribe();
resolve(
outbound.payload as Extract<SessionOutboundMessage, { type: TResponseType }>["payload"],
);
}
});
client.sendSessionMessage(message);
});
}
describe("pluggable tunnel providers E2E", () => {
test("runs a custom tunnel provider in a plugin subprocess, streams lifecycle events, aborts cleanly, and tears down on reload and disable", async () => {
const markerDir = await mkdtemp(path.join(tmpdir(), "paseo-tunnel-markers-"));
roots.push(markerDir);
const markerFile = path.join(markerDir, "events.log");
const daemon = await createTestPaseoDaemon();
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.0",
});
try {
await client.connect();
expect(client.getLastServerInfoMessage()?.features?.tunnelProviders).toBe(true);
await client.patchDaemonConfig({ pluginsEnabled: true });
const pluginDir = await writeTunnelPlugin({
pluginId: "custom-tunnel-plugin",
providerId: "custom-tunnel",
markerFile,
});
await expect(client.installDirectoryPlugin(pluginDir)).resolves.toMatchObject({
id: "custom-tunnel-plugin",
status: "running",
});
// List providers
const providersRes = await sendRpc(
client,
{ type: "tunnel.providers.list.request", requestId: "req-providers" },
"tunnel.providers.list.response",
);
expect(providersRes.providers).toEqual<TunnelProviderInfo[]>([
{
id: "custom-tunnel",
pluginId: "custom-tunnel-plugin",
label: "Custom Tunnel",
description: "Subprocess test tunnel provider.",
docsUrl: "https://example.test/docs/tunnel",
availability: { status: "available", detail: "ready-v1" },
},
]);
// Observe exposures
const observedEvents: TunnelExposure[] = [];
const unsubscribeRaw = client.subscribeRawMessages((message) => {
if (message.type === "tunnel.exposure.changed") {
observedEvents.push(message.payload.exposure);
}
});
const initialList = await sendRpc(
client,
{ type: "tunnel.exposures.list.request", requestId: "req-observe", observe: true },
"tunnel.exposures.list.response",
);
expect(initialList.exposures).toEqual([]);
expect(initialList.subscriptionId).toBeTruthy();
// Open exposure
const opened = await sendRpc(
client,
{
type: "tunnel.exposure.open.request",
requestId: "req-open-1",
id: "exp-mcp",
providerId: "custom-tunnel",
host: "127.0.0.1",
port: 4321,
label: "External MCP",
slug: "mcp",
},
"tunnel.exposure.open.response",
);
expect(opened.exposure).toMatchObject({
id: "exp-mcp",
providerId: "custom-tunnel",
target: { host: "127.0.0.1", port: 4321, label: "External MCP", slug: "mcp" },
state: "ready",
url: "https://mcp.custom-tunnel.test",
stability: "ephemeral",
});
// Close exposure explicitly
const closed = await sendRpc(
client,
{
type: "tunnel.exposure.close.request",
requestId: "req-close-1",
exposureId: "exp-mcp",
},
"tunnel.exposure.close.response",
);
expect(closed).toEqual({
requestId: "req-close-1",
exposureId: "exp-mcp",
closed: true,
});
// Verify full lifecycle event stream: connecting -> ready -> closed
expect(observedEvents.map((entry) => entry.state)).toEqual(["connecting", "ready", "closed"]);
const logAfterClose = await readFile(markerFile, "utf8");
expect(logAfterClose).toContain("open:exp-mcp:127.0.0.1:4321");
expect(logAfterClose).toContain("aborted:exp-mcp");
// Open a second exposure and reload the plugin -> must tear down exposure cleanly
await sendRpc(
client,
{
type: "tunnel.exposure.open.request",
requestId: "req-open-2",
id: "exp-reload",
providerId: "custom-tunnel",
host: "127.0.0.1",
port: 4322,
slug: "svc",
},
"tunnel.exposure.open.response",
);
expect(daemon.daemon.tunnelManager.listExposures().map((e) => e.id)).toEqual(["exp-reload"]);
await client.reloadPlugin("custom-tunnel-plugin");
expect(daemon.daemon.tunnelManager.listExposures()).toEqual([]);
const logAfterReload = await readFile(markerFile, "utf8");
expect(logAfterReload).toContain("aborted:exp-reload");
// Open a third exposure after reload, then disable plugin -> must tear down and unregister provider
await sendRpc(
client,
{
type: "tunnel.exposure.open.request",
requestId: "req-open-3",
id: "exp-disable",
providerId: "custom-tunnel",
host: "127.0.0.1",
port: 4323,
slug: "svc2",
},
"tunnel.exposure.open.response",
);
await client.disablePlugin("custom-tunnel-plugin");
expect(daemon.daemon.tunnelManager.listExposures()).toEqual([]);
expect(
(
await sendRpc(
client,
{ type: "tunnel.providers.list.request", requestId: "req-providers-after" },
"tunnel.providers.list.response",
)
).providers,
).toEqual([]);
const logAfterDisable = await readFile(markerFile, "utf8");
expect(logAfterDisable).toContain("aborted:exp-disable");
unsubscribeRaw();
} finally {
await client.close();
await daemon.close();
}
}, 60_000);
test("enforces tunnel.manage for mutating tunnel RPCs and daemon.read for read RPCs", async () => {
const markerDir = await mkdtemp(path.join(tmpdir(), "paseo-tunnel-auth-"));
roots.push(markerDir);
const markerFile = path.join(markerDir, "events.log");
const daemon = await createTestPaseoDaemon();
const owner = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.0",
});
const reader = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.0",
sessionPermissions: ["daemon.read"],
});
const workspaceOnly = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.0",
sessionPermissions: ["workspace.read"],
});
const tunnelOperator = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.0",
sessionPermissions: ["tunnel.manage"],
});
try {
await owner.connect();
await owner.patchDaemonConfig({ pluginsEnabled: true });
const pluginDir = await writeTunnelPlugin({
pluginId: "auth-tunnel-plugin",
providerId: "auth-tunnel",
markerFile,
});
await owner.installDirectoryPlugin(pluginDir);
await Promise.all([reader.connect(), workspaceOnly.connect(), tunnelOperator.connect()]);
// daemon.read can list providers and exposures, cannot open/close
const readerProviders = await sendRpc(
reader,
{ type: "tunnel.providers.list.request", requestId: "r1" },
"tunnel.providers.list.response",
);
expect(readerProviders.providers.map((p) => p.id)).toEqual(["auth-tunnel"]);
const readerExposures = await sendRpc(
reader,
{ type: "tunnel.exposures.list.request", requestId: "r2" },
"tunnel.exposures.list.response",
);
expect(readerExposures.exposures).toEqual([]);
await expect(
sendRpc(
reader,
{
type: "tunnel.exposure.open.request",
requestId: "r3",
providerId: "auth-tunnel",
host: "127.0.0.1",
port: 5000,
},
"tunnel.exposure.open.response",
),
).rejects.toMatchObject({ code: "access_denied" });
await expect(
sendRpc(
reader,
{
type: "tunnel.exposure.close.request",
requestId: "r4",
exposureId: "exp-1",
},
"tunnel.exposure.close.response",
),
).rejects.toMatchObject({ code: "access_denied" });
// workspace.read is denied on read tunnel RPCs too
await expect(
sendRpc(
workspaceOnly,
{ type: "tunnel.providers.list.request", requestId: "w1" },
"tunnel.providers.list.response",
),
).rejects.toMatchObject({ code: "access_denied" });
// tunnel.manage can list, open, and close
const opened = await sendRpc(
tunnelOperator,
{
type: "tunnel.exposure.open.request",
requestId: "t1",
id: "exp-auth",
providerId: "auth-tunnel",
host: "127.0.0.1",
port: 5001,
},
"tunnel.exposure.open.response",
);
expect(opened.exposure.state).toBe("ready");
const closed = await sendRpc(
tunnelOperator,
{
type: "tunnel.exposure.close.request",
requestId: "t2",
exposureId: "exp-auth",
},
"tunnel.exposure.close.response",
);
expect(closed.closed).toBe(true);
} finally {
await Promise.all([
owner.close(),
reader.close(),
workspaceOnly.close(),
tunnelOperator.close(),
]);
await daemon.close();
}
}, 60_000);
test("boots built-in cloudflared-tunnel and tailscale-funnel plugins cleanly without credentials", async () => {
const daemon = await createTestPaseoDaemon({
pluginsEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, [
"cloudflared-tunnel",
"tailscale-funnel",
]),
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.0",
});
try {
await client.connect();
const res = await sendRpc(
client,
{ type: "tunnel.providers.list.request", requestId: "builtin-1" },
"tunnel.providers.list.response",
);
expect(res.providers.map((provider) => provider.id)).toEqual([
"cloudflared",
"tailscale-funnel",
]);
for (const provider of res.providers) {
expect(["available", "unavailable"]).toContain(provider.availability.status);
}
} finally {
await client.close();
await daemon.close();
}
}, 60_000);
});
+16 -1
View File
@@ -3,6 +3,7 @@ import { type WorkspaceRuntimeStore } from "./workspace-runtime-store/index.js";
import type { AgentMessageBehavior, AgentMessageDelivery } from "./agent/agent-messages/index.js";
import { AgentDirectory, type BackgroundVisibility } from "./agent/directory.js";
import { ConnectedHostSession } from "./connected-hosts/index.js";
import { TunnelSession, type TunnelManager } from "./tunnels/index.js";
import type { ConnectedHosts } from "./connected-hosts/index.js";
import {
createWorkspaceBaseBranchService,
@@ -496,6 +497,7 @@ type AgentMcpTransportFactory = () => Promise<unknown>;
export interface SessionOptions {
connectedHosts?: ConnectedHosts;
tunnelManager?: TunnelManager;
sourceId?: string;
routed?: boolean;
browserToolsBroker?: BrowserToolsBroker | null;
@@ -770,6 +772,7 @@ function resolveAgentSubscriptionSnapshotIds(
export class Session {
private readonly connectedHostSession: ConnectedHostSession | null;
private readonly tunnelSession: TunnelSession | null;
private routed = false;
isRouted(): boolean {
return this.routed;
@@ -998,6 +1001,7 @@ export class Session {
this.sessionId = uuidv4();
this.hostSourceId = hostSource(options);
this.connectedHostSession = createHostSession(options, this);
this.tunnelSession = createTunnelSession(options, this);
this.onMessage = onMessage;
this.onMessageToSource = onMessageToSource
? (source, message) => this.observeSourceSend(() => onMessageToSource(source, message))
@@ -2774,9 +2778,13 @@ export class Session {
return undefined;
}
private dispatchDomainSessionMessage(msg: SessionInboundMessage): Promise<void> | undefined {
return this.connectedHostSession?.dispatch(msg) ?? this.tunnelSession?.dispatch(msg);
}
private async dispatchInboundMessage(msg: SessionInboundMessage, source?: object): Promise<void> {
const promise =
this.connectedHostSession?.dispatch(msg) ??
this.dispatchDomainSessionMessage(msg) ??
this.dispatchSubscriptionMessage(msg, source) ??
this.dispatchVoiceAndControlMessage(msg) ??
this.dispatchAgentObservationMessage(msg, source) ??
@@ -9897,6 +9905,13 @@ function createHostSession(options: SessionOptions, session: Session): Connected
);
}
function createTunnelSession(options: SessionOptions, session: Session): TunnelSession | null {
if (!options.tunnelManager) return null;
return new TunnelSession(options.tunnelManager, session.delivery, (message) =>
session.publish(message),
);
}
function hostSource(options: SessionOptions): string {
return options.sourceId ?? "owner";
}
@@ -0,0 +1,10 @@
export {
TunnelError,
TunnelManager,
type ExposeTunnelInput,
type RegisteredTunnelProvider,
type TunnelErrorCode,
type TunnelHandle,
type TunnelManagerEvent,
} from "./manager.js";
export { TunnelSession } from "./session.js";
@@ -0,0 +1,211 @@
import { describe, expect, it } from "vitest";
import type { TunnelEvent, TunnelProviderStatus, TunnelTarget } from "@getpaseo/plugin/server";
import { TunnelError, TunnelManager, type TunnelManagerEvent } from "./manager.js";
function createFakeProvider(options: {
id: string;
pluginId: string;
label?: string;
status?: () => Promise<TunnelProviderStatus>;
onOpen?: (
exposureId: string,
target: TunnelTarget,
callbacks: {
onEvent(event: TunnelEvent): void;
onClosed(error?: string): void;
},
) => { close(): Promise<void> };
}) {
const closedExposures: string[] = [];
const provider = {
id: options.id,
pluginId: options.pluginId,
label: options.label ?? options.id,
status: options.status ?? (async () => ({ status: "available" as const, detail: "ready" })),
open(
exposureId: string,
target: TunnelTarget,
callbacks: {
onEvent(event: TunnelEvent): void;
onClosed(error?: string): void;
},
) {
if (options.onOpen) return options.onOpen(exposureId, target, callbacks);
queueMicrotask(() => {
callbacks.onEvent({ type: "connecting" });
callbacks.onEvent({
type: "ready",
url: `https://${target.slug ?? exposureId}.example.test`,
stability: "ephemeral",
});
});
return {
async close() {
closedExposures.push(exposureId);
callbacks.onEvent({ type: "closed", reason: "requested" });
callbacks.onClosed();
},
};
},
};
return { provider, closedExposures };
}
describe("TunnelManager", () => {
it("lists providers with probed availability and isolates per-provider status failures", async () => {
const manager = new TunnelManager();
manager.registerProvider(
createFakeProvider({
id: "alpha",
pluginId: "plugin-a",
label: "Alpha",
status: async () => ({ status: "available", detail: "v1.2.3" }),
}).provider,
);
manager.registerProvider(
createFakeProvider({
id: "beta",
pluginId: "plugin-b",
label: "Beta",
status: async () => {
throw new Error("CLI probe crashed");
},
}).provider,
);
const providers = await manager.listProviders();
expect(providers).toEqual([
{
id: "alpha",
pluginId: "plugin-a",
label: "Alpha",
availability: { status: "available", detail: "v1.2.3" },
},
{
id: "beta",
pluginId: "plugin-b",
label: "Beta",
availability: { status: "unavailable", reason: "CLI probe crashed" },
},
]);
});
it("tracks lifecycle transitions from connecting to ready to closed and removes closed exposures", async () => {
const manager = new TunnelManager();
const { provider, closedExposures } = createFakeProvider({
id: "demo",
pluginId: "demo-plugin",
});
manager.registerProvider(provider);
const events: TunnelManagerEvent[] = [];
const unsubscribe = manager.subscribe((event) => events.push(event));
const exposure = await manager.expose({
id: "exp-1",
providerId: "demo",
host: "127.0.0.1",
port: 4321,
label: "External MCP",
slug: "mcp",
});
expect(exposure.state).toBe("ready");
expect(exposure.url).toBe("https://mcp.example.test");
expect(exposure.stability).toBe("ephemeral");
expect(manager.listExposures()).toHaveLength(1);
await expect(manager.close("exp-1")).resolves.toBe(true);
await expect(manager.close("exp-1")).resolves.toBe(false);
expect(closedExposures).toEqual(["exp-1"]);
expect(manager.listExposures()).toEqual([]);
const states = events
.filter((event) => event.type === "exposure.changed")
.map((event) => event.exposure.state);
expect(states).toEqual(["connecting", "ready", "closed"]);
unsubscribe();
});
it("tears down active exposures when the owning plugin is unregistered or on closeAll", async () => {
const manager = new TunnelManager();
const first = createFakeProvider({ id: "p1", pluginId: "plugin-1" });
const second = createFakeProvider({ id: "p2", pluginId: "plugin-2" });
manager.registerProvider(first.provider);
manager.registerProvider(second.provider);
await manager.expose({ id: "e1", providerId: "p1", host: "127.0.0.1", port: 3001 });
await manager.expose({ id: "e2", providerId: "p2", host: "127.0.0.1", port: 3002 });
await manager.unregisterPlugin("plugin-1");
expect(first.closedExposures).toEqual(["e1"]);
expect(manager.listExposures().map((entry) => entry.id)).toEqual(["e2"]);
await manager.closeAll();
expect(second.closedExposures).toEqual(["e2"]);
expect(manager.listExposures()).toEqual([]);
});
it("rejects expose when provider fails before ready and leaves no leaked exposure", async () => {
const manager = new TunnelManager();
manager.registerProvider(
createFakeProvider({
id: "failing",
pluginId: "failing-plugin",
onOpen(_exposureId, _target, callbacks) {
queueMicrotask(() => {
callbacks.onClosed("All 3 Funnel ports are in use");
});
return { close: async () => undefined };
},
}).provider,
);
await expect(
manager.expose({ providerId: "failing", host: "127.0.0.1", port: 8080 }),
).rejects.toMatchObject({
code: "open_failed",
message: "All 3 Funnel ports are in use",
});
expect(manager.listExposures()).toEqual([]);
});
it("rejects duplicate provider IDs and invalid targets", async () => {
const manager = new TunnelManager();
manager.registerProvider(createFakeProvider({ id: "dup", pluginId: "p1" }).provider);
expect(() =>
manager.registerProvider(createFakeProvider({ id: "dup", pluginId: "p2" }).provider),
).toThrow(TunnelError);
await expect(
manager.expose({ providerId: "missing", host: "127.0.0.1", port: 8080 }),
).rejects.toMatchObject({ code: "provider_not_found" });
await expect(
manager.expose({ providerId: "dup", host: "127.0.0.1", port: 0 }),
).rejects.toMatchObject({ code: "invalid_target" });
for (const badHost of [
"",
" ",
"127.0.0.1:8080",
"localhost:3000",
"http://127.0.0.1",
"127.0.0.1/path",
"127.0.0.1?q=1",
"127.0.0.1#frag",
"user@127.0.0.1",
"local host",
"[::1]:8080",
"[not-an-ip]",
]) {
await expect(
manager.expose({ providerId: "dup", host: badHost, port: 8080 }),
).rejects.toMatchObject({ code: "invalid_target" });
}
const ipv6 = await manager.expose({ id: "exp-v6", providerId: "dup", host: "::1", port: 8080 });
expect(ipv6.target.host).toBe("::1");
await manager.close("exp-v6");
});
});
@@ -0,0 +1,518 @@
import { randomUUID } from "node:crypto";
import { isIP } from "node:net";
import type {
TunnelEvent,
TunnelProviderStatus,
TunnelStability,
TunnelTarget,
} from "@getpaseo/plugin/server";
import type { TunnelExposure, TunnelProviderInfo } from "@getpaseo/protocol/tunnels";
import type pino from "pino";
const DEFAULT_READY_TIMEOUT_MS = 30_000;
export type TunnelErrorCode =
| "provider_not_found"
| "provider_duplicate"
| "exposure_duplicate"
| "invalid_target"
| "open_failed"
| "open_timeout"
| "aborted";
export class TunnelError extends Error {
constructor(
readonly code: TunnelErrorCode,
message: string,
options?: { cause?: unknown },
) {
super(message, options);
this.name = "TunnelError";
}
}
export interface TunnelHandle {
close(): Promise<void>;
}
export interface RegisteredTunnelProvider {
readonly id: string;
readonly pluginId: string;
readonly label: string;
readonly description?: string;
readonly docsUrl?: string;
status(options?: { signal?: AbortSignal }): Promise<TunnelProviderStatus>;
open(
exposureId: string,
target: TunnelTarget,
callbacks: {
onEvent(event: TunnelEvent): void;
onClosed(error?: string): void;
},
): TunnelHandle;
}
export interface ExposeTunnelInput {
id?: string;
providerId: string;
host: string;
port: number;
label?: string;
slug?: string;
waitForReady?: boolean;
readyTimeoutMs?: number;
signal?: AbortSignal;
}
export type TunnelManagerEvent =
| { type: "exposure.changed"; exposure: TunnelExposure }
| { type: "providers.changed" };
interface ActiveExposure {
snapshot: TunnelExposure;
handle: TunnelHandle | null;
closed: boolean;
closing: Promise<void> | null;
lastClosedReason: string | null;
resolveReady: (exposure: TunnelExposure) => void;
rejectReady: (error: Error) => void;
readySettled: boolean;
}
function cloneExposure(exposure: TunnelExposure): TunnelExposure {
return {
...exposure,
target: { ...exposure.target },
};
}
const HOSTNAME_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i;
function isValidTargetHost(host: string): boolean {
if (!host || host.length > 253) return false;
if (/[\s/\\?#@]/.test(host)) return false;
if (host.startsWith("[") || host.endsWith("]")) {
if (!host.startsWith("[") || !host.endsWith("]")) return false;
return isIP(host.slice(1, -1)) === 6;
}
if (isIP(host) !== 0) return true;
if (host.includes(":")) return false;
return HOSTNAME_PATTERN.test(host);
}
function isHttpUrl(value: string): boolean {
try {
const parsed = new URL(value);
return parsed.protocol === "https:" || parsed.protocol === "http:";
} catch {
return false;
}
}
function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export class TunnelManager {
private readonly providers = new Map<string, RegisteredTunnelProvider>();
private readonly exposures = new Map<string, ActiveExposure>();
private readonly listeners = new Set<(event: TunnelManagerEvent) => void>();
private readonly logger: pino.Logger | null;
private readonly now: () => Date;
constructor(options?: { logger?: pino.Logger; now?: () => Date }) {
this.logger = options?.logger?.child({ module: "tunnels" }) ?? null;
this.now = options?.now ?? (() => new Date());
}
subscribe(listener: (event: TunnelManagerEvent) => void): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
registerProvider(provider: RegisteredTunnelProvider): void {
const id = provider.id.trim();
if (!id) {
throw new TunnelError("invalid_target", "Tunnel provider ID is required");
}
if (this.providers.has(id)) {
throw new TunnelError("provider_duplicate", `Tunnel provider "${id}" is already registered`);
}
this.providers.set(id, { ...provider, id });
this.emit({ type: "providers.changed" });
}
async unregisterProvider(providerId: string): Promise<void> {
if (!this.providers.delete(providerId)) return;
const affected = [...this.exposures.values()]
.filter((entry) => entry.snapshot.providerId === providerId)
.map((entry) => entry.snapshot.id);
await Promise.allSettled(affected.map((id) => this.close(id)));
this.emit({ type: "providers.changed" });
}
async unregisterPlugin(pluginId: string): Promise<void> {
const owned = [...this.providers.values()]
.filter((provider) => provider.pluginId === pluginId)
.map((provider) => provider.id);
if (owned.length === 0) return;
for (const id of owned) {
this.providers.delete(id);
}
const ownedSet = new Set(owned);
const affected = [...this.exposures.values()]
.filter((entry) => ownedSet.has(entry.snapshot.providerId))
.map((entry) => entry.snapshot.id);
await Promise.allSettled(affected.map((id) => this.close(id)));
this.emit({ type: "providers.changed" });
}
async syncPluginProviders(
pluginId: string,
nextProviders: readonly RegisteredTunnelProvider[],
): Promise<void> {
const currentOwned = [...this.providers.values()].filter(
(provider) => provider.pluginId === pluginId,
);
const nextIds = new Set(nextProviders.map((provider) => provider.id));
const removedIds = currentOwned.map((provider) => provider.id).filter((id) => !nextIds.has(id));
for (const id of removedIds) {
this.providers.delete(id);
}
for (const next of nextProviders) {
const existing = this.providers.get(next.id);
if (existing && existing.pluginId !== pluginId) {
this.logger?.warn(
{ pluginId, providerId: next.id, ownerPluginId: existing.pluginId },
"Ignoring duplicate tunnel provider ID from another plugin",
);
continue;
}
this.providers.set(next.id, next);
}
if (removedIds.length > 0) {
const removedSet = new Set(removedIds);
const affected = [...this.exposures.values()]
.filter((entry) => removedSet.has(entry.snapshot.providerId))
.map((entry) => entry.snapshot.id);
await Promise.allSettled(affected.map((id) => this.close(id)));
}
this.emit({ type: "providers.changed" });
}
async listProviders(options?: { signal?: AbortSignal }): Promise<TunnelProviderInfo[]> {
const registered = [...this.providers.values()].sort((left, right) =>
left.id.localeCompare(right.id),
);
return Promise.all(
registered.map(async (provider): Promise<TunnelProviderInfo> => {
let availability: TunnelProviderStatus;
try {
availability = await provider.status({ signal: options?.signal });
} catch (error) {
availability = {
status: "unavailable",
reason: describeError(error),
};
}
const info: TunnelProviderInfo = {
id: provider.id,
pluginId: provider.pluginId,
label: provider.label,
availability,
};
if (provider.description !== undefined) info.description = provider.description;
if (provider.docsUrl !== undefined) info.docsUrl = provider.docsUrl;
return info;
}),
);
}
listExposures(): TunnelExposure[] {
return [...this.exposures.values()]
.map((entry) => cloneExposure(entry.snapshot))
.sort(
(left, right) =>
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
);
}
getExposure(exposureId: string): TunnelExposure | null {
const entry = this.exposures.get(exposureId);
return entry ? cloneExposure(entry.snapshot) : null;
}
async expose(input: ExposeTunnelInput): Promise<TunnelExposure> {
const providerId = input.providerId.trim();
const provider = this.providers.get(providerId);
if (!provider) {
throw new TunnelError("provider_not_found", `Unknown tunnel provider: ${providerId}`);
}
const host = input.host.trim();
if (!isValidTargetHost(host)) {
throw new TunnelError(
"invalid_target",
`Tunnel target host must be a valid hostname or IP address (got "${input.host}")`,
);
}
if (!Number.isInteger(input.port) || input.port < 1 || input.port > 65535) {
throw new TunnelError(
"invalid_target",
`Tunnel target port must be an integer between 1 and 65535 (got ${input.port})`,
);
}
const id = input.id !== undefined ? input.id.trim() : `tun_${randomUUID()}`;
if (!id) {
throw new TunnelError("invalid_target", "Tunnel exposure ID must not be empty");
}
if (this.exposures.has(id)) {
throw new TunnelError("exposure_duplicate", `Tunnel exposure "${id}" is already active`);
}
if (input.signal?.aborted) {
throw new TunnelError("aborted", "Tunnel exposure request was aborted");
}
const timestamp = this.now().toISOString();
const target: TunnelTarget = {
id,
host,
port: input.port,
...(input.label !== undefined ? { label: input.label } : {}),
...(input.slug !== undefined ? { slug: input.slug } : {}),
};
let resolveReady!: (exposure: TunnelExposure) => void;
let rejectReady!: (error: Error) => void;
const readyPromise = new Promise<TunnelExposure>((resolve, reject) => {
resolveReady = resolve;
rejectReady = reject;
});
// Prevent unhandled rejections if waitForReady is false or callers drop out early.
void readyPromise.catch(() => undefined);
const entry: ActiveExposure = {
snapshot: {
id,
providerId: provider.id,
target: {
host,
port: input.port,
...(input.label !== undefined ? { label: input.label } : {}),
...(input.slug !== undefined ? { slug: input.slug } : {}),
},
state: "connecting",
url: null,
stability: null,
detail: null,
error: null,
createdAt: timestamp,
updatedAt: timestamp,
},
handle: null,
closed: false,
closing: null,
lastClosedReason: null,
resolveReady,
rejectReady,
readySettled: false,
};
this.exposures.set(id, entry);
this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) });
try {
entry.handle = provider.open(id, target, {
onEvent: (event) => this.handleProviderEvent(entry, event),
onClosed: (error) => this.handleProviderClosed(entry, error),
});
} catch (error) {
const message = describeError(error);
this.finalizeExposure(entry, { error: message });
throw new TunnelError("open_failed", message, { cause: error });
}
if (input.waitForReady === false) {
return cloneExposure(entry.snapshot);
}
const timeoutMs = input.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
return await new Promise<TunnelExposure>((resolve, reject) => {
const cleanup = () => {
if (timer) clearTimeout(timer);
input.signal?.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
void this.close(id);
reject(new TunnelError("aborted", "Tunnel exposure request was aborted"));
};
const timer = setTimeout(() => {
cleanup();
void this.close(id);
reject(
new TunnelError(
"open_timeout",
`Timed out waiting for tunnel provider "${provider.id}" to become ready`,
),
);
}, timeoutMs);
input.signal?.addEventListener("abort", onAbort, { once: true });
readyPromise.then(
(exposure) => {
cleanup();
resolve(exposure);
return undefined;
},
(error) => {
cleanup();
reject(error);
return undefined;
},
);
});
}
async close(exposureId: string): Promise<boolean> {
const entry = this.exposures.get(exposureId);
if (!entry) return false;
if (entry.closing) {
await entry.closing;
return true;
}
const closing = (async () => {
try {
await entry.handle?.close();
} catch (error) {
this.logger?.warn({ err: error, exposureId }, "Tunnel handle close failed");
} finally {
this.finalizeExposure(entry, {});
}
})();
entry.closing = closing;
await closing;
return true;
}
async closeAll(): Promise<void> {
const ids = [...this.exposures.keys()];
await Promise.allSettled(ids.map((id) => this.close(id)));
}
private handleProviderEvent(entry: ActiveExposure, event: TunnelEvent): void {
if (entry.closed) return;
const timestamp = this.now().toISOString();
if (event.type === "connecting") {
const detail = event.detail ?? null;
if (entry.snapshot.state === "connecting" && entry.snapshot.detail === detail) return;
entry.snapshot = {
...entry.snapshot,
state: "connecting",
detail,
updatedAt: timestamp,
};
this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) });
return;
}
if (event.type === "ready") {
if (!isHttpUrl(event.url)) {
const message = `Tunnel provider "${entry.snapshot.providerId}" reported invalid URL: ${event.url}`;
this.finalizeExposure(entry, { error: message });
void entry.handle?.close().catch(() => undefined);
return;
}
const stability: TunnelStability | null = event.stability ?? null;
entry.snapshot = {
...entry.snapshot,
state: "ready",
url: event.url,
stability,
detail: event.detail ?? null,
error: null,
updatedAt: timestamp,
};
const snapshot = cloneExposure(entry.snapshot);
this.emit({ type: "exposure.changed", exposure: snapshot });
if (!entry.readySettled) {
entry.readySettled = true;
entry.resolveReady(snapshot);
}
return;
}
if (event.type === "reconnecting") {
entry.snapshot = {
...entry.snapshot,
state: "reconnecting",
detail: event.reason ?? null,
updatedAt: timestamp,
};
this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) });
return;
}
if (event.type === "error") {
entry.snapshot = {
...entry.snapshot,
state: "error",
error: event.message,
updatedAt: timestamp,
};
this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) });
if (event.recoverable !== true && !entry.readySettled) {
entry.readySettled = true;
entry.rejectReady(new TunnelError("open_failed", event.message));
}
return;
}
if (event.type === "closed") {
entry.lastClosedReason = event.reason ?? null;
this.finalizeExposure(entry, { reason: event.reason });
}
}
private handleProviderClosed(entry: ActiveExposure, error?: string): void {
this.finalizeExposure(entry, { error });
}
private finalizeExposure(
entry: ActiveExposure,
options: { reason?: string; error?: string },
): void {
if (entry.closed) return;
entry.closed = true;
this.exposures.delete(entry.snapshot.id);
const error = options.error ?? entry.snapshot.error;
const detail = options.reason ?? entry.lastClosedReason ?? entry.snapshot.detail;
entry.snapshot = {
...entry.snapshot,
state: "closed",
detail,
error,
updatedAt: this.now().toISOString(),
};
this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) });
if (!entry.readySettled) {
entry.readySettled = true;
entry.rejectReady(
new TunnelError("open_failed", error ?? "Tunnel closed before becoming ready"),
);
}
}
private emit(event: TunnelManagerEvent): void {
for (const listener of this.listeners) {
try {
listener(event);
} catch (error) {
this.logger?.warn({ err: error }, "Tunnel manager listener failed");
}
}
}
}
@@ -0,0 +1,129 @@
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import type { SessionDelivery } from "../session/owned-subscriptions/index.js";
import { TunnelError, type TunnelManager } from "./manager.js";
type TunnelRequest<T extends SessionInboundMessage["type"]> = Extract<
SessionInboundMessage,
{ type: T }
>;
/** Adapts daemon TunnelManager capabilities to source-owned session delivery. */
export class TunnelSession {
constructor(
private readonly tunnels: Pick<
TunnelManager,
"listProviders" | "listExposures" | "expose" | "close" | "subscribe"
>,
private readonly delivery: SessionDelivery,
private readonly emit: (message: SessionOutboundMessage) => void,
) {}
dispatch(message: SessionInboundMessage): Promise<void> | undefined {
if (!message.type.startsWith("tunnel.")) return;
return this.handle(message);
}
private async handle(message: SessionInboundMessage): Promise<void> {
try {
await this.execute(message);
} catch (error) {
this.fail(message, error);
}
}
private fail(message: SessionInboundMessage, error: unknown): void {
if (!("requestId" in message) || !message.requestId) return;
const code = error instanceof TunnelError ? error.code : "tunnel_error";
const text = error instanceof Error ? error.message : String(error);
this.emit({
type: "rpc_error",
payload: {
requestId: message.requestId,
requestType: message.type,
code,
error: text,
},
});
}
private async execute(message: SessionInboundMessage): Promise<void> {
switch (message.type) {
case "tunnel.providers.list.request":
this.emit({
type: "tunnel.providers.list.response",
payload: {
requestId: message.requestId,
providers: await this.tunnels.listProviders({ signal: this.delivery.requestSignal }),
},
});
return;
case "tunnel.exposures.list.request":
return this.listExposures(message);
case "tunnel.exposure.open.request": {
const exposure = await this.tunnels.expose({
id: message.id,
providerId: message.providerId,
host: message.host,
port: message.port,
label: message.label,
slug: message.slug,
signal: this.delivery.requestSignal,
});
this.emit({
type: "tunnel.exposure.open.response",
payload: { requestId: message.requestId, exposure },
});
return;
}
case "tunnel.exposure.close.request": {
const closed = await this.tunnels.close(message.exposureId);
this.emit({
type: "tunnel.exposure.close.response",
payload: {
requestId: message.requestId,
exposureId: message.exposureId,
closed,
},
});
return;
}
}
}
private async listExposures(
message: TunnelRequest<"tunnel.exposures.list.request">,
): Promise<void> {
if (!message.observe) {
this.emit({
type: "tunnel.exposures.list.response",
payload: {
requestId: message.requestId,
exposures: this.tunnels.listExposures(),
},
});
return;
}
let stop = () => {};
const owner = this.delivery.begin("tunnels", undefined, () => stop());
try {
stop = this.tunnels.subscribe((event) => {
if (event.type !== "exposure.changed") return;
owner.emit({
type: "tunnel.exposure.changed",
payload: { subscriptionId: owner.id, exposure: event.exposure },
});
});
this.emit({
type: "tunnel.exposures.list.response",
payload: {
requestId: message.requestId,
subscriptionId: owner.id,
exposures: this.tunnels.listExposures(),
},
});
} catch (error) {
await owner.release();
throw error;
}
}
}
@@ -15,6 +15,7 @@ import { createToolHosts } from "./agent/host-operations/index.js";
import { HOST_ROUTE_OPCODE } from "@getpaseo/protocol/binary-frames/index";
import { DaemonLinkEndpoint, VirtualHostSocket } from "./connected-hosts/index.js";
import { ConnectedHosts } from "./connected-hosts/index.js";
import type { TunnelManager } from "./tunnels/index.js";
import { stat } from "node:fs/promises";
import {
createWorkspaceBaseBranchService,
@@ -680,6 +681,7 @@ export class VoiceAssistantWebSocketServer {
private readonly advertiseRelayConfig: boolean;
private readonly directorySync = new DirectorySyncService();
private readonly pluginRuntime: SessionOptions["pluginRuntime"];
private readonly tunnelManager: TunnelManager | null;
private readonly orchestrationSkills: SessionOptions["orchestrationSkills"];
private async validateCompletedCreation(snapshot: CreationSnapshot): Promise<void> {
@@ -750,6 +752,7 @@ export class VoiceAssistantWebSocketServer {
workspaceLabelService?: WorkspaceLabelService,
workspaceArchiveOperations?: WorkspaceArchiveOperations,
pushNotifications?: PushNotifications,
tunnelManager?: TunnelManager | null,
) {
this.logger = logger.child({ module: "websocket-server" });
this.workspaceSetupRuntime = workspaceSetupRuntime;
@@ -767,6 +770,7 @@ export class VoiceAssistantWebSocketServer {
this.browserToolsBroker = browserToolsBroker ?? null;
this.hubRelationships = hubRelationships ?? null;
this.pluginRuntime = pluginRuntime;
this.tunnelManager = tunnelManager ?? null;
this.orchestrationSkills = orchestrationSkills;
this.agentManager = agentManager;
this.agentStorage = agentStorage;
@@ -1725,6 +1729,7 @@ export class VoiceAssistantWebSocketServer {
private createSocketSession(options: SocketSessionOptions): Session {
return new Session({
connectedHosts: this.connectedHosts,
tunnelManager: this.tunnelManager ?? undefined,
getSourceLocalEndpoint: (source) => this.socketLocalEndpoints.get(source),
getConnectedHostBufferedAmount: () => {
let total = 0;
@@ -2208,6 +2213,8 @@ export class VoiceAssistantWebSocketServer {
pluginSubscriptions: true,
// COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01.
pluginNotifications: true,
// COMPAT(tunnelProviders): added in v0.18.0, remove gate after 2027-06-01.
...(this.tunnelManager ? { tunnelProviders: true } : {}),
// COMPAT(skillManagement): added in v0.4.0, remove gate after 2027-08-16.
skillManagement: true,
// COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/website",
"version": "0.18.0",
"version": "0.17.6",
"private": true,
"type": "module",
"scripts": {
+15
View File
@@ -0,0 +1,15 @@
# Custom tunnel provider example
Registers a tunnel provider with `server.registerTunnelProvider()`.
## What it does
- Probes the local CLI in `status()` and returns `available` or `unavailable` with install guidance.
- Spawns the tunnel process in `open(target, { report, signal })`, parses the public HTTPS URL, and reports `connecting`, `ready`, and `closed` events.
- Terminates the child process cleanly when `signal` aborts.
## Install
```bash
paseo plugin install /absolute/path/to/plugin-examples/tunnel-provider
```
@@ -0,0 +1,6 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import { createCustomTunnelProvider } from "./server/tunnel";
export default function contribute(server: PluginServerContext) {
return server.registerTunnelProvider(createCustomTunnelProvider());
}
@@ -0,0 +1,6 @@
{
"id": "tunnel-provider",
"name": "Custom tunnel provider",
"description": "Expose local HTTP endpoints through a custom tunnel binary.",
"requirements": { "paseo": ">=0.18.0-beta.1" }
}
@@ -0,0 +1,85 @@
import {
execCommand,
spawnProcess,
terminateProcess,
type TunnelProviderRegistration,
} from "@getpaseo/plugin/server";
const URL_PATTERN = /https:\/\/[a-z0-9.-]+/i;
function formatHostForUrl(host: string): string {
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
}
export function createCustomTunnelProvider(): TunnelProviderRegistration {
const binary = process.env.CUSTOM_TUNNEL_BIN || "custom-tunnel";
return {
id: "custom-tunnel",
label: "Custom Tunnel",
description: "Expose a local HTTP host and port through a custom CLI.",
docsUrl: "https://example.com/docs/custom-tunnel",
async status({ signal }) {
try {
const { stdout } = await execCommand(binary, ["--version"], { signal, timeout: 5_000 });
return { status: "available", detail: stdout.trim() || undefined };
} catch {
return {
status: "unavailable",
reason: `${binary} is not installed or not on PATH.`,
installUrl: "https://example.com/install",
fixHint: `Install ${binary} or set CUSTOM_TUNNEL_BIN in the daemon environment.`,
};
}
},
async open(target, { report, signal }) {
report({ type: "connecting" });
const child = spawnProcess(
binary,
["http", `${formatHostForUrl(target.host)}:${target.port}`],
{
stdio: "pipe",
},
);
let ready = false;
const onOutput = (chunk: Buffer | string) => {
if (ready || signal.aborted) return;
const match = URL_PATTERN.exec(String(chunk));
if (!match) return;
ready = true;
report({ type: "ready", url: match[0], stability: "ephemeral" });
};
child.stdout.on("data", onOutput);
child.stderr.on("data", onOutput);
const onAbort = () => {
void terminateProcess(child, "SIGTERM").catch(() => undefined);
};
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) onAbort();
try {
const code = await new Promise<number | null>((resolve, reject) => {
child.once("error", reject);
child.once("close", (exitCode) => resolve(exitCode));
});
if (signal.aborted) {
report({ type: "closed", reason: "aborted" });
return;
}
if (!ready || (code !== null && code !== 0)) {
throw new Error(`${binary} exited with code ${code ?? "null"}`);
}
report({ type: "closed" });
} finally {
signal.removeEventListener("abort", onAbort);
}
},
};
}
@@ -162,64 +162,6 @@ describe("claude usage source", () => {
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
});
it.each([false, true])("reports USD extra usage with rolling windows %j", async (hasWindows) => {
writeClaudeCredentials(claudeHome, "at_valid");
fetchApi = mockFetch(
new Map([
[
"https://api.anthropic.com/api/oauth/usage",
() =>
jsonResponse({
...(hasWindows ? makeClaudeResponse() : {}),
extra_usage: {
is_enabled: true,
monthly_limit: 5000,
used_credits: 1250,
currency: "USD",
},
}),
],
]),
);
const claude = findProvider(await service().listUsage(), "claude");
expect(claude.balances).toEqual([
expect.objectContaining({
id: "extra_usage_monthly",
used: 12.5,
remaining: 37.5,
limit: 50,
unit: "usd",
}),
]);
expect(claude.details).toContainEqual(
expect.objectContaining({ id: "extra_usage", value: "Enabled" }),
);
});
it.each(["EUR", null, undefined])(
"does not report extra usage balances for currency %j",
async (currency) => {
writeClaudeCredentials(claudeHome, "at_valid");
fetchApi = mockFetch(
new Map([
[
"https://api.anthropic.com/api/oauth/usage",
() =>
jsonResponse({
...makeClaudeResponse(),
extra_usage: { monthly_limit: 5000, used_credits: 1250, currency },
}),
],
]),
);
const claude = findProvider(await service().listUsage(), "claude");
expect(claude.balances).toEqual([]);
},
);
it("accepts a null Claude resets_at when a window has no scheduled reset", async () => {
writeClaudeCredentials(claudeHome, "at_valid");
+4 -28
View File
@@ -68,9 +68,6 @@ const ClaudeUsageResponseSchema = z.object({
extra_usage: z
.object({
is_enabled: z.boolean().optional(),
monthly_limit: ApiNumberSchema.nullish(),
used_credits: ApiNumberSchema.nullish(),
currency: z.string().nullish(),
})
.nullish(),
});
@@ -501,26 +498,6 @@ function toCredentialRecord(credentials: ClaudeCredentials): ClaudeCredentialRec
: null;
}
function extraUsageBalances(extraUsage: ClaudeUsageResponse["extra_usage"]) {
if (extraUsage?.currency?.toUpperCase() !== "USD") return [];
const used = extraUsage.used_credits == null ? undefined : extraUsage.used_credits / 100;
const limit = extraUsage.monthly_limit == null ? undefined : extraUsage.monthly_limit / 100;
if (used == null && limit == null) return [];
return [
{
id: "extra_usage_monthly",
label: "Extra usage",
used,
remaining: used != null && limit != null ? Math.max(0, limit - used) : undefined,
limit,
unit: "usd" as const,
tone: toneFromUsedPct(
used != null && limit != null && limit > 0 ? (used / limit) * 100 : null,
),
},
];
}
export async function fetchUsage(
input: UsageInput,
fetchApi: typeof fetch = fetch,
@@ -622,21 +599,20 @@ export async function fetchUsage(
}
const details: UsageDetail[] = [];
const extraUsage = resp.extra_usage;
if (extraUsage?.is_enabled !== undefined) {
const extraUsageEnabled = resp.extra_usage?.is_enabled;
if (extraUsageEnabled !== undefined) {
details.push({
id: "extra_usage",
label: "Extra usage",
value: extraUsage.is_enabled ? "Enabled" : "Disabled",
value: extraUsageEnabled ? "Enabled" : "Disabled",
});
}
const balances = extraUsageBalances(extraUsage);
return {
status: "available",
planLabel: plan ?? undefined,
windows,
balances,
balances: [],
details,
};
}
@@ -0,0 +1,14 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import { createCloudflaredTunnelProvider } from "./server/cloudflared.js";
import { cloudflaredSettings, type CloudflaredSettings } from "./shared/settings.js";
export default function contribute(server: PluginServerContext) {
const settings = server.registerSettings(cloudflaredSettings);
const readSettings = async (): Promise<CloudflaredSettings> => {
const state = await settings.read();
return state.status === "ready" ? state.values : {};
};
return server.registerTunnelProvider(createCloudflaredTunnelProvider({ readSettings }));
}
@@ -0,0 +1 @@
{ "id": "cloudflared-tunnel", "requirements": { "paseo": ">=0.17.6" } }
@@ -0,0 +1,210 @@
import {
execCommand,
spawnProcess,
terminateProcess,
type TunnelProviderRegistration,
type TunnelProviderStatus,
} from "@getpaseo/plugin/server";
import type { CloudflaredSettings } from "../shared/settings.js";
const CLOUDFLARED_INSTALL_URL =
"https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/";
const CLOUDFLARED_DOCS_URL =
"https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/";
// api.trycloudflare.com is the provisioning endpoint. It appears in errors, never as a tunnel URL.
const QUICK_TUNNEL_URL_PATTERN = /https:\/\/(?!api\.)[a-z0-9-]+\.trycloudflare\.com/i;
const FORCE_KILL_DELAY_MS = 2_000;
export interface CloudflaredProviderOptions {
readSettings?: () => Promise<CloudflaredSettings>;
env?: NodeJS.ProcessEnv;
}
function formatHostForUrl(host: string): string {
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
}
function firstLine(text: string): string | undefined {
const line = text
.split(/\r?\n/)
.map((entry) => entry.trim())
.find((entry) => entry.length > 0);
return line;
}
// On Windows a bare name that is not on PATH runs through cmd.exe, which exits 9009 for an
// unknown command instead of failing the spawn with ENOENT.
const WINDOWS_COMMAND_NOT_FOUND_EXIT_CODE = 9009;
function isNotFoundError(error: unknown): boolean {
if (typeof error !== "object" || error === null || !("code" in error)) return false;
if (error.code === "ENOENT" || error.code === "ENOTDIR") return true;
return process.platform === "win32" && error.code === WINDOWS_COMMAND_NOT_FOUND_EXIT_CODE;
}
export function createCloudflaredTunnelProvider(
options: CloudflaredProviderOptions = {},
): TunnelProviderRegistration {
const readSettings: () => Promise<CloudflaredSettings> =
options.readSettings ?? (async () => ({}));
const env = options.env;
async function resolveBinary(): Promise<string> {
const values = await readSettings();
return values.binaryPath?.trim() || "cloudflared";
}
return {
id: "cloudflared",
label: "Cloudflare Tunnel",
description: "Expose local HTTP targets with Cloudflare quick tunnels.",
docsUrl: CLOUDFLARED_DOCS_URL,
async status({ signal }): Promise<TunnelProviderStatus> {
const binary = await resolveBinary();
try {
const { stdout, stderr } = await execCommand(binary, ["--version"], {
env,
signal,
timeout: 5_000,
});
const version = firstLine(stdout) ?? firstLine(stderr);
return {
status: "available",
detail: version ? `${version} (quick tunnel)` : "quick tunnel",
};
} catch (error) {
if (isNotFoundError(error)) {
return {
status: "unavailable",
reason: `${binary} is not installed or not on PATH.`,
installUrl: CLOUDFLARED_INSTALL_URL,
fixHint: "Install cloudflared and make sure it is available on PATH.",
};
}
return {
status: "unavailable",
reason: `Failed to query ${binary}: ${error instanceof Error ? error.message : String(error)}`,
installUrl: CLOUDFLARED_INSTALL_URL,
fixHint: "Verify that cloudflared runs cleanly from your shell.",
};
}
},
async open(target, { report, signal }): Promise<void> {
const binary = await resolveBinary();
const targetUrl = `http://${formatHostForUrl(target.host)}:${target.port}`;
report({ type: "connecting" });
const child = spawnProcess(binary, ["tunnel", "--no-autoupdate", "--url", targetUrl], {
env,
stdio: "pipe",
});
let readyReported = false;
let exited = false;
let lastOutputLine = "";
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
let stdoutRemainder = "";
let stderrRemainder = "";
const stopChild = () => {
if (exited) return;
void terminateProcess(child, "SIGTERM").catch(() => undefined);
if (!forceKillTimer) {
forceKillTimer = setTimeout(() => {
if (!exited) {
void terminateProcess(child, "SIGKILL").catch(() => undefined);
}
}, FORCE_KILL_DELAY_MS);
}
};
const processLine = (rawLine: string) => {
const line = rawLine.trim();
if (!line) return;
lastOutputLine = line;
if (readyReported || signal.aborted) return;
const match = QUICK_TUNNEL_URL_PATTERN.exec(line);
if (match) {
readyReported = true;
report({
type: "ready",
url: match[0],
stability: "ephemeral",
});
}
};
const consumeChunk = (stream: "stdout" | "stderr", chunk: Buffer | string) => {
const text = (stream === "stdout" ? stdoutRemainder : stderrRemainder) + String(chunk);
const lines = text.split(/\r?\n/);
const remainder = lines.pop() ?? "";
if (stream === "stdout") stdoutRemainder = remainder;
else stderrRemainder = remainder;
for (const line of lines) processLine(line);
};
child.stdout.on("data", (chunk) => consumeChunk("stdout", chunk));
child.stderr.on("data", (chunk) => consumeChunk("stderr", chunk));
const onAbort = () => stopChild();
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) stopChild();
try {
const result = await new Promise<{
code: number | null;
exitSignal: NodeJS.Signals | null;
spawnError?: Error;
}>((resolve) => {
child.once("error", (error) => {
exited = true;
resolve({ code: null, exitSignal: null, spawnError: error });
});
child.once("close", (code, exitSignal) => {
exited = true;
if (stdoutRemainder) processLine(stdoutRemainder);
if (stderrRemainder) processLine(stderrRemainder);
resolve({ code, exitSignal });
});
});
if (signal.aborted) {
report({ type: "closed", reason: "aborted" });
return;
}
if (result.spawnError) {
if (isNotFoundError(result.spawnError)) {
throw new Error(
`${binary} is not installed or not on PATH. Install cloudflared and retry.`,
);
}
throw result.spawnError;
}
if (!readyReported) {
const detail = lastOutputLine ? `: ${lastOutputLine}` : "";
throw new Error(
`cloudflared exited before tunnel became ready (code ${result.code ?? "null"})${detail}`,
);
}
if (result.code && result.code !== 0) {
const detail = lastOutputLine ? `: ${lastOutputLine}` : "";
const message = `cloudflared exited with code ${result.code}${detail}`;
report({ type: "error", message, recoverable: false });
throw new Error(message);
}
report({ type: "closed" });
} finally {
signal.removeEventListener("abort", onAbort);
if (forceKillTimer) clearTimeout(forceKillTimer);
}
},
};
}
@@ -0,0 +1,13 @@
import { defineSettings } from "@getpaseo/plugin";
import { z } from "zod";
export const cloudflaredSettings = defineSettings({
id: "cloudflared",
scope: "host",
version: 1,
schema: z.object({
binaryPath: z.string().trim().min(1).optional(),
}),
});
export type CloudflaredSettings = z.infer<typeof cloudflaredSettings.schema>;
@@ -0,0 +1,205 @@
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { TunnelEvent } from "@getpaseo/plugin/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createCloudflaredTunnelProvider } from "../server/cloudflared.js";
const tempDirs: string[] = [];
afterEach(async () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});
/** Writes a fake CLI that runs `script` with Node. Windows ignores shebangs, so it gets a `.cmd` launcher. */
async function writeFakeCli(dir: string, name: string, script: string): Promise<string> {
if (process.platform === "win32") {
const scriptPath = path.join(dir, `${name}.cjs`);
await writeFile(scriptPath, script, "utf8");
const launcher = path.join(dir, `${name}.cmd`);
await writeFile(launcher, `@"${process.execPath}" "${scriptPath}" %*\r\n`, "utf8");
return launcher;
}
const launcher = path.join(dir, name);
await writeFile(launcher, `#!${process.execPath}\n${script}\n`, "utf8");
await chmod(launcher, 0o755);
return launcher;
}
function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
async function createFakeCloudflared(scriptBody: string): Promise<{ dir: string; binary: string }> {
const dir = await mkdtemp(path.join(os.tmpdir(), "paseo-fake-cloudflared-"));
tempDirs.push(dir);
const binary = await writeFakeCli(dir, "cloudflared", scriptBody);
return { dir, binary };
}
const unusedPaseo = {} as never;
describe("cloudflared-tunnel built-in plugin", () => {
it("reports unavailable with install guidance when cloudflared is missing", async () => {
const emptyDir = await mkdtemp(path.join(os.tmpdir(), "paseo-empty-path-"));
tempDirs.push(emptyDir);
const provider = createCloudflaredTunnelProvider({
env: { ...process.env, PATH: emptyDir },
});
const status = await provider.status({
paseo: unusedPaseo,
signal: new AbortController().signal,
});
expect(status).toMatchObject({
status: "unavailable",
installUrl: expect.stringContaining("cloudflare.com"),
fixHint: expect.stringContaining("cloudflared"),
});
});
it("opens a quick tunnel, parses trycloudflare.com URL as ephemeral, and terminates on abort", async () => {
const markerFile = path.join(os.tmpdir(), `paseo-cf-term-${Date.now()}-${Math.random()}.txt`);
const { dir } = await createFakeCloudflared(`
const fs = require("node:fs");
const args = process.argv.slice(2);
if (args[0] === "--version") {
console.log("cloudflared version 2026.5.0 (built 2026-05-01)");
process.exit(0);
}
fs.writeFileSync(${JSON.stringify(markerFile)}, JSON.stringify({ pid: process.pid, args }));
console.error("INF +------------------------------------------------------------+");
console.error("INF | https://quick-demo-123.trycloudflare.com |");
console.error("INF +------------------------------------------------------------+");
setInterval(() => {}, 10_000);
`);
tempDirs.push(markerFile);
const provider = createCloudflaredTunnelProvider({
env: { ...process.env, PATH: `${dir}${path.delimiter}${process.env.PATH ?? ""}` },
});
const status = await provider.status({
paseo: unusedPaseo,
signal: new AbortController().signal,
});
expect(status).toEqual({
status: "available",
detail: "cloudflared version 2026.5.0 (built 2026-05-01) (quick tunnel)",
});
const controller = new AbortController();
const events: TunnelEvent[] = [];
let readyResolve!: () => void;
const readyPromise = new Promise<void>((resolve) => {
readyResolve = resolve;
});
const running = provider.open(
{ id: "tun_1", host: "127.0.0.1", port: 4321, label: "External MCP" },
{
paseo: unusedPaseo,
signal: controller.signal,
report(event) {
events.push(event);
if (event.type === "ready") readyResolve();
},
},
);
await readyPromise;
const started = JSON.parse(await readFile(markerFile, "utf8")) as {
pid: number;
args: string[];
};
expect(started.args).toEqual(["tunnel", "--no-autoupdate", "--url", "http://127.0.0.1:4321"]);
controller.abort();
await running;
await vi.waitFor(() => expect(isProcessAlive(started.pid)).toBe(false));
expect(events).toEqual([
{ type: "connecting" },
{
type: "ready",
url: "https://quick-demo-123.trycloudflare.com",
stability: "ephemeral",
},
{ type: "closed", reason: "aborted" },
]);
});
it("brackets IPv6 hosts when launching quick tunnels", async () => {
const argsFile = path.join(os.tmpdir(), `paseo-cf-v6-${Date.now()}-${Math.random()}.txt`);
const { binary } = await createFakeCloudflared(`
const fs = require("node:fs");
const args = process.argv.slice(2);
fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(args));
console.error("INF https://ipv6-demo.trycloudflare.com");
process.on("SIGTERM", () => process.exit(0));
setInterval(() => {}, 10_000);
`);
tempDirs.push(argsFile);
const provider = createCloudflaredTunnelProvider({
readSettings: async () => ({ binaryPath: binary }),
});
const controller = new AbortController();
let readyResolve!: () => void;
const readyPromise = new Promise<void>((resolve) => {
readyResolve = resolve;
});
const running = provider.open(
{ id: "tun_v6", host: "::1", port: 4321 },
{
paseo: unusedPaseo,
signal: controller.signal,
report(event) {
if (event.type === "ready") readyResolve();
},
},
);
await readyPromise;
expect(JSON.parse(await readFile(argsFile, "utf8"))).toEqual([
"tunnel",
"--no-autoupdate",
"--url",
"http://[::1]:4321",
]);
controller.abort();
await running;
});
it("fails the open when quick tunnel provisioning fails instead of reporting the API endpoint", async () => {
const { binary } = await createFakeCloudflared(`
console.error('ERR Couldn\\'t start tunnel error="failed to request quick Tunnel: Post \\\\"https://api.trycloudflare.com/tunnel\\\\": dial tcp: lookup api.trycloudflare.com: no such host"');
process.exit(1);
`);
const provider = createCloudflaredTunnelProvider({
readSettings: async () => ({ binaryPath: binary }),
});
const events: TunnelEvent[] = [];
await expect(
provider.open(
{ id: "tun_offline", host: "127.0.0.1", port: 4321 },
{
paseo: unusedPaseo,
signal: new AbortController().signal,
report(event) {
events.push(event);
},
},
),
).rejects.toThrow(/exited before tunnel became ready/);
expect(events).toEqual([{ type: "connecting" }]);
});
});
@@ -117,56 +117,6 @@ test("coerces credit balance and marks a 96 percent window dangerous", async ()
]);
});
test("reports enterprise individual spend limit percentage and reset", async () => {
const report = await fetchUsage(authInput(fixtureHome), async () =>
Response.json({
plan_type: "enterprise",
spend_control: {
individual_limit: { used_percent: 5, remaining_percent: 95, reset_at: 1795996800 },
},
}),
);
expect(report).toMatchObject({
planLabel: "enterprise",
windows: [
expect.objectContaining({
id: "individual_limit",
label: "Individual spend limit",
summary: true,
usedPct: 5,
remainingPct: 95,
resetsAt: new Date(1795996800 * 1000).toISOString(),
}),
],
});
});
test.each([
[{ used_percent: 5 }, 5, 95],
[{ remaining_percent: 95 }, 5, 95],
[{ used_percent: 5, remaining_percent: 90 }, 5, 90],
[{ used_percent: 110 }, 110, 0],
])(
"completes individual spending percentages for %j",
async (individual_limit, usedPct, remainingPct) => {
const report = await fetchUsage(authInput(fixtureHome), async () =>
Response.json({ spend_control: { individual_limit } }),
);
expect(report).toMatchObject({
status: "available",
windows: [expect.objectContaining({ id: "individual_limit", usedPct, remainingPct })],
});
},
);
test("omits individual spend limit without a percentage", async () => {
const report = await fetchUsage(authInput(fixtureHome), async () =>
Response.json({ spend_control: { individual_limit: { reset_at: 1795996800 } } }),
);
expect(report.windows).toEqual([]);
});
test("summarizes the session and weekly windows by default, not code review", async () => {
const report = await fetchUsage(
authInput(fixtureHome),
@@ -34,15 +34,6 @@ const rateLimitSchema = z.object({
primary_window: windowSchema.nullish(),
secondary_window: windowSchema.nullish(),
});
const spendControlSchema = z.object({
individual_limit: z
.object({
used_percent: number.nullish(),
remaining_percent: number.nullish(),
reset_at: number.nullish(),
})
.nullish(),
});
const responseSchema = z.object({
plan_type: z.string().optional(),
email: z.string().optional(),
@@ -57,7 +48,6 @@ const responseSchema = z.object({
)
.nullish(),
code_review_rate_limit: rateLimitSchema.nullish(),
spend_control: spendControlSchema.nullish(),
credits: z.object({ balance: number.optional() }).nullish(),
});
@@ -242,27 +232,6 @@ export async function fetchUsage(
},
});
}),
...(usage.spend_control?.individual_limit
? (() => {
const limit = usage.spend_control.individual_limit;
const usedPct =
limit.used_percent ??
(limit.remaining_percent != null ? 100 - limit.remaining_percent : undefined);
if (usedPct === undefined) return [];
return [
{
id: "individual_limit",
label: "Individual spend limit",
summary: true,
usedPct,
remainingPct: limit.remaining_percent ?? Math.max(0, 100 - usedPct),
resetsAt:
limit.reset_at != null ? new Date(limit.reset_at * 1000).toISOString() : null,
tone: toneFromUsedPct(usedPct),
},
];
})()
: []),
...usageWindows({
rateLimit: usage.code_review_rate_limit,
scope: { id: "code_review", label: "Code review" },
+4 -108
View File
@@ -5,22 +5,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { discover, fetchUsage } from "./usage.js";
import type { UsageReport } from "@getpaseo/plugin/server/usage";
// The slot the Kimi CLI writes for a login to the global (.ai) deployment.
const GLOBAL_SLOT = "kimi-code-env-0e4f99c69cc27850";
function kimiCredentialPath(dir: string, slot = "kimi-code"): string {
return join(dir, "credentials", `${slot}.json`);
function kimiCredentialPath(dir: string): string {
return join(dir, "credentials", "kimi-code.json");
}
function writeKimiCredentials(
dir: string,
accessToken: string,
overrides: object = {},
slot = "kimi-code",
): void {
function writeKimiCredentials(dir: string, accessToken: string, overrides: object = {}): void {
mkdirSync(join(dir, "credentials"), { recursive: true });
writeFileSync(
kimiCredentialPath(dir, slot),
kimiCredentialPath(dir),
JSON.stringify({
access_token: accessToken,
refresh_token: "rt_kimi",
@@ -181,102 +173,6 @@ describe("kimi usage source", () => {
});
});
it("fetches usage from the global deployment for a kimi.ai login", async () => {
writeKimiCredentials(join(homeDir, ".kimi-code"), "kimi_global_token", {}, GLOBAL_SLOT);
let requestedUrl: string | null = null;
let authorization: string | null = null;
fetchApi = (async (url: RequestInfo | URL, init?: RequestInit) => {
requestedUrl = url.toString();
authorization = (init?.headers as Record<string, string> | undefined)?.Authorization ?? null;
return jsonResponse({ usage: { limit: "100", remaining: "60" } });
}) as unknown as typeof fetch;
const kimi = findProvider(await service().listUsage(), "kimi");
expect(requestedUrl).toBe("https://api.kimi.ai/coding/v1/usages");
expect(authorization).toBe("Bearer kimi_global_token");
expect(kimi.status).toBe("available");
});
it("prefers the login the CLI still refreshes over a stale slot", async () => {
const kimiHome = join(homeDir, ".kimi-code");
writeKimiCredentials(kimiHome, "kimi_stale_token", { expires_at: 1_791_426_752 });
writeKimiCredentials(kimiHome, "kimi_live_token", { expires_at: 1_793_292_337 }, GLOBAL_SLOT);
expect(await discover()).toEqual([
{
key: "default",
input: {
store: "file",
locator: kimiCredentialPath(kimiHome, GLOBAL_SLOT),
baseUrl: "https://api.kimi.ai/coding/v1",
},
},
]);
});
it("fetches global usage when an expired default-deployment login remains", async () => {
const kimiHome = join(homeDir, ".kimi-code");
writeKimiCredentials(kimiHome, "expired_default", { expires_at: 1_700_000_000 });
writeKimiCredentials(kimiHome, "live_global", { expires_at: 2_000_000_000 }, GLOBAL_SLOT);
const [account] = await discover();
if (!account) throw new Error("No configured Kimi account");
const requests: string[] = [];
const report = await fetchUsage(
account.input as Parameters<typeof fetchUsage>[0],
async (url, init) => {
requests.push(url.toString());
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer live_global");
return jsonResponse({ usage: { limit: "100", remaining: "60" } });
},
);
expect(requests).toEqual(["https://api.kimi.ai/coding/v1/usages"]);
expect(report).toMatchObject({ status: "available", windows: [{ usedPct: 40 }] });
});
it("keeps KIMI_CODE_HOME ahead of a newer legacy-home login", async () => {
const selectedHome = join(homeDir, "selected-kimi");
process.env.KIMI_CODE_HOME = selectedHome;
writeKimiCredentials(
selectedHome,
"selected_global_token",
{ expires_at: 2_000_000_000 },
GLOBAL_SLOT,
);
writeKimiCredentials(join(homeDir, ".kimi"), "legacy_token", { expires_at: 2_000_000_100 });
const accounts = await discover();
expect(accounts).toEqual([
{
key: "default",
input: {
store: "file",
locator: kimiCredentialPath(selectedHome, GLOBAL_SLOT),
baseUrl: "https://api.kimi.ai/coding/v1",
},
},
]);
});
it("asks the user to run kimi when the CLI token has expired", async () => {
writeKimiCredentials(join(homeDir, ".kimi-code"), "kimi_cli_token", {
expires_at: 1_700_000_000,
});
const kimi = findProvider(await service().listUsage(), "kimi");
expect(kimi).toEqual({
providerId: "kimi",
status: "unavailable",
problem: { kind: "expired", expiresAt: "2023-11-14T22:13:20.000Z", refreshedBy: "kimi" },
error: null,
planLabel: null,
});
});
it("reads Kimi credentials whose optional fields are null", async () => {
writeKimiCredentials(join(homeDir, ".kimi-code"), "kimi_cli_token", {
expires_at: null,
+17 -43
View File
@@ -1,5 +1,4 @@
import type { UsageInput } from "../shared/input.js";
import { createHash } from "node:crypto";
import { promises as fs } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
@@ -19,21 +18,7 @@ const ApiOptionalStringSchema = z.preprocess(
z.coerce.string().optional(),
);
const KIMI_CODE_BASE_URL = "https://api.kimi.com/coding/v1";
// The Kimi CLI's official deployments. A login writes its token to a credential
// slot derived from the deployment, so a global (.ai) login never touches
// kimi-code.json. Mirrors resolveKimiCodeOAuthKey in the Kimi CLI.
const KIMI_CODE_DEPLOYMENTS = [
{ oauthHost: "https://auth.kimi.com", baseUrl: KIMI_CODE_BASE_URL },
{ oauthHost: "https://auth.kimi.ai", baseUrl: "https://api.kimi.ai/coding/v1" },
];
function credentialSlot(deployment: { oauthHost: string; baseUrl: string }): string {
if (deployment.baseUrl === KIMI_CODE_BASE_URL) return "kimi-code";
const hash = createHash("sha256").update(JSON.stringify(deployment)).digest("hex");
return `kimi-code-env-${hash.slice(0, 16)}`;
}
const KIMI_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
const KimiUsageFieldsSchema = z.object({
limit: ApiOptionalStringSchema,
@@ -272,7 +257,7 @@ export async function fetchUsage(
fetchApi: typeof fetch = fetch,
): Promise<UsageReport> {
async function callUsageApi(token: string): Promise<Response> {
return fetchApi(`${input.baseUrl ?? KIMI_CODE_BASE_URL}/usages`, {
return fetchApi(KIMI_USAGE_URL, {
signal: AbortSignal.timeout(15_000),
headers: {
Authorization: `Bearer ${token}`,
@@ -287,7 +272,6 @@ export async function fetchUsage(
return unavailable({
kind: "expired",
expiresAt: new Date(credentials.expires_at * 1000).toISOString(),
refreshedBy: "kimi",
});
const res = await callUsageApi(credentials.access_token);
@@ -322,31 +306,21 @@ async function readCredentials(input: UsageInput): Promise<KimiCredentials | und
}
}
export async function discover(): Promise<UsageAccount[]> {
for (const locator of ["KIMI_TOKEN", "KIMI_API_KEY"]) {
const input: UsageInput = { store: "env", locator };
const candidates: UsageInput[] = ["KIMI_TOKEN", "KIMI_API_KEY"].map((locator) => ({
store: "env",
locator,
}));
candidates.push(
...[
join(
process.env.KIMI_CODE_HOME || join(homedir(), ".kimi-code"),
"credentials",
"kimi-code.json",
),
join(homedir(), ".kimi", "credentials", "kimi-code.json"),
].map((locator) => ({ store: "file" as const, locator })),
);
for (const input of candidates)
if (await readCredentials(input)) return [{ key: "default", input }];
}
const homes = [
process.env.KIMI_CODE_HOME || join(homedir(), ".kimi-code"),
join(homedir(), ".kimi"),
];
// A login to another deployment leaves the old slot behind with a dead token.
// Within each home, prefer the latest expiry. Keep the configured home ahead
// of the legacy fallback, even if that fallback holds a newer token.
for (const home of homes) {
let found: { input: UsageInput; expiresAt: number } | undefined;
for (const deployment of KIMI_CODE_DEPLOYMENTS) {
const input: UsageInput = {
store: "file",
locator: join(home, "credentials", `${credentialSlot(deployment)}.json`),
baseUrl: deployment.baseUrl,
};
const credentials = await readCredentials(input);
if (!credentials) continue;
const expiresAt = credentials.expires_at ?? Number.POSITIVE_INFINITY;
if (!found || expiresAt > found.expiresAt) found = { input, expiresAt };
}
if (found) return [{ key: "default", input: found.input }];
}
return [];
}
@@ -3,7 +3,6 @@ export const inputSchema = z
.object({
store: z.enum(["env", "file"]),
locator: z.string().min(1),
baseUrl: z.url().optional(),
})
.strict();
export type UsageInput = z.infer<typeof inputSchema>;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/builtin-plugins",
"version": "0.18.0",
"version": "0.17.6",
"private": true,
"type": "module",
"scripts": {
+6
View File
@@ -0,0 +1,6 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import { createTailscaleFunnelProvider } from "./server/tailscale.js";
export default function contribute(server: PluginServerContext) {
return server.registerTunnelProvider(createTailscaleFunnelProvider());
}
@@ -0,0 +1 @@
{ "id": "tailscale-funnel", "requirements": { "paseo": ">=0.17.6" } }
@@ -0,0 +1,380 @@
import {
execCommand,
spawnProcess,
terminateProcess,
type TunnelProviderRegistration,
type TunnelProviderStatus,
} from "@getpaseo/plugin/server";
export const TAILSCALE_FUNNEL_PORTS = [443, 8443, 10000] as const;
const TAILSCALE_INSTALL_URL = "https://tailscale.com/download";
const TAILSCALE_FUNNEL_DOCS_URL = "https://tailscale.com/kb/1223/funnel";
const FUNNEL_READY_PATTERN = /available on the internet/i;
const FORCE_KILL_DELAY_MS = 2_000;
export interface TailscaleFunnelProviderOptions {
binary?: string;
env?: NodeJS.ProcessEnv;
}
interface TailscaleStatusJson {
BackendState?: unknown;
Self?: {
DNSName?: unknown;
Capabilities?: unknown;
CapMap?: unknown;
};
}
interface TailscaleFunnelStatusJson {
TCP?: Record<string, unknown>;
Web?: Record<string, unknown>;
AllowFunnel?: Record<string, unknown>;
}
function formatHostForUrl(host: string): string {
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
}
// On Windows a bare name that is not on PATH runs through cmd.exe, which exits 9009 for an
// unknown command instead of failing the spawn with ENOENT.
const WINDOWS_COMMAND_NOT_FOUND_EXIT_CODE = 9009;
function isNotFoundError(error: unknown): boolean {
if (typeof error !== "object" || error === null || !("code" in error)) return false;
if (error.code === "ENOENT" || error.code === "ENOTDIR") return true;
return process.platform === "win32" && error.code === WINDOWS_COMMAND_NOT_FOUND_EXIT_CODE;
}
function hasFunnelCapability(self: NonNullable<TailscaleStatusJson["Self"]>): boolean {
if (Array.isArray(self.Capabilities)) {
if (
self.Capabilities.some(
(capability) => typeof capability === "string" && /funnel/i.test(capability),
)
) {
return true;
}
}
if (self.CapMap && typeof self.CapMap === "object" && !Array.isArray(self.CapMap)) {
for (const [key, value] of Object.entries(self.CapMap)) {
if (/funnel/i.test(key) && value !== false && value !== null && value !== undefined) {
return true;
}
}
}
return false;
}
function parsePortFromKey(key: string): number | null {
const direct = /^\d+$/.exec(key.trim());
if (direct) {
const value = Number(direct[0]);
return Number.isInteger(value) ? value : null;
}
const hostPort = /:(\d+)$/.exec(key.trim());
if (hostPort) {
const value = Number(hostPort[1]);
return Number.isInteger(value) ? value : null;
}
return null;
}
export function extractOccupiedFunnelPorts(raw: unknown): Set<number> {
const occupied = new Set<number>();
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return occupied;
const status = raw as TailscaleFunnelStatusJson;
if (status.TCP && typeof status.TCP === "object") {
for (const key of Object.keys(status.TCP)) {
const port = parsePortFromKey(key);
if (port !== null) occupied.add(port);
}
}
if (status.Web && typeof status.Web === "object") {
for (const key of Object.keys(status.Web)) {
const port = parsePortFromKey(key);
if (port !== null) occupied.add(port);
}
}
if (status.AllowFunnel && typeof status.AllowFunnel === "object") {
for (const [key, enabled] of Object.entries(status.AllowFunnel)) {
if (!enabled) continue;
const port = parsePortFromKey(key);
if (port !== null) occupied.add(port);
}
}
return occupied;
}
export function createTailscaleFunnelProvider(
options: TailscaleFunnelProviderOptions = {},
): TunnelProviderRegistration {
const binary = options.binary ?? "tailscale";
const env = options.env;
const allocatedPorts = new Set<number>();
let allocationTail: Promise<void> = Promise.resolve();
async function withAllocationLock<T>(run: () => Promise<T>): Promise<T> {
const previous = allocationTail;
let release!: () => void;
allocationTail = new Promise<void>((resolve) => {
release = resolve;
});
await previous;
try {
return await run();
} finally {
release();
}
}
async function probeStatus(
signal?: AbortSignal,
): Promise<
| { ok: true; dnsName: string; status: TunnelProviderStatus }
| { ok: false; status: Extract<TunnelProviderStatus, { status: "unavailable" }> }
> {
let stdout: string;
try {
({ stdout } = await execCommand(binary, ["status", "--json"], {
env,
signal,
timeout: 5_000,
}));
} catch (error) {
if (isNotFoundError(error)) {
return {
ok: false,
status: {
status: "unavailable",
reason: `${binary} CLI is not installed or not on PATH.`,
installUrl: TAILSCALE_INSTALL_URL,
fixHint: "Install Tailscale and make sure the tailscale CLI is on PATH.",
},
};
}
return {
ok: false,
status: {
status: "unavailable",
reason: `Tailscale is not running or could not be queried: ${error instanceof Error ? error.message : String(error)}`,
fixHint: "Start Tailscale and run `tailscale status` to verify connectivity.",
},
};
}
let parsed: TailscaleStatusJson;
try {
parsed = JSON.parse(stdout) as TailscaleStatusJson;
} catch {
return {
ok: false,
status: {
status: "unavailable",
reason: "Could not parse output from `tailscale status --json`.",
fixHint: "Verify that your Tailscale CLI is up to date.",
},
};
}
const backendState = typeof parsed.BackendState === "string" ? parsed.BackendState : "unknown";
if (backendState !== "Running") {
return {
ok: false,
status: {
status: "unavailable",
reason: `Tailscale is not connected (state: ${backendState}).`,
fixHint: "Run `tailscale up` and sign in to your tailnet.",
},
};
}
const self = parsed.Self;
const dnsName =
typeof self?.DNSName === "string" ? self.DNSName.trim().replace(/\.+$/, "") : "";
if (!dnsName) {
return {
ok: false,
status: {
status: "unavailable",
reason: "MagicDNS is not enabled for this Tailscale node.",
fixHint: "Enable MagicDNS in the Tailscale admin console.",
},
};
}
if (!self || !hasFunnelCapability(self)) {
return {
ok: false,
status: {
status: "unavailable",
reason: "Tailscale Funnel is not enabled for this node or tailnet.",
installUrl: TAILSCALE_FUNNEL_DOCS_URL,
fixHint:
"Enable HTTPS certificates and Funnel in your Tailscale admin console and ACL policy.",
},
};
}
return {
ok: true,
dnsName,
status: {
status: "available",
detail: dnsName,
},
};
}
// A port is only free when Tailscale says so. Treating a failed status call as "nothing in use"
// would replace, and later remove, the user's own Serve or Funnel handler on that port.
async function inspectOccupiedPorts(signal?: AbortSignal): Promise<Set<number>> {
let stdout: string;
try {
({ stdout } = await execCommand(binary, ["funnel", "status", "--json"], {
env,
signal,
timeout: 5_000,
}));
} catch (error) {
throw new Error(
`Could not read the current Tailscale Funnel configuration: ${error instanceof Error ? error.message : String(error)}`,
{ cause: error },
);
}
const trimmed = stdout.trim();
if (!trimmed) return new Set();
try {
return extractOccupiedFunnelPorts(JSON.parse(trimmed));
} catch (error) {
throw new Error("Could not parse output from `tailscale funnel status --json`.", {
cause: error,
});
}
}
return {
id: "tailscale-funnel",
label: "Tailscale Funnel",
description: "Expose local HTTP endpoints on your Tailscale MagicDNS hostname via Funnel.",
docsUrl: TAILSCALE_FUNNEL_DOCS_URL,
async status({ signal }): Promise<TunnelProviderStatus> {
const probe = await probeStatus(signal);
return probe.status;
},
// Foreground `tailscale funnel` keeps the Funnel only while the CLI runs. tailscaled drops the
// configuration when the CLI exits for any reason, so a crash or a reboot cannot leave the
// target public. `--bg` would persist it in tailscaled with no owner.
async open(target, { report, signal }): Promise<void> {
report({ type: "connecting" });
const probe = await probeStatus(signal);
if (!probe.ok) {
throw new Error(probe.status.reason);
}
const targetUrl = `http://${formatHostForUrl(target.host)}:${target.port}`;
const port = await withAllocationLock(async () => {
if (signal.aborted) return null;
const occupied = await inspectOccupiedPorts(signal);
const freePort = TAILSCALE_FUNNEL_PORTS.find(
(candidate) => !occupied.has(candidate) && !allocatedPorts.has(candidate),
);
if (freePort === undefined) {
throw new Error(
"All 3 Tailscale Funnel HTTPS ports (443, 8443, 10000) are already in use. Close an existing Funnel exposure before opening another.",
);
}
allocatedPorts.add(freePort);
return freePort;
});
if (port === null) {
report({ type: "closed", reason: "aborted" });
return;
}
const publicUrl =
port === 443 ? `https://${probe.dnsName}` : `https://${probe.dnsName}:${port}`;
const child = spawnProcess(binary, ["funnel", `--https=${port}`, targetUrl], {
env,
stdio: "pipe",
});
let readyReported = false;
let exited = false;
let lastOutputLine = "";
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
const stopChild = () => {
if (exited) return;
void terminateProcess(child, "SIGTERM").catch(() => undefined);
forceKillTimer ??= setTimeout(() => {
if (!exited) void terminateProcess(child, "SIGKILL").catch(() => undefined);
}, FORCE_KILL_DELAY_MS);
};
const consumeOutput = (chunk: Buffer | string) => {
for (const rawLine of String(chunk).split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) continue;
lastOutputLine = line;
if (readyReported || signal.aborted || !FUNNEL_READY_PATTERN.test(line)) continue;
readyReported = true;
report({ type: "ready", url: publicUrl, stability: "stable" });
}
};
child.stdout.on("data", consumeOutput);
child.stderr.on("data", consumeOutput);
signal.addEventListener("abort", stopChild, { once: true });
if (signal.aborted) stopChild();
try {
const result = await new Promise<{ code: number | null; spawnError?: Error }>((resolve) => {
child.once("error", (error) => {
exited = true;
resolve({ code: null, spawnError: error });
});
child.once("close", (code) => {
exited = true;
resolve({ code });
});
});
if (signal.aborted) {
report({ type: "closed", reason: "aborted" });
return;
}
const detail = lastOutputLine ? `: ${lastOutputLine}` : "";
if (result.spawnError) {
throw new Error(
`Failed to start Tailscale Funnel on HTTPS port ${port}: ${result.spawnError.message}`,
{ cause: result.spawnError },
);
}
if (!readyReported) {
throw new Error(
`Failed to start Tailscale Funnel on HTTPS port ${port} (code ${result.code ?? "null"})${detail}`,
);
}
if (result.code === 0) {
report({ type: "closed" });
return;
}
const message = `tailscale funnel exited with code ${result.code ?? "null"}${detail}`;
report({ type: "error", message, recoverable: false });
throw new Error(message);
} finally {
signal.removeEventListener("abort", stopChild);
if (forceKillTimer) clearTimeout(forceKillTimer);
allocatedPorts.delete(port);
}
},
};
}
@@ -0,0 +1,343 @@
import { chmod, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { TunnelEvent } from "@getpaseo/plugin/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTailscaleFunnelProvider } from "../server/tailscale.js";
const tempDirs: string[] = [];
afterEach(async () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});
interface FakeTailscaleState {
funnelPorts: Record<string, string>;
history: string[][];
}
/** Writes a fake CLI that runs `script` with Node. Windows ignores shebangs, so it gets a `.cmd` launcher. */
async function writeFakeCli(dir: string, name: string, script: string): Promise<string> {
if (process.platform === "win32") {
const scriptPath = path.join(dir, `${name}.cjs`);
await writeFile(scriptPath, script, "utf8");
const launcher = path.join(dir, `${name}.cmd`);
await writeFile(launcher, `@"${process.execPath}" "${scriptPath}" %*\r\n`, "utf8");
return launcher;
}
const launcher = path.join(dir, name);
await writeFile(launcher, `#!${process.execPath}\n${script}\n`, "utf8");
await chmod(launcher, 0o755);
return launcher;
}
function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
// Each `tailscale funnel` process owns one file in portsDir that records its pid. Like tailscaled
// with a foreground Funnel, a port counts as in use only while that process lives. Every call
// appends one history line. Separate files keep concurrent fake processes from overwriting each
// other's state.
async function createFakeTailscale(initial: {
statusJson: Record<string, unknown>;
funnelPorts?: Record<string, string>;
funnelStatusFails?: boolean;
}): Promise<{ binary: string; readState: () => Promise<FakeTailscaleState> }> {
const dir = await mkdtemp(path.join(os.tmpdir(), "paseo-fake-tailscale-"));
tempDirs.push(dir);
const configFile = path.join(dir, "config.json");
const historyFile = path.join(dir, "history.jsonl");
const portsDir = path.join(dir, "ports");
await mkdir(portsDir);
await writeFile(
configFile,
JSON.stringify({
statusJson: initial.statusJson,
funnelStatusFails: initial.funnelStatusFails ?? false,
}),
"utf8",
);
await writeFile(historyFile, "", "utf8");
// Ports configured outside Paseo stay in use for the whole test, so they belong to this process.
for (const [port, target] of Object.entries(initial.funnelPorts ?? {})) {
await writeFile(
path.join(portsDir, port),
JSON.stringify({ pid: process.pid, target }),
"utf8",
);
}
const binary = await writeFakeCli(
dir,
"tailscale",
`const fs = require("node:fs");
const path = require("node:path");
const config = JSON.parse(fs.readFileSync(${JSON.stringify(configFile)}, "utf8"));
const portsDir = ${JSON.stringify(portsDir)};
const args = process.argv.slice(2);
fs.appendFileSync(${JSON.stringify(historyFile)}, JSON.stringify(args) + "\\n");
if (args[0] === "status" && args[1] === "--json") {
console.log(JSON.stringify(config.statusJson));
process.exit(0);
}
if (args[0] === "funnel" && args[1] === "status" && args[2] === "--json") {
if (config.funnelStatusFails) {
console.error("funnel status failed");
process.exit(1);
}
const isAlive = (pid) => {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
};
const tcp = {};
for (const port of fs.readdirSync(portsDir)) {
const { pid } = JSON.parse(fs.readFileSync(path.join(portsDir, port), "utf8"));
if (isAlive(pid)) tcp[port] = { HTTPS: true };
}
console.log(JSON.stringify({ TCP: tcp }));
process.exit(0);
}
// Foreground funnel: tailscaled keeps the configuration only while this process runs.
if (args[0] === "funnel" && args[1].startsWith("--https=")) {
const portFile = path.join(portsDir, args[1].slice("--https=".length));
fs.writeFileSync(portFile, JSON.stringify({ pid: process.pid, target: args[2] }));
const removeConfig = () => {
fs.rmSync(portFile, { force: true });
process.exit(0);
};
process.on("SIGTERM", removeConfig);
process.on("SIGINT", removeConfig);
console.log("Available on the internet:");
console.log("https://devbox.tailnet.ts.net/");
console.log("Press Ctrl+C to exit.");
setInterval(() => {}, 10_000);
return;
}
console.error("Unexpected tailscale args:", args.join(" "));
process.exit(1);
`,
);
return {
binary,
readState: async () => {
const funnelPorts: Record<string, string> = {};
for (const port of await readdir(portsDir)) {
const entry = JSON.parse(await readFile(path.join(portsDir, port), "utf8")) as {
pid: number;
target: string;
};
if (isProcessAlive(entry.pid)) funnelPorts[port] = entry.target;
}
const history = (await readFile(historyFile, "utf8"))
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as string[]);
return { funnelPorts, history };
},
};
}
const unusedPaseo = {} as never;
describe("tailscale-funnel built-in plugin", () => {
it("reports unavailable when tailscale CLI is missing", async () => {
const emptyDir = await mkdtemp(path.join(os.tmpdir(), "paseo-empty-ts-path-"));
tempDirs.push(emptyDir);
const provider = createTailscaleFunnelProvider({
env: { ...process.env, PATH: emptyDir },
});
const status = await provider.status({
paseo: unusedPaseo,
signal: new AbortController().signal,
});
expect(status).toMatchObject({
status: "unavailable",
installUrl: "https://tailscale.com/download",
});
});
it("reports clear diagnostics when logged out, MagicDNS is off, or Funnel is disabled", async () => {
const loggedOut = await createFakeTailscale({
statusJson: { BackendState: "NeedsLogin", Self: {} },
});
expect(
await createTailscaleFunnelProvider({ binary: loggedOut.binary }).status({
paseo: unusedPaseo,
signal: new AbortController().signal,
}),
).toMatchObject({
status: "unavailable",
reason: expect.stringContaining("NeedsLogin"),
});
const noMagicDns = await createFakeTailscale({
statusJson: { BackendState: "Running", Self: { DNSName: "" } },
});
expect(
await createTailscaleFunnelProvider({ binary: noMagicDns.binary }).status({
paseo: unusedPaseo,
signal: new AbortController().signal,
}),
).toMatchObject({
status: "unavailable",
reason: expect.stringContaining("MagicDNS"),
});
const noFunnel = await createFakeTailscale({
statusJson: {
BackendState: "Running",
Self: { DNSName: "devbox.tailnet.ts.net.", Capabilities: [] },
},
});
expect(
await createTailscaleFunnelProvider({ binary: noFunnel.binary }).status({
paseo: unusedPaseo,
signal: new AbortController().signal,
}),
).toMatchObject({
status: "unavailable",
reason: expect.stringContaining("Funnel"),
});
});
it("allocates ports 443, 8443, 10000, rejects a 4th exposure, and stops the foreground funnel on abort", async () => {
const fake = await createFakeTailscale({
statusJson: {
BackendState: "Running",
Self: {
DNSName: "devbox.tailnet.ts.net.",
Capabilities: ["https://tailscale.com/cap/funnel-v1"],
},
},
});
const provider = createTailscaleFunnelProvider({ binary: fake.binary });
expect(
await provider.status({
paseo: unusedPaseo,
signal: new AbortController().signal,
}),
).toEqual({
status: "available",
detail: "devbox.tailnet.ts.net",
});
const openExposure = async (id: string, port: number, host = "127.0.0.1") => {
const controller = new AbortController();
const events: TunnelEvent[] = [];
let resolveReady!: (url: string) => void;
const ready = new Promise<string>((resolve) => {
resolveReady = resolve;
});
const done = provider.open(
{ id, host, port },
{
paseo: unusedPaseo,
signal: controller.signal,
report(event) {
events.push(event);
if (event.type === "ready") resolveReady(event.url);
},
},
);
const url = await ready;
return { controller, events, url, done };
};
const first = await openExposure("e1", 3001);
const second = await openExposure("e2", 3002);
const third = await openExposure("e3", 3003);
expect(first.url).toBe("https://devbox.tailnet.ts.net");
expect(second.url).toBe("https://devbox.tailnet.ts.net:8443");
expect(third.url).toBe("https://devbox.tailnet.ts.net:10000");
expect(first.events).toEqual([
{ type: "connecting" },
{ type: "ready", url: "https://devbox.tailnet.ts.net", stability: "stable" },
]);
// 4th exposure fails cleanly because all 3 Funnel ports are in use.
await expect(
provider.open(
{ id: "e4", host: "127.0.0.1", port: 3004 },
{
paseo: unusedPaseo,
signal: new AbortController().signal,
report() {},
},
),
).rejects.toThrow(/All 3 Tailscale Funnel HTTPS ports \(443, 8443, 10000\) are already in use/);
// Abort the second exposure (port 8443) -> stops its foreground funnel and frees port 8443.
second.controller.abort();
await second.done;
expect(second.events.at(-1)).toEqual({ type: "closed", reason: "aborted" });
// Windows force-kills the launcher tree, so the funnel process can outlive `done` briefly.
await vi.waitFor(async () =>
expect((await fake.readState()).funnelPorts).toEqual({
"443": "http://127.0.0.1:3001",
"10000": "http://127.0.0.1:3003",
}),
);
// A new exposure reuses the freed port 8443 and brackets IPv6 hosts.
const fourth = await openExposure("e4", 3004, "::1");
expect(fourth.url).toBe("https://devbox.tailnet.ts.net:8443");
const stateWithIpv6 = await fake.readState();
expect(stateWithIpv6.funnelPorts["8443"]).toBe("http://[::1]:3004");
first.controller.abort();
third.controller.abort();
fourth.controller.abort();
await Promise.all([first.done, third.done, fourth.done]);
await vi.waitFor(async () => expect((await fake.readState()).funnelPorts).toEqual({}));
const finalState = await fake.readState();
expect(finalState.history).toContainEqual(["funnel", "--https=443", "http://127.0.0.1:3001"]);
expect(finalState.history.flat()).not.toContain("--bg");
});
it("refuses to open when the current Funnel configuration cannot be read", async () => {
const fake = await createFakeTailscale({
statusJson: {
BackendState: "Running",
Self: {
DNSName: "devbox.tailnet.ts.net.",
Capabilities: ["https://tailscale.com/cap/funnel-v1"],
},
},
funnelStatusFails: true,
});
const provider = createTailscaleFunnelProvider({ binary: fake.binary });
await expect(
provider.open(
{ id: "e1", host: "127.0.0.1", port: 3001 },
{ paseo: unusedPaseo, signal: new AbortController().signal, report() {} },
),
).rejects.toThrow(/Could not read the current Tailscale Funnel configuration/);
const state = await fake.readState();
expect(state.funnelPorts).toEqual({});
expect(
state.history.some((args) => args[0] === "funnel" && args[1]?.startsWith("--https=")),
).toBe(false);
});
});
+84
View File
@@ -864,6 +864,90 @@ export default function contribute(server: PluginServerContext) {
See the complete [worktrunk example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk).
## Tunnel providers {#tunnel-providers}
**Requires Paseo 0.18.** Register a tunnel provider from `index.server.ts` with
`server.registerTunnelProvider()` to turn a local HTTP `host:port` target into a public HTTPS URL.
The registration returns a cleanup function that unregisters the provider and closes its active
exposures.
```ts
import {
execCommand,
spawnProcess,
terminateProcess,
type PluginServerContext,
} from "@getpaseo/plugin/server";
export default function contribute(server: PluginServerContext) {
return server.registerTunnelProvider({
id: "custom-tunnel",
label: "Custom Tunnel",
description: "Expose local HTTP targets through a custom tunnel binary.",
docsUrl: "https://example.com/docs/custom-tunnel",
async status({ signal }) {
try {
const { stdout } = await execCommand("custom-tunnel", ["--version"], {
signal,
timeout: 5_000,
});
return { status: "available", detail: stdout.trim() || undefined };
} catch {
return {
status: "unavailable",
reason: "custom-tunnel is not installed or not on PATH.",
installUrl: "https://example.com/install",
fixHint: "Install custom-tunnel and make sure that it is on PATH.",
};
}
},
async open(target, { report, signal }) {
report({ type: "connecting" });
const child = spawnProcess("custom-tunnel", ["http", `${target.host}:${target.port}`], {
stdio: "pipe",
});
signal.addEventListener(
"abort",
() => {
void terminateProcess(child, "SIGTERM").catch(() => undefined);
},
{ once: true },
);
let ready = false;
child.stderr.on("data", (chunk) => {
if (ready || signal.aborted) return;
const match = /https:\/\/[a-z0-9.-]+/i.exec(String(chunk));
if (!match) return;
ready = true;
report({ type: "ready", url: match[0], stability: "ephemeral" });
});
await new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.once("close", () => resolve());
});
report({ type: "closed", reason: signal.aborted ? "aborted" : undefined });
},
});
}
```
- `id` must match `/^[a-z][a-z0-9._-]*$/` and must be unique across installed and built-in plugins.
- `status({ paseo, signal })` checks whether the provider can open tunnels on this host. Return
`{ status: "available", detail? }` or `{ status: "unavailable", reason, installUrl?, fixHint? }`.
- `open(target, { paseo, signal, report })` owns one exposure until `signal` aborts or the tunnel
closes. `target` carries `{ id, host, port, label?, slug? }`.
- Call `report(event)` as the exposure changes state:
- `{ type: "connecting", detail? }`
- `{ type: "ready", url, stability?: "ephemeral" | "stable", detail? }`
- `{ type: "reconnecting", reason? }`
- `{ type: "error", message, recoverable?: boolean }`
- `{ type: "closed", reason? }`
- Keep `open()` pending while the tunnel stays up. When `signal` aborts, stop child processes or
remote rules, report `{ type: "closed" }`, and resolve. If `open()` throws or exits before
reporting `ready`, Paseo fails the exposure and removes it cleanly.
See the complete [tunnel-provider example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/tunnel-provider).
## Entry point and cleanup
Each present entry default-exports one contribution function and returns cleanup. Client entries
+77
View File
@@ -661,6 +661,83 @@ export default function contribute(server: PluginServerContext) {
完整插件见 [worktrunk 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk)。
## 隧道 Provider {#tunnel-providers}
**需要 Paseo 0.18**。在服务端入口 `index.server.ts` 中调用 `server.registerTunnelProvider()` 注册隧道 Provider,可将本地 HTTP `host:port` 目标转为公网 HTTPS URL。注册返回一个清理函数,调用后会注销该 Provider 并关闭其所有活动的暴露。
```ts
import {
execCommand,
spawnProcess,
terminateProcess,
type PluginServerContext,
} from "@getpaseo/plugin/server";
export default function contribute(server: PluginServerContext) {
return server.registerTunnelProvider({
id: "custom-tunnel",
label: "Custom Tunnel",
description: "Expose local HTTP targets through a custom tunnel binary.",
docsUrl: "https://example.com/docs/custom-tunnel",
async status({ signal }) {
try {
const { stdout } = await execCommand("custom-tunnel", ["--version"], {
signal,
timeout: 5_000,
});
return { status: "available", detail: stdout.trim() || undefined };
} catch {
return {
status: "unavailable",
reason: "custom-tunnel is not installed or not on PATH.",
installUrl: "https://example.com/install",
fixHint: "Install custom-tunnel and make sure that it is on PATH.",
};
}
},
async open(target, { report, signal }) {
report({ type: "connecting" });
const child = spawnProcess("custom-tunnel", ["http", `${target.host}:${target.port}`], {
stdio: "pipe",
});
signal.addEventListener(
"abort",
() => {
void terminateProcess(child, "SIGTERM").catch(() => undefined);
},
{ once: true },
);
let ready = false;
child.stderr.on("data", (chunk) => {
if (ready || signal.aborted) return;
const match = /https:\/\/[a-z0-9.-]+/i.exec(String(chunk));
if (!match) return;
ready = true;
report({ type: "ready", url: match[0], stability: "ephemeral" });
});
await new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.once("close", () => resolve());
});
report({ type: "closed", reason: signal.aborted ? "aborted" : undefined });
},
});
}
```
- `id` 必须匹配 `/^[a-z][a-z0-9._-]*$/`,且在已安装插件和内置插件之间唯一。
- `status({ paseo, signal })` 检查该 Provider 能否在此主机上打开隧道。返回 `{ status: "available", detail? }` 或 `{ status: "unavailable", reason, installUrl?, fixHint? }`。
- `open(target, { paseo, signal, report })` 负责一个暴露,直到 `signal` 中止或隧道关闭。`target` 包含 `{ id, host, port, label?, slug? }`。
- 暴露状态变化时调用 `report(event)`:
- `{ type: "connecting", detail? }`
- `{ type: "ready", url, stability?: "ephemeral" | "stable", detail? }`
- `{ type: "reconnecting", reason? }`
- `{ type: "error", message, recoverable?: boolean }`
- `{ type: "closed", reason? }`
- 隧道保持连接期间,`open()` 应保持挂起。`signal` 中止时,停止子进程或移除远程规则,报告 `{ type: "closed" }`,然后返回。如果 `open()` 抛出错误,或在报告 `ready` 之前退出,Paseo 会将该暴露标记为失败并将其完整移除。
完整插件见 [tunnel-provider 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/tunnel-provider)。
## 入口与清理 {#entry-point-and-cleanup}
每个存在的入口都默认导出一个贡献函数,并返回清理函数。客户端入口接收 `PluginClientContext`;服务端入口接收 `PluginServerContext`。客户端注册方法返回幂等的移除函数,但标题栏按钮和 Composer 标签除外,它们返回 `{ update, remove }` 句柄。入口的清理函数会在 Paseo 移除剩余的注册之前运行。
-8
View File
@@ -146,14 +146,6 @@ test("change gating allows superseded workflow runs to cancel", () => {
test("published npm packages declare and ship the repository license", () => {
const rootManifest = JSON.parse(readFileSync(new URL("package.json", repoRoot), "utf8"));
assert.match(rootManifest.scripts["release:publish"], /scripts\/publish-release-packages\.mjs/);
assert.match(
rootManifest.scripts["release:ship"],
/^npm run release:push && npm run release:publish$/,
);
assert.match(
rootManifest.scripts["release:ship:beta"],
/^npm run release:push && npm run release:publish:beta$/,
);
const workspaceArgs = PUBLISH_WORKSPACES.map((workspace) => `--workspace=${workspace}`);
const packed = JSON.parse(
execFileSync("npm", ["pack", "--dry-run", "--ignore-scripts", "--json", ...workspaceArgs], {