Add managed local plugin lifecycle (#3222)

* feat(plugins): add local plugin surfaces and RPCs

Keep plugin execution scoped to its daemon while allowing one local TypeScript entry point to contribute validated RPCs and native client surfaces. Paseo owns host selection, navigation chrome, and per-installation query caches.

* feat(plugins): add Linear attachment source

* fix(nix): refresh npm dependency hash

* test(server): exclude internal sessions from Hub counts

* test(server): distinguish Hub execution sessions

* feat(plugins): make local plugins explicitly opt-in

Keep plugin loading dormant until configuration enables it, and collect unsupported examples under one directory.

* refactor(plugins): establish host boundaries

* fix(nix): refresh plugin dependency hash

* fix(plugins): complete packaging and startup rollback

* feat(plugins): add managed local lifecycle

Make trusted local plugins recoverable and authorable through daemon-owned lifecycle operations, host settings, and a capability-gated CLI. Reloads fully stop the previous plugin before starting new code, while generated projects provide strict TSX checking without changing runtime dependency ownership.

* fix(nix): refresh plugin dependency hash
This commit is contained in:
Mohamed Boudra
2026-08-14 17:12:49 +02:00
committed by GitHub
parent f0bd2c8483
commit 23853a1515
115 changed files with 7481 additions and 17 deletions
+33
View File
@@ -0,0 +1,33 @@
# Linear plugin example
This example adds `Attach Linear issue` to the composer. Search by issue identifier
or title, then send a stable issue snapshot to the agent.
Set a personal API key in the daemon environment:
```bash
export LINEAR_API_KEY="lin_api_..."
```
Register the extension in `$PASEO_HOME/config.json`:
```json
{
"pluginsEnabled": true,
"plugins": {
"linear": {
"source": "directory",
"path": "/absolute/path/to/paseo/plugin-examples/linear"
}
}
}
```
Restart the development daemon after changing its environment or plugin configuration.
The entry point demonstrates the complete attachment-source pattern:
- define one validated search RPC;
- handle it in the daemon subprocess;
- register a declarative attachment source for the client;
- keep credentials and vendor API calls out of the client bundle.
+46
View File
@@ -0,0 +1,46 @@
import { z } from "zod";
import {
defineAttachmentSource,
defineRpc,
type PluginAttachmentSearchPayload,
type PluginContext,
} from "@paseo/plugin";
import { createLinearIssueSearch } from "./linear";
const SearchPayloadSchema = z.object({
items: z.array(
z.object({
id: z.string(),
identifier: z.string(),
title: z.string(),
subtitle: z.string().optional(),
url: z.string().url(),
text: z.string(),
resourceType: z.string(),
}),
),
});
const searchIssues = defineRpc({
name: "issues.search",
input: z.object({ query: z.string() }),
output: SearchPayloadSchema,
});
const issueAttachments = defineAttachmentSource({
id: "issues",
title: "Linear issue",
icon: "CircleDot",
pickerTitle: "Attach Linear issue",
searchPlaceholder: "Search by identifier or title",
search: searchIssues,
});
export default function contribute(plugin: PluginContext) {
plugin.handle(searchIssues, async ({ query }): Promise<PluginAttachmentSearchPayload> => {
const linear = createLinearIssueSearch({ apiKey: process.env.LINEAR_API_KEY ?? "" });
return linear.search(query);
});
plugin.addAttachmentSource(issueAttachments);
return () => undefined;
}
+135
View File
@@ -0,0 +1,135 @@
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
import { describe, expect, it } from "vitest";
import { createLinearIssueSearch } from "./linear";
const issue = {
id: "issue-uuid",
identifier: "ENG-123",
title: "Plugin attachments",
description: "Let extensions attach external context.",
url: "https://linear.app/acme/issue/ENG-123/plugin-attachments",
priorityLabel: "High",
state: { name: "In Progress" },
assignee: { name: "Mohamed" },
project: { name: "Paseo" },
labels: { nodes: [{ name: "Feature" }] },
};
interface CapturedRequest {
authorization: string | undefined;
body: { query: string; variables: Record<string, unknown> };
}
async function readRequest(request: IncomingMessage): Promise<CapturedRequest> {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(Buffer.from(chunk));
return {
authorization: request.headers.authorization,
body: JSON.parse(Buffer.concat(chunks).toString("utf8")) as CapturedRequest["body"],
};
}
async function withLinearServer<T>(
respond: (request: CapturedRequest, response: ServerResponse) => void,
run: (endpoint: string) => Promise<T>,
): Promise<T> {
const server = createServer((request, response) => {
void readRequest(request).then((captured) => respond(captured, response));
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address() as AddressInfo;
try {
return await run(`http://127.0.0.1:${address.port}/graphql`);
} finally {
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
}
function sendJson(response: ServerResponse, body: unknown): void {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(body));
}
describe("Linear issue search", () => {
it("resolves an exact issue identifier and formats its agent snapshot", async () => {
const result = await withLinearServer(
(request, response) => {
expect(request.authorization).toBe("lin_api_test");
expect(request.body.variables).toEqual({ id: "ENG-123" });
sendJson(response, { data: { issue } });
},
async (endpoint) => {
const linear = createLinearIssueSearch({ apiKey: "lin_api_test", endpoint });
return linear.search("eng-123");
},
);
expect(result).toEqual({
items: [
{
id: "issue-uuid",
identifier: "ENG-123",
title: "Plugin attachments",
subtitle: "In Progress · Mohamed",
url: issue.url,
resourceType: "issue",
text: [
"Linear issue ENG-123: Plugin attachments",
`URL: ${issue.url}`,
"Status: In Progress",
"Priority: High",
"Assignee: Mohamed",
"Project: Paseo",
"Labels: Feature",
"",
"Let extensions attach external context.",
].join("\n"),
},
],
});
});
it("searches issue titles through a case-insensitive filter", async () => {
const result = await withLinearServer(
(request, response) => {
expect(request.body.variables).toEqual({
filter: { title: { containsIgnoreCase: "plugin" } },
});
sendJson(response, { data: { issues: { nodes: [issue] } } });
},
async (endpoint) => {
const linear = createLinearIssueSearch({ apiKey: "lin_api_test", endpoint });
return linear.search(" plugin ");
},
);
expect(result.items.map((item) => item.identifier)).toEqual(["ENG-123"]);
});
it("surfaces GraphQL errors even when HTTP succeeds", async () => {
await expect(
withLinearServer(
(_request, response) => sendJson(response, { errors: [{ message: "Token expired" }] }),
async (endpoint) => {
const linear = createLinearIssueSearch({ apiKey: "lin_api_test", endpoint });
return linear.search("ENG-123");
},
),
).rejects.toThrow("Token expired");
});
it("requires a daemon-side API key", () => {
expect(() => createLinearIssueSearch({ apiKey: "" })).toThrow(
"Set LINEAR_API_KEY in the daemon environment",
);
});
});
+183
View File
@@ -0,0 +1,183 @@
import { z } from "zod";
const LinearIssueSchema = z.object({
id: z.string(),
identifier: z.string(),
title: z.string(),
description: z.string().nullable(),
url: z.string(),
priorityLabel: z.string(),
state: z.object({ name: z.string() }),
assignee: z.object({ name: z.string() }).nullable(),
project: z.object({ name: z.string() }).nullable(),
labels: z.object({ nodes: z.array(z.object({ name: z.string() })) }),
});
const LinearGraphqlErrorSchema = z.object({ message: z.string() }).passthrough();
const ExactIssueResponseSchema = z.object({
data: z.object({ issue: LinearIssueSchema.nullable() }).nullable().optional(),
errors: z.array(LinearGraphqlErrorSchema).optional(),
});
const IssueSearchResponseSchema = z.object({
data: z
.object({ issues: z.object({ nodes: z.array(LinearIssueSchema) }) })
.nullable()
.optional(),
errors: z.array(LinearGraphqlErrorSchema).optional(),
});
const ISSUE_FIELDS = `
id
identifier
title
description
url
priorityLabel
state { name }
assignee { name }
project { name }
labels { nodes { name } }
`;
const EXACT_ISSUE_QUERY = `
query PaseoLinearIssue($id: String!) {
issue(id: $id) { ${ISSUE_FIELDS} }
}
`;
const SEARCH_ISSUES_QUERY = `
query PaseoLinearIssues($filter: IssueFilter) {
issues(first: 20, filter: $filter, orderBy: updatedAt) {
nodes { ${ISSUE_FIELDS} }
}
}
`;
const LINEAR_IDENTIFIER = /^[A-Z][A-Z0-9]+-\d+$/i;
export interface LinearAttachmentItem {
id: string;
identifier: string;
title: string;
subtitle?: string;
url: string;
text: string;
resourceType: string;
}
export interface LinearIssueSearch {
search(query: string): Promise<{ items: LinearAttachmentItem[] }>;
}
interface LinearIssueSearchOptions {
apiKey: string;
endpoint?: string;
request?: typeof fetch;
}
interface GraphqlRequest {
query: string;
variables: Record<string, unknown>;
}
class LinearApiError extends Error {
constructor(message: string) {
super(message);
this.name = "LinearApiError";
}
}
function issueSubtitle(issue: z.infer<typeof LinearIssueSchema>): string | undefined {
const parts = [issue.state.name, issue.assignee?.name].filter(
(part): part is string => typeof part === "string" && part.length > 0,
);
return parts.length > 0 ? parts.join(" · ") : undefined;
}
function issueText(issue: z.infer<typeof LinearIssueSchema>): string {
const labels = issue.labels.nodes.map((label) => label.name).join(", ");
const lines = [
`Linear issue ${issue.identifier}: ${issue.title}`,
`URL: ${issue.url}`,
`Status: ${issue.state.name}`,
`Priority: ${issue.priorityLabel}`,
];
if (issue.assignee) lines.push(`Assignee: ${issue.assignee.name}`);
if (issue.project) lines.push(`Project: ${issue.project.name}`);
if (labels) lines.push(`Labels: ${labels}`);
lines.push("", issue.description ?? "No description.");
return lines.join("\n");
}
function toAttachmentItem(issue: z.infer<typeof LinearIssueSchema>): LinearAttachmentItem {
const subtitle = issueSubtitle(issue);
return {
id: issue.id,
identifier: issue.identifier,
title: issue.title,
...(subtitle ? { subtitle } : {}),
url: issue.url,
text: issueText(issue),
resourceType: "issue",
};
}
function describeHttpFailure(status: number): string {
if (status === 401 || status === 403) return "Linear rejected LINEAR_API_KEY";
if (status === 429) return "Linear rate limit reached. Try again shortly";
return `Linear API request failed with HTTP ${status}`;
}
function throwGraphqlErrors(errors: Array<{ message: string }> | undefined): void {
if (!errors || errors.length === 0) return;
throw new LinearApiError(errors.map((error) => error.message).join("; "));
}
export function createLinearIssueSearch(options: LinearIssueSearchOptions): LinearIssueSearch {
const apiKey = options.apiKey.trim();
if (!apiKey) throw new LinearApiError("Set LINEAR_API_KEY in the daemon environment");
const endpoint = options.endpoint ?? "https://api.linear.app/graphql";
const request = options.request ?? fetch;
async function graphql(body: GraphqlRequest): Promise<unknown> {
const response = await request(endpoint, {
method: "POST",
headers: {
Authorization: apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (!response.ok) throw new LinearApiError(describeHttpFailure(response.status));
return response.json();
}
async function findExact(identifier: string): Promise<LinearAttachmentItem[]> {
const response = ExactIssueResponseSchema.parse(
await graphql({ query: EXACT_ISSUE_QUERY, variables: { id: identifier } }),
);
throwGraphqlErrors(response.errors);
return response.data?.issue ? [toAttachmentItem(response.data.issue)] : [];
}
async function searchTitles(query: string): Promise<LinearAttachmentItem[]> {
const filter = query ? { title: { containsIgnoreCase: query } } : null;
const response = IssueSearchResponseSchema.parse(
await graphql({ query: SEARCH_ISSUES_QUERY, variables: { filter } }),
);
throwGraphqlErrors(response.errors);
if (!response.data) throw new LinearApiError("Linear returned no issue data");
return response.data.issues.nodes.map(toAttachmentItem);
}
return {
async search(query: string) {
const normalized = query.trim();
if (LINEAR_IDENTIFIER.test(normalized)) {
return { items: await findExact(normalized.toUpperCase()) };
}
const items = await searchTitles(normalized);
return { items };
},
};
}
+3
View File
@@ -0,0 +1,3 @@
{
"id": "linear"
}