mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 04:29:01 +01:00
fix(agents): keep a prepared agent setup when its configuration changes (#23669)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A new agent can use a plugin environment that requires an agent. A lifecycle plugin prepares that environment before the agent can work. > - The setup flow creates a draft agent first, so that this preparation can start before the person finishes setup. > - Each change to the draft's harness, model, or sign-in started preparation again. The hire also started it again. > - Verification cannot start until the last preparation is complete. So the early preparation did not decrease the wait after the hire. > - This pull request keeps the preparation when the agent stays on the same environment driver. > - The benefit is that a person who finishes setup waits only for verification. ## Linked Issues or Issue Description I searched the open and closed issues and pull requests. I did not find a duplicate. **What happened?** Create an agent in setup on a plugin environment that declares `requiresAgent: true`. The draft is prepared. Then choose a harness, sign in, and hire the agent. Each of these three steps starts `preparing` again. The agent page shows preparation after the hire, although the environment was ready before the person signed in. **Expected behavior** A change to the harness, model, credentials, or instructions does not change the environment. It must not start preparation again. The hire must go directly to verification. If preparation is in progress, the hire must join it. **Steps to reproduce** 1. Install a lifecycle plugin with an environment driver that declares `requiresAgent: true`. 2. Make that environment the instance default. 3. Create a setup draft and wait until `lifecycleState` is `verifying`. 4. Save a different model on the draft. `lifecycleState` goes back to `preparing`. 5. Hire the draft. `lifecycleState` goes back to `preparing` again. **Paperclip version or commit** `7e025ae65f` **Deployment mode** Self-hosted server with a plugin environment that requires an agent. ## What Changed - A configuration change restarts `preparing` only when the agent moves to an environment that needs setup. The existing environment and driver check makes this decision. - A prepared setup draft stays prepared when its harness, model, credentials, or runtime configuration change. - The hire of a prepared draft goes directly to `verifying` with a new operation. - The hire of a draft that is still `preparing` keeps the operation and its version. Verification starts when that operation is complete. - A hire that moves to an environment that needs setup starts `preparing` again, as before. - A save that changes an environment to another driver of the same plugin now also refuses `preparing` agents, the same as `ready` and `verifying` ones. - A change to instructions alone does not restart verification. The hire writes the managed instruction files immediately after it commits, and verification does not read them. - The hire clears an old lifecycle error on the draft. - These behaviors do not change: - a draft that no longer needs preparation goes to `pausing` - a hire that needs approval, a hire with a hold, and a company hold - an edit to other execution configuration during verification - an edit during `resuming` - `doc/AGENT-LIFECYCLE.md` describes the new rules. ## Verification - `npx vitest run src/modules/agent-lifecycle`: 224 passed. Four new tests cover a prepared draft, a hire from a prepared draft, a hire during preparation, and an instruction change. Three of them failed before the change. The fourth could not run because a test before it left the fixture blocked. - `npx vitest run` on the hire, lifecycle delivery, agent secret, pending approval, secret binding, managed plugin environment, and plugin task tests: all passed. - `npx vitest run` on the two Dot onboarding files: 25 passed. - `pnpm --filter @paperclipai/server typecheck`: passed. - Not done: a live test with a plugin environment. Three existing tests used an agent in `preparing` to test that a configuration change fences verification. They now use `verifying`. ## Risks - A lifecycle plugin that reads the agent's harness or model during `preparing` is not called again when they change. The lifecycle request does not carry them. Verification still tests the final configuration. - A prepared environment can be lost between preparation and hire. Verification then fails and retries, and a pause and resume prepares it again. Before this change, the hire prepared it again. - An edit during `preparing` does not cancel the attempt in progress. A plugin must not fail because the agent's configuration changed during its call. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with extended thinking, 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 - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8604231091
commit
c2a8821809
9 files changed
+185
-31
No files matched your search
+15
-4
@@ -139,9 +139,19 @@ The application supplies the worker driver at startup.
|
||||
`updateConfiguration` owns the transaction for an ordinary configuration update.
|
||||
The module locks the agent. The configuration service validates and prepares the
|
||||
patch. The module saves it and invalidates an old verification result when
|
||||
execution configuration changes during setup. The service then updates dependent
|
||||
execution configuration changes during verification. A change to instructions
|
||||
alone keeps the verification. The service then updates dependent
|
||||
records and saves the configuration revision in the same transaction.
|
||||
A change to the harness, model, credentials, or instructions does not restart
|
||||
`preparing`. Preparation restarts only when the agent moves to an environment
|
||||
that needs setup.
|
||||
There is no separate invalidation operation for callers.
|
||||
A prepared setup draft waits in `verifying` with no background work. Edits keep
|
||||
it prepared. If an edit means that the draft no longer needs preparation, the
|
||||
draft pauses. When the draft becomes a hire on the same environment driver, a
|
||||
prepared draft goes directly to verification. A draft that is still `preparing`
|
||||
keeps its operation, and the hire verifies after that operation completes. A
|
||||
hire that needs setup for another environment starts `preparing` again.
|
||||
Configuration writes reject caller-supplied lifecycle fields.
|
||||
For `updateAndTransition`, lifecycle owns the transaction and calls the
|
||||
same configuration operation. Both changes commit together.
|
||||
@@ -222,9 +232,10 @@ the agent.
|
||||
|
||||
Saving an environment or the instance default that gives such a plugin to `ready`
|
||||
or `verifying` agents without that selection returns a conflict. The same applies
|
||||
when the change keeps the plugin but changes its driver; then every `ready` or
|
||||
`verifying` agent on the environment needs setup. Pause those agents, save the
|
||||
change, and then resume them.
|
||||
when the change keeps the plugin but changes its driver; then every `ready`,
|
||||
`preparing`, or `verifying` agent on the environment needs setup. A preparation
|
||||
in progress belongs to the previous driver. Pause those agents, save the change,
|
||||
and then resume them.
|
||||
|
||||
This save check trusts a selection when the old environment uses another plugin
|
||||
or none. An agent keeps its selection after it leaves the plugin's environment.
|
||||
|
||||
@@ -45,7 +45,7 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
|
||||
}
|
||||
|
||||
it("invalidates setup when a broker pairing is applied or revoked", async () => {
|
||||
const f = await fixture(undefined, "preparing");
|
||||
const f = await fixture(undefined, "verifying");
|
||||
const consent = await f.oauth.consent(f.id, { type: "board", source: "session", userId: f.userId },
|
||||
{ decision: "approve", companyId: f.company.id, allowWrites: false });
|
||||
const tokens = await f.oauth.token({ grant_type: "authorization_code", client_id: f.client.client_id,
|
||||
|
||||
@@ -125,6 +125,22 @@ export function jsonEqual(left: unknown, right: unknown): boolean {
|
||||
return canonicalJson(left) === canonicalJson(right);
|
||||
}
|
||||
|
||||
const INSTRUCTION_CONFIGURATION_KEYS = [
|
||||
"instructionsBundleMode",
|
||||
"instructionsRootPath",
|
||||
"instructionsEntryFile",
|
||||
"instructionsFilePath",
|
||||
"agentsMdPath",
|
||||
"promptTemplate",
|
||||
"bootstrapPromptTemplate",
|
||||
];
|
||||
|
||||
export function adapterConfigWithoutInstructions(adapterConfig: unknown) {
|
||||
return adapterConfig && typeof adapterConfig === "object" && !Array.isArray(adapterConfig)
|
||||
? Object.fromEntries(Object.entries(adapterConfig).filter(([key]) => !INSTRUCTION_CONFIGURATION_KEYS.includes(key)))
|
||||
: adapterConfig;
|
||||
}
|
||||
|
||||
export function buildConfigSnapshot(
|
||||
row: Pick<typeof agents.$inferSelect, ConfigRevisionField>,
|
||||
): AgentConfigSnapshot {
|
||||
|
||||
@@ -289,6 +289,8 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
const users = { environmentId: boundEnvironmentId, inheritsDefault: false };
|
||||
const id = await agent(boundEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] });
|
||||
await expect(assertAgentsReadyForEnvironmentChange(db, bound, sibling, users)).rejects.toThrow("need setup first");
|
||||
await db.update(agents).set({ lifecycleState: "preparing", status: "paused" }).where(eq(agents.id, id));
|
||||
await expect(assertAgentsReadyForEnvironmentChange(db, bound, sibling, users)).rejects.toThrow("need setup first");
|
||||
await expect(assertAgentsReadyForEnvironmentChange(db, bound, bound, users)).resolves.toBeUndefined();
|
||||
await db.update(agents).set({ lifecycleState: "paused", status: "paused" }).where(eq(agents.id, id));
|
||||
await expect(assertAgentsReadyForEnvironmentChange(db, bound, sibling, users)).resolves.toBeUndefined();
|
||||
|
||||
@@ -1030,6 +1030,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
it("fences verification when the saved configuration changes", async () => {
|
||||
const lifecycle = createAgentLifecycle(db); const store = createLifecycleStore(db);
|
||||
const agent = await hire();
|
||||
await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, agent.id));
|
||||
const claimed = (await store.claim(agent.id, "configuration-test", new Date()))!;
|
||||
await store.setRequiredPlugins(claimed, "configuration-test", []);
|
||||
await agentConfiguration(db).update(agent.id, { adapterConfig: { command: "echo" } });
|
||||
@@ -1040,6 +1041,10 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
it("invalidates only changed execution configuration during setup", async () => {
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const agent = await hire();
|
||||
const preparing = await current(agent.id);
|
||||
await lifecycle.updateConfiguration(agent.id, { adapterConfig: { command: "true" } });
|
||||
expect(await current(agent.id)).toMatchObject({ lifecycleVersion: preparing.lifecycleVersion, lifecycleOperation: preparing.lifecycleOperation });
|
||||
await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, agent.id));
|
||||
const before = await current(agent.id);
|
||||
await lifecycle.updateConfiguration(agent.id, { name: "Profile only" });
|
||||
await lifecycle.updateConfiguration(agent.id, { adapterConfig: before.adapterConfig });
|
||||
@@ -1111,6 +1116,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
|
||||
it("rolls back configuration and verification invalidation in the binding transaction", async () => {
|
||||
const agent = await hire();
|
||||
await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, agent.id));
|
||||
const before = await current(agent.id);
|
||||
await expect(updateAgentConfigurationInTransaction(db, agent.id, { name: "Uncommitted" }))
|
||||
.rejects.toThrow("requires a database transaction");
|
||||
|
||||
@@ -3,7 +3,7 @@ import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { agents, companies, companyMemberships, principalPermissionGrants, environments, plugins, createDb, type Db } from "@paperclipai/db";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { createAgentLifecycle, configureAgentLifecycle, createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
|
||||
import { agentService as agentConfiguration } from "../../../services/agents.js";
|
||||
@@ -20,7 +20,9 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
let db: Db;
|
||||
let companyId: string;
|
||||
const workers: ReturnType<typeof configureAgentLifecycle>[] = [];
|
||||
const releases: (() => void)[] = [];
|
||||
beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("paperclip-agent-setup-"); db = createDb(database.connectionString); }, 90_000);
|
||||
afterEach(() => { for (const release of releases.splice(0)) release(); });
|
||||
afterAll(async () => { for (const work of workers) await work.stop(); await database?.cleanup(); });
|
||||
beforeEach(async () => {
|
||||
for (const work of workers) await work.stop();
|
||||
@@ -57,18 +59,31 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
await expect(lifecycle.requestHire(companyId, { id, name: "Early agent" }, { setupAgentId: id })).rejects.toThrow("no longer available");
|
||||
});
|
||||
|
||||
it("prepares agent-dependent drafts, stays idle until finish, and invalidates changed environments", async () => {
|
||||
async function agentEnvironment(hold?: () => Promise<unknown>) {
|
||||
const pluginId = randomUUID(), environmentId = randomUUID();
|
||||
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "agent-environment-test", version: "1.0.0", status: "ready",
|
||||
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"],
|
||||
environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true }] } as never });
|
||||
await db.insert(environments).values({ id: environmentId, name: "Agent-owned test computer", driver: "plugin", status: "active",
|
||||
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } });
|
||||
const call = vi.fn(async (_id, _method, input) => ({ operationId: input.operationId, version: input.version, status: "complete" }));
|
||||
environmentDrivers: ["tasks", "desktop"].map(driverKey => ({ driverKey, requiresAgent: true, supportsTasks: true })) } as never });
|
||||
const environment = async (id: string, driverKey: string) => {
|
||||
await db.insert(environments).values({ id, name: `Agent-owned ${id}`, driver: "plugin", status: "active",
|
||||
config: { pluginKey: pluginId, driverKey, driverConfig: {} } });
|
||||
return id;
|
||||
};
|
||||
await environment(environmentId, "tasks");
|
||||
const call = vi.fn(async (_id, _method, input) => {
|
||||
if (input.phase === "preparing") await hold?.();
|
||||
return { operationId: input.operationId, version: input.version, status: "complete" };
|
||||
});
|
||||
const runHost = vi.fn<LifecycleDriver["runHost"]>(async () => "complete");
|
||||
const driver = createLifecycleDriver(db, { call } as never);
|
||||
const runHost = vi.fn(async () => "complete" as const);
|
||||
const work = configureAgentLifecycle(db, { ...driver, requiredPluginIds: async () => [pluginId], runHost });
|
||||
const work = configureAgentLifecycle(db, { ...driver, runHost });
|
||||
workers.push(work);
|
||||
const phases = () => call.mock.calls.map(([, , request]) => request.phase);
|
||||
return { pluginId, environmentId, environment, call, runHost, work, phases };
|
||||
}
|
||||
|
||||
it("prepares agent-dependent drafts, stays idle until finish, and invalidates changed environments", async () => {
|
||||
const { environmentId, call, runHost, work } = await agentEnvironment();
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const id = randomUUID();
|
||||
const input = { id, name: "Early computer", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId };
|
||||
@@ -130,6 +145,92 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
expect(runHost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a prepared draft prepared while its harness, model, sign-in and instructions change", async () => {
|
||||
const { environmentId, environment, work, phases } = await agentEnvironment();
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const id = randomUUID();
|
||||
await lifecycle.requestHire(companyId, { id, name: "Prepared", adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId }, { setupOnly: true, runnerResolved: true });
|
||||
await work.process(id);
|
||||
const prepared = await current(id);
|
||||
expect(prepared.lifecycleState).toBe("verifying");
|
||||
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "claude", model: "changed", env: { TOKEN: { type: "plain", value: "saved" } } } });
|
||||
await lifecycle.updateConfiguration(id, { runtimeConfig: { heartbeat: { enabled: false } } });
|
||||
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: await environment(randomUUID(), "tasks") });
|
||||
await work.process(id);
|
||||
expect(await current(id)).toMatchObject({ lifecycleState: "verifying", lifecycleVersion: prepared.lifecycleVersion,
|
||||
lifecycleOperation: { id: prepared.lifecycleOperation!.id } });
|
||||
expect(phases()).toEqual(["preparing"]);
|
||||
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: await environment(randomUUID(), "desktop") });
|
||||
expect((await current(id)).lifecycleState).toBe("preparing");
|
||||
await work.process(id);
|
||||
expect(phases()).toEqual(["preparing", "preparing"]);
|
||||
expect((await current(id)).lifecycleState).toBe("verifying");
|
||||
});
|
||||
|
||||
it("verifies a prepared draft at hire without preparing it again", async () => {
|
||||
const { environmentId, environment, work, phases } = await agentEnvironment();
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const hire = async (finalEnvironmentId: string) => {
|
||||
const id = randomUUID();
|
||||
const input = { id, name: "Hired", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId };
|
||||
await lifecycle.requestHire(companyId, input, { setupOnly: true, runnerResolved: true });
|
||||
await work.process(id);
|
||||
const prepared = await current(id);
|
||||
await lifecycle.requestHire(companyId, { ...input, adapterConfig: { provider: "claude", model: "chosen" }, status: "idle",
|
||||
defaultEnvironmentId: finalEnvironmentId }, { setupAgentId: id, runnerResolved: true, responsibleUserId: "owner" });
|
||||
return { prepared, hired: await current(id) };
|
||||
};
|
||||
const same = await hire(environmentId);
|
||||
expect(same.hired).toMatchObject({ lifecycleState: "verifying", lifecycleHolds: [], lifecycleOperation: { responsibleUserId: "owner" } });
|
||||
expect(same.hired.lifecycleVersion).toBeGreaterThan(same.prepared.lifecycleVersion);
|
||||
expect(same.hired.lifecycleOperation!.id).not.toBe(same.prepared.lifecycleOperation!.id);
|
||||
await work.process(same.hired.id);
|
||||
expect((await current(same.hired.id)).lifecycleState).toBe("ready");
|
||||
expect(phases()).toEqual(["preparing", "verifying"]);
|
||||
expect((await hire(await environment(randomUUID(), "desktop"))).hired.lifecycleState).toBe("preparing");
|
||||
});
|
||||
|
||||
it("joins the preparation in progress when a draft is edited and hired", async () => {
|
||||
let entered!: () => void, release!: () => void;
|
||||
const started = new Promise<void>(resolve => { entered = resolve; });
|
||||
const held = new Promise<void>(resolve => { release = resolve; });
|
||||
const { environmentId, work, phases } = await agentEnvironment(() => { entered(); return held; });
|
||||
releases.push(release);
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const id = randomUUID();
|
||||
const input = { id, name: "Joined", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId };
|
||||
await lifecycle.requestHire(companyId, input, { setupOnly: true, runnerResolved: true });
|
||||
const processing = work.process(id);
|
||||
await started;
|
||||
const preparing = await current(id);
|
||||
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "claude" } });
|
||||
await lifecycle.requestHire(companyId, { ...input, adapterConfig: { provider: "claude" }, status: "idle" },
|
||||
{ setupAgentId: id, runnerResolved: true, responsibleUserId: "owner" });
|
||||
expect(await current(id)).toMatchObject({ lifecycleState: "preparing", lifecycleHolds: [], lifecycleVersion: preparing.lifecycleVersion,
|
||||
lifecycleOperation: { id: preparing.lifecycleOperation!.id, leaseOwner: preparing.lifecycleOperation!.leaseOwner, responsibleUserId: "owner" } });
|
||||
release();
|
||||
await processing;
|
||||
expect(await current(id)).toMatchObject({ lifecycleState: "ready", lifecycleHolds: [], lifecycleOperation: { responsibleUserId: "owner" } });
|
||||
expect(phases()).toEqual(["preparing", "verifying"]);
|
||||
});
|
||||
|
||||
it("keeps a running verification when only instructions change", async () => {
|
||||
const { environmentId, work } = await agentEnvironment();
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const id = randomUUID();
|
||||
await lifecycle.requestHire(companyId, { id, name: "Verified", adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "codex", promptTemplate: "Old" }, defaultEnvironmentId: environmentId, status: "idle" }, { runnerResolved: true });
|
||||
await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, id));
|
||||
const verifying = await current(id);
|
||||
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", instructionsBundleMode: "managed",
|
||||
instructionsRootPath: "/managed", instructionsEntryFile: "AGENTS.md", instructionsFilePath: "/managed/AGENTS.md" } });
|
||||
expect(await current(id)).toMatchObject({ lifecycleVersion: verifying.lifecycleVersion,
|
||||
adapterConfig: { instructionsFilePath: "/managed/AGENTS.md" }, lifecycleOperation: { id: verifying.lifecycleOperation!.id } });
|
||||
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", model: "changed" } });
|
||||
expect((await current(id)).lifecycleVersion).toBe(verifying.lifecycleVersion + 1);
|
||||
});
|
||||
|
||||
it("lets only the setup creator configure and retry a stopping draft with creation permission", async () => {
|
||||
await db.insert(companyMemberships).values(["setup-owner", "setup-other"].map(principalId => ({ companyId,
|
||||
principalType: "user", principalId, membershipRole: "member" })));
|
||||
|
||||
@@ -4,7 +4,7 @@ import { agentConfigurationRevision } from "../../../lib/agent-configuration-rev
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { agents, type Db } from "@paperclipai/db";
|
||||
import { agentRecordQueries, AGENT_CONFIGURATION_FIELDS, jsonEqual, type AgentConfigurationPatch, type UpdateAgentOptions } from "../../../lib/agent-records.js";
|
||||
import { agentRecordQueries, adapterConfigWithoutInstructions, AGENT_CONFIGURATION_FIELDS, jsonEqual, type AgentConfigurationPatch, type UpdateAgentOptions } from "../../../lib/agent-records.js";
|
||||
import type { ActivityPublication } from "../../../types/activity-publication.js";
|
||||
import { AgentLifecycleConflict, canConfigureAgentConnection } from "../domain/policy.js";
|
||||
import type { LifecycleEffects } from "./effects.js";
|
||||
@@ -24,21 +24,29 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects
|
||||
}
|
||||
const patch = await effects.prepareConfiguration(tx, current, data, options);
|
||||
assertConfigurationFields(patch);
|
||||
const changed = ["adapterType", "adapterConfig", "runtimeConfig", "defaultEnvironmentId"].some(key =>
|
||||
Object.prototype.hasOwnProperty.call(patch, key) && !jsonEqual(patch[key as keyof typeof patch], current[key as keyof typeof current]));
|
||||
const needsEnvironmentSetup = ["ready", "verifying"].includes(current.lifecycleState)
|
||||
&& Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId")
|
||||
&& patch.defaultEnvironmentId !== current.defaultEnvironmentId
|
||||
const patched = <K extends "adapterType" | "adapterConfig" | "runtimeConfig" | "defaultEnvironmentId">(key: K) =>
|
||||
Object.prototype.hasOwnProperty.call(patch, key) && !jsonEqual(patch[key], current[key]);
|
||||
const environmentChanged = patched("defaultEnvironmentId");
|
||||
const changed = environmentChanged || patched("adapterType") || patched("adapterConfig") || patched("runtimeConfig");
|
||||
const executionChanged = environmentChanged || patched("adapterType") || patched("runtimeConfig") || patched("adapterConfig")
|
||||
&& !jsonEqual(adapterConfigWithoutInstructions(patch.adapterConfig), adapterConfigWithoutInstructions(current.adapterConfig));
|
||||
const settingUp = current.lifecycleHolds.includes("setup");
|
||||
const needsEnvironmentSetup = environmentChanged && ["ready", "preparing", "verifying"].includes(current.lifecycleState)
|
||||
&& await effects.environmentChangeRequiresSetup(tx, current.defaultEnvironmentId, patch.defaultEnvironmentId, current.lifecycleRequiredPluginIds);
|
||||
const pauseForEnvironment = needsEnvironmentSetup && current.lifecycleState === "ready";
|
||||
const prepareEnvironment = needsEnvironmentSetup && !current.lifecycleHolds.includes("setup");
|
||||
const prepareSetup = changed && current.lifecycleHolds.length === 1 && current.lifecycleHolds[0] === "setup"
|
||||
&& ["paused", "preparing", "verifying"].includes(current.lifecycleState)
|
||||
const draft = changed && current.lifecycleHolds.length === 1 && settingUp
|
||||
&& ["paused", "preparing", "verifying"].includes(current.lifecycleState);
|
||||
const draftNeedsPreparation = draft
|
||||
&& await effects.setupRequiresPreparation(tx, current.companyId,
|
||||
Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId") ? patch.defaultEnvironmentId : current.defaultEnvironmentId,
|
||||
{ adapterType: patch.adapterType ?? current.adapterType,
|
||||
adapterConfig: Object.prototype.hasOwnProperty.call(patch, "adapterConfig") ? patch.adapterConfig : current.adapterConfig });
|
||||
const invalidate = changed && (["preparing", "verifying", "resuming"].includes(current.lifecycleState) || prepareSetup || pauseForEnvironment);
|
||||
const prepareSetup = draftNeedsPreparation && (current.lifecycleState === "paused" || needsEnvironmentSetup);
|
||||
const stopSetup = draft && !draftNeedsPreparation && current.lifecycleState !== "paused";
|
||||
const prepareEnvironment = needsEnvironmentSetup && !settingUp && !pauseForEnvironment;
|
||||
const reverify = executionChanged && !settingUp && current.lifecycleState === "verifying";
|
||||
const invalidate = prepareSetup || stopSetup || prepareEnvironment || pauseForEnvironment || reverify
|
||||
|| changed && current.lifecycleState === "resuming";
|
||||
if(prepareSetup&&!canConfigureAgentConnection(current))await effects.beforeConnectionEligibilityRestore?.(tx,current.companyId,current.id);
|
||||
if (pauseForEnvironment) await effects.beforeStatusChange(tx, current.companyId, id, current.status, "paused");
|
||||
if (invalidate) await effects.notifyWork(tx);
|
||||
@@ -46,8 +54,7 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects
|
||||
lifecycleVersion: current.lifecycleVersion + 1, lifecycleError: null,
|
||||
...(prepareSetup || prepareEnvironment ? { lifecycleState: "preparing" as const } : {}),
|
||||
...(pauseForEnvironment ? { lifecycleState: "pausing" as const, status: "paused", pausedAt: new Date() } : {}),
|
||||
...(!prepareSetup && current.lifecycleHolds.includes("setup") && ["preparing", "verifying"].includes(current.lifecycleState)
|
||||
? { lifecycleState: "pausing" as const } : {}),
|
||||
...(stopSetup ? { lifecycleState: "pausing" as const } : {}),
|
||||
lifecycleOperation: { ...current.lifecycleOperation!, id: randomUUID(), hostComplete: false,
|
||||
completedPluginIds: [], attempts: 0, leaseOwner: undefined, leaseUntil: undefined, leaseHolder: undefined,
|
||||
retryAt: undefined, retryRequired: undefined, verificationFailures: undefined,
|
||||
|
||||
@@ -38,20 +38,30 @@ export function agentRecords(db: Db, effects: LifecycleEffects) {
|
||||
const companyHolds = company?.status === "paused" ? ["company_paused"] : company?.status === "archived" ? ["company_archived"] : [];
|
||||
const holds = [...(status === "paused" ? [pauseReason ?? "manual"] : []), ...companyHolds];
|
||||
const prepareSetup = options?.setupOnly && !companyHolds.length && await effects.setupRequiresPreparation(txDb, companyId, prepared.defaultEnvironmentId, prepared);
|
||||
const keepsPreparation = setup !== undefined && status !== "pending_approval" && status !== "terminated" && !holds.length
|
||||
&& (setup.lifecycleState === "preparing" || setup.lifecycleState === "verifying")
|
||||
&& !await effects.environmentChangeRequiresSetup(txDb, setup.defaultEnvironmentId,
|
||||
prepared.defaultEnvironmentId === undefined ? setup.defaultEnvironmentId : prepared.defaultEnvironmentId, setup.lifecycleRequiredPluginIds);
|
||||
const joinsPreparation = keepsPreparation && setup.lifecycleState === "preparing" && setup.lifecycleOperation !== null;
|
||||
const lifecycleState = status === "pending_approval" ? "pending_approval" : status === "terminated" ? "terminated"
|
||||
: prepareSetup ? "preparing" : status === "paused" ? "paused" : companyHolds.length ? "pausing" : "preparing";
|
||||
if (lifecycleState === "preparing" || lifecycleState === "pausing") await effects.notifyWork(tx);
|
||||
: prepareSetup ? "preparing" : status === "paused" ? "paused" : companyHolds.length ? "pausing"
|
||||
: keepsPreparation && setup.lifecycleState === "verifying" ? "verifying" : "preparing";
|
||||
if (lifecycleState === "preparing" || lifecycleState === "verifying" || lifecycleState === "pausing") await effects.notifyWork(tx);
|
||||
const createdStatus=status === "pending_approval" ? "pending_approval" : status === "terminated" ? "terminated" : "paused";
|
||||
const responsibleUserId = options?.responsibleUserId ?? options?.createdByUserId;
|
||||
const values: typeof agents.$inferInsert = {
|
||||
...prepared,
|
||||
...(setup ? { permissions: preserveAgentInteractionPermissions(setup.permissions, prepared.permissions) } : {}),
|
||||
createdByUserId: setup?.createdByUserId ?? options?.createdByUserId ?? null,
|
||||
lifecycleState,
|
||||
lifecycleVersion: setup ? setup.lifecycleVersion + 1 : 1,
|
||||
lifecycleVersion: !setup ? 1 : joinsPreparation ? setup.lifecycleVersion : setup.lifecycleVersion + 1,
|
||||
lifecycleHolds: holds,
|
||||
lifecycleError: null,
|
||||
pauseReason: holds[0] ?? null,
|
||||
pausedAt: holds.length ? new Date() : null,
|
||||
lifecycleOperation: { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, resumeState: "preparing" as const, responsibleUserId: options?.responsibleUserId ?? options?.createdByUserId },
|
||||
lifecycleOperation: joinsPreparation
|
||||
? { ...setup.lifecycleOperation!, retryAt: undefined, responsibleUserId }
|
||||
: { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, resumeState: "preparing" as const, responsibleUserId },
|
||||
status: createdStatus,
|
||||
companyId,
|
||||
};
|
||||
|
||||
@@ -86,10 +86,11 @@ export async function agentsNeedSetupForEnvironmentChange(db: Db, before: AgentE
|
||||
const usesEnvironment = or(users.environmentId ? eq(agents.defaultEnvironmentId, users.environmentId) : undefined,
|
||||
users.inheritsDefault ? isNull(agents.defaultEnvironmentId) : undefined);
|
||||
if (!usesEnvironment) return false;
|
||||
const unprepared = previous?.pluginId === target.pluginId ? undefined
|
||||
const changesDriver = previous?.pluginId === target.pluginId;
|
||||
const unprepared = changesDriver ? undefined
|
||||
: sql`not coalesce(${agents.lifecycleRequiredPluginIds}, '[]'::jsonb) @> ${JSON.stringify([target.pluginId])}::jsonb`;
|
||||
const [waiting] = await db.select({ id: agents.id }).from(agents).where(and(usesEnvironment,
|
||||
inArray(agents.lifecycleState, ["ready", "verifying"]), unprepared)).limit(1);
|
||||
inArray(agents.lifecycleState, changesDriver ? ["ready", "preparing", "verifying"] : ["ready", "verifying"]), unprepared)).limit(1);
|
||||
return Boolean(waiting);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user