Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 7b1e93ea18 fix(plugins): launch tunnel CLIs without a shell so a missing CLI reads as not installed
On Windows a bare name that is not on PATH ran through cmd.exe, which exits
with a generic code and a localized "not recognized" message. The providers
then reported a missing tailscale or cloudflared as "not running" or "failed
to query". Without a shell the spawn fails with ENOENT on every platform.
Both CLIs ship as executables; a .cmd set as a full binary path still runs
through cmd.exe. This replaces the exit-code 9009 check, which cmd.exe does
not return as the process exit code.
2026-11-27 15:17:26 +01:00
Mohamed Boudra 89077b2289 test(plugin): parse shared declarations once in SDK boundary type checks
Each typeErrors() call built a fresh program and parsed the SDK, library,
and dependency declarations again. On a slow Windows runner one check took
over the 5 s test timeout. The checks now share the parsed configuration
and declaration files, so each one parses only its snippet. The file runs
in about a quarter of the time locally.
2026-11-27 14:53:37 +01:00
Mohamed Boudra 2fc24a0918 test(plugins): replace the Windows Path variable in tunnel CLI tests
Windows keeps the original case of environment names, usually `Path`.
Spreading process.env and setting `PATH` left the real search path beside
the override, so the missing-CLI tests could still find or query a real CLI.
The missing-CLI tests now assert the exact "not installed" status.
2026-11-27 14:45:53 +01:00
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
Mohamed Boudra 5d003d9613 test(cli): report version from fake ACP provider helper (#11032)
antigravity-provider status() now runs --version and requires >= 1.5.1 (#10992). Without a --version handler, supervisor-acp.cjs exited with empty stdout on the version probe and broke 23-daemon-sigint-supervisor.test.ts at createAgent().
2026-11-27 16:36:42 +07:00
paseo-bot[bot]andpeanut_hzm 9868ebc11c fix(usage): discover the GLM Agent login for its Usage card (#8376)
* fix(usage): follow the CLIs' current auth locations for MiniMax and Z.ai

The usage sources look for credentials where the CLIs used to keep them, so
their plan quota never appears in Settings → Usage.

MiniMax Code (`mcode`) moved its OAuth login to
`~/.minimax/auth/<buildEnv>/<region>/<clientId>/auth.json`, with the token
inside a `records` map and the region in a sibling `auth-state.json`. The
source still looked in `~/.mmx/` for the older `access_token` shape. It also
called `/v1/token_plan/remains`, which the agent backend answers with
`status_code 1004` ("Please carry the API secret key in the 'Authorization'
field"); the coding-plan endpoint the CLI itself uses is
`/v1/api/openplatform/coding_plan/remains`.

Z.ai's `glm-acp-agent` reads `Z_AI_API_KEY` and persists it to
`~/.config/glm-acp-agent/credentials.json` as `z_ai_api_key`. The source
looked for `ZAI_API_KEY` and `GLM_API_KEY` only, and never read the
credentials file.

Both keep their existing lookups working, so a configured environment
variable or the older `~/.mmx/` layout still resolves.

* fix(usage): narrow credential discovery repair to the verified GLM path

Keep the independently reproduced GLM discovery fix and isolate its file test from inherited XDG_CONFIG_HOME. Leave MiniMax quota routing for separate verification before changing existing API-key requests.

Co-authored-by: peanut_hzm <peanut_hzm@163.com>

* test(usage): isolate the legacy login locator from inherited credentials

---------

Co-authored-by: peanut_hzm <peanut_hzm@163.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 09:21:16 +00:00
46 changed files with 4009 additions and 225 deletions
+2 -11
View File
@@ -202,17 +202,8 @@ This is the Android counterpart of the iOS local-simulator flow in [development.
`modules/paseo-scroll` replaces React Native's vertical scroll view with `PaseoScrollView`, which
keeps React Native's scroll manager interface and corrects how the chat timeline holds its position.
[agent-stream-disclosure.md](agent-stream-disclosure.md#scroll-view-corrections) lists the
corrections and the React Native issues they work around.
The timeline's `nativeID` (`agent-chat-scroll-native-virtualized`) also identifies it to the native
scroll owner: a nested panel's edge overshoot and unconsumed fling must leave the timeline still.
Ordinary scroll parents retain Android's handoff. Keep that identity in sync with
`agent-stream/strategy-native.tsx`; the end pin is absent while reading history, so it cannot
identify the timeline for this rule.
Its instrumentation tests run the scroll view in a real window, mounting through React Native's own
mounting manager and injecting touches. `PanelEdgeTest` covers both panel edges, flings,
interior/direct scrolling, and ordinary-parent handoff:
corrections and the React Native issues they work around. Its instrumentation tests run the scroll
view in a real window, mounting through React Native's own mounting manager and injecting touches:
```bash
cd packages/app/android
+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.
@@ -1,158 +0,0 @@
package sh.paseo.scroll
import android.app.Activity
import android.content.Intent
import android.os.SystemClock
import android.view.View
import android.widget.FrameLayout
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.views.scroll.ReactScrollView
import com.facebook.react.views.scroll.ReactScrollViewManager
import com.facebook.react.views.view.ReactViewGroup
import com.facebook.soloader.SoLoader
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/** Forward-order parent, as used by the current Android timeline, and a nested panel at its edge. */
@RunWith(AndroidJUnit4::class)
class PanelEdgeTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private var activity: Activity? = null
private lateinit var manager: ReactScrollViewManager
@After fun finish() {
instrumentation.runOnMainSync { activity?.finish() }
}
@Test fun panelBottomEdgeLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
child.stopNestedScroll()
assertEquals("Panel stays at its bottom", 600, child.scrollY)
assertEquals("Panel overshoot must leave timeline still", 400, parent.scrollY)
}
}
@Test fun panelTopEdgeLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 0)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, -100, null)
child.stopNestedScroll()
assertEquals("Panel stays at its top", 0, child.scrollY)
assertEquals("Panel overshoot must leave timeline still", 400, parent.scrollY)
}
}
@Test fun panelFlingLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedFling(0f, 1500f, false)
child.stopNestedScroll()
}
SystemClock.sleep(500)
instrumentation.runOnMainSync {
assertEquals("Panel fling must leave timeline still", 400, parent.scrollY)
}
}
@Test fun disablingChildNestedScrollPreventsHandoff() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.isNestedScrollingEnabled = false
assertEquals(false, child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
assertEquals(400, parent.scrollY)
}
}
@Test fun ordinaryParentStillConsumesNestedOvershoot() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
manager.setNativeId(parent, "ordinary-scroll-parent")
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
child.stopNestedScroll()
assertEquals("Ordinary parent retains framework handoff", 500, parent.scrollY)
}
}
@Test fun ordinaryParentStillConsumesUnconsumedFling() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
manager.setNativeId(parent, "ordinary-scroll-parent")
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedFling(0f, 1500f, false)
child.stopNestedScroll()
}
SystemClock.sleep(500)
instrumentation.runOnMainSync { assertTrue(parent.scrollY > 400) }
}
@Test fun consumedPanelFlingDoesNotStartParentFling() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
assertEquals(false, child.dispatchNestedFling(0f, 1500f, true))
child.stopNestedScroll()
assertEquals(400, parent.scrollY)
}
}
@Test fun panelInteriorScrollingLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 100)
assertEquals(100, child.scrollY)
assertEquals(400, parent.scrollY)
parent.scrollTo(0, 500)
assertEquals("Direct timeline scrolling remains available", 500, parent.scrollY)
}
}
private fun openPanel(): Pair<ReactScrollView, ReactScrollView> {
val started = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
activity = started
lateinit var parent: ReactScrollView
lateinit var child: ReactScrollView
instrumentation.runOnMainSync {
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(started)
SoLoader.init(started, OpenSourceMergedSoMapping)
val react = MountingReactContext(started.applicationContext)
val context = ThemedReactContext(react, started)
manager = PaseoScrollPackage().createViewManager(react, ReactScrollViewManager.REACT_CLASS) as ReactScrollViewManager
parent = manager.createViewInstance(context)
manager.setNativeId(parent, "agent-chat-scroll-native-virtualized")
child = manager.createViewInstance(context)
child.isNestedScrollingEnabled = true
val content = ReactViewGroup(context)
content.addView(child, FrameLayout.LayoutParams(300, 200).apply { topMargin = 400 })
parent.addView(content)
val childContent = ReactViewGroup(context)
child.addView(childContent)
started.setContentView(FrameLayout(started).apply { addView(parent, FrameLayout.LayoutParams(300, 400)) })
parent.layout(0, 0, 300, 400)
content.layout(0, 0, 300, 2000)
child.layout(0, 400, 300, 600)
childContent.layout(0, 0, 300, 800)
parent.scrollTo(0, 400)
}
return Pair(parent, child)
}
}
@@ -14,13 +14,10 @@ import com.facebook.react.views.scroll.ReactScrollView;
import com.facebook.react.views.scroll.ReactScrollViewHelper;
/**
* React Native's vertical scroll view with six corrections. Java, because the content-position
* React Native's vertical scroll view with five corrections. Java, because the content-position
* config type is internal to React Native's Kotlin module.
*/
final class PaseoScrollView extends ReactScrollView {
// The chat timeline, packages/app/src/agent-stream/strategy-native.tsx.
private static final String TIMELINE_NATIVE_ID = "agent-chat-scroll-native-virtualized";
// The chat timeline's end pin, packages/app/src/agent-stream/native-end-pin.tsx.
private static final String END_PIN_NATIVE_ID = "paseo-end-pin";
@@ -38,26 +35,6 @@ final class PaseoScrollView extends ReactScrollView {
super(context);
}
// A panel owns its gesture through its edges; remaining child motion must not move the chat
// behind it. The timeline's native identity stays present when its end pin is removed for
// reading history. Ordinary parents retain Android's nested-scroll handoff.
@Override
public void onNestedScroll(
View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
if (isTimeline()) return;
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
if (isTimeline() && !consumed) return true;
return super.onNestedFling(target, velocityX, velocityY, consumed);
}
private boolean isTimeline() {
return TIMELINE_NATIVE_ID.equals(getTag(R.id.view_tag_native_id));
}
@Override
public void setMaintainVisibleContentPosition(
@Nullable MaintainVisibleScrollPositionHelper.Config config) {
@@ -775,7 +775,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
extraData={renderHistoryMountedRow}
keyExtractor={keyExtractor}
testID="agent-chat-scroll"
// The Android scroll owner identifies the timeline to contain nested panel gestures.
nativeID="agent-chat-scroll-native-virtualized"
ListHeaderComponent={historyStartContent}
ListFooterComponent={liveAuxiliaryContent ?? undefined}
@@ -2,6 +2,11 @@ const { randomUUID } = require("node:crypto");
const { appendFileSync } = require("node:fs");
const { createInterface } = require("node:readline");
if (process.argv.slice(2).includes("--version")) {
process.stdout.write("1.5.18\n");
process.exit(0);
}
const eventsPath = process.argv[2];
const record = (event) => appendFileSync(eventsPath, JSON.stringify(event) + "\n");
const modes = {
+98 -14
View File
@@ -72,22 +72,33 @@ function boundaryViolations(entry: string, runtime: "shared" | "server" | "clien
return violations;
}
const typeCheckConfigPath = path.resolve(sourceDirectory, "../tsconfig.examples.json");
const typeCheckOptions = ts.parseJsonConfigFileContent(
ts.readConfigFile(typeCheckConfigPath, ts.sys.readFile).config,
ts.sys,
path.dirname(typeCheckConfigPath),
).options;
const typeCheckFile = path.resolve(
sourceDirectory,
"../../../plugin-examples/skill-example/client/example.tsx",
);
// Every snippet compiles against the same SDK, library, and dependency declarations. Parsing them
// once keeps each check to the snippet itself; a fresh parse per check can pass the test timeout
// on a slow runner.
const sharedSourceFiles = new Map<string, ts.SourceFile | undefined>();
function typeErrors(code: string): string[] {
const configPath = path.resolve(sourceDirectory, "../tsconfig.examples.json");
const { config } = ts.readConfigFile(configPath, ts.sys.readFile);
const { options } = ts.parseJsonConfigFileContent(config, ts.sys, path.dirname(configPath));
const file = path.resolve(
sourceDirectory,
"../../../plugin-examples/skill-example/client/example.tsx",
);
const host = ts.createCompilerHost(options);
const host = ts.createCompilerHost(typeCheckOptions);
const getSourceFile = host.getSourceFile;
host.getSourceFile = (name, language, ...rest) =>
path.resolve(name) === file
? ts.createSourceFile(name, code, language)
: getSourceFile.call(host, name, language, ...rest);
host.fileExists = (name) => path.resolve(name) === file || ts.sys.fileExists(name);
const program = ts.createProgram([file], options, host);
host.getSourceFile = (name, language, ...rest) => {
if (path.resolve(name) === typeCheckFile) return ts.createSourceFile(name, code, language);
if (!sharedSourceFiles.has(name)) {
sharedSourceFiles.set(name, getSourceFile.call(host, name, language, ...rest));
}
return sharedSourceFiles.get(name);
};
host.fileExists = (name) => path.resolve(name) === typeCheckFile || ts.sys.fileExists(name);
const program = ts.createProgram([typeCheckFile], typeCheckOptions, host);
return ts
.getPreEmitDiagnostics(program)
.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
@@ -779,3 +790,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>;
}
+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(),
}),
});
@@ -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.
+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);
}
},
};
}
@@ -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,214 @@
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;
}
// Every launch passes `shell: false`: the CLI ships as an executable. With a shell, Windows runs a
// missing bare name through cmd.exe, which prints a localized "not recognized" error instead of
// failing the spawn with ENOENT. A `.cmd` given as a full path still runs through cmd.exe.
function isNotFoundError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
(error.code === "ENOENT" || error.code === "ENOTDIR")
);
}
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,
shell: false,
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,
shell: false,
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,215 @@
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;
}
// Windows keeps the original case of environment names, often `Path`. Spreading process.env and
// setting `PATH` would leave the real `Path` in place beside it.
function envWithPath(searchPath: string): NodeJS.ProcessEnv {
const env = Object.fromEntries(
Object.entries(process.env).filter(([name]) => name.toUpperCase() !== "PATH"),
);
return { ...env, PATH: searchPath };
}
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: envWithPath(emptyDir),
});
const status = await provider.status({
paseo: unusedPaseo,
signal: new AbortController().signal,
});
expect(status).toEqual({
status: "unavailable",
reason: "cloudflared is not installed or not on PATH.",
installUrl: expect.stringContaining("cloudflare.com"),
fixHint: "Install cloudflared and make sure it is available on PATH.",
});
});
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 { binary } = 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({
readSettings: async () => ({ binaryPath: binary }),
});
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" }]);
});
});
+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,385 @@
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;
}
// Every launch passes `shell: false`: the CLI ships as an executable. With a shell, Windows runs a
// missing bare name through cmd.exe, which prints a localized "not recognized" error instead of
// failing the spawn with ENOENT. A `.cmd` given as a full path still runs through cmd.exe.
function isNotFoundError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
(error.code === "ENOENT" || error.code === "ENOTDIR")
);
}
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,
shell: false,
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,
shell: false,
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,
shell: false,
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,354 @@
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;
}
// Windows keeps the original case of environment names, often `Path`. Spreading process.env and
// setting `PATH` would leave the real `Path` in place beside it.
function envWithPath(searchPath: string): NodeJS.ProcessEnv {
const env = Object.fromEntries(
Object.entries(process.env).filter(([name]) => name.toUpperCase() !== "PATH"),
);
return { ...env, PATH: searchPath };
}
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: envWithPath(emptyDir),
});
const status = await provider.status({
paseo: unusedPaseo,
signal: new AbortController().signal,
});
expect(status).toEqual({
status: "unavailable",
reason: "tailscale CLI is not installed or not on PATH.",
installUrl: "https://tailscale.com/download",
fixHint: "Install Tailscale and make sure the tailscale CLI is on PATH.",
});
});
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);
});
});
+58 -9
View File
@@ -1,4 +1,4 @@
import { mkdtempSync, rmSync } from "node:fs";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -32,11 +32,13 @@ describe("zai usage source", () => {
process.env["USERPROFILE"] = homeDir;
for (const key of [
"APPDATA",
"XDG_CONFIG_HOME",
"COPILOT_TOKEN",
"GITHUB_TOKEN",
"GITHUB_PAT",
"CURSOR_ACCESS_TOKEN",
"CURSOR_TOKEN",
"Z_AI_API_KEY",
"ZAI_API_KEY",
"GLM_API_KEY",
"GROK_API_KEY",
@@ -116,11 +118,61 @@ describe("zai usage source", () => {
details: expect.arrayContaining([{ id: "status", label: "Status", value: "VALID" }]),
});
});
});
it("discovery returns a locator when fetch finds zai credentials", async () => {
const previous = process.env["ZAI_API_KEY"];
try {
it("fetches Z.ai usage from Z_AI_API_KEY, the name the glm-acp-agent CLI uses", async () => {
process.env["Z_AI_API_KEY"] = "zai_cli_token";
let authorization: string | null = null;
fetchApi = (async (_url: RequestInfo | URL, init?: RequestInit) => {
authorization = (init?.headers as Record<string, string> | undefined)?.Authorization ?? null;
return jsonResponse({ data: [{ productName: "GLM Coding Max", status: "VALID" }] });
}) as unknown as typeof fetch;
const zai = findProvider(await service().listUsage(), "zai");
expect(authorization).toBe("Bearer zai_cli_token");
expect(zai).toMatchObject({ status: "available", planLabel: "GLM Coding Max" });
});
it("reads Z.ai usage from the credentials file the glm-acp-agent CLI writes", async () => {
const configDir = join(homeDir, ".config", "glm-acp-agent");
mkdirSync(configDir, { recursive: true });
writeFileSync(
join(configDir, "credentials.json"),
JSON.stringify({ z_ai_api_key: "zai_file_token" }),
);
let authorization: string | null = null;
fetchApi = (async (_url: RequestInfo | URL, init?: RequestInit) => {
authorization = (init?.headers as Record<string, string> | undefined)?.Authorization ?? null;
return jsonResponse({ data: [{ productName: "GLM Coding Max", status: "VALID" }] });
}) as unknown as typeof fetch;
const zai = findProvider(await service().listUsage(), "zai");
expect(authorization).toBe("Bearer zai_file_token");
expect(zai).toMatchObject({ status: "available" });
});
it("honours XDG_CONFIG_HOME for the credentials file", async () => {
const configDir = join(homeDir, "xdg", "glm-acp-agent");
mkdirSync(configDir, { recursive: true });
writeFileSync(
join(configDir, "credentials.json"),
JSON.stringify({ z_ai_api_key: "zai_xdg_token" }),
);
process.env["XDG_CONFIG_HOME"] = join(homeDir, "xdg");
let authorization: string | null = null;
fetchApi = (async (_url: RequestInfo | URL, init?: RequestInit) => {
authorization = (init?.headers as Record<string, string> | undefined)?.Authorization ?? null;
return jsonResponse({ data: [{ productName: "GLM Coding Max", status: "VALID" }] });
}) as unknown as typeof fetch;
const zai = findProvider(await service().listUsage(), "zai");
expect(authorization).toBe("Bearer zai_xdg_token");
expect(zai).toMatchObject({ status: "available" });
});
it("discovery returns a locator when fetch finds zai credentials", async () => {
process.env["ZAI_API_KEY"] = "fixture-token";
let requested = false;
await fetchFirst(async () => {
@@ -131,10 +183,7 @@ it("discovery returns a locator when fetch finds zai credentials", async () => {
expect(await discover()).toEqual([
{ key: "default", input: { store: "env", locator: "ZAI_API_KEY" } },
]);
} finally {
if (previous === undefined) delete process.env["ZAI_API_KEY"];
else process.env["ZAI_API_KEY"] = previous;
}
});
});
describe("account discovery", () => {
+37 -2
View File
@@ -1,4 +1,7 @@
import type { UsageInput } from "../shared/input.js";
import { promises as fs } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { z } from "zod";
import {
unavailable,
@@ -25,11 +28,16 @@ const ZaiUsageResponseSchema = z.object({
.optional(),
});
/** The credentials file the `glm-acp-agent` CLI writes. */
const ZaiCredentialsSchema = z.object({
z_ai_api_key: z.string().optional(),
});
export async function fetchUsage(
input: UsageInput,
fetchApi: typeof fetch = fetch,
): Promise<UsageReport> {
const token = process.env[input.locator];
const token = await readToken(input);
if (!token) throw new Error("Z.ai login store no longer exists");
const res = await fetchApi("https://api.z.ai/api/biz/subscription/list", {
@@ -64,9 +72,36 @@ export async function fetchUsage(
};
}
/**
* The Z.AI API key comes from the environment or from the credentials file the
* `glm-acp-agent` CLI writes. The CLI names the variable `Z_AI_API_KEY`; the
* older `ZAI_API_KEY` spelling is still accepted.
*/
async function readToken(input: UsageInput): Promise<string | undefined> {
if (input.store === "env") {
return process.env[input.locator];
}
try {
const raw: unknown = JSON.parse(await fs.readFile(input.locator, "utf8"));
return ZaiCredentialsSchema.parse(raw).z_ai_api_key;
} catch {
return undefined;
}
}
export async function discover(): Promise<UsageAccount[]> {
for (const locator of ["ZAI_API_KEY", "GLM_API_KEY"]) {
for (const locator of ["Z_AI_API_KEY", "ZAI_API_KEY", "GLM_API_KEY"]) {
if (process.env[locator]) return [{ key: "default", input: { store: "env", locator } }];
}
const credentialsPath = join(
process.env.XDG_CONFIG_HOME || join(homedir(), ".config"),
"glm-acp-agent",
"credentials.json",
);
if (await readToken({ store: "file", locator: credentialsPath })) {
return [{ key: "default", input: { store: "file", locator: credentialsPath } }];
}
return [];
}
+1 -1
View File
@@ -1,7 +1,7 @@
import { z } from "zod";
export const inputSchema = z
.object({
store: z.literal("env"),
store: z.enum(["env", "file"]),
locator: z.string().min(1),
})
.strict();
+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 移除剩余的注册之前运行。