mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
Add plugin lifecycle delivery and an initial resource baseline (#15343)
## Thinking Path > - Paperclip manages agents and projects for work. > - Their lifecycle changes already commit to a durable journal. > - Plugins need to read these records and track completed work. > - Existing resources need a one-time baseline before delivery is enabled. > - Worker crashes must leave unfinished records available for retry. > - Each plugin needs its own progress and company access checks. > - This PR adds a pull inbox through the existing plugin SDK and job system. ## Linked Issues or Issue Description **Problem or motivation** Plugins cannot consume the durable resource lifecycle journal. In-process notifications can disappear during a restart and cannot record successful completion. Resource plugins need retries, company boundaries, and ordered transitions. **Proposed solution** Add `ctx.events.listLifecycle(companyId, limit?, afterId?)` and `ctx.events.acknowledgeLifecycle(companyId, eventId)` under `events.subscribe`. Seed a one-time baseline from current resource state. Deliver creation first, then the remaining transitions in ID order. Store acknowledgments for each plugin. Use existing plugin jobs to poll configured companies. **Alternatives considered** A global sequence cursor can skip lower IDs that commit later. Fire-and-forget subscriptions cannot record completion. A new dispatcher is unnecessary because plugin jobs support polling. Consumers serialize polling and use provider idempotency keys. **Roadmap alignment** This extends the existing plugin system and builds on #15280 and #15306. Searches found no duplicate resource inbox work. Related #13306 exposes decision events on the in-process bus. This PR includes the initial journal baseline. Provider provisioning remains separate work. ## What Changed - Add company-scoped lifecycle reads and acknowledgments to the SDK and worker RPC host. - Gate both methods by capability, invocation or proactive company scope, plugin readiness, and company enablement. - Seed hired agents and all projects once. Preserve paused/terminated agent state and archived project state. Keep pending hires behind approval. - Preserve existing history and deliver backfilled creation before partial transition histories. - Deliver project archive events from #15371 through the SDK. Seed archive intents for archived projects and update intents for active projects with a partial archive history. - Store acknowledgments per plugin and reject acknowledgments that skip earlier resource events. - Page past failed resources while retaining their pending records. Reset the page cursor each sweep to include late commits. - Add acknowledgment storage, an index for resource ordering, tests, and authoring guidance. - Preserve native identity definitions and sequence progress in JavaScript backups. Repair journal ID generators lost by older backups before seeding the baseline, without changing existing IDs. ## Verification - `pnpm -r typecheck` passed after the final origin/master rebase. - `pnpm build` passed before the final metadata rebase. The final CI build also passed. - All 46 focused lifecycle, SDK harness/RPC, migration snapshot, and legacy restore checks passed again with migration 0309. - Checks cover retries, per-plugin progress, resource order, capability/company boundaries, baseline idempotency, approval gates, archive delivery, restored projects with partial histories, and atomic migration rollback. - Full CI passed on final commit `0e674b87fc`. One unrelated Cursor fixture hit a 10-second timeout; it passed locally in under one second, and the failed server shard passed on retry. - Greptile scored the final commit 5/5 with no unresolved review threads. - The branch is rebased onto origin/master and is conflict-free. - Earlier full local runs were stopped as scope changed. CI ran the complete repository suite. - `git diff --check` and a local secret/PII scan passed. ## Risks - Apply migration `0309_loving_the_hood.sql` before starting the new server. It creates acknowledgment storage and an index, then seeds the baseline in the same transaction. Agent/project writes wait for the migration to commit. Keep these writes quiesced through the migration and activation of the new capture-capable server; do not resume an older runtime that lacks capture after the baseline. - The baseline records current desired state, not historical transitions. It includes archived projects and terminated-agent cleanup intents. It runs once with the delivery migration; no later or runtime journal backfill is planned. - Delivery is at least once. Concurrent reads can repeat an event. Consumers must serialize polling, use stable company/event idempotency keys, and acknowledge successful operations only. - Reset `afterId` at the start of every polling sweep. It is a page cursor, not a persisted high-water mark. - Deleting a plugin removes its acknowledgment records. A new installation may replay existing journal events. - Records contain identity and action. Consumers must load current authorized data before acting. Cleanup and retention policy belong to the provider plugin. - Provider calls, VM/volume provisioning, and journal retention are outside this PR. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, repository inspection, code execution, and tool use. The exact deployment model ID and context window are not exposed in this session. ## 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 - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
854af7df19
commit
1cebdd4c4f
23 files changed
+930
-20
No files matched your search
@@ -605,12 +605,14 @@ describe("plugin proactive company scope (LOOA-629)", () => {
|
||||
}) {
|
||||
const companiesGet = overrides?.companiesGet ?? vi.fn(async () => ({ id: "company-1", name: "Co" }));
|
||||
const stateGet = overrides?.stateGet ?? vi.fn(async () => ({ value: "ok" }));
|
||||
const listLifecycle = vi.fn(async () => [{ id: "1", companyId: "company-1" }]);
|
||||
const hostHandlers = createHostClientHandlers({
|
||||
pluginId: "test.plugin",
|
||||
capabilities: ["companies.read", "plugin.state.read"],
|
||||
capabilities: ["companies.read", "plugin.state.read", "events.subscribe"],
|
||||
services: {
|
||||
companies: { get: companiesGet },
|
||||
state: { get: stateGet },
|
||||
events: { listLifecycle },
|
||||
} as unknown as HostServices,
|
||||
});
|
||||
const handle = createPluginWorkerHandle("test.plugin", {
|
||||
@@ -621,7 +623,7 @@ describe("plugin proactive company scope (LOOA-629)", () => {
|
||||
apiVersion: 1,
|
||||
hostHandlers,
|
||||
});
|
||||
return { handle, companiesGet, stateGet };
|
||||
return { handle, companiesGet, stateGet, listLifecycle };
|
||||
}
|
||||
|
||||
it("denies a proactive company-scoped call when no company is authorized", async () => {
|
||||
@@ -640,6 +642,25 @@ describe("plugin proactive company scope (LOOA-629)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("admits lifecycle polling only for configured proactive companies", async () => {
|
||||
const { handle, listLifecycle } = makeHandle();
|
||||
const poll = (companyId: string) => handle.call("getData", {
|
||||
params: { mode: "omit", hostMethod: "events.listLifecycle", requestedCompanyId: companyId },
|
||||
} as unknown as HostToWorkerMethods["getData"][0]);
|
||||
try {
|
||||
await handle.start();
|
||||
await expect(poll("company-1")).rejects.toMatchObject({ code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED });
|
||||
handle.setProactiveCompanyScopes(["company-1"]);
|
||||
expect(await poll("company-1")).toEqual([{ id: "1", companyId: "company-1" }]);
|
||||
await expect(poll("company-2")).rejects.toMatchObject({ code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED });
|
||||
handle.setProactiveCompanyScopes([]);
|
||||
await expect(poll("company-1")).rejects.toMatchObject({ code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED });
|
||||
expect(listLifecycle).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it("admits a proactive company-scoped call for an authorized company", async () => {
|
||||
const { handle, companiesGet } = makeHandle();
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { agentApiKeys, agents, budgetPolicies, companies, costEvents, createDb, projects, resourceLifecycleEvents, type Db } from "@paperclipai/db";
|
||||
import { agentApiKeys, agents, budgetPolicies, companies, costEvents, createDb, pluginCompanySettings, pluginLifecycleAcknowledgments, plugins, projects, resourceLifecycleEvents, type Db } from "@paperclipai/db";
|
||||
import { createHostClientHandlers } from "@paperclipai/plugin-sdk";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { agentService } from "../services/agents.js";
|
||||
@@ -8,6 +10,9 @@ import { approvalService } from "../services/approvals.js";
|
||||
import { budgetService } from "../services/budgets.js";
|
||||
import { projectService } from "../services/projects.js";
|
||||
import { recordResourceCreationEvent } from "../services/resource-lifecycle-events.js";
|
||||
import { pluginLifecycleInbox } from "../services/plugin-lifecycle-inbox.js";
|
||||
import { buildHostServices } from "../services/plugin-host-services.js";
|
||||
import { createPluginEventBus } from "../services/plugin-event-bus.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describePostgres = support.supported ? describe : describe.skip;
|
||||
@@ -34,6 +39,10 @@ describePostgres("Resource lifecycle events", () => {
|
||||
const events = () => db.select().from(resourceLifecycleEvents).where(eq(resourceLifecycleEvents.companyId, companyId));
|
||||
const createAgent = (status: "idle" | "pending_approval" | "terminated" = "idle", database: Db = db) =>
|
||||
agentService(database).create(companyId, { name: "Lifecycle agent", adapterType: "process", adapterConfig: {}, status });
|
||||
const createPlugin = async () => {
|
||||
const [plugin] = await db.insert(plugins).values({ pluginKey: randomUUID(), packageName: "lifecycle-fixture", version: "1.0.0", status: "ready", manifestJson: {} as never }).returning();
|
||||
return plugin;
|
||||
};
|
||||
|
||||
it("records direct and approval-free hires once, including concurrent duplicate submissions", async () => {
|
||||
const agent = await createAgent();
|
||||
@@ -291,4 +300,171 @@ describePostgres("Resource lifecycle events", () => {
|
||||
}
|
||||
});
|
||||
|
||||
const backfillBaseline = () => db.transaction(async tx => {
|
||||
const migration = readFileSync(new URL("../../../packages/db/src/migrations/0309_loving_the_hood.sql", import.meta.url), "utf8");
|
||||
const lock = migration.split("--> statement-breakpoint")[0];
|
||||
const baseline = migration.slice(migration.indexOf("-- Seed a one-time current-state baseline"));
|
||||
for (const statement of [lock, ...baseline.split("--> statement-breakpoint")]) {
|
||||
if (statement.trim()) await tx.execute(sql.raw(statement));
|
||||
}
|
||||
});
|
||||
|
||||
it("backfills a current-state baseline once without bypassing approval or reordering partial histories", async () => {
|
||||
const [live, paused, terminated, pending, partial, resumed] = await db.insert(agents).values([
|
||||
{ companyId, name: "Legacy live", status: "idle" },
|
||||
{ companyId, name: "Legacy paused", status: "paused" },
|
||||
{ companyId, name: "Legacy terminated", status: "terminated" },
|
||||
{ companyId, name: "Legacy pending", status: "pending_approval" },
|
||||
{ companyId, name: "Partial pause", status: "paused" },
|
||||
{ companyId, name: "Partial resume", status: "idle" },
|
||||
]).returning();
|
||||
const [archived] = await db.insert(projects).values({ companyId, name: "Archived baseline", archivedAt: new Date(0) }).returning();
|
||||
const [restored] = await db.insert(projects).values({ companyId, name: "Restored baseline" }).returning();
|
||||
await db.insert(resourceLifecycleEvents).values({ companyId, resourceType: "project", resourceId: restored.id, action: "archive" });
|
||||
const existing = await createAgent();
|
||||
const [earlyPause] = await db.insert(resourceLifecycleEvents).values([
|
||||
{ companyId, resourceType: "agent", resourceId: partial.id, action: "pause" },
|
||||
{ companyId, resourceType: "agent", resourceId: resumed.id, action: "pause" },
|
||||
]).returning();
|
||||
const deletedId = randomUUID();
|
||||
const [deleted] = await db.insert(resourceLifecycleEvents).values({ companyId, resourceType: "agent", resourceId: deletedId, action: "terminate" }).returning();
|
||||
await backfillBaseline();
|
||||
const baseline = (await events()).sort((a, b) => a.id - b.id);
|
||||
const actions = (id: string) => baseline.filter(e => e.resourceId === id).map(e => e.action);
|
||||
expect(actions(live.id)).toEqual(["create"]);
|
||||
expect(actions(paused.id)).toEqual(["create", "pause"]);
|
||||
expect(actions(terminated.id)).toEqual(["terminate"]);
|
||||
expect(actions(pending.id)).toEqual([]);
|
||||
expect(actions(partial.id)).toEqual(["pause", "create"]);
|
||||
expect(actions(resumed.id)).toEqual(["pause", "create", "resume"]);
|
||||
expect(actions(archived.id)).toEqual(["create", "archive"]);
|
||||
expect(actions(restored.id)).toEqual(["archive", "create", "update"]);
|
||||
expect(actions(existing.id)).toEqual(["create"]);
|
||||
expect(baseline.find(e => e.id === deleted.id)).toEqual(deleted);
|
||||
const plugin = await createPlugin();
|
||||
const inbox = pluginLifecycleInbox(db, plugin.id);
|
||||
const creation = (await inbox.list(companyId)).find(e => e.resourceId === partial.id)!;
|
||||
expect(creation.action).toBe("create");
|
||||
expect(Number(creation.id)).toBeGreaterThan(earlyPause.id);
|
||||
await expect(inbox.acknowledge(companyId, String(earlyPause.id))).rejects.toMatchObject({ status: 409 });
|
||||
await inbox.acknowledge(companyId, creation.id);
|
||||
expect((await inbox.list(companyId)).find(e => e.resourceId === partial.id)).toMatchObject({ id: String(earlyPause.id), action: "pause" });
|
||||
const projectCreate = (await inbox.list(companyId)).find(e => e.resourceId === archived.id)!;
|
||||
await inbox.acknowledge(companyId, projectCreate.id);
|
||||
const archive = (await inbox.list(companyId)).find(e => e.resourceId === archived.id)!;
|
||||
expect(archive.action).toBe("archive");
|
||||
await inbox.acknowledge(companyId, archive.id);
|
||||
expect((await inbox.list(companyId)).find(e => e.resourceId === archived.id)).toBeUndefined();
|
||||
await backfillBaseline();
|
||||
expect((await events()).sort((a, b) => a.id - b.id)).toEqual(baseline);
|
||||
});
|
||||
|
||||
it("keeps delivery unavailable when the baseline migration fails", async () => {
|
||||
await db.insert(agents).values({ companyId, name: "Legacy paused", status: "paused" });
|
||||
await db.execute(sql`ALTER TABLE resource_lifecycle_events ALTER COLUMN id DROP IDENTITY`);
|
||||
await db.execute(sql`DROP TABLE plugin_lifecycle_acknowledgments`);
|
||||
await db.execute(sql`DROP INDEX resource_lifecycle_events_resource_order_idx`);
|
||||
const applyDeliveryMigration = () => db.transaction(async tx => {
|
||||
const migration = readFileSync(new URL("../../../packages/db/src/migrations/0309_loving_the_hood.sql", import.meta.url), "utf8");
|
||||
for (const statement of migration.split("--> statement-breakpoint")) {
|
||||
if (statement.trim()) await tx.execute(sql.raw(statement));
|
||||
}
|
||||
});
|
||||
await db.execute(sql`ALTER TABLE resource_lifecycle_events ADD CONSTRAINT fixture_reject_baseline CHECK (action <> 'pause') NOT VALID`);
|
||||
try {
|
||||
await expect(applyDeliveryMigration()).rejects.toMatchObject({ cause: { constraint_name: "fixture_reject_baseline" } });
|
||||
expect(await events()).toEqual([]);
|
||||
expect((await db.execute(sql`SELECT is_identity FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'resource_lifecycle_events' AND column_name = 'id'`))[0]).toMatchObject({ is_identity: "NO" });
|
||||
expect((await db.execute(sql`SELECT to_regclass('public.plugin_lifecycle_acknowledgments') AS relation`))[0]).toMatchObject({ relation: null });
|
||||
} finally {
|
||||
await db.execute(sql`ALTER TABLE resource_lifecycle_events DROP CONSTRAINT fixture_reject_baseline`);
|
||||
await applyDeliveryMigration();
|
||||
expect((await db.execute(sql`SELECT is_identity FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'resource_lifecycle_events' AND column_name = 'id'`))[0]).toMatchObject({ is_identity: "YES" });
|
||||
}
|
||||
});
|
||||
|
||||
it("retries until acknowledgment, preserves resource order, and isolates progress per plugin", async () => {
|
||||
const first = await createPlugin();
|
||||
const second = await createPlugin();
|
||||
const agent = await createAgent();
|
||||
await agentService(db).pause(agent.id);
|
||||
await agentService(db).resume(agent.id);
|
||||
const journal = (await events()).sort((a, b) => a.id - b.id);
|
||||
const inbox = pluginLifecycleInbox(db, first.id);
|
||||
const [event] = await inbox.list(companyId);
|
||||
expect(event).toMatchObject({ id: String(journal[0].id), resourceId: agent.id, action: "create" });
|
||||
expect(await pluginLifecycleInbox(db, first.id).list(companyId)).toEqual([event]);
|
||||
await expect(inbox.acknowledge(companyId, String(journal[1].id))).rejects.toMatchObject({ status: 409 });
|
||||
await Promise.all([inbox.acknowledge(companyId, event.id), inbox.acknowledge(companyId, event.id)]);
|
||||
expect(await inbox.list(companyId)).toEqual([expect.objectContaining({ action: "pause" })]);
|
||||
expect(await pluginLifecycleInbox(db, second.id).list(companyId)).toEqual([event]);
|
||||
await inbox.acknowledge(companyId, String(journal[1].id));
|
||||
await inbox.acknowledge(companyId, String(journal[2].id));
|
||||
expect(await inbox.list(companyId)).toEqual([]);
|
||||
await db.delete(plugins).where(eq(plugins.id, first.id));
|
||||
expect(await db.select().from(pluginLifecycleAcknowledgments).where(eq(pluginLifecycleAcknowledgments.pluginId, first.id))).toEqual([]);
|
||||
});
|
||||
|
||||
it("pages past 100 failing resources without skipping their later events", async () => {
|
||||
const plugin = await createPlugin();
|
||||
const inbox = pluginLifecycleInbox(db, plugin.id);
|
||||
await db.insert(resourceLifecycleEvents).values(Array.from({ length: 101 }, () => ({
|
||||
companyId, resourceType: "agent" as const, resourceId: randomUUID(), action: "create" as const,
|
||||
})));
|
||||
const first = await inbox.list(companyId, 100);
|
||||
await db.insert(resourceLifecycleEvents).values({ companyId, resourceType: "agent", resourceId: first[0].resourceId, action: "pause" });
|
||||
const next = await inbox.list(companyId, 100, first.at(-1)!.id);
|
||||
expect(next).toHaveLength(1);
|
||||
expect(next[0].resourceId).not.toBe(first[0].resourceId);
|
||||
await inbox.acknowledge(companyId, next[0].id);
|
||||
expect(await inbox.list(companyId, 100, first.at(-1)!.id)).toEqual([]);
|
||||
expect(await inbox.list(companyId, 100)).toEqual(first);
|
||||
await expect(inbox.list(companyId, 100, "invalid")).rejects.toMatchObject({ status: 400 });
|
||||
});
|
||||
|
||||
it("never skips a lower event id that commits after a higher id is acknowledged", async () => {
|
||||
const plugin = await createPlugin();
|
||||
const inbox = pluginLifecycleInbox(db, plugin.id);
|
||||
await db.transaction(async tx => {
|
||||
const low = await agentService(tx as unknown as Db).create(companyId, { name: "Delayed commit" });
|
||||
const high = await createAgent();
|
||||
const [visible] = await inbox.list(companyId);
|
||||
expect(visible.resourceId).toBe(high.id);
|
||||
await inbox.acknowledge(companyId, visible.id);
|
||||
expect(await inbox.list(companyId)).toEqual([]);
|
||||
expect(low.id).not.toBe(high.id);
|
||||
});
|
||||
expect(await inbox.list(companyId)).toEqual([expect.objectContaining({ action: "create" })]);
|
||||
});
|
||||
|
||||
it("enforces capability, invocation company, plugin availability, and company boundaries through host RPC", async () => {
|
||||
const plugin = await createPlugin();
|
||||
await createAgent();
|
||||
const services = buildHostServices(db, plugin.id, plugin.pluginKey, createPluginEventBus());
|
||||
const handlers = createHostClientHandlers({ pluginId: plugin.id, capabilities: ["events.subscribe"], services });
|
||||
const scope = { invocationScope: { companyId } };
|
||||
try {
|
||||
await expect(handlers["events.listLifecycle"]({ companyId })).rejects.toThrow("company context");
|
||||
const other = randomUUID();
|
||||
await expect(handlers["events.listLifecycle"]({ companyId: other }, scope)).rejects.toThrow("requested company");
|
||||
const denied = createHostClientHandlers({ pluginId: plugin.id, capabilities: [], services });
|
||||
await expect(denied["events.listLifecycle"]({ companyId }, scope)).rejects.toThrow("events.subscribe");
|
||||
await expect(denied["events.acknowledgeLifecycle"]({ companyId, eventId: "1" }, scope)).rejects.toThrow("events.subscribe");
|
||||
const [event] = await handlers["events.listLifecycle"]({ companyId }, scope);
|
||||
await expect(handlers["events.acknowledgeLifecycle"]({ companyId: other, eventId: event.id }, scope)).rejects.toThrow("requested company");
|
||||
await expect(pluginLifecycleInbox(db, plugin.id).acknowledge(other, event.id)).rejects.toMatchObject({ status: 404 });
|
||||
await db.insert(pluginCompanySettings).values({ pluginId: plugin.id, companyId, enabled: false });
|
||||
await expect(handlers["events.listLifecycle"]({ companyId }, scope)).rejects.toMatchObject({ status: 403 });
|
||||
await expect(handlers["events.acknowledgeLifecycle"]({ companyId, eventId: event.id }, scope)).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(pluginCompanySettings).set({ enabled: true }).where(eq(pluginCompanySettings.pluginId, plugin.id));
|
||||
await expect(handlers["events.listLifecycle"]({ companyId, limit: 0 }, scope)).rejects.toMatchObject({ status: 400 });
|
||||
await expect(handlers["events.acknowledgeLifecycle"]({ companyId, eventId: "1e2" }, scope)).rejects.toMatchObject({ status: 400 });
|
||||
await handlers["events.acknowledgeLifecycle"]({ companyId, eventId: event.id }, scope);
|
||||
expect(await handlers["events.listLifecycle"]({ companyId }, scope)).toEqual([]);
|
||||
await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, plugin.id));
|
||||
await expect(handlers["events.listLifecycle"]({ companyId }, scope)).rejects.toMatchObject({ status: 403 });
|
||||
} finally {
|
||||
services.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -47,6 +47,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { pluginRegistryService } from "./plugin-registry.js";
|
||||
import { pluginStateStore } from "./plugin-state-store.js";
|
||||
import { pluginLifecycleInbox } from "./plugin-lifecycle-inbox.js";
|
||||
import { pluginDatabaseService } from "./plugin-database.js";
|
||||
import { pluginManagedAgentService } from "./plugin-managed-agents.js";
|
||||
import { pluginManagedRoutineService } from "./plugin-managed-routines.js";
|
||||
@@ -757,6 +758,7 @@ export function buildHostServices(
|
||||
const approvalSvc = approvalService(db);
|
||||
const interactions = issueThreadInteractionService(db);
|
||||
const scopedBus = eventBus.forPlugin(pluginKey);
|
||||
const lifecycleInbox = pluginLifecycleInbox(db, pluginId);
|
||||
|
||||
// Track active session event subscriptions for cleanup
|
||||
const activeSubscriptions = new Set<{ unsubscribe: () => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
@@ -1557,6 +1559,12 @@ export function buildHostServices(
|
||||
},
|
||||
|
||||
events: {
|
||||
async listLifecycle(params) {
|
||||
return lifecycleInbox.list(ensureCompanyId(params.companyId), params.limit, params.afterId);
|
||||
},
|
||||
async acknowledgeLifecycle(params) {
|
||||
await lifecycleInbox.acknowledge(ensureCompanyId(params.companyId), params.eventId);
|
||||
},
|
||||
async emit(params) {
|
||||
if (params.companyId) {
|
||||
await ensurePluginAvailableForCompany(params.companyId);
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { pluginCompanySettings, pluginLifecycleAcknowledgments, plugins, resourceLifecycleEvents, type Db } from "@paperclipai/db";
|
||||
import type { ResourceLifecycleEvent } from "@paperclipai/plugin-sdk";
|
||||
import { z } from "zod";
|
||||
import { and, asc, eq, gt, sql } from "drizzle-orm";
|
||||
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
|
||||
|
||||
/** Durable pull delivery. Provider work stays outside tenant transactions. */
|
||||
export function pluginLifecycleInbox(db: Db, pluginId: string) {
|
||||
const unacknowledged = sql`NOT EXISTS (
|
||||
SELECT 1 FROM plugin_lifecycle_acknowledgments ack
|
||||
WHERE ack.plugin_id = ${pluginId} AND ack.event_id = ${resourceLifecycleEvents.id}
|
||||
)`;
|
||||
const firstForResource = sql`NOT EXISTS (
|
||||
SELECT 1 FROM resource_lifecycle_events older
|
||||
WHERE older.company_id = ${resourceLifecycleEvents.companyId}
|
||||
AND older.resource_type = ${resourceLifecycleEvents.resourceType}
|
||||
AND older.resource_id = ${resourceLifecycleEvents.resourceId}
|
||||
-- Backfilled creation must precede transitions captured before this baseline.
|
||||
AND ${resourceLifecycleEvents.action} <> 'create'
|
||||
AND (older.action = 'create' OR older.id < ${resourceLifecycleEvents.id})
|
||||
AND NOT EXISTS (SELECT 1 FROM plugin_lifecycle_acknowledgments ack
|
||||
WHERE ack.plugin_id = ${pluginId} AND ack.event_id = older.id)
|
||||
)`;
|
||||
|
||||
async function assertAvailable(database: Db, companyId: string) {
|
||||
if (!z.string().uuid().safeParse(companyId).success) throw badRequest("companyId must be a UUID");
|
||||
const [plugin] = await database.select({ status: plugins.status }).from(plugins).where(eq(plugins.id, pluginId));
|
||||
const [settings] = await database.select({ enabled: pluginCompanySettings.enabled }).from(pluginCompanySettings)
|
||||
.where(and(eq(pluginCompanySettings.pluginId, pluginId), eq(pluginCompanySettings.companyId, companyId)));
|
||||
if (plugin?.status !== "ready" || settings?.enabled === false) throw forbidden("Plugin is not enabled for this company");
|
||||
}
|
||||
|
||||
return {
|
||||
async list(companyId: string, limit = 50, afterId?: string): Promise<ResourceLifecycleEvent[]> {
|
||||
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw badRequest("limit must be an integer from 1 to 100");
|
||||
if (afterId !== undefined && (typeof afterId !== "string" || !/^[1-9]\d*$/.test(afterId) || !Number.isSafeInteger(Number(afterId)))) throw badRequest("Invalid lifecycle page id");
|
||||
await assertAvailable(db, companyId);
|
||||
const rows = await db.select().from(resourceLifecycleEvents)
|
||||
.where(and(eq(resourceLifecycleEvents.companyId, companyId), unacknowledged, firstForResource, afterId === undefined ? undefined : gt(resourceLifecycleEvents.id, Number(afterId))))
|
||||
.orderBy(asc(resourceLifecycleEvents.id)).limit(limit);
|
||||
return rows.map(row => ({ ...row, id: String(row.id), createdAt: row.createdAt.toISOString() })) as ResourceLifecycleEvent[];
|
||||
},
|
||||
async acknowledge(companyId: string, eventId: string): Promise<void> {
|
||||
if (typeof eventId !== "string" || !/^[1-9]\d*$/.test(eventId) || !Number.isSafeInteger(Number(eventId))) throw badRequest("Invalid lifecycle event id");
|
||||
await db.transaction(async tx => {
|
||||
const txDb = tx as unknown as Db;
|
||||
await assertAvailable(txDb, companyId);
|
||||
const [event] = await tx.select().from(resourceLifecycleEvents)
|
||||
.where(and(eq(resourceLifecycleEvents.companyId, companyId), eq(resourceLifecycleEvents.id, Number(eventId)))).for("update");
|
||||
if (!event) throw notFound("Lifecycle event not found");
|
||||
const [eligible] = await tx.select({ id: resourceLifecycleEvents.id }).from(resourceLifecycleEvents)
|
||||
.where(and(eq(resourceLifecycleEvents.id, event.id), firstForResource));
|
||||
if (!eligible) throw conflict("Acknowledge earlier lifecycle events for this resource first");
|
||||
await tx.insert(pluginLifecycleAcknowledgments).values({ pluginId, eventId: event.id }).onConflictDoNothing();
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user