Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 524116e111 fix(plugins): harden worktree manager lifecycle, rollback, and schema 2026-11-20 08:14:06 +01:00
Mohamed Boudra 1230337165 feat(plugins): let plugins manage worktree create, remove, and restore
Adds server.registerWorktreeManager({ create, remove?, restore? }) so external worktree tools such as Worktrunk can own Git worktree creation, removal, and restoration instead of overloading worktree.create.before.

Keeping worktree.create.before purely transformative preserves multi-plugin chaining, rollback, and the 30s hook budget, while giving manager operations a 120s budget matching git worktree commands. Paseo snapshots existing worktrees before create so managers cannot hijack pre-existing user worktrees, writes comparison-base and owning plugin metadata into paseo/worktree.json and the workspace record, saves refs/paseo/kept-commits before removal so restore stays safe, and falls back to built-in Git if a manager declines or is disabled.
2026-11-20 07:52:07 +01:00
Mohamed Boudra b3d860cce2 feat(website): apply new Paseo and Paseo Hub branding (#10271)
Replace the website's legacy Paseo mark and plain-text headers with the canonical Paseo butterfly and Paseo Hub flower marks and Plus Jakarta Sans SemiBold lockups from assets/brand/.

Sourcing the website SVG components directly from assets/brand/ keeps mark proportions, 94% butterfly optical balance, and outlined wordmarks aligned with the canonical assets without shipping an extra webfont or duplicating paths across components.
2026-11-20 13:04:59 +07:00
James DumayandJames Dumay 7b9c6a7d4a feat(providers): bundle goose plugin with multi-provider model selection (#9719)
Moves goose into a built-in opt-in provider plugin (`plugins/goose-provider`) and lists models from every provider configured in goose.

- Bundles `plugins/goose-provider` with `server_info.features.gooseProvider`, legacy host catalog fallback, legacy `extends: "acp"` config migration, and legacy session handle decoding (`COMPAT(gooseProvider)`).
- Adds `context.request(method, params)` and synchronous `config(state, context)` hooks to `@getpaseo/plugin/server/acp`.
- Queries goose's provider inventory RPC during discovery to expose `<provider>/<model>` entries (falling back to the base catalog if unavailable), switches provider before model on selection, and namespaces session config snapshots.

Co-authored-by: James Dumay <james@generalinference.xyz>
2026-11-20 12:35:11 +07:00
74 changed files with 3355 additions and 123 deletions
+12
View File
@@ -471,6 +471,18 @@ Workspace records decide ownership, including explicit non-ownership after recov
ownership checks prefer the marker-verified worktree root over the legacy
path shape: a plugin can place a worktree several directories below the default worktrees root.
A plugin can also take over worktree creation, removal, and restoration with
`server.registerWorktreeManager({ create, remove?, restore? })`. It runs after
`worktree.create.before` and before `worktree.create.after`, with a 120-second timeout matching Git
worktree commands. Paseo snapshots existing worktree paths before calling `create` so a manager
cannot adopt a pre-existing directory as Paseo-owned, verifies Git worktree postconditions, records
`worktreeManagerPluginId` in `paseo/worktree.json` and on the workspace record,
and skips first-agent branch auto-rename. Removal saves `refs/paseo/kept-commits/<sha>` before
calling the owning plugin's `remove`, and both `remove` and `restore` carry `untrusted` for fork
change requests and fall back to built-in Git when the plugin declines or is disabled. See the
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
`plugin-examples/worktrunk`.
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
@@ -29,7 +29,12 @@ const ACP_PROVIDER = {
interface ProviderCatalogDaemonClient {
getLastServerInfoMessage(): {
features?: { fxProvider?: boolean; hopliteProvider?: boolean; plugins?: boolean };
features?: {
gooseProvider?: boolean;
fxProvider?: boolean;
hopliteProvider?: boolean;
plugins?: boolean;
};
} | null;
connect(): Promise<void>;
close(): Promise<void>;
@@ -204,3 +209,47 @@ test("model selector excludes Hoplite before opt-in", async ({ page }, testInfo)
await client.close();
}
});
test("adds bundled goose from the catalog", async ({ page }) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "goose-catalog-e2e",
});
try {
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(true);
await client.patchDaemonConfig({ removeProviders: ["goose"] });
await gotoAppShell(page);
await addGooseFromSettings(page, getServerId());
expect((await client.getDaemonConfig()).config.providers?.goose).toEqual({ enabled: true });
} finally {
await client.patchDaemonConfig({ removeProviders: ["goose"] });
await client.close();
}
});
test("adds goose through ACP on an older host", async ({ page, outdatedDaemon }) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "goose-catalog-old-host",
port: Number(new URL(`http://${outdatedDaemon.endpoint}`).port),
});
try {
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(false);
await seedSavedSettingsHosts(page, [outdatedDaemon]);
await page.reload();
await addGooseFromSettings(page, outdatedDaemon.serverId);
expect((await client.getDaemonConfig()).config.providers?.goose).toMatchObject({
extends: "acp",
command: ["goose", "acp"],
});
} finally {
await client.close();
}
});
async function addGooseFromSettings(page: import("@playwright/test").Page, serverId: string) {
await openSettings(page);
await openSettingsHost(page, serverId);
await openSettingsHostSection(page, serverId, "providers");
await openAddProvider(page);
await installAcpCatalogProvider(page, "goose");
await expectProviderInstalledInSettings(page, "goose");
}
@@ -224,6 +224,7 @@ const CATALOG_DATA = [
},
{
id: "goose",
bundledProvider: { hostFeature: "gooseProvider" },
title: "goose",
description: "A local, extensible, open source AI agent that automates engineering tasks",
version: "1.33.1",
@@ -150,3 +150,21 @@ describe("ACP provider catalog", () => {
});
});
});
it("adds bundled goose on capable hosts and uses the ACP config on older hosts", () => {
const goose = findProvider("goose");
expect(buildAcpProviderConfigPatch(goose, (feature) => feature === "gooseProvider")).toEqual({
providers: { goose: { enabled: true } },
});
expect(buildAcpProviderConfigPatch(goose)).toEqual({
providers: {
goose: {
extends: "acp",
label: "goose",
description: goose.description,
command: ["goose", "acp"],
env: {},
},
},
});
});
@@ -19,12 +19,16 @@ export function buildAcpProviderConfigPatch(
hostSupports: (feature: HostFeatureName) => boolean = () => false,
): MutableDaemonConfigPatch {
if (entry.bundledProvider) {
const feature = entry.bundledProvider.hostFeature;
if (hostSupports(feature)) {
return { providers: { [entry.id]: { enabled: true } } };
}
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
if (!hostSupports(entry.bundledProvider.hostFeature)) {
if (feature !== "gooseProvider") {
throw new Error(`Update the host to add ${entry.title}.`);
}
return { providers: { [entry.id]: { enabled: true } } };
}
return {
providers: {
+65
View File
@@ -589,3 +589,68 @@ describe("sidebar data SDK boundary", () => {
).toEqual([]);
});
});
describe("worktree manager SDK boundary", () => {
it("types create, remove, and restore handlers with discriminated results and cleanup", () => {
expect(
typeErrors(`
import type {
PluginServerContext,
WorktreeManagerRegistration,
PluginWorktreeCreateInput,
PluginWorktreeCreateResult,
PluginWorktreeRemoveRequest,
PluginWorktreeRemoveResult,
PluginWorktreeRestoreRequest,
PluginWorktreeRestoreResult,
} from "@getpaseo/plugin/server";
export default function contribute(server: PluginServerContext) {
const manager: WorktreeManagerRegistration = {
async create(request: PluginWorktreeCreateInput, { paseo, signal }) {
if (request.kind === "branch-off") {
const start: string = request.startPoint ?? request.baseRef;
// @ts-expect-error startPoint is read-only
request.startPoint = "other";
if (!start) return;
}
if (signal.aborted) return;
void paseo;
const result: PluginWorktreeCreateResult = { type: "created", path: request.path };
return result;
},
async remove(request: PluginWorktreeRemoveRequest, { signal }) {
const reason: "archive" | "rollback" = request.reason;
const force: boolean = request.force;
const untrusted: boolean = request.untrusted;
// @ts-expect-error remove request fields are read-only
request.path = "/other";
if (!reason || !force || untrusted || signal.aborted) return;
const result: PluginWorktreeRemoveResult = { type: "removed" };
return result;
},
async restore(request: PluginWorktreeRestoreRequest) {
const untrusted: boolean = request.untrusted;
void untrusted;
if (request.target.type === "commit") return;
if (request.target.type === "from-base") {
const base: string = request.target.baseRef;
void base;
}
const result: PluginWorktreeRestoreResult = { type: "restored", path: request.path };
return result;
},
};
const dispose: () => void = server.registerWorktreeManager(manager);
server.registerWorktreeManager({
// @ts-expect-error create result requires discriminant
async create() {
return { path: "/tmp/wt" };
},
});
return dispose;
}
`),
).toEqual([]);
});
});
@@ -23,6 +23,8 @@ import { z } from "zod";
import type {
AcpConfigAccess,
AcpConfigChange,
AcpConfigureContext,
AcpRequest,
AcpToolCallSnapshot,
AcpTransformer,
AcpVendorUpdate,
@@ -261,10 +263,10 @@ async function discover(
});
try {
let catalog = await runtime.discover(input.cwd);
const config = runtime.configAccess();
const context = runtime.configContext();
for (const transformer of state.options.transformers ?? []) {
if (transformer.discover) {
catalog = await transformer.discover(catalog, { sessionId: "catalog", config });
catalog = await transformer.discover(catalog, context);
}
}
state.emit({ type: "catalog", requestId: input.requestId, catalog });
@@ -902,16 +904,13 @@ class AcpRuntime {
this.autoAccept = enableAutoAccept;
return;
}
const access = this.configAccess();
const context: AcpConfigureContext = {
...this.configContext(),
catalog: () => toProviderCatalog(this.modes, this.configOptions),
apply: (nativeChange) => this.applyNativeConfigChange(nativeChange),
};
for (const transformer of this.transformers) {
if (
(await transformer.configure?.(change, {
sessionId: this.options.boundarySessionId,
config: access,
catalog: () => toProviderCatalog(this.modes, this.configOptions),
apply: (nativeChange) => this.applyNativeConfigChange(nativeChange),
})) === "handled"
) {
if ((await transformer.configure?.(change, context)) === "handled") {
return;
}
}
@@ -951,7 +950,20 @@ class AcpRuntime {
this.configOptions = response.configOptions;
}
configAccess(): AcpConfigAccess {
configContext() {
return {
sessionId: this.options.boundarySessionId,
config: this.configAccess(),
request: this.request,
};
}
private readonly request: AcpRequest = async (method, params) =>
jsonValue(
await this.call(this.connection.extMethod(method, params as Record<string, unknown>)),
);
private configAccess(): AcpConfigAccess {
return {
read: async () => configValues(this.configOptions),
set: async (id, value) => {
@@ -989,6 +1001,10 @@ class AcpRuntime {
modes: [...config.modes, { ...autoAcceptMode.mode, isUnattended: true }],
};
}
const context = { sessionId: this.options.boundarySessionId };
for (const transformer of this.transformers) {
config = transformer.config?.(config, context) ?? config;
}
this.emit({
type: "session.config",
sessionId: this.options.boundarySessionId,
+132
View File
@@ -2320,3 +2320,135 @@ describe("ACP session history replay", () => {
}
});
});
it("sends extension requests from discovery and configure and preserves JSON-RPC errors", async () => {
const { connector, instances } = connectorHarness({
handleRequest(instance, request) {
if (request.method === "_example/catalog") {
instance.respond(request, { model: "vendor-model" });
return true;
}
if (request.method === "_example/select") {
instance.reject(request, "Vendor rejected the selection");
return true;
}
return false;
},
});
const registration = runAcpProvider({
id: "extensions",
label: "Extensions",
connector,
transformers: [
{
async discover(catalog, { request }) {
expect(await request("_example/catalog", { scope: "all" })).toEqual({
model: "vendor-model",
});
return { ...catalog, defaultModel: "vendor-model" };
},
async configure(change, { request }) {
await expect(request("_example/select", { model: change.value })).rejects.toMatchObject({
code: -32603,
message: "Vendor rejected the selection",
});
return "handled";
},
},
],
});
const connection = await registration.connect({
versions: [1],
capabilities: ["session.configure"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send({ type: "catalog", requestId: "catalog" });
expect(
await waitForEvent(
events,
(event) => event.type === "catalog" || event.type === "request.failed",
),
).toMatchObject({ type: "catalog", catalog: { defaultModel: "vendor-model" } });
expect(instances[1].requests).toContainEqual(
expect.objectContaining({
method: "_example/catalog",
params: { scope: "all" },
}),
);
const input = openInput();
await connection.send({ ...input, config: { ...input.config, model: "vendor-model" } });
expect(
await waitForEvent(
events,
(event) => event.type === "session.ready" || event.type === "request.failed",
),
).toMatchObject({ type: "session.ready" });
expect(instances[2].requests).toContainEqual(
expect.objectContaining({
method: "_example/select",
params: { model: "vendor-model" },
}),
);
} finally {
await connection.close();
}
});
it("rewrites the session-ready, notification and configure-commit config snapshots", async () => {
const modelOption = {
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: "first",
options: ["first", "second", "third"].map((value) => ({ name: value, value })),
};
const { connector, instances } = connectorHarness({ configOptions: [modelOption] });
const registration = runAcpProvider({
id: "config-transformer",
label: "Config Transformer",
connector,
transformers: [
{
config(state, { sessionId }) {
return { ...state, model: `${sessionId}/${state.model}` };
},
},
],
});
const connection = await registration.connect({
versions: [1],
capabilities: ["session.configure"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
const models = () =>
events.flatMap((event) => (event.type === "session.config" ? [event.config.model] : []));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
expect(models()).toEqual(["session-1/first"]);
instances[1].notify("session/update", {
sessionId: "connector-session",
update: {
sessionUpdate: "config_option_update",
configOptions: [{ ...modelOption, currentValue: "second" }],
},
});
await expect.poll(models).toEqual(["session-1/first", "session-1/second"]);
await connection.send({
type: "session.configure",
requestId: "configure",
sessionId: "session-1",
changes: { model: "third" },
});
await expect.poll(models).toEqual(["session-1/first", "session-1/second", "session-1/third"]);
} finally {
await connection.close();
}
});
+7
View File
@@ -70,12 +70,17 @@ export interface AcpConfigAccess {
set(id: string, value: JsonValue): Promise<void>;
}
/** Sends an ACP extension request to the agent. Rejects with the agent's JSON-RPC error. */
export type AcpRequest = (method: string, params: JsonValue) => Promise<JsonValue>;
export interface AcpDiscoveryContext extends AcpContext {
config: AcpConfigAccess;
request: AcpRequest;
}
export interface AcpConfigureContext extends AcpContext {
config: AcpConfigAccess;
request: AcpRequest;
catalog(): ProviderCatalog;
apply(change: AcpConfigChange): Promise<void>;
}
@@ -117,6 +122,8 @@ export interface AcpTransformer {
context: AcpDiscoveryContext,
): Promise<ProviderCatalog> | ProviderCatalog;
configure?(change: AcpConfigChange, context: AcpConfigureContext): Promise<"handled" | "pass">;
/** Rewrites every session config snapshot before Paseo sees it. */
config?(state: ProviderConfigState, context: AcpContext): ProviderConfigState;
notification?(
notification: { method: string; params: JsonValue },
context: AcpContext,
+2
View File
@@ -5,6 +5,7 @@ import type { PluginCleanup } from "../contracts.js";
import type { ProviderRegistration } from "./provider.js";
import type { UsageSourceRegistration } from "./usage.js";
import type { PluginLifecycleRegistration } from "./lifecycle.js";
import type { WorktreeManagerRegistration } from "./worktree.js";
export interface PluginHandlerContext {
paseo: PaseoApi;
@@ -64,6 +65,7 @@ export interface PluginServerContext extends PluginLifecycleRegistration {
): void;
registerProvider(provider: ProviderRegistration): void;
registerUsageSource(source: UsageSourceRegistration): void;
registerWorktreeManager(manager: WorktreeManagerRegistration): () => void;
}
export type PluginServerContribution = (server: PluginServerContext) => PluginCleanup;
+11
View File
@@ -35,3 +35,14 @@ export { spawnProcess, execCommand, terminateProcess } from "./process.js";
export { defineAgentTool } from "./agent-tools.js";
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
export type {
PluginWorktreeContext,
PluginWorktreeCreateInput,
PluginWorktreeCreateResult,
PluginWorktreeRemoveRequest,
PluginWorktreeRemoveResult,
PluginWorktreeRestoreTarget,
PluginWorktreeRestoreRequest,
PluginWorktreeRestoreResult,
WorktreeManagerRegistration,
} from "./worktree.js";
+6 -1
View File
@@ -37,7 +37,12 @@ export type PluginWorktreeCreateRequest = {
slug: string;
path: string;
} & (
| { kind: "branch-off"; baseRef: string }
| {
kind: "branch-off";
baseRef: string;
/** Where the new branch starts when that is not `baseRef`, such as a fork's head. */
readonly startPoint?: string;
}
| { kind: "checkout-branch" }
| {
kind: "checkout-change-request";
+64
View File
@@ -0,0 +1,64 @@
import type { PluginHookContext, PluginWorktreeCreateRequest } from "./lifecycle.js";
/** Context passed to worktree manager callbacks. */
export type PluginWorktreeContext = PluginHookContext;
/** Resolved creation request handed to a worktree manager after `worktree.create.before`. */
export type PluginWorktreeCreateInput = PluginWorktreeCreateRequest;
/** Return `{ type: "created", path }` to claim creation, or `undefined` to decline. */
export interface PluginWorktreeCreateResult {
type: "created";
path: string;
}
export interface PluginWorktreeRemoveRequest {
readonly repoRoot: string | null;
readonly path: string;
readonly branch: string | null;
readonly reason: "archive" | "rollback";
readonly force: boolean;
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
}
/** Return `{ type: "removed" }` after removing the worktree, or `undefined` to fall back to Git. */
export interface PluginWorktreeRemoveResult {
type: "removed";
}
export type PluginWorktreeRestoreTarget =
| { readonly type: "branch"; readonly branch: string }
| { readonly type: "commit"; readonly commit: string }
| { readonly type: "from-base"; readonly branch: string; readonly baseRef: string };
export interface PluginWorktreeRestoreRequest {
readonly repoRoot: string;
/** Recorded path the worktree must be restored to. */
readonly path: string;
readonly target: PluginWorktreeRestoreTarget;
readonly baseRef: string | null;
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
}
/** Return `{ type: "restored", path }` after recreating the worktree, or `undefined` to fall back to Git. */
export interface PluginWorktreeRestoreResult {
type: "restored";
path: string;
}
export interface WorktreeManagerRegistration {
create(
request: PluginWorktreeCreateInput,
context: PluginWorktreeContext,
): Promise<PluginWorktreeCreateResult | void>;
remove?(
request: PluginWorktreeRemoveRequest,
context: PluginWorktreeContext,
): Promise<PluginWorktreeRemoveResult | void>;
restore?(
request: PluginWorktreeRestoreRequest,
context: PluginWorktreeContext,
): Promise<PluginWorktreeRestoreResult | void>;
}
@@ -814,7 +814,7 @@ describe("checkout PR schemas", () => {
});
test.each(
["hopliteProvider", "fxProvider"].flatMap((name) =>
["hopliteProvider", "fxProvider", "gooseProvider"].flatMap((name) =>
[undefined, false, true].map((value) => [name, value] as const),
),
)("accepts optional bundled provider capability (%s: %s)", (name, value) => {
+2
View File
@@ -4151,6 +4151,8 @@ export const ServerInfoStatusPayloadSchema = z
hopliteProvider: z.boolean().optional(),
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
fxProvider: z.boolean().optional(),
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
gooseProvider: z.boolean().optional(),
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
importSessionWorkspaceTarget: z.boolean().optional(),
// COMPAT(importSessionSearch): added in v0.8.0, remove gate after 2027-03-02.
@@ -17,10 +17,12 @@ import type {
} from "../messages.js";
import type { AgentManager, AgentSubscriber, SubscribeOptions } from "./agent-manager.js";
import type { AgentStorage } from "./agent-storage.js";
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
interface CreateAgentLifecycleDispatchDependencies {
paseoHome: string;
worktreesRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -184,6 +186,7 @@ export class CreateAgentLifecycleDispatch {
{
paseoHome: this.dependencies.paseoHome,
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
worktreeManagers: this.dependencies.worktreeManagers,
github: this.dependencies.github,
workspaceGitService: this.dependencies.workspaceGitService,
agentManager: this.dependencies.agentManager,
@@ -2788,3 +2788,29 @@ test("plugin provider import launches with runtime MCP servers and returns only
await registry.shutdown();
}
});
test("resumes a goose session saved by the generic ACP provider", async () => {
const logger = createTestLogger();
const harness = createProviderHarness();
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([{ ...harness.registration, id: "goose" }]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const client = registry.goose.createClient(logger);
try {
const session = await client.resumeSession(
{
provider: "goose",
sessionId: "native-goose-session",
nativeHandle: "native-goose-session",
},
{ provider: "goose", cwd: "/tmp" },
);
expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({
persistence: { version: 1, data: { sessionId: "native-goose-session" } },
});
await session.close();
} finally {
await plugins.shutdown();
}
});
@@ -2174,6 +2174,10 @@ function decodePersistence(handle: AgentPersistenceHandle): ProviderPersistence
if (fromMetadata !== undefined) {
return ProviderPersistenceSchema.parse(fromMetadata);
}
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy handles have migrated.
if (handle.provider === "goose" && !handle.sessionId.startsWith("plugin:")) {
return { version: 1, data: { sessionId: handle.sessionId } };
}
return decodePersistenceId(handle.sessionId);
}
@@ -139,6 +139,7 @@ export interface PaseoToolHostDependencies {
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
>;
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
emitWorkspaceUpdatesForWorkspaceIds?: ArchiveDependencies["emitWorkspaceUpdatesForWorkspaceIds"];
@@ -3409,6 +3410,7 @@ function archiveWorktreeDependencies(
return {
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.worktreesRoot,
worktreeManagers: options.worktreeManagers,
github: options.github,
workspaceGitService: options.workspaceGitService,
agentManager: context.agentManager,
@@ -16,10 +16,12 @@ import type { ForgeService } from "../../services/forge-service.js";
import type { TerminalManager } from "../../terminal/terminal-manager.js";
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
import type { WorkspaceArchiveContext } from "../workspace-registry.js";
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
export interface AutoArchiveArchiveOptions {
paseoHome: string;
paseoWorktreesBaseRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
daemonConfigStore: DaemonConfigStore;
workspaceGitService: WorkspaceGitServiceImpl;
github: ForgeService;
@@ -99,6 +101,7 @@ export async function archiveIfSafe(input: {
{
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot,
worktreeManagers: options.worktreeManagers,
github: options.github,
workspaceGitService: options.workspaceGitService,
agentManager: options.agentManager,
+8
View File
@@ -1160,6 +1160,8 @@ export async function createPaseoDaemon(
worktreeRoot: workspace.worktreeRoot,
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
mainRepoRoot: workspace.mainRepoRoot,
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
untrustedSource: workspace.untrustedSource,
}));
};
const markWorkspaceArchivingExternal = (workspaceIds: Iterable<string>, archivingAt: string) => {
@@ -1218,6 +1220,7 @@ export async function createPaseoDaemon(
setupAutoArchiveOnMerge({
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
daemonConfigStore,
workspaceGitService,
github,
@@ -1246,6 +1249,7 @@ export async function createPaseoDaemon(
createPaseoWorktree: async (workflowInput, workflowOptions) => {
return createRegisteredPaseoWorktree(workflowInput, {
lifecycle: pluginRuntime,
worktreeManagers: pluginRuntime,
github,
...(workflowOptions?.resolveDefaultBranch
? {
@@ -1306,6 +1310,7 @@ export async function createPaseoDaemon(
{
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
github,
workspaceGitService,
agentManager,
@@ -1330,6 +1335,7 @@ export async function createPaseoDaemon(
const hubAgentLifecycle = new CreateAgentLifecycleDispatch({
paseoHome: config.paseoHome,
worktreesRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
agentManager,
agentStorage,
github,
@@ -1428,6 +1434,7 @@ export async function createPaseoDaemon(
{
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
github,
workspaceGitService,
agentManager,
@@ -1577,6 +1584,7 @@ export async function createPaseoDaemon(
daemonConfigStore,
github,
workspaceGitService,
worktreeManagers: pluginRuntime,
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
listActiveWorkspaces: listActiveWorkspacesExternal,
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
@@ -0,0 +1,88 @@
// Local ACP peer shaped like `goose acp`.
const readline = require("node:readline");
const inventory = {
openrouter: { name: "OpenRouter", model: "anthropic/claude-sonnet-4.5" },
openai: { name: "OpenAI", model: "gpt-4o" },
anthropic: { name: "Anthropic", model: "sonnet" },
};
let provider = "goose";
let model = inventory.openrouter.model;
const select = (id, currentValue, values) => ({
id,
name: id,
...(id === "model" ? { category: "model" } : {}),
type: "select",
currentValue,
options: values.map((value) => ({ value, name: value })),
});
const configOptions = () => [
select("provider", provider, ["goose", ...Object.keys(inventory)]),
select("model", model, [inventory[provider === "goose" ? "openrouter" : provider].model]),
];
const send = (message) =>
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method, params } = JSON.parse(line);
if (id === undefined) return;
let result;
switch (method) {
case "initialize":
result = { protocolVersion: 1, agentCapabilities: { loadSession: true }, authMethods: [] };
break;
case "session/new":
case "session/load":
result = { sessionId: "goose-fixture", configOptions: configOptions() };
break;
case "_goose/unstable/providers/list":
result = {
entries: Object.entries(inventory).map(([providerId, entry]) => ({
providerId,
providerName: entry.name,
configured: providerId !== "anthropic",
models: [{ id: entry.model, name: entry.model }],
})),
};
break;
case "_goose/unstable/config/read":
result = {
value: params.key === "GOOSE_PROVIDER" ? "openrouter" : inventory.openrouter.model,
};
break;
case "session/set_config_option":
if (params.configId === "provider") {
provider = params.value;
model = inventory[provider === "goose" ? "openrouter" : provider].model;
} else if (params.configId === "model") {
if (params.value !== inventory[provider === "goose" ? "openrouter" : provider].model) {
send({ id, error: { code: -32602, message: "Model unavailable for selected provider" } });
return;
}
model = params.value;
}
result = { configOptions: configOptions() };
break;
case "session/prompt":
send({
method: "session/update",
params: {
sessionId: params.sessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: `${provider}/${model}` },
},
},
});
result = { stopReason: "end_turn" };
break;
case "session/close":
result = {};
break;
default:
send({ id, error: { code: -32601, message: "Method not found" } });
return;
}
send({ id, result });
});
@@ -519,3 +519,60 @@ test("a provider update outlives the client that started it and a new client rea
await daemon.close();
}
}, 60000);
test("bundled goose lists configured providers and switches models across providers", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-goose-models-"));
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: root,
cleanup: false,
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, ["goose-provider"]),
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.16.0",
});
const openRouterModel = "openrouter/anthropic/claude-sonnet-4.5";
const openAiModel = "openai/gpt-4o";
try {
await client.connect();
await client.fetchAgents({ subscribe: {} });
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(true);
expect(
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "goose"),
).toBe(false);
await client.patchDaemonConfig({
providers: {
goose: {
enabled: true,
command: [process.execPath, path.resolve(import.meta.dirname, "goose-fixture.cjs")],
},
},
});
const catalog = await client.listProviderModels("goose", { cwd: root });
expect(catalog.error).toBeNull();
expect(catalog.models.map((model) => [model.id, model.isDefault === true])).toEqual([
[openRouterModel, true],
[openAiModel, false],
]);
const agent = await client.createAgent({ provider: "goose", cwd: root, model: openAiModel });
await client.sendMessage(agent.id, "Which provider and model are you running?");
expect((await client.waitForFinish(agent.id, 10_000)).status).toBe("idle");
await client.setAgentModel(agent.id, openRouterModel);
await client.sendMessage(agent.id, "Which provider and model are you running now?");
expect((await client.waitForFinish(agent.id, 10_000)).status).toBe("idle");
expect((await client.fetchAgent(agent.id))?.agent.model).toBe(openRouterModel);
const timeline = await client.fetchAgentTimeline(agent.id, { limit: 100 });
expect(
timeline.entries.flatMap(({ item }) =>
item.type === "assistant_message" ? [item.text] : [],
),
).toEqual([openAiModel, openRouterModel]);
} finally {
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true });
}
}, 60_000);
@@ -1,5 +1,6 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import { stat } from "node:fs/promises";
import { resolve } from "node:path";
@@ -63,6 +64,7 @@ export interface AttemptFirstAgentBranchAutoNameResult {
export interface CreatePaseoWorktreeDeps extends CreateWorktreeCoreDeps {
lifecycle?: Pick<PluginLifecycle, "wait" | "before">;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "createWorktree" | "removeWorktree">;
workspaceGitService: WorkspaceGitService;
workspaceProvisioning: Pick<WorkspaceProvisioningService, "createWorkspaceForWorktree">;
}
@@ -114,6 +116,7 @@ async function createPaseoWorktreeWithPriority(
worktreeRoot: createdWorktree.worktree.worktreePath,
branch: createdWorktree.worktree.branchName || null,
baseBranch: createdWorktree.worktree.comparisonBaseRef,
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
title: input.title?.trim() || resolveFirstAgentPromptTitle(input.firstAgentContext),
metadata: input.metadata,
expectsInitialAgent: Boolean(input.firstAgentContext),
@@ -152,6 +155,12 @@ async function createPaseoWorktreeWithPriority(
teardownCwds: [],
paseoHome: input.paseoHome,
worktreesBaseRoot: input.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
removeReason: "rollback",
untrusted:
createdWorktree.intent.kind === "checkout-change-request" &&
Boolean(createdWorktree.intent.headRepository),
},
error,
);
@@ -286,6 +295,10 @@ async function maybeMarkFirstAgentBranchAutoNameEligible(options: {
if (!createdWorktree.created || createdWorktree.intent.kind !== "branch-off") {
return;
}
// A worktree manager plugin owns branch and directory naming, so skip silent renames.
if (createdWorktree.worktree.worktreeManagerPluginId) {
return;
}
// A branch the caller named is their choice; only a placeholder slug is replaced.
if (input.branchName !== undefined) {
return;
@@ -1089,3 +1089,31 @@ describe("speech provider config normalization", () => {
}
});
});
test.each([
["goose", "acp"],
["/opt/bin/goose", "acp"],
])(
"migrates the legacy goose entry and preserves command overrides (%s %s)",
(binary, subcommand) => {
const command = [binary, subcommand];
const overrides = {
enabled: false,
label: "My goose",
env: { GOOSE_PROVIDER: "openai" },
models: [{ id: "primary", label: "Primary" }],
additionalModels: [{ id: "secondary", label: "Secondary" }],
};
const parsed = PersistedConfigSchema.parse({
agents: {
providers: {
goose: { ...overrides, extends: "acp", description: "Old description", command },
},
},
});
expect(parsed.agents?.providers?.goose).toEqual({
...overrides,
...(command[0] === "goose" ? {} : { command }),
});
},
);
+21 -5
View File
@@ -199,16 +199,32 @@ function isLegacyProviderEntry(value: unknown): boolean {
}
function normalizeAgentProviders(value: unknown): unknown {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return value;
if (!isConfigRecord(value)) return value;
let rawProviders = value;
const goose = configRecord(value.goose);
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy configs have migrated.
if (goose?.extends === "acp") {
const { extends: _base, description: _description, command, ...overrides } = goose;
const usesDefaultCommand =
Array.isArray(command) &&
command.length === 2 &&
command[0] === "goose" &&
command[1] === "acp";
rawProviders = {
...value,
goose: {
...overrides,
...(command !== undefined && !usesDefaultCommand ? { command } : {}),
},
};
}
const rawProviders = value as Record<string, unknown>;
const hasLegacyEntries = Object.values(rawProviders).some((entry) =>
isLegacyProviderEntry(entry),
);
if (!hasLegacyEntries) {
return value;
return rawProviders;
}
const legacyEntries: Record<string, unknown> = {};
@@ -224,7 +240,7 @@ function normalizeAgentProviders(value: unknown): unknown {
const parsedLegacyEntries = AgentProviderRuntimeSettingsMapSchema.safeParse(legacyEntries);
if (!parsedLegacyEntries.success) {
return value;
return rawProviders;
}
return {
@@ -9,6 +9,7 @@ export const builtinPlugins = [
"copilot-usage-source",
"cursor-usage-source",
"fx-provider",
"goose-provider",
"grok-usage-source",
"hoplite-provider",
"kimi-usage-source",
+25 -1
View File
@@ -24,7 +24,7 @@ import { type ManagedPluginCandidate, ManagedPluginSources } from "./managed-sou
import { readPluginManifest } from "./manifest.js";
import { expandTilde } from "../../utils/path.js";
import { runPluginBuild } from "./preparation.js";
import { PluginRuntime } from "./runtime.js";
import { PluginRuntime, type PluginWorktreeManagerRuntime } from "./runtime.js";
import type { PluginRuntimeSubscription } from "./runtime-subscription.js";
import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js";
import type {
@@ -50,6 +50,9 @@ interface PluginRuntimePort {
drainEvents?: PluginRuntime["drainEvents"];
before?: PluginLifecycle["before"];
wait?: PluginLifecycle["wait"];
createWorktree?: PluginWorktreeManagerRuntime["createWorktree"];
removeWorktree?: PluginWorktreeManagerRuntime["removeWorktree"];
restoreWorktree?: PluginWorktreeManagerRuntime["restoreWorktree"];
catalog: PluginRuntime["catalog"];
invoke(pluginId: string, method: string, input: unknown): Promise<unknown>;
startSubscription: PluginRuntime["startSubscription"];
@@ -192,6 +195,27 @@ export class PluginService {
return request;
};
readonly createWorktree: PluginWorktreeManagerRuntime["createWorktree"] = async (
request,
options,
) => {
return (await this.runtime.createWorktree?.(request, options)) ?? null;
};
readonly removeWorktree: PluginWorktreeManagerRuntime["removeWorktree"] = async (
request,
options,
) => {
return (await this.runtime.removeWorktree?.(request, options)) ?? null;
};
readonly restoreWorktree: PluginWorktreeManagerRuntime["restoreWorktree"] = async (
request,
options,
) => {
return (await this.runtime.restoreWorktree?.(request, options)) ?? null;
};
subscribeSettings(listener: (pluginId: string, settingsId: string) => void): () => void {
this.settingsListeners.add(listener);
return () => this.settingsListeners.delete(listener);
@@ -57,7 +57,12 @@ const changeRequestFields = {
};
const worktreeRequestSchema = z.discriminatedUnion("kind", [
z
.object({ ...worktreeRequestFields, kind: z.literal("branch-off"), baseRef: z.string().min(1) })
.object({
...worktreeRequestFields,
kind: z.literal("branch-off"),
baseRef: z.string().min(1),
startPoint: z.string().min(1).optional(),
})
.strict(),
z
.object({
@@ -239,6 +244,28 @@ function changesSessionOpenTarget(previous: SessionOpenRequest, next: SessionOpe
);
}
type WorktreeBeforeRequest = z.infer<(typeof beforeSchemas)["worktree.create.before"]>;
function validateWorktreeBeforeResult(
previous: WorktreeBeforeRequest,
next: WorktreeBeforeRequest,
): WorktreeBeforeRequest {
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
}
if (previous.kind === "branch-off" && next.kind === "branch-off") {
if (next.startPoint !== undefined && next.startPoint !== previous.startPoint) {
throw new Error("worktree.create.before hooks cannot change startPoint");
}
if (next.startPoint === undefined && previous.startPoint !== undefined) {
return { ...next, startPoint: previous.startPoint };
}
} else if (next.kind === "branch-off" && next.startPoint !== undefined) {
throw new Error("worktree.create.before hooks cannot change startPoint");
}
return next;
}
export async function validateBeforeResult<Name extends keyof PluginWireBeforeRequests>(
name: Name,
input: PluginWireBeforeRequests[Name],
@@ -280,9 +307,7 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
if (name === "worktree.create.before") {
const previous = beforeSchemas["worktree.create.before"].parse(input);
const next = beforeSchemas["worktree.create.before"].parse(result);
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
}
return validateWorktreeBeforeResult(previous, next) as PluginWireBeforeRequests[Name];
}
return result;
}
@@ -45,6 +45,11 @@ export interface PluginUsageSourceMetadata {
icon?: string;
}
export interface PluginWorktreeManagerCapabilities {
hasRemove: boolean;
hasRestore: boolean;
}
export type PluginProcessRequest =
| { type: "tool.call"; requestId: string; agent: PluginHookAgent; name: string; input: unknown }
| { type: "tool.cancel"; requestId: string }
@@ -84,6 +89,10 @@ export type PluginProcessRequest =
}
| { type: "hook"; requestId: string; name: string; input: unknown }
| { type: "hook.cancel"; requestId: string }
| { type: "worktree.create"; requestId: string; request: unknown }
| { type: "worktree.remove"; requestId: string; request: unknown }
| { type: "worktree.restore"; requestId: string; request: unknown }
| { type: "worktree.cancel"; requestId: 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 }
@@ -115,6 +124,10 @@ export type PluginProcessRequest =
export type PluginProcessMessage =
| { type: "settings.changed"; settingsId: string }
| { type: "hooks.changed"; hooks: string[] }
| {
type: "worktree_manager.changed";
worktreeManager: PluginWorktreeManagerCapabilities | null;
}
| {
type: "ready";
methods: string[];
@@ -122,6 +135,7 @@ export type PluginProcessMessage =
providers: PluginProviderMetadata[];
usageSources?: PluginUsageSourceMetadata[];
hooks?: string[];
worktreeManager?: PluginWorktreeManagerCapabilities | null;
}
| { type: "result"; requestId: string; output: unknown }
| { type: "error"; requestId: string; error: string }
@@ -149,6 +163,12 @@ export type PluginProcessMessage =
| { type: "paseo_close" };
const hooksSchema = z.array(z.string());
const worktreeManagerCapabilitiesSchema = z
.object({
hasRemove: z.boolean(),
hasRestore: z.boolean(),
})
.strict();
const providerMetadataSchema = z
.object({
@@ -294,6 +314,14 @@ export const PluginProcessRequestSchema: z.ZodType<PluginProcessRequest> = z.dis
})
.strict(),
z.object({ type: z.literal("hook.cancel"), requestId: z.string() }).strict(),
z
.object({
type: z.enum(["worktree.create", "worktree.remove", "worktree.restore"]),
requestId: z.string().min(1),
request: z.unknown(),
})
.strict(),
z.object({ type: z.literal("worktree.cancel"), requestId: z.string().min(1) }).strict(),
z
.object({
type: z.literal("usage.fetch"),
@@ -356,6 +384,12 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
[
z.object({ type: z.literal("settings.changed"), settingsId: z.string() }).strict(),
z.object({ type: z.literal("hooks.changed"), hooks: hooksSchema }).strict(),
z
.object({
type: z.literal("worktree_manager.changed"),
worktreeManager: worktreeManagerCapabilitiesSchema.nullable(),
})
.strict(),
z
.object({
type: z.literal("ready"),
@@ -364,6 +398,7 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
providers: z.array(providerMetadataSchema),
usageSources: z.array(usageSourceMetadataSchema).optional(),
hooks: hooksSchema.optional(),
worktreeManager: worktreeManagerCapabilitiesSchema.nullable().optional(),
})
.strict(),
z
@@ -16,6 +16,10 @@ import type {
PluginHandlerContext,
PluginServerContext,
PluginServerContribution,
PluginWorktreeCreateInput,
PluginWorktreeRemoveRequest,
PluginWorktreeRestoreRequest,
WorktreeManagerRegistration,
} from "@getpaseo/plugin/server";
import { assertPluginWireValue } from "@getpaseo/protocol/binary-frames/index";
import {
@@ -115,6 +119,8 @@ export function createPluginWorker(options: {
const subscriptions = new PluginSubscriptionHandlers({ send, sendAndWait });
const providers = new Map<string, ProviderRegistration>();
const usageSources = new Map<string, UsageSourceRegistration>();
let worktreeManager: WorktreeManagerRegistration | null = null;
const worktreeRequests = new Map<string, AbortController>();
const providerConnections = new Map<
string,
{ connection: ProviderConnection; unsubscribe: () => void; closing?: Promise<void> }
@@ -228,6 +234,36 @@ export function createPluginWorker(options: {
usageSources.set(id, { ...source, id });
}
function worktreeManagerCapabilities() {
if (!worktreeManager) return null;
return {
hasRemove: worktreeManager.remove !== undefined,
hasRestore: worktreeManager.restore !== undefined,
};
}
function registerWorktreeManager(manager: WorktreeManagerRegistration): () => void {
if (!manager || typeof manager.create !== "function") {
throw new Error("Plugin worktree manager must implement create()");
}
if (manager.remove !== undefined && typeof manager.remove !== "function") {
throw new Error("Invalid remove callback for plugin worktree manager");
}
if (manager.restore !== undefined && typeof manager.restore !== "function") {
throw new Error("Invalid restore callback for plugin worktree manager");
}
if (worktreeManager !== null) {
throw new Error("Plugin already registered a worktree manager");
}
worktreeManager = manager;
send({ type: "worktree_manager.changed", worktreeManager: worktreeManagerCapabilities() });
return () => {
if (worktreeManager !== manager) return;
worktreeManager = null;
send({ type: "worktree_manager.changed", worktreeManager: null });
};
}
function providerMetadata(provider: ProviderRegistration) {
return {
id: provider.id,
@@ -433,6 +469,7 @@ export function createPluginWorker(options: {
handle,
registerProvider,
registerUsageSource,
registerWorktreeManager,
registerSettings,
addHook: hooks.addHook,
on: hooks.on,
@@ -459,6 +496,7 @@ export function createPluginWorker(options: {
methods: [...handlers.keys()].sort(),
subscriptions: subscriptions.catalog(),
hooks: hooks.catalog(),
worktreeManager: worktreeManagerCapabilities(),
providers: [...providers.values()]
.sort((left, right) => left.id.localeCompare(right.id))
.map(providerMetadata),
@@ -478,6 +516,8 @@ export function createPluginWorker(options: {
for (const pending of pendingProviderConnections.values()) pending.tombstoned = true;
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"));
worktreeManager = null;
const currentCleanup = cleanup;
cleanup = null;
try {
@@ -519,6 +559,9 @@ export function createPluginWorker(options: {
message.type === "provider.catalog_key" ||
message.type === "usage.fetch" ||
message.type === "usage.discover" ||
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore" ||
message.type === "subscribe"
) {
send({ type: "error", requestId: message.requestId, error: "Plugin is stopping" });
@@ -704,6 +747,10 @@ export function createPluginWorker(options: {
handleHookMessage(message);
return;
}
if (isWorktreeMessage(message)) {
handleWorktreeMessage(message);
return;
}
if (message.type === "invoke") invoke(message);
else handleSubscriptionMessage(message);
}
@@ -769,6 +816,88 @@ export function createPluginWorker(options: {
): message is Extract<PluginProcessRequest, { type: "hook" | "hook.cancel" }> {
return message.type === "hook" || message.type === "hook.cancel";
}
function isWorktreeMessage(
message: PluginProcessRequest,
): message is Extract<
PluginProcessRequest,
{ type: "worktree.create" | "worktree.remove" | "worktree.restore" | "worktree.cancel" }
> {
return (
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore" ||
message.type === "worktree.cancel"
);
}
function handleWorktreeMessage(
message: Extract<
PluginProcessRequest,
{ type: "worktree.create" | "worktree.remove" | "worktree.restore" | "worktree.cancel" }
>,
): void {
if (message.type === "worktree.cancel") {
worktreeRequests.get(message.requestId)?.abort(new Error("Worktree request canceled"));
return;
}
if (!paseo) {
send({
type: "error",
requestId: message.requestId,
error: "Plugin Paseo API is unavailable",
});
return;
}
const manager = worktreeManager;
if (!manager) {
send({
type: "error",
requestId: message.requestId,
error: "Plugin has no registered worktree manager",
});
return;
}
const controller = new AbortController();
worktreeRequests.set(message.requestId, controller);
const context = { paseo, signal: controller.signal };
void (async () => {
if (message.type === "worktree.create") {
return (
(await manager.create(
structuredClone(message.request) as PluginWorktreeCreateInput,
context,
)) ?? null
);
}
if (message.type === "worktree.remove") {
if (!manager.remove) {
throw new Error("Plugin worktree manager does not implement remove");
}
return (
(await manager.remove(
structuredClone(message.request) as PluginWorktreeRemoveRequest,
context,
)) ?? null
);
}
if (!manager.restore) {
throw new Error("Plugin worktree manager does not implement restore");
}
return (
(await manager.restore(
structuredClone(message.request) as PluginWorktreeRestoreRequest,
context,
)) ?? null
);
})()
.then(
(output) => send({ type: "result", requestId: message.requestId, output }),
(error) =>
send({ type: "error", requestId: message.requestId, error: describeError(error) }),
)
.finally(() => worktreeRequests.delete(message.requestId));
}
return { shutdown };
}
+138 -2
View File
@@ -18,7 +18,15 @@ import {
type ProviderStatus,
type ProviderStatusRequest,
} from "@getpaseo/plugin/server/provider";
import type { PluginHookEvents, PluginHookAgent, AgentToolResult } from "@getpaseo/plugin/server";
import type {
PluginHookEvents,
PluginHookAgent,
AgentToolResult,
PluginWorktreeCreateInput,
PluginWorktreeRemoveRequest,
PluginWorktreeRestoreRequest,
} from "@getpaseo/plugin/server";
import { z } from "zod";
import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js";
import { fork } from "node:child_process";
import path from "node:path";
@@ -42,6 +50,7 @@ import type {
PluginProcessRequest,
PluginProviderMetadata,
PluginUsageSourceMetadata,
PluginWorktreeManagerCapabilities,
} from "./plugin-process-protocol.js";
import { PluginProcessMessageSchema } from "./plugin-process-protocol.js";
import {
@@ -53,7 +62,36 @@ import { InternalPluginChild } from "./internal-child.js";
import { evaluateBundle } from "./bundle-evaluator.js";
const REQUEST_TIMEOUT_MS = 30_000;
const WORKTREE_MANAGER_TIMEOUT_MS = 120_000;
const TOOL_CALL_TIMEOUT_MS = 10 * 60_000;
const worktreeCreateResultSchema = z
.object({ type: z.literal("created"), path: z.string().min(1) })
.strict()
.nullable();
const worktreeRemoveResultSchema = z
.object({ type: z.literal("removed") })
.strict()
.nullable();
const worktreeRestoreResultSchema = z
.object({ type: z.literal("restored"), path: z.string().min(1) })
.strict()
.nullable();
export interface PluginWorktreeManagerRuntime {
createWorktree(
request: PluginWorktreeCreateInput,
options?: { signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null>;
removeWorktree(
request: PluginWorktreeRemoveRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string } | null>;
restoreWorktree(
request: PluginWorktreeRestoreRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null>;
}
const MAX_LOG_ENTRIES = 500;
const MAX_LOG_BYTES = 256 * 1024;
const MAX_LOG_LINE_BYTES = 16 * 1024;
@@ -100,6 +138,7 @@ interface LoadedPlugin {
subscriptionMethods: ReadonlySet<string>;
subscriptions: Map<string, BufferedPluginSubscription>;
hooks: string[];
worktreeManager: PluginWorktreeManagerCapabilities | null;
providers: readonly PluginProviderMetadata[];
usageSources: readonly PluginUsageSourceMetadata[];
child: PluginChild | null;
@@ -293,8 +332,17 @@ function isInstallationRequest(message: PluginProcessRequest): boolean {
);
}
function isWorktreeManagerRequest(message: PluginProcessRequest): boolean {
return (
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore"
);
}
function requestTimeoutMs(message: PluginProcessRequest): number | null {
if (message.type === "tool.call") return TOOL_CALL_TIMEOUT_MS;
if (isWorktreeManagerRequest(message)) return WORKTREE_MANAGER_TIMEOUT_MS;
// An updater runs as long as it needs; daemon shutdown aborts it.
if (message.type === "provider.installation.update") return null;
return REQUEST_TIMEOUT_MS;
@@ -752,6 +800,83 @@ export class PluginRuntime {
return request;
}
async createWorktree(
request: PluginWorktreeCreateInput,
options?: { signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null> {
const plugins = [...this.plugins.values()]
.filter((plugin) => plugin.worktreeManager !== null)
.sort((left, right) => left.id.localeCompare(right.id));
for (const loaded of plugins) {
try {
const raw = await this.request(
loaded,
{ type: "worktree.create", requestId: randomUUID(), request },
{ signal: options?.signal },
);
const parsed = worktreeCreateResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id, path: parsed.path };
}
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.create failed: ${describeError(error)}`, {
cause: error,
});
}
}
return null;
}
async removeWorktree(
request: PluginWorktreeRemoveRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string } | null> {
if (!options?.preferredPluginId) return null;
const loaded = this.plugins.get(options.preferredPluginId);
if (!loaded?.worktreeManager?.hasRemove) return null;
try {
const raw = await this.request(
loaded,
{ type: "worktree.remove", requestId: randomUUID(), request },
{ signal: options.signal },
);
const parsed = worktreeRemoveResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id };
}
return null;
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.remove failed: ${describeError(error)}`, {
cause: error,
});
}
}
async restoreWorktree(
request: PluginWorktreeRestoreRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null> {
if (!options?.preferredPluginId) return null;
const loaded = this.plugins.get(options.preferredPluginId);
if (!loaded?.worktreeManager?.hasRestore) return null;
try {
const raw = await this.request(
loaded,
{ type: "worktree.restore", requestId: randomUUID(), request },
{ signal: options.signal },
);
const parsed = worktreeRestoreResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id, path: parsed.path };
}
return null;
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.restore failed: ${describeError(error)}`, {
cause: error,
});
}
}
async getProviderCatalogCacheKey(
pluginId: string,
providerId: string,
@@ -853,10 +978,12 @@ export class PluginRuntime {
loaded.pending.delete(requestId);
if (message.type === "tool.call")
void send(child, { type: "tool.cancel", requestId }).catch(() => {});
if (isWorktreeManagerRequest(message))
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
if (isInstallationRequest(message))
void send(child, { type: "provider.installation.cancel", requestId }).catch(() => {});
signal?.removeEventListener("abort", cancel);
reject(signal?.reason ?? new Error("Tool call canceled"));
reject(signal?.reason ?? new Error("Plugin request canceled"));
};
const timeoutMs = requestTimeoutMs(message);
const timeout =
@@ -870,6 +997,9 @@ export class PluginRuntime {
if (message.type === "hook") {
void send(child, { type: "hook.cancel", requestId }).catch(() => {});
}
if (isWorktreeManagerRequest(message)) {
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
}
// The handler may still start after the daemon gave up on it.
if (message.type === "subscribe") {
const { subscriptionId } = message;
@@ -935,6 +1065,7 @@ export class PluginRuntime {
subscriptionMethods: new Set(),
subscriptions: new Map(),
hooks: [],
worktreeManager: null,
providers: [],
usageSources: [],
child: null,
@@ -1067,6 +1198,7 @@ export class PluginRuntime {
subscriptionMethods: new Set(ready.subscriptions ?? []),
subscriptions: new Map(),
hooks: ready.hooks ?? [],
worktreeManager: ready.worktreeManager ?? null,
providers: ready.providers ?? [],
usageSources: ready.usageSources ?? [],
child,
@@ -1156,6 +1288,10 @@ export class PluginRuntime {
}
return;
}
if (message.type === "worktree_manager.changed") {
loaded.worktreeManager = message.worktreeManager;
return;
}
if (message.type === "settings.changed") {
this.dependencies.onSettingsChanged?.(loaded.id, message.settingsId);
return;
@@ -0,0 +1,692 @@
import { execFileSync } from "node:child_process";
import { chmod, mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { expect, test } from "vitest";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { readPaseoWorktreeMetadata } from "../../utils/worktree-metadata.js";
const REPO_ROOT = path.resolve(fileURLToPath(new URL("../../../../..", import.meta.url)));
const WORKTRUNK_EXAMPLE = path.join(REPO_ROOT, "plugin-examples", "worktrunk");
function git(cwd: string, args: string[]): string {
return execFileSync(
"git",
[
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"-c",
"commit.gpgsign=false",
...args,
],
{ cwd, encoding: "utf8", stdio: "pipe" },
).trim();
}
async function createRepo(dir: string): Promise<string> {
await mkdir(dir, { recursive: true });
git(dir, ["init", "-b", "main"]);
await writeFile(path.join(dir, "README.md"), "hello\n");
git(dir, ["add", "README.md"]);
git(dir, ["commit", "-m", "initial"]);
return realpath(dir);
}
async function createFakeWorktrunkCli(dir: string, logFile: string): Promise<string> {
const scriptPath = path.join(dir, "fake-wt.mjs");
await writeFile(
scriptPath,
`#!/usr/bin/env node
import { execFileSync } from "node:child_process";
import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
const rawArgs = process.argv.slice(2);
let cwd = process.cwd();
const args = [];
for (let index = 0; index < rawArgs.length; index++) {
if (rawArgs[index] === "-C" && rawArgs[index + 1]) {
cwd = rawArgs[++index];
} else {
args.push(rawArgs[index]);
}
}
const command = args[0];
if (command === "switch") {
const create = args.includes("--create");
const baseIdx = args.indexOf("--base");
const base = baseIdx !== -1 ? args[baseIdx + 1] : undefined;
const pathIdx = args.indexOf("--path");
const explicitPath = pathIdx !== -1 ? args[pathIdx + 1] : undefined;
const skip = new Set(["switch", "--create", "--no-cd", "--yes", "--no-hooks", "--format=json"]);
if (baseIdx !== -1) {
skip.add("--base");
skip.add(base);
}
if (pathIdx !== -1) {
skip.add("--path");
skip.add(explicitPath);
}
const branch = args.find((arg) => !skip.has(arg));
if (!branch) {
console.error("missing branch");
process.exit(1);
}
if (!create && !explicitPath && branch === "main") {
appendFileSync(
${JSON.stringify(logFile)},
JSON.stringify({ command: "switch", cwd, branch, action: "existing", args }) + "\\n",
);
process.stdout.write(JSON.stringify({ path: cwd, branch, action: "existing" }) + "\\n");
process.exit(0);
}
const repoName = path.basename(cwd);
const target =
explicitPath ?? path.join(path.dirname(cwd), \`\${repoName}.\${branch.replaceAll("/", "-")}\`);
mkdirSync(path.dirname(target), { recursive: true });
const gitArgs = create
? ["worktree", "add", "-b", branch, target, ...(base ? [base] : [])]
: ["worktree", "add", target, branch];
execFileSync("git", gitArgs, { cwd, stdio: "pipe" });
writeFileSync(path.join(target, ".wt-hook-ran"), create ? "pre-start" : "reopen");
appendFileSync(
${JSON.stringify(logFile)},
JSON.stringify({ command: "switch", cwd, branch, base, create, explicitPath, target, args }) + "\\n",
);
process.stdout.write(JSON.stringify({ path: target, branch, action: "created" }) + "\\n");
if (branch.endsWith("fail-pre-start")) {
console.error("pre-start hook failed");
process.exit(1);
}
process.exit(0);
}
if (command === "remove") {
const target = args.at(-1);
const keptRefs = execFileSync("git", ["for-each-ref", "--format=%(refname)", "refs/paseo/kept-commits"], {
cwd,
encoding: "utf8",
stdio: "pipe",
})
.trim()
.split("\\n")
.filter(Boolean);
appendFileSync(
${JSON.stringify(logFile)},
JSON.stringify({ command: "remove", cwd, target, args, keptRefsCount: keptRefs.length }) + "\\n",
);
execFileSync("git", ["worktree", "remove", target, "--force"], { cwd, stdio: "pipe" });
process.exit(0);
}
if (command === "config" && args[1] === "state" && args[2] === "marker") {
appendFileSync(
${JSON.stringify(logFile)},
JSON.stringify({ command: "marker", cwd, args: args.slice(3) }) + "\\n",
);
process.exit(0);
}
console.error("unexpected wt command: " + rawArgs.join(" "));
process.exit(1);
`,
);
if (process.platform === "win32") {
const cmdPath = path.join(dir, "fake-wt.cmd");
await writeFile(cmdPath, `@node "${scriptPath}" %*\r\n`);
return cmdPath;
}
await chmod(scriptPath, 0o755);
return scriptPath;
}
test("plugin-examples/worktrunk manages create, before-hook chaining, archive with kept-commits, and restore across daemon restarts", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktrunk-example-"));
const repository = await createRepo(path.join(root, "repo"));
git(repository, ["branch", "release"]);
const wtLog = path.join(root, "wt-log.jsonl");
const fakeWt = await createFakeWorktrunkCli(root, wtLog);
const previousBin = process.env.WORKTRUNK_BIN;
process.env.WORKTRUNK_BIN = fakeWt;
const transformPluginDir = path.join(root, "a-branch-transform");
await mkdir(transformPluginDir);
await writeFile(
path.join(transformPluginDir, "paseo-plugin.json"),
JSON.stringify({ id: "a-branch-transform", requirements: { paseo: ">=0.14.0" } }),
);
await writeFile(
path.join(transformPluginDir, "index.server.ts"),
`export default function contribute(server) {
return server.addHook("worktree.create.before", async ({ request }) => {
if (request.kind !== "branch-off") return;
return { ...request, branch: "team/" + request.branch, baseRef: "release" };
});
}
`,
);
let daemon = await createTestPaseoDaemon({
paseoHomeRoot: path.join(root, "state"),
cleanup: false,
});
let client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await client.connect();
await client.patchDaemonConfig({ pluginsEnabled: true });
expect((await client.installDirectoryPlugin(transformPluginDir)).status).toBe("running");
expect((await client.installDirectoryPlugin(WORKTRUNK_EXAMPLE)).status).toBe("running");
const created = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, worktreeSlug: "feat-one" },
});
expect(created.error).toBeNull();
const workspaceId = created.workspace!.id;
const worktreePath = created.workspace!.workspaceDirectory;
const expectedPath = path.join(path.dirname(repository), "repo.team-feat-one");
expect(await realpath(worktreePath)).toBe(await realpath(expectedPath));
expect(git(worktreePath, ["branch", "--show-current"])).toBe("team/feat-one");
expect(await readFile(path.join(worktreePath, ".wt-hook-ran"), "utf8")).toBe("pre-start");
const metadata = await readPaseoWorktreeMetadata(worktreePath);
expect(metadata).toMatchObject({
baseRefName: "release",
baseRef: "refs/heads/release",
worktreeManagerPluginId: "worktrunk",
changeRequestLookupTarget: {
headRef: "team/feat-one",
localBranchName: "team/feat-one",
},
});
// Worktree manager plugins own branch/directory naming, so auto-rename must stay skipped.
expect(
metadata && "firstAgentBranchAutoName" in metadata
? metadata.firstAgentBranchAutoName
: undefined,
).toBeUndefined();
// Checking out a branch already checked out in the main repo causes wt to return
// action="existing", so the example declines and Paseo falls back to Git.
const checkedOutMain = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, action: "checkout", refName: "main" },
});
expect(checkedOutMain.error).toBeNull();
expect(
(await readPaseoWorktreeMetadata(checkedOutMain.workspace!.workspaceDirectory))
?.worktreeManagerPluginId,
).toBeUndefined();
await client.archiveWorkspace(checkedOutMain.workspace!.id);
// If wt exits non-zero after creating the worktree (e.g. pre-start hook failure),
// the example cleans up the partial worktree from stdout before rethrowing.
const failedPreStart = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, worktreeSlug: "fail-pre-start" },
});
expect(failedPreStart.workspace).toBeNull();
expect(failedPreStart.error).toContain("pre-start hook failed");
await expect(
stat(path.join(path.dirname(repository), "repo.team-fail-pre-start")),
).rejects.toMatchObject({ code: "ENOENT" });
// Archive delegates removal to `wt remove` (run from repoRoot) AFTER Paseo writes refs/paseo/kept-commits/*.
const archived = await client.archiveWorkspace(workspaceId);
expect(archived.error).toBeNull();
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
// Restart daemon and restore: delegates to `wt switch --path <recordedPath> <branch>`.
await client.close();
await daemon.close();
daemon = await createTestPaseoDaemon({
paseoHomeRoot: path.join(root, "state"),
cleanup: false,
pluginsEnabled: true,
plugins: {
"a-branch-transform": { source: "directory", path: transformPluginDir, enabled: true },
worktrunk: { source: "directory", path: WORKTRUNK_EXAMPLE, enabled: true },
},
});
client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
await client.connect();
await client.restoreWorkspace(workspaceId);
expect(git(worktreePath, ["branch", "--show-current"])).toBe("team/feat-one");
expect(await readFile(path.join(worktreePath, ".wt-hook-ran"), "utf8")).toBe("reopen");
expect(await readPaseoWorktreeMetadata(worktreePath)).toMatchObject({
worktreeManagerPluginId: "worktrunk",
baseRefName: "release",
});
const events = (await readFile(wtLog, "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line));
expect(events).toEqual([
expect.objectContaining({
command: "switch",
branch: "team/feat-one",
base: "release",
create: true,
}),
expect.objectContaining({
command: "switch",
branch: "main",
action: "existing",
}),
expect.objectContaining({
command: "switch",
branch: "team/fail-pre-start",
create: true,
}),
expect.objectContaining({
command: "remove",
cwd: repository,
args: expect.arrayContaining([
"remove",
"--foreground",
"--no-delete-branch",
"--no-hooks",
"--force",
]),
}),
expect.objectContaining({
command: "remove",
cwd: repository,
keptRefsCount: 1,
args: expect.arrayContaining([
"remove",
"--foreground",
"--no-delete-branch",
"--yes",
"--force",
]),
}),
expect.objectContaining({
command: "switch",
branch: "team/feat-one",
create: false,
explicitPath: await realpath(worktreePath),
}),
]);
} finally {
if (previousBin === undefined) delete process.env.WORKTRUNK_BIN;
else process.env.WORKTRUNK_BIN = previousBin;
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
test("worktree manager supports decline fallback, rollback delegation, and disabled-plugin fallback on archive and restore", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-manager-fallback-"));
const repository = await createRepo(path.join(root, "repo"));
const eventsFile = path.join(root, "events.jsonl");
const pluginDir = path.join(root, "custom-manager");
await mkdir(pluginDir);
await writeFile(
path.join(pluginDir, "paseo-plugin.json"),
JSON.stringify({ id: "custom-manager", requirements: { paseo: ">=0.16.0" } }),
);
await writeFile(
path.join(pluginDir, "index.server.ts"),
`import { execFileSync } from "node:child_process";
import { appendFileSync } from "node:fs";
import path from "node:path";
export default function contribute(server) {
const removeManager = server.registerWorktreeManager({
async create(request) {
if (request.branch === "decline-me") return;
const target = path.join(path.dirname(request.repoRoot), "managed-" + request.branch);
execFileSync("git", ["worktree", "add", "-b", request.branch, target, request.baseRef], {
cwd: request.repoRoot,
stdio: "pipe",
});
appendFileSync(${JSON.stringify(eventsFile)}, JSON.stringify({ op: "create", branch: request.branch, target }) + "\\n");
return { type: "created", path: target };
},
async remove(request) {
appendFileSync(${JSON.stringify(eventsFile)}, JSON.stringify({ op: "remove", reason: request.reason, path: request.path }) + "\\n");
execFileSync("git", ["worktree", "remove", request.path, "--force"], {
cwd: request.repoRoot,
stdio: "pipe",
});
return { type: "removed" };
},
});
const removeAfter = server.addHook("worktree.create.after", async ({ worktree }) => {
if (worktree.branch === "abort-after") {
throw new Error("rejected after creation");
}
});
return () => {
removeAfter();
removeManager();
};
}
`,
);
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: path.join(root, "state"),
cleanup: false,
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await client.connect();
await client.patchDaemonConfig({ pluginsEnabled: true });
expect((await client.installDirectoryPlugin(pluginDir)).status).toBe("running");
// 1. Declining falls back cleanly to Paseo's built-in git worktree creation.
const declined = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName: "decline-me" },
});
expect(declined.error).toBeNull();
const declinedMeta = await readPaseoWorktreeMetadata(declined.workspace!.workspaceDirectory);
expect(declinedMeta?.worktreeManagerPluginId).toBeUndefined();
// 2. Failure in worktree.create.after rolls back through the manager's remove(reason: "rollback").
const aborted = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName: "abort-after" },
});
expect(aborted.workspace).toBeNull();
expect(aborted.error).toContain("rejected after creation");
await expect(
stat(path.join(path.dirname(repository), "managed-abort-after")),
).rejects.toMatchObject({
code: "ENOENT",
});
// 3. Create a managed worktree, then disable the plugin: archive & restore fall back to Git.
const managed = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName: "survive-disable" },
});
expect(managed.error).toBeNull();
const managedPath = managed.workspace!.workspaceDirectory;
await client.disablePlugin("custom-manager");
const archived = await client.archiveWorkspace(managed.workspace!.id);
expect(archived.error).toBeNull();
await expect(stat(managedPath)).rejects.toMatchObject({ code: "ENOENT" });
await client.restoreWorkspace(managed.workspace!.id);
expect(git(managedPath, ["branch", "--show-current"])).toBe("survive-disable");
// Re-enabling the plugin must not route removal of a Git-restored worktree back to the plugin.
await client.enablePlugin("custom-manager");
await client.archiveWorkspace(managed.workspace!.id);
await expect(stat(managedPath)).rejects.toMatchObject({ code: "ENOENT" });
const events = (await readFile(eventsFile, "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line));
expect(events).toEqual([
expect.objectContaining({ op: "create", branch: "abort-after" }),
expect.objectContaining({ op: "remove", reason: "rollback" }),
expect.objectContaining({ op: "create", branch: "survive-disable" }),
]);
} finally {
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
test("worktree manager rejects pre-existing worktrees, detached HEAD, wrong repos, and non-worktree paths without modifying them", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-manager-guards-"));
const repository = await createRepo(path.join(root, "repo"));
const otherRepo = await createRepo(path.join(root, "other-repo"));
// Pre-existing manual worktree the user created outside Paseo.
const existingManual = path.join(root, "manual-existing");
git(repository, ["worktree", "add", "-b", "manual-branch", existingManual, "main"]);
const plainDir = path.join(root, "not-a-worktree");
await mkdir(plainDir);
const pluginDir = path.join(root, "bad-manager");
await mkdir(pluginDir);
await writeFile(
path.join(pluginDir, "paseo-plugin.json"),
JSON.stringify({ id: "bad-manager", requirements: { paseo: ">=0.16.0" } }),
);
await writeFile(
path.join(pluginDir, "index.server.ts"),
`import { execFileSync } from "node:child_process";
import path from "node:path";
export default function contribute(server) {
return server.registerWorktreeManager({
async create(request) {
if (request.branch === "existing") {
return { type: "created", path: ${JSON.stringify(existingManual)} };
}
if (request.branch === "plain-dir") {
return { type: "created", path: ${JSON.stringify(plainDir)} };
}
if (request.branch === "other-repo") {
const target = path.join(${JSON.stringify(root)}, "other-wt");
execFileSync("git", ["worktree", "add", "-b", "other-wt", target, "main"], {
cwd: ${JSON.stringify(otherRepo)},
stdio: "pipe",
});
return { type: "created", path: target };
}
if (request.branch === "detached") {
const target = path.join(${JSON.stringify(root)}, "detached-wt");
execFileSync("git", ["worktree", "add", "--detach", target, "main"], {
cwd: request.repoRoot,
stdio: "pipe",
});
return { type: "created", path: target };
}
return { type: "created", path: "relative/path" };
},
});
}
`,
);
const daemon = await createTestPaseoDaemon();
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await client.connect();
await client.patchDaemonConfig({ pluginsEnabled: true });
expect((await client.installDirectoryPlugin(pluginDir)).status).toBe("running");
const cases: Array<[string, string]> = [
["existing", "already-existing worktree"],
["plain-dir", "did not create a Git worktree"],
["other-repo", "outside the repository"],
["detached", "detached HEAD"],
["relative", "relative path"],
];
for (const [branchName, expectedError] of cases) {
const created = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName },
});
expect(created.workspace).toBeNull();
expect(created.error).toContain(expectedError);
}
// The pre-existing manual worktree must stay untouched and un-owned by Paseo.
expect(await readPaseoWorktreeMetadata(existingManual)).toBeNull();
expect((await stat(existingManual)).isDirectory()).toBe(true);
// The newly created detached worktree failed adoption and must be rolled back cleanly.
await expect(stat(path.join(root, "detached-wt"))).rejects.toMatchObject({ code: "ENOENT" });
expect(git(repository, ["worktree", "list", "--porcelain"])).not.toContain("detached-wt");
} finally {
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
test("worktree manager rejects duplicate registration and fails removal when the directory remains on disk", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-manager-edge-"));
const repository = await createRepo(path.join(root, "repo"));
const dupPluginDir = path.join(root, "dup-manager");
await mkdir(dupPluginDir);
await writeFile(
path.join(dupPluginDir, "paseo-plugin.json"),
JSON.stringify({ id: "dup-manager", requirements: { paseo: ">=0.16.0" } }),
);
await writeFile(
path.join(dupPluginDir, "index.server.ts"),
`export default function contribute(server) {
server.registerWorktreeManager({ async create() {} });
server.registerWorktreeManager({ async create() {} });
return () => {};
}
`,
);
const leakyRemoveDir = path.join(root, "leaky-remove");
await mkdir(leakyRemoveDir);
await writeFile(
path.join(leakyRemoveDir, "paseo-plugin.json"),
JSON.stringify({ id: "leaky-remove", requirements: { paseo: ">=0.16.0" } }),
);
await writeFile(
path.join(leakyRemoveDir, "index.server.ts"),
`import { execFileSync } from "node:child_process";
import path from "node:path";
export default function contribute(server) {
return server.registerWorktreeManager({
async create(request) {
const target = path.join(path.dirname(request.repoRoot), "leaky-" + request.branch);
execFileSync("git", ["worktree", "add", "-b", request.branch, target, request.baseRef], {
cwd: request.repoRoot,
stdio: "pipe",
});
return { type: "created", path: target };
},
async remove() {
// Claims removed without deleting the directory.
return { type: "removed" };
},
});
}
`,
);
const daemon = await createTestPaseoDaemon();
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await client.connect();
await client.patchDaemonConfig({ pluginsEnabled: true });
await expect(client.installDirectoryPlugin(dupPluginDir)).rejects.toThrow(
"Plugin already registered a worktree manager",
);
expect((await client.installDirectoryPlugin(leakyRemoveDir)).status).toBe("running");
const created = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName: "still-here" },
});
expect(created.error).toBeNull();
const worktreePath = created.workspace!.workspaceDirectory;
const archived = await client.archiveWorkspace(created.workspace!.id);
expect(archived.error).toBeNull();
// Removal failure keeps the directory instead of silently deleting behind the manager.
expect((await stat(worktreePath)).isDirectory()).toBe(true);
} finally {
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
test("untrusted workspaces pass untrusted=true to worktree manager remove and restore, and worktrunk skips hooks", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktrunk-untrusted-"));
const repository = await createRepo(path.join(root, "repo"));
const wtLog = path.join(root, "wt-log.jsonl");
const fakeWt = await createFakeWorktrunkCli(root, wtLog);
const previousBin = process.env.WORKTRUNK_BIN;
process.env.WORKTRUNK_BIN = fakeWt;
const stateDir = path.join(root, "state");
let daemon = await createTestPaseoDaemon({
paseoHomeRoot: stateDir,
cleanup: false,
});
let client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await client.connect();
await client.patchDaemonConfig({ pluginsEnabled: true });
expect((await client.installDirectoryPlugin(WORKTRUNK_EXAMPLE)).status).toBe("running");
const created = await client.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName: "fork-pr-branch" },
});
expect(created.error).toBeNull();
const workspaceId = created.workspace!.id;
const worktreePath = created.workspace!.workspaceDirectory;
// Mark the persisted workspace record as originating from an untrusted fork PR and reload daemon.
await client.close();
await daemon.close();
const workspacesPath = path.join(daemon.paseoHome, "projects", "workspaces.json");
const records = JSON.parse(await readFile(workspacesPath, "utf8")) as Array<
Record<string, unknown>
>;
for (const record of records) {
if (record.workspaceId === workspaceId) {
record.untrustedSource = {
kind: "change_request",
forge: "github",
number: 42,
headRepository: "fork-owner/repo",
};
}
}
await writeFile(workspacesPath, JSON.stringify(records, null, 2));
daemon = await createTestPaseoDaemon({
paseoHomeRoot: stateDir,
cleanup: false,
pluginsEnabled: true,
plugins: {
worktrunk: { source: "directory", path: WORKTRUNK_EXAMPLE, enabled: true },
},
});
client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
await client.connect();
const archived = await client.archiveWorkspace(workspaceId);
expect(archived.error).toBeNull();
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
await client.restoreWorkspace(workspaceId);
expect(git(worktreePath, ["branch", "--show-current"])).toBe("fork-pr-branch");
const events = (await readFile(wtLog, "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line) as { command: string; cwd: string; args: string[] });
const removeEvent = events.find((event) => event.command === "remove");
expect(removeEvent).toBeDefined();
expect(removeEvent!.cwd).toBe(repository);
expect(removeEvent!.args).toContain("--no-hooks");
expect(removeEvent!.args).not.toContain("--yes");
const restoreEvent = events.at(-1);
expect(restoreEvent?.command).toBe("switch");
expect(restoreEvent?.args).toContain("--no-hooks");
expect(restoreEvent?.args).not.toContain("--yes");
} finally {
if (previousBin === undefined) delete process.env.WORKTRUNK_BIN;
else process.env.WORKTRUNK_BIN = previousBin;
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
@@ -529,6 +529,9 @@ test("routes plugin requests and releases its owned catalog subscription on clea
return request;
},
emit: () => {},
createWorktree: async () => null,
removeWorktree: async () => null,
restoreWorktree: async () => null,
listPlugins: async () => [plugin],
getLogs: () => [
{
@@ -670,6 +673,9 @@ test("leaves out the client bundles a catalog request already holds", async () =
const pluginRuntime: NonNullable<SessionOptions["pluginRuntime"]> = {
before: async (_name, request) => request,
emit: () => {},
createWorktree: async () => null,
removeWorktree: async () => null,
restoreWorktree: async () => null,
listPlugins: async () => [],
getLogs: () => [],
installDirectory: async () => {
+10
View File
@@ -529,6 +529,9 @@ export interface SessionOptions {
wait: import("./plugins/lifecycle/index.js").PluginLifecycle["wait"];
before: import("./plugins/lifecycle/index.js").PluginLifecycle["before"];
emit: import("./plugins/lifecycle/index.js").PluginLifecycle["emit"];
createWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["createWorktree"];
removeWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["removeWorktree"];
restoreWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["restoreWorktree"];
listPlugins(): Promise<import("@getpaseo/protocol/messages").PluginListItem[]>;
getLogs(pluginId: string): import("@getpaseo/protocol/messages").PluginLogEntry[];
installDirectory(input: {
@@ -1034,6 +1037,7 @@ export class Session {
this.workspaceRecovery = createWorkspaceRecoveryService({
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
getProject: (projectId) => this.projectRegistry.get(projectId),
isDirectory: (path) => this.filesystem.isDirectory(path),
@@ -1254,6 +1258,7 @@ export class Session {
this.createAgentLifecycleDispatch = new CreateAgentLifecycleDispatch({
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
agentManager: this.agentManager,
agentStorage: this.agentStorage,
github: this.github,
@@ -5780,6 +5785,7 @@ export class Session {
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
@@ -6550,6 +6556,7 @@ export class Session {
): Promise<CreatePaseoWorktreeResult> {
const result = await createPaseoWorktree(input, {
lifecycle: this.pluginRuntime,
worktreeManagers: this.pluginRuntime,
github: this.github,
...(options?.resolveDefaultBranch
? { resolveDefaultBranch: options.resolveDefaultBranch }
@@ -6580,6 +6587,8 @@ export class Session {
worktreeRoot: workspace.worktreeRoot,
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
mainRepoRoot: workspace.mainRepoRoot,
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
untrustedSource: workspace.untrustedSource,
}));
}
@@ -8128,6 +8137,7 @@ export class Session {
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
@@ -52,6 +52,7 @@ export interface CreateWorktreeWorkspaceInput {
worktreeRoot: string;
branch: string | null;
baseBranch: string | null;
worktreeManagerPluginId?: string | null;
title: string | null;
metadata?: Record<string, JsonValue>;
expectsInitialAgent?: boolean;
@@ -279,6 +280,7 @@ export function createWorkspaceProvisioningService(deps: {
projectId: project.projectId,
...initialWorkspacePlacement({ source: "checkout", cwd: normalizedCwd, checkout }),
baseBranch: baseMetadata?.baseRef ?? baseMetadata?.baseRefName ?? null,
worktreeManagerPluginId: baseMetadata?.worktreeManagerPluginId ?? null,
title: title?.trim() || null,
metadata: context?.metadata,
createdAt: timestamp,
@@ -320,6 +322,7 @@ export function createWorkspaceProvisioningService(deps: {
baseBranch: input.baseBranch,
mainRepoRoot: repoRoot,
}),
worktreeManagerPluginId: input.worktreeManagerPluginId ?? null,
title: input.title,
metadata: input.metadata,
createdAt: timestamp,
@@ -5,12 +5,18 @@ import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
import { runGitCommand } from "../../../utils/run-git-command.js";
import {
adoptPluginWorktree,
cleanupFailedPluginWorktree,
createWorktree,
isPaseoOwnedWorktreeCwd,
listGitWorktreePaths,
mapWorkspaceCwdToWorktree,
rollbackCreatedPaseoWorktree,
type WorktreeSource,
} from "../../../utils/worktree.js";
import { validateWorktreePath } from "../../../utils/worktree-path.js";
import type { PluginWorktreeManagerRuntime } from "../../plugins/runtime.js";
import type { PluginWorktreeRestoreTarget } from "@getpaseo/plugin/server";
import { WorktreeRequestError, toWorktreeRequestError } from "../../worktree-errors.js";
import {
resolveWorkspaceDisplayName,
@@ -64,6 +70,7 @@ type UnavailableRecoveryState = Extract<WorkspaceRecoveryState, { kind: "unavail
export function createWorkspaceRecoveryService(deps: {
paseoHome: string;
worktreesRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "restoreWorktree" | "removeWorktree">;
getWorkspace: (workspaceId: string) => Promise<PersistedWorkspaceRecord | null>;
getProject: (projectId: string) => Promise<PersistedProjectRecord | null>;
isDirectory: (path: string) => Promise<boolean>;
@@ -140,17 +147,27 @@ export function createWorkspaceRecoveryService(deps: {
throw new Error(resolved.message);
}
let workspaceToUnarchive = resolved.workspace;
if (resolved.kind === "restore") {
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
const restoredByPluginId = await recreateArchivedWorktree(
resolved.workspace,
resolved.sourceRepoRoot,
);
if ((resolved.workspace.worktreeManagerPluginId ?? null) !== restoredByPluginId) {
const { worktreeManagerPluginId: _previous, ...withoutManager } = resolved.workspace;
workspaceToUnarchive = restoredByPluginId
? { ...withoutManager, worktreeManagerPluginId: restoredByPluginId }
: withoutManager;
}
}
await deps.unarchiveWorkspace(resolved.workspace);
await deps.unarchiveWorkspace(workspaceToUnarchive);
return { workspaceId, action: resolved.kind };
}
async function recreateArchivedWorktree(
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): Promise<void> {
): Promise<string | null> {
let source: WorktreeSource;
const checkout = parseWorkspaceHead(workspace);
if (checkout.kind === "branch") {
@@ -195,17 +212,17 @@ export function createWorkspaceRecoveryService(deps: {
}
let recreatedWorktreePath: string;
let restoredByPluginId: string | null = null;
try {
const result = await createWorktree({
cwd: sourceRepoRoot,
worktreeSlug: basename(previousWorktreePath),
const restored = await recreateWorktreeCheckout({
workspace,
sourceRepoRoot,
source,
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
previousWorktreePath,
hasRecordedWorktreePath,
});
recreatedWorktreePath = result.worktreePath;
recreatedWorktreePath = restored.worktreePath;
restoredByPluginId = restored.pluginId;
} catch (error) {
throw toWorktreeRequestError(error);
}
@@ -236,15 +253,103 @@ export function createWorkspaceRecoveryService(deps: {
teardownCwds: [],
paseoHome: deps.paseoHome,
worktreesBaseRoot: deps.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: restoredByPluginId,
removeReason: "rollback",
untrusted: Boolean(workspace.untrustedSource),
},
error,
);
}
return restoredByPluginId;
}
async function recreateWorktreeCheckout(options: {
workspace: PersistedWorkspaceRecord;
sourceRepoRoot: string;
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>;
previousWorktreePath: string;
hasRecordedWorktreePath: boolean;
}): Promise<{ worktreePath: string; pluginId: string | null }> {
const { workspace, sourceRepoRoot, source, previousWorktreePath, hasRecordedWorktreePath } =
options;
const managerPluginId = workspace.worktreeManagerPluginId;
const untrusted = Boolean(workspace.untrustedSource);
if (managerPluginId && hasRecordedWorktreePath && deps.worktreeManagers) {
const existingWorktreePaths = await listGitWorktreePaths(sourceRepoRoot);
const managed = await deps.worktreeManagers.restoreWorktree(
{
repoRoot: sourceRepoRoot,
path: previousWorktreePath,
target: restoreTargetFromWorktreeSource(source),
baseRef: workspace.baseBranch,
untrusted,
},
{ preferredPluginId: managerPluginId },
);
if (managed) {
try {
const validatedPath = await validateWorktreePath({
candidate: managed.path,
repoPath: sourceRepoRoot,
allowExistingPath: true,
});
if (!createRealpathAwarePathMatcher(previousWorktreePath)(validatedPath)) {
throw new WorktreeRequestError({
code: "unknown",
message: `Plugin ${managed.pluginId} restored worktree to ${validatedPath}, expected ${previousWorktreePath}`,
});
}
const adopted = await adoptPluginWorktree({
cwd: sourceRepoRoot,
source,
worktreePath: validatedPath,
worktreeManagerPluginId: managed.pluginId,
existingWorktreePaths,
});
return { worktreePath: adopted.worktreePath, pluginId: managed.pluginId };
} catch (error) {
await cleanupFailedPluginWorktree({
cwd: sourceRepoRoot,
candidatePath: managed.path,
existingWorktreePaths,
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: managed.pluginId,
untrusted,
paseoHome: deps.paseoHome,
worktreesBaseRoot: deps.worktreesRoot,
}).catch(() => {});
throw error;
}
}
}
const result = await createWorktree({
cwd: sourceRepoRoot,
worktreeSlug: basename(previousWorktreePath),
source,
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
});
return { worktreePath: result.worktreePath, pluginId: null };
}
return { inspect, restore };
}
function restoreTargetFromWorktreeSource(
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>,
): PluginWorktreeRestoreTarget {
if (source.kind === "restore") {
return { type: "branch", branch: source.branchName };
}
if (source.kind === "restore-commit") {
return { type: "commit", commit: source.commit };
}
return { type: "from-base", branch: source.branchName, baseRef: source.baseRef };
}
async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null): Promise<string> {
if (recordedBase) {
try {
@@ -2214,6 +2214,8 @@ export class VoiceAssistantWebSocketServer {
hopliteProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("hoplite"),
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
fxProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("fx"),
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
gooseProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("goose"),
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
importSessionWorkspaceTarget: true,
// COMPAT(importSessionSearch): added in v0.7.3, remove gate after 2027-03-02.
@@ -22,16 +22,21 @@ import type {
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
export type ActiveWorkspaceRef = Pick<
PersistedWorkspaceRecord,
"workspaceId" | "cwd" | "kind" | "worktreeRoot" | "isPaseoOwnedWorktree" | "mainRepoRoot"
>;
> & {
worktreeManagerPluginId?: string | null;
untrustedSource?: PersistedWorkspaceRecord["untrustedSource"];
};
export interface ArchiveDependencies {
paseoHome?: string;
// Base directory that may hold worktrees across repositories.
paseoWorktreesBaseRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
github: ForgeService;
workspaceGitService: Pick<WorkspaceGitService, "getSnapshot" | "invalidateWorktrees">;
agentManager: Pick<AgentManager, "listAgents" | "getAgent" | "archiveAgent" | "archiveSnapshot">;
@@ -119,6 +124,8 @@ interface BackingDirectory {
registryProven: boolean;
mainRepoRoot: string | null;
paseoWorktreesRoot: string | null;
worktreeManagerPluginId: string | null;
untrusted: boolean;
}
interface ArchiveTarget {
@@ -313,6 +320,8 @@ async function resolveWorkspaceBackingDirectory(
workspace: ActiveWorkspaceRef,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<BackingDirectory> {
const worktreeManagerPluginId = workspace.worktreeManagerPluginId ?? null;
const untrusted = Boolean(workspace.untrustedSource);
if (workspace.isPaseoOwnedWorktree === false) {
return {
path: resolve(workspace.worktreeRoot ?? workspace.cwd),
@@ -321,6 +330,8 @@ async function resolveWorkspaceBackingDirectory(
registryProven: false,
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
@@ -331,6 +342,8 @@ async function resolveWorkspaceBackingDirectory(
registryProven: true,
mainRepoRoot: workspace.mainRepoRoot,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
if (workspace.kind !== "worktree") {
@@ -341,6 +354,8 @@ async function resolveWorkspaceBackingDirectory(
registryProven: false,
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
@@ -350,7 +365,12 @@ async function resolveWorkspaceBackingDirectory(
workspace.worktreeRoot ?? workspace.cwd,
dependencies,
);
return { ...backing, mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot };
return {
...backing,
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
untrusted: untrusted || backing.untrusted,
};
}
async function resolveBackingDirectory(
@@ -369,6 +389,8 @@ async function resolveBackingDirectory(
registryProven: false,
mainRepoRoot: ownership.repoRoot ?? null,
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
worktreeManagerPluginId: null,
untrusted: false,
};
}
@@ -453,11 +475,15 @@ async function maybeRemoveDirectory(
teardownTarget.workspaceId === null || archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
);
let untrustedBacking = backing.untrusted;
try {
const allowedTeardownTargets = await filterAllowedTeardownTargets(
dependencies,
teardownTargets,
);
if (allowedTeardownTargets.length < teardownTargets.length) {
untrustedBacking = true;
}
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
request.checkpoint();
await runWorktreeTeardownCommands({
@@ -501,6 +527,10 @@ async function maybeRemoveDirectory(
paseoHome: dependencies.paseoHome,
worktreesBaseRoot: dependencies.paseoWorktreesBaseRoot,
registryProven: backing.registryProven,
worktreeManagers: dependencies.worktreeManagers,
worktreeManagerPluginId: backing.worktreeManagerPluginId,
removeReason: "archive",
untrusted: untrustedBacking,
});
dependencies.workspaceGitService.invalidateWorktrees();
dependencies.github.invalidate({ cwd: backing.path });
@@ -88,6 +88,7 @@ const PersistedWorkspaceRecordSchema = z.object({
.transform((value) => value ?? null),
isPaseoOwnedWorktree: z.boolean().default(false),
mainRepoRoot: z.string().nullable().default(null),
worktreeManagerPluginId: z.string().min(1).optional(),
createdAt: z.string(),
updatedAt: z.string(),
archivedAt: z.string().nullable(),
@@ -698,6 +699,7 @@ export function createPersistedWorkspaceRecord(input: {
baseBranch?: string | null;
isPaseoOwnedWorktree?: boolean;
mainRepoRoot?: string | null;
worktreeManagerPluginId?: string | null;
createdAt: string;
updatedAt: string;
archivedAt?: string | null;
@@ -708,7 +710,7 @@ export function createPersistedWorkspaceRecord(input: {
untrustedSource?: UntrustedWorkspaceSource;
background?: boolean;
}): PersistedWorkspaceRecord {
const { background, ...rest } = input;
const { background, worktreeManagerPluginId, ...rest } = input;
return PersistedWorkspaceRecordSchema.parse({
...rest,
background: background ?? false,
@@ -718,6 +720,7 @@ export function createPersistedWorkspaceRecord(input: {
baseBranch: input.baseBranch ?? null,
isPaseoOwnedWorktree: input.isPaseoOwnedWorktree ?? false,
mainRepoRoot: input.mainRepoRoot ?? null,
...(worktreeManagerPluginId ? { worktreeManagerPluginId } : {}),
archivedAt: input.archivedAt ?? null,
autoArchivedChangeRequestUrl: input.autoArchivedChangeRequestUrl ?? null,
pinnedAt: input.pinnedAt ?? null,
@@ -1,16 +1,21 @@
import type { PluginWorktreeCreateRequest } from "@getpaseo/plugin/server";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import { createNameId } from "mnemonic-id";
import type { ForgeService } from "../services/forge-service.js";
import {
adoptPluginWorktree,
cleanupFailedPluginWorktree,
createWorktree,
fetchFirstAvailableRef,
listGitWorktreePaths,
resolveDefaultWorktreePath,
slugify,
validateBranchSlug,
type CreatedWorktree,
} from "../utils/worktree.js";
import { validateWorktreePath } from "../utils/worktree-path.js";
import {
resolveWorktreeCreationIntent,
type ResolveWorktreeCreationIntentInput,
@@ -36,6 +41,7 @@ export interface CreateWorktreeCoreInput {
export interface CreateWorktreeCoreDeps {
lifecycle?: Pick<PluginLifecycle, "before">;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "createWorktree" | "removeWorktree">;
github: ForgeService;
workspaceGitService?: Pick<
WorkspaceGitService,
@@ -149,6 +155,22 @@ async function createWorktreeCoreWithPriority(
normalizedSlug = validateWorktreeSlug(transformed.slug);
intent = creationIntentFromRequest(transformed, intent);
const managedWorktree = await tryCreateWithWorktreeManager({
repoRoot,
transformed,
intent,
input,
deps,
});
if (managedWorktree) {
return {
worktree: managedWorktree,
intent,
repoRoot,
created: true,
};
}
return {
worktree: await createWorktree({
cwd: repoRoot,
@@ -164,6 +186,47 @@ async function createWorktreeCoreWithPriority(
};
}
async function tryCreateWithWorktreeManager(options: {
repoRoot: string;
transformed: PluginWorktreeCreateRequest;
intent: WorktreeCreationIntent;
input: Pick<CreateWorktreeCoreInput, "paseoHome" | "worktreesRoot">;
deps: Pick<CreateWorktreeCoreDeps, "worktreeManagers">;
}): Promise<CreatedWorktree | null> {
const { repoRoot, transformed, intent, input, deps } = options;
if (!deps.worktreeManagers) return null;
const existingWorktreePaths = await listGitWorktreePaths(repoRoot);
const managed = await deps.worktreeManagers.createWorktree(transformed);
if (!managed) return null;
const untrusted = intent.kind === "checkout-change-request" && Boolean(intent.headRepository);
try {
const validatedPath = await validateWorktreePath({
candidate: managed.path,
repoPath: repoRoot,
allowExistingPath: true,
});
return await adoptPluginWorktree({
cwd: repoRoot,
source: intent,
worktreePath: validatedPath,
worktreeManagerPluginId: managed.pluginId,
existingWorktreePaths,
});
} catch (error) {
await cleanupFailedPluginWorktree({
cwd: repoRoot,
candidatePath: managed.path,
existingWorktreePaths,
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: managed.pluginId,
untrusted,
paseoHome: input.paseoHome,
worktreesBaseRoot: input.worktreesRoot,
}).catch(() => {});
throw error;
}
}
function describeCreationRequest(
intent: WorktreeCreationIntent,
placement: Pick<PluginWorktreeCreateRequest, "repoRoot" | "sourceCheckout" | "slug" | "path">,
@@ -174,6 +237,7 @@ function describeCreationRequest(
kind: intent.kind,
branch: intent.branchName,
baseRef: intent.baseBranch,
...(intent.startPoint ? { startPoint: intent.startPoint } : {}),
};
if (intent.kind === "checkout-branch")
return { ...placement, kind: intent.kind, branch: intent.branchName };
@@ -22,6 +22,7 @@ const PaseoWorktreeMetadataV1Schema = z.object({
baseRefName: z.string().min(1),
baseRef: z.string().min(1).optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
});
const PaseoWorktreeMetadataV2Schema = z.object({
@@ -29,6 +30,7 @@ const PaseoWorktreeMetadataV2Schema = z.object({
baseRefName: z.string().min(1),
baseRef: z.string().min(1).optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
firstAgentBranchAutoName: z
.discriminatedUnion("status", [
z.object({
@@ -227,6 +229,7 @@ export async function writePaseoWorktreeMetadata(
baseRefName: string;
baseRef?: string;
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
worktreeManagerPluginId?: string;
},
): Promise<void> {
return mutateMetadata(worktreeRoot, async (root) => {
@@ -244,6 +247,9 @@ export async function writePaseoWorktreeMetadata(
...(options.changeRequestLookupTarget
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
: {}),
...(options.worktreeManagerPluginId
? { worktreeManagerPluginId: options.worktreeManagerPluginId }
: {}),
};
await writePaseoWorktreeMetadataFile(root, metadata);
});
+4 -2
View File
@@ -47,8 +47,10 @@ async function pathExists(path: string): Promise<boolean> {
export async function validateWorktreePath(options: {
candidate: string;
repoPath: string;
/** The worktree manager already created the destination, so it is expected to exist. */
allowExistingPath?: boolean;
}): Promise<string> {
const { candidate, repoPath } = options;
const { candidate, repoPath, allowExistingPath = false } = options;
if (!isAbsolute(candidate)) {
throw new Error(
`Worktree hook returned a relative path '${candidate}'; it must be an absolute path`,
@@ -79,7 +81,7 @@ export async function validateWorktreePath(options: {
if (relativeToCandidate !== null && relativeToCandidate !== "") {
throw new Error(`Worktree hook returned an ancestor of the repository: ${normalized}`);
}
if ((await pathExists(normalized)) || (await pathExists(candidate))) {
if (!allowExistingPath && ((await pathExists(normalized)) || (await pathExists(candidate)))) {
throw new Error(
`Worktree hook returned a path that already exists: ${normalized}. Paseo creates the returned path.`,
);
+347 -17
View File
@@ -47,6 +47,7 @@ import {
isPathInsideRoot,
} from "./path.js";
import { terminateWithTreeKill } from "./tree-kill.js";
import type { PluginWorktreeManagerRuntime } from "../server/plugins/runtime.js";
export { slugify, validateBranchSlug } from "@getpaseo/protocol/branch-slug";
@@ -62,6 +63,7 @@ export interface WorktreeConfig {
export interface CreatedWorktree extends WorktreeConfig {
comparisonBaseRef: string | null;
worktreeManagerPluginId?: string;
}
export interface WorktreeRuntimeEnv {
@@ -1211,6 +1213,19 @@ export async function listPaseoWorktrees({
return worktrees;
}
/** Normalized paths of all currently registered worktrees for the repo containing `cwd`. */
export async function listGitWorktreePaths(cwd: string): Promise<Set<string>> {
const { stdout } = await runGitCommand(["worktree", "list", "--porcelain"], {
cwd,
envOverlay: READ_ONLY_GIT_ENV,
});
const paths = new Set<string>();
for (const entry of parseWorktreeList(stdout)) {
paths.add(await normalizePathForOwnership(entry.path));
}
return paths;
}
export interface DeletePaseoWorktreeOptions {
cwd: string | null;
worktreePath?: string;
@@ -1225,6 +1240,11 @@ export interface DeletePaseoWorktreeOptions {
// gone, where the marker proof can no longer be verified. Only pass
// this when the record was matched against the path by the caller.
registryProven?: boolean;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
worktreeManagerPluginId?: string | null;
removeReason?: "archive" | "rollback";
untrusted?: boolean;
signal?: AbortSignal;
}
// Project scoping for delete: a proof for some other repo's worktree must
@@ -1280,6 +1300,11 @@ export async function deletePaseoWorktree({
paseoHome,
worktreesBaseRoot,
registryProven,
worktreeManagers,
worktreeManagerPluginId,
removeReason = "archive",
untrusted = false,
signal,
}: DeletePaseoWorktreeOptions): Promise<void> {
if (!worktreePath && !worktreeSlug) {
throw new Error("worktreePath or worktreeSlug is required");
@@ -1320,17 +1345,19 @@ export async function deletePaseoWorktree({
}
if (await pathExists(resolvedWorktree)) {
for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) {
await runWorktreeTeardownCommands({
worktreePath: resolvedWorktree,
teardownCwd,
});
}
const commit = await readWorktreeHead(resolvedWorktree);
if (commit) {
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], {
cwd: resolvedWorktree,
});
const removedByPlugin = await prepareAndTryPluginWorktreeRemove({
cwd,
resolvedWorktree,
teardownCwds,
worktreeManagers,
worktreeManagerPluginId,
removeReason,
untrusted,
signal,
});
if (removedByPlugin) {
await pruneWorktreesBestEffort(cwd);
return;
}
}
@@ -1349,16 +1376,83 @@ export async function deletePaseoWorktree({
}
await removeDirectoryWithRetries(resolvedWorktree);
await pruneWorktreesBestEffort(cwd);
}
if (cwd) {
try {
await runGitCommand(["worktree", "prune"], { cwd, timeout: 30_000 });
} catch {
// not critical; git will prune lazily
}
async function pruneWorktreesBestEffort(cwd: string | null): Promise<void> {
if (!cwd) return;
try {
await runGitCommand(["worktree", "prune"], { cwd, timeout: 30_000 });
} catch {
// not critical; git will prune lazily
}
}
async function prepareAndTryPluginWorktreeRemove(options: {
cwd: string | null;
resolvedWorktree: string;
teardownCwds?: string[];
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
worktreeManagerPluginId?: string | null;
removeReason: "archive" | "rollback";
untrusted: boolean;
signal?: AbortSignal;
}): Promise<boolean> {
const {
cwd,
resolvedWorktree,
teardownCwds,
worktreeManagers,
worktreeManagerPluginId,
removeReason,
untrusted,
signal,
} = options;
for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) {
await runWorktreeTeardownCommands({
worktreePath: resolvedWorktree,
teardownCwd,
});
}
const effectiveManagerPluginId =
worktreeManagerPluginId !== undefined
? worktreeManagerPluginId
: ((await readPaseoWorktreeMetadata(resolvedWorktree).catch(() => null))
?.worktreeManagerPluginId ?? null);
const branch = effectiveManagerPluginId
? await getCurrentBranch(resolvedWorktree).catch(() => null)
: null;
const commit = await readWorktreeHead(resolvedWorktree);
if (commit) {
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], {
cwd: resolvedWorktree,
});
}
if (!effectiveManagerPluginId || !worktreeManagers) {
return false;
}
const removedByPlugin = await worktreeManagers.removeWorktree(
{
repoRoot: cwd,
path: resolvedWorktree,
branch,
reason: removeReason,
force: true,
untrusted,
},
{ preferredPluginId: effectiveManagerPluginId, signal },
);
if (removedByPlugin === null) {
return false;
}
if (await pathExists(resolvedWorktree)) {
throw new Error(
`Plugin ${removedByPlugin.pluginId} worktree.remove reported removed, but the directory still exists: ${resolvedWorktree}`,
);
}
return true;
}
export async function rollbackCreatedPaseoWorktree(
options: DeletePaseoWorktreeOptions,
cause: unknown,
@@ -1568,6 +1662,242 @@ export async function createWorktree({
}
}
export interface AdoptPluginWorktreeOptions {
cwd: string;
source: WorktreeSource;
worktreePath: string;
worktreeManagerPluginId: string;
/** Worktree paths that existed before creation; an overlap fails instead of hijacking user worktrees. */
existingWorktreePaths?: ReadonlySet<string>;
}
/**
* Roll back a newly created worktree that failed adoption or path verification.
* Only touches a directory that was absent from `existingWorktreePaths` and
* shares the source repository's Git common dir.
*/
export async function cleanupFailedPluginWorktree(options: {
cwd: string;
candidatePath: string;
existingWorktreePaths?: ReadonlySet<string>;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
worktreeManagerPluginId: string;
untrusted?: boolean;
paseoHome?: string;
worktreesBaseRoot?: string;
}): Promise<void> {
const {
cwd,
candidatePath,
existingWorktreePaths,
worktreeManagers,
worktreeManagerPluginId,
untrusted,
paseoHome,
worktreesBaseRoot,
} = options;
let rootPath: string;
try {
const { stdout } = await runGitCommand(["rev-parse", "--show-toplevel"], {
cwd: candidatePath,
});
rootPath = await normalizePathForOwnership(stdout.trim());
} catch {
return;
}
if (existingWorktreePaths?.has(rootPath)) {
return;
}
const [worktreeCommonDir, repoCommonDir] = await Promise.all([
getGitCommonDir(rootPath).catch(() => null),
getGitCommonDir(cwd).catch(() => null),
]);
if (
!worktreeCommonDir ||
!repoCommonDir ||
(await normalizePathForOwnership(worktreeCommonDir)) !==
(await normalizePathForOwnership(repoCommonDir))
) {
return;
}
await deletePaseoWorktree({
cwd,
worktreePath: rootPath,
teardownCwds: [],
paseoHome,
worktreesBaseRoot,
registryProven: true,
worktreeManagers,
worktreeManagerPluginId,
removeReason: "rollback",
untrusted,
});
}
/**
* Verify and adopt a worktree created or restored by a worktree manager plugin.
* Paseo validates Git worktree postconditions and writes `paseo/worktree.json`
* so diffs, PR/MR lookup hints, listing, ownership, and removal continue to work.
*/
export function adoptPluginWorktree(
options: AdoptPluginWorktreeOptions & {
source: Exclude<WorktreeSource, { kind: "restore-commit" }>;
},
): Promise<CreatedWorktree>;
export function adoptPluginWorktree(
options: AdoptPluginWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
export async function adoptPluginWorktree(
options: AdoptPluginWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }> {
const { cwd, source, worktreePath, worktreeManagerPluginId, existingWorktreePaths } = options;
const normalizedPath = await normalizePathForOwnership(worktreePath);
if (existingWorktreePaths?.has(normalizedPath)) {
throw new Error(
`Plugin ${worktreeManagerPluginId} returned an already-existing worktree: ${normalizedPath}`,
);
}
const { stdout: rootStdout } = await runGitCommand(["rev-parse", "--show-toplevel"], {
cwd: normalizedPath,
}).catch(() => {
throw new Error(
`Plugin ${worktreeManagerPluginId} did not create a Git worktree at: ${normalizedPath}`,
);
});
if ((await normalizePathForOwnership(rootStdout.trim())) !== normalizedPath) {
throw new Error(
`Plugin ${worktreeManagerPluginId} created a worktree whose root is not the returned path: ${normalizedPath}`,
);
}
const [worktreeCommonDir, repoCommonDir] = await Promise.all([
getGitCommonDir(normalizedPath),
getGitCommonDir(cwd),
]);
if (
(await normalizePathForOwnership(worktreeCommonDir)) !==
(await normalizePathForOwnership(repoCommonDir))
) {
throw new Error(
`Plugin ${worktreeManagerPluginId} created a worktree outside the repository: ${normalizedPath}`,
);
}
const { stdout: branchStdout } = await runGitCommand(["rev-parse", "--abbrev-ref", "HEAD"], {
cwd: normalizedPath,
});
const rawBranch = branchStdout.trim();
const detached = !rawBranch || rawBranch === "HEAD";
if (detached && source.kind !== "restore-commit") {
throw new Error(
`Plugin ${worktreeManagerPluginId} created a worktree with a detached HEAD: ${normalizedPath}`,
);
}
const branchName = detached ? null : rawBranch;
const metadata = await resolveAdoptedWorktreeMetadata({ cwd, source, branchName });
await writePaseoWorktreeMetadata(normalizedPath, {
baseRefName: metadata.baseRefName,
...(metadata.baseRef ? { baseRef: metadata.baseRef } : {}),
...(metadata.changeRequestLookupTarget
? { changeRequestLookupTarget: metadata.changeRequestLookupTarget }
: {}),
worktreeManagerPluginId,
});
await seedPaseoConfigFile({ sourceCwd: cwd, targetCwd: normalizedPath });
return {
branchName,
worktreePath: normalizedPath,
comparisonBaseRef: metadata.baseRef ?? metadata.baseRefName,
worktreeManagerPluginId,
};
}
async function tryResolveExactBaseRef(cwd: string, ref: string): Promise<string | undefined> {
try {
return await resolveBaseBranchForWorktree(cwd, ref);
} catch {
return undefined;
}
}
function branchChangeRequestHint(
branchName: string | null,
): { changeRequestLookupTarget: PaseoWorktreeChangeRequestHint } | Record<string, never> {
if (!branchName) return {};
return {
changeRequestLookupTarget: createPaseoWorktreeChangeRequestHint({
headRef: branchName,
localBranchName: branchName,
}),
};
}
async function resolveAdoptedChangeRequestMetadata(
cwd: string,
source: Extract<WorktreeSource, { kind: "checkout-change-request" | "checkout-github-pr" }>,
branchName: string | null,
): Promise<{
baseRefName: string;
baseRef?: string;
changeRequestLookupTarget: PaseoWorktreeChangeRequestHint;
}> {
const changeRequestNumber =
source.kind === "checkout-github-pr" ? source.githubPrNumber : source.changeRequestNumber;
const baseRefName = normalizeRequiredBaseBranch(source.baseRefName);
const baseRef = await tryResolveExactBaseRef(cwd, source.baseRefName);
return {
baseRefName,
...(baseRef ? { baseRef } : {}),
changeRequestLookupTarget: createPaseoWorktreeChangeRequestHint({
headRef: source.headRef,
...(source.headRepositoryOwner ? { headRepositoryOwner: source.headRepositoryOwner } : {}),
changeRequestNumber,
...(branchName ? { localBranchName: branchName } : {}),
}),
};
}
async function resolveAdoptedWorktreeMetadata(options: {
cwd: string;
source: WorktreeSource;
branchName: string | null;
}): Promise<{
baseRefName: string;
baseRef?: string;
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
}> {
const { cwd, source, branchName } = options;
if (source.kind === "checkout-change-request" || source.kind === "checkout-github-pr") {
return resolveAdoptedChangeRequestMetadata(cwd, source, branchName);
}
if (source.kind === "checkout-branch") {
const resolvedBranch = branchName ?? source.branchName;
const baseRefName = await resolveCheckoutBranchBaseRef(cwd, resolvedBranch);
return { baseRefName, ...branchChangeRequestHint(resolvedBranch) };
}
if (source.kind === "branch-off") {
const baseRefName = normalizeRequiredBaseBranch(source.baseBranch);
const baseRef = await tryResolveExactBaseRef(cwd, source.baseBranch);
return { baseRefName, ...(baseRef ? { baseRef } : {}), ...branchChangeRequestHint(branchName) };
}
if (source.kind === "restore") {
const baseRefName = normalizeRequiredBaseBranch(
source.baseRef ?? branchName ?? source.branchName,
);
const baseRef =
source.baseRef && isQualifiedRef(source.baseRef)
? await tryResolveExactBaseRef(cwd, source.baseRef)
: undefined;
return { baseRefName, ...(baseRef ? { baseRef } : {}), ...branchChangeRequestHint(branchName) };
}
const baseRefName = normalizeRequiredBaseBranch(source.baseRef);
const baseRef =
source.kind === "restore-from-base" || isQualifiedRef(source.baseRef)
? await tryResolveExactBaseRef(cwd, source.baseRef)
: undefined;
return { baseRefName, ...(baseRef ? { baseRef } : {}) };
}
interface ResolveWorktreeSourcePlanOptions {
cwd: string;
source: WorktreeSource;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

@@ -89,6 +89,7 @@ import {
PiIcon,
} from "~/components/agent-icons";
import { DiscordIcon, GitHubIcon, SlackIcon } from "~/components/brand-icons";
import { PaseoHubMark } from "~/components/paseo-brand";
import {
MobileChat,
MobileDiff,
@@ -515,6 +516,7 @@ function TurnkeySection() {
description={t("landing.runAnywhere.teamsDescription")}
ctaHref={localize("/hub")}
ctaLabel={t("landing.runAnywhere.teamsCta")}
ctaIcon={PASEO_HUB_CTA_ICON}
showIntegrationIcons
/>
</div>
@@ -523,12 +525,15 @@ function TurnkeySection() {
);
}
const PASEO_HUB_CTA_ICON = <PaseoHubMark className="h-4 w-4 shrink-0" />;
function TurnkeyExtensionCard({
icon: Icon,
title,
description,
ctaHref,
ctaLabel,
ctaIcon,
showIntegrationIcons = false,
}: {
icon: LucideIcon;
@@ -536,6 +541,7 @@ function TurnkeyExtensionCard({
description: string;
ctaHref: string;
ctaLabel: string;
ctaIcon?: React.ReactNode;
showIntegrationIcons?: boolean;
}) {
return (
@@ -545,6 +551,7 @@ function TurnkeyExtensionCard({
href={ctaHref}
className="inline-flex items-center gap-1.5 rounded-full bg-foreground px-2.5 py-1.5 text-xs text-background transition-colors hover:bg-foreground/90"
>
{ctaIcon}
{ctaLabel}
<ArrowRight className="h-3.5 w-3.5" />
</a>
@@ -1,21 +1,11 @@
// Exact SVG paths from packages/app/src/components/icons/
import { OpenCodeIcon as OpenCodeBrandIcon, PiIcon as PiBrandIcon } from "../agent-icons";
import { PaseoMark as CanonicalPaseoMark } from "../paseo-brand";
/** The Paseo brand swirl — public/logo.svg, drawn as a small sidebar avatar mark. */
/** The Paseo butterfly mark, drawn as a small sidebar avatar or tool-call mark. */
export function PaseoMark({ size = 13, className }: { size?: number; className?: string }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 700 700"
fill="currentColor"
aria-hidden="true"
className={className}
>
<path d="M291.495 91.399C333.897 104.892 379.155 135.075 416.229 173.191C453.389 211.394 484.429 259.725 495.708 311.251C497.555 319.693 498.865 328.216 499.586 336.776C509.755 326.554 519.867 317.815 529.89 311.547C540.647 304.821 553.808 299.297 568.641 299.785C584.29 300.299 597.395 307.326 607.747 317.632C632.173 341.947 629.612 372.898 619.872 397.936C610.185 422.833 591.557 447.826 572.732 469.124C553.591 490.78 532.713 510.308 516.779 524.318C508.775 531.355 501.936 537.073 497.07 541.052C494.635 543.043 492.689 544.603 491.334 545.679C490.657 546.217 490.126 546.635 489.756 546.926C489.571 547.071 489.425 547.184 489.321 547.265C489.269 547.305 489.227 547.338 489.196 547.362C489.181 547.374 489.168 547.385 489.157 547.393C489.153 547.397 489.147 547.401 489.144 547.403C489.134 547.4 488.837 547.06 473.001 528.499L489.135 547.411C478.157 555.911 462.033 554.334 453.122 543.89C444.213 533.448 445.887 518.094 456.861 509.592C456.863 509.591 456.865 509.588 456.869 509.586C456.88 509.577 456.902 509.561 456.933 509.536C456.997 509.487 457.101 509.404 457.245 509.292C457.533 509.066 457.979 508.715 458.569 508.247C459.749 507.31 461.506 505.901 463.742 504.073C468.216 500.414 474.589 495.088 482.073 488.508C497.114 475.284 516.315 457.282 533.578 437.75C551.157 417.862 565.26 398.01 571.859 381.048C578.403 364.227 575.681 356.302 570.724 351.367C568.928 349.579 567.744 348.902 567.267 348.676C566.888 348.496 566.811 348.52 566.804 348.52C566.605 348.513 563.971 348.537 557.953 352.3C545.161 360.299 528.815 377.492 506.807 403.867C494.927 418.106 481.871 434.435 467.547 451.957C463.709 457.28 459.503 462.538 454.91 467.717L454.702 467.549C420.808 508.347 380.37 553.856 332.335 593.848C301.853 619.226 262.656 622.597 228.642 614.743C194.834 606.936 162.658 587.448 142.217 561.686C108.054 518.631 100.57 469.801 108.223 427.836C115.56 387.606 137.391 351.005 166.502 331.557C161.248 315.813 156.813 299.49 153.519 283.013C142.593 228.368 143.239 167.031 174.28 119.619C186.922 100.31 205.846 89.1535 227.387 85.2773C248.1 81.5504 270.278 84.648 291.495 91.399ZM378.642 206.356C345.773 172.563 307.463 147.917 275.208 137.654C259.096 132.527 246.171 131.514 236.828 133.195C228.314 134.727 222.227 138.497 217.721 145.38C196.712 177.468 193.858 224.004 203.82 273.827C206.532 287.394 210.127 300.834 214.345 313.817C236.45 310.276 260.156 311.463 281.22 317.11C319.621 327.403 357.501 355.419 357.501 405.654C357.501 435.255 339.111 465.136 307.278 473.815C273.211 483.103 238.854 464.822 213.105 427.541C203.716 413.947 194.443 397.766 185.947 379.89C174.028 392.223 163.08 411.953 158.673 436.118C153.128 466.518 158.514 501.286 183.085 532.253C195.993 548.522 217.742 562.031 240.771 567.349C263.594 572.619 284.147 569.24 298.664 557.154C349.383 514.927 390.709 466.547 426.366 422.952C448.879 390.86 453.195 356.06 445.578 321.265C436.703 280.718 411.425 240.06 378.642 206.356ZM306.296 405.722C306.296 384.769 292.223 370.736 267.284 364.051C256.012 361.03 244.156 360.087 233.095 360.771C240.361 375.935 248.168 389.513 255.897 400.704C275.647 429.298 289.989 427.822 293.247 426.934C298.737 425.437 306.296 418.161 306.296 405.722Z" />
</svg>
);
return <CanonicalPaseoMark width={size} height={size} className={className} />;
}
/** GitHub mark for the toolbar and PR panel. */
@@ -1,25 +1,11 @@
// Small shared bits for the mobile mockups. The Paseo butterfly mark is the
// app icon (packages/website/public/favicon.svg) with the black plate dropped,
// so it can be tinted and placed on any tile. Tile fills are the app's identity
// Small shared bits for the mobile mockups. Tile fills are the app's identity
// palette — packages/app/src/styles/identity-colors.ts — surfaced as
// `--color-mock-tile-*` tokens in styles.css.
const BUTTERFLY_D =
"M291.495 91.399C333.897 104.892 379.155 135.075 416.229 173.191C453.389 211.394 484.429 259.725 495.708 311.251C497.555 319.693 498.865 328.216 499.586 336.776C509.755 326.554 519.867 317.815 529.89 311.547C540.647 304.821 553.808 299.297 568.641 299.785C584.29 300.299 597.395 307.326 607.747 317.632C632.173 341.947 629.612 372.898 619.872 397.936C610.185 422.833 591.557 447.826 572.732 469.124C553.591 490.78 532.713 510.308 516.779 524.318C508.775 531.355 501.936 537.073 497.07 541.052C494.635 543.043 492.689 544.603 491.334 545.679C490.657 546.217 490.126 546.635 489.756 546.926C489.571 547.071 489.425 547.184 489.321 547.265C489.269 547.305 489.227 547.338 489.196 547.362C489.181 547.374 489.168 547.385 489.157 547.393C489.153 547.397 489.147 547.401 489.144 547.403C489.134 547.4 488.837 547.06 473.001 528.499L489.135 547.411C478.157 555.911 462.033 554.334 453.122 543.89C444.213 533.448 445.887 518.094 456.861 509.592C456.863 509.591 456.865 509.588 456.869 509.586C456.88 509.577 456.902 509.561 456.933 509.536C456.997 509.487 457.101 509.404 457.245 509.292C457.533 509.066 457.979 508.715 458.569 508.247C459.749 507.31 461.506 505.901 463.742 504.073C468.216 500.414 474.589 495.088 482.073 488.508C497.114 475.284 516.315 457.282 533.578 437.75C551.157 417.862 565.26 398.01 571.859 381.048C578.403 364.227 575.681 356.302 570.724 351.367C568.928 349.579 567.744 348.902 567.267 348.676C566.888 348.496 566.811 348.52 566.804 348.52C566.605 348.513 563.971 348.537 557.953 352.3C545.161 360.299 528.815 377.492 506.807 403.867C494.927 418.106 481.871 434.435 467.547 451.957C463.709 457.28 459.503 462.538 454.91 467.717L454.702 467.549C420.808 508.347 380.37 553.856 332.335 593.848C301.853 619.226 262.656 622.597 228.642 614.743C194.834 606.936 162.658 587.448 142.217 561.686C108.054 518.631 100.57 469.801 108.223 427.836C115.56 387.606 137.391 351.005 166.502 331.557C161.248 315.813 156.813 299.49 153.519 283.013C142.593 228.368 143.239 167.031 174.28 119.619C186.922 100.31 205.846 89.1535 227.387 85.2773C248.1 81.5504 270.278 84.648 291.495 91.399ZM378.642 206.356C345.773 172.563 307.463 147.917 275.208 137.654C259.096 132.527 246.171 131.514 236.828 133.195C228.314 134.727 222.227 138.497 217.721 145.38C196.712 177.468 193.858 224.004 203.82 273.827C206.532 287.394 210.127 300.834 214.345 313.817C236.45 310.276 260.156 311.463 281.22 317.11C319.621 327.403 357.501 355.419 357.501 405.654C357.501 435.255 339.111 465.136 307.278 473.815C273.211 483.103 238.854 464.822 213.105 427.541C203.716 413.947 194.443 397.766 185.947 379.89C174.028 392.223 163.08 411.953 158.673 436.118C153.128 466.518 158.514 501.286 183.085 532.253C195.993 548.522 217.742 562.031 240.771 567.349C263.594 572.619 284.147 569.24 298.664 557.154C349.383 514.927 390.709 466.547 426.366 422.952C448.879 390.86 453.195 356.06 445.578 321.265C436.703 280.718 411.425 240.06 378.642 206.356ZM306.296 405.722C306.296 384.769 292.223 370.736 267.284 364.051C256.012 361.03 244.156 360.087 233.095 360.771C240.361 375.935 248.168 389.513 255.897 400.704C275.647 429.298 289.989 427.822 293.247 426.934C298.737 425.437 306.296 418.161 306.296 405.722Z";
import { PaseoMark as CanonicalPaseoMark } from "../../paseo-brand";
export function PaseoMark({ size = 20, className }: { size?: number; className?: string }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 700 700"
fill="currentColor"
className={className}
aria-hidden="true"
>
<path transform="translate(350,350) scale(1.05) translate(-350,-350)" d={BUTTERFLY_D} />
</svg>
);
return <CanonicalPaseoMark width={size} height={size} className={className} />;
}
/** A hashed identity tile — one letter on a muted identity fill. */
@@ -0,0 +1,74 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { HubLockup, PaseoHubLockup, PaseoHubMark, PaseoLockup, PaseoMark } from "./paseo-brand";
const REPO_ROOT = path.resolve(import.meta.dirname, "../../../..");
const BRAND_ROOT = path.join(REPO_ROOT, "assets/brand");
const WEBSITE_PUBLIC = path.join(REPO_ROOT, "packages/website/public");
function extractPathData(svg: string): string[] {
return [...svg.matchAll(/\bd="([^"]+)"/g)].map((m) => m[1]);
}
describe("paseo brand assets", () => {
it("renders canonical Paseo and Paseo Hub marks with currentColor", () => {
const paseoHtml = renderToStaticMarkup(<PaseoMark className="h-6 w-6" />);
const hubHtml = renderToStaticMarkup(<PaseoHubMark className="h-6 w-6" />);
const canonicalPaseo = readFileSync(path.join(BRAND_ROOT, "marks/paseo-white.svg"), "utf8");
const canonicalHub = readFileSync(path.join(BRAND_ROOT, "marks/paseo-hub-white.svg"), "utf8");
expect(paseoHtml).toContain('viewBox="0 0 700 700"');
expect(paseoHtml).toContain('stroke="currentColor"');
expect(paseoHtml).toContain('stroke-width="50"');
expect(extractPathData(paseoHtml)).toEqual(extractPathData(canonicalPaseo));
expect(hubHtml).toContain('viewBox="0 0 700 700"');
expect(hubHtml).toContain('stroke="currentColor"');
expect(hubHtml).toContain('stroke-width="50"');
expect(extractPathData(hubHtml)).toEqual(extractPathData(canonicalHub));
});
it("renders canonical Paseo, Paseo Hub, and Hub lockups at shared 144-unit height", () => {
const cases = [
{ Component: PaseoLockup, file: "lockups/paseo-white.svg", width: 580 },
{ Component: PaseoHubLockup, file: "lockups/paseo-hub-white.svg", width: 842 },
{ Component: HubLockup, file: "lockups/hub-white.svg", width: 461 },
];
for (const { Component, file, width } of cases) {
const html = renderToStaticMarkup(<Component className="h-6 w-auto" />);
const canonical = readFileSync(path.join(BRAND_ROOT, file), "utf8");
expect(html).toContain(`viewBox="0 0 ${width} 144"`);
expect(html).toContain(`width="${width}"`);
expect(html).toContain('height="144"');
expect(html).toContain('stroke="currentColor"');
expect(html).toContain('fill="currentColor"');
expect(extractPathData(html)).toEqual(extractPathData(canonical));
}
});
it("keeps public/logo.svg and public/favicon.svg aligned with assets/brand", () => {
const canonicalPaseo = readFileSync(path.join(BRAND_ROOT, "marks/paseo-white.svg"), "utf8");
const publicLogo = readFileSync(path.join(WEBSITE_PUBLIC, "logo.svg"), "utf8");
const publicFavicon = readFileSync(path.join(WEBSITE_PUBLIC, "favicon.svg"), "utf8");
expect(publicLogo).toBe(canonicalPaseo);
expect(publicFavicon).toContain('<rect width="700" height="700" rx="156" fill="#000000"');
expect(extractPathData(publicFavicon)).toEqual(extractPathData(canonicalPaseo));
});
it("ships a multi-size favicon.ico with 48, 32, and 16px entries", () => {
const ico = readFileSync(path.join(WEBSITE_PUBLIC, "favicon.ico"));
expect(ico.readUInt16LE(0)).toBe(0);
expect(ico.readUInt16LE(2)).toBe(1);
const count = ico.readUInt16LE(4);
const sizes: number[] = [];
for (let i = 0; i < count; i += 1) {
sizes.push(ico[6 + i * 16] || 256);
}
expect(sizes).toEqual([48, 32, 16]);
});
});
@@ -0,0 +1,154 @@
// Canonical Paseo and Paseo Hub brand marks and lockups, sourced directly from
// `assets/brand/` (see `assets/brand/README.md`).
import type * as React from "react";
import hubLockupSvg from "../../../../assets/brand/lockups/hub-white.svg?raw";
import paseoHubLockupSvg from "../../../../assets/brand/lockups/paseo-hub-white.svg?raw";
import paseoLockupSvg from "../../../../assets/brand/lockups/paseo-white.svg?raw";
import paseoHubMarkSvg from "../../../../assets/brand/marks/paseo-hub-white.svg?raw";
import paseoMarkSvg from "../../../../assets/brand/marks/paseo-white.svg?raw";
interface ParsedMark {
width: number;
height: number;
viewBox: string;
path: string;
strokeWidth: number;
}
interface ParsedLockup extends ParsedMark {
wordmarkPath: string;
}
function readAttr(tag: string, name: string, source: string): string {
const match = tag.match(new RegExp(`${name}="([^"]+)"`));
if (!match) {
throw new Error(`Missing ${name} attribute in canonical brand SVG (${source})`);
}
return match[1];
}
function parseSvgHeader(svg: string, source: string) {
const svgTag = svg.match(/<svg\b[^>]*>/)?.[0];
if (!svgTag) {
throw new Error(`Missing <svg> root in canonical brand SVG (${source})`);
}
const paths = [...svg.matchAll(/<path\b[^>]*\/?>/g)].map((m) => m[0]);
return {
width: Number(readAttr(svgTag, "width", source)),
height: Number(readAttr(svgTag, "height", source)),
viewBox: readAttr(svgTag, "viewBox", source),
paths,
};
}
function parseMark(svg: string, source: string): ParsedMark {
const { width, height, viewBox, paths } = parseSvgHeader(svg, source);
if (paths.length !== 1) {
throw new Error(`Expected 1 path in brand mark SVG (${source}), found ${paths.length}`);
}
return {
width,
height,
viewBox,
path: readAttr(paths[0], "d", source),
strokeWidth: Number(readAttr(paths[0], "stroke-width", source)),
};
}
function parseLockup(svg: string, source: string): ParsedLockup {
const { width, height, viewBox, paths } = parseSvgHeader(svg, source);
if (paths.length !== 2) {
throw new Error(`Expected 2 paths in brand lockup SVG (${source}), found ${paths.length}`);
}
return {
width,
height,
viewBox,
path: readAttr(paths[0], "d", source),
strokeWidth: Number(readAttr(paths[0], "stroke-width", source)),
wordmarkPath: readAttr(paths[1], "d", source),
};
}
const PASEO_MARK = parseMark(paseoMarkSvg, "marks/paseo-white.svg");
const PASEO_HUB_MARK = parseMark(paseoHubMarkSvg, "marks/paseo-hub-white.svg");
const PASEO_LOCKUP = parseLockup(paseoLockupSvg, "lockups/paseo-white.svg");
const PASEO_HUB_LOCKUP = parseLockup(paseoHubLockupSvg, "lockups/paseo-hub-white.svg");
const HUB_LOCKUP = parseLockup(hubLockupSvg, "lockups/hub-white.svg");
function BrandMark({ asset, props }: { asset: ParsedMark; props: React.SVGProps<SVGSVGElement> }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={asset.width}
height={asset.height}
viewBox={asset.viewBox}
fill="none"
aria-hidden="true"
{...props}
>
<path
d={asset.path}
stroke="currentColor"
strokeWidth={asset.strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}
function BrandLockup({
asset,
props,
}: {
asset: ParsedLockup;
props: React.SVGProps<SVGSVGElement>;
}) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={asset.width}
height={asset.height}
viewBox={asset.viewBox}
fill="none"
aria-hidden="true"
{...props}
>
<path
d={asset.path}
stroke="currentColor"
strokeWidth={asset.strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
<path d={asset.wordmarkPath} fill="currentColor" />
</svg>
);
}
/** Canonical Paseo butterfly mark (700x700 viewBox, stroked with currentColor). */
export function PaseoMark(props: React.SVGProps<SVGSVGElement>) {
return <BrandMark asset={PASEO_MARK} props={props} />;
}
/** Canonical Paseo Hub five-petal flower mark (700x700 viewBox, stroked with currentColor). */
export function PaseoHubMark(props: React.SVGProps<SVGSVGElement>) {
return <BrandMark asset={PASEO_HUB_MARK} props={props} />;
}
/** Canonical Paseo lockup (butterfly mark at 94% optical scale + Plus Jakarta Sans SemiBold). */
export function PaseoLockup(props: React.SVGProps<SVGSVGElement>) {
return <BrandLockup asset={PASEO_LOCKUP} props={props} />;
}
/** Canonical Paseo Hub lockup (flower mark + Plus Jakarta Sans SemiBold). */
export function PaseoHubLockup(props: React.SVGProps<SVGSVGElement>) {
return <BrandLockup asset={PASEO_HUB_LOCKUP} props={props} />;
}
/** Canonical Hub lockup (flower mark + "Hub"), used where Paseo is already on screen. */
export function HubLockup(props: React.SVGProps<SVGSVGElement>) {
return <BrandLockup asset={HUB_LOCKUP} props={props} />;
}
@@ -3,6 +3,7 @@ import { PLUGINS_LINKED } from "~/plugins/launch";
import "~/styles.css";
import { DiscordIcon, GitHubIcon } from "~/components/brand-icons";
import { LanguageSelector } from "~/components/language-selector";
import { PaseoLockup } from "~/components/paseo-brand";
import { useLocalizePath } from "~/i18n";
import { useStars } from "~/routes/__root";
@@ -14,9 +15,12 @@ export function SiteHeader() {
const { stars } = useStars();
return (
<header className="flex flex-col items-center gap-4 md:flex-row md:justify-between">
<a href={localize("/")} className="flex items-center gap-3">
<img src="/logo.svg" alt="Paseo" className="w-6 h-6" />
<span className="text-lg font-medium">Paseo</span>
<a
href={localize("/")}
aria-label="Paseo"
className="inline-flex items-center text-foreground"
>
<PaseoLockup className="h-[22px] w-auto" />
</a>
<div className="flex flex-wrap items-center justify-center gap-4">
{PLUGINS_LINKED && (
@@ -9,6 +9,7 @@ import { useTranslation } from "react-i18next";
import { buildDocsNavTree, getDoc, getDocs } from "~/docs";
import { splitLocalePath, useLocale, useLocalizePath } from "~/i18n";
import { LanguageSelector } from "~/components/language-selector";
import { PaseoLockup } from "~/components/paseo-brand";
import "~/styles.css";
export const Route = createFileRoute("/{-$locale}/docs")({
@@ -35,9 +36,12 @@ function DocsLayout() {
{/* Mobile header */}
<header className="lg:hidden sticky top-0 z-50 bg-background border-b border-border">
<div className="flex items-center justify-between p-4">
<Link to={localize("/")} className="flex items-center gap-3">
<img src="/logo.svg" alt="Paseo" className="w-6 h-6" />
<span className="text-lg font-medium">Paseo</span>
<Link
to={localize("/")}
aria-label="Paseo"
className="inline-flex items-center text-foreground"
>
<PaseoLockup className="h-[22px] w-auto" />
</Link>
<div className="flex items-center gap-3">
<LanguageSelector />
@@ -63,9 +67,12 @@ function DocsLayout() {
{/* Desktop sidebar */}
<aside className="hidden lg:block sticky top-0 h-screen w-60 shrink-0 border-r border-border p-6 overflow-y-auto">
<div className="flex items-center justify-between gap-3 mb-8">
<Link to={localize("/")} className="flex items-center gap-3">
<img src="/logo.svg" alt="Paseo" className="w-6 h-6" />
<span className="text-lg font-medium">Paseo</span>
<Link
to={localize("/")}
aria-label="Paseo"
className="inline-flex items-center text-foreground"
>
<PaseoLockup className="h-[22px] w-auto" />
</Link>
<LanguageSelector />
</div>
+11 -4
View File
@@ -12,6 +12,7 @@ import {
PiIcon,
} from "~/components/agent-icons";
import { DiscordIcon, GitHubIcon, SlackIcon } from "~/components/brand-icons";
import { HubLockup, PaseoHubLockup, PaseoHubMark } from "~/components/paseo-brand";
import { AGENT_PAGES } from "~/data/agent-pages";
import { FAQItem } from "~/components/faq-item";
import { SiteShell } from "~/components/site-shell";
@@ -63,7 +64,10 @@ function Hub() {
const { plans } = Route.useLoaderData();
return (
<SiteShell width="default">
<h1 className="text-3xl font-medium tracking-tight mb-4">{t("hub.title")}</h1>
<h1 className="mb-5">
<PaseoHubLockup className="h-9 md:h-10 w-auto text-foreground" />
<span className="sr-only">{t("hub.title")}</span>
</h1>
<p className="text-lg text-white/70 leading-relaxed max-w-2xl">{t("hub.intro")}</p>
<p className="text-white/40 text-sm mt-3">{t("hub.runIt")}</p>
@@ -379,7 +383,7 @@ function DemoMessage({
<div className="flex gap-3">
<div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.06]">
{bot ? (
<img src="/logo.svg" alt="" className="h-4 w-4" />
<PaseoHubMark className="h-5 w-5 text-white" />
) : (
<span className="text-xs font-medium text-white/60">M</span>
)}
@@ -478,8 +482,11 @@ function Shape() {
<Connector label={t("hub.shape.webhooks")} />
<div className="w-full max-w-xs rounded-xl border border-white/20 bg-white/[0.06] px-6 py-5 text-center">
<p className="font-medium">{t("hub.shape.hub")}</p>
<p className="text-xs text-muted-foreground mt-1">{t("hub.shape.hubHosting")}</p>
<p className="flex justify-center">
<HubLockup className="h-[22px] w-auto text-foreground" />
<span className="sr-only">{t("hub.shape.hub")}</span>
</p>
<p className="text-xs text-muted-foreground mt-1.5">{t("hub.shape.hubHosting")}</p>
</div>
<Connector label={t("hub.shape.sameRpcs")} />
+5
View File
@@ -2,3 +2,8 @@ declare module "*.md?raw" {
const content: string;
export default content;
}
declare module "*.svg?raw" {
const content: string;
export default content;
}
+20
View File
@@ -0,0 +1,20 @@
# Worktrunk plugin example
Delegates Paseo worktree creation, removal, and restoration to [Worktrunk](https://worktrunk.dev) (`wt`), and updates `wt list` activity markers (`🤖` / `💬`) as agents run.
## What it does
- **Create:** routes branch-off, branch checkout, GitHub PR (`pr:N`), and GitLab MR (`mr:N`) creation through `wt switch --no-cd --yes --format=json` so Worktrunk controls placement, branch setup, and `pre-start` / `post-start` hooks. Unsupported forges decline and fall back to Paseo's Git checkout.
- **Remove:** routes archive and creation rollback through `wt remove --foreground --no-delete-branch --yes` so Worktrunk runs `pre-remove` and `post-remove` hooks while keeping the branch for Paseo's restore flow.
- **Restore:** routes archived worktree restoration through `wt switch --path <recorded-path>` for branch restores, and falls back to Paseo for detached-commit restores.
- **Activity markers:** sets `🤖` when an agent turn starts, `💬` when a turn ends or awaits permission, and clears the marker on close or archive. Background helpers are skipped.
## Prerequisites
Install Worktrunk (`wt`, or `git-wt.exe` on Windows) on `PATH`, or set `WORKTRUNK_BIN` in the daemon environment.
## Install
```bash
paseo plugin install /absolute/path/to/plugin-examples/worktrunk
```
+44
View File
@@ -0,0 +1,44 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import {
WAITING_MARKER,
WORKING_MARKER,
createWithWorktrunk,
removeWithWorktrunk,
restoreWithWorktrunk,
setActivityMarker,
} from "./server/wt.js";
export default function contribute(server: PluginServerContext) {
const cleanups = [
server.registerWorktreeManager({
create: (request, { signal }) => createWithWorktrunk(request, signal),
remove: (request, { signal }) => removeWithWorktrunk(request, signal),
restore: (request, { signal }) => restoreWithWorktrunk(request, signal),
}),
server.addHook("agent.turn.before", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, WORKING_MARKER, signal);
}),
server.addHook("agent.turn.after", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, WAITING_MARKER, signal);
}),
server.addHook("agent.permission.before", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, WAITING_MARKER, signal);
}),
server.addHook("agent.close.after", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, null, signal);
}),
server.addHook("agent.archive.after", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, null, signal);
}),
];
return () => {
for (const cleanup of cleanups) cleanup();
};
}
@@ -0,0 +1,6 @@
{
"id": "worktrunk",
"name": "Worktrunk",
"description": "Manage Git worktrees and agent activity markers through Worktrunk (wt).",
"requirements": { "paseo": ">=0.16.0" }
}
+244
View File
@@ -0,0 +1,244 @@
import { lstatSync } from "node:fs";
import { delimiter, join } from "node:path";
import {
execCommand,
type PluginWorktreeCreateInput,
type PluginWorktreeRemoveRequest,
type PluginWorktreeRestoreRequest,
} from "@getpaseo/plugin/server";
const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
export const WORKING_MARKER = "🤖";
export const WAITING_MARKER = "💬";
interface SwitchJsonOutput {
path: string;
action?: string;
}
/**
* Resolve the Worktrunk CLI executable.
* Honors `WORKTRUNK_BIN` first; on Windows prefers `git-wt.exe` and skips the
* WindowsApps alias that points to Windows Terminal.
*/
export function resolveWorktrunkBin(): string | null {
const configured = process.env.WORKTRUNK_BIN?.trim();
if (configured) return configured;
if (process.platform !== "win32") return "wt";
const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
const findOnPath = (name: string) =>
dirs
.map((dir) => join(dir, name))
.find((candidate) => {
try {
lstatSync(candidate);
return true;
} catch {
return false;
}
});
if (findOnPath("git-wt.exe")) return "git-wt.exe";
const wt = findOnPath("wt.exe");
return wt && !/[\\/]WindowsApps[\\/]/i.test(wt) ? "wt" : null;
}
async function runWt(
args: string[],
options: { cwd?: string; signal?: AbortSignal } = {},
): Promise<string> {
const bin = resolveWorktrunkBin();
if (!bin) {
throw new Error(
"Worktrunk CLI not found on PATH. Install wt (or git-wt.exe on Windows) or set WORKTRUNK_BIN.",
);
}
try {
const { stdout } = await execCommand(bin, args, {
cwd: options.cwd,
signal: options.signal,
maxBuffer: MAX_OUTPUT_BYTES,
});
return stdout;
} catch (error) {
const stderr = (error as { stderr?: string }).stderr?.trim();
throw new Error(stderr || (error instanceof Error ? error.message : String(error)), {
cause: error,
});
}
}
function tryParseSwitchOutput(stdout: string | undefined): SwitchJsonOutput | null {
if (!stdout?.trim()) return null;
try {
const parsed = JSON.parse(stdout) as { path?: unknown; action?: unknown };
if (typeof parsed.path !== "string" || parsed.path.length === 0) return null;
return {
path: parsed.path,
...(typeof parsed.action === "string" ? { action: parsed.action } : {}),
};
} catch {
return null;
}
}
function parseSwitchOutput(stdout: string): SwitchJsonOutput {
const parsed = tryParseSwitchOutput(stdout);
if (!parsed) {
throw new Error("wt switch --format=json output did not include a worktree path");
}
return parsed;
}
function isUntrustedCreate(request: PluginWorktreeCreateInput): boolean {
return request.kind === "checkout-change-request" && Boolean(request.headRepository);
}
function hookFlags(untrusted: boolean): string[] {
// Never approve repository-defined hooks on untrusted checkouts such as fork PRs.
return untrusted ? ["--no-hooks"] : ["--yes"];
}
export function buildCreateArgs(request: PluginWorktreeCreateInput): string[] | null {
const common = [
"-C",
request.repoRoot,
"switch",
"--no-cd",
...hookFlags(isUntrustedCreate(request)),
"--format=json",
];
switch (request.kind) {
case "branch-off":
return [
...common,
"--create",
request.branch,
"--base",
request.startPoint ?? request.baseRef,
];
case "checkout-branch":
return [...common, request.branch];
case "checkout-change-request":
if (request.forge === "github") return [...common, `pr:${request.changeRequestNumber}`];
if (request.forge === "gitlab") return [...common, `mr:${request.changeRequestNumber}`];
return null;
case "checkout-github-pr":
return [...common, `pr:${request.githubPrNumber}`];
}
}
async function cleanupPartiallyCreatedWorktree(repoRoot: string, error: unknown): Promise<void> {
// Worktrunk prints `{ path, action: "created" }` on stdout even when a later hook exits non-zero.
const stdout =
error instanceof Error && error.cause && typeof error.cause === "object"
? (error.cause as { stdout?: string }).stdout
: undefined;
const parsed = tryParseSwitchOutput(stdout);
if (!parsed || (parsed.action !== undefined && parsed.action !== "created")) return;
await runWt([
"-C",
repoRoot,
"remove",
"--foreground",
"--no-delete-branch",
"--no-hooks",
"--force",
parsed.path,
]).catch(() => {});
}
export async function createWithWorktrunk(
request: PluginWorktreeCreateInput,
signal: AbortSignal,
): Promise<{ type: "created"; path: string } | undefined> {
const args = buildCreateArgs(request);
if (!args) return undefined;
let stdout: string;
try {
stdout = await runWt(args, { signal });
} catch (error) {
await cleanupPartiallyCreatedWorktree(request.repoRoot, error);
throw error;
}
const output = parseSwitchOutput(stdout);
// If Worktrunk switched to an already-existing checkout instead of creating one,
// decline so Paseo falls back to Git (which creates a unique branch).
if (output.action !== undefined && output.action !== "created") {
return undefined;
}
return { type: "created", path: output.path };
}
export async function removeWithWorktrunk(
request: PluginWorktreeRemoveRequest,
signal: AbortSignal,
): Promise<{ type: "removed" }> {
// Run from the main repository root when available and skip repository hooks for
// untrusted workspaces (or when repoRoot is unknown) so fork PRs cannot run hooks.
const runDir = request.repoRoot ?? request.path;
const skipHooks = request.untrusted || request.repoRoot === null;
const args = [
"-C",
runDir,
"remove",
"--foreground",
"--no-delete-branch",
...hookFlags(skipHooks),
...(request.force ? ["--force"] : []),
request.path,
];
await runWt(args, { signal });
return { type: "removed" };
}
export async function restoreWithWorktrunk(
request: PluginWorktreeRestoreRequest,
signal: AbortSignal,
): Promise<{ type: "restored"; path: string } | undefined> {
if (request.target.type === "commit") {
// Detached-commit restores fall back to Paseo's built-in Git restore.
return undefined;
}
const common = [
"-C",
request.repoRoot,
"switch",
"--path",
request.path,
"--no-cd",
...hookFlags(request.untrusted),
"--format=json",
];
const args =
request.target.type === "branch"
? [...common, request.target.branch]
: [...common, "--create", request.target.branch, "--base", request.target.baseRef];
let stdout: string;
try {
stdout = await runWt(args, { signal });
} catch (error) {
await cleanupPartiallyCreatedWorktree(request.repoRoot, error);
throw error;
}
const output = parseSwitchOutput(stdout);
return { type: "restored", path: output.path };
}
export async function setActivityMarker(
cwd: string,
marker: string | null,
signal: AbortSignal,
): Promise<void> {
const args =
marker === null
? ["config", "state", "marker", "clear"]
: ["config", "state", "marker", "set", marker];
try {
await runWt(args, { cwd, signal });
} catch {
// Activity markers are best-effort and must not disrupt agent sessions.
}
}
+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
<path fill="currentColor" d="M20.9093 19.3861L19.5185 18.2413C18.7624 17.619 18.1189 16.8713 17.6157 16.0313C16.9205 14.8706 15.9599 13.8912 14.8133 13.1735L14.2533 12.8475C14.0614 12.7141 13.9276 12.5062 13.9086 12.2716C13.8963 12.1204 13.9326 11.9852 14.0171 11.8662C14.3087 11.4553 15.896 9.74698 16.1722 9.51845C16.528 9.22442 16.9243 8.97987 17.2921 8.69986C17.3443 8.66 17.3968 8.62035 17.4485 8.57989C17.4503 8.57808 17.4529 8.57668 17.4545 8.57508C17.5725 8.48195 17.6838 8.383 17.7724 8.26563C18.2036 7.76631 18.195 7.3443 18.195 7.3443C18.195 7.3443 18.1954 7.3439 18.1956 7.3437C18.1497 7.23133 17.9847 6.88163 17.6492 6.71759C17.9458 6.71178 18.2805 6.82294 18.4323 6.97156C18.6148 6.68534 18.7328 6.49967 18.9162 6.18762C18.9599 6.11352 18.9831 5.97652 18.8996 5.89981C18.8996 5.89981 18.8992 5.89981 18.8988 5.89981C18.8988 5.89981 18.8988 5.8994 18.8988 5.899C18.8972 5.8974 18.8952 5.8962 18.8936 5.8946C18.892 5.893 18.891 5.89119 18.8892 5.88939C18.8892 5.88939 18.8888 5.88939 18.8884 5.88939C18.8884 5.88939 18.8884 5.88899 18.8884 5.88859C18.885 5.88518 18.8812 5.88258 18.8776 5.87938C18.8754 5.87717 18.8736 5.87457 18.8716 5.87217C18.8692 5.87016 18.8665 5.86836 18.8643 5.86616C18.8609 5.86275 18.8587 5.85855 18.8551 5.85534C18.8551 5.85534 18.8545 5.85514 18.8543 5.85534C18.8543 5.85534 18.8543 5.85494 18.8543 5.85454C18.8527 5.85294 18.8507 5.85174 18.8491 5.85013C18.8475 5.84853 18.8463 5.84653 18.8447 5.84493C18.8447 5.84493 18.8441 5.84473 18.8439 5.84493C18.8439 5.84493 18.8439 5.84453 18.8439 5.84413C18.7672 5.7606 18.6302 5.78384 18.5561 5.8275C18.1503 6.06625 17.7555 6.32322 17.3996 6.54855C17.3996 6.54855 16.9778 6.53973 16.4783 6.97116C16.3607 7.05989 16.2618 7.17125 16.1688 7.28902C16.167 7.29082 16.1654 7.29322 16.164 7.29503C16.1234 7.3465 16.0837 7.39898 16.0441 7.45145C15.7639 7.81939 15.5195 8.21556 15.2255 8.57128C14.9971 8.84768 13.2887 10.4348 12.8777 10.7264C12.7587 10.8109 12.6237 10.8474 12.4723 10.835C12.2379 10.8161 12.0298 10.6821 11.8965 10.4903L11.5704 9.93024C10.8527 8.78318 9.87332 7.82299 8.71264 7.12778C7.87262 6.62466 7.12514 5.98092 6.50264 5.22503L5.35778 3.83421C5.3013 3.76571 5.19314 3.77693 5.15268 3.85585C5.02249 4.10941 4.77393 4.64479 4.58346 5.36483C4.57885 5.38186 4.58286 5.39988 4.59407 5.4135C4.83082 5.69952 5.37901 6.32983 6.03196 6.863C6.07742 6.90005 6.04017 6.97336 5.98369 6.95774C5.42047 6.80432 4.87288 6.55796 4.46308 6.34805C4.42964 6.33103 4.38918 6.35226 4.38437 6.38951C4.32068 6.89985 4.30425 7.46027 4.37155 8.05112C4.37355 8.07035 4.38577 8.08697 4.4036 8.09479C4.87088 8.29808 5.61816 8.59311 6.40269 8.78078C6.45958 8.7944 6.45777 8.87632 6.40029 8.88733C5.78941 9.0023 5.14968 9.02794 4.62973 9.02113C4.59327 9.02073 4.56643 9.05518 4.57625 9.09023C4.6806 9.45896 4.822 9.8339 5.00847 10.2115C5.08559 10.3811 5.16951 10.5475 5.25944 10.7104C5.27486 10.7382 5.3047 10.7548 5.33655 10.7534C5.76577 10.7324 6.28452 10.6871 6.80608 10.595C6.89501 10.5794 6.94268 10.6964 6.86757 10.7466C6.51345 10.9834 6.13571 11.1873 5.7844 11.3551C5.73733 11.3777 5.72211 11.4378 5.75315 11.4797C5.96186 11.7625 6.19139 12.0301 6.44075 12.2794C6.44075 12.2794 7.66853 13.5441 7.70198 13.6432C8.41841 12.9096 9.59612 12.0964 10.8966 11.3864C9.15488 12.8036 8.18387 13.8499 7.69517 14.4444L7.35447 14.9225C7.17742 15.1708 7.02379 15.4346 6.89541 15.7112C6.46579 16.6356 5.75756 18.5051 5.75756 18.5051C5.70328 18.6515 5.74754 18.7959 5.84168 18.89C5.84388 18.8922 5.84609 18.8944 5.84849 18.8964C5.85069 18.8986 5.8527 18.901 5.8549 18.9032C5.94924 18.9976 6.09345 19.0416 6.23986 18.9874C6.23986 18.9874 8.10897 18.2791 9.03371 17.8495C9.31031 17.7211 9.57429 17.5673 9.82245 17.3905L10.349 17.0153C10.6278 16.8166 11.0096 16.8483 11.2517 17.0904L12.4655 18.3042C12.7148 18.5535 12.9824 18.7831 13.2652 18.9918C13.3073 19.0226 13.3672 19.0076 13.3898 18.9605C13.5579 18.6094 13.7618 18.2313 13.9983 17.8774C14.0486 17.8022 14.1657 17.8501 14.1499 17.9388C14.0576 18.4606 14.0127 18.9794 13.9915 19.4084C13.9899 19.44 14.0067 19.4701 14.0345 19.4855C14.1972 19.5756 14.3636 19.6595 14.5335 19.7364C14.911 19.9229 15.2862 20.0645 15.6547 20.1687C15.6897 20.1785 15.7242 20.1516 15.7238 20.1152C15.7168 19.595 15.7424 18.9553 15.8576 18.3446C15.8684 18.2869 15.9503 18.2851 15.9641 18.3422C16.1516 19.127 16.4466 19.8742 16.6501 20.3413C16.6579 20.3591 16.6744 20.3712 16.6938 20.3734C17.2847 20.4407 17.8451 20.4242 18.3554 20.3606C18.3929 20.3559 18.4141 20.3155 18.3969 20.2818C18.187 19.872 17.9406 19.3241 17.7872 18.7612C17.7718 18.7046 17.8449 18.6675 17.8819 18.713C18.4151 19.3659 19.0454 19.9141 19.3314 20.1508C19.345 20.1621 19.3633 20.1659 19.3801 20.1615C20.1003 19.9712 20.6357 19.7226 20.8891 19.5922C20.968 19.5518 20.9792 19.4436 20.9107 19.3871L20.9093 19.3861Z"/>
</svg>

After

Width:  |  Height:  |  Size: 4.8 KiB

+7
View File
@@ -0,0 +1,7 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import { createGooseProvider } from "./server/provider.js";
export default function contribute(server: PluginServerContext) {
server.registerProvider(createGooseProvider());
return () => {};
}
+1
View File
@@ -0,0 +1 @@
{ "id": "goose-provider", "requirements": { "paseo": ">=0.17.0" } }
@@ -0,0 +1,135 @@
import type { AcpConfigureContext, AcpRequest } from "@getpaseo/plugin/server/acp";
import type { ProviderCatalog, ProviderConfigState } from "@getpaseo/plugin/server/provider";
import { describe, expect, it } from "vitest";
import { gooseModels } from "./models.js";
const routerModel = "anthropic/claude-sonnet-4.5";
const baseCatalog: ProviderCatalog = {
models: [{ id: routerModel, label: "Sonnet" }],
modes: [],
defaultModel: routerModel,
};
const configuredProviders: AcpRequest = async (method, params) => {
if (method === "_goose/unstable/providers/list") {
expect(params).toEqual({ providerIds: [] });
return {
entries: [
{
providerId: "openrouter",
providerName: "OpenRouter",
configured: true,
models: [{ id: routerModel, name: "Sonnet" }],
},
{
providerId: "openai",
providerName: "OpenAI",
configured: true,
models: [{ id: "gpt-4o", name: "GPT-4o" }],
},
{
providerId: "anthropic",
providerName: "Anthropic",
configured: false,
models: [{ id: "sonnet", name: "Sonnet" }],
},
],
};
}
expect(method).toBe("_goose/unstable/config/read");
if (params && typeof params === "object" && "key" in params) {
if (params.key === "GOOSE_PROVIDER") return { value: "openrouter" };
if (params.key === "GOOSE_MODEL") return { value: routerModel };
}
throw new Error("Unexpected config key");
};
function configContext(request = configuredProviders) {
const writes: Array<[string, unknown]> = [];
const context: AcpConfigureContext = {
sessionId: "goose-session",
request,
config: {
async read() {
return {};
},
async set(id, value) {
writes.push([id, value]);
},
},
catalog: () => baseCatalog,
apply: async () => {},
};
return { context, writes };
}
describe("goose model transformer", () => {
it("lists configured providers and keeps slash-delimited model IDs intact", async () => {
const { context } = configContext();
expect(await gooseModels.discover(baseCatalog, context)).toEqual({
...baseCatalog,
models: [
{ id: `openrouter/${routerModel}`, label: "Sonnet", description: "OpenRouter" },
{ id: "openai/gpt-4o", label: "GPT-4o", description: "OpenAI" },
],
defaultModel: `openrouter/${routerModel}`,
});
});
it("keeps the base catalog when the RPC is unavailable", async () => {
const { context } = configContext(async () => {
throw new Error("Method not found");
});
expect(await gooseModels.discover(baseCatalog, context)).toBe(baseCatalog);
});
it("keeps the base catalog when no providers are configured", async () => {
const { context } = configContext(async () => ({ entries: [] }));
expect(await gooseModels.discover(baseCatalog, context)).toBe(baseCatalog);
});
it("sets the provider before the model and preserves slashes in the model", async () => {
const { context, writes } = configContext();
const result = await gooseModels.configure(
{ target: "model", value: `openrouter/${routerModel}` },
context,
);
expect(result).toBe("handled");
expect(writes).toEqual([
["provider", "openrouter"],
["model", routerModel],
]);
});
it.each(["gpt-4o", routerModel])("passes the legacy model %s through", async (value) => {
const { context, writes } = configContext();
expect(await gooseModels.configure({ target: "model", value }, context)).toBe("pass");
expect(writes).toEqual([]);
});
function snapshotFor(provider: string): ProviderConfigState {
return {
model: routerModel,
models: baseCatalog.models,
modes: [],
thinkingOptions: [],
settings: [
{ type: "select", id: "provider", label: "Provider", value: provider, options: [] },
],
};
}
it("namespaces models in a snapshot for an explicit provider", () => {
const snapshot = snapshotFor("openrouter");
expect(gooseModels.config(snapshot)).toEqual({
...snapshot,
model: `openrouter/${routerModel}`,
models: [{ id: `openrouter/${routerModel}`, label: "Sonnet" }],
});
});
it("keeps the snapshot unchanged while goose Default is selected", () => {
const snapshot = snapshotFor("goose");
expect(gooseModels.config(snapshot)).toBe(snapshot);
});
});
+82
View File
@@ -0,0 +1,82 @@
import type { AcpRequest, AcpTransformer } from "@getpaseo/plugin/server/acp";
import { z } from "zod";
const inventorySchema = z.object({
entries: z.array(
z.object({
providerId: z.string(),
providerName: z.string(),
configured: z.boolean(),
models: z.array(z.object({ id: z.string(), name: z.string() })),
}),
),
});
const configValueSchema = z.object({ value: z.string().min(1) });
async function configuredProviders(request: AcpRequest) {
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once supported goose versions have this RPC.
const response = await request("_goose/unstable/providers/list", { providerIds: [] }).catch(
() => null,
);
const inventory = inventorySchema.safeParse(response);
return inventory.success ? inventory.data.entries.filter((entry) => entry.configured) : [];
}
async function readDefault(request: AcpRequest, key: "GOOSE_PROVIDER" | "GOOSE_MODEL") {
const response = await request("_goose/unstable/config/read", { key }).catch(() => null);
const parsed = configValueSchema.safeParse(response);
return parsed.success ? parsed.data.value : undefined;
}
export const gooseModels = {
async discover(catalog, { request }) {
const providers = await configuredProviders(request);
if (providers.length === 0) return catalog;
const models = providers.flatMap((provider) =>
provider.models.map((model) => ({
id: `${provider.providerId}/${model.id}`,
label: model.name,
description: provider.providerName,
})),
);
if (models.length === 0) return catalog;
const [providerId, modelId] = await Promise.all([
readDefault(request, "GOOSE_PROVIDER"),
readDefault(request, "GOOSE_MODEL"),
]);
return {
...catalog,
models,
defaultModel: providerId && modelId ? `${providerId}/${modelId}` : undefined,
};
},
async configure(change, { config, request }) {
if (change.target !== "model" || !change.value) return "pass";
const separator = change.value.indexOf("/");
if (separator <= 0) return "pass";
const providerId = change.value.slice(0, separator);
const providers = await configuredProviders(request);
if (!providers.some((provider) => provider.providerId === providerId)) return "pass";
await config.set("provider", providerId);
await config.set("model", change.value.slice(separator + 1));
return "handled";
},
config(state) {
const provider = state.settings?.find((setting) => setting.id === "provider");
if (provider?.type !== "select" || !provider.value || provider.value === "goose") {
return state;
}
const namespace = (modelId: string) => `${provider.value}/${modelId}`;
return {
...state,
model: state.model === undefined ? undefined : namespace(state.model),
models: state.models.map((model) => ({ ...model, id: namespace(model.id) })),
};
},
} satisfies AcpTransformer;
+17
View File
@@ -0,0 +1,17 @@
import { runAcpProvider } from "@getpaseo/plugin/server/acp";
import type { ProviderRegistration } from "@getpaseo/plugin/server/provider";
import { gooseModels } from "./models.js";
export function createGooseProvider(): ProviderRegistration {
return {
requiresConfiguration: true,
...runAcpProvider({
id: "goose",
label: "goose",
description: "A local, extensible, open source AI agent that automates engineering tasks",
icon: "icon.svg",
command: ["goose", "acp"],
transformers: [gooseModels],
}),
};
}
+2 -1
View File
@@ -208,7 +208,7 @@ Every field except `repoRoot` and `sourceCheckout` is transformable. Return all
Paseo resolves symlinked parents and validates the returned path. It must be absolute, must not exist, and must not be the filesystem root, your home directory, the repository root, inside a `.git` directory, or an ancestor of the repository. An existing destination fails creation; Paseo never adds a suffix to a plugin-chosen path. The plugin must leave directory creation to Paseo.
Ordering: `worktree.create.before` → `git worktree add` → `worktree.create.after` → workspace registration. Restoring a missing worktree recreates it at its recorded path without running either worktree creation hook.
Ordering: `worktree.create.before` → worktree manager `create` (or `git worktree add`) → `worktree.create.after` → workspace registration. To delegate `git worktree add`, removal, and restoration to an external tool such as Worktrunk, register a [worktree manager](/docs/plugins/reference#worktree-managers) with `server.registerWorktreeManager()` instead of creating directories inside `worktree.create.before`. Restoring a missing worktree recreates it at its recorded path without running creation hooks, delegating to the owning manager's optional `restore` handler when present.
## worktree.create.after
@@ -700,6 +700,7 @@ replaces that scope's prior value.
| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection |
| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options |
| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process |
| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | Worktree manager (`create`, `remove`, `restore`) and agent activity markers |
Read logger output with `paseo plugin logs lifecycle-logger` or the host's `daemon.log`.
+8 -7
View File
@@ -205,7 +205,7 @@ server.addHook("worktree.create.before", async ({ request }) => ({
Paseo 解析父目录中的符号链接并验证返回的路径。路径必须为绝对路径且不存在,不能是文件系统根目录、用户主目录、仓库根目录、`.git` 目录内的路径或仓库的祖先目录。目标已存在时创建失败,Paseo 不会为插件选择的路径添加后缀。插件应让 Paseo 创建目录。
顺序:`worktree.create.before` → `git worktree add` → `worktree.create.after` → 注册工作区。恢复缺失的 worktree 时使用记录的原路径,不运行这两个创建钩子。
顺序:`worktree.create.before` → worktree 管理器 `create`(或 `git worktree add`)→ `worktree.create.after` → 注册工作区。若要将 `git worktree add`、移除和恢复委托给 Worktrunk 等外部工具,请使用 `server.registerWorktreeManager()` 注册 [worktree 管理器](/docs/plugins/reference#worktree-managers),而不是在 `worktree.create.before` 中创建目录。恢复缺失的 worktree 时使用记录的原路径,不运行创建钩子,并在对应管理器提供可选 `restore` 处理函数时委托给它。
## worktree.create.after {#worktreecreateafter}
@@ -677,12 +677,13 @@ Creation request
## 完整示例 {#complete-examples}
| 插件 | 包含 |
| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- |
| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区和 worktree 钩子;隐去环境变量值的 JSON 日志 |
| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree |
| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 |
| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 |
| 插件 | 包含 |
| ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区和 worktree 钩子;隐去环境变量值的 JSON 日志 |
| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree |
| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 |
| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 |
| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | worktree 管理器(`create`、`remove`、`restore`)与 Agent 活动标记 |
用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。
+6 -1
View File
@@ -572,7 +572,12 @@ export default function contribute(server: PluginServerContext) {
The shim owns the ACP process, capability mapping, session lifecycle, prompts, permissions, and
timeline conversion. Do not copy that machinery into the plugin.
Use `transformers` only for vendor differences ACP cannot describe. Validate vendor payloads with
Use `transformers` for vendor differences ACP cannot describe. The
[goose model transformer](https://github.com/getpaseo/paseo/blob/main/plugins/goose-provider/server/models.ts)
uses `context.request` to read the agent's model inventory and `config` to prefix session model IDs
with the active provider. See the [ACP adapter reference](/docs/plugins/reference#providers).
Validate vendor payloads with
Zod and leave malformed or unrelated values unchanged:
```ts
+6 -1
View File
@@ -472,7 +472,12 @@ export default function contribute(server: PluginServerContext) {
适配层负责 ACP 进程、能力映射、会话生命周期、提示词、权限和时间线转换。不要把这些机制复制到插件中。
只在 ACP 无法描述厂商差异时使用 `transformers`。用 Zod 校验厂商负载,并让格式错误或无关的值保持不变:
使用 `transformers` 处理 ACP 无法描述的厂商差异。
[goose 模型转换器](https://github.com/getpaseo/paseo/blob/main/plugins/goose-provider/server/models.ts)
使用 `context.request` 读取 Agent 的模型列表,并使用 `config` 为会话的模型 ID 添加当前 Provider 前缀。
参见 [ACP 适配器参考](/docs/plugins/reference#providers)。
用 Zod 校验厂商负载,并让格式错误或无关的值保持不变:
```ts
import type { AcpTransformer } from "@getpaseo/plugin/server/acp";
+105 -1
View File
@@ -433,7 +433,14 @@ Paseo refreshes an agent by closing its current provider session and opening it
configuration and persistence. Providers re-read external state during `session.open`.
Use `runAcpProvider()` from `@getpaseo/plugin/server/acp` to adapt a command-backed ACP. Add transformer
hooks only for a vendor's discovery, configuration, notification, or tool-call differences.
hooks for vendor behavior. See [Adapt an ACP agent](/docs/plugins/providers#adapt-an-acp-agent).
In `discover` and `configure`, call `context.request(method, params)` to send an ACP extension
request. The promise returns a JSON value or rejects with the agent's JSON-RPC error.
Use `config(state, context)` to return the configuration snapshot that Paseo displays.
Paseo calls this synchronous hook for initial, notification, and committed configuration snapshots.
Use `configure` to send changes to the agent.
`ProviderRegistration.icon` is a file path relative to the plugin directory, such as `icon.svg`.
It must resolve inside that directory to a regular file that follows the
@@ -685,6 +692,103 @@ for 0.10 clients and renders problems into its `error` string.
The source icon is a file path with the same rules as a provider icon.
## Worktree managers {#worktree-managers}
**Requires Paseo 0.16.** Register a worktree manager from `index.server.ts` with
`server.registerWorktreeManager()` when an external tool such as Worktrunk should own creating,
removing, and restoring Git worktrees instead of Paseo running `git worktree add` and
`git worktree remove` directly.
```ts
import { execCommand, type PluginServerContext } from "@getpaseo/plugin/server";
export default function contribute(server: PluginServerContext) {
return server.registerWorktreeManager({
async create(request, { signal }) {
if (request.kind !== "branch-off") return;
const { stdout } = await execCommand(
"wt",
[
"-C",
request.repoRoot,
"switch",
"--create",
request.branch,
"--base",
request.startPoint ?? request.baseRef,
"--no-cd",
"--yes",
"--format=json",
],
{ signal },
);
const { path } = JSON.parse(stdout) as { path: string };
return { type: "created", path };
},
async remove({ path, force }, { signal }) {
await execCommand(
"wt",
[
"-C",
path,
"remove",
"--foreground",
"--no-delete-branch",
"--yes",
...(force ? ["--force"] : []),
path,
],
{ signal },
);
return { type: "removed" };
},
async restore({ repoRoot, path, target }, { signal }) {
if (target.type !== "branch") return;
const { stdout } = await execCommand(
"wt",
[
"-C",
repoRoot,
"switch",
target.branch,
"--path",
path,
"--no-cd",
"--yes",
"--format=json",
],
{ signal },
);
const { path: restoredPath } = JSON.parse(stdout) as { path: string };
return { type: "restored", path: restoredPath };
},
});
}
```
- **Create** runs after all `worktree.create.before` hooks and before `worktree.create.after`, with a
120-second timeout. Return `{ type: "created", path }` to claim creation, or `undefined` to decline
so the next manager or Paseo's built-in Git checkout runs. Paseo verifies that `path` is a safe,
newly created Git worktree of the same repository on a named branch, then records the checked-out
`HEAD` branch (managers may normalize or uniquely name the branch, and should create a new branch
for `branch-off`), writes comparison-base metadata, and seeds `paseo.json`. If adoption or a later
creation step fails after a new worktree was created in the repository, Paseo rolls it back; if
`create` throws before returning, the plugin is responsible for cleaning up any partial worktree it
created. First-agent branch auto-rename is skipped for manager-created worktrees.
- **Remove** is optional and runs on workspace archive and creation rollback, after Paseo runs
`paseo.json` teardown and saves `refs/paseo/kept-commits/<sha>` for restore. Return
`{ type: "removed" }` after removing the directory, or `undefined` to fall back to Git. When
`untrusted` is `true` (for example, a fork change request), skip repository-defined hooks. Paseo
routes removal to the plugin that created the worktree, falling back to Git when that plugin is
disabled or uninstalled.
- **Restore** is optional and runs when unarchiving a workspace whose worktree directory was deleted.
It receives the recorded `path` that the recreated worktree must occupy, `target` (`branch`,
`commit`, or `from-base`), and `untrusted`. Return `{ type: "restored", path }` or `undefined` to
fall back to Git. When `restore` falls back to Git, Paseo clears the workspace's manager ownership
so subsequent archives also use Git.
See the complete [worktrunk example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk).
## Entry point and cleanup
Each present entry default-exports one contribution function and returns cleanup. Client entries
+85 -1
View File
@@ -363,7 +363,14 @@ Provider 选项是一个记录,即 `session.open` 中的 `ProviderSessionConfi
Paseo 刷新 Agent 的方式是关闭它当前的 Provider 会话,再用当前的配置和持久化值打开它。Provider 在 `session.open` 期间重新读取外部状态。
使用 `@getpaseo/plugin/server/acp` 中的 `runAcpProvider()` 适配一个基于命令的 ACP。只针对厂商在发现、配置、通知或工具调用方面的差异添加转换器钩子。
使用 `@getpaseo/plugin/server/acp` 中的 `runAcpProvider()` 适配一个基于命令的 ACP。使用转换器钩子处理厂商特有的行为。参见[适配 ACP Agent](/docs/plugins/providers#adapt-an-acp-agent)。
在 `discover` 和 `configure` 中,调用 `context.request(method, params)` 发送 ACP 扩展请求。
Promise 返回 JSON 值,或以 Agent 的 JSON-RPC 错误拒绝。
使用 `config(state, context)` 返回 Paseo 显示的配置快照。
Paseo 在会话就绪、收到配置通知或提交配置更改时调用此同步钩子。
使用 `configure` 向 Agent 发送更改。
`ProviderRegistration.icon` 是相对于插件目录的文件路径,例如 `icon.svg`。它必须解析到该目录内一个遵循 [SVG 图标规则](#svg-rules)的普通文件。Paseo 在插件启动时读取并校验该文件;这个字符串从不是内联 SVG 或 URL。
@@ -535,6 +542,83 @@ export default function contribute(server: PluginServerContext) {
来源图标是一个文件路径,规则与 Provider 图标相同。
## worktree 管理器 {#worktree-managers}
**需要 Paseo 0.16**。在服务端入口 `index.server.ts` 中调用 `server.registerWorktreeManager()`,可将 Git worktree 的创建、移除和恢复委托给 Worktrunk 等外部工具,而无需由 Paseo 直接运行 `git worktree add` 和 `git worktree remove`。
```ts
import { execCommand, type PluginServerContext } from "@getpaseo/plugin/server";
export default function contribute(server: PluginServerContext) {
return server.registerWorktreeManager({
async create(request, { signal }) {
if (request.kind !== "branch-off") return;
const { stdout } = await execCommand(
"wt",
[
"-C",
request.repoRoot,
"switch",
"--create",
request.branch,
"--base",
request.startPoint ?? request.baseRef,
"--no-cd",
"--yes",
"--format=json",
],
{ signal },
);
const { path } = JSON.parse(stdout) as { path: string };
return { type: "created", path };
},
async remove({ path, force }, { signal }) {
await execCommand(
"wt",
[
"-C",
path,
"remove",
"--foreground",
"--no-delete-branch",
"--yes",
...(force ? ["--force"] : []),
path,
],
{ signal },
);
return { type: "removed" };
},
async restore({ repoRoot, path, target }, { signal }) {
if (target.type !== "branch") return;
const { stdout } = await execCommand(
"wt",
[
"-C",
repoRoot,
"switch",
target.branch,
"--path",
path,
"--no-cd",
"--yes",
"--format=json",
],
{ signal },
);
const { path: restoredPath } = JSON.parse(stdout) as { path: string };
return { type: "restored", path: restoredPath };
},
});
}
```
- **Create**:在所有 `worktree.create.before` 钩子之后、`worktree.create.after` 之前运行,超时为 120 秒。返回 `{ type: "created", path }` 表示接管创建,返回 `undefined` 表示放弃并交由下一个管理器或 Paseo 内置 Git 检出处理。Paseo 会验证 `path` 是同一仓库下新建且安全的命名分支 Git worktree,并记录实际检出的 `HEAD` 分支(管理器可自行规范或生成唯一分支名,但在 `branch-off` 时应创建新分支),随后写入基准元数据并生成 `paseo.json`。若在仓库内新建 worktree 后采纳或后续创建步骤失败,Paseo 会执行回滚;若 `create` 在返回前抛出错误,则由插件清理其部分创建的 worktree。由管理器创建的 worktree 会跳过首个 Agent 的分支自动重命名。
- **Remove**:可选。在工作区归档和创建回滚时运行,位于 Paseo 执行 `paseo.json` 清理并保存 `refs/paseo/kept-commits/<sha>` 之后。删除目录后返回 `{ type: "removed" }`,或返回 `undefined` 回退到 Git。当 `untrusted` 为 `true`(例如来自 fork 变更请求)时,请跳过仓库内定义的钩子。Paseo 会将移除路由到创建该 worktree 的插件;若该插件已停用或移除,则回退到内置 Git。
- **Restore**:可选。在取消归档且 worktree 目录已被删除时运行,接收必须恢复到的原路径 `path`、目标 `target`(`branch`、`commit` 或 `from-base`)以及 `untrusted`。返回 `{ type: "restored", path }`,或返回 `undefined` 回退到 Git。当 `restore` 回退到 Git 时,Paseo 会清除该工作区的管理器归属,后续归档也会使用 Git。
完整插件见 [worktrunk 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk)。
## 入口与清理 {#entry-point-and-cleanup}
每个存在的入口都默认导出一个贡献函数,并返回清理函数。客户端入口接收 `PluginClientContext`;服务端入口接收 `PluginServerContext`。客户端注册方法返回幂等的移除函数,但标题栏按钮和 Composer 标签除外,它们返回 `{ update, remove }` 句柄。入口的清理函数会在 Paseo 移除剩余的注册之前运行。
+1 -1
View File
@@ -51,7 +51,7 @@ To add one, open **Settings → Hosts → your host → Providers**, select **+
- [Gajae Code](https://gajae-code.com), subscription-based coding agent with plan-before-mutation workflows.
- [Gemini CLI](https://geminicli.com), Google's official Gemini CLI.
- [GLM Agent](https://github.com/stefandevo/glm-acp-agent), Zhipu AI's GLM coding agent.
- [goose](https://block.github.io/goose/), Block's local open-source AI agent.
- [goose](https://block.github.io/goose/), Block's local open-source AI agent. Paseo lists models from all providers configured in goose when goose supports model inventory discovery.
- [Grok](https://docs.x.ai/build/overview), xAI's Grok Build agentic coding CLI.
- [Hermes Agent](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp), Nous Research's self-improving agent.
- [Junie](https://junie.jetbrains.com/docs/junie-cli-acp.html), JetBrains' coding agent.
@@ -49,7 +49,7 @@ Paseo 可以运行任何使用 [Agent Client Protocol](https://agentclientprotoc
- [Gajae Code](https://gajae-code.com):订阅制编程 Agent,采用先规划再修改的工作流。
- [Gemini CLI](https://geminicli.com):Google 官方的 Gemini CLI。
- [GLM Agent](https://github.com/stefandevo/glm-acp-agent):智谱 AI 的 GLM 编程 Agent。
- [goose](https://block.github.io/goose/):Block 的本地开源 AI Agent。
- [goose](https://block.github.io/goose/):Block 的本地开源 AI Agent。如果 goose 支持发现模型清单,Paseo 会列出 goose 中所有已配置 Provider 的模型。
- [Grok](https://docs.x.ai/build/overview):xAI 的 Grok Build Agent 编程 CLI。
- [Hermes Agent](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp):Nous Research 的自我改进型 Agent。
- [Junie](https://junie.jetbrains.com/docs/junie-cli-acp.html):JetBrains 的编程 Agent。