Fix Photon capability fallback and retryable construction cleanup

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-11-11 06:47:09 -06:00
1 parent 02441b75b3
commit 30bcfa3bbd
17 files changed
+848 -88

No files matched your search

+10 -1
View File
@@ -35,6 +35,8 @@ const required = [
["@chat-adapter/teams", "4.39.0"],
["@chat-adapter/telegram", "4.39.0"],
["@discordjs/ws", "1.2.3"],
["@grpc/grpc-js", "1.14.5"],
["@photon-ai/advanced-imessage", "2.2.0"],
];
for (const [name, version] of required) {
@@ -83,7 +85,12 @@ test("release selection includes every chat runtime patch and the existing ACPX
join(tmpdir(), "paperclip-chat-release-contract-"),
);
t.after(() => rmSync(destination, { recursive: true, force: true }));
for (const [name, version] of [...required, ["acpx", "0.13.1"]]) {
for (const [name, version] of [
...required,
["acpx", "0.13.1"],
["@agentclientprotocol/claude-agent-acp", "0.73.0"],
["@agentclientprotocol/codex-acp", "1.6.2"],
]) {
const directory = join(destination, "node_modules", name);
mkdirSync(directory, { recursive: true });
writeFileSync(
@@ -101,6 +108,8 @@ test("release selection includes every chat runtime patch and the existing ACPX
[
...required.map(([name, version]) => `${name}@${version}`),
"acpx@0.13.1",
"@agentclientprotocol/claude-agent-acp@0.73.0",
"@agentclientprotocol/codex-acp@1.6.2",
].sort(),
);
writeFileSync(
+2
View File
@@ -129,6 +129,8 @@
"@chat-adapter/teams",
"@chat-adapter/telegram",
"@discordjs/ws",
"@grpc/grpc-js",
"@photon-ai/advanced-imessage",
"acpx"
],
"devDependencies": {
@@ -2,13 +2,14 @@ import { randomUUID, generateKeyPairSync } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { eq, sql } from "drizzle-orm";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { applyPendingMigrations, agents, chatEndpointLeases, chatEndpoints, chatConversations, chatEndpointResources, companies, chatSdkState, companySecrets, createDb, toolConnections } from "@paperclipai/db";
import { applyPendingMigrations, companyMemberships, agents, chatEndpointLeases, chatEndpoints, chatConversations, chatEndpointResources, chatPublications, companies, chatSdkState, companySecrets, createDb, toolConnections } from "@paperclipai/db";
import { resolveExternalTestDatabaseUrl } from "../helpers/external-test-database.js";
import { createChatMilestoneFixtures } from "../helpers/chat-milestone-fixtures.js";
import { chatChannelService } from "../../services/chat-channels.js";
import { createChatSdkRuntime } from "../../services/chat-sdk-runtime.js";
import { createChatSdkRuntime, type CreateChatSdkEndpointRuntimeOptions } from "../../services/chat-sdk-runtime.js";
import { ChatRuntime, createChatRuntime } from "../../services/chat-runtime.js";
import { heartbeatService } from "../../services/heartbeat.js";
import { instanceSettingsService } from "../../services/instance-settings.js";
import { PhotonChatAdapter } from "../../services/photon/adapter.js";
@@ -34,6 +35,7 @@ import { createPhotonExternalOwner, PhotonLocalResources } from "../../services/
import type { ProcessProbe } from "../../services/owner-proof.js";
import { deleteCompany } from "../../services/company-deletion.js";
import { connectionManagementService } from "../../services/connection-management.js";
import { toolAccessService } from "../../services/tool-access.js";
import { preparePhotonCompanyDeletion, assertPhotonCompanyRetired, lockPhotonCompanyMutation, registerPhotonRemovalOwner } from "../../services/chat-channels/imessage-photon/company-retirement.js";
import { chatCompanyDeletion } from "../../services/chat-channels/company-deletion.js";
@@ -46,7 +48,7 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
let f: Awaited<ReturnType<ReturnType<typeof createChatMilestoneFixtures>["create"]>>;
let directory: string;
const services: ReturnType<typeof chatChannelService>[] = [];
const runtimes: ReturnType<typeof createChatSdkRuntime>[] = [];
const runtimes: (ReturnType<typeof createChatSdkRuntime> | ReturnType<typeof createChatRuntime>)[] = [];
const heartbeats: ReturnType<typeof heartbeatService>[] = [];
const owners: ReturnType<typeof createPhotonExternalRuntimeOwner>[] = [];
const coordinators: ReturnType<typeof createDeliveryWorkCoordinator>[] = [];
@@ -105,6 +107,146 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
expect(connection).toMatchObject({enabled:true,status:"active",healthStatus:"healthy"});
expect(connection!.credentialSecretRefs.length).toBeGreaterThan(0);
});
it("positively unsupported Cloud retains normal local Photon intake across restart without staging a handoff",async()=>{
// Preserve the real service/configuration/credential SQL owners. Only the
// provider HTTP response and unused SDK start are controlled boundaries.
const signing = generateKeyPairSync("ed25519"), sealing = generateKeyPairSync("x25519");
const config = { baseUrl: "https://cloud.example", instanceId: "instance", environment: "test" as const,
signPrivateKey: signing.privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
sealPrivateKey: sealing.privateKey.export({ type: "pkcs8", format: "pem" }).toString() };
const status = vi.fn(async () => Response.json({ active: true, status: "active", profiles: [] }));
const connector = cloudConnectors.createPaperclipCloudConnector({ config, request: status });
vi.spyOn(cloudConnectors, "paperclipCloudConnectorConfigFromEnv").mockReturnValue(config);
vi.spyOn(cloudConnectors, "createPaperclipCloudConnector").mockReturnValue(connector);
const runtime=createChatSdkRuntime();runtimes.push(runtime);
vi.spyOn(PhotonChatAdapter.prototype,"initialize").mockResolvedValue(undefined);
vi.spyOn(PhotonReceiver.prototype,"start").mockImplementation(()=>undefined);
const fetchProvider: typeof fetch=async(input,init)=>{
const url=new URL(input instanceof Request?input.url:String(input));
expect(url.origin).toBe("https://spectrum.photon.codes");
expect(new Headers(init?.headers).get("authorization")).toBe("Basic "+Buffer.from("project:controlled-project-secret").toString("base64"));
if(url.pathname==="/projects/project/"&&init?.method==="GET")return Response.json({succeed:true,data:{id:"project",name:"Controlled Photon"}});
if(url.pathname==="/projects/project/imessage/tokens"&&init?.method==="POST")return Response.json({succeed:true,data:{type:"dedicated",auth:{line:"controlled-line-token"},numbers:{line:"+15555550100"},expiresIn:300}});
throw new Error("unexpected controlled Spectrum request");
};
const heartbeat=heartbeatService(db);heartbeats.push(heartbeat);
const service=chatChannelService(db,{runtime,heartbeat,fetch:fetchProvider,publicBaseUrl:"https://tenant.example"});services.push(service);
const created=await service.create(f.companyId,{provider:"imessage-photon",assignedAgentId:f.agentId},f.userId);
if(!created)throw new Error("normal Photon endpoint creation failed");
const endpointId=created.id;
await service.configure(endpointId,{action:"configure",credentials:{projectSecret:"controlled-project-secret"},photon:{allocation:"dedicated",projectId:"project",lineId:"line"}},f.userId);
const [endpoint]=await db.select().from(chatEndpoints).where(eq(chatEndpoints.id,endpointId));
expect(endpoint?.setup,"normal configuration must stage Photon handoff subject").toMatchObject({photonExternalSubject:f.userId});
expect(endpoint?.status).toBe("verifying");
const state = photonStateFor(db, { companyId: f.companyId, endpointId });
expect(await state.read(PHOTON_EXTERNAL_STATE), "a positively unsupported Cloud must not persist an enrolling receiver").toBeNull();
expect(runtime.get(endpointId)).not.toBeNull();
await service.shutdown();
const restarted = createChatSdkRuntime(); runtimes.push(restarted);
const next = chatChannelService(db, { runtime: restarted, heartbeat, fetch: fetchProvider, publicBaseUrl: "https://tenant.example" }); services.push(next);
// Restart an already-configured endpoint through its NORMAL reconstruction
// entrypoint, not a second configuration or synthetic status transition.
await expect(next.reconcileProviderRuntimes()).resolves.toEqual({ eligible: 1, local: 1, ownedElsewhere: 0, failed: 0 });
expect(restarted.get(endpointId), "restart must retain actual normal local runtime creation").not.toBeNull();
expect(await state.read(PHOTON_EXTERNAL_STATE)).toBeNull();
expect(status.mock.calls.length).toBeGreaterThan(0);
const [connection]=await db.select().from(toolConnections).where(eq(toolConnections.id,endpoint!.connectionId));
expect(connection).toMatchObject({enabled:true,status:"active",healthStatus:"healthy"});
expect(connection!.credentialSecretRefs.length).toBeGreaterThan(0);
});
it("normal receiver cancellation settles only the exact never-created resource and retains its enrolled business intent",async()=>{
// Preserve the real service/configuration/credential SQL owners. Only the
// provider HTTP response and unused SDK start are controlled boundaries.
const signing = generateKeyPairSync("ed25519"), sealing = generateKeyPairSync("x25519");
const config = { baseUrl: "https://cloud.example", instanceId: "instance", environment: "test" as const,
signPrivateKey: signing.privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
sealPrivateKey: sealing.privateKey.export({ type: "pkcs8", format: "pem" }).toString() };
const status = vi.fn(async () => Response.json({ active: true, status: "active", profiles: [], photonReceiver: { version: 1 } }));
const connector = cloudConnectors.createPaperclipCloudConnector({ config, request: status });
vi.spyOn(cloudConnectors, "paperclipCloudConnectorConfigFromEnv").mockReturnValue(config);
vi.spyOn(cloudConnectors, "createPaperclipCloudConnector").mockReturnValue(connector);
const runtime=createChatSdkRuntime();runtimes.push(runtime);
let cancelledAbort: (() => Promise<void>) | undefined;
const replace = runtime.replaceEndpoint.bind(runtime);
vi.spyOn(runtime, "replaceEndpoint").mockImplementation(async options => {
const lifecycle: CreateChatSdkEndpointRuntimeOptions & { onConstructionAborted?(): Promise<void> } = options;
cancelledAbort = lifecycle.onConstructionAborted;
const replacing = replace(options);
const joined = replacing.then(value => ({ value }), error => ({ error }));
await runtime.removeEndpoint(options.endpointId);
const result = await joined;
if ("error" in result) throw result.error;
return result.value;
});
const allocate = vi.spyOn(photonClients, "createOwnedPhotonClient");
vi.spyOn(PhotonChatAdapter.prototype,"initialize").mockResolvedValue(undefined);
vi.spyOn(PhotonReceiver.prototype,"start").mockImplementation(()=>undefined);
const fetchProvider: typeof fetch=async(input,init)=>{
const url=new URL(input instanceof Request?input.url:String(input));
expect(url.origin).toBe("https://spectrum.photon.codes");
expect(new Headers(init?.headers).get("authorization")).toBe("Basic "+Buffer.from("project:controlled-project-secret").toString("base64"));
if(url.pathname==="/projects/project/"&&init?.method==="GET")return Response.json({succeed:true,data:{id:"project",name:"Controlled Photon"}});
if(url.pathname==="/projects/project/imessage/tokens"&&init?.method==="POST")return Response.json({succeed:true,data:{type:"dedicated",auth:{line:"controlled-line-token"},numbers:{line:"+15555550100"},expiresIn:300}});
throw new Error("unexpected controlled Spectrum request");
};
let replaceBeforeLockedCommit = false;
const normalStore = photonStores.createPhotonExternalStore;
vi.spyOn(photonStores, "createPhotonExternalStore").mockImplementation(database => {
const store = normalStore(database), retained = store.retained.bind(store);
return { ...store, retained: async (...args: Parameters<typeof store.retained>) => {
const [expected, update, after] = args;
if (replaceBeforeLockedCommit) {
replaceBeforeLockedCommit = false;
if (!expected.localResource) throw new Error("actual receiver descriptor absent");
const changedId = randomUUID();
const newer = { ...expected, localResourceId: changedId,
localResource: { ...expected.localResource, id: changedId, closed: false } };
delete newer.localClosureConfirmed; // An unclosed replacement has no true-only close receipt.
expect(newer.localClosureConfirmed).toBeUndefined();
expect(newer.localResource.closed).toBe(false);
// Controlled store-contract race: use REAL SQL but feed the update its
// latest locked owner, rather than the earlier preliminary snapshot.
await photonStateFor(database, expected.identity).update(PHOTON_EXTERNAL_STATE, () => newer);
return retained(newer, update, after);
}
return retained(...args);
} };
});
const heartbeat=heartbeatService(db);heartbeats.push(heartbeat);
const service=chatChannelService(db,{runtime,heartbeat,fetch:fetchProvider,publicBaseUrl:"https://tenant.example"});services.push(service);
const created=await service.create(f.companyId,{provider:"imessage-photon",assignedAgentId:f.agentId},f.userId);
if(!created)throw new Error("normal Photon endpoint creation failed");
const endpointId=created.id;
await expect(service.configure(endpointId,{action:"configure",credentials:{projectSecret:"controlled-project-secret"},photon:{allocation:"dedicated",projectId:"project",lineId:"line"}},f.userId)).rejects.toMatchObject({ status: 422 });
const [endpoint]=await db.select().from(chatEndpoints).where(eq(chatEndpoints.id,endpointId));
expect(endpoint?.setup,"normal configuration must stage Photon handoff subject").toMatchObject({photonExternalSubject:f.userId});
expect(endpoint?.status).toBe("attention");
const state = photonStateFor(db, { companyId: f.companyId, endpointId });
const retained = readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE));
expect(allocate).not.toHaveBeenCalled();
expect(retained?.localClosureConfirmed, "a superseded pre-constructor receiver must settle its exact never-created resource").toBe(true);
expect(retained?.localResource?.closed).toBe(true);
expect(retained).toMatchObject({ phase: "enrolling", initialSequence: null, joinedSequence: null, acceptedSequence: null, pending: null });
expect(retained?.senderResource).toBeUndefined();
expect(runtime.get(endpointId)).toBeNull();
if (!cancelledAbort || !retained) throw new Error("normal exact receiver cancellation owner absent");
await cancelledAbort(); // Same caller's lost cleanup reply is idempotent.
expect(readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE))).toEqual(retained);
replaceBeforeLockedCommit = true;
await expect(cancelledAbort()).rejects.toThrow("receiver changed during close commit");
const raced = readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE));
expect(raced?.handoffId).toBe(retained.handoffId);
expect(raced?.localResourceId).not.toBe(retained.localResourceId);
expect(raced?.localResource?.closed).toBe(false);
expect(raced?.localClosureConfirmed).toBeUndefined();
if (!raced) throw new Error("controlled later receiver owner absent");
// Controlled replacement of the durable handoff identity is a negative CAS
// port, not fabricated Cloud acceptance or process-birth evidence.
const newer = { ...raced, handoffId: randomUUID() };
await state.update(PHOTON_EXTERNAL_STATE, () => newer);
await cancelledAbort();
expect(readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE))).toEqual(newer);
});
it("unchanged external intake stays idle but changed or revoked authority is immediately due and retires normally",async()=>{
const [endpoint]=await db.select().from(chatEndpoints).where(eq(chatEndpoints.id,f.endpointId)); if(!endpoint)throw new Error("fixture endpoint absent");
@@ -113,6 +255,7 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
const changedNotify=vi.fn();
const configured={provider:"imessage-photon" as const,userName:"Agent",intakeAfter:1,credentials:{allocation:"dedicated" as const,projectId:"project",projectSecret:"controlled-secret",lineId:"line",phoneNumber:"+15555550100"}};
const makeOwner=()=>createPhotonExternalRuntimeOwner(db,{
retainConstructionCleanup: () => { throw new Error("revoked fixture cannot allocate a never-created resource"); },
broker:()=>brokerAvailable?({instanceIdentity:()=>({instanceId:"instance",environment:"test" as const}),photonReceiverOperation:async({operation})=>{
requests.push(structuredClone(operation));
const value=readPhotonExternalState(await photonStateFor(db,{companyId:f.companyId,endpointId:f.endpointId}).read(PHOTON_EXTERNAL_STATE));
@@ -187,14 +330,82 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
}
});
async function managedConfiguration() {
it("normal remove fences an unaccepted Photon enrollment before removing its credentials",async()=>{
// Preserve the real service/configuration/credential SQL owners. Only the
// provider HTTP response and unused SDK start are controlled boundaries.
const signing = generateKeyPairSync("ed25519"), sealing = generateKeyPairSync("x25519");
const config = { baseUrl: "https://cloud.example", instanceId: "instance", environment: "test" as const,
signPrivateKey: signing.privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
sealPrivateKey: sealing.privateKey.export({ type: "pkcs8", format: "pem" }).toString() };
const connector = cloudConnectors.createPaperclipCloudConnector({ config,
request: async () => Response.json({ active: true, status: "active", profiles: [], photonReceiver: { version: 1 } }) });
vi.spyOn(cloudConnectors, "paperclipCloudConnectorConfigFromEnv").mockReturnValue(config);
vi.spyOn(cloudConnectors, "createPaperclipCloudConnector").mockReturnValue(connector);
const currentAdmin = randomUUID();
const requests: Record<string, unknown>[] = [];
vi.spyOn(connector, "photonReceiverOperation").mockImplementation(async ({ operation, subject }) => {
requests.push(structuredClone(operation));
const retained = readPhotonExternalState(await photonStateFor(db, { companyId: f.companyId, endpointId }).read(PHOTON_EXTERNAL_STATE));
if (!retained) throw new Error("actual original enrollment intent absent");
if (operation.kind === "cancel-enrollment") {
expect(subject).toBe(currentAdmin);
expect(operation).toEqual({ kind: "cancel-enrollment", binding: retained.binding, handoffId: retained.handoffId, originalSubject: retained.identity.subject });
expect(retained).toMatchObject({ phase: "retiring", localClosureConfirmed: true, enrollmentCancellation: "requested" });
// Controlled exact Cloud cancellation API receipt, NOT a physical claim.
// The independent Cloud owner controls qualify its atomic floor below.
return { binding: retained.binding, handoffId: retained.handoffId, phase: "cancelled" };
}
throw new Error("Photon retirement owner absent");
});
const runtime=createChatSdkRuntime();runtimes.push(runtime);
vi.spyOn(PhotonChatAdapter.prototype,"initialize").mockResolvedValue(undefined);
vi.spyOn(PhotonReceiver.prototype,"start").mockImplementation(()=>undefined);
const fetchProvider: typeof fetch=async(input,init)=>{
const url=new URL(input instanceof Request?input.url:String(input));
expect(url.origin).toBe("https://spectrum.photon.codes");
expect(new Headers(init?.headers).get("authorization")).toBe("Basic "+Buffer.from("project:controlled-project-secret").toString("base64"));
if(url.pathname==="/projects/project/"&&init?.method==="GET")return Response.json({succeed:true,data:{id:"project",name:"Controlled Photon"}});
if(url.pathname==="/projects/project/imessage/tokens"&&init?.method==="POST")return Response.json({succeed:true,data:{type:"dedicated",auth:{line:"controlled-line-token"},numbers:{line:"+15555550100"},expiresIn:300}});
throw new Error("unexpected controlled Spectrum request");
};
const heartbeat=heartbeatService(db);heartbeats.push(heartbeat);
const service=chatChannelService(db,{runtime,heartbeat,fetch:fetchProvider,publicBaseUrl:"https://tenant.example"});services.push(service);
const created=await service.create(f.companyId,{provider:"imessage-photon",assignedAgentId:f.agentId},f.userId);
if(!created)throw new Error("normal Photon endpoint creation failed");
const endpointId=created.id;
await service.configure(endpointId,{action:"configure",credentials:{projectSecret:"controlled-project-secret"},photon:{allocation:"dedicated",projectId:"project",lineId:"line"}},f.userId);
const [endpoint]=await db.select().from(chatEndpoints).where(eq(chatEndpoints.id,endpointId));
const state = photonStateFor(db, { companyId: f.companyId, endpointId });
const original = readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE));
if (!endpoint || !original) throw new Error("normal original Photon intent absent");
expect(original.phase).toBe("enrolling"); expect(runtime.get(endpointId)).not.toBeNull();
expect(requests).toEqual([]); // Configuration never attempted a Cloud enrollment.
await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: currentAdmin, status: "active", membershipRole: "owner" });
await db.delete(companyMemberships).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, f.userId)));
const management = connectionManagementService(db), resource = { type: "connection_management" as const, companyId: f.companyId,
connectionId: endpoint.connectionId, provider: "imessage-photon", purpose: "chat" as const, operation: "POST /chat-endpoints/:endpointId/configure" };
await expect(management.authorize({ type: "board", userId: f.userId, source: "session" }, "connections:configure", resource)).rejects.toMatchObject({ status: 403 });
await expect(management.authorize({ type: "board", userId: randomUUID(), source: "session" }, "connections:configure", resource)).rejects.toMatchObject({ status: 403 });
const authority = await management.authorize({ type: "board", userId: currentAdmin, source: "session" }, "connections:configure", resource);
await expect(service.configure(endpointId, { action: "remove" }, currentAdmin, authority),
"ordinary removal must fence an unaccepted enrollment instead of stranding missing Cloud custody").resolves.toMatchObject({ status: "archived" });
const [removed] = await db.select().from(toolConnections).where(eq(toolConnections.id, endpoint.connectionId));
expect(removed.credentialSecretRefs).toEqual([]);
expect(readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE))).toMatchObject({ phase: "retired", enrollmentCancellation: "fenced",
handoffId: original.handoffId, binding: original.binding, initialSequence: original.initialSequence, acceptedSequence: original.acceptedSequence });
expect(requests.map(value => value.kind)).toEqual(["cancel-enrollment"]);
await expect(service.configure(endpointId, { action: "remove" }, currentAdmin, authority)).rejects.toMatchObject({ status: 409 });
});
async function managedConfiguration(useNormalRegistry = false) {
const createRegistry = useNormalRegistry ? createChatRuntime : createChatSdkRuntime;
// The real connector object/composition is retained; only the provider RPC
// port is controlled here. This is not managed distribution/auth proof.
const signing = generateKeyPairSync("ed25519"), sealing = generateKeyPairSync("x25519");
const config = { baseUrl: "https://cloud.example", instanceId: "instance", environment: "test" as const,
signPrivateKey: signing.privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
sealPrivateKey: sealing.privateKey.export({ type: "pkcs8", format: "pem" }).toString() };
const connector = cloudConnectors.createPaperclipCloudConnector({ config });
const connector = cloudConnectors.createPaperclipCloudConnector({ config, request: async () => Response.json({ active: true, status: "active", profiles: [], photonReceiver: { version: 1 } }) });
vi.spyOn(cloudConnectors, "paperclipCloudConnectorConfigFromEnv").mockReturnValue(config);
vi.spyOn(cloudConnectors, "createPaperclipCloudConnector").mockReturnValue(connector);
vi.spyOn(PhotonChatAdapter.prototype, "initialize").mockResolvedValue(undefined);
@@ -207,7 +418,7 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
data: { type: "dedicated", auth: { line: "controlled-line-token" }, numbers: { line: "+15555550100" }, expiresIn: 300 } });
throw new Error("unexpected controlled Spectrum request");
};
let runtime = createChatSdkRuntime(); runtimes.push(runtime);
let runtime = createRegistry(); runtimes.push(runtime);
const heartbeat = heartbeatService(db); heartbeats.push(heartbeat);
let service = chatChannelService(db, { runtime, heartbeat, fetch: fetchProvider, publicBaseUrl: "https://tenant.example" }); services.push(service);
const endpoint = await service.create(f.companyId, { provider: "imessage-photon", assignedAgentId: f.agentId }, f.userId);
@@ -239,14 +450,55 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
return operation.kind === "status" ? { binding, handoffId: retained.handoffId, phase: retirement } : { binding };
});
return { get service() { return service; }, get runtime() { return runtime; }, endpoint, connection, state, retained, requests,
async reconstructExternal(control: ReturnType<typeof photonFixture>) {
async reconstructExternal(control: ReturnType<typeof photonFixture>, cancelFirstReplacement = false, constructorFault?: Error, expectedReservationFailure = false) {
// Retain controlled enrolled history, but really join the original local
// service and its receiver lease before reconstructing the normal owner.
await service.shutdown();
runtime = createChatSdkRuntime(); runtimes.push(runtime);
runtime = createRegistry(); runtimes.push(runtime);
service = chatChannelService(db, { runtime, heartbeat, fetch: fetchProvider, publicBaseUrl: "https://tenant.example" }); services.push(service);
vi.spyOn(photonClients, "createOwnedPhotonClient").mockReturnValue(control.adapter.client);
let observedCloudBirth = false;
const clients: { client: ReturnType<typeof photonFixture>["adapter"]["client"]; methods: { method: string; active?: unknown }[]; closeAttempts: number; joined: boolean }[] = [];
const births: { runtime: NonNullable<ReturnType<typeof runtime.get>>; resourceId: string }[] = [];
const allocate = vi.spyOn(photonClients, "createOwnedPhotonClient");
if (constructorFault) allocate.mockImplementation(() => { throw constructorFault; });
else allocate.mockImplementation(() => {
// Distinct controlled client for EVERY actual factory allocation. The
// shared provider port owns send receipts; each client owns its close.
const owned = photonFixture(), methods: { method: string; active?: unknown }[] = [];
const row = { client: owned.adapter.client, methods, closeAttempts: 0, joined: false };
const close = async () => {
row.closeAttempts++;
if (row.joined) return;
await control.client.close(); // Existing shared controlled close-fault port.
await owned.client.close();
row.joined = true;
};
const channel = (name: "chats" | "messages" | "attachments" | "groups" | "polls" | "events") => new Proxy(owned.adapter.client[name], {
get(target, key, receiver) {
const method = Reflect.get(target, key, receiver);
if (typeof method !== "function") return method;
return (...args: unknown[]) => {
if (row.joined) throw new Error("Controlled Photon client used after its own close");
const operation = `${name}.${String(key)}`;
methods.push({ method: operation, ...(operation === "chats.setTyping" ? { active: args[1] } : {}) });
if (["chats.get", "messages.sendText", "chats.setTyping"].includes(operation)) expect(args[0]).toBe(control.chat.guid);
// These are actual method invocations, not prefilled roles or
// provider outcomes. One provider receipt map spans clients.
const providerMethod = Reflect.get(control.adapter.client[name], key);
if (typeof providerMethod !== "function") throw new Error("Unsupported controlled Photon method");
return Reflect.apply(providerMethod, control.adapter.client[name], args);
};
},
});
row.client = new Proxy(owned.adapter.client, { get(target, key, receiver) {
if (key === "close") return close;
if (key === "chats" || key === "messages" || key === "attachments" || key === "groups" || key === "polls" || key === "events") return channel(key);
return Reflect.get(target, key, receiver);
} });
clients.push(row);
return row.client;
});
let observedCloudBirth = false, cancel = cancelFirstReplacement;
let cancelledAbort: (() => Promise<void>) | undefined;
const replace = runtime.replaceEndpoint.bind(runtime);
vi.spyOn(runtime, "replaceEndpoint").mockImplementation(async options => {
const selected = readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE));
@@ -256,7 +508,24 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
expect(typeof options.callbacks.onPhotonUsefulClientDebt).toBe("function");
expect(typeof options.callbacks.onPhotonSenderRuntimeClosed).toBe("function");
observedCloudBirth = true;
return replace(options); // Actual normal Runtime/SDK; callbacks unchanged.
if (cancel) {
cancel = false;
const lifecycle: CreateChatSdkEndpointRuntimeOptions & { onConstructionAborted?(): Promise<void> } = options;
cancelledAbort = lifecycle.onConstructionAborted;
// Actual registry queue cancellation before its constructor runs.
const replacing = replace(options);
const joined = replacing.then(value => ({ value }), error => ({ error }));
const removal = runtime.removeEndpoint(endpoint.id).then(() => ({ complete: true as const }), error => ({ error }));
const [result, removed] = await Promise.all([joined, removal]);
if ("error" in result && "error" in removed) throw new AggregateError([result.error, removed.error], "Controlled cancellation and normal removal both retained cleanup failures");
if ("error" in result) throw result.error;
if ("error" in removed) throw removed.error;
return result.value;
}
const constructed = await replace(options); // Actual normal Runtime/SDK; callbacks unchanged.
if (!selected?.senderResource) throw new Error("actual prebirth sender descriptor absent");
births.push({ runtime: constructed, resourceId: selected.senderResource.id });
return constructed;
});
// Complete existing direct-message history, matching normal inbound
// ensureResource: same company/endpoint/canonical thread, available DM.
@@ -274,6 +543,51 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
if (!conversation) throw new Error("normal outbound conversation fixture absent");
const published = await service.publishBoardMessage(endpoint.id, conversation.id,
"Controlled ordinary sender bootstrap", randomUUID(), f.userId);
if (cancelFirstReplacement || constructorFault || expectedReservationFailure) {
expect(published?.state).not.toBe("published");
expect(control.client.messages.sendText).not.toHaveBeenCalled();
if (!published || published.state !== "delivery_unknown") throw new Error("actual original publication unknown receipt absent");
const originalId = published.id;
return { cancelledAbort: async () => { if (!cancelledAbort) throw new Error("normal never-created cleanup callback absent"); await cancelledAbort(); },
retryOriginalPublication: async () => {
// The normal FIFO deliberately blocks later publications behind
// unknown delivery. Only the explicit operator Retry authorizes
// this ORIGINAL publication; no new row or implicit resend.
const authority = await connectionManagementService(db).authorize({ type: "board", userId: f.userId, source: "session" },
"connections:configure", { type: "connection_management", companyId: f.companyId, connectionId: connection.id,
provider: "imessage-photon", purpose: "chat", operation: "POST /chat-endpoints/:endpointId/publications/:publicationId/resolve" });
await authority.reauthorize();
await service.resolvePublication(endpoint.id, originalId, "retry_anyway", f.userId);
const [current] = await db.select().from(chatPublications).where(and(eq(chatPublications.companyId, f.companyId),
eq(chatPublications.endpointId, endpoint.id), eq(chatPublications.id, originalId)));
if (!current) throw new Error("original publication receipt missing after ordinary operator Retry");
expect(current.id).toBe(originalId); expect(current.payload).toEqual(published.payload);
return current;
},
verifyUsefulOwnership: async () => {
expect(births).toHaveLength(1); // One actual successful Runtime constructor.
const birth = births[0]; if (!birth) throw new Error("normal Runtime birth witness absent");
expect(runtime.get(endpoint.id)).toBe(birth.runtime);
const current = readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE));
expect(current?.senderResource).toMatchObject({ id: birth.resourceId, closed: false });
expect(new Set(clients.map(row => row.client)).size).toBe(clients.length);
expect(clients.filter(row => row.methods.length === 0)).toHaveLength(1); // Constructor bootstrap, drained by external handoff.
expect(clients.flatMap(row => row.methods)).toEqual([
{ method: "chats.get" }, { method: "messages.sendText" }, { method: "chats.setTyping", active: false },
]);
for (const client of clients) { expect(client.closeAttempts).toBe(1); expect(client.joined).toBe(true); }
},
joinCurrentSender: async () => {
const birth = births[0]; if (!birth) throw new Error("normal Runtime birth witness absent");
await runtime.removeEndpoint(endpoint.id); // Normal actual SDK+adapter join and captured close CAS.
expect(runtime.get(endpoint.id)).toBeNull(); expect(runtime.hasUnsettledLifecycle()).toBe(false);
const closed = readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE));
expect(closed?.senderResource).toMatchObject({ id: birth.resourceId, closed: true });
expect(closed?.handoffId).toBe(retained.handoffId); expect(closed?.acceptedSequence).toBe(retained.acceptedSequence);
for (const client of clients) expect(client.joined).toBe(true);
} };
}
expect(published?.redactedError, "ordinary publication must not retain a redacted failure").toBeNull();
expect(published?.state).toBe("published");
expect(control.client.messages.sendText).toHaveBeenCalledOnce();
@@ -286,6 +600,125 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
pendingRetirement() { retirement = "retiring"; }, finishRetirement() { retirement = "retired"; } };
}
it("normal publication cancellation before construction settles only its exact never-created sender and permits ordinary retry", async () => {
const c = await managedConfiguration(), control = photonFixture();
const retry = await c.reconstructExternal(control, true);
if (!retry) throw new Error("cancelled publication retry control absent");
expect(photonClients.createOwnedPhotonClient).not.toHaveBeenCalled();
const aborted = readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE));
expect(aborted?.senderResource?.closed, "cancelled normal replacement must settle the exact never-constructed sender allocation").toBe(true);
expect(aborted).toMatchObject({ phase: "external", handoffId: c.retained.handoffId, binding: c.retained.binding });
expect(aborted?.localClosureConfirmed).toBeUndefined(); // No invented receiver close.
const published = await retry.retryOriginalPublication();
expect(published?.state).toBe("published");
expect(control.client.messages.sendText).toHaveBeenCalledOnce();
await retry.verifyUsefulOwnership();
const current = readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE));
expect(current?.senderResource?.id).not.toBe(aborted?.senderResource?.id);
expect(current?.senderResource?.closed).toBe(false);
expect(current?.acceptedSequence).toBe(c.retained.acceptedSequence);
await retry.cancelledAbort(); // Lost original cleanup reply after a newer slot.
expect(readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE))).toEqual(current);
await retry.joinCurrentSender();
});
it("ordinary authorized publication retries a failed never-created sender receipt before any new reservation", async () => {
const failure = new Error("controlled never-created SQL receipt write failed");
let failReceipt = false;
const normalStore = photonStores.createPhotonExternalStore;
vi.spyOn(photonStores, "createPhotonExternalStore").mockImplementation(database => {
const store = normalStore(database), retained = store.retained.bind(store);
return { ...store, retained: async (...args: Parameters<typeof store.retained>) => {
const [expected] = args;
if (failReceipt && expected.senderResource?.closed === false) throw failure;
return retained(...args);
} };
});
const c = await managedConfiguration(), control = photonFixture();
failReceipt = true;
try {
const retry = await c.reconstructExternal(control, true);
if (!retry) throw new Error("ordinary publication retry control absent");
const pending = readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE));
expect(pending?.senderResource?.closed).toBe(false);
expect(c.runtime.hasUnsettledLifecycle()).toBe(true);
expect(photonClients.createOwnedPhotonClient).not.toHaveBeenCalled();
failReceipt = false; // Repair the controlled fault only at explicit ordinary Retry.
const published = await retry.retryOriginalPublication();
expect(published?.state, "ordinary publication must join the original failed abort receipt before its sender preflight").toBe("published");
expect(control.client.messages.sendText).toHaveBeenCalledOnce();
await retry.verifyUsefulOwnership();
expect(c.runtime.hasUnsettledLifecycle()).toBe(false);
const current = readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE));
expect(current?.senderResource?.id).not.toBe(pending?.senderResource?.id);
expect(current?.acceptedSequence).toBe(c.retained.acceptedSequence);
await retry.joinCurrentSender();
} finally { failReceipt = false; } // Normal service shutdown can join any retained exact receipt.
});
it("ordinary publication joins a lost reservation reply and failed direct never-created receipt before allocating again", async () => {
const lost = new Error("controlled sender reservation committed reply lost");
const cleanupFailure = new Error("controlled direct never-created receipt write failed");
let loseReply = false, failCleanup = false, observedLostReply = false, observedCleanupFailure = false;
const normalStore = photonStores.createPhotonExternalStore;
vi.spyOn(photonStores, "createPhotonExternalStore").mockImplementation(database => {
const store = normalStore(database), current = store.current.bind(store), retained = store.retained.bind(store);
return { ...store,
current: async <T,>(...args: Parameters<typeof store.current<T>>): Promise<T> => {
const result = await current<T>(...args);
const parsed = photonExternalStateSchema.safeParse(result);
if (loseReply && parsed.success && parsed.data.senderResource?.closed === false) {
loseReply = false; observedLostReply = true; throw lost;
}
return result;
},
retained: async (...args: Parameters<typeof store.retained>) => {
if (failCleanup && args[0].senderResource?.closed === false) {
failCleanup = false; observedCleanupFailure = true; throw cleanupFailure;
}
return retained(...args);
},
};
});
const c = await managedConfiguration(true), control = photonFixture();
expect(c.runtime).toBeInstanceOf(ChatRuntime);
loseReply = true; failCleanup = true;
const retry = await c.reconstructExternal(control, false, undefined, true);
if (!retry) throw new Error("ordinary reservation-failure retry control absent");
expect(c.runtime).toBeInstanceOf(ChatRuntime);
expect(observedLostReply).toBe(true); expect(observedCleanupFailure).toBe(true);
const pending = readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE));
expect(pending?.senderResource?.closed).toBe(false);
expect(c.runtime.hasUnsettledLifecycle()).toBe(true);
expect(photonClients.createOwnedPhotonClient).not.toHaveBeenCalled();
const published = await retry.retryOriginalPublication();
expect(published?.state).toBe("published");
expect(control.client.messages.sendText).toHaveBeenCalledOnce();
await retry.verifyUsefulOwnership();
expect(c.runtime.hasUnsettledLifecycle()).toBe(false);
const settled = readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE));
expect(settled?.senderResource?.id).not.toBe(pending?.senderResource?.id);
expect(settled?.acceptedSequence).toBe(c.retained.acceptedSequence);
await retry.joinCurrentSender();
});
it("an entered normal sender constructor cannot turn its unknown allocation into never-created cleanup on publication retry", async () => {
const c = await managedConfiguration(), control = photonFixture();
const retry = await c.reconstructExternal(control, false, new Error("controlled constructor entry failure"));
if (!retry) throw new Error("constructor failure retry control absent");
const pending = readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE));
expect(pending?.senderResource?.closed).toBe(false);
expect(photonClients.createOwnedPhotonClient).toHaveBeenCalledOnce();
const next = await retry.retryOriginalPublication();
expect(next?.state).not.toBe("published");
expect(control.client.messages.sendText).not.toHaveBeenCalled();
expect(photonClients.createOwnedPhotonClient).toHaveBeenCalledOnce();
const retained = readPhotonExternalState(await c.state.read(PHOTON_EXTERNAL_STATE));
expect(retained?.senderResource?.id).toBe(pending?.senderResource?.id);
expect(retained?.senderResource?.closed).toBe(false);
expect(retained?.failure).toMatchObject({ code: "sender_close", nextAttemptAt: null });
});
it("normal receiver worker settles a paused or archived Photon owner after exact retirement", async () => {
const c = await managedConfiguration();
await c.service.configure(c.endpoint.id, { action: "pause" }, f.userId);
@@ -363,6 +796,7 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
if (!current) throw new Error("retained sender owner absent");
await c.state.update(PHOTON_EXTERNAL_STATE, () => ({ ...current, failure: { code: "sender_close" as const, attempts: 3, nextAttemptAt: new Date().toISOString() } }));
const replacement = createPhotonExternalRuntimeOwner(db, {
retainConstructionCleanup: (id, cleanup) => c.runtime.retainPendingConstructionCleanup(id, cleanup),
broker: () => ({ instanceIdentity: () => ({ instanceId: "instance", environment: "test" as const }), photonReceiverOperation: async () => { throw new Error("unknown sender must not invoke provider"); } }),
endpointRecord: async id => {
const [endpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, id)); if (!endpoint) return null;
@@ -403,6 +837,7 @@ describe.skipIf(!external)("Photon normal configuration and retained receiver au
if (!endpointRow) throw new Error("current endpoint missing");
const leaseStopFailure = new Error("controlled finite lease stop reply lost before sender birth");
const neverBorn = createPhotonExternalRuntimeOwner(db, {
retainConstructionCleanup: (id, cleanup) => c.runtime.retainPendingConstructionCleanup(id, cleanup),
broker: () => broker,
withReceiverLease: async (_record, work) => { await work({ token }); throw leaseStopFailure; },
endpointRecord: async () => ({ endpoint: endpointRow, assignedAgentName: "Agent", connectionName: c.connection.name,
@@ -0,0 +1,66 @@
import { describe, expect, it, vi } from "vitest";
import { createChatSdkRuntime, type CreateChatSdkEndpointRuntimeOptions } from "../../services/chat-sdk-runtime.js";
import { createChatRuntime } from "../../services/chat-runtime.js";
import * as photonClients from "../../services/photon/owned-client.js";
import { memoryPersistence } from "./fixture.js";
const options = (onConstructionAborted: () => Promise<void>): CreateChatSdkEndpointRuntimeOptions & { onConstructionAborted(): Promise<void> } => ({
companyId: "company", endpointId: "endpoint", logger: "silent", persistence: memoryPersistence(), onConstructionAborted,
providerConfig: { provider: "imessage-photon", userName: "Agent", intakeAfter: 0,
credentials: { allocation: "dedicated", projectId: "project", projectSecret: "controlled-secret", lineId: "line", phoneNumber: "+15555550100" } },
callbacks: { onMessage: async () => {} },
});
describe.each([["SDK registry", createChatSdkRuntime], ["normal SDK and voice registry", createChatRuntime]] as const)("%s", (_label, createRegistry) => {
it("superseded normal registry replacement settles its exact never-constructed sender reservation", async () => {
// Actual registry queue and generation cancellation. This controlled reservation
// callback is not SQL, a process-exit claim or physical transport evidence.
const registry = createRegistry();
let reservationClosed = false;
const aborted = vi.fn(async () => { reservationClosed = true; });
const allocate = vi.spyOn(photonClients, "createOwnedPhotonClient");
try {
const replacement = registry.replaceEndpoint(options(aborted));
const rejected = replacement.then(() => null, error => error);
const removal = registry.removeEndpoint("endpoint");
expect(await rejected).toBeInstanceOf(Error);
await removal;
expect(allocate).not.toHaveBeenCalled();
expect(reservationClosed, "a superseded pre-constructor replacement must settle its owned never-created allocation").toBe(true);
expect(aborted).toHaveBeenCalledOnce();
expect(registry.hasUnsettledLifecycle()).toBe(false);
} finally { try { await registry.shutdown(); } finally { vi.restoreAllMocks(); } }
});
it("constructor entry retains uncertain sender responsibility instead of running never-created cleanup", async () => {
const registry = createRegistry(), failure = new Error("controlled constructor entered and failed");
const aborted = vi.fn(async () => {});
const allocate = vi.spyOn(photonClients, "createOwnedPhotonClient").mockImplementation(() => { throw failure; });
try {
await expect(registry.replaceEndpoint(options(aborted))).rejects.toBe(failure);
expect(allocate).toHaveBeenCalledOnce(); expect(aborted).not.toHaveBeenCalled();
} finally { try { await registry.shutdown(); } finally { vi.restoreAllMocks(); } }
});
it("failed never-created cleanup receipt stays in the normal registry until explicit retirement retry joins", async () => {
const registry = createRegistry(); await registry.shutdown();
const failure = new Error("controlled never-created receipt reply lost");
let allowReply = false, committed = false;
const aborted = vi.fn(async () => { committed = true; if (!allowReply) throw failure; });
const allocate = vi.spyOn(photonClients, "createOwnedPhotonClient");
try {
const error = await registry.replaceEndpoint(options(aborted)).then(() => null, error => error);
expect(error).toBeInstanceOf(AggregateError);
if (!(error instanceof AggregateError)) throw new Error("normal abort error absent");
expect(error.errors[0]).toBeInstanceOf(Error); expect(error.errors[1]).toBe(failure);
expect(committed).toBe(true); expect(aborted).toHaveBeenCalledOnce();
expect(registry.hasUnsettledLifecycle()).toBe(true); expect(allocate).not.toHaveBeenCalled();
allowReply = true;
await expect(registry.removeEndpoint("endpoint")).resolves.toBe(true);
expect(aborted).toHaveBeenCalledTimes(2); expect(registry.hasUnsettledLifecycle()).toBe(false);
expect(allocate).not.toHaveBeenCalled();
} finally { allowReply = true; try { await registry.shutdown(); } finally { vi.restoreAllMocks(); } }
});
});
+1 -1
View File
@@ -1371,7 +1371,7 @@ export function companyRoutes(db: Db, storage?: StorageService, options?: Compan
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
assertBoard(req);
const company = await svc.remove(companyId);
const company = await svc.remove(companyId, req.actor.type === "board" ? req.actor.userId : undefined);
if (!company) {
res.status(404).json({ error: "Company not found" });
return;
+8 -3
View File
@@ -919,6 +919,8 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
ownership: id => discordGatewayOwnerships.get(id), currentRuntime: id => runtime.get(id),
release: ownership => stopDiscordGatewayOwnership(ownership, { removeRuntime: false, notifyStopped: false }),
removeRuntime: async id => { runtimeVersions.delete(id); return runtime.removeEndpoint(id); },
joinConstructionCleanup: id => runtime.joinPendingConstructionCleanup(id),
retainConstructionCleanup: (id, cleanup) => runtime.retainPendingConstructionCleanup(id, cleanup),
config: async record => {
const config = runtimeConfig(record.endpoint, record.endpoint.botUsername ?? record.assignedAgentName, await resolveCredentials(record.endpoint));
if (config.provider !== "imessage-photon") throw new Error("Photon external provider changed");
@@ -1097,11 +1099,14 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
? await photonExternalRuntimeOwner.reserveLocalRuntime(record, context, discordOwnership, providerConfig) : null;
const photonSenderAllocation = providerConfig?.provider === "imessage-photon" && await photonExternalRuntimeOwner.placement(record)
? await photonExternalRuntimeOwner.reserveSenderRuntime(record, context, discordOwnership ?? undefined) : null;
const photonConstructionAllocation = photonSenderAllocation ?? photonAllocation;
instance = providerConfig === null
? await replaceSpekoChannelRuntime(runtime, record, persistence)
: await runtime.replaceEndpoint({
companyId: record.endpoint.companyId,
endpointId: record.endpoint.id,
onConstructionAborted: photonConstructionAllocation
? () => photonExternalRuntimeOwner.runtimeConstructionAborted(photonConstructionAllocation, context) : undefined,
providerConfig,
persistence,
concurrency: record.endpoint.concurrencyPolicy,
@@ -1172,7 +1177,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
: undefined,
},
});
if (photonAllocation) photonExternalRuntimeOwner.attachLocalRuntime(photonAllocation, instance);
if (photonAllocation) photonExternalRuntimeOwner.attachLocalRuntime(photonAllocation.resourceId, instance);
if (photonSenderAllocation) photonExternalRuntimeOwner.attachSenderRuntime(photonSenderAllocation.resourceId, instance);
context.endpointRuntime = instance;
runtimeContexts.set(instance as object, context);
@@ -3522,10 +3527,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
nativeBotIdentityMatches, assertNativeBotIdentityAvailable, isNativeBotIdentityUniqueViolation, nativeBotIdentityConflict,
legacyGitHubLabelsMatchVerifiedCredentials, normalizedCredentials, verifyCredentials,
persistCredentials, clearCredentials, resolveCredentials, prepareProviderInventory,
prepareCredentialRemoval: async endpointId => {
prepareCredentialRemoval: async (endpointId, authority) => {
const record = await endpointRecord(endpointId);
if (record?.endpoint.provider !== "imessage-photon") return "unhandled";
await photonExternalRuntimeOwner.retire(endpointId);
await photonExternalRuntimeOwner.retire(endpointId, authority);
// Also joins local-only/retired-registry resources and their short lease.
await invalidateRuntime(endpointId);
return "settled";
@@ -81,7 +81,7 @@ type ChatConfigurationOptions = Pick<ReturnType<typeof createChatCredentials>, "
getWebhookPublicBaseUrl: () => string | null;
invalidateRuntime: (endpointId: string) => Promise<boolean>;
/** Provider-owned durable/resource settlement before destroying credentials. */
prepareCredentialRemoval?: (endpointId: string) => Promise<"settled" | "unhandled">;
prepareCredentialRemoval?: (endpointId: string, authority: { responsibleUserId?: string | null; reauthorize(): Promise<void> }) => Promise<"settled" | "unhandled">;
reconcileProviderResourceRows: ReturnType<typeof createChatResourceReconciliation>["reconcileProviderResourceRows"];
reconcileDiscordCommands: ReturnType<typeof createDiscordCommands>["reconcileDiscordCommands"];
runtimeFor: (endpoint: EndpointRow, input?: { requireDiscordOwnership?: boolean; waitForDiscordOwnership?: boolean }) => Promise<ChatEndpointRuntime>;
@@ -461,7 +461,10 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
if (input.action === "remove") {
const settleRemovalRuntime = async (invalidateUnhandled = true) => {
await credentialLease.assertOwned();
const result = await options.prepareCredentialRemoval?.(endpoint.id);
const result = await options.prepareCredentialRemoval?.(endpoint.id, {
responsibleUserId: managementContext?.responsibleUserId ?? actorUserId,
reauthorize: async () => { await managementContext?.reauthorize(); await credentialLease.assertOwned(); },
});
await credentialLease.assertOwned();
if (result !== "settled" && invalidateUnhandled) await invalidateRuntime(endpoint.id).catch(() => undefined);
};
@@ -53,7 +53,7 @@ async function assertEndpointRetired(tx: Transaction, endpoint: typeof chatEndpo
}
/** Before agent termination or destructive SQL: keep consumer and credentials alive on 409. */
export async function preparePhotonCompanyDeletion(db: Db, companyId: string) {
export async function preparePhotonCompanyDeletion(db: Db, companyId: string, actorUserId?: string | null) {
let cursor: string | undefined;
while (true) {
const endpoints = await db.select({ id: chatEndpoints.id }).from(chatEndpoints).where(and(
@@ -62,7 +62,7 @@ export async function preparePhotonCompanyDeletion(db: Db, companyId: string) {
if (!endpoints.length) return;
const owner = owners.get(db);
if (!owner) throw pending();
for (const endpoint of endpoints) await owner.remove(endpoint.id, async () => undefined);
for (const endpoint of endpoints) await owner.remove(endpoint.id, async () => undefined, actorUserId);
cursor = endpoints[endpoints.length - 1]!.id;
}
}
@@ -42,6 +42,7 @@ export const photonExternalStateSchema = z.object({
phase: z.enum(["enrolling", "joining", "external", "retiring", "retired"]),
// The complete non-secret enrollment input survives an ambiguous broker reply.
binding: photonExternalBindingSchema,
enrollmentCancellation: z.enum(["requested", "fenced"]).optional(),
acceptedRetirement: z.object({ binding: photonExternalBindingSchema, handoffId: z.string().uuid() }).strict().nullable(),
initialSequence: sequence.nullable(),
joinedSequence: sequence.nullable(), acceptedSequence: sequence.nullable(),
@@ -53,6 +54,8 @@ export function readPhotonExternalState(value: unknown): PhotonExternalState | n
if (value === null) return null;
const state = photonExternalStateSchema.parse(value);
assertPhotonExternalBinding(state.identity, state.binding);
if (state.enrollmentCancellation && !["retiring", "retired"].includes(state.phase)
|| state.enrollmentCancellation === "fenced" && state.phase !== "retired") throw new Error("Photon enrollment cancellation phase changed");
if (state.localResource?.closed === true && state.localClosureConfirmed !== true
|| state.localClosureConfirmed === true && state.localResource && state.localResource.closed !== true)
throw new Error("Photon physical close receipt and original descriptor disagree");
@@ -44,6 +44,7 @@ export async function handoffCheckpoint(state: PhotonState, identity: PhotonExte
}
export interface PhotonExternalBroker {
instanceIdentity(): { instanceId: string; environment: PhotonExternalBinding["environment"] };
photonReceiverAvailable?(): Promise<boolean>;
photonReceiverOperation(input: { subject: string; companyId: string; operation: Record<string, unknown> }): Promise<unknown>;
}
/** Resource IDs identify a retained object; ONLY awaiting its real close confirms
@@ -255,16 +256,32 @@ export function createPhotonExternalOwner(options: { store: PhotonExternalStore;
});
// Caller can now use ONLY the ordinary authenticated delivery ACK.
}
async function retire(retained: PhotonExternalState): Promise<void> {
async function retire(retained: PhotonExternalState, cleanup?: { responsibleUserId?: string | null; reauthorize(): Promise<void> }): Promise<void> {
if (retained.phase === "retired") return;
if (retained.phase !== "retiring") retained = await options.store.retained(retained, value => ({ ...value, phase: "retiring", failure: value.failure?.code === "sender_close" ? value.failure : null }));
if (retained.phase !== "retiring") retained = await options.store.retained(retained, value => ({ ...value, phase: "retiring", ...(value.phase === "enrolling" ? { enrollmentCancellation: "requested" as const } : {}), failure: value.failure?.code === "sender_close" ? value.failure : null }));
try {
const sender = await repairSender(retained); retained = sender.state;
if (!sender.closed) throw new PhotonSenderResourceUnknown("Photon original sender process or resource closure remains unknown");
const physical = await repair(retained); retained = physical.state;
if (!physical.closed) throw new PhotonPhysicalResourceUnknown("Photon original local resource closure is unknown; physical retirement remains held");
const request = { subject: retained.identity.subject, companyId: retained.identity.companyId };
await requireBroker().photonReceiverOperation({ ...request, operation: { kind: "retire", binding: retained.binding } });
if (retained.enrollmentCancellation === "requested") {
await cleanup?.reauthorize();
const cancellation = z.object({ binding: photonExternalBindingSchema, handoffId: z.string().uuid(),
phase: z.enum(["cancelled", "staged", "active", "retiring", "retired"]) }).strict().parse(
await requireBroker().photonReceiverOperation({ companyId: retained.identity.companyId,
subject: cleanup?.responsibleUserId ?? retained.identity.subject,
operation: { kind: "cancel-enrollment", binding: retained.binding, handoffId: retained.handoffId, originalSubject: retained.identity.subject } }));
if (!isDeepStrictEqual(cancellation.binding, retained.binding) || cancellation.handoffId !== retained.handoffId)
throw new Error("Photon enrollment cancellation tuple changed");
if (cancellation.phase === "cancelled" || cancellation.phase === "retired") {
await cleanup?.reauthorize();
await options.store.retained(retained, value => ({ ...value, phase: "retired",
...(cancellation.phase === "cancelled" ? { enrollmentCancellation: "fenced" as const } : {}), failure: null }));
options.notify(retained.identity); return;
}
throw new Error("Photon original physical close or queue drain remains outstanding");
} else await requireBroker().photonReceiverOperation({ ...request, operation: { kind: "retire", binding: retained.binding } });
const response = z.object({ binding: photonExternalBindingSchema, handoffId: z.string().uuid(),
phase: z.enum(["staged", "active", "retiring", "retired"]) }).strict().parse(await requireBroker().photonReceiverOperation({ ...request, operation: { kind: "status", binding: retained.binding } }));
if (!isDeepStrictEqual(response.binding, retained.binding) || response.handoffId !== retained.handoffId) throw new Error("Photon retirement tuple changed");
@@ -13,12 +13,13 @@ import type { EndpointRecord, RuntimeContext, DiscordGatewayOwnership, InternalS
import { credentialFingerprint } from "../credential-fingerprint.js";
import { createPhotonExternalStore, PHOTON_EXTERNAL_STATE } from "./external-store.js";
import { createPhotonExternalOwner, PhotonLocalResources, type PhotonExternalBroker } from "./external-owner.js";
import { readPhotonExternalState, parsePhotonExternalDelivery, photonHash, type PhotonExternalIdentity } from "./external-contract.js";
import { readPhotonExternalState, parsePhotonExternalDelivery, photonHash, type PhotonExternalIdentity, type PhotonResourceDescriptor } from "./external-contract.js";
import { currentControllerProcess, UNKNOWN_PROCESS_SPACE } from "../../controller-process-identity.js";
import { randomUUID, createHash } from "node:crypto";
export type PhotonCloudDelivery = { id: string; event: string; createdAt: string; installationId: string | null; bindingIds: readonly string[]; payload: Record<string, unknown> };
export type PhotonSenderAllocation = { readonly resourceId: string; readonly handoffId: string; readonly identity: Readonly<PhotonExternalIdentity> };
export type PhotonRuntimeAllocation = { readonly kind: "receiver" | "sender"; readonly resourceId: string; readonly handoffId: string; readonly identity: Readonly<PhotonExternalIdentity>; readonly descriptor: Readonly<PhotonResourceDescriptor>; readonly context: RuntimeContext };
export type PhotonSenderAllocation = PhotonRuntimeAllocation & { readonly kind: "sender" };
type Ingress = (event: PhotonCloudDelivery) => Promise<void>;
const ingress = new WeakMap<Db, Ingress>();
export async function dispatchPhotonCloudEvent(db: Db, event: PhotonCloudDelivery) {
@@ -71,6 +72,8 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
release(ownership: DiscordGatewayOwnership): Promise<void>;
currentRuntime(id: string): ChatEndpointRuntime | null;
removeRuntime(id: string): Promise<boolean>;
joinConstructionCleanup?(id: string): Promise<void>;
retainConstructionCleanup(id: string, cleanup: () => Promise<void>): void;
config(record: EndpointRecord): Promise<ResolvedPhotonChatConfig>;
admit(id: string, event: LiveEvent, context: RuntimeContext): Promise<void>;
notify(id: string): void;
@@ -92,7 +95,8 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
if (record.endpoint.provider !== "imessage-photon") return null;
return selected(record);
}
async function reserveLocalRuntime(record: EndpointRecord, context: RuntimeContext, lease: { token: string }, config: ResolvedPhotonChatConfig): Promise<string | null> {
async function reserveLocalRuntime(record: EndpointRecord, context: RuntimeContext, lease: { token: string }, config: ResolvedPhotonChatConfig): Promise<PhotonRuntimeAllocation | null> {
await options.joinConstructionCleanup?.(record.endpoint.id);
const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject, broker = options.broker();
if (!subject || !broker || record.endpoint.provider !== "imessage-photon") return null;
const identity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: record.endpoint.id,
@@ -106,16 +110,35 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
options.notify(record.endpoint.id);
throw conflict("Photon original handoff must recover before a replacement receiver allocation");
}
if (!broker.photonReceiverAvailable) throw new Error("Photon Cloud receiver capability is unknown");
if (!await broker.photonReceiverAvailable()) return null;
const controller = await currentControllerProcess();
if (controller.hostHash === UNKNOWN_PROCESS_SPACE || !controller.processStartedAt)
throw conflict("Photon local allocation requires its actual process birth and namespace");
const id = randomUUID();
const descriptor = { id, controller, leaseDigest: photonHash(lease.token), closed: false };
// Durable descriptor precedes construction/initialize, not an after-crash backfill.
await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).prepare({
identity, lease, config, localResourceId: id, localResource: { id, controller, leaseDigest: photonHash(lease.token), closed: false } });
return id;
try {
const reserved = await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).prepare({
identity, lease, config, localResourceId: id, localResource: descriptor });
return { kind: "receiver", resourceId: id, handoffId: reserved.handoffId, identity: { ...reserved.identity }, descriptor, context };
} catch (primary) {
// No caller can enter the constructor before this reservation returns.
const settleNeverCreated = async () => {
const current = await store.read(identity);
if (current?.localResourceId === id && isDeepStrictEqual(current.localResource, descriptor))
await runtimeConstructionAborted({ kind: "receiver", resourceId: id, handoffId: current.handoffId, identity, descriptor, context }, context);
};
try { await settleNeverCreated(); }
catch (cleanup) {
options.retainConstructionCleanup(record.endpoint.id, settleNeverCreated);
throw new AggregateError([primary, cleanup], "Photon receiver reservation and never-created cleanup failed");
}
throw primary;
}
}
async function reserveSenderRuntime(record: EndpointRecord, context: RuntimeContext, lease?: { token: string }): Promise<PhotonSenderAllocation> {
await options.joinConstructionCleanup?.(record.endpoint.id);
const retained = await selected(record), broker = options.broker();
if (!retained || !broker) throw new Error("Photon sender has no current external placement");
if (context.generation !== retained.identity.runtimeGeneration || context.credentialFingerprint !== retained.identity.credentialReferences)
@@ -124,12 +147,13 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
if (controller.hostHash === UNKNOWN_PROCESS_SPACE || !controller.processStartedAt)
throw conflict("Photon sender allocation requires actual process birth and namespace");
const owner = createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) });
const allocation: { intended: { id: string; leaseDigest: string } | null } = { intended: null };
const allocation: { intended: PhotonResourceDescriptor | null } = { intended: null };
const reserve = async (owned: { token: string }) => {
const id = randomUUID();
allocation.intended = { id, leaseDigest: photonHash(owned.token) };
const reserved = await owner.reserveSender(retained.identity, owned, { id, controller, leaseDigest: allocation.intended.leaseDigest, closed: false });
return { resourceId: id, handoffId: reserved.handoffId, identity: { ...reserved.identity } };
const descriptor = { id, controller, leaseDigest: photonHash(owned.token), closed: false };
allocation.intended = descriptor;
const reserved = await owner.reserveSender(retained.identity, owned, descriptor);
return { kind: "sender" as const, resourceId: id, handoffId: reserved.handoffId, identity: { ...reserved.identity }, descriptor, context };
};
try { return await (lease ? reserve(lease) : options.withReceiverLease(record, reserve)); }
catch (primary) {
@@ -137,18 +161,55 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
// object can have been constructed. Join a failed finite-lease cleanup
// without orphaning that exact never-born allocation intent.
const intended = allocation.intended;
if (intended) try {
// Even a lost reservation-commit reply can be matched to the nonce and
// birth this exact caller generated BEFORE that write. Never backfill.
const neverBorn = await store.read(retained.identity);
if (neverBorn?.senderResource?.id === intended.id
&& neverBorn.senderResource.leaseDigest === intended.leaseDigest
&& isDeepStrictEqual(neverBorn.senderResource.controller, controller))
await owner.confirmSenderClosed(neverBorn, intended.id);
} catch (cleanup) { throw new AggregateError([primary, cleanup], "Photon sender reservation and never-born cleanup failed"); }
if (intended) {
const settleNeverCreated = async () => {
// This caller generated the nonce/birth BEFORE reservation, and has
// not returned to any constructor. Revalidate the full slot in SQL.
const neverBorn = await store.read(retained.identity);
if (neverBorn?.handoffId === retained.handoffId && isDeepStrictEqual(neverBorn.senderResource, intended))
await runtimeConstructionAborted({ kind: "sender", resourceId: intended.id, handoffId: retained.handoffId,
identity: { ...retained.identity }, descriptor: intended, context }, context);
};
try { await settleNeverCreated(); }
catch (cleanup) {
options.retainConstructionCleanup(record.endpoint.id, settleNeverCreated);
throw new AggregateError([primary, cleanup], "Photon sender reservation and never-born cleanup failed");
}
}
throw primary;
}
}
async function runtimeConstructionAborted(allocation: PhotonRuntimeAllocation, context: RuntimeContext): Promise<void> {
// ONLY the normal registry pre-constructor boundary or this exact reservation
// function can invoke this capability. Absence is never the evidence.
if (allocation.context !== context || context.endpointRuntime || resources.known(allocation.resourceId)
|| context.generation !== allocation.identity.runtimeGeneration
|| context.credentialFingerprint !== allocation.identity.credentialReferences)
throw new Error("Photon never-created allocation authority changed");
const current = await store.read(allocation.identity);
if (!current || current.handoffId !== allocation.handoffId || !isDeepStrictEqual(current.identity, allocation.identity)) return;
const descriptor = allocation.kind === "sender" ? current.senderResource : current.localResource;
if (!descriptor || descriptor.id !== allocation.resourceId) return;
if (!isDeepStrictEqual({ ...descriptor, closed: false }, allocation.descriptor))
throw new Error("Photon never-created allocation descriptor changed");
await store.retained(current, value => {
// Revalidate INSIDE the locked update, even if a store implementation
// supplies a newer value than the preliminary read.
const latest = allocation.kind === "sender" ? value.senderResource : value.localResource;
if (value.handoffId !== allocation.handoffId || !isDeepStrictEqual(value.identity, allocation.identity)
|| !latest || latest.id !== allocation.resourceId
|| allocation.kind === "receiver" && value.localResourceId !== allocation.resourceId
|| !isDeepStrictEqual({ ...latest, closed: false }, allocation.descriptor))
throw new Error(`Photon never-created ${allocation.kind} changed during close commit`);
if (allocation.kind === "sender") return { ...value, senderResource: { ...latest, closed: true },
failure: value.failure?.code === "sender_close" ? null : value.failure };
// Preserve enrollment/business/accepted checkpoint/failure responsibility.
const next = { ...value, localResource: { ...latest, closed: true }, localClosureConfirmed: true as const };
delete next.localResourceDebt;
return next;
});
}
function attachSenderRuntime(id: string, runtime: ChatEndpointRuntime): void {
resources.attach(id, runtime, () => runtime.shutdown());
}
@@ -189,6 +250,7 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
const run = (async () => {
const record = await options.endpointRecord(id);
if (!record || record.endpoint.provider !== "imessage-photon") return;
await options.joinConstructionCleanup?.(id);
const previous = await store.read({ companyId: record.endpoint.companyId, endpointId: id });
const broker = options.broker(), subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject;
const identity: PhotonExternalIdentity | null = subject ? { companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId,
@@ -204,6 +266,10 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
if (previous && previous.phase !== "retired") throw new Error("Photon retained Cloud receiver port is unavailable");
return;
}
if (!previous || previous.phase === "retired") {
if (!broker.photonReceiverAvailable) throw new Error("Photon Cloud receiver capability is unknown");
if (!await broker.photonReceiverAvailable()) return;
}
const optionsConfig = await options.config(record);
const originalRuntime = options.currentRuntime(id);
const originalResourceCurrent = previous?.localResourceId && originalRuntime
@@ -306,13 +372,15 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
await store.retained(external, value => ({ ...value, failure: { code: "sender_close", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } }));
options.notify(id);
}
async function retire(id: string) {
async function retire(id: string, cleanup?: { responsibleUserId?: string | null; reauthorize(): Promise<void> }) {
const record = await options.endpointRecord(id), broker = options.broker();
if (!record || record.endpoint.provider !== "imessage-photon") return;
await cleanup?.reauthorize();
await options.joinConstructionCleanup?.(id);
let retained = await store.read({ companyId: record.endpoint.companyId, endpointId: id });
if (!retained || retained.phase === "retired") return;
if (retained.phase !== "retiring") retained = await store.retained(retained, value => ({ ...value,
phase: "retiring", failure: value.failure?.code === "sender_close" ? value.failure : null }));
phase: "retiring", ...(value.phase === "enrolling" ? { enrollmentCancellation: "requested" as const } : {}), failure: value.failure?.code === "sender_close" ? value.failure : null }));
// Join the normal registry's current OR retained failed runtime first. A
// missing runtime is never proof of a separately recorded sender close.
const removed = await options.removeRuntime(id);
@@ -330,7 +398,7 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
}
if (retained.failure?.code === "sender_close") retained = await store.retained(retained, value => ({ ...value, failure: null }));
}
await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).retire(retained);
await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).retire(retained, cleanup);
}
async function retained(scope?: { kind: "endpoint" | "connection" | "company"; id: string }) {
const values = [];
@@ -383,11 +451,18 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
if (!subject || !broker || !management.responsibleUserId || !management.decision.allowed || management.decision.action !== "connections:configure"
|| management.resource.companyId !== record.endpoint.companyId || management.resource.connectionId && management.resource.connectionId !== record.endpoint.connectionId)
throw forbidden("Current company connection authority is required");
await options.joinConstructionCleanup?.(endpointId);
const state = await store.read({ companyId: record.endpoint.companyId, endpointId });
const connector = broker.instanceIdentity();
if (!state || state.handoffId !== actionId || state.binding.instanceId !== connector.instanceId || state.binding.environment !== connector.environment)
throw conflict("Photon retained retry identity changed");
if (state.phase === "retired") return { actionId, state: "complete" as const };
if (state.phase === "retiring" && state.enrollmentCancellation === "requested") {
await retire(endpointId, { responsibleUserId: management.responsibleUserId, reauthorize: () => management.reauthorize() });
const settled = await store.read(state.identity);
if (settled?.handoffId !== state.handoffId || !isDeepStrictEqual(settled.binding, state.binding)) throw conflict("Photon retry owner changed");
if (settled.phase === "retired") return { actionId, state: "complete" as const };
}
// Retry is real current-authorized business recovery/physical repair. An
// unknown old UUID remains debt; it is never certified closed by this action.
if (state.phase === "external" || state.phase === "retiring")
@@ -407,7 +482,7 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
return { actionId, state: "scheduled" as const };
}
ingress.set(db, receive);
return { reserveLocalRuntime, attachLocalRuntime, reserveSenderRuntime, attachSenderRuntime, senderRuntimeClosed, reconcile, placement, senderDebt, retire, retained, cleanupFailure, retry, close() { if (ingress.get(db) === receive) ingress.delete(db); return Promise.all([...active.values()]).then(() => undefined); } };
return { reserveLocalRuntime, attachLocalRuntime, reserveSenderRuntime, attachSenderRuntime, senderRuntimeClosed, runtimeConstructionAborted, reconcile, placement, senderDebt, retire, retained, cleanupFailure, retry, close() { if (ingress.get(db) === receive) ingress.delete(db); return Promise.all([...active.values()]).then(() => undefined); } };
}
/** Called by normal configuration SQL with its actual authorized actor. Existing
+43 -19
View File
@@ -1,5 +1,5 @@
import type { WebhookOptions } from "chat";
import { createChatSdkEndpointRuntime, ChatSdkEndpointNotRegisteredError, type CreateChatSdkEndpointRuntimeOptions } from "./chat-sdk-runtime.js";
import { createChatSdkEndpointRuntime, ChatSdkEndpointNotRegisteredError, ChatRuntimeConstructionCleanup, type CreateChatSdkEndpointRuntimeOptions } from "./chat-sdk-runtime.js";
import { createVoiceRuntime, type ChatEndpointRuntime, type CreateVoiceRuntimeOptions } from "./voice/voice-runtime.js";
/** One lifecycle registry for the Chat SDK and hosted voice transports. */
@@ -10,6 +10,7 @@ export class ChatRuntime {
ChatEndpointRuntime
>();
private readonly lifecycleTails = new Map<string, Promise<void>>();
private readonly constructionCleanup = new ChatRuntimeConstructionCleanup();
private readonly replacementGenerations = new Map<string, number>();
private shuttingDown = false;
@@ -25,7 +26,7 @@ export class ChatRuntime {
/** Retirement failures retain their owner even after get/list hide it. */
hasUnsettledLifecycle(): boolean {
return this.retiringEndpoints.size > 0 || this.lifecycleTails.size > 0;
return this.retiringEndpoints.size > 0 || this.constructionCleanup.has() || this.lifecycleTails.size > 0;
}
private enqueueLifecycle<T>(
@@ -50,15 +51,28 @@ export class ChatRuntime {
return result;
}
retainPendingConstructionCleanup(endpointId: string, cleanup: () => Promise<void>): void {
this.constructionCleanup.retain(endpointId, cleanup);
}
async joinPendingConstructionCleanup(endpointId: string): Promise<void> {
await this.enqueueLifecycle(endpointId, () => this.constructionCleanup.join(endpointId));
}
private async retireEndpoint(endpointId: string): Promise<boolean> {
const previous =
this.endpoints.get(endpointId) ?? this.retiringEndpoints.get(endpointId);
if (!previous) return false;
this.endpoints.delete(endpointId);
this.retiringEndpoints.set(endpointId, previous);
await previous.shutdown();
this.retiringEndpoints.delete(endpointId);
return true;
const previous = this.endpoints.get(endpointId) ?? this.retiringEndpoints.get(endpointId);
const hadAbort = this.constructionCleanup.has(endpointId), errors: unknown[] = [];
if (previous) {
this.endpoints.delete(endpointId);
this.retiringEndpoints.set(endpointId, previous);
try { await previous.shutdown(); this.retiringEndpoints.delete(endpointId); }
catch (error) { errors.push(error); }
}
try { await this.constructionCleanup.join(endpointId); }
catch (error) { errors.push(error); }
if (errors.length === 1) throw errors[0];
if (errors.length) throw new AggregateError(errors, "Chat runtime retirement remains incomplete");
return Boolean(previous) || hadAbort;
}
private nextReplacementGeneration(endpointId: string): number {
@@ -82,17 +96,26 @@ export class ChatRuntime {
async replaceEndpoint(
options: CreateChatSdkEndpointRuntimeOptions,
): Promise<ChatEndpointRuntime> {
if (this.shuttingDown) throw new Error("Chat SDK runtime is shutting down");
const abort = (primary: unknown): Promise<never> => this.constructionCleanup.abort(options.endpointId, options.onConstructionAborted, primary);
if (this.shuttingDown) {
return await this.enqueueLifecycle(options.endpointId, () => abort(new Error("Chat SDK runtime is shutting down")));
}
const generation = this.nextReplacementGeneration(options.endpointId);
return await this.enqueueLifecycle(options.endpointId, async () => {
this.assertReplacementCurrent(options.endpointId, generation);
await this.retireEndpoint(options.endpointId);
this.assertReplacementCurrent(options.endpointId, generation);
const next = createChatSdkEndpointRuntime(options);
this.endpoints.set(options.endpointId, next);
// The service installs callback context before initialize() starts the
// Discord gateway. Preserve that caller-owned initialization boundary.
return next;
let constructionStarted = false;
try {
this.assertReplacementCurrent(options.endpointId, generation);
await this.retireEndpoint(options.endpointId);
this.assertReplacementCurrent(options.endpointId, generation);
constructionStarted = true;
const next = createChatSdkEndpointRuntime(options);
this.endpoints.set(options.endpointId, next);
// Caller installs context before initialize starts any provider intake.
return next;
} catch (error) {
if (!constructionStarted) return await abort(error);
throw error; // Constructor entry is not never-created evidence.
}
});
}
@@ -133,6 +156,7 @@ export class ChatRuntime {
const endpointIds = new Set([
...this.endpoints.keys(),
...this.retiringEndpoints.keys(),
...this.constructionCleanup.endpointIds(),
...this.lifecycleTails.keys(),
]);
const results = await Promise.allSettled(
+92 -18
View File
@@ -528,6 +528,8 @@ export interface ChatSdkRuntimeCallbacks {
export interface CreateChatSdkEndpointRuntimeOptions {
callbacks: ChatSdkRuntimeCallbacks;
/** Invoked only if registry replacement fails before constructor entry. */
onConstructionAborted?(): Promise<void>;
companyId: string;
concurrency?: ConcurrencyConfig | ConcurrencyStrategy;
/** Start Discord's long-lived Gateway listener for the elected owner only. */
@@ -3208,6 +3210,51 @@ export class ChatSdkEndpointNotRegisteredError extends Error {
}
/** Process-local lifecycle registry; durable state remains in Paperclip persistence. */
/** Pending receipt ownership only; each registry keeps its existing lifecycle queue. */
export class ChatRuntimeConstructionCleanup {
private readonly pending = new Map<string, Set<() => Promise<void>>>();
has(endpointId?: string): boolean {
return endpointId === undefined ? this.pending.size > 0 : this.pending.has(endpointId);
}
endpointIds(): Iterable<string> { return this.pending.keys(); }
retain(endpointId: string, cleanup: () => Promise<void>): void {
const owners = this.pending.get(endpointId) ?? new Set<() => Promise<void>>();
owners.add(cleanup);
this.pending.set(endpointId, owners);
}
private completed(endpointId: string, cleanup: () => Promise<void>): void {
const owners = this.pending.get(endpointId);
if (!owners) return;
owners.delete(cleanup);
if (!owners.size && this.pending.get(endpointId) === owners) this.pending.delete(endpointId);
}
async join(endpointId: string): Promise<void> {
const owners = this.pending.get(endpointId);
if (!owners) return;
const errors: unknown[] = [];
for (const cleanup of [...owners]) {
try { await cleanup(); this.completed(endpointId, cleanup); }
catch (error) { errors.push(error); }
}
if (errors.length === 1) throw errors[0];
if (errors.length) throw new AggregateError(errors, "Chat never-created resource cleanup remains owned");
}
async abort(endpointId: string, cleanup: (() => Promise<void>) | undefined, primary: unknown): Promise<never> {
if (cleanup) {
this.retain(endpointId, cleanup);
try { await cleanup(); this.completed(endpointId, cleanup); }
catch (error) { throw new AggregateError([primary, error], "Chat runtime construction abort cleanup failed"); }
}
throw primary;
}
}
export class ChatSdkRuntime {
private readonly endpoints = new Map<string, ChatSdkEndpointRuntime>();
private readonly retiringEndpoints = new Map<
@@ -3215,6 +3262,7 @@ export class ChatSdkRuntime {
ChatSdkEndpointRuntime
>();
private readonly lifecycleTails = new Map<string, Promise<void>>();
private readonly constructionCleanup = new ChatRuntimeConstructionCleanup();
private readonly replacementGenerations = new Map<string, number>();
private shuttingDown = false;
@@ -3230,7 +3278,7 @@ export class ChatSdkRuntime {
/** Retirement failures retain their owner even after get/list hide it. */
hasUnsettledLifecycle(): boolean {
return this.retiringEndpoints.size > 0 || this.lifecycleTails.size > 0;
return this.retiringEndpoints.size > 0 || this.constructionCleanup.has() || this.lifecycleTails.size > 0;
}
private enqueueLifecycle<T>(
@@ -3255,15 +3303,32 @@ export class ChatSdkRuntime {
return result;
}
/** Transfer a captured never-created cleanup responsibility before returning its failure. */
retainPendingConstructionCleanup(endpointId: string, cleanup: () => Promise<void>): void {
this.constructionCleanup.retain(endpointId, cleanup);
}
/** Join only never-created cleanup; preserve active Runtime/consumer ownership. */
async joinPendingConstructionCleanup(endpointId: string): Promise<void> {
await this.enqueueLifecycle(endpointId, () => this.constructionCleanup.join(endpointId));
}
private async retireEndpoint(endpointId: string): Promise<boolean> {
const previous =
this.endpoints.get(endpointId) ?? this.retiringEndpoints.get(endpointId);
if (!previous) return false;
this.endpoints.delete(endpointId);
this.retiringEndpoints.set(endpointId, previous);
await previous.shutdown();
this.retiringEndpoints.delete(endpointId);
return true;
const previous = this.endpoints.get(endpointId) ?? this.retiringEndpoints.get(endpointId);
const hadAbort = this.constructionCleanup.has(endpointId), errors: unknown[] = [];
if (previous) {
this.endpoints.delete(endpointId);
this.retiringEndpoints.set(endpointId, previous);
try { await previous.shutdown(); this.retiringEndpoints.delete(endpointId); }
catch (error) { errors.push(error); }
}
// Independent never-created receipt settlement must still be attempted when
// a predecessor's real shutdown fails. Both owners remain retryable.
try { await this.constructionCleanup.join(endpointId); }
catch (error) { errors.push(error); }
if (errors.length === 1) throw errors[0];
if (errors.length) throw new AggregateError(errors, "Chat runtime retirement and construction cleanup failed");
return Boolean(previous || hadAbort);
}
private nextReplacementGeneration(endpointId: string): number {
@@ -3287,17 +3352,25 @@ export class ChatSdkRuntime {
async replaceEndpoint(
options: CreateChatSdkEndpointRuntimeOptions,
): Promise<ChatSdkEndpointRuntime> {
if (this.shuttingDown) throw new Error("Chat SDK runtime is shutting down");
const abort = (primary: unknown): Promise<never> => this.constructionCleanup.abort(options.endpointId, options.onConstructionAborted, primary);
if (this.shuttingDown) {
return await this.enqueueLifecycle(options.endpointId, () => abort(new Error("Chat SDK runtime is shutting down")));
}
const generation = this.nextReplacementGeneration(options.endpointId);
return await this.enqueueLifecycle(options.endpointId, async () => {
this.assertReplacementCurrent(options.endpointId, generation);
await this.retireEndpoint(options.endpointId);
this.assertReplacementCurrent(options.endpointId, generation);
const next = createChatSdkEndpointRuntime(options);
this.endpoints.set(options.endpointId, next);
// The service installs callback context before initialize() starts the
// Discord gateway. Preserve that caller-owned initialization boundary.
return next;
let constructionStarted = false;
try {
this.assertReplacementCurrent(options.endpointId, generation);
await this.retireEndpoint(options.endpointId);
this.assertReplacementCurrent(options.endpointId, generation);
constructionStarted = true;
const next = createChatSdkEndpointRuntime(options);
this.endpoints.set(options.endpointId, next);
return next;
} catch (primary) {
if (!constructionStarted) return await abort(primary);
throw primary;
}
});
}
@@ -3325,6 +3398,7 @@ export class ChatSdkRuntime {
const endpointIds = new Set([
...this.endpoints.keys(),
...this.retiringEndpoints.keys(),
...this.constructionCleanup.endpointIds(),
...this.lifecycleTails.keys(),
]);
const results = await Promise.allSettled(
+1 -1
View File
@@ -550,7 +550,7 @@ export function companyService(db: Db, _budgetHooks: BudgetServiceHooks = {}) {
return result.company;
},
remove: (id: string) => deleteCompany(db, id),
remove: (id: string, actorUserId?: string | null) => deleteCompany(db, id, actorUserId),
stats: () =>
Promise.all([
+2 -2
View File
@@ -63,8 +63,8 @@ import {
routines,
} from "@paperclipai/db";
export async function deleteCompany(db: Db, id: string) {
await preparePhotonCompanyDeletion(db, id);
export async function deleteCompany(db: Db, id: string, actorUserId?: string | null) {
await preparePhotonCompanyDeletion(db, id, actorUserId);
const lifecycle = createAgentLifecycle(db);
const companyAgents = await db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, id));
for (const agent of companyAgents) {
@@ -917,3 +917,40 @@ describe("Slack form normal connector terminal reply contracts", () => {
await expect(call({})).rejects.toBeInstanceOf(PaperclipCloudConnectorError);
});
});
describe("Photon authenticated receiver capability (controlled HTTP responses)", () => {
it("distinguishes a valid legacy absence from supported version one using the normal signed status request", async () => {
const keys = config();
for (const supported of [false, true]) {
const request = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
const body = JSON.parse(String(init?.body)) as { request: string };
const claims = JSON.parse(Buffer.from(body.request.split(".")[1]!, "base64url").toString());
expect(claims).toMatchObject({ iss: instanceId, op: "status", sub: "instance-capabilities", cid: "instance-capabilities" });
return Response.json({ active: true, status: "active", profiles: [], ...(supported ? { photonReceiver: { version: 1 } } : {}) });
});
const connector = createPaperclipCloudConnector({ config: keys.config, request });
await expect(connector.photonReceiverAvailable()).resolves.toBe(supported);
}
});
it("never turns uncertain authority or malformed status into local fallback", async () => {
const keys = config();
const bodies = [
{ active: false, status: "suspended", profiles: [] },
{ active: true, status: "active" },
{ active: true, status: "active", profiles: [42] },
{ active: true, status: "active", profiles: [], photonReceiver: null },
{ active: true, status: "active", profiles: [], photonReceiver: { version: 2 } },
];
for (const body of bodies) {
const connector = createPaperclipCloudConnector({ config: keys.config, request: async () => Response.json(body) });
await expect(connector.photonReceiverAvailable()).rejects.toBeInstanceOf(Error);
}
for (const status of [401, 403, 503]) {
const connector = createPaperclipCloudConnector({ config: keys.config, request: async () => Response.json({ error: "REAUTHORIZATION_REQUIRED" }, { status }) });
await expect(connector.photonReceiverAvailable()).rejects.toBeInstanceOf(Error);
}
const connector = createPaperclipCloudConnector({ config: keys.config, request: async () => { throw new Error("controlled network interruption"); } });
await expect(connector.photonReceiverAvailable()).rejects.toBeInstanceOf(Error);
});
});
@@ -419,6 +419,15 @@ export function createPaperclipCloudConnector(input: {
const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" });
return response.active === true && response.slackEvents?.version === 1;
},
async photonReceiverAvailable(): Promise<boolean> {
const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" });
if (response.active !== true || response.status !== "active" || (!Array.isArray(response.profiles) || !response.profiles.every(value => typeof value === "string"))) throw badEnvelope();
// Only a valid authenticated legacy status is positive lack of support.
// Unknown versions, malformed responses and rejected requests retain debt.
if (response.photonReceiver === undefined) return false;
if (!isRecord(response.photonReceiver) || response.photonReceiver.version !== 1) throw badEnvelope();
return true;
},
async photonReceiverOperation(values: { subject: string; companyId: string; operation: Record<string, unknown> }): Promise<unknown> {
const response = await call("photon-receiver", values, { field: "operation", value: JSON.stringify(values.operation) });
if (!isRecord(response.photonReceiver)) throw badEnvelope();
@@ -733,9 +742,10 @@ function parseCloudHandoff(value: unknown): { kind: "paperclip_cloud"; session:
return { kind: "paperclip_cloud", session };
}
export type PaperclipCloudConnector = Omit<ReturnType<typeof createPaperclipCloudConnector>, "instanceIdentity" | "slackFormOperation" | "photonReceiverOperation"> & {
export type PaperclipCloudConnector = Omit<ReturnType<typeof createPaperclipCloudConnector>, "instanceIdentity" | "slackFormOperation" | "photonReceiverOperation" | "photonReceiverAvailable"> & {
instanceIdentity?: () => Readonly<{ instanceId: string; environment: PaperclipCloudConnectorEnvironment }>;
photonReceiverOperation?: ReturnType<typeof createPaperclipCloudConnector>["photonReceiverOperation"];
photonReceiverAvailable?: ReturnType<typeof createPaperclipCloudConnector>["photonReceiverAvailable"];
slackFormOperation?: ReturnType<typeof createPaperclipCloudConnector>["slackFormOperation"];
};
export type PaperclipCloudGoogleWorkspaceConnector = PaperclipCloudConnector;