mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 12:33:05 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A managed instance gets its plugins from the control plane, and people do not install them > - Some of these plugins need deployment values, such as a service origin and a capability > - The plugin worker environment is scrubbed, and only a fixed list of first-party providers gets deployment variables > - Core also sends lifecycle events and project instance secrets only to plugins with a saved config row > - So a provisioned plugin cannot work until a person saves configuration for it > - This pull request lets the managed config grant named variables to a selected plugin > - The benefit is that a distribution plugin can run with no tenant configuration, and Core does not need to name it ## Linked Issues or Issue Description No issue exists. This describes the problem. I searched open pull requests for related work and found no duplicate. **What existing behavior does this improve?** How a plugin provisioned through `plugins.autoInstall` receives its deployment settings. **Current behavior** `buildPluginWorkerEnv` forwards variables only from a fixed list that names first-party packages. A distribution plugin cannot be on that list without Core naming it. A plugin with no `pluginConfig` row gets no resource lifecycle events, and project instance secrets refuse it. **Proposed behavior** The managed config can include `plugins.workerEnv`. It maps a catalog key to variable names. The worker of that plugin receives those variables from the server process environment. The managed config can also include `plugins.enabledCompanies`. It maps a catalog key to company IDs. In those companies, the plugin gets lifecycle events and can use project instance secrets with no config row. **Reason and benefit** The control plane stays the only place that decides which plugin gets which values. Tenants do not handle these values, and they are not in the database or in the managed config document. **Alternatives considered** - Create a config or enablement row for each company. The control plane would need a new tenant write API, and a row can stay after the document removes access or return after a database restore. The document is never saved, like the other managed settings. - Give a grant access to every company. This has no per-company opt-in. - Put the values in the managed config document. The document does not hold secrets, and this rule stays true because it holds only names. ## What Changed - `parseManagedConfigEnv` accepts an optional `plugins.workerEnv` object. Each key must be in `plugins.autoInstall`. Names must be uppercase variable names, with no duplicates. - Startup fails if a name looks like a host credential, such as a name with `KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `DATABASE` or `JWT` as a word, or if it controls how the worker loads code, such as `NODE_OPTIONS`. - `parseManagedConfigEnv` accepts an optional `plugins.enabledCompanies` object. Each key must be in `plugins.autoInstall`. Values must be lowercase company UUIDs, with no duplicates. - `managedPluginWorkerEnvGrant` and `managedPluginEnabledCompanies` return values by plugin key. A managed instance only starts a selected plugin from the current image, so the saved package path is not part of this check. It can be old or null. - `buildPluginWorkerEnv` forwards granted variables. This does not depend on the `environment.drivers.register` capability. - Plugin lifecycle delivery includes a plugin with no config row only for the companies the document names. It still skips a company that disabled the plugin. The runtime event listener follows the same rule. - Project instance secrets accept a plugin with no config row only for a company the document names. - A variable grant alone gives no company access. - `doc/plugins/DISTRIBUTION-PLUGINS.md` describes both sections. ## Verification - `npx vitest run` in `server/` on `managed-config`, `managed-plugin-worker-env`, `plugin-lifecycle-delivery`, `project-instance-secrets`, `plugin-database` and `bundled-plugins`: 201 tests pass. - The new tests cover a digest-verified distribution plugin, a stale saved package path, a catalog key named after an inherited property, a company the document does not name, a company that disabled the plugin, a named company that does not exist, a grant with no enabled company, and host credential names. - `tsc --noEmit` in `server/` shows no errors in the changed files. My worktree does not have the built `@paperclipai/paperclip-runner` package, so unrelated files show errors locally. CI runs the full typecheck. - I did not run the full test suite locally. CI runs it. - I did not test this change on a running instance. ## Risks - **Older builds:** a build without this change refuses a document with `plugins.workerEnv` or `plugins.enabledCompanies`, because it fails closed on unknown keys. A control plane must send these sections only to a build that supports them. - **Trust:** the granted plugin gets the variable values in its process. The image owner and the control plane already trust this plugin. The name check stops a mistake with host credentials, but a name check cannot prove that a value is not sensitive. Core cannot use an allowlist, because it must not name the variables of a private plugin. - **Company scope:** the control plane sets which companies a plugin serves. A new company needs a new document, and the server reads the document when it starts. Self-hosted instances do not change. - **Rotation:** a new value reaches the worker only when the server restarts. Rotation without a restart is not part of this change. - **Background calls:** a grant does not add proactive company access. A plugin that makes background calls with no invocation still needs a saved config for that company. - This changes core plugin behavior, and I did not discuss it in `#dev` first. Maintainers can tell me if they want a discussion before review. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
208 lines
12 KiB
TypeScript
208 lines
12 KiB
TypeScript
import { projectInstanceSecretService } from "./project-instance-secrets.js";
|
|
import { and, asc, eq, inArray, isNull, or, sql } from "drizzle-orm";
|
|
import { companies, pluginCompanySettings, pluginConfig, plugins, projects, type Db } from "@paperclipai/db";
|
|
import { logger } from "../middleware/logger.js";
|
|
import { pluginLifecycleInbox } from "./plugin-lifecycle-inbox.js";
|
|
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
|
|
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
|
|
import { parseProjectExecutionWorkspacePolicy } from "./execution-workspace-policy.js";
|
|
import { isWorkspaceProvider } from "./project-workspace-provider.js";
|
|
import { managedPluginEnabledCompanies } from "./managed-plugin-worker-env.js";
|
|
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
|
|
import type { PluginLifecycleManager } from "./plugin-lifecycle.js";
|
|
|
|
type Coordinator = ReturnType<typeof createDeliveryWorkCoordinator>;
|
|
|
|
/** The journal is the queue. Notifications only wake its single local dispatcher. */
|
|
export function registerPluginLifecycleDelivery(
|
|
coordinator: Coordinator,
|
|
db: Db,
|
|
manager: Pick<PluginWorkerManager, "call" | "isRunning" | "onConfigApplied">,
|
|
lifecycle: Pick<PluginLifecycleManager, "on" | "off">,
|
|
) {
|
|
// Startup and every wake remain pending until an admitted run inspects the inbox.
|
|
// The coordinator may reconcile signals while idle drain prevents dispatch.
|
|
let pending = true;
|
|
let disposed = false;
|
|
const retryAt = new Map<string, number>();
|
|
const refreshedRuntimeCompanies = new Set<string>();
|
|
const retryMs = 30_000;
|
|
async function managedTargets() {
|
|
const ready = await db.select().from(plugins).where(eq(plugins.status, "ready"));
|
|
const targets = ready.flatMap(plugin => managedPluginEnabledCompanies(plugin.pluginKey).map(companyId => ({ plugin, companyId })));
|
|
if (!targets.length) return targets;
|
|
const existing = await db.select({ id: companies.id }).from(companies)
|
|
.where(inArray(companies.id, targets.map(target => target.companyId)));
|
|
const existingIds = new Set(existing.map(company => company.id));
|
|
return targets.filter(target => existingIds.has(target.companyId));
|
|
}
|
|
async function enabledManagedPlugins() {
|
|
const targets = await managedTargets();
|
|
if (!targets.length) return [];
|
|
const disabled = await db.select({ pluginId: pluginCompanySettings.pluginId, companyId: pluginCompanySettings.companyId }).from(pluginCompanySettings)
|
|
.where(and(inArray(pluginCompanySettings.pluginId, targets.map(target => target.plugin.id)), eq(pluginCompanySettings.enabled, false)));
|
|
const disabledKeys = new Set(disabled.map(row => `${row.pluginId}:${row.companyId}`));
|
|
return targets.filter(target => !disabledKeys.has(`${target.plugin.id}:${target.companyId}`)).map(target => target.plugin);
|
|
}
|
|
async function deliveryTargets() {
|
|
const configured = await db.select({ plugin: plugins, companyId: pluginConfig.companyId })
|
|
.from(plugins).innerJoin(pluginConfig, eq(pluginConfig.pluginId, plugins.id))
|
|
.where(eq(plugins.status, "ready"))
|
|
.orderBy(asc(plugins.installOrder), asc(pluginConfig.companyId));
|
|
const managed = await managedTargets();
|
|
if (!managed.length) return configured;
|
|
const seen = new Set(configured.map(target => `${target.plugin.id}:${target.companyId}`));
|
|
return [...configured, ...managed.filter(target => !seen.has(`${target.plugin.id}:${target.companyId}`))].sort((a, b) =>
|
|
(a.plugin.installOrder ?? Infinity) - (b.plugin.installOrder ?? Infinity) || a.companyId.localeCompare(b.companyId));
|
|
}
|
|
const delivery = coordinator.register(DELIVERY_QUEUES.pluginLifecycle, {
|
|
retryMs,
|
|
hasPending: async () => pending,
|
|
onSettled: () => { pending = true; },
|
|
nextRunAt() {
|
|
if (!pending) return null;
|
|
let next: number | null = null;
|
|
for (const at of retryAt.values()) {
|
|
// An expired deadline during idle drain must not schedule a busy loop.
|
|
if (at > Date.now() && (next === null || at < next)) next = at;
|
|
}
|
|
return next;
|
|
},
|
|
async run(signal) {
|
|
pending = false;
|
|
try {
|
|
await ensureListening();
|
|
for (const [key, at] of retryAt) if (at <= Date.now()) retryAt.delete(key);
|
|
for (const { plugin, companyId } of await deliveryTargets()) {
|
|
const types = plugin.manifestJson.resourceLifecycle;
|
|
if (!types?.length || !plugin.manifestJson.capabilities.includes("events.subscribe")) continue;
|
|
const [disabled] = await db.select({ id: pluginCompanySettings.id }).from(pluginCompanySettings)
|
|
.where(and(eq(pluginCompanySettings.pluginId, plugin.id), eq(pluginCompanySettings.companyId, companyId), eq(pluginCompanySettings.enabled, false)));
|
|
if (disabled) continue;
|
|
if (types.includes("agent_runtime") && !refreshedRuntimeCompanies.has(companyId)) {
|
|
await db.execute(sql`SELECT paperclip_invalidate_company_agent_runtimes(${companyId}::uuid)`);
|
|
refreshedRuntimeCompanies.add(companyId);
|
|
}
|
|
const inbox = pluginLifecycleInbox(db, plugin.id);
|
|
let afterId: string | undefined;
|
|
// Visit independent resources past a failed or deferred head.
|
|
for (;;) {
|
|
if (signal.aborted) return;
|
|
const events = await inbox.list(companyId, 100, afterId, types);
|
|
for (const event of events) {
|
|
if (signal.aborted) return;
|
|
const retryKey = `${plugin.id}:${event.id}`;
|
|
if (retryAt.has(retryKey)) { pending = true; continue; }
|
|
if (!manager.isRunning(plugin.id)) { pending = true; break; }
|
|
let stage = "eligibility";
|
|
try {
|
|
// Recheck enablement for each invocation; a disable during a batch must stop delivery.
|
|
const [enabled] = await db.select({ manifest: plugins.manifestJson }).from(plugins)
|
|
.leftJoin(pluginCompanySettings, and(eq(pluginCompanySettings.pluginId, plugins.id), eq(pluginCompanySettings.companyId, companyId)))
|
|
.where(and(eq(plugins.id, plugin.id), eq(plugins.status, "ready"),
|
|
or(isNull(pluginCompanySettings.enabled), eq(pluginCompanySettings.enabled, true))));
|
|
if (!enabled?.manifest.resourceLifecycle?.includes(event.resourceType) || !enabled.manifest.capabilities.includes("events.subscribe")) break;
|
|
if (event.resourceType === "project" && isWorkspaceProvider(enabled.manifest)) {
|
|
stage = "ownership";
|
|
const [project] = await db.select({ policy: projects.executionWorkspacePolicy }).from(projects)
|
|
.where(and(eq(projects.id, event.resourceId), eq(projects.companyId, companyId)));
|
|
if (project && parseProjectExecutionWorkspacePolicy(project.policy)?.storageProviderPluginId !== plugin.id) {
|
|
await inbox.acknowledge(companyId, event.id);
|
|
wake();
|
|
continue;
|
|
}
|
|
}
|
|
stage = "credentials";
|
|
const credentials = event.resourceType === "project" && enabled.manifest.capabilities.includes("projects.instance-secrets")
|
|
? await projectInstanceSecretService(db, plugin.id).prepare(event) : undefined;
|
|
stage = "callback";
|
|
const result = await manager.call(plugin.id, "resourceLifecycle", credentials ? { ...event, instanceSecrets: credentials.instanceSecrets } : event, 30_000);
|
|
stage = "result";
|
|
if (result?.eventId !== event.id || !["acknowledged", "retry", "deferred"].includes(result.status)) {
|
|
throw new Error("Invalid resource lifecycle result");
|
|
}
|
|
if (signal.aborted) return;
|
|
if (result.status === "acknowledged") {
|
|
stage = "acknowledgment";
|
|
if (result.instanceSecrets !== undefined && !credentials) throw new Error("Project instance secrets outside callback scope");
|
|
await inbox.acknowledge(companyId, event.id, credentials ? { snapshot: credentials.snapshot, changes: result.instanceSecrets ?? {} } : undefined);
|
|
// An acknowledgment exposes the next event for this resource. Drain immediately.
|
|
wake();
|
|
} else if (result.status === "retry") {
|
|
retryAt.set(retryKey, Date.now() + retryMs);
|
|
pending = true;
|
|
}
|
|
} catch (error) {
|
|
retryAt.set(retryKey, Date.now() + retryMs);
|
|
// Provider error messages/data may contain secrets; retain only routing
|
|
// identifiers, the failed stage, and the protocol's numeric error code.
|
|
const code = (error as { code?: unknown } | null)?.code;
|
|
logger.warn({ pluginId: plugin.id, companyId, eventId: event.id, stage,
|
|
...(typeof code === "number" ? { rpcCode: code } : {}) }, "Resource lifecycle delivery failed; retry scheduled");
|
|
// Failed RPCs and uncertain acknowledgments leave durable work for replay.
|
|
pending = true;
|
|
}
|
|
}
|
|
if (events.length < 100) break;
|
|
afterId = events.at(-1)!.id;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
pending = true; // A failed scan must survive a retry skipped during idle drain.
|
|
throw error;
|
|
}
|
|
},
|
|
});
|
|
function wake() { if (disposed) return; pending = true; delivery.wake(); }
|
|
let listening: Awaited<ReturnType<Db["$client"]["listen"]>> | undefined;
|
|
let listenerUpdate = Promise.resolve();
|
|
function ensureListening() {
|
|
const update = listenerUpdate.then(async () => {
|
|
if (disposed || !db.$client?.listen) return;
|
|
const configured = await db.select({ manifest: plugins.manifestJson }).from(plugins)
|
|
.innerJoin(pluginConfig, eq(pluginConfig.pluginId, plugins.id))
|
|
.leftJoin(pluginCompanySettings, and(eq(pluginCompanySettings.pluginId, plugins.id), eq(pluginCompanySettings.companyId, pluginConfig.companyId)))
|
|
.where(and(eq(plugins.status, "ready"), or(isNull(pluginCompanySettings.enabled), eq(pluginCompanySettings.enabled, true))));
|
|
const installed = [...configured, ...(await enabledManagedPlugins()).map(plugin => ({ manifest: plugin.manifestJson }))];
|
|
if (disposed) return;
|
|
const wanted = installed.some(plugin => plugin.manifest.resourceLifecycle?.includes("agent_runtime") && plugin.manifest.capabilities?.includes("events.subscribe"));
|
|
if (wanted) listening ??= await db.$client.listen("paperclip_plugin_lifecycle", wake, wake);
|
|
else if (listening) {
|
|
const subscription = listening;
|
|
listening = undefined;
|
|
await subscription.unlisten();
|
|
}
|
|
});
|
|
listenerUpdate = update.catch(() => {});
|
|
return update;
|
|
}
|
|
function pluginChanged() {
|
|
wake();
|
|
void ensureListening().catch(wake);
|
|
}
|
|
const listenerReady = ensureListening();
|
|
const unsubscribeConfig = manager.onConfigApplied(pluginChanged);
|
|
lifecycle.on("plugin.loaded", pluginChanged);
|
|
lifecycle.on("plugin.enabled", pluginChanged);
|
|
lifecycle.on("plugin.worker_started", pluginChanged);
|
|
lifecycle.on("plugin.status_changed", pluginChanged);
|
|
lifecycle.on("plugin.disabled", pluginChanged);
|
|
lifecycle.on("plugin.unloaded", pluginChanged);
|
|
return {
|
|
...delivery,
|
|
ready: listenerReady,
|
|
wake,
|
|
dispose() {
|
|
disposed = true;
|
|
void listenerUpdate.then(() => listening?.unlisten()).catch(() => {});
|
|
unsubscribeConfig();
|
|
lifecycle.off("plugin.loaded", pluginChanged);
|
|
lifecycle.off("plugin.enabled", pluginChanged);
|
|
lifecycle.off("plugin.worker_started", pluginChanged);
|
|
lifecycle.off("plugin.status_changed", pluginChanged);
|
|
lifecycle.off("plugin.disabled", pluginChanged);
|
|
lifecycle.off("plugin.unloaded", pluginChanged);
|
|
},
|
|
};
|
|
}
|