mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 23:06:17 +01:00
Keep hosted Muse contacts with Cloud between useful imports
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
caf3db497c
commit
2759e45323
39 files changed
+1090
-86
No files matched your search
@@ -2915,3 +2915,5 @@ export {
|
||||
TASK_IDENTITY_CHANGED_FIELD,
|
||||
issueActivityChangesTaskIdentity,
|
||||
} from "./issue-activity-identity.js";
|
||||
|
||||
export * from "./muse-hosted-protocol.js";
|
||||
@@ -0,0 +1,31 @@
|
||||
import { z } from "zod";
|
||||
const integer=z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const digest=z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const origin=z.string().url().max(2048).refine(value=>{const parsed=new URL(value);return parsed.protocol==="https:"&&parsed.origin===value;});
|
||||
export const museHostedNamespaceSchema=z.object({stackId:z.string().min(1).max(200),instanceId:z.string().min(1).max(200),origin}).strict();
|
||||
export const museReceiverRecordSchema=z.object({bindingId:z.uuid(),companyId:z.uuid(),agentId:z.uuid(),operatorId:z.string().min(1).max(200),generation:integer.positive(),
|
||||
state:z.enum(["available","idle","retired"]),qualificationExpiresAt:integer.nullable(),
|
||||
item:z.object({sourceEventId:z.string().min(1).max(200),attempt:integer,notifiedAt:integer.nullable(),expiresAt:integer.nullable()}).strict().nullable()}).strict().superRefine((row,ctx)=>{
|
||||
if(row.state!=="available"&&row.item!==null)ctx.addIssue({code:"custom",message:"Unavailable Muse receiver has a signal"});
|
||||
});
|
||||
export const museReceiverReferenceSchema=z.object({profile:z.literal("hosted-muse-v1"),generation:digest,count:integer.max(1000),contactImportWakeVersion:z.literal(1).optional()}).strict();
|
||||
export const museContactBucketSchema=z.object({id:z.uuid(),bindingId:z.uuid(),companyId:z.uuid(),generation:integer.positive(),bucketAt:integer,firstAt:integer,lastAt:integer,
|
||||
contacts:integer.positive(),gapsAtMostSevenSeconds:integer,maxGapMs:integer,timestamps:z.array(integer).min(1).max(60),incomplete:z.boolean()}).strict().superRefine((row,ctx)=>{
|
||||
if(!row.incomplete&&(row.contacts!==row.timestamps.length||row.timestamps.at(-1)!==row.lastAt))ctx.addIssue({code:"custom",message:"Incomplete Muse timestamps were not declared"});
|
||||
if(row.bucketAt!==Math.floor(row.firstAt/30_000)*30_000||row.lastAt<row.firstAt||row.timestamps[0]!==row.firstAt||row.timestamps.at(-1)!>row.lastAt||row.contacts<row.timestamps.length||row.gapsAtMostSevenSeconds>=row.contacts+1||row.timestamps.some((at,i)=>i>0&&at<row.timestamps[i-1]!))ctx.addIssue({code:"custom",message:"Invalid Muse contact bucket"});
|
||||
});
|
||||
export const museContactPageSchema=z.object({version:z.literal(1),namespace:museHostedNamespaceSchema,recipientNamespace:museHostedNamespaceSchema,sourceId:z.uuid(),after:integer,through:integer,
|
||||
entries:z.array(z.object({sequence:integer.positive(),bucket:museContactBucketSchema}).strict()).max(20),digest}).strict();
|
||||
export type MuseHostedNamespace=z.infer<typeof museHostedNamespaceSchema>;
|
||||
export type MuseReceiverRecord=z.infer<typeof museReceiverRecordSchema>;
|
||||
export type MuseReceiverReference=z.infer<typeof museReceiverReferenceSchema>;
|
||||
export type MuseContactBucket=z.infer<typeof museContactBucketSchema>;
|
||||
export type MuseContactPage=z.infer<typeof museContactPageSchema>;
|
||||
|
||||
export const museReceiverOwnershipSchema=z.discriminatedUnion("state",[
|
||||
z.object({state:z.literal("unowned")}).strict(),
|
||||
z.object({state:z.literal("pending")}).strict(),
|
||||
z.object({state:z.literal("owned"),namespace:museHostedNamespaceSchema,revision:integer,mirrorGeneration:digest,reference:museReceiverReferenceSchema,sourceId:z.uuid()}).strict(),
|
||||
]);
|
||||
export const museContactExchangeSchema=z.object({page:museContactPageSchema,ownership:museReceiverOwnershipSchema}).strict();
|
||||
export type MuseReceiverOwnership=z.infer<typeof museReceiverOwnershipSchema>;
|
||||
@@ -1,3 +1,20 @@
|
||||
import { createServer, request as nodeRequest, type Server } from "node:http";
|
||||
import { mkdtemp } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { createRequire } from "node:module";
|
||||
import { mcpClientMirrorState } from "@paperclipai/db";
|
||||
import { mcpClientMirrorReceiptSchema } from "../services/public-mcp/client-mirror-contract.js";
|
||||
import { livenessDb, checkpointDb, fileStorageDb } from "@paperclipai/db";
|
||||
import { migrateCloudConfiguration } from "../services/cloud-configuration-migration.js";
|
||||
import { initializeAdapterSettings } from "../services/adapter-settings.js";
|
||||
import { initializeCloudRuntimeConfig } from "../services/cloud-runtime-config.js";
|
||||
import { createStorageService } from "../storage/service.js";
|
||||
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
|
||||
import { removeTestHome } from "./remove-test-home.js";
|
||||
import { instanceSettings as runtimeInstanceSettings } from "@paperclipai/db";
|
||||
import { initializeCloudRuntimeIdentity, applyCloudRuntimeIdentityAssertion, resetCloudRuntimeIdentityForTests, getCloudRuntimeIdentity } from "../services/cloud-runtime-identity.js";
|
||||
import { subscribeDatabaseWork } from "@paperclipai/db";
|
||||
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
||||
import express from "express";
|
||||
@@ -5,7 +22,7 @@ import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { activityLog, agentCommentary, documents, issueDocuments } from "@paperclipai/db";
|
||||
import request from "supertest";
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import { createHash, generateKeyPairSync, sign, randomBytes, randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, authUsers, companies, companyMemberships, createDb, closeRegisteredClients, applyPendingMigrations, externalAgentHolds, heartbeatRuns, issueAccessGrants, issueComments, issues, projects, principalPermissionGrants, mcpOauthGrants, mcpOauthRequests, mcpOauthTokens, dotAgentBindings, dotRunnerAssignments, dotRunnerOperations, museIdleReceipts, museAgentBindings as bindings, museCredentials, museInputDeliveries, museReceiverContactBuckets, museMailboxItems as mailbox, museRunnerAssignments as assignments, museRunnerOperations as operations, nativeRunFinalizations } from "@paperclipai/db";
|
||||
@@ -48,7 +65,7 @@ describe("personal Muse control plane",()=>{
|
||||
let temporary:Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>|undefined,db:ReturnType<typeof createDb>,externalDatabaseUrl:string|undefined;
|
||||
beforeAll(async()=>{
|
||||
externalDatabaseUrl=process.env.PAPERCLIP_MUSE_CONTROL_TEST_DATABASE_URL?.trim();
|
||||
if(externalDatabaseUrl){await applyPendingMigrations(externalDatabaseUrl);db=createDb(externalDatabaseUrl);}
|
||||
if(externalDatabaseUrl){await applyPendingMigrations(externalDatabaseUrl);db=createDb(externalDatabaseUrl,{maxConnections:4});}
|
||||
else {temporary=await startEmbeddedPostgresTestDatabase("muse-control-");db=createDb(temporary.connectionString);}
|
||||
await instanceSettingsService(db).updateExperimental({enableNativeRunner:true,enableMuse:true});
|
||||
},30000);
|
||||
@@ -1041,6 +1058,427 @@ describe("personal Muse control plane",()=>{
|
||||
expect(logs[0]).toMatchObject({actorType:"agent",actorId:f.agent.id,agentId:f.agent.id,responsibleUserId:f.operatorId,details:{bindingId:f.binding.id,generation:1,authorizingUserId:f.operatorId,requestId}});
|
||||
expect(JSON.stringify(logs)).not.toContain(nonce);
|
||||
});
|
||||
it("receiver shutdown joins an admitted real signal before persisting its contact",async()=>{
|
||||
const f=await fixture(false);
|
||||
let release!:()=>void,entered!:()=>void;
|
||||
const gate=new Promise<void>(resolve=>{release=resolve;}),atTransaction=new Promise<void>(resolve=>{entered=resolve;});
|
||||
const owner=new Proxy(db,{get(target,key,receiver){
|
||||
if(key!=="transaction")return Reflect.get(target,key,receiver);
|
||||
return async(...args:Parameters<typeof db.transaction>)=>{entered();await gate;return Reflect.apply(target.transaction,target,args);};
|
||||
}});
|
||||
const receiver=museReceiver(owner);
|
||||
let contactCompleted=false;
|
||||
const contact=receiver.signal(f.binding.id).then(result=>{contactCompleted=true;return result;});
|
||||
await atTransaction;
|
||||
const stop=receiver.stop().then(()=>{expect(contactCompleted).toBe(true);});
|
||||
release();
|
||||
try {await stop;} finally {await contact;}
|
||||
const rows=await db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
expect(rows.reduce((count,row)=>count+row.contacts,0)).toBe(1);
|
||||
expect((await db.select().from(bindings).where(eq(bindings.id,f.binding.id)))[0].receiverContactAt).not.toBeNull();
|
||||
await expect(receiver.signal(f.binding.id)).rejects.toMatchObject({status:503});
|
||||
});
|
||||
it("receiver shutdown retains failed contact debt and a restarted owner persists it exactly once",async()=>{
|
||||
const f=await fixture(false);let failNext=false;
|
||||
const owner=new Proxy(db,{get(target,key,receiver){
|
||||
if(key!=="transaction")return Reflect.get(target,key,receiver);
|
||||
return async(...args:Parameters<typeof db.transaction>)=>{
|
||||
if(failNext){failNext=false;throw new Error("controlled contact persistence failure");}
|
||||
return Reflect.apply(target.transaction,target,args);
|
||||
};
|
||||
}});
|
||||
const receiver=museReceiver(owner);
|
||||
await receiver.signal(f.binding.id);failNext=true;
|
||||
await expect(receiver.stop()).rejects.toThrow("Muse receiver contact persistence is incomplete.");
|
||||
expect(await db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id))).toEqual([]);
|
||||
receiver.start();await receiver.stop();
|
||||
const rows=await db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
expect(rows.reduce((count,row)=>count+row.contacts,0)).toBe(1);
|
||||
expect(rows.every(row=>row.incomplete)).toBe(true);
|
||||
await receiver.stop();
|
||||
expect(await db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id))).toEqual(rows);
|
||||
receiver.start();await receiver.signal(f.binding.id);await receiver.stop();
|
||||
const recovered=await db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
expect(recovered.reduce((count,row)=>count+row.contacts,0)).toBe(2);
|
||||
});
|
||||
// Narrow first-evidence controls, not an assembled Cloud sleep/full-ACK proof.
|
||||
// Readiness is reached through OAuth, persisted contact and the actual HTTP
|
||||
// challenge response. No ready/status/contact/receipt is stamped by these tests.
|
||||
async function actualReadyContact() {
|
||||
const f=await oauthFixture(false),tokens=await f.oauth.token(f.tokenInput());
|
||||
const receiverOwner=createDb(externalDatabaseUrl??temporary!.connectionString,{maxConnections:1});
|
||||
const receiver=museReceiver(receiverOwner);receiver.start();
|
||||
const app=express();app.use(museTransportRoutes(receiverOwner,oauthOrigin));app.use(errorHandler);
|
||||
const access=tokens.access_token;
|
||||
try {
|
||||
expect((await request(app).get("/api/muse/v1/signal").set("X-Paperclip-Muse-Binding",f.binding.id)).status).toBe(200);
|
||||
await receiver.flush();
|
||||
const inbox=await request(app).post("/api/muse/v1/queries").set("Authorization","Bearer "+access)
|
||||
.send({version:1,query:"mailbox",after:0});
|
||||
expect(inbox.status).toBe(200);
|
||||
const challenge=inbox.body.items.find((item:{kind:string})=>item.kind==="readiness_challenge");
|
||||
expect(challenge).toBeDefined();
|
||||
const confirmed=await request(app).post("/api/muse/v1/commands").set("Authorization","Bearer "+access)
|
||||
.send({version:1,command:"challenge.confirm",nonce:challenge.references.nonce,requestId:randomUUID()});
|
||||
expect(confirmed.status).toBe(200);expect(confirmed.body.status).toBe("ready");
|
||||
const acknowledged=await request(app).post("/api/muse/v1/queries").set("Authorization","Bearer "+access)
|
||||
.send({version:1,query:"mailbox",after:inbox.body.nextCursor});
|
||||
expect(acknowledged.status).toBe(200);expect(acknowledged.body.items).toEqual([]);
|
||||
const [ready]=await db.select().from(bindings).where(eq(bindings.id,f.binding.id));
|
||||
expect(ready.status).toBe("ready");expect(ready.verifiedReplyAt).not.toBeNull();
|
||||
return {...f,receiverOwner};
|
||||
} catch(error) {await receiver.stop();await receiverOwner.$client.end({timeout:1});throw error;}
|
||||
}
|
||||
it("observes a real settled HTTP contact admitted after empty handoff and persists it on normal stop",async()=>{
|
||||
const f=await actualReadyContact(),receiver=museReceiver(f.receiverOwner);
|
||||
await receiver.prepareHostedHandoff(new AbortController().signal);
|
||||
const read=()=>db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
const before=await read(),total=(rows:Awaited<ReturnType<typeof read>>)=>rows.reduce((sum,row)=>sum+row.contacts,0);
|
||||
let arrived!:()=>void,release!:()=>void;
|
||||
const atIngress=new Promise<void>(resolve=>{arrived=resolve;}),gate=new Promise<void>(resolve=>{release=resolve;});
|
||||
const app=express();app.use(idleAdmissionMiddleware);
|
||||
app.use(async(_req,_res,next)=>{arrived();await gate;next();});
|
||||
app.use(museTransportRoutes(f.receiverOwner,oauthOrigin));app.use(errorHandler);trackIdleRequestHandlers(app);
|
||||
const baseline=idleWorkSnapshot().active;
|
||||
const contact=request(app).get("/api/muse/v1/signal").set("X-Paperclip-Muse-Binding",f.binding.id).then(response=>response);
|
||||
try {
|
||||
await atIngress;
|
||||
// HTTP is already admitted, but the receiver has no admitted signal yet.
|
||||
await receiver.prepareHostedHandoff(new AbortController().signal);
|
||||
expect(await read()).toEqual(before);
|
||||
release();
|
||||
const response=await contact;expect(response.status).toBe(200);expect(response.body).toEqual({version:1,signal:null});
|
||||
await vi.waitFor(()=>expect(idleWorkSnapshot().active).toBe(baseline));
|
||||
// This diagnoses buffered custody; it is NOT an asserted safe-sleep/fullACK.
|
||||
expect(await read()).toEqual(before);
|
||||
await receiver.stop();
|
||||
const saved=await read();expect(total(saved)).toBe(total(before)+1);
|
||||
receiver.start();await receiver.stop();
|
||||
expect(await read()).toEqual(saved);
|
||||
} finally {release();await contact;await receiver.stop();await f.receiverOwner.$client.end({timeout:1});}
|
||||
},15000);
|
||||
it("retains a late HTTP contact through failed stop and same-owner restart without inventing persisted custody",async()=>{
|
||||
const f=await actualReadyContact();let failNext=false;
|
||||
const owner=new Proxy(f.receiverOwner,{get(target,key,receiver){
|
||||
if(key!=="transaction")return Reflect.get(target,key,receiver);
|
||||
return async(...args:Parameters<typeof db.transaction>)=>{
|
||||
if(failNext){failNext=false;throw new Error("controlled late-contact persistence failure");}
|
||||
return Reflect.apply(target.transaction,target,args);
|
||||
};
|
||||
}});
|
||||
const receiver=museReceiver(owner),app=express();app.use(idleAdmissionMiddleware);
|
||||
app.use(museTransportRoutes(owner,oauthOrigin));app.use(errorHandler);trackIdleRequestHandlers(app);
|
||||
const read=()=>db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
const before=await read(),total=(rows:Awaited<ReturnType<typeof read>>)=>rows.reduce((sum,row)=>sum+row.contacts,0);
|
||||
try {
|
||||
await receiver.prepareHostedHandoff(new AbortController().signal);
|
||||
const response=await request(app).get("/api/muse/v1/signal").set("X-Paperclip-Muse-Binding",f.binding.id);
|
||||
expect(response.status).toBe(200);expect(response.body).toEqual({version:1,signal:null});
|
||||
expect(await read()).toEqual(before);
|
||||
failNext=true;
|
||||
await expect(receiver.stop()).rejects.toThrow("Muse receiver contact persistence is incomplete.");
|
||||
expect(await read()).toEqual(before);
|
||||
receiver.start();await receiver.stop();
|
||||
const saved=await read();expect(total(saved)).toBe(total(before)+1);
|
||||
expect(saved.filter(row=>!before.some(old=>old.id===row.id)).every(row=>row.incomplete)).toBe(true);
|
||||
receiver.start();await receiver.stop();expect(await read()).toEqual(saved);
|
||||
} finally {failNext=false;await receiver.stop();await museReceiver(f.receiverOwner).stop();await f.receiverOwner.$client.end({timeout:1});}
|
||||
},15000);
|
||||
|
||||
// Selected fresh-paired-DB control. This tests actual worker/HTTP/commit/ACK
|
||||
// composition; logical pressure seeding is NOT the physical 5s/90s cadence proof.
|
||||
async function coupledMuseContactRecovery(physicalCadence: boolean) {
|
||||
const cloudUrl=process.env.PAPERCLIP_MUSE_CONTACT_CLOUD_TEST_DATABASE_URL;
|
||||
const checkout=process.env.PAPERCLIP_MUSE_CONTACT_CLOUD_CHECKOUT;
|
||||
if(!externalDatabaseUrl||!cloudUrl||!checkout||!path.isAbsolute(checkout))throw new Error("Explicit paired owned databases and own compiled Cloud checkout required");
|
||||
const parsed=new URL(cloudUrl);
|
||||
if(!["postgres:","postgresql:"].includes(parsed.protocol)||!["127.0.0.1","localhost","[::1]"].includes(parsed.hostname)
|
||||
||!parsed.port||!/^[A-Za-z0-9_]+_test$/.test(decodeURIComponent(parsed.pathname.slice(1)))
|
||||
||["options","database","dbname"].some(key=>parsed.searchParams.has(key))||cloudUrl===externalDatabaseUrl)throw new Error("Distinct explicit owned loopback Cloud *_test database required");
|
||||
const load=(name:string)=>import(pathToFileURL(path.join(checkout,"dist",name)).href);
|
||||
const [registryModule,provisionerModule,fakeModule,serviceModule,secretModule,providersModule,
|
||||
runtimeModule,readinessModule,storeModule,wakeModule,quotaModule,mirrorModule,museContractModule,pressureModule]=await Promise.all([
|
||||
load("registry/postgres.js"),load("provisioner/provisioner.js"),load("providers/fake.js"),load("service/app.js"),
|
||||
load("providers/stack-secrets.js"),load("connections/providers.js"),
|
||||
load("runtime/runtime-identity-assertion.js"),load("sleep/wake-readiness.js"),load("muse-receiver/store.js"),
|
||||
load("muse-receiver/contact-import-wake.js"),load("assistant-mcp/import-quota.js"),load("assistant-mcp/client-mirror-store.js"),load("muse-receiver/contract.js"),load("muse-receiver/contact-import-pressure.js")]);
|
||||
const provider=new fakeModule.FakeCloudStackProvider();
|
||||
const f=await actualReadyContact(),stackId="contact-paired-"+randomUUID(),instanceId="instance-"+randomUUID(),cloudOrigin="https://muse-contact-cloud.example.test";
|
||||
const qualified = (await f.broker.bindingForAgent(f.company.id, f.agent.id))!;
|
||||
await f.broker.beginQualification({companyId:f.company.id,agentId:f.agent.id,bindingId:f.binding.id,
|
||||
generation:qualified.generation,expectedRevision:qualified.revision,qualificationId:randomUUID(),
|
||||
expiresAt:new Date(Date.now()+10*60_000),operatorId:f.operatorId});
|
||||
const home=await mkdtemp(path.join(tmpdir(),"muse-custody-paired-")),control=generateKeyPairSync("ed25519"),signing=generateKeyPairSync("ed25519"),seal=generateKeyPairSync("x25519"),kid="muse-paired-current";
|
||||
const jwks=JSON.stringify({keys:[{...control.publicKey.export({format:"jwk"}),kid,alg:"EdDSA",use:"sig"}]});
|
||||
const namespace={stackId,instanceId,origin:oauthOrigin};
|
||||
let registry:any,cloud:any,app:express.Express|undefined,appDb:ReturnType<typeof createDb>|undefined,cloudServer:Server|undefined,appServer:Server|undefined;
|
||||
let cloudLoopback="",appLoopback="",passed=false,dropCommittedAck=false,lostAckObserved=false,firstAckEntered=false,armLostAck=false,ackCommits=0,wakeHints=0,appQueries=0;
|
||||
let releaseAck!:()=>void;
|
||||
const ackGate=new Promise<void>(resolve=>{releaseAck=resolve;});
|
||||
const {Pool}=createRequire(path.join(checkout,"package.json"))("pg");
|
||||
const pool=new Pool({connectionString:cloudUrl,max:2,connectionTimeoutMillis:5000,idleTimeoutMillis:1000});
|
||||
const limits={stack:{...quotaModule.MCP_IMPORT_LIMITS.stack,museContactRows:160},global:{...quotaModule.MCP_IMPORT_LIMITS.global}};
|
||||
const keys=new Map<string,Buffer>();const restorers:Array<()=>void>=[];
|
||||
const listen=(server:Server)=>new Promise<string>((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",()=>{const address=server.address();if(!address||typeof address==="string")return reject(new Error("Missing owned listener"));resolve("http://127.0.0.1:"+address.port);});});
|
||||
const close=(server:Server|undefined)=>server?new Promise<void>((resolve,reject)=>server.close(error=>error?reject(error):resolve())):Promise.resolve();
|
||||
const mapped:typeof fetch=async(input,init)=>{
|
||||
const original=new Request(input,init),url=new URL(original.url);
|
||||
if(![cloudOrigin,oauthOrigin].includes(url.origin))throw new Error("Off-boundary paired Muse request");
|
||||
if(url.origin===oauthOrigin&&url.pathname==="/api/instance/connector-events/wake")wakeHints++;
|
||||
const base=url.origin===cloudOrigin?cloudLoopback:appLoopback;if(!base)throw new Error("Owned transport not ready");
|
||||
const body=original.body?Buffer.from(await original.arrayBuffer()):undefined,headers=new Headers(original.headers);headers.set("host",url.host);
|
||||
return new Promise<Response>((resolve,reject)=>{
|
||||
const sent=nodeRequest(new URL(url.pathname+url.search,base),{method:original.method,headers:Object.fromEntries(headers),signal:original.signal},response=>{
|
||||
const parts:Buffer[]=[];let bytes=0;
|
||||
response.on("data",part=>{bytes+=part.length;if(bytes>1_048_576)return response.destroy(new Error("Bounded paired response exceeded"));parts.push(Buffer.from(part));});
|
||||
response.on("error",reject);response.on("end",()=>{
|
||||
if(dropCommittedAck&&url.origin===cloudOrigin&&url.pathname==="/v1/connector/mcp-muse-contacts"){
|
||||
dropCommittedAck=false;lostAckObserved=true;reject(new Error("Controlled lost response AFTER real exact ACK committed"));return;
|
||||
}
|
||||
const resultHeaders=new Headers();for(const [key,value] of Object.entries(response.headers))if(value!==undefined)for(const item of Array.isArray(value)?value:[value])resultHeaders.append(key,item);
|
||||
resolve(new Response([204,205,304].includes(response.statusCode!)?null:Buffer.concat(parts),{status:response.statusCode,headers:resultHeaders}));
|
||||
});
|
||||
});sent.on("error",reject);sent.end(body);
|
||||
});
|
||||
};
|
||||
const contacts=()=>db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
const cloudState=async()=> (await pool.query("SELECT mcp_client_mirror,muse_receiver_contacts,mcp_import_usage FROM cloud_harness.company_stacks WHERE id=$1",[stackId])).rows[0];
|
||||
const pending=(state:Awaited<ReturnType<typeof cloudState>>)=>state.muse_receiver_contacts.epochs.reduce((n:number,e:{rows:unknown[]})=>n+e.rows.length,0);
|
||||
const makeCloud=async()=>{
|
||||
const store=new storeModule.PostgresMuseReceiverStore(pool,limits),realContacts=store.contacts.bind(store);
|
||||
const observe=vi.spyOn(store,"contacts").mockImplementation(async(...raw:any[])=>{
|
||||
const [scope,operation]=raw;
|
||||
if(operation.operation==="ack"){
|
||||
// Observe actual App durable import BEFORE allowing its exact Cloud ACK.
|
||||
const saved=await contacts();for(const entry of operation.page.entries){const bucket=entry.bucket;
|
||||
expect(saved.find(row=>row.replicaId===bucket.id&&row.bucketAt.getTime()===bucket.bucketAt)).toMatchObject({contacts:bucket.contacts,bindingGeneration:bucket.generation});}
|
||||
if(armLostAck){firstAckEntered=true;await ackGate;}
|
||||
const result=await realContacts(scope,operation);ackCommits++;
|
||||
if(armLostAck){armLostAck=false;dropCommittedAck=true;}return result;
|
||||
}
|
||||
return realContacts(scope,operation);
|
||||
});restorers.push(()=>observe.mockRestore());
|
||||
const storePort=vi.spyOn(registry,"museReceiverStore").mockReturnValue(store);
|
||||
const wakePort=vi.spyOn(registry,"museContactImportWakeSource").mockImplementation((ports:any)=>wakeModule.createMuseContactImportWakeSource(pool,ports,limits));
|
||||
restorers.push(()=>storePort.mockRestore(),()=>wakePort.mockRestore());
|
||||
const noShared=async()=>{throw new Error("Unexpected shared/provider secret");};
|
||||
const vault=new secretModule.StackEncryptedSecretStore({region:"us-east-1",secretRefPrefix:"secret://muse-paired",database:registry.stackSecretDatabase(),
|
||||
keys:{getKey:async(name:string)=>keys.get(name),createKeyIfAbsent:async(name:string,value:Buffer)=>{if(keys.has(name))return"exists";keys.set(name,Buffer.from(value));return"created";},deleteKey:async(name:string)=>{keys.delete(name);},listKeyNames:async(prefix:string)=>[...keys.keys()].filter(name=>name.startsWith(prefix+"/"))},
|
||||
shared:{getSecret:noShared,putSecret:noShared,createSecretIfAbsent:noShared,deleteSecret:noShared}});
|
||||
const runtime=runtimeModule.createRuntimeIdentitySignerFromEnv({CLOUD_HARNESS_RUNTIME_IDENTITY_SIGNING_JWK:JSON.stringify({...control.privateKey.export({format:"jwk"}),kid,alg:"EdDSA",use:"sig"}),CLOUD_HARNESS_RUNTIME_IDENTITY_JWKS:jwks},{required:true});
|
||||
const readiness=readinessModule.createHttpWakeReadinessProbe({fetch:mapped});
|
||||
cloud=serviceModule.createCloudHarnessService({registry,provider,baseDomain:"paperclip.app",customerAppOrigin:cloudOrigin,
|
||||
runtimeIdentity:runtime,incomingMcpWakeEnabled:true,entryReadinessProbe:readiness,wakeReadinessProbe:readiness,
|
||||
tenantSessionSigningKey:"muse-paired-tenant-".repeat(3),customerSessionSigningKey:"muse-paired-customer-".repeat(3),appVersion:"paired",schemaVersion:"fixture",
|
||||
assistantMcp:{store:registry.assistantMcpStore(),encryptionKey:Buffer.alloc(32,9)},connector:{environment:"test",providers:providersModule.providerRegistryFromEnvironment({}),
|
||||
fetchImplementation:mapped,secrets:{resolve:noShared},store:registry.connectorStore(),stackEnrollment:{secrets:vault,secretRefPrefix:"secret://muse-paired"}}});
|
||||
cloudServer=createServer((req,res)=>cloud.handler(req,res));cloudLoopback=await listen(cloudServer);return store;
|
||||
};
|
||||
const makeApp=async()=>{
|
||||
appDb=createDb(externalDatabaseUrl,{maxConnections:2,applicationName:"muse-paired-import"});
|
||||
for(const owner of [appDb,livenessDb(appDb),checkpointDb(appDb),fileStorageDb(appDb)])owner.$client.options.debug=()=>{appQueries++;};
|
||||
await migrateCloudConfiguration(appDb);await initializeAdapterSettings(appDb);await initializeCloudRuntimeConfig(appDb);
|
||||
const {createApp}=await import("../app.js");
|
||||
app=await createApp(appDb,{uiMode:"none",serverPort:3100,storageService:createStorageService(createLocalDiskStorageProvider(path.join(home,"objects"))),
|
||||
deploymentMode:"authenticated",deploymentExposure:"private",bindHost:"127.0.0.1",allowedHostnames:[new URL(oauthOrigin).hostname],authPublicBaseUrl:oauthOrigin,authReady:true,
|
||||
companyDeletionEnabled:false,managedPluginAutoInstall:[],decisionServiceOptions:{wakeOriginAgent:async()=>{throw new Error("No task work in contact-import control");}}});
|
||||
await app.locals.bundledPluginsStartup;appServer=createServer(app);appLoopback=await listen(appServer);
|
||||
};
|
||||
const stopApp=async()=>{await app?.locals.paperclipShutdown();app=undefined;await close(appServer);appServer=undefined;await appDb?.$client.end({timeout:1});appDb=undefined;};
|
||||
try {
|
||||
registry=await registryModule.PostgresCloudHarnessRegistry.connect({connectionString:cloudUrl,maxConnections:2,runMigrations:true,migrationsPath:path.join(checkout,"migrations"),migrationLockTimeoutMs:5000});
|
||||
await registry.createFleetReleaseArtifact({id:stackId,appVersion:"paired"});await registry.importFeatureCatalog({releaseArtifactId:stackId,catalogVersion:"paired",features:{"cloud.feature-masking":{tier:"managed"}}});
|
||||
await new provisionerModule.CloudStackProvisioner({registry,provider}).provisionDevelopmentStack({idempotencyKey:stackId,
|
||||
accountGroup:{id:stackId,slug:stackId,displayName:"Muse paired"},owner:{id:f.operatorId,email:f.operatorId+"@example.test"},
|
||||
stack:{stackId,accountGroupId:stackId,stackSlug:"paperclip",displayName:"Muse paired",kind:"demo",primaryHost:new URL(oauthOrigin).hostname,region:"us-east-1"},
|
||||
versionPlan:{appVersion:"paired",schemaVersion:"fixture",rolloutTrack:"stable"},sleepPolicy:{desiredState:"awake"},
|
||||
primaryCompany:{paperclipCompanyId:f.company.id,displayName:"Muse paired",defaultBudgetCents:0}});
|
||||
await registry.updateStackWakeState(stackId,{providerRefs:[{provider:"railway",resourceType:"service_domain:web",externalId:stackId,name:"tenant",metadata:{upstreamOrigin:oauthOrigin}}],lifecycleState:"active",sleepState:"awake"});
|
||||
await registry.connectorStore().putCloudStackInstance({id:instanceId,kind:"cloud_stack",companyStackId:stackId,environment:"test",signPublicKey:signing.publicKey.export({format:"jwk"}).x!,sealPublicKey:seal.publicKey.export({format:"jwk"}).x!,origins:[oauthOrigin],activeOrigin:oauthOrigin,label:"Muse paired actual namespace",status:"active",createdAt:new Date(),updatedAt:new Date()});
|
||||
for(const [key,value] of Object.entries({PAPERCLIP_HOME:home,PAPERCLIP_CONFIG:path.join(home,"runtime-config.json"),PAPERCLIP_SECRETS_MASTER_KEY:randomBytes(32).toString("base64"),
|
||||
PAPERCLIP_CLOUD_STACK_ID:stackId,PAPERCLIP_PUBLIC_URL:oauthOrigin,PAPERCLIP_AUTH_PUBLIC_BASE_URL:oauthOrigin,PAPERCLIP_API_URL:oauthOrigin,PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS:jwks,
|
||||
PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID:instanceId,PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT:"test",PAPERCLIP_CLOUD_CONNECTOR_BASE_URL:cloudOrigin,
|
||||
PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY:signing.privateKey.export({format:"jwk"}).d!,PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY:seal.privateKey.export({format:"jwk"}).d!}))vi.stubEnv(key,value);
|
||||
expect(getCloudRuntimeIdentity()).toBeNull();await initializeCloudRuntimeIdentity(db);
|
||||
const issued=Math.floor(Date.now()/1000),encode=(value:unknown)=>Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
const body=encode({alg:"EdDSA",typ:"paperclip-cloud-runtime-identity+jwt",kid})+"."+encode({v:1,iss:"paperclip-cloud",aud:"paperclip-runtime-identity/v1",sub:stackId,claimId:randomUUID(),previousOrigin:oauthOrigin,canonicalOrigin:oauthOrigin,stackSlug:"paperclip",iat:issued,exp:issued+60});
|
||||
await applyCloudRuntimeIdentityAssertion({db,compactJws:body+"."+sign(null,Buffer.from(body),control.privateKey).toString("base64url")});
|
||||
await instanceSettingsService(db).updateExperimental({enablePublicMcp:true,enableMuse:true,enableNativeRunner:true});
|
||||
// DECLARED INITIAL STATE: retained Cloud-only historical contacts after
|
||||
// acknowledged prior custody. These direct normal-store ACKs establish
|
||||
// NO claimed historical App proof or current import capability. Current
|
||||
// capability/full mirror below must come from actual App registration.
|
||||
const historicalRecords=Array.from({length:96},()=>({bindingId:randomUUID(),companyId:f.company.id,agentId:randomUUID(),operatorId:f.operatorId,
|
||||
generation:1,state:"idle",qualificationExpiresAt:null,item:null}));
|
||||
const reference={profile:"hosted-muse-v1",generation:museContractModule.museReceiverGeneration(namespace,0,historicalRecords),count:historicalRecords.length};
|
||||
const initial={version:1,instanceId,origin:oauthOrigin,revision:0,baseRevision:null,expectedRecords:0,museReceivers:reference};
|
||||
const oldMirror=new mirrorModule.PostgresMcpClientMirrorStore(pool,undefined,limits),scope={...namespace,companyId:f.company.id,museProfile:"hosted-muse-v1"};
|
||||
await oldMirror.sync(scope,{...initial,operation:"begin"});
|
||||
await oldMirror.sync(scope,{...initial,operation:"append-muse-receivers",sequence:0,entries:historicalRecords});
|
||||
expect((await oldMirror.sync(scope,{...initial,operation:"complete"})).complete).toBe(true);
|
||||
const initialStore=new storeModule.PostgresMuseReceiverStore(pool,limits),historicalAt=Date.now()-120*30000;
|
||||
for(const record of historicalRecords){
|
||||
await initialStore.signal(namespace,record.bindingId,historicalAt);
|
||||
const read=await initialStore.contacts(namespace,{operation:"read"});
|
||||
await initialStore.contacts(namespace,{operation:"ack",page:read.page});
|
||||
}
|
||||
const retained=await cloudState();expect(retained.mcp_import_usage.museContactRows).toBe(97);
|
||||
expect(retained.mcp_import_usage.museContactRows).toBeGreaterThan(limits.stack.museContactRows/2);
|
||||
expect(retained.mcp_client_mirror.published.museReceivers.contactImportWakeVersion).toBeUndefined();
|
||||
vi.stubGlobal("fetch",mapped);let store=await makeCloud();await makeApp();
|
||||
await vi.waitFor(async()=>{const state=await cloudState();expect(state.mcp_client_mirror.stage).toBeNull();
|
||||
expect(state.mcp_client_mirror.published.museReceivers.contactImportWakeVersion).toBe(1);
|
||||
expect(state.mcp_client_mirror.museRecords.find((record:{bindingId:string})=>record.bindingId===f.binding.id)).toMatchObject({state:"idle",item:null});},{timeout:15000,interval:50});
|
||||
const baseline=await contacts(),baselineCount=baseline.reduce((n,row)=>n+row.contacts,0),originalExpiry=(await db.select().from(bindings).where(eq(bindings.id,f.binding.id)))[0].qualificationExpiresAt;
|
||||
expect(originalExpiry).toBeInstanceOf(Date);
|
||||
let physicalContacts = 0;
|
||||
const publicPresence = () => new Promise<void>((resolve, reject) => {
|
||||
// Exercise the actual Cloud public-host ingress, not the App URL mapper.
|
||||
const sent = nodeRequest(new URL("/api/muse/v1/signal", cloudLoopback), {
|
||||
headers: { host: new URL(oauthOrigin).host, "x-paperclip-muse-binding": f.binding.id },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
}, response => {
|
||||
const parts: Buffer[] = []; let bytes = 0;
|
||||
response.on("data", part => { bytes += part.length; if (bytes > 65536) return response.destroy(new Error("Bounded presence response exceeded")); parts.push(Buffer.from(part)); });
|
||||
response.on("error", reject); response.on("end", () => {
|
||||
try { expect(response.statusCode).toBe(200); expect(JSON.parse(Buffer.concat(parts).toString())).toEqual({version:1,signal:null}); physicalContacts++; resolve(); }
|
||||
catch (error) { reject(error); }
|
||||
});
|
||||
}); sent.on("error", reject); sent.end();
|
||||
});
|
||||
const custodyContactCount = (state: Awaited<ReturnType<typeof cloudState>>) => state.muse_receiver_contacts.epochs.reduce(
|
||||
(sum: number, epoch: {rows: {bucket: {contacts: number}}[]}) => sum + epoch.rows.reduce((n, row) => n + row.bucket.contacts, 0), 0);
|
||||
const physicalQuiet = async () => {
|
||||
const before = await cloudState(), beforeHints = wakeHints, beforeQueries = appQueries, started = Date.now();
|
||||
for (let tick = 0; tick < 19; tick++) {
|
||||
await publicPresence();
|
||||
expect(wakeHints).toBe(beforeHints); expect(appQueries).toBe(beforeQueries);
|
||||
if (tick < 18) await new Promise<void>(resolve => setTimeout(resolve, 5000));
|
||||
}
|
||||
expect(Date.now() - started).toBeGreaterThanOrEqual(90_000);
|
||||
expect(custodyContactCount(await cloudState()) - custodyContactCount(before)).toBe(19);
|
||||
expect((await db.select().from(bindings).where(eq(bindings.id,f.binding.id)))[0].qualificationExpiresAt).toEqual(originalExpiry);
|
||||
};
|
||||
if (physicalCadence) await physicalQuiet();
|
||||
const preceding = await cloudState(), precedingPending = pending(preceding), physicalBeforePressure = physicalContacts;
|
||||
// Explicit normal-store pressure admissions are distinct from the real
|
||||
// wall-clock contact stream. No SQL state, capability or ACK is stamped.
|
||||
armLostAck=true;const at=Date.now()-24*30000-(physicalCadence?90_000:0);for(let i=0;i<24;i++)await store.signal(namespace,f.binding.id,at+i*30000);
|
||||
const pressureBefore=await cloudState();expect(pending(pressureBefore)).toBe(precedingPending+24);
|
||||
const projected=(await pool.query(`${pressureModule.MUSE_CONTACT_PRESSURE_CTE} SELECT * FROM eligible WHERE stack_id=$13`,[...pressureModule.museContactPressureParameters(limits),stackId])).rows[0];
|
||||
expect(Number(projected.floor_rows)).toBeGreaterThan(limits.stack.museContactRows/2);
|
||||
expect(projected.low_watermark_met).toBe(false);expect(projected.admission_headroom).toBe(true);expect(projected.eligible).toBe(true);
|
||||
await vi.waitFor(()=>{expect(wakeHints).toBeGreaterThan(0);},{timeout:45000,interval:50});await vi.waitFor(()=>{expect(firstAckEntered).toBe(true);},{timeout:15000,interval:25});
|
||||
expect(pending(await cloudState())).toBe(pending(pressureBefore));expect(ackCommits).toBe(0);
|
||||
// 202 is only a wake hint. Actual import has committed while Cloud ACK is withheld.
|
||||
const committedBeforeAck=await contacts();expect(committedBeforeAck.reduce((n,row)=>n+row.contacts,0)).toBeGreaterThan(baselineCount);
|
||||
const arrival=await mapped(oauthOrigin+"/api/muse/v1/signal",{headers:{"X-Paperclip-Muse-Binding":f.binding.id}});
|
||||
expect(arrival.status).toBe(200);expect(await arrival.json()).toEqual({version:1,signal:null});releaseAck();
|
||||
await vi.waitFor(()=>{expect(ackCommits).toBe(1);expect(lostAckObserved).toBe(true);},{timeout:15000,interval:25});
|
||||
await stopApp();await cloud.stopBackgroundTasks();await close(cloudServer);cloudServer=undefined;
|
||||
for(const restore of restorers.splice(0).reverse())restore();await registry.close();
|
||||
registry=await registryModule.PostgresCloudHarnessRegistry.connect({connectionString:cloudUrl,maxConnections:2,runMigrations:false});
|
||||
store=await makeCloud();await makeApp();
|
||||
await vi.waitFor(async()=>{
|
||||
const state=await cloudState();expect(pending(state)).toBe(0);
|
||||
const [local]=await db.select().from(mcpClientMirrorState).where(eq(mcpClientMirrorState.id,"public"));
|
||||
const receipt=mcpClientMirrorReceiptSchema.parse(local.receipt);expect(receipt).toEqual(state.mcp_client_mirror.published);expect(receipt.revision).toBe(local.revision);
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
},{timeout:15000,interval:50});
|
||||
const imported=await contacts();expect(imported.reduce((n,row)=>n+row.contacts,0)).toBe(baselineCount+25+physicalBeforePressure);
|
||||
expect((await db.select().from(bindings).where(eq(bindings.id,f.binding.id)))[0].qualificationExpiresAt).toEqual(originalExpiry);
|
||||
const drained=await cloudState();expect(drained.mcp_import_usage.museContactRows).toBe(98);
|
||||
expect(limits.stack.museContactRows-drained.mcp_import_usage.museContactRows).toBeGreaterThanOrEqual(3);
|
||||
expect(limits.stack.museContactBytes-drained.mcp_import_usage.museContactBytes).toBeGreaterThanOrEqual(8192);
|
||||
expect(drained.muse_receiver_contacts.epochs[0].sourceId).toBe(retained.muse_receiver_contacts.epochs[0].sourceId);
|
||||
for(const record of historicalRecords)expect(drained.muse_receiver_contacts.epochs[0].lastContacts[record.bindingId+":1"])
|
||||
.toBe(retained.muse_receiver_contacts.epochs[0].lastContacts[record.bindingId+":1"]);
|
||||
const hintCount=wakeHints,queries=appQueries;
|
||||
if (physicalCadence) await physicalQuiet();
|
||||
else await new Promise(resolve=>setTimeout(resolve,15000));
|
||||
expect(wakeHints).toBe(hintCount);expect(appQueries).toBe(queries);expect(await contacts()).toEqual(imported);
|
||||
passed=true;
|
||||
} finally {
|
||||
releaseAck();const failures:unknown[]=[];
|
||||
for(const join of [stopApp,()=>cloud?.stopBackgroundTasks(),()=>close(cloudServer),
|
||||
...restorers.reverse().map(restore=>async()=>restore()),()=>registry?.close(),()=>pool.end(),
|
||||
()=>museReceiver(f.receiverOwner).stop(),()=>f.receiverOwner.$client.end({timeout:1}),
|
||||
()=>db.delete(runtimeInstanceSettings).where(eq(runtimeInstanceSettings.singletonKey,"cloud-runtime-identity/v1"))]) {
|
||||
try {await join();}catch(error){failures.push(error);}
|
||||
}
|
||||
resetCloudRuntimeIdentityForTests();vi.unstubAllGlobals();vi.unstubAllEnvs();
|
||||
if(passed&&!failures.length)removeTestHome(home);
|
||||
if(failures.length)throw new AggregateError(failures,"Paired Muse owners did not all close");
|
||||
}
|
||||
}
|
||||
it("imports above-LOW retained-history pressure through the normal App owner and preserves a lost ACK", () => coupledMuseContactRecovery(false), 120000);
|
||||
it("keeps actual five-second Cloud presence tenant-SQL-quiet for90s before and after pressure import with exact ACK recovery", () => coupledMuseContactRecovery(true), 300000);
|
||||
|
||||
async function applyActualManagedContactIdentity() {
|
||||
expect(getCloudRuntimeIdentity()).toBeNull();
|
||||
expect(await db.select().from(runtimeInstanceSettings).where(eq(runtimeInstanceSettings.singletonKey,"cloud-runtime-identity/v1"))).toEqual([]);
|
||||
const key=generateKeyPairSync("ed25519"),kid="late-contact-source",stackId="late-contact-"+randomUUID(),issued=Math.floor(Date.now()/1000);
|
||||
const env={...process.env,PAPERCLIP_CLOUD_STACK_ID:stackId,PAPERCLIP_PUBLIC_URL:oauthOrigin,
|
||||
PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS:JSON.stringify({keys:[{...key.publicKey.export({format:"jwk"}),kid,alg:"EdDSA",use:"sig"}]})};
|
||||
await initializeCloudRuntimeIdentity(db,env);
|
||||
const encode=(value:unknown)=>Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
const body=encode({alg:"EdDSA",typ:"paperclip-cloud-runtime-identity+jwt",kid})+"."+encode({v:1,iss:"paperclip-cloud",aud:"paperclip-runtime-identity/v1",sub:stackId,
|
||||
claimId:randomUUID(),previousOrigin:oauthOrigin,canonicalOrigin:oauthOrigin,stackSlug:"paperclip",iat:issued,exp:issued+60});
|
||||
await applyCloudRuntimeIdentityAssertion({db,env,compactJws:body+"."+sign(null,Buffer.from(body),key.privateKey).toString("base64url")});
|
||||
expect(getCloudRuntimeIdentity()?.canonicalOrigin).toBe(oauthOrigin);
|
||||
return async()=>{await db.delete(runtimeInstanceSettings).where(eq(runtimeInstanceSettings.singletonKey,"cloud-runtime-identity/v1"));resetCloudRuntimeIdentityForTests();};
|
||||
}
|
||||
it("managed late HTTP success after empty handoff already has durable contact before stop or reconstruction",async()=>{
|
||||
const f=await actualReadyContact(),reset=await applyActualManagedContactIdentity(),receiver=museReceiver(f.receiverOwner);
|
||||
const read=()=>db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
const before=await read(),total=(rows:Awaited<ReturnType<typeof read>>)=>rows.reduce((sum,row)=>sum+row.contacts,0);
|
||||
let release!:()=>void,arrived!:()=>void;const gate=new Promise<void>(resolve=>{release=resolve;}),atIngress=new Promise<void>(resolve=>{arrived=resolve;});
|
||||
const app=express();app.use(idleAdmissionMiddleware);app.use(async(_req,_res,next)=>{arrived();await gate;next();});
|
||||
app.use(museTransportRoutes(f.receiverOwner,oauthOrigin));app.use(errorHandler);trackIdleRequestHandlers(app);
|
||||
const pending=request(app).get("/api/muse/v1/signal").set("X-Paperclip-Muse-Binding",f.binding.id).then(response=>response);
|
||||
try {
|
||||
await atIngress;await receiver.prepareHostedHandoff(new AbortController().signal);expect(await read()).toEqual(before);
|
||||
release();const response=await pending;expect(response.status).toBe(200);expect(response.body).toEqual({version:1,signal:null});
|
||||
const saved=await read();expect(total(saved)).toBe(total(before)+1);
|
||||
await receiver.stop();expect(await read()).toEqual(saved);
|
||||
const reconstructed=createDb(externalDatabaseUrl??temporary!.connectionString,{maxConnections:1});
|
||||
try {const next=museReceiver(reconstructed);next.start();await next.stop();expect(await read()).toEqual(saved);}
|
||||
finally {await reconstructed.$client.end({timeout:1});}
|
||||
} finally {release();await pending;await receiver.stop();await f.receiverOwner.$client.end({timeout:1});await reset();}
|
||||
},15000);
|
||||
it("managed late persistence failure rejects HTTP and stop until same owner repairs its exact retained contact",async()=>{
|
||||
const f=await actualReadyContact(),reset=await applyActualManagedContactIdentity();let transactions=0,failPersistence=true;
|
||||
const owner=new Proxy(f.receiverOwner,{get(target,key,receiver){if(key!=="transaction")return Reflect.get(target,key,receiver);return async(...args:Parameters<typeof db.transaction>)=>{
|
||||
if(transactions++>0&&failPersistence)throw new Error("controlled managed contact persistence outage");return Reflect.apply(target.transaction,target,args);
|
||||
};}});
|
||||
const receiver=museReceiver(owner),app=express();app.use(museTransportRoutes(owner,oauthOrigin));app.use(errorHandler);
|
||||
const read=()=>db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
const before=await read(),total=(rows:Awaited<ReturnType<typeof read>>)=>rows.reduce((sum,row)=>sum+row.contacts,0);
|
||||
try {
|
||||
await receiver.prepareHostedHandoff(new AbortController().signal);
|
||||
const response=await request(app).get("/api/muse/v1/signal").set("X-Paperclip-Muse-Binding",f.binding.id);
|
||||
expect(response.status).toBe(500);expect(await read()).toEqual(before);
|
||||
await expect(receiver.stop()).rejects.toThrow("Muse receiver contact persistence is incomplete.");expect(await read()).toEqual(before);
|
||||
failPersistence=false;receiver.start();await receiver.stop();const saved=await read();expect(total(saved)).toBe(total(before)+1);
|
||||
expect(saved.filter(row=>!before.some(old=>old.id===row.id)).every(row=>row.incomplete)).toBe(true);
|
||||
receiver.start();await receiver.stop();expect(await read()).toEqual(saved);
|
||||
} finally {failPersistence=false;await receiver.stop();await museReceiver(f.receiverOwner).stop();await f.receiverOwner.$client.end({timeout:1});await reset();}
|
||||
},15000);
|
||||
it("hosted handoff joins existing signal custody without stopping the receiver",async()=>{
|
||||
const f=await fixture(false);let entered!:()=>void,release!:()=>void;
|
||||
const inside=new Promise<void>(resolve=>{entered=resolve;}),gate=new Promise<void>(resolve=>{release=resolve;});
|
||||
const owner=new Proxy(db,{get(target,key,receiver){
|
||||
if(key!=="transaction")return Reflect.get(target,key,receiver);
|
||||
return async(...args:Parameters<typeof db.transaction>)=>{entered();await gate;return Reflect.apply(target.transaction,target,args);};
|
||||
}});
|
||||
const receiver=museReceiver(owner),contact=receiver.signal(f.binding.id);await inside;
|
||||
const handoff=receiver.prepareHostedHandoff(new AbortController().signal);release();await contact;await handoff;
|
||||
const first=await db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
expect(first.reduce((count,row)=>count+row.contacts,0)).toBe(1);
|
||||
await receiver.signal(f.binding.id);await receiver.prepareHostedHandoff(new AbortController().signal);
|
||||
const second=await db.select().from(museReceiverContactBuckets).where(eq(museReceiverContactBuckets.bindingId,f.binding.id));
|
||||
expect(second.reduce((count,row)=>count+row.contacts,0)).toBe(2);await receiver.stop();
|
||||
});
|
||||
it("keeps expired public readiness quiet after an acknowledged item becomes eligible for rearm",async()=>{
|
||||
const f=await fixture();
|
||||
const state=(await f.broker.bindingForAgent(f.company.id,f.agent.id))!;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { notifyMuseContactVerification } from "../modules/external-agents/index.js";
|
||||
import { prepareMuseReceiverAuthorityMutation, notifyMuseContactVerification } from "../modules/external-agents/index.js";
|
||||
import { idleApiActivity } from "../services/idle-api-activity.js";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
import type { Request, RequestHandler } from "express";
|
||||
@@ -675,6 +675,9 @@ async function resolveCloudTenantActorOnce(
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.principalId, userId),
|
||||
)).for("update");
|
||||
if (!existing || existing.status !== "active" || existing.membershipRole !== membershipRole) {
|
||||
await prepareMuseReceiverAuthorityMutation(tx, { companyId, operatorId: userId });
|
||||
}
|
||||
// Serialize authority restoration and its notice while retaining the
|
||||
// guarded upsert that leaves unchanged memberships untouched.
|
||||
if (!existing || existing.status !== "active" || existing.membershipRole === "viewer") {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { and,eq,sql,type SQL } from "drizzle-orm";
|
||||
import { museAgentBindings as bindings,agents,companies,type Db } from "@paperclipai/db";
|
||||
import type { IdleDeadlineSnapshot } from "../../services/idle-deadline-types.js";
|
||||
import type { McpClientMirrorReceipt } from "../../services/public-mcp/client-mirror-contract.js";
|
||||
import type { IdleMcpInspectionBudget,IdleMcpWakeProof } from "../../services/public-mcp/idle-wake-proof.js";
|
||||
import { idleExternalAgentHistoryChecks } from "./idle-history-proof.js";
|
||||
import { readMuseReceiverProjection } from "./muse-hosted-projection.js";
|
||||
export interface IdleMuseReceiverProof extends IdleDeadlineSnapshot {
|
||||
coveredBindings:Array<{id:string;generation:number;grantId:string|null;retired:boolean}>;
|
||||
}
|
||||
/** A current full ACK plus a fresh current-auth projection, never a flag alone. */
|
||||
export async function readIdleMuseReceiverProof(tx:Pick<Db,"select">,context:{enabled:boolean;contactImportWakeVersion?:1;namespace?:{stackId:string;instanceId:string;origin:string};receipt?:McpClientMirrorReceipt;now:number;budget:IdleMcpInspectionBudget}):Promise<IdleMuseReceiverProof>{
|
||||
const blocked=(state:string):IdleMuseReceiverProof=>({blocked:true,state,deadlines:[],coveredBindings:[]});
|
||||
if(!context.enabled)return {blocked:false,state:"disabled",deadlines:[],coveredBindings:[]};
|
||||
const {namespace,receipt}=context;
|
||||
if(context.contactImportWakeVersion!==1||receipt?.museReceivers?.contactImportWakeVersion!==1)return blocked("missing-muse-contact-import-wake");
|
||||
if(!namespace||!receipt?.enabled||receipt.instanceId!==namespace.instanceId||receipt.origin!==namespace.origin||!receipt.museReceivers)return blocked("missing-muse-receiver-owner");
|
||||
const projection=await readMuseReceiverProjection(tx,namespace,receipt.revision,{enabled:true,contactImportWakeVersion:context.contactImportWakeVersion,beforeRead:context.budget.beforeRead,check:context.budget.check});
|
||||
if(!projection.complete)return blocked("pending-muse-receiver-setup");
|
||||
if(JSON.stringify(projection.reference)!==JSON.stringify(receipt.museReceivers))return blocked("changed-muse-receiver-owner");
|
||||
await context.budget.beforeRead();
|
||||
const rows=await tx.select({id:bindings.id,generation:bindings.generation,grantId:bindings.grantId,pairedAt:bindings.pairedAt,agentExists:agents.id,companyExists:companies.id}).from(bindings)
|
||||
.leftJoin(agents,and(eq(agents.id,bindings.agentId),eq(agents.companyId,bindings.companyId))).leftJoin(companies,eq(companies.id,bindings.companyId)).limit(1001);context.budget.check();
|
||||
if(rows.length!==projection.records.length)return blocked("changed-muse-receiver-count");
|
||||
const coveredBindings:IdleMuseReceiverProof["coveredBindings"]=[],deadlines:number[]=[];
|
||||
for(const row of rows){
|
||||
if(!row.agentExists||!row.companyExists)return blocked("orphaned-muse-receiver");
|
||||
const record=projection.records.find(record=>record.bindingId===row.id&&record.generation===row.generation);
|
||||
if(!record)return blocked("changed-muse-receiver-generation");
|
||||
if(record.item)return blocked("pending-muse-mailbox");
|
||||
if(record.state!=="retired"&&record.qualificationExpiresAt!==null){if(record.qualificationExpiresAt<=context.now)return blocked("due-muse-qualification");deadlines.push(record.qualificationExpiresAt);}
|
||||
if(row.pairedAt)coveredBindings.push({id:row.id,generation:row.generation,grantId:row.grantId,retired:record.state==="retired"});
|
||||
}
|
||||
return {blocked:false,state:["hosted-muse-v1",projection.reference,coveredBindings],deadlines,coveredBindings};
|
||||
}
|
||||
/** Replace only the exact covered binding rows. Unknown legacy credentials,
|
||||
* assignments, effects, mailboxes, input and stop holds retain their old checks. */
|
||||
export function idleMuseWorkQuery(reason:string,proof:IdleMuseReceiverProof|undefined,ingress:IdleMcpWakeProof|undefined):SQL|undefined{
|
||||
if(reason!=="muse_agent_bindings"||!proof||proof.blocked||!ingress)return;
|
||||
const covered=proof.coveredBindings.filter(row=>row.retired||row.grantId!==null&&ingress.grantIds.includes(row.grantId));
|
||||
if(!covered.length)return;
|
||||
const original=idleExternalAgentHistoryChecks.find(check=>check.reason==="muse_agent_bindings");if(!original)return;
|
||||
return sql`${sql.raw(original.query)} AND NOT (${sql.join(covered.map(row=>sql`(b.id=${row.id}::uuid AND b.generation=${row.generation})`),sql` OR `)})`;
|
||||
}
|
||||
@@ -21,3 +21,13 @@ export function createDotPrincipalHttp(oauth: Parameters<typeof dotPrincipalCont
|
||||
}
|
||||
|
||||
export { notifyMuseContactVerification, pendingMuseContactVerifications, parseMuseVerificationHint, type MuseVerificationScope } from "./muse-verification-work.js";
|
||||
|
||||
export { museReceiverReferenceSchema,museReceiverRecordSchema,museReceiverGeneration,type MuseReceiverReference,type MuseReceiverRecord } from "./muse-hosted-contract.js";
|
||||
export { prepareMuseReceiverMutation,prepareMuseReceiverAuthorityMutation,readMuseReceiverProjection } from "./muse-hosted-projection.js";
|
||||
export { syncMuseContactCustody } from "./muse-hosted-sync.js";
|
||||
|
||||
export { recoverMuseReceiverContinuity } from "./muse-hosted-continuity.js";
|
||||
|
||||
export { readIdleMuseReceiverProof,idleMuseWorkQuery,type IdleMuseReceiverProof } from "./idle-muse-receiver-proof.js";
|
||||
|
||||
export { museReceiverDiscoveryDocument,isMuseReceiverDiscoveryRequest } from "./muse-hosted-discovery.js";
|
||||
@@ -0,0 +1,32 @@
|
||||
import { notifyMuseContactVerification } from "./muse-verification-work.js";
|
||||
import { and,eq,sql } from "drizzle-orm";
|
||||
import { museAgentBindings as bindings,museReceiverContactBuckets as buckets,agents,type Db } from "@paperclipai/db";
|
||||
import { museContactPageSchema,museContactPageDigest,sameMuseNamespace,type MuseHostedNamespace } from "./muse-hosted-contract.js";
|
||||
/** Validate and commit immutable chunks before the existing connector sends their exact ACK. */
|
||||
export async function importMuseContactPage(db:Db,namespace:MuseHostedNamespace,value:unknown) {
|
||||
const page=museContactPageSchema.parse(value);
|
||||
const {digest,...unsigned}=page;
|
||||
if(!sameMuseNamespace(page.recipientNamespace,namespace)||page.namespace.stackId!==namespace.stackId||page.namespace.origin!==namespace.origin||museContactPageDigest(unsigned)!==digest||page.through!== (page.entries.at(-1)?.sequence??page.after)
|
||||
||page.entries.some((entry,index)=>entry.sequence!==page.after+index+1))throw new Error("Muse contact page changed");
|
||||
await db.transaction(async tx=>{
|
||||
for(const {bucket} of page.entries) {
|
||||
const [candidate]=await tx.select().from(bindings).where(and(eq(bindings.id,bucket.bindingId),eq(bindings.companyId,bucket.companyId)));
|
||||
if(!candidate)throw new Error("Muse contact binding is unavailable");
|
||||
const [agent]=await tx.select({id:agents.id}).from(agents).where(and(eq(agents.id,candidate.agentId),eq(agents.companyId,bucket.companyId))).for("update");
|
||||
if(!agent)throw new Error("Muse contact agent is unavailable");
|
||||
const [binding]=await tx.select().from(bindings).where(and(eq(bindings.id,bucket.bindingId),eq(bindings.companyId,bucket.companyId),eq(bindings.agentId,agent.id))).for("update");
|
||||
if(!binding||bucket.generation>binding.generation)throw new Error("Muse contact binding generation is unavailable");
|
||||
const row={companyId:bucket.companyId,bindingId:bucket.bindingId,bindingGeneration:bucket.generation,replicaId:bucket.id,bucketAt:new Date(bucket.bucketAt),firstAt:new Date(bucket.firstAt),lastAt:new Date(bucket.lastAt),contacts:bucket.contacts,gapsAtMostSevenSeconds:bucket.gapsAtMostSevenSeconds,maxGapMs:bucket.maxGapMs,timestamps:bucket.timestamps.map(at=>new Date(at).toISOString()),incomplete:bucket.incomplete};
|
||||
const old=await tx.select().from(buckets).where(and(eq(buckets.bindingId,row.bindingId),eq(buckets.bindingGeneration,row.bindingGeneration),eq(buckets.replicaId,row.replicaId),eq(buckets.bucketAt,row.bucketAt))).for("update");
|
||||
if(old.length){
|
||||
const prior=old[0]!;
|
||||
if(prior.contacts!==row.contacts||prior.firstAt.getTime()!==row.firstAt.getTime()||prior.lastAt.getTime()!==row.lastAt.getTime()||prior.gapsAtMostSevenSeconds!==row.gapsAtMostSevenSeconds||prior.maxGapMs!==row.maxGapMs||JSON.stringify(prior.timestamps)!==JSON.stringify(row.timestamps)||prior.incomplete!==row.incomplete)throw new Error("Muse contact chunk is not immutable");
|
||||
} else {
|
||||
if(binding.generation===row.bindingGeneration&&!binding.revokedAt)await notifyMuseContactVerification(tx,{companyId:row.companyId,bindingId:row.bindingId,generation:row.bindingGeneration},"contact-persist");
|
||||
await tx.insert(buckets).values(row);
|
||||
}
|
||||
await tx.update(bindings).set({receiverContactAt:sql`greatest(${bindings.receiverContactAt},${row.lastAt.toISOString()}::timestamptz)`}).where(and(eq(bindings.id,row.bindingId),eq(bindings.generation,row.bindingGeneration)));
|
||||
}
|
||||
});
|
||||
return {sourceId:page.sourceId,after:page.after,through:page.through,digest};
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { and,eq,gt,isNotNull,isNull } from "drizzle-orm";
|
||||
import { museAgentBindings as bindings,type Db } from "@paperclipai/db";
|
||||
import { getCloudRuntimeIdentity } from "../../services/cloud-runtime-identity.js";
|
||||
import { createPaperclipCloudConnector,paperclipCloudConnectorConfigFromEnv } from "../../services/paperclip-cloud-connector.js";
|
||||
import { instanceSettingsService } from "../../services/instance-settings.js";
|
||||
import { syncMuseContactCustody } from "./muse-hosted-sync.js";
|
||||
import { readMuseReceiverProjection } from "./muse-hosted-projection.js";
|
||||
import { sameMuseNamespace } from "./muse-hosted-contract.js";
|
||||
/** One bounded startup reconciliation; no timer or cached allow decision. */
|
||||
export async function recoverMuseReceiverContinuity(db:Db,signal:AbortSignal):Promise<ReadonlyMap<string,number>> {
|
||||
const none=new Map<string,number>(),identity=getCloudRuntimeIdentity(),config=paperclipCloudConnectorConfigFromEnv();
|
||||
if(!identity||!config||!identity.canonicalOrigin)return none;
|
||||
const flags=await instanceSettingsService(db).getExperimentalReadOnly();
|
||||
if(!flags.enableMuse||!flags.enableNativeRunner)return none;
|
||||
const [qualification]=await db.select({id:bindings.id}).from(bindings).where(and(isNull(bindings.revokedAt),isNotNull(bindings.pairedAt),gt(bindings.qualificationExpiresAt,new Date()))).limit(1);
|
||||
if(!qualification)return none;
|
||||
const namespace={stackId:identity.stackId,instanceId:config.instanceId,origin:identity.canonicalOrigin};
|
||||
const connector=createPaperclipCloudConnector({config});
|
||||
const ownership=await syncMuseContactCustody(db,namespace,body=>connector.syncMuseReceiverContacts(body),signal);
|
||||
if(ownership.state==="pending")throw new Error("Muse receiver continuity awaits its current publication");
|
||||
if(ownership.state!=="owned")return none;
|
||||
if(!sameMuseNamespace(ownership.namespace,namespace))throw new Error("Muse receiver continuity namespace changed");
|
||||
// Recompute from CURRENT authorization and generation. A remembered ACK or
|
||||
// enabled flag alone cannot suppress the normal lost-memory marker.
|
||||
const current=await readMuseReceiverProjection(db,namespace,ownership.revision,{enabled:true,contactImportWakeVersion:ownership.reference.contactImportWakeVersion});
|
||||
if(!current.complete)return none;
|
||||
if(JSON.stringify(current.reference)!==JSON.stringify(ownership.reference))return none;
|
||||
return new Map(current.records.filter(row=>row.state!=="retired").map(row=>[row.bindingId,row.generation]));
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
museHostedNamespaceSchema, museReceiverRecordSchema,
|
||||
type MuseHostedNamespace, type MuseReceiverRecord, type MuseContactPage,
|
||||
} from "@paperclipai/shared";
|
||||
export {
|
||||
museHostedNamespaceSchema, museReceiverRecordSchema, museReceiverReferenceSchema,
|
||||
museContactBucketSchema, museContactPageSchema, museContactExchangeSchema, museReceiverOwnershipSchema,
|
||||
type MuseHostedNamespace, type MuseReceiverRecord, type MuseReceiverReference,
|
||||
type MuseContactBucket, type MuseContactPage, type MuseReceiverOwnership,
|
||||
} from "@paperclipai/shared";
|
||||
|
||||
export function museReceiverGeneration(namespace:MuseHostedNamespace,revision:number,records:readonly MuseReceiverRecord[]) {
|
||||
if(!Number.isSafeInteger(revision)||revision<0)throw new Error("Invalid Muse receiver revision");
|
||||
const rows=records.map(row=>museReceiverRecordSchema.parse(row)).sort((a,b)=>Buffer.compare(Buffer.from(a.bindingId),Buffer.from(b.bindingId)));
|
||||
if(rows.length>1000||new Set(rows.map(row=>row.bindingId)).size!==rows.length)throw new Error("Muse receiver projection is incomplete");
|
||||
return createHash("sha256").update(JSON.stringify(["paperclip-hosted-muse-v1",museHostedNamespaceSchema.parse(namespace),revision,rows])).digest("hex");
|
||||
}
|
||||
export function museContactPageDigest(page:Omit<MuseContactPage,"digest">) {
|
||||
return createHash("sha256").update(JSON.stringify(["paperclip-muse-contact-page-v1",page.version,page.namespace,page.recipientNamespace,page.sourceId,page.after,page.through,page.entries])).digest("hex");
|
||||
}
|
||||
export function sameMuseNamespace(a:MuseHostedNamespace,b:MuseHostedNamespace){return a.stackId===b.stackId&&a.instanceId===b.instanceId&&a.origin===b.origin;}
|
||||
export const MUSE_CONTACT_POLICY=Object.freeze({stackRows:20_000,globalRows:100_000,stackBytes:16*1_048_576,globalBytes:256*1_048_576});
|
||||
// Fixed admission policy, not a measured capacity. Never discard an unacknowledged contact.
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Exact existing Muse metadata. No personal-MCP issuer or device grant is invented. */
|
||||
export function museReceiverDiscoveryDocument(input:{origin:string;authorizationOrigin:string}){
|
||||
const path="/api/muse/v1/oauth",issuer=input.origin+path;
|
||||
return {path:path+"/metadata",document:{issuer,authorization_endpoint:input.authorizationOrigin+path+"/authorize",token_endpoint:issuer+"/token",registration_endpoint:issuer+"/register",revocation_endpoint:issuer+"/revoke",
|
||||
resource:input.origin+"/api/muse/v1",scopes_supported:["paperclip:agent","offline_access"],grant_types_supported:["authorization_code","refresh_token"],response_types_supported:["code"],token_endpoint_auth_methods_supported:["none"],code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:true}};
|
||||
}
|
||||
export function isMuseReceiverDiscoveryRequest(request:{method?:string;url?:string}){
|
||||
return ["GET","HEAD"].includes(request.method??"")&&request.url==="/api/muse/v1/oauth/metadata";
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { and,asc,eq,inArray,isNull,sql,or,isNotNull } from "drizzle-orm";
|
||||
import { museAgentBindings as bindings,museMailboxItems as mailbox,museRunnerAssignments as assignments,externalAgentHolds as holds,type Db } from "@paperclipai/db";
|
||||
import { inspectMuseConnectionCredential,assertMuseReceiverAuthority,assertMuseCurrentAuthority,museStopControlBoundaryIds,hasMuseStopControlAccess } from "../../services/muse-identity.js";
|
||||
import { canConfigureAgentConnection } from "../agent-lifecycle/index.js";
|
||||
import { HttpError } from "../../errors.js";
|
||||
import { getCloudRuntimeIdentity } from "../../services/cloud-runtime-identity.js";
|
||||
import { prepareMcpClientMutation,type McpClientMutationDatabase } from "../../services/public-mcp/client-mirror-mutations.js";
|
||||
import { museReceiverGeneration,type MuseHostedNamespace,type MuseReceiverRecord } from "./muse-hosted-contract.js";
|
||||
/** Same outer producer transaction, before its mailbox/authority write. No stale eligibility filter. */
|
||||
export async function prepareMuseReceiverMutation(tx:McpClientMutationDatabase) {
|
||||
if(getCloudRuntimeIdentity())await prepareMcpClientMutation(tx);
|
||||
}
|
||||
/** Hints target only a bound affected identity. Old eligibility is never used to suppress a restoration. */
|
||||
export async function prepareMuseReceiverAuthorityMutation(tx:McpClientMutationDatabase,scope:{companyId?:string;agentId?:string;operatorId?:string}={}) {
|
||||
if(!getCloudRuntimeIdentity())return;
|
||||
const [binding]=await tx.select({id:bindings.id}).from(bindings).where(and(
|
||||
scope.companyId?eq(bindings.companyId,scope.companyId):undefined,scope.agentId?eq(bindings.agentId,scope.agentId):undefined,scope.operatorId?eq(bindings.operatorId,scope.operatorId):undefined,
|
||||
or(isNotNull(bindings.pairedAt),isNotNull(bindings.receiverContactAt)),or(isNull(bindings.revokedAt),isNull(bindings.detectorRemovedAt)))).limit(1);
|
||||
if(binding)await prepareMcpClientMutation(tx);
|
||||
}
|
||||
/** No contact is recorded and no worker subject fabricated by this projection. */
|
||||
export async function readMuseReceiverProjection(db:Pick<Db,"select">,namespace:MuseHostedNamespace,revision:number,options:{enabled:boolean;contactImportWakeVersion?:1;beforeRead?:()=>Promise<void>;check?:()=>void}) {
|
||||
await options.beforeRead?.();
|
||||
const rows=await db.select().from(bindings).orderBy(asc(bindings.id)).limit(1001);
|
||||
if(rows.length>1000)throw new Error("Muse receiver projection exceeds its bounded declaration");
|
||||
// An incomplete setup is parked on its existing contact/verification producer;
|
||||
// it must neither receive a full custody ACK nor keep a 5s mirror retry alive.
|
||||
if(rows.some(b=>b.pairedAt&&!b.revokedAt&&(b.status!=="ready"||!b.receiverContactAt||!b.verifiedReplyAt
|
||||
||b.qualificationExpiresAt&&b.qualificationExpiresAt<=new Date())))return {complete:false as const,records:[],reference:undefined};
|
||||
const records:MuseReceiverRecord[]=[];
|
||||
for(const b of rows) {
|
||||
options.check?.();
|
||||
const base={bindingId:b.id,companyId:b.companyId,agentId:b.agentId,operatorId:b.operatorId,generation:b.generation,qualificationExpiresAt:b.qualificationExpiresAt?.getTime()??null};
|
||||
if(!b.pairedAt||b.revokedAt){records.push({...base,state:"retired",item:null});continue;}
|
||||
|
||||
|
||||
const record=await (async()=>{
|
||||
const tx=db;
|
||||
await options.beforeRead?.();
|
||||
const [current]=await tx.select().from(bindings).where(and(eq(bindings.id,b.id),eq(bindings.generation,b.generation),isNull(bindings.revokedAt)));
|
||||
if(!current)throw new Error("Muse receiver source changed during publication");
|
||||
let agent;
|
||||
try {
|
||||
const credential=await inspectMuseConnectionCredential(tx,current,namespace.origin+"/api/muse/v1");
|
||||
if(credential.state==="pending"){await assertMuseCurrentAuthority(tx,current,true,true);return {...base,state:"idle" as const,item:null};}
|
||||
agent=await assertMuseReceiverAuthority(tx,current,namespace.origin+"/api/muse/v1");
|
||||
}catch(error){if(error instanceof HttpError&&[401,403,404,410].includes(error.status))return {...base,state:"retired" as const,item:null};throw error;}
|
||||
const disabled=!options.enabled;
|
||||
if(disabled&&!await hasMuseStopControlAccess(tx,current))return {...base,state:"idle" as const,item:null};
|
||||
const stopOnly=disabled||(agent.status==="paused"&&!canConfigureAgentConnection(agent));
|
||||
const boundaries=tx.select({boundary:holds.stopBoundary}).from(holds).where(inArray(holds.id,museStopControlBoundaryIds(tx,current)));
|
||||
const [selected]=await tx.select({item:mailbox}).from(mailbox).leftJoin(assignments,eq(assignments.id,mailbox.assignmentId)).where(and(eq(mailbox.bindingId,current.id),eq(mailbox.bindingGeneration,current.generation),
|
||||
stopOnly?and(eq(mailbox.kind,"authority_revoked"),sql`${mailbox.id} > ${current.workerCursor}`,inArray(sql`${mailbox.references}->'boundary'`,boundaries)):
|
||||
sql`((${mailbox.kind}='assignment' and ${assignments.claimedAt} is null and ${assignments.status}='offered') or (${mailbox.kind}='readiness_challenge' and ${!!current.challengeHash&&!!current.challengeExpiresAt&¤t.challengeExpiresAt>new Date()} and ${mailbox.id}>${current.workerCursor} and encode(sha256(convert_to(${mailbox.references}->>'nonce','UTF8')),'hex')=${current.challengeHash}) or (${mailbox.kind} not in ('assignment','readiness_challenge') and ${mailbox.id}>${current.workerCursor}))`)).orderBy(asc(mailbox.id)).limit(1);
|
||||
return {...base,state:selected?"available" as const:"idle" as const,item:selected?{sourceEventId:selected.item.sourceEventId,attempt:selected.item.signalAttempt,notifiedAt:selected.item.signalNotifiedAt?.getTime()??null,
|
||||
expiresAt:selected.item.kind==="readiness_challenge"?current.challengeExpiresAt!.getTime():null}:null};
|
||||
})();
|
||||
options.check?.();
|
||||
records.push(record);
|
||||
}
|
||||
return {complete:true as const,records,reference:{profile:"hosted-muse-v1" as const,generation:museReceiverGeneration(namespace,revision,records),count:records.length,...(options.contactImportWakeVersion===1?{contactImportWakeVersion:1 as const}:{})}};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { museContactExchangeSchema,type MuseHostedNamespace } from "./muse-hosted-contract.js";
|
||||
import { importMuseContactPage } from "./muse-hosted-contact-import.js";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
export async function syncMuseContactCustody(db:Db,namespace:MuseHostedNamespace,exchange:(serialized:string)=>Promise<unknown>,signal:AbortSignal) {
|
||||
// A pass is bounded; concrete remaining chunks stay in the existing queue via its caller's pending flag.
|
||||
const lastThrough=new Map<string,number>();
|
||||
for(let pageNumber=0;pageNumber<1000;pageNumber++){
|
||||
signal.throwIfAborted();const response=museContactExchangeSchema.parse(await exchange(JSON.stringify({version:1,operation:"read"}))),page=response.page;
|
||||
if(!page.entries.length)return response.ownership;
|
||||
if(page.through<=(lastThrough.get(page.sourceId)??-1))throw new Error("Muse contact import did not advance");
|
||||
lastThrough.set(page.sourceId,page.through);
|
||||
await importMuseContactPage(db,namespace,page);
|
||||
signal.throwIfAborted();await exchange(JSON.stringify({version:1,operation:"ack",page}));
|
||||
}
|
||||
throw new Error("Muse contact custody remains pending after bounded import");
|
||||
}
|
||||
|
||||
/** Existing read/commit/exact-ACK owner, joined before qualification evidence is
|
||||
* assessed. Hard expiry/revocation is enforced independently and never renewed.
|
||||
* This does not infer continuity from mirror revisions or produce task authority.
|
||||
*/
|
||||
export async function syncCurrentMuseContactEvidence(db:Db,signal:AbortSignal) {
|
||||
const {getCloudRuntimeIdentity}=await import("../../services/cloud-runtime-identity.js");
|
||||
const {createPaperclipCloudConnector,paperclipCloudConnectorConfigFromEnv}=await import("../../services/paperclip-cloud-connector.js");
|
||||
const identity=getCloudRuntimeIdentity();
|
||||
if(!identity)return;
|
||||
const config=paperclipCloudConnectorConfigFromEnv();
|
||||
if(!config||!identity.canonicalOrigin)throw new Error("Muse contact evidence awaits its current hosted owner");
|
||||
const namespace={stackId:identity.stackId,instanceId:config.instanceId,origin:identity.canonicalOrigin};
|
||||
const connector=createPaperclipCloudConnector({config});
|
||||
await syncMuseContactCustody(db,namespace,serialized=>connector.syncMuseReceiverContacts(serialized),signal);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { prepareMuseReceiverAuthorityMutation } from "./muse-hosted-projection.js";
|
||||
import { and, asc, eq, gt, isNotNull, isNull } from "drizzle-orm";
|
||||
import { agents, museAgentBindings as bindings, type Db } from "@paperclipai/db";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../services/delivery-work-notifications.js";
|
||||
@@ -43,13 +44,14 @@ export async function pendingMuseContactVerifications(
|
||||
}
|
||||
|
||||
export async function notifyMuseContactVerification(
|
||||
tx: Pick<Db, "select">,
|
||||
tx: Pick<Db, "select"|"insert"|"update"|"execute">,
|
||||
scope?: MuseVerificationScope,
|
||||
trigger: "authority" | "contact-persist" = "authority",
|
||||
): Promise<number> {
|
||||
if (trigger === "contact-persist" && (!scope?.bindingId || scope.generation === undefined)) {
|
||||
throw new Error("Muse contact intent requires its exact binding generation");
|
||||
}
|
||||
await prepareMuseReceiverAuthorityMutation(tx,scope);
|
||||
let after: string | undefined;
|
||||
let count = 0;
|
||||
while (true) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { prepareMuseReceiverMutation } from "./muse-hosted-projection.js";
|
||||
import { budgetServiceInTransaction } from "../../services/budgets.js";
|
||||
import { pendingMuseTerminalAssignmentCondition } from "./muse-terminal-settlement.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../services/delivery-work-notifications.js";
|
||||
@@ -110,6 +111,7 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
for(const a of live) {
|
||||
const [last]=await tx.select({id:operations.requestId}).from(operations).where(eq(operations.assignmentId,a.id)).orderBy(desc(operations.createdAt)).limit(1);
|
||||
const boundary:MuseStopBoundary={bindingId:b.id,generation:b.generation,assignmentId:a.id,runId:a.runId,turnId:a.turnId,assignmentRevision:a.revision,stopNonce:randomUUID(),operationBoundary:last?.id??null};
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(assignments).set({status:"fenced"}).where(eq(assignments.id,a.id));
|
||||
const [unresolved]=await tx.select({id:operations.id}).from(operations).where(and(eq(operations.assignmentId,a.id),inArray(operations.status,["dispatched","pending","unknown"]))).limit(1);
|
||||
if(a.claimedAt) await tx.insert(holds).values({companyId:b.companyId,agentId:b.agentId,provider:"muse",assignmentId:a.id,bindingId:b.id,bindingGeneration:b.generation,runId:a.runId,workerUnknown:true,nativeEffectsUnknown:!!unresolved,stopBoundary:boundary}).onConflictDoUpdate({target:[holds.provider,holds.assignmentId],set:{stopBoundary:boundary,workerUnknown:true,nativeEffectsUnknown:sql`${holds.nativeEffectsUnknown} or ${!!unresolved}`,releasedAt:null,updatedAt:new Date()}});
|
||||
@@ -125,6 +127,7 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
async function revokeBinding(tx:ExternalAdmissionTransaction,b:typeof bindings.$inferSelect,operatorId:string,reason:string,actorType:"user"|"system"="user") {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.museMaintenance, "*");
|
||||
const runs=await fence(tx,b,reason);
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(bindings).set({status:"revoked",revokedAt:new Date(),ticketHash:null,challengeHash:null,cleanupExpiresAt:new Date(Date.now()+MUSE_CLEANUP_TTL_MS),deadlineEnforcedAt:b.deadlineEnforcedAt??(b.qualificationExpiresAt&&b.qualificationExpiresAt<=new Date()?new Date():null),revision:b.revision+1,updatedAt:new Date()}).where(eq(bindings.id,b.id));
|
||||
await tx.update(credentials).set({revokedAt:new Date()}).where(and(eq(credentials.bindingId,b.id),inArray(credentials.kind,["access","refresh","signal"])));
|
||||
await tx.update(credentials).set({expiresAt:new Date(Date.now()+MUSE_CLEANUP_TTL_MS)}).where(and(eq(credentials.bindingId,b.id),inArray(credentials.kind,["cleanup","detector_cleanup"]),isNull(credentials.revokedAt)));
|
||||
@@ -132,7 +135,7 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
await logActivity(tx as unknown as Db,{companyId:b.companyId,actorType,actorId:operatorId,action:"muse.binding_revoked",entityType:"agent",entityId:b.agentId,details:{bindingId:b.id,generation:b.generation,authorizingUserId:b.operatorId,source:reason,externalStopConfirmed:false}});
|
||||
return runs;
|
||||
}
|
||||
const nativeBroker=createNativeExternalBroker<AgentConnectionSubject>(db,"muse",{enabled:database=>identity.enabled(database),expectedResource:connectionResource,
|
||||
const nativeBroker=createNativeExternalBroker<AgentConnectionSubject>(db,"muse",{prepareMailboxMutation:prepareMuseReceiverMutation,enabled:database=>identity.enabled(database),expectedResource:connectionResource,
|
||||
assertSubjectCredential:async(tx,s)=>{await assertMuseSubjectCredential(tx,s,s.credentialSource==="oauth"?connectionResource():undefined);},
|
||||
authorize:async(s,id,settled)=>{const {b,a}=await authorizeAssignment(s,id,settled);return {binding:b,assignment:a};}});
|
||||
const operation=nativeBroker.operation;
|
||||
@@ -175,13 +178,15 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
if(old) {
|
||||
if(old.id!==input.replaceBindingId||old.revision!==input.expectedRevision||old.operatorId!==input.operatorId)throw conflict("Invitation changed. Refresh before replacing its ticket.");
|
||||
replacedRuns=await fence(tx,old,"reconnect");
|
||||
await tx.update(bindings).set({status:"revoked",revokedAt:new Date(),cleanupExpiresAt:new Date(Date.now()+MUSE_CLEANUP_TTL_MS),ticketHash:null,revision:old.revision+1,updatedAt:new Date()}).where(eq(bindings.id,old.id));
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(bindings).set({status:"revoked",revokedAt:new Date(),cleanupExpiresAt:new Date(Date.now()+MUSE_CLEANUP_TTL_MS),ticketHash:null,revision:old.revision+1,updatedAt:new Date()}).where(eq(bindings.id,old.id));
|
||||
await tx.update(credentials).set({revokedAt:new Date()}).where(and(eq(credentials.bindingId,old.id),inArray(credentials.kind,["access","refresh","signal"])));
|
||||
await revokeOAuthAuthority(tx,old);
|
||||
await tx.update(credentials).set({expiresAt:new Date(Date.now()+MUSE_CLEANUP_TTL_MS)}).where(and(eq(credentials.bindingId,old.id),inArray(credentials.kind,["cleanup","detector_cleanup"]),isNull(credentials.revokedAt)));
|
||||
} else if(input.replaceBindingId)throw conflict("Invitation changed. Refresh before replacing its ticket.");
|
||||
const [latest]=await tx.select({generation:bindings.generation}).from(bindings).where(and(eq(bindings.companyId,input.companyId),eq(bindings.agentId,input.agentId))).orderBy(desc(bindings.generation)).limit(1);
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.museMaintenance, "*");
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
const [created]=await tx.insert(bindings).values({id:bindingId,companyId:input.companyId,agentId:input.agentId,operatorId:input.operatorId,generation:(latest?.generation??0)+1,ticketHash:museCredentialHash(ticket),ticketExpiresAt:new Date(Date.now()+MUSE_TICKET_TTL_MS)}).returning();
|
||||
await logActivity(tx as unknown as Db,{companyId:input.companyId,actorType:"user",actorId:input.operatorId,action:"muse.pairing_created",entityType:"agent",entityId:input.agentId,details:{bindingId:created!.id,generation:created!.generation}});
|
||||
await updateAgentConfigurationInTransaction(tx as unknown as Db,agent.id,{adapterConfig:{...agent.adapterConfig,museBindingId:created!.id}},{recordRevision:{createdByUserId:input.operatorId,source:"muse-pairing"}});
|
||||
@@ -228,8 +233,10 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
await assertMuseCurrentAuthority(tx,b,true);
|
||||
if(b.challengeHash&&b.challengeExpiresAt&&b.challengeExpiresAt>new Date())return {bindingId:b.id,generation:b.generation,revision:b.revision,expiresAt:b.challengeExpiresAt.toISOString(),status:"pending" as const};
|
||||
const expiry=new Date(Date.now()+10*60_000);
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(bindings).set({challengeHash:museCredentialHash(nonce),challengeExpiresAt:expiry,revision:b.revision+1,updatedAt:new Date()}).where(eq(bindings.id,b.id));
|
||||
await tx.insert(mailbox).values({companyId,bindingId:b.id,bindingGeneration:b.generation,kind:"readiness_challenge",sourceEventId:`muse-challenge:${randomUUID()}`,references:{nonce}});
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.insert(mailbox).values({companyId,bindingId:b.id,bindingGeneration:b.generation,kind:"readiness_challenge",sourceEventId:`muse-challenge:${randomUUID()}`,references:{nonce}});
|
||||
await logActivity(tx as unknown as Db,{companyId,actorType:operatorId?"user":"system",actorId:operatorId??"muse-runner",agentId, responsibleUserIdOverride:operatorId??b.operatorId,action:"muse.readiness_challenge_created",entityType:"agent",entityId:agentId,details:{bindingId:b.id,generation:b.generation,revision:b.revision+1,authorizingUserId:b.operatorId,expiresAt:expiry.toISOString()}},publications);
|
||||
return {bindingId:b.id,generation:b.generation,revision:b.revision+1,expiresAt:expiry.toISOString(),status:"pending" as const};
|
||||
}));
|
||||
@@ -257,6 +264,7 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
const [b]=await tx.select().from(bindings).where(and(eq(bindings.id,boundary.bindingId),eq(bindings.companyId,companyId),eq(bindings.agentId,agentId),eq(bindings.generation,boundary.generation))).for("update");
|
||||
const [hold]=await tx.select().from(holds).where(and(eq(holds.companyId,companyId),eq(holds.agentId,agentId),eq(holds.provider,"muse"),eq(holds.assignmentId,boundary.assignmentId))).for("update");
|
||||
if(!b||b.revision!==input.expectedRevision||!hold?.stopBoundary||externalOperationDigest("tool",{boundary:hold.stopBoundary})!==externalOperationDigest("tool",{boundary}))throw conflict("Stop boundary changed. Refresh before attesting.");
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(holds).set({operatorAttestedAt:new Date(),workerUnknown:false,releasedAt:hold.nativeEffectsUnknown?null:new Date(),updatedAt:new Date()}).where(eq(holds.id,hold.id));
|
||||
await tx.update(bindings).set({revision:b.revision+1,updatedAt:new Date()}).where(eq(bindings.id,b.id));
|
||||
await logActivity(tx as unknown as Db,{companyId,actorType:"user",actorId:operatorId,action:"muse.worker_stop_attested",entityType:"agent",entityId:agentId,details:{bindingId:b.id,assignmentId:boundary.assignmentId,stopNonce:boundary.stopNonce,nativeEffectsUnknown:hold.nativeEffectsUnknown,externalStopConfirmed:false}});
|
||||
@@ -281,6 +289,7 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
if(b.revision!==input.expectedRevision)throw conflict("Connection changed. Refresh before attesting.");
|
||||
const now=new Date(),observedAt=new Date(input.observation.observedAt);
|
||||
if(observedAt<b.revokedAt!||observedAt>now||(b.qualificationExpiresAt&&observedAt<b.qualificationExpiresAt))throw conflict("Use an observation made after revocation and the qualification deadline, not a future observation.");
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(bindings).set({detectorRemovalRequestedAt:b.detectorRemovalRequestedAt??now,detectorRemovedAt:now,revision:b.revision+1,updatedAt:now}).where(eq(bindings.id,b.id));
|
||||
await logActivity(tx as unknown as Db,{companyId,actorType:"user",actorId:operatorId,agentId,responsibleUserIdOverride:operatorId,action:"muse.detector_cleanup_attested",entityType:"agent",entityId:agentId,
|
||||
details:{bindingId:b.id,generation:b.generation,qualificationId:b.qualificationId,expectedRevision:input.expectedRevision,revision:b.revision+1,source:"operator_runtime_attestation",hookScript:detectorHook(b),method:input.observation.method,includeDisabled:true,hookId:input.observation.hookId,outcome:input.observation.outcome,observedAt:observedAt.toISOString(),observationSha256:input.observation.sha256,recordedAt:now.toISOString(),inputDigest:digest,externalStopConfirmed:false}},publications);
|
||||
@@ -324,6 +333,7 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
await assertMuseCurrentAuthority(tx,b);
|
||||
const startedAt=new Date(input.expiresAt.getTime()-24*60*60_000);
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.museMaintenance, "*");
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(bindings).set({qualificationId:input.qualificationId,qualificationStartedAt:startedAt,qualificationExpiresAt:input.expiresAt,revision:b.revision+1,updatedAt:new Date()}).where(eq(bindings.id,b.id));
|
||||
await logActivity(tx as unknown as Db,{companyId:input.companyId,actorType:"user",actorId:input.operatorId,agentId:input.agentId,action:"muse.qualification_started",entityType:"agent",entityId:input.agentId,details:{bindingId:b.id,generation:b.generation,revision:b.revision+1,authorizingUserId:b.operatorId,qualificationId:input.qualificationId,startedAt:startedAt.toISOString(),expiresAt:input.expiresAt.toISOString()}},publications);
|
||||
return {qualificationId:input.qualificationId,startedAt:startedAt.toISOString(),expiresAt:input.expiresAt.toISOString(),revision:b.revision+1};
|
||||
@@ -338,6 +348,10 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
if(b.qualificationExpiresAt&&b.qualificationExpiresAt<=new Date())await db.update(bindings).set({deadlineEnforcedAt:new Date()}).where(and(eq(bindings.id,b.id),eq(bindings.qualificationId,input.qualificationId),isNull(bindings.deadlineEnforcedAt)));
|
||||
},
|
||||
async readQualificationEvidence(companyId:string,agentId:string,bindingId:string,qualificationId:string):Promise<MuseQualificationEvidence> {
|
||||
// Import and flush only through the original custody owners before reading
|
||||
// history. endQualification's original revoke/expiry path is unchanged.
|
||||
await (await import("../../services/muse-receiver.js")).museReceiver(db).flush();
|
||||
await (await import("./muse-hosted-sync.js")).syncCurrentMuseContactEvidence(db,AbortSignal.timeout(30_000));
|
||||
const [b]=await db.select().from(bindings).where(and(eq(bindings.id,bindingId),eq(bindings.companyId,companyId),eq(bindings.agentId,agentId),eq(bindings.qualificationId,qualificationId)));
|
||||
if(!b)throw notFound("Qualification not found.");
|
||||
const startedAt=b.qualificationStartedAt??b.createdAt;
|
||||
@@ -392,6 +406,7 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
{ companyId: b.companyId, agentId: b.agentId },
|
||||
() => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle));
|
||||
await assertMuseCurrentAuthority(tx, b, true);
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
const [ready]=await tx.update(bindings).set({status:"ready",verifiedReplyAt:new Date(),challengeHash:null,challengeExpiresAt:null,revision:b.revision+1,updatedAt:new Date()}).where(and(eq(bindings.id,b.id),eq(bindings.generation,b.generation),eq(bindings.challengeHash,museCredentialHash(c.nonce)),gt(bindings.challengeExpiresAt,new Date()),isNull(bindings.revokedAt))).returning();
|
||||
if(!ready)throw conflict("Challenge expired or does not match.");
|
||||
await logActivity(tx as unknown as Db,{companyId:b.companyId,actorType:"agent",actorId:b.agentId,agentId:b.agentId,responsibleUserIdOverride:b.operatorId,action:"muse.background_reply_verified",entityType:"agent",entityId:b.agentId,details:{bindingId:b.id,generation:b.generation,authorizingUserId:b.operatorId,requestId:c.requestId}},publications);
|
||||
@@ -425,7 +440,10 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
const rows=await tx.select().from(mailbox).where(and(eq(mailbox.bindingId,b.id),eq(mailbox.bindingGeneration,b.generation),gt(mailbox.id,q.after),
|
||||
disabled?and(eq(mailbox.kind,"authority_revoked"),inArray(sql`${mailbox.references}->'boundary'`,boundaries)):undefined)).orderBy(asc(mailbox.id)).limit(50);
|
||||
const cursor=rows.at(-1)?.id??q.after;
|
||||
await tx.update(bindings).set({workerCursor:Math.max(current.workerCursor,q.after)}).where(eq(bindings.id,b.id));
|
||||
if(q.after>current.workerCursor) {
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(bindings).set({workerCursor:q.after}).where(eq(bindings.id,b.id));
|
||||
}
|
||||
return {bindingId:b.id,generation:b.generation,items:rows,nextCursor:cursor};
|
||||
});
|
||||
if(q.query==="assignment.read") {const {a}=await authorizeAssignment(s,q.assignmentId);return {assignmentId:a.id,revision:a.revision,status:a.status,...a.projection,accounting:{usage:null,cost:null}};}
|
||||
@@ -494,6 +512,7 @@ function createMuseBroker(db:Db, publicOrigin?:string) {
|
||||
if(s.provider!=="muse"||b.operatorId!==s.authorizingUserId||!credential||!b.revokedAt||!b.cleanupExpiresAt||b.cleanupExpiresAt<=now)throw forbidden("Cleanup authority expired.");
|
||||
}
|
||||
if (removed ? !b.detectorRemovedAt : !b.detectorRemovalRequestedAt) {
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(bindings).set({...(removed?{detectorRemovedAt:new Date()}:{detectorRemovalRequestedAt:new Date()}),updatedAt:new Date()}).where(eq(bindings.id,b.id));
|
||||
await logActivity(tx as unknown as Db,{companyId:b.companyId,actorType:"agent",actorId:b.agentId,agentId:b.agentId,responsibleUserIdOverride:b.operatorId,action:removed?"muse.detector_removal_reported":"muse.detector_removal_requested",entityType:"agent",entityId:b.agentId,details:{bindingId:b.id,generation:b.generation,authorizingUserId:b.operatorId,externalStopConfirmed:false}},publications);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ interface Identity<S> {
|
||||
authorize(subject:S,assignmentId:string,settled?:boolean):Promise<Authority>;
|
||||
enabled(database:Pick<Db,"select">,provider?:"openai_dot"|"grok_bot"):Promise<boolean>;
|
||||
expectedResource?():string;
|
||||
prepareMailboxMutation?(tx:Pick<Db,"select"|"insert"|"update"|"execute">):Promise<void>;
|
||||
assertSubjectCredential?(tx:ExternalAdmissionTransaction,subject:S):Promise<void>;
|
||||
}
|
||||
type Execution={binding:{companyId:string;agentId:string;runId:string};provider:{kind?:"openai_dot"|"grok_bot"|"muse";binding:DotBindingSnapshot}};
|
||||
@@ -55,7 +56,8 @@ export function createNativeExternalBroker<S>(db:Db,provider:Provider,identity:I
|
||||
async function receipt(database:Database,id:string) {return (await database.execute<Receipt>(sql`select ${receiptColumns} from ${operationTable} where id=${id}::uuid`))[0];}
|
||||
async function currentBinding(database:Database,id:string,generation:number,allowFence=false) {
|
||||
const [b]=await database.execute<Binding>(sql`select ${bindingColumns} from ${bindingTable} where id=${id}::uuid and generation=${generation} and (${allowFence} or revoked_at is null) for update`);
|
||||
if(!b)throw forbidden("External binding generation is unavailable.");return b;
|
||||
if(!b)throw forbidden("External binding generation is unavailable.");
|
||||
return b;
|
||||
}
|
||||
async function assertCurrentAuthority(database:Database,b:Binding,allowFence=false) {
|
||||
if(allowFence)return;
|
||||
@@ -122,6 +124,9 @@ export function createNativeExternalBroker<S>(db:Db,provider:Provider,identity:I
|
||||
await tx.execute(sql`select id from ${bindingTable} where id=${a.bindingId}::uuid for update`);
|
||||
// A result can commit before the command acknowledgement is lost.
|
||||
// Only an actual unresolved-send transition adds an effect barrier.
|
||||
const [unresolved]=await tx.execute(sql`select 1 from ${operationTable} where id=${row.id}::uuid and status in ('dispatched','pending') for update`);
|
||||
if(!unresolved)return;
|
||||
await identity.prepareMailboxMutation?.(tx);
|
||||
await notifyExternalAgentSettlement(tx, { companyId: a.companyId, bindingId: a.bindingId });
|
||||
const changed=await tx.execute(sql`update ${operationTable} set status='unknown',updated_at=now() where id=${row.id}::uuid and status in ('dispatched','pending') returning id`);
|
||||
if(changed.length)await tx.update(externalAgentHolds).set({nativeEffectsUnknown:true,releasedAt:null,updatedAt:new Date()}).where(and(eq(externalAgentHolds.provider,provider),eq(externalAgentHolds.assignmentId,a.id)));
|
||||
@@ -151,6 +156,7 @@ export function createNativeExternalBroker<S>(db:Db,provider:Provider,identity:I
|
||||
if(command.action!=="accept"&&!a.claimedAt)throw conflict("Claim the assignment before running operations.");
|
||||
if(command.action==="accept") {
|
||||
if(a.claimedAt||!isFutureAssignmentTime(a.acceptBy))throw conflict("Assignment already claimed or claim expired.");
|
||||
await identity.prepareMailboxMutation?.(tx);
|
||||
await tx.execute(sql`update ${assignmentTable} set status='claimed',claimed_at=now() where id=${id}::uuid`);
|
||||
await tx.insert(externalAgentHolds).values({companyId:b.companyId,agentId:b.agentId,provider,assignmentId:id,bindingId:b.id,bindingGeneration:b.generation,runId:a.runId,workerUnknown:true}).onConflictDoNothing();
|
||||
}
|
||||
@@ -196,6 +202,14 @@ export function createNativeExternalBroker<S>(db:Db,provider:Provider,identity:I
|
||||
return (await tx.execute<Assignment>(sql`select ${assignmentColumns} from ${assignmentTable} where run_id=${b.runId}::uuid and company_id=${b.companyId}::uuid and agent_id=${b.agentId}::uuid and binding_id=${b.bindingId}::uuid and binding_generation=${b.bindingGeneration} and normalized_session_id=${b.normalizedSessionId} and turn_id=${b.turnId} and revision=${b.assignmentRevision} for update`))[0];
|
||||
}
|
||||
async function reserveRevocationEvent(tx:ExternalAdmissionTransaction,a:Assignment,sourceEventId:string,references:Record<string,unknown>) {
|
||||
if(provider==="muse") {
|
||||
const [old]=await tx.execute<{companyId:string;assignmentId:string|null;kind:string}>(sql`select company_id as "companyId",assignment_id as "assignmentId",kind from ${mailboxTable} where binding_id=${a.bindingId}::uuid and binding_generation=${a.bindingGeneration} and source_event_id=${sourceEventId}`);
|
||||
if(old) {
|
||||
if(old.companyId!==a.companyId||old.assignmentId!==a.id||old.kind!=="authority_revoked")throw conflict("Runner event identity conflicts with its durable receipt.");
|
||||
return false;
|
||||
}
|
||||
await identity.prepareMailboxMutation?.(tx);
|
||||
}
|
||||
if (provider === "openai_dot") await notifyDeliveryWork(tx, DELIVERY_QUEUES.dotEvents, `binding:${a.bindingId}`);
|
||||
const [created]=await tx.execute(sql`insert into ${mailboxTable} (company_id,binding_id,binding_generation,assignment_id,kind,source_event_id,"references") values (${a.companyId}::uuid,${a.bindingId}::uuid,${a.bindingGeneration},${a.id}::uuid,'authority_revoked',${sourceEventId},${JSON.stringify(references)}::jsonb) on conflict do nothing returning id`);
|
||||
if(created)return true;
|
||||
@@ -214,6 +228,9 @@ export function createNativeExternalBroker<S>(db:Db,provider:Provider,identity:I
|
||||
await db.transaction(tx=>withExecutionAdmission(tx,execution.binding.companyId,execution.binding.agentId,runId,async()=>{
|
||||
const [binding]=await tx.execute<Binding>(sql`select ${bindingColumns} from ${bindingTable} where id=${ref.bindingId}::uuid for update`);
|
||||
if(!binding||execution.provider.kind&&execution.provider.kind!==(provider==="muse"?"muse":binding.providerKind))throw forbidden("Runner controller provider does not match its binding.");
|
||||
const [unconfirmed]=provider==="muse"&&existing
|
||||
? await tx.execute(sql`select 1 from ${operationTable} where assignment_id=${existing.id}::uuid and status in ('dispatched','pending') limit 1`) : [];
|
||||
if(unconfirmed)await identity.prepareMailboxMutation?.(tx);
|
||||
await tx.execute(sql`update ${assignmentTable} set controller_generation=${owner.controllerGeneration} where run_id=${runId}::uuid and binding_generation=${ref.bindingGeneration} and controller_generation<=${owner.controllerGeneration}`);
|
||||
// Dot has target-owned replay receipts. Muse's unconfirmed sends
|
||||
// become independent unknown barriers on controller replacement.
|
||||
@@ -279,6 +296,14 @@ export function createNativeExternalBroker<S>(db:Db,provider:Provider,identity:I
|
||||
const [old]=await tx.execute<Assignment>(sql`select ${assignmentColumns} from ${assignmentTable} where run_id=${runId}::uuid and turn_id=${b.turnId}`);
|
||||
const projection={...p,binding:b};
|
||||
if(old&&externalOperationDigest("tool",old.projection)!==externalOperationDigest("tool",projection))throw conflict("Assignment event changed its immutable projection.");
|
||||
if(provider==="muse") {
|
||||
const [delivered]=await tx.execute<{companyId:string;assignmentId:string|null;kind:string;references:Record<string,unknown>|null}>(sql`select company_id as "companyId",assignment_id as "assignmentId",kind,"references" from ${mailboxTable} where binding_id=${b.bindingId}::uuid and binding_generation=${b.bindingGeneration} and source_event_id=${event.sourceEventId} limit 1`);
|
||||
if(delivered&&(!old||delivered.companyId!==b.companyId||delivered.assignmentId!==old.id||delivered.kind!=="assignment"
|
||||
||delivered.references?.assignmentId!==old.id||delivered.references?.runId!==runId||delivered.references?.revision!==old.revision))
|
||||
throw conflict("Runner event identity conflicts with its durable receipt.");
|
||||
if(old&&delivered)return;
|
||||
await identity.prepareMailboxMutation?.(tx);
|
||||
}
|
||||
if (!old && provider === "muse") await notifyExternalAgentSettlement(tx, { companyId: b.companyId, bindingId: b.bindingId });
|
||||
const [a]=old?[old]:await tx.execute<Assignment>(sql`insert into ${assignmentTable} (company_id,binding_id,binding_generation,run_id,agent_id,normalized_session_id,turn_id,revision,controller_generation,catalog_digest,status,projection,accept_by,expires_at) values (${b.companyId}::uuid,${b.bindingId}::uuid,${b.bindingGeneration},${runId}::uuid,${b.agentId}::uuid,${b.normalizedSessionId},${b.turnId},${b.assignmentRevision},${owner.controllerGeneration},${externalOperationDigest("tool",{tools:p.tools})},'offered',${JSON.stringify(projection)}::jsonb,${new Date(Number(p.acceptByUnixMs)).toISOString()}::timestamptz,${new Date(Number(p.expiresAtUnixMs)).toISOString()}::timestamptz) returning ${assignmentColumns}`);
|
||||
if(!a)throw conflict("Assignment creation failed.");
|
||||
@@ -308,7 +333,10 @@ export function createNativeExternalBroker<S>(db:Db,provider:Provider,identity:I
|
||||
// the same fact must preserve later work and its original evidence.
|
||||
return;
|
||||
}
|
||||
if (provider === "muse") await notifyExternalAgentSettlement(tx, { companyId: a.companyId, bindingId: a.bindingId });
|
||||
if (provider === "muse") {
|
||||
await identity.prepareMailboxMutation?.(tx);
|
||||
await notifyExternalAgentSettlement(tx, { companyId: a.companyId, bindingId: a.bindingId });
|
||||
}
|
||||
if (provider === "openai_dot") await notifyDeliveryWork(tx, DELIVERY_QUEUES.dotEvents, `binding:${a.bindingId}`);
|
||||
await tx.execute(sql`update ${operationTable} set status=${provider==="muse"&&outcome.status==="rejected"?"rejected":store.completed},outcome=${JSON.stringify(outcome)}::jsonb,source_event_id=${event.sourceEventId},updated_at=now() where id=${op.id}::uuid`);
|
||||
const action=op.command.action;
|
||||
@@ -344,6 +372,13 @@ export function createNativeExternalBroker<S>(db:Db,provider:Provider,identity:I
|
||||
const a=await eventAssignment(tx,b);if(!a||a.status==="fenced")throw forbidden("Input target authority unavailable.");
|
||||
const [old]=await tx.execute<{inputDigest:string;turnId:string}>(sql`select input_digest as "inputDigest",turn_id as "turnId" from muse_input_deliveries where assignment_id=${a.id}::uuid and request_id=${requestId}`);
|
||||
if(old&&(old.inputDigest!==inputDigest||old.turnId!==turnId))throw conflict("Input delivery changed its immutable digest.");
|
||||
const [delivered]=await tx.execute<{companyId:string;assignmentId:string|null;kind:string;references:Record<string,unknown>|null}>(sql`select company_id as "companyId",assignment_id as "assignmentId",kind,"references" from ${mailboxTable} where binding_id=${a.bindingId}::uuid and binding_generation=${a.bindingGeneration} and source_event_id=${event.sourceEventId} limit 1`);
|
||||
if(delivered&&(delivered.companyId!==a.companyId||delivered.assignmentId!==a.id||delivered.kind!=="input_available"
|
||||
||delivered.references?.assignmentId!==a.id||delivered.references?.requestId!==requestId
|
||||
||delivered.references?.turnId!==turnId||delivered.references?.inputDigest!==inputDigest))
|
||||
throw conflict("Runner event identity conflicts with its durable receipt.");
|
||||
if(old&&delivered)return;
|
||||
await identity.prepareMailboxMutation?.(tx);
|
||||
await tx.execute(sql`insert into muse_input_deliveries (company_id,assignment_id,request_id,turn_id,input_digest,response,source_event_id) values (${a.companyId}::uuid,${a.id}::uuid,${requestId},${turnId},${inputDigest},${JSON.stringify(response)}::jsonb,${event.sourceEventId}) on conflict do nothing`);
|
||||
await tx.execute(sql`insert into ${mailboxTable} (company_id,binding_id,binding_generation,assignment_id,kind,source_event_id,"references") values (${a.companyId}::uuid,${a.bindingId}::uuid,${a.bindingGeneration},${a.id}::uuid,'input_available',${event.sourceEventId},${JSON.stringify({assignmentId:a.id,requestId,turnId,inputDigest})}::jsonb) on conflict do nothing`);
|
||||
}));
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { prepareMuseReceiverAuthorityMutation } from "../modules/external-agents/index.js";
|
||||
import { notifyMuseContactVerification } from "../modules/external-agents/index.js";
|
||||
import { notifyStatusCardIssueChange } from "./status-card-notifications.js";
|
||||
import { notifyDeferredExecutionEligibility } from "./deferred-execution-notifications.js";
|
||||
@@ -597,6 +598,7 @@ export function accessService(db: Db) {
|
||||
if (existing.status === "active" && nextStatus !== "active" && existing.principalType === "user") {
|
||||
await sweepMemberConnectionAccess(tx, companyId, existing.principalId, now);
|
||||
}
|
||||
await prepareMuseReceiverAuthorityMutation(tx,{companyId,...(existing.principalType==="user"?{operatorId:existing.principalId}:{agentId:existing.principalId})});
|
||||
const updated = await tx
|
||||
.update(companyMemberships)
|
||||
.set({
|
||||
@@ -783,6 +785,7 @@ export function accessService(db: Db) {
|
||||
),
|
||||
);
|
||||
|
||||
await prepareMuseReceiverAuthorityMutation(tx,{companyId,...(existing.principalType==="user"?{operatorId:existing.principalId}:{agentId:existing.principalId})});
|
||||
const archived = await tx
|
||||
.update(companyMemberships)
|
||||
.set({
|
||||
@@ -887,6 +890,7 @@ export function accessService(db: Db) {
|
||||
if (toArchive.length > 0) {
|
||||
const now = new Date();
|
||||
for (const membership of toArchive) {
|
||||
await prepareMuseReceiverAuthorityMutation(tx,{companyId:membership.companyId,operatorId:membership.principalId});
|
||||
await sweepMemberConnectionAccess(tx, membership.companyId, membership.principalId, now);
|
||||
}
|
||||
await tx
|
||||
@@ -952,6 +956,7 @@ export function accessService(db: Db) {
|
||||
)).for("update").then(rows => rows[0] ?? null);
|
||||
if (existing) {
|
||||
if (existing.status !== status || existing.membershipRole !== membershipRole) {
|
||||
await prepareMuseReceiverAuthorityMutation(tx,{companyId,...(principalType==="user"?{operatorId:principalId}:{agentId:principalId})});
|
||||
if(status==="active"&&(principalType==="agent"||membershipRole!=="viewer")
|
||||
&&(existing.status!=="active"||principalType==="user"&&existing.membershipRole==="viewer"))
|
||||
await notifyMuseContactVerification(tx,{companyId,...(principalType==="user"?{operatorId:principalId}:{agentId:principalId})});
|
||||
@@ -1207,6 +1212,7 @@ export function accessService(db: Db) {
|
||||
await sweepMemberConnectionAccess(tx, companyId, existing.principalId, now);
|
||||
}
|
||||
|
||||
await prepareMuseReceiverAuthorityMutation(tx,{companyId,...(existing.principalType==="user"?{operatorId:existing.principalId}:{agentId:existing.principalId})});
|
||||
return tx
|
||||
.update(companyMemberships)
|
||||
.set({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { prepareMuseReceiverAuthorityMutation } from "../modules/external-agents/index.js";
|
||||
import { notifyMuseContactVerification } from "../modules/external-agents/index.js";
|
||||
import { notifyBudgetResumeAgentReady } from "./budget-resume-continuation.js";
|
||||
import { currentControllerProcessStamp } from "./controller-process-identity.js";
|
||||
@@ -60,6 +61,7 @@ export function createAgentLifecycleEffects(_hooks: BudgetServiceHooks = {}): li
|
||||
async beforeStatusChange(tx, companyId, agentId, before, after) {
|
||||
await notifyAttentionRetentionWork(tx, { companyId });
|
||||
if (before !== after) {
|
||||
await prepareMuseReceiverAuthorityMutation(tx,{companyId,agentId});
|
||||
await notifyStrandedAgentStatus(tx, { companyId, agentId });
|
||||
await notifyRunDispatch(tx, { companyId });
|
||||
await notifyDeferredExecutionEligibility(tx, { companyId });
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { prepareMuseReceiverAuthorityMutation } from "../modules/external-agents/index.js";
|
||||
import { notifyMuseContactVerification } from "../modules/external-agents/index.js";
|
||||
import { promoteDeferredWorkIntents } from "./work-intent-outbox.js";
|
||||
import { notifyDeferredExecutionEligibility } from "./deferred-execution-notifications.js";
|
||||
@@ -344,6 +345,7 @@ export function companyService(db: Db, _budgetHooks: BudgetServiceHooks = {}) {
|
||||
const renamedPrefix = await resolveRenamedIssuePrefix(tx, id, companyPatch);
|
||||
|
||||
if (companyPatch.status !== undefined && companyPatch.status !== existing.status) {
|
||||
await prepareMuseReceiverAuthorityMutation(tx,{companyId:id});
|
||||
if(willReactivate)await notifyMuseContactVerification(tx,{companyId:id});
|
||||
await notifyRunDispatch(tx, { companyId: id });
|
||||
await notifyGitHubCompanyChange(tx, id);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { prepareMuseReceiverAuthorityMutation } from "../modules/external-agents/index.js";
|
||||
import { mcpCompanyDeletion } from "./public-mcp/company-deletion.js";
|
||||
import { notifyStatusCardEvaluation } from "./status-card-notifications.js";
|
||||
import { notifyExternalObjectRefresh } from "./external-object-refresh-notifications.js";
|
||||
@@ -76,6 +77,7 @@ export async function deleteCompany(db: Db, id: string) {
|
||||
const [existing] = await tx.select({ id: companies.id }).from(companies)
|
||||
.where(eq(companies.id, id)).for("no key update");
|
||||
if (!existing) return null;
|
||||
await prepareMuseReceiverAuthorityMutation(tx,{companyId:id});
|
||||
await mcpCompanyDeletion.deleteCompanyData(tx, id);
|
||||
await notifyExternalObjectRefresh(tx, id);
|
||||
await notifyIssueRecovery(tx, { companyId: id });
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
/** Process-local hint only; Cloud retains the durable target until event acknowledgment. */
|
||||
const receivers = new WeakMap<object, () => void>();
|
||||
export function registerConnectionEventWake(owner: object, wake: () => void) {
|
||||
receivers.set(owner, wake);
|
||||
return () => { if (receivers.get(owner) === wake) receivers.delete(owner); };
|
||||
/** Process-local hints only; durable owners retain work until their exact acknowledgment. */
|
||||
const receivers = new WeakMap<object, Map<() => void, { importsClientMetadata: boolean }>>();
|
||||
export function registerConnectionEventWake(owner: object, wake: () => void,
|
||||
options: { importsClientMetadata?: boolean } = {}) {
|
||||
let current = receivers.get(owner);
|
||||
if (!current) { current = new Map(); receivers.set(owner, current); }
|
||||
const registration = { importsClientMetadata: options.importsClientMetadata === true };
|
||||
current.set(wake, registration);
|
||||
return () => {
|
||||
const active = receivers.get(owner);
|
||||
if (active?.get(wake) !== registration) return;
|
||||
active.delete(wake);
|
||||
if (!active.size) receivers.delete(owner);
|
||||
};
|
||||
}
|
||||
export function wakeConnectionEvents(owner: object): boolean {
|
||||
const wake = receivers.get(owner);
|
||||
if (!wake) return false;
|
||||
wake();
|
||||
const current = receivers.get(owner);
|
||||
if (!current?.size) return false;
|
||||
for (const wake of [...current.keys()]) wake();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Inspection never emits a wake or polls the broker. */
|
||||
export const hasConnectionEventWakeReceiver = (owner: object): boolean => receivers.has(owner);
|
||||
export function hasConnectionEventWakeReceiver(owner: object,
|
||||
options: { importsClientMetadata?: boolean } = {}): boolean {
|
||||
const current = receivers.get(owner);
|
||||
// The default remains the ordinary connection-event capability. Import-only
|
||||
// registration must never enroll or suppress polling for ordinary events.
|
||||
return Boolean(current && [...current.values()].some(value =>
|
||||
value.importsClientMetadata === (options.importsClientMetadata === true)));
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
readIdleIncomingWakeProof,
|
||||
incomingWakeFingerprint,
|
||||
} from "./idle-incoming-wake.js";
|
||||
import { registerConnectionEventWake } from "./connection-event-wake.js";
|
||||
import { registerConnectionEventWake,hasConnectionEventWakeReceiver,wakeConnectionEvents } from "./connection-event-wake.js";
|
||||
import type { VerifiedIdleCapabilities } from "./idle-incoming-wake-capability.js";
|
||||
|
||||
const ownerId = "00000000-0000-4000-8000-000000000001";
|
||||
@@ -81,13 +81,14 @@ function input(
|
||||
db: object,
|
||||
capabilities: VerifiedIdleCapabilities,
|
||||
now?: () => number,
|
||||
receiver: { importsClientMetadata?: boolean } = {},
|
||||
) {
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID", "fixture-instance");
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY", "fixture");
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY", "fixture");
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT", "test");
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_CONNECTOR_BASE_URL", "http://127.0.0.1");
|
||||
stops.push(registerConnectionEventWake(db, () => {}));
|
||||
stops.push(registerConnectionEventWake(db, () => {}, receiver));
|
||||
return { ownerId, receiverOwner: db, capabilities, now };
|
||||
}
|
||||
afterEach(() => {
|
||||
@@ -182,3 +183,60 @@ describe("bounded API admission projection", () => {
|
||||
{ ownerId, receiverOwner: {}, capabilities: api, now: () => clock })).rejects.toThrow(/budget exhausted/);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("connection event and client metadata receiver purposes", () => {
|
||||
it("does not discharge the ordinary incoming-event guard with an import-only receiver", async () => {
|
||||
const f = fixture(1);
|
||||
const sql = database([() => [], () => f.endpoints, () => f.registrations]);
|
||||
const context = input(sql.db, f.capability, undefined, { importsClientMetadata: true });
|
||||
expect(hasConnectionEventWakeReceiver(sql.db)).toBe(false);
|
||||
expect(hasConnectionEventWakeReceiver(sql.db, { importsClientMetadata: true })).toBe(true);
|
||||
await expect(readIdleIncomingWakeProof(sql.db, context)).rejects.toThrow("Incoming GitHub receiver is not bound");
|
||||
expect(sql.select).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps an ordinary receiver eligible for events without advertising metadata import", async () => {
|
||||
const f = fixture(1);
|
||||
const sql = database([() => [], () => f.endpoints, () => f.registrations]);
|
||||
const context = input(sql.db, f.capability);
|
||||
expect(hasConnectionEventWakeReceiver(sql.db)).toBe(true);
|
||||
expect(hasConnectionEventWakeReceiver(sql.db, { importsClientMetadata: true })).toBe(false);
|
||||
const proof = await readIdleIncomingWakeProof(sql.db, context);
|
||||
expect(proof?.endpointIds).toEqual(["endpoint-0"]);
|
||||
expect(sql.select).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("fans out both purposes and unregisters exact owners without promoting the remaining capability", () => {
|
||||
for (const stopFirst of ["ordinary", "import"] as const) {
|
||||
const owner = {}, ordinary = vi.fn(), metadata = vi.fn();
|
||||
const stopOrdinary = registerConnectionEventWake(owner, ordinary);
|
||||
const stopImport = registerConnectionEventWake(owner, metadata, { importsClientMetadata: true });
|
||||
stops.push(stopOrdinary, stopImport);
|
||||
expect(hasConnectionEventWakeReceiver(owner)).toBe(true);
|
||||
expect(hasConnectionEventWakeReceiver(owner, { importsClientMetadata: true })).toBe(true);
|
||||
expect(wakeConnectionEvents(owner)).toBe(true);
|
||||
expect(ordinary).toHaveBeenCalledTimes(1);
|
||||
expect(metadata).toHaveBeenCalledTimes(1);
|
||||
(stopFirst === "ordinary" ? stopOrdinary : stopImport)();
|
||||
expect(hasConnectionEventWakeReceiver(owner)).toBe(stopFirst !== "ordinary");
|
||||
expect(hasConnectionEventWakeReceiver(owner, { importsClientMetadata: true })).toBe(stopFirst !== "import");
|
||||
expect(wakeConnectionEvents(owner)).toBe(true);
|
||||
expect(ordinary).toHaveBeenCalledTimes(stopFirst === "ordinary" ? 1 : 2);
|
||||
expect(metadata).toHaveBeenCalledTimes(stopFirst === "import" ? 1 : 2);
|
||||
stopOrdinary(); stopImport();
|
||||
expect(wakeConnectionEvents(owner)).toBe(false);
|
||||
}
|
||||
const owner = {}, wake = vi.fn();
|
||||
const staleStop = registerConnectionEventWake(owner, wake);
|
||||
const stopReplacement = registerConnectionEventWake(owner, wake);
|
||||
stops.push(staleStop, stopReplacement);
|
||||
staleStop();
|
||||
expect(hasConnectionEventWakeReceiver(owner)).toBe(true);
|
||||
expect(hasConnectionEventWakeReceiver(owner, { importsClientMetadata: true })).toBe(false);
|
||||
expect(wakeConnectionEvents(owner)).toBe(true);
|
||||
expect(wake).toHaveBeenCalledTimes(1);
|
||||
stopReplacement();
|
||||
expect(hasConnectionEventWakeReceiver(owner)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -437,7 +437,7 @@ export async function readIdleSleepSafety(
|
||||
const replacement = deadlineProof?.blocked === false ? deadlineWorkReplacement(check.reason) : undefined;
|
||||
const mcp = incomingProof?.mcp;
|
||||
const mcpRetryQuery = mcp && deadlineProof?.blocked === false && deadlineProof.mcp === mcp.schedule
|
||||
? idleMcpWorkQuery(check.reason, { ingress: mcp.ingress, subscriptions: mcp.subscriptions, retries: mcp.retries }) : undefined;
|
||||
? idleMcpWorkQuery(check.reason, { ingress: mcp.ingress,muse:mcp.muse, subscriptions: mcp.subscriptions, retries: mcp.retries }) : undefined;
|
||||
return { ...check, query: mcpRetryQuery ?? incomingWakeWorkQuery(check.reason, incomingProof,
|
||||
deadlineProof?.githubContinuity?.connectionIds) ?? deadlineOwnerWorkReplacement(deadlineProof, check.reason) ?? (replacement ? sql.raw(replacement) : check.query) };
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import { MUSE_ACCESS_TTL_MS, MUSE_REFRESH_INACTIVITY_MS, MUSE_RESOURCE_PATH, MUS
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import { musePublicOrigin } from "./muse-setup.js";
|
||||
import { unauthorized, forbidden } from "../errors.js";
|
||||
import { withExternalAdmissionGuard, type ExternalAdmissionTransaction } from "../modules/external-agents/index.js";
|
||||
import { prepareMuseReceiverMutation, withExternalAdmissionGuard, type ExternalAdmissionTransaction } from "../modules/external-agents/index.js";
|
||||
import { canConfigureAgentConnection } from "../modules/agent-lifecycle/index.js";
|
||||
export const museCredentialHash = (value: string) => createHash("sha256").update(value).digest("hex");
|
||||
const token = () => randomBytes(32).toString("base64url");
|
||||
@@ -13,7 +13,7 @@ export type MuseCredentialKind = typeof credentials.$inferSelect.kind;
|
||||
export type MuseIdentityDatabase = Db | ExternalAdmissionTransaction;
|
||||
/** A scoped fence is reportable only while its exact assignment and durable
|
||||
* boundary still agree. Callers independently validate the credential lane. */
|
||||
function scopedMuseStopBoundaryIds(db:MuseIdentityDatabase,b:Pick<typeof bindings.$inferSelect,"id"|"companyId"|"agentId"|"generation"|"operatorId">,revoked:boolean,now:Date,provider="muse") {
|
||||
function scopedMuseStopBoundaryIds(db:Pick<Db,"select">,b:Pick<typeof bindings.$inferSelect,"id"|"companyId"|"agentId"|"generation"|"operatorId">,revoked:boolean,now:Date,provider="muse") {
|
||||
return db.select({id:holds.id}).from(holds)
|
||||
.innerJoin(assignments,and(eq(assignments.id,holds.assignmentId),eq(assignments.companyId,holds.companyId),eq(assignments.agentId,holds.agentId),eq(assignments.bindingId,holds.bindingId),eq(assignments.bindingGeneration,holds.bindingGeneration),eq(assignments.runId,holds.runId),eq(assignments.status,"fenced")))
|
||||
.innerJoin(bindings,and(eq(bindings.id,holds.bindingId),eq(bindings.companyId,holds.companyId),eq(bindings.agentId,holds.agentId),eq(bindings.generation,holds.bindingGeneration),eq(bindings.operatorId,b.operatorId),revoked?sql`${bindings.revokedAt} is not null`:isNull(bindings.revokedAt),revoked?gt(bindings.cleanupExpiresAt,now):inArray(bindings.status,["connected","ready"])))
|
||||
@@ -28,14 +28,14 @@ function scopedMuseStopBoundaryIds(db:MuseIdentityDatabase,b:Pick<typeof binding
|
||||
.groupBy(holds.id)
|
||||
.having(revoked?sql`true`:sql`min(${mailbox.createdAt}) > ${new Date(now.getTime()-MUSE_CLEANUP_TTL_MS).toISOString()}::timestamptz and min(${mailbox.createdAt}) <= ${now.toISOString()}::timestamptz`);
|
||||
}
|
||||
export function museCleanupBoundaryIds(db:MuseIdentityDatabase,s:AgentConnectionSubject,revoked=false,now=new Date()) {
|
||||
export function museCleanupBoundaryIds(db:Pick<Db,"select">,s:AgentConnectionSubject,revoked=false,now=new Date()) {
|
||||
return scopedMuseStopBoundaryIds(db,{id:s.bindingId,companyId:s.companyId,agentId:s.agentId,generation:s.generation,operatorId:s.authorizingUserId},revoked,now,s.provider);
|
||||
}
|
||||
/** Public control selection uses persisted binding scope, never a worker subject. */
|
||||
export function museStopControlBoundaryIds(db:MuseIdentityDatabase,b:typeof bindings.$inferSelect,now=new Date()) {
|
||||
export function museStopControlBoundaryIds(db:Pick<Db,"select">,b:typeof bindings.$inferSelect,now=new Date()) {
|
||||
return scopedMuseStopBoundaryIds(db,b,false,now);
|
||||
}
|
||||
export async function assertMuseCurrentAuthority(db: MuseIdentityDatabase, b: typeof bindings.$inferSelect, allowSetup = false, allowPaused = false) {
|
||||
export async function assertMuseCurrentAuthority(db:Pick<Db,"select">, b: typeof bindings.$inferSelect, allowSetup = false, allowPaused = false) {
|
||||
const [agent] = await db.select().from(agents).where(and(eq(agents.id,b.agentId),eq(agents.companyId,b.companyId)));
|
||||
const [company] = await db.select().from(companies).where(eq(companies.id,b.companyId));
|
||||
const [user] = await db.select({id:authUsers.id}).from(authUsers).where(eq(authUsers.id,b.operatorId));
|
||||
@@ -80,7 +80,7 @@ export async function assertMuseSubjectCredential(db: MuseIdentityDatabase, s: A
|
||||
}
|
||||
/** Disabled OAuth cannot refresh. Do not wake a worker for stop control when
|
||||
* no live access credential remains; resuming the feature can restore refresh. */
|
||||
export async function hasMuseStopControlAccess(db:MuseIdentityDatabase,b:typeof bindings.$inferSelect) {
|
||||
export async function hasMuseStopControlAccess(db:Pick<Db,"select">,b:typeof bindings.$inferSelect) {
|
||||
const now=new Date();
|
||||
const [access]=b.grantId
|
||||
? await db.select({id:mcpOauthTokens.id}).from(mcpOauthTokens).where(and(eq(mcpOauthTokens.grantId,b.grantId),eq(mcpOauthTokens.kind,"access"),isNull(mcpOauthTokens.usedAt),gt(mcpOauthTokens.expiresAt,now))).limit(1)
|
||||
@@ -103,7 +103,7 @@ export async function revokeMuseOAuthGrant(db: Db, grant: typeof mcpOauthGrants.
|
||||
await museRunnerBroker(db).revokeOAuthGrant({grantId:grant.id,companyId:grant.companyId,agentId:grant.agentId,authorizingUserId:grant.userId});
|
||||
}
|
||||
/** Safe lifecycle facts shared by public polling and board status; no token values. */
|
||||
export async function inspectMuseConnectionCredential(db:MuseIdentityDatabase,b:typeof bindings.$inferSelect,expectedResource?:string):Promise<{state:"pending"|"active"|"expired"|"revoked";refreshExpiresAt:string|null}> {
|
||||
export async function inspectMuseConnectionCredential(db:Pick<Db,"select">,b:typeof bindings.$inferSelect,expectedResource?:string):Promise<{state:"pending"|"active"|"expired"|"revoked";refreshExpiresAt:string|null}> {
|
||||
const now=new Date(),result=(state:"pending"|"active"|"expired"|"revoked",refreshExpiresAt:Date|null=null)=>({state,refreshExpiresAt:refreshExpiresAt?.toISOString()??null});
|
||||
if(b.revokedAt)return result("revoked");
|
||||
if(!b.pairedAt)return result(b.ticketExpiresAt&&b.ticketExpiresAt>now?"pending":"expired");
|
||||
@@ -125,7 +125,7 @@ export async function inspectMuseConnectionCredential(db:MuseIdentityDatabase,b:
|
||||
return result(refresh?"active":"expired",refresh?.expiresAt??null);
|
||||
}
|
||||
/** Public polling uses persisted identity policy, never a fabricated worker subject. */
|
||||
export async function assertMuseReceiverAuthority(db:MuseIdentityDatabase,b:typeof bindings.$inferSelect,expectedResource?:string) {
|
||||
export async function assertMuseReceiverAuthority(db:Pick<Db,"select">,b:typeof bindings.$inferSelect,expectedResource?:string) {
|
||||
const credential=await inspectMuseConnectionCredential(db,b,expectedResource);
|
||||
if(credential.state!=="active")throw unauthorized("Muse receiver credential authority is unavailable; reconnect Muse.");
|
||||
return assertMuseCurrentAuthority(db,b,true,true);
|
||||
@@ -162,6 +162,7 @@ export function museIdentity(db: Db) {
|
||||
return s.enableMuse && s.enableNativeRunner;
|
||||
}
|
||||
async function issue(tx: ExternalAdmissionTransaction, b: typeof bindings.$inferSelect, familyId: string=randomUUID()): Promise<MuseCredentials> {
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
const accessToken=token(), refreshToken=token(), cleanupToken=token(), detectorCleanupToken=token();
|
||||
const accessExpiresAt=new Date(Date.now()+MUSE_ACCESS_TTL_MS), refreshExpiresAt=new Date(Date.now()+MUSE_REFRESH_INACTIVITY_MS);
|
||||
await tx.insert(credentials).values(([['access',accessToken,accessExpiresAt],['refresh',refreshToken,refreshExpiresAt],['cleanup',cleanupToken,refreshExpiresAt],['detector_cleanup',detectorCleanupToken,refreshExpiresAt]] as const).map(([kind,value,expiresAt])=>({companyId:b.companyId,bindingId:b.id,bindingGeneration:b.generation,kind,familyId,tokenHash:museCredentialHash(value),expiresAt})));
|
||||
@@ -175,6 +176,7 @@ export function museIdentity(db: Db) {
|
||||
}
|
||||
}
|
||||
return {
|
||||
prepareMailboxMutation:prepareMuseReceiverMutation,
|
||||
enabled,
|
||||
async authenticateOAuthAccess(value:string,publicOrigin?:string,options:{stopControl?:boolean}={}):Promise<AgentConnectionSubject> {
|
||||
const {museOAuth}=await import("./muse-oauth.js");
|
||||
@@ -187,12 +189,24 @@ export function museIdentity(db: Db) {
|
||||
const subject:AgentConnectionSubject={provider:"muse",credentialSource:"oauth",grantId:principal.grant.id,companyId:b.companyId,
|
||||
agentId:b.agentId,bindingId:b.id,generation:b.generation,authorizingUserId:b.operatorId,credentialId:principal.accessTokenId};
|
||||
const expectedResource=musePublicOrigin(publicOrigin)+MUSE_RESOURCE_PATH;
|
||||
await assertMuseSubjectCredential(db,subject,expectedResource);await assertMuseReceiverAuthority(db,b,expectedResource);
|
||||
if(options.stopControl&&!await enabled())await assertMuseDisabledStopControlCredential(db,subject,expectedResource);
|
||||
await db.update(bindings).set({workerActivityAt:new Date()}).where(and(eq(bindings.id,b.id),eq(bindings.grantId,principal.grant.id),isNull(bindings.revokedAt)));
|
||||
await db.update(mcpOauthTokens).set({expiresAt:new Date(Date.now()+MUSE_REFRESH_INACTIVITY_MS)}).where(and(eq(mcpOauthTokens.grantId,principal.grant.id),
|
||||
eq(mcpOauthTokens.kind,"refresh"),isNull(mcpOauthTokens.usedAt),gt(mcpOauthTokens.expiresAt,new Date())));
|
||||
return subject;
|
||||
return db.transaction(tx=>withExternalAdmissionGuard(tx,b.companyId,b.agentId,async()=>{
|
||||
// Same normal agent→binding order as pairing/refresh. Publish the intent
|
||||
// before extending the credential/receiver deadline in this transaction.
|
||||
const [current]=await tx.select().from(bindings).where(and(eq(bindings.id,b.id),eq(bindings.companyId,b.companyId),
|
||||
eq(bindings.agentId,b.agentId),eq(bindings.operatorId,b.operatorId),eq(bindings.generation,b.generation),
|
||||
eq(bindings.grantId,principal.grant.id),isNull(bindings.revokedAt))).for("update");
|
||||
if(!current)throw unauthorized("Muse OAuth binding changed.");
|
||||
await assertMuseSubjectCredential(tx,subject,expectedResource);await assertMuseReceiverAuthority(tx,current,expectedResource);
|
||||
if(!await enabled(tx)){
|
||||
if(!options.stopControl)throw unauthorized("Muse authority was fenced.");
|
||||
await assertMuseDisabledStopControlCredential(tx,subject,expectedResource);
|
||||
}
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(bindings).set({workerActivityAt:new Date()}).where(eq(bindings.id,current.id));
|
||||
await tx.update(mcpOauthTokens).set({expiresAt:new Date(Date.now()+MUSE_REFRESH_INACTIVITY_MS)}).where(and(eq(mcpOauthTokens.grantId,principal.grant.id),
|
||||
eq(mcpOauthTokens.kind,"refresh"),isNull(mcpOauthTokens.usedAt),gt(mcpOauthTokens.expiresAt,new Date())));
|
||||
return subject;
|
||||
}));
|
||||
},
|
||||
async pair(ticket: string, clientVersion: string): Promise<MuseCredentials> {
|
||||
if (!await enabled()) throw forbidden("Muse is disabled for new connections.");
|
||||
@@ -202,6 +216,7 @@ export function museIdentity(db: Db) {
|
||||
const [b]=await tx.select().from(bindings).where(and(eq(bindings.id,candidate.id),eq(bindings.ticketHash,museCredentialHash(ticket)),eq(bindings.status,"pairing"),isNull(bindings.revokedAt),gt(bindings.ticketExpiresAt,new Date()))).for("update");
|
||||
if (!b) throw unauthorized("Pairing ticket expired or was consumed.");
|
||||
await assertMuseCurrentAuthority(tx,b,true);
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
const [paired]=await tx.update(bindings).set({status:"connected",ticketHash:null,ticketExpiresAt:null,pairedAt:new Date(),workerActivityAt:new Date(),clientVersion,revision:b.revision+1,updatedAt:new Date()}).where(eq(bindings.id,b.id)).returning();
|
||||
return issue(tx,paired!);
|
||||
}));
|
||||
@@ -218,11 +233,13 @@ export function museIdentity(db: Db) {
|
||||
const [binding]=await tx.select().from(bindings).where(eq(bindings.id,b.id)).for("update");
|
||||
const [old]=await tx.select().from(credentials).where(eq(credentials.id,candidate.id)).for("update");
|
||||
if (old?.consumedAt) {
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(credentials).set({revokedAt:new Date()}).where(and(eq(credentials.familyId,old.familyId),inArray(credentials.kind,["access","refresh","signal"])));
|
||||
return null;
|
||||
}
|
||||
if (!binding || binding.revokedAt || binding.generation!==old?.bindingGeneration || old.revokedAt || old.expiresAt<=new Date()) return null;
|
||||
await assertMuseCurrentAuthority(tx,binding,true,true);
|
||||
await prepareMuseReceiverMutation(tx);
|
||||
await tx.update(credentials).set({consumedAt:new Date()}).where(eq(credentials.id,old.id));
|
||||
await tx.update(credentials).set({revokedAt:new Date()}).where(and(eq(credentials.familyId,old.familyId),eq(credentials.bindingId,binding.id),inArray(credentials.kind,["access","signal"])));
|
||||
await tx.update(bindings).set({workerActivityAt:new Date(),updatedAt:new Date()}).where(eq(bindings.id,binding.id));
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { HttpError } from "../errors.js";
|
||||
import { museIdentity, inspectMuseConnectionCredential } from "./muse-identity.js";
|
||||
import { canConfigureAgentConnection } from "../modules/agent-lifecycle/index.js";
|
||||
import { pendingMuseContactVerifications, parseMuseVerificationHint, type MuseVerificationScope, pendingMuseTerminalBindings, type ExternalAgentSettlementScope } from "../modules/external-agents/index.js";
|
||||
import { recoverMuseReceiverContinuity, pendingMuseContactVerifications, parseMuseVerificationHint, type MuseVerificationScope, pendingMuseTerminalBindings, type ExternalAgentSettlementScope } from "../modules/external-agents/index.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { and, asc, eq, gt, isNull, lte } from "drizzle-orm";
|
||||
import { and, asc, eq, gt, isNull, lte, sql } from "drizzle-orm";
|
||||
import { museAgentBindings as bindings, mcpOauthGrants, type Db } from "@paperclipai/db";
|
||||
import { museRunnerBroker } from "./muse-runner-broker.js";
|
||||
import { museReceiver } from "./muse-receiver.js";
|
||||
@@ -33,8 +33,11 @@ export function startMuseMaintenance(
|
||||
const settlementAllowed = await canSettle();
|
||||
const inspected = new Set<string>();
|
||||
if (!startupMarked) {
|
||||
const continuous=await recoverMuseReceiverContinuity(db,signal);
|
||||
const owned=[...continuous].map(([id,generation])=>sql`(${bindings.id}=${id} and ${bindings.generation}=${generation})`);
|
||||
await db.update(bindings).set({ cadenceEvidenceIncompleteAt: new Date() })
|
||||
.where(and(isNull(bindings.revokedAt), gt(bindings.qualificationExpiresAt, new Date())));
|
||||
.where(and(isNull(bindings.revokedAt), gt(bindings.qualificationExpiresAt, new Date()),
|
||||
owned.length?sql`not (${sql.join(owned,sql` or `)})`:undefined));
|
||||
startupMarked = true;
|
||||
}
|
||||
let failed = false;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getCloudRuntimeIdentity } from "./cloud-runtime-identity.js";
|
||||
import { notifyMuseContactVerification } from "../modules/external-agents/index.js";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
@@ -13,10 +14,14 @@ function createReceiver(db:Db) {
|
||||
const pending=new Map<string,{companyId:string;bindingId:string;bindingGeneration:number;bucketAt:Date;firstAt:Date;lastAt:Date;contacts:number;gapsAtMostSevenSeconds:number;maxGapMs:number;timestamps:string[];incomplete:boolean}>();
|
||||
const previous=new Map<string,number>();
|
||||
let flushPromise:Promise<void>|undefined;
|
||||
const admittedSignals=new Set<Promise<{version:1;signal:{reference:string}|null}>>();
|
||||
let stopping=false;
|
||||
let stopPromise:Promise<void>|undefined;
|
||||
async function flush() {
|
||||
if(flushPromise)return flushPromise;
|
||||
flushPromise=(async()=>{
|
||||
const batch=[...pending.entries()];pending.clear();
|
||||
let failures=0;
|
||||
for(const [key,bucket]of batch) {
|
||||
try {
|
||||
const current=await db.transaction(async tx=>{
|
||||
@@ -31,11 +36,13 @@ function createReceiver(db:Db) {
|
||||
await museRunnerBroker(db).verify(current.companyId,current.agentId,{bindingId:current.id,generation:current.generation,expectedRevision:current.revision}).catch(()=>{});
|
||||
}
|
||||
} catch {
|
||||
failures++;
|
||||
const newer=pending.get(key);
|
||||
if(newer){newer.firstAt=bucket.firstAt;newer.contacts+=bucket.contacts;newer.timestamps=[...bucket.timestamps,...newer.timestamps].slice(0,60);newer.incomplete=true;}
|
||||
if(newer){newer.firstAt=new Date(Math.min(bucket.firstAt.getTime(),newer.firstAt.getTime()));newer.lastAt=new Date(Math.max(bucket.lastAt.getTime(),newer.lastAt.getTime()));newer.contacts+=bucket.contacts;newer.gapsAtMostSevenSeconds+=bucket.gapsAtMostSevenSeconds;newer.maxGapMs=Math.max(bucket.maxGapMs,newer.maxGapMs);newer.timestamps=[...bucket.timestamps,...newer.timestamps].slice(0,60);newer.incomplete=true;}
|
||||
else pending.set(key,{...bucket,incomplete:true});
|
||||
}
|
||||
}
|
||||
if(failures)throw new Error("Muse receiver contact persistence is incomplete.");
|
||||
})().finally(()=>{flushPromise=undefined;});return flushPromise;
|
||||
}
|
||||
function recordPublicContact(b: typeof bindings.$inferSelect, now: number) {
|
||||
@@ -57,7 +64,7 @@ function createReceiver(db:Db) {
|
||||
else bucket.incomplete = true;
|
||||
}
|
||||
/** A public binding reference is presence evidence, never worker authority. */
|
||||
async function signal(bindingId: string, expectedResource?:string) {
|
||||
async function signalOnce(bindingId: string, expectedResource?:string) {
|
||||
const idle = { version: 1 as const, signal: null };
|
||||
const unavailable = () => new HttpError(410, "Muse receiver is unavailable.");
|
||||
const [candidate] = await db.select().from(bindings).where(eq(bindings.id, bindingId));
|
||||
@@ -106,11 +113,52 @@ function createReceiver(db:Db) {
|
||||
const reference = "sha256:" + createHash("sha256").update(`${current.id}:${current.generation}:${item.item.sourceEventId}:${attempt}`).digest("hex");
|
||||
return { version: 1 as const, signal: { reference } };
|
||||
});
|
||||
if (contacted) recordPublicContact(contacted, Date.now());
|
||||
if (contacted) {
|
||||
recordPublicContact(contacted, Date.now());
|
||||
if (getCloudRuntimeIdentity()) {
|
||||
// A warm-forward decision can outlive the hosted handoff's empty join.
|
||||
// Never confirm that late managed contact while it exists only in RAM.
|
||||
// The first join may be a batch captured before this contact; the next
|
||||
// flush captures its retained bucket (or joins one that already did).
|
||||
// Normal persistence failure keeps its original debt and rejects HTTP.
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function signal(bindingId:string,expectedResource?:string) {
|
||||
if(stopping)return Promise.reject(new HttpError(503,"Muse receiver is stopping."));
|
||||
const admitted=signalOnce(bindingId,expectedResource);
|
||||
admittedSignals.add(admitted);
|
||||
void admitted.then(()=>admittedSignals.delete(admitted),()=>admittedSignals.delete(admitted));
|
||||
return admitted;
|
||||
}
|
||||
async function prepareHostedHandoff(signal:AbortSignal) {
|
||||
do {
|
||||
signal.throwIfAborted();
|
||||
await Promise.allSettled([...admittedSignals]);
|
||||
await flush();
|
||||
} while(admittedSignals.size||pending.size);
|
||||
}
|
||||
let timer:NodeJS.Timeout|undefined;
|
||||
function start() {if(timer)return;timer=setInterval(()=>void flush().catch(()=>{}),PERSISTENCE_LAG_MS);timer.unref();}
|
||||
async function stop() {if(timer)clearInterval(timer);timer=undefined;await flush();}
|
||||
return {signal,flush,start,stop,persistenceLagMs:PERSISTENCE_LAG_MS};
|
||||
function start() {
|
||||
if(stopPromise)throw new Error("Muse receiver shutdown is still running.");
|
||||
stopping=false;
|
||||
if(timer)return;
|
||||
timer=setInterval(()=>void flush().catch(()=>{}),PERSISTENCE_LAG_MS);timer.unref();
|
||||
}
|
||||
function stop() {
|
||||
if(stopPromise)return stopPromise;
|
||||
stopping=true;
|
||||
if(timer)clearInterval(timer);timer=undefined;
|
||||
stopPromise=(async()=>{
|
||||
await Promise.allSettled([...admittedSignals]);
|
||||
// A signal admitted before stop may add a new batch while an older flush
|
||||
// is in flight. Join both; failed persistence keeps its debt and rejects.
|
||||
do {await flush();} while(pending.size);
|
||||
})().finally(()=>{stopPromise=undefined;});
|
||||
return stopPromise;
|
||||
}
|
||||
return {signal,flush,prepareHostedHandoff,start,stop,persistenceLagMs:PERSISTENCE_LAG_MS};
|
||||
}
|
||||
@@ -36,7 +36,7 @@ export const GMAIL_CONNECTOR_SCOPES = [
|
||||
export { GOOGLE_WORKSPACE_CONNECTOR_PROFILES };
|
||||
|
||||
export type PaperclipCloudConnectorEnvironment = "development" | "test" | "staging" | "production";
|
||||
export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "mcp-client-mirror" | "mcp-revocation-index" | "mcp-dot-subscription-authority";
|
||||
export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "mcp-client-mirror" | "mcp-revocation-index" | "mcp-dot-subscription-authority" | "mcp-muse-contacts";
|
||||
export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | "slack.manager" | "github.bot";
|
||||
export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack";
|
||||
|
||||
@@ -128,6 +128,7 @@ type ConnectorResponse = {
|
||||
|
||||
const ENDPOINTS: Record<PaperclipCloudConnectorOperation, string> = {
|
||||
"mcp-client-mirror": "/v1/connector/mcp-client-mirror",
|
||||
"mcp-muse-contacts": "/v1/connector/mcp-muse-contacts",
|
||||
"mcp-dot-subscription-authority": "/v1/connector/mcp-dot-subscription-authority",
|
||||
"mcp-revocation-index": "/v1/connector/mcp-revocation-index",
|
||||
"slack-events": "/v1/connector/slack-events",
|
||||
@@ -334,7 +335,7 @@ export function createPaperclipCloudConnector(input: {
|
||||
...(secret ? { [secret.field]: secret.value } : {}),
|
||||
};
|
||||
const encodedBody = JSON.stringify(body);
|
||||
if (operation === "mcp-client-mirror" && secret?.field === "binding") {
|
||||
if ((operation === "mcp-client-mirror" || operation === "mcp-muse-contacts") && secret?.field === "binding") {
|
||||
assertMcpClientMirrorEnvelope(body.request, secret.value, encodedBody);
|
||||
}
|
||||
let response: Response;
|
||||
@@ -425,6 +426,10 @@ export function createPaperclipCloudConnector(input: {
|
||||
|
||||
return {
|
||||
instanceIdentity: () => Object.freeze({ instanceId: config.instanceId, environment: config.environment }),
|
||||
async syncMuseReceiverContacts(serialized:string):Promise<unknown> {
|
||||
const response=await call("mcp-muse-contacts",{subject:"instance-client-metadata",companyId:"instance-client-metadata"},{field:"binding",value:serialized});
|
||||
return response.museContactPage;
|
||||
},
|
||||
async syncMcpClientMirror(serialized: string): Promise<unknown> {
|
||||
const response = await call("mcp-client-mirror", {subject:"instance-client-metadata",companyId:"instance-client-metadata"}, {field:"binding",value:serialized});
|
||||
return (response as ConnectorResponse & {mcpClientMirror?:unknown}).mcpClientMirror;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { museReceiverReferenceSchema,museReceiverRecordSchema,type MuseReceiverReference } from "@paperclipai/shared";
|
||||
import { mcpClientMirrorPageFits } from "./client-mirror-wire.js";
|
||||
import { mcpDeviceStatusReferenceSchema,mcpDeviceStatusEntrySchema } from "./device-status-contract.js";
|
||||
import { createHash } from "node:crypto";
|
||||
@@ -14,27 +15,28 @@ export const mcpMirroredClientSchema = z.object({ id: identifier, name: z.string
|
||||
const change = z.discriminatedUnion("operation", [z.object({ operation: z.literal("upsert"), client: mcpMirroredClientSchema }).strict(),
|
||||
z.object({ operation: z.literal("delete"), clientId: identifier }).strict()]);
|
||||
const identity = z.object({ version: z.literal(1),dotProfile:z.literal("hosted-dot-v1").optional(), instanceId: z.string().min(1).max(200), origin, revision,authorizationOrigin:origin.optional(),
|
||||
deviceStatus:mcpDeviceStatusReferenceSchema.optional(),baseRevision: revision.nullable(), expectedRecords: revision });
|
||||
museReceivers:museReceiverReferenceSchema.optional(),deviceStatus:mcpDeviceStatusReferenceSchema.optional(),baseRevision: revision.nullable(), expectedRecords: revision });
|
||||
export const mcpClientMirrorRequestSchema = z.discriminatedUnion("operation", [
|
||||
identity.extend({ operation: z.literal("begin"),deviceKey:z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional() }).strict(),
|
||||
identity.extend({ operation: z.literal("disable") }).strict(),
|
||||
identity.extend({ operation: z.literal("append"), sequence: revision, changes: z.array(change).min(1).max(200) }).strict(),
|
||||
identity.extend({ operation: z.literal("append-device-status"),sequence:revision,entries:z.array(mcpDeviceStatusEntrySchema).min(1).max(200) }).strict(),
|
||||
identity.extend({ operation: z.literal("append-muse-receivers"),sequence:revision,entries:z.array(museReceiverRecordSchema).min(1).max(200) }).strict(),
|
||||
identity.extend({ operation: z.literal("complete") }).strict(),
|
||||
]).refine(mcpClientMirrorPageFits,"MCP client mirror page is too large");
|
||||
export const mcpClientMirrorReceiptSchema = z.object({ version: z.literal(1), instanceId: z.string().min(1).max(200), origin, revision,authorizationOrigin:origin.optional(),
|
||||
deviceStatus:mcpDeviceStatusReferenceSchema.optional(),frontDoor:z.literal("tenant-personal-v1").optional(),dotProfile:z.literal("hosted-dot-v1").optional(),enabled:z.boolean(),generation: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
|
||||
museReceivers:museReceiverReferenceSchema.optional(),deviceStatus:mcpDeviceStatusReferenceSchema.optional(),frontDoor:z.literal("tenant-personal-v1").optional(),dotProfile:z.literal("hosted-dot-v1").optional(),enabled:z.boolean(),generation: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
|
||||
export const mcpClientMirrorResponseSchema = z.discriminatedUnion("complete", [
|
||||
z.object({ complete: z.literal(true), receipt: mcpClientMirrorReceiptSchema }).strict(),
|
||||
z.object({ complete: z.literal(false), nextSequence: revision, receivedRecords: revision,nextDeviceSequence:revision.optional() }).strict(),
|
||||
z.object({ complete: z.literal(false), nextSequence: revision, receivedRecords: revision,nextMuseSequence:revision.optional(),nextDeviceSequence:revision.optional() }).strict(),
|
||||
]);
|
||||
export type McpMirroredClient = z.infer<typeof mcpMirroredClientSchema>;
|
||||
export type McpClientMirrorChange = z.infer<typeof change>;
|
||||
export type McpClientMirrorRequest = z.infer<typeof mcpClientMirrorRequestSchema>;
|
||||
export type McpClientMirrorReceipt = z.infer<typeof mcpClientMirrorReceiptSchema>;
|
||||
export type McpClientMirrorResponse = z.infer<typeof mcpClientMirrorResponseSchema>;
|
||||
export function mcpClientMirrorGeneration(value: Pick<McpClientMirrorRequest,"instanceId"|"origin"|"revision">&{enabled?:boolean;frontDoor?:"tenant-personal-v1";dotProfile?:"hosted-dot-v1";authorizationOrigin?:string;deviceStatus?:z.infer<typeof mcpDeviceStatusReferenceSchema>}) {
|
||||
return createHash("sha256").update(JSON.stringify(["mcp-client-mirror-v1",value.instanceId,value.origin,value.revision,value.enabled??true,value.frontDoor??null,value.deviceStatus??null,value.authorizationOrigin??value.origin,...(value.dotProfile?[value.dotProfile]:[])])).digest("hex");
|
||||
export function mcpClientMirrorGeneration(value: Pick<McpClientMirrorRequest,"instanceId"|"origin"|"revision">&{enabled?:boolean;frontDoor?:"tenant-personal-v1";dotProfile?:"hosted-dot-v1";authorizationOrigin?:string;deviceStatus?:z.infer<typeof mcpDeviceStatusReferenceSchema>;museReceivers?:MuseReceiverReference}) {
|
||||
return createHash("sha256").update(JSON.stringify(["mcp-client-mirror-v1",value.instanceId,value.origin,value.revision,value.enabled??true,value.frontDoor??null,value.deviceStatus??null,value.authorizationOrigin??value.origin,...(value.dotProfile?[value.dotProfile]:[]),...(value.museReceivers?[value.museReceivers]:[])])).digest("hex");
|
||||
}
|
||||
export function mcpClientMirrorPageHash(changes: McpClientMirrorChange[]) {
|
||||
return createHash("sha256").update(JSON.stringify(changes)).digest("hex");
|
||||
|
||||
@@ -2,8 +2,10 @@ import { eq, sql } from "drizzle-orm";
|
||||
import { mcpOauthClientMirrorState as state, mcpOauthClientChanges as changes, type Db } from "@paperclipai/db";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js";
|
||||
|
||||
export type McpClientMutationDatabase = Pick<Db,"select"|"insert"|"update"|"execute">;
|
||||
|
||||
const revisions = new WeakMap<object, number>();
|
||||
export async function prepareMcpClientMutation(tx: Db) {
|
||||
export async function prepareMcpClientMutation(tx: McpClientMutationDatabase) {
|
||||
const existing = revisions.get(tx);
|
||||
if (existing !== undefined) return existing;
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpClientMirror);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { MuseReceiverRecord } from "@paperclipai/shared";
|
||||
import type { McpClientMirrorChange, McpClientMirrorRequest } from "./client-mirror-contract.js";
|
||||
import type { McpDeviceStatusEntry } from "./device-status-contract.js";
|
||||
import { mcpClientMirrorPageFits } from "./client-mirror-wire.js";
|
||||
@@ -33,3 +34,14 @@ export function mcpClientMirrorDevicePages(identity: Identity, entries: McpDevic
|
||||
if(page.length)pages.push(request());
|
||||
return pages;
|
||||
}
|
||||
|
||||
export function mcpClientMirrorMusePages(identity:Identity,entries:MuseReceiverRecord[]):Extract<McpClientMirrorRequest,{operation:"append-muse-receivers"}>[] {
|
||||
type Page=Extract<McpClientMirrorRequest,{operation:"append-muse-receivers"}>;
|
||||
const pages:Page[]=[];let page:MuseReceiverRecord[]=[];
|
||||
const request=():Page=>({...identity,operation:"append-muse-receivers",sequence:pages.length,entries:page});
|
||||
for(const entry of entries){const candidate={...request(),entries:[...page,entry]};
|
||||
if(page.length&&(page.length===200||!mcpClientMirrorPageFits(candidate))){pages.push(request());page=[];}
|
||||
page.push(entry);if(!mcpClientMirrorPageFits(request()))throw new Error("Muse receiver record exceeds its bounded wire contract");
|
||||
}
|
||||
if(page.length)pages.push(request());return pages;
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import { mcpClientMirrorClientPages, mcpClientMirrorDevicePages } from "./client-mirror-pages.js";
|
||||
import { registerConnectionEventWake,hasConnectionEventWakeReceiver } from "../connection-event-wake.js";
|
||||
import { museReceiver } from "../muse-receiver.js";
|
||||
import { readMuseReceiverProjection,syncMuseContactCustody } from "../../modules/external-agents/index.js";
|
||||
import { museAgentBindings } from "@paperclipai/db";
|
||||
import { mcpClientMirrorClientPages, mcpClientMirrorDevicePages,mcpClientMirrorMusePages } from "./client-mirror-pages.js";
|
||||
import { getCloudRuntimeIdentity } from "../cloud-runtime-identity.js";
|
||||
import { mcpDeviceStatusEntrySchema,mcpDeviceStatusFingerprint,mcpDeviceStatusGeneration,mcpDeviceStatusKeyId } from "./device-status-contract.js";
|
||||
import { deriveLocalEncryptedInstanceSecret } from "../../secrets/local-encrypted-provider.js";
|
||||
@@ -17,7 +21,7 @@ import { mcpClientMirrorGeneration, mcpClientMirrorReceiptSchema, mcpClientMirro
|
||||
export function sameMcpClientMirrorReceipt(left:McpClientMirrorReceipt,right:McpClientMirrorReceipt){
|
||||
return left.version===right.version&&left.instanceId===right.instanceId&&left.origin===right.origin
|
||||
&&left.revision===right.revision&&left.enabled===right.enabled&&left.generation===right.generation
|
||||
&&left.dotProfile===right.dotProfile&&left.frontDoor===right.frontDoor&&(left.authorizationOrigin??left.origin)===(right.authorizationOrigin??right.origin)
|
||||
&&JSON.stringify(left.museReceivers)===JSON.stringify(right.museReceivers)&&left.dotProfile===right.dotProfile&&left.frontDoor===right.frontDoor&&(left.authorizationOrigin??left.origin)===(right.authorizationOrigin??right.origin)
|
||||
&&left.deviceStatus?.keyId===right.deviceStatus?.keyId&&left.deviceStatus?.generation===right.deviceStatus?.generation
|
||||
&&left.deviceStatus?.count===right.deviceStatus?.count;
|
||||
}
|
||||
@@ -30,8 +34,10 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick<ReturnType<ty
|
||||
const publish = input.publish ?? (connector ? (request:McpClientMirrorRequest) => connector.syncMcpClientMirror(JSON.stringify(request)) : undefined);
|
||||
let pending = true,refreshPublished=true,fullRecovery=false,reserveFullRevision=false;
|
||||
let boundStackId=getCloudRuntimeIdentity()?.stackId;
|
||||
let stopImportWake=()=>{};
|
||||
const importWakeArmed=()=>Boolean(connector&&hasConnectionEventWakeReceiver(db,{importsClientMetadata:true}));
|
||||
const worker=coordinator.register(DELIVERY_QUEUES.mcpClientMirror, {
|
||||
retryMs:5_000,pausePassiveMaintenance:true,onSettled:()=>{pending=true;},
|
||||
retryMs:5_000,pausePassiveMaintenance:true,onSettled:()=>{pending=true;},onStop:()=>stopImportWake(),
|
||||
async run(signal) {
|
||||
pending=false;
|
||||
const managedIdentity=getCloudRuntimeIdentity();
|
||||
@@ -41,7 +47,9 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick<ReturnType<ty
|
||||
try {
|
||||
const experimental=await instanceSettingsService(db).getExperimentalReadOnly();
|
||||
dotProfile=experimental.enableOpenAiDot?"hosted-dot-v1":false;
|
||||
enabled=experimental.enablePublicMcp||Boolean(dotProfile);
|
||||
const [receiverObligation]=await db.select({id:museAgentBindings.id}).from(museAgentBindings).where(sql`${museAgentBindings.pairedAt} is not null and (${museAgentBindings.revokedAt} is null or ${museAgentBindings.detectorRemovedAt} is null)`).limit(1);
|
||||
const museRequired=experimental.enableMuse&&experimental.enableNativeRunner||Boolean(receiverObligation);
|
||||
enabled=experimental.enablePublicMcp||Boolean(dotProfile)||museRequired;
|
||||
const assertCurrentAuthority=()=>{
|
||||
const identity=getCloudRuntimeIdentity(),currentConfig=paperclipCloudConnectorConfigFromEnv();
|
||||
if(!identity||identity.stackId!==managedIdentity.stackId||boundStackId!==undefined&&identity.stackId!==boundStackId
|
||||
@@ -51,7 +59,8 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick<ReturnType<ty
|
||||
boundStackId??=identity.stackId;
|
||||
};
|
||||
if(enabled)assertCurrentAuthority();
|
||||
const publishEnabled=(request:McpClientMirrorRequest)=>{assertCurrentAuthority();publicationAttempted=true;return publish(request);};
|
||||
if(connector&&managedIdentity&&museRequired)await syncMuseContactCustody(db,{stackId:managedIdentity.stackId,instanceId,origin},serialized=>connector.syncMuseReceiverContacts(serialized),signal);
|
||||
const publishEnabled=(request:McpClientMirrorRequest)=>{assertCurrentAuthority();if(request.museReceivers?.contactImportWakeVersion===1&&!importWakeArmed())throw new Error("Client metadata import receiver stopped");publicationAttempted=true;return publish(request);};
|
||||
const captured=await db.transaction(async tx=>{
|
||||
await tx.execute(sql`SELECT pg_advisory_xact_lock(736721042)`);
|
||||
if(enabled)await tx.insert(state).values({id:"public",revision:0}).onConflictDoNothing();
|
||||
@@ -87,8 +96,10 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick<ReturnType<ty
|
||||
if(deviceRows.length>1000)throw new Error("MCP retained device set exceeds canonical1000 admission bound");
|
||||
const entries=deviceRows.map(row=>mcpDeviceStatusEntrySchema.parse({requestId:row.requestId,clientId:row.clientId,resource:row.resource,ingressOwner:row.ingressOwner,status:row.status,expiresAt:row.expiresAt.getTime(),fingerprint:mcpDeviceStatusFingerprint(deviceKey,row.deviceCodeHash,row.clientId,row.resource)}));
|
||||
const deviceStatus={keyId,generation:mcpDeviceStatusGeneration({instanceId,origin,revision:captured.revision,keyId},entries),count:entries.length};
|
||||
const museProjection=museRequired?await readMuseReceiverProjection(db,{stackId:managedIdentity.stackId,instanceId,origin},captured.revision,{enabled:experimental.enableMuse&&experimental.enableNativeRunner,contactImportWakeVersion:importWakeArmed()?1:undefined}):undefined;
|
||||
const muse=museProjection?.complete?museProjection:undefined;
|
||||
if(baseRevision===captured.revision&&old.success){
|
||||
if((old.data.dotProfile??false)===dotProfile&&JSON.stringify(old.data.deviceStatus)===JSON.stringify(deviceStatus)&&(old.data.authorizationOrigin??origin)===(input.authorizationOrigin??origin))return;
|
||||
if(JSON.stringify(old.data.museReceivers)===JSON.stringify(muse?.reference)&&(old.data.dotProfile??false)===dotProfile&&JSON.stringify(old.data.deviceStatus)===JSON.stringify(deviceStatus)&&(old.data.authorizationOrigin??origin)===(input.authorizationOrigin??origin))return;
|
||||
await db.transaction(async tx=>{
|
||||
await tx.execute(sql`SELECT pg_advisory_xact_lock(736721042)`);
|
||||
const [current]=await tx.select({revision:state.revision}).from(state).where(eq(state.id,"public")).for("update");
|
||||
@@ -99,12 +110,12 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick<ReturnType<ty
|
||||
const [count] = baseRevision===null ? await db.select({total:sql<number>`count(*)::int`}).from(clients)
|
||||
: await db.select({total:sql<number>`count(*)::int`}).from(changes).where(and(gt(changes.revision,baseRevision),lte(changes.revision,captured.revision)));
|
||||
if (!count || !Number.isSafeInteger(count.total) || count.total<0) throw new Error("Invalid MCP client mirror count");
|
||||
const identity = {version:1 as const,...(dotProfile?{dotProfile}:{}),instanceId,origin,revision:captured.revision,baseRevision,expectedRecords:count.total,deviceStatus,...(input.authorizationOrigin?{authorizationOrigin:input.authorizationOrigin}:{})};
|
||||
const identity = {version:1 as const,...(dotProfile?{dotProfile}:{}),instanceId,origin,revision:captured.revision,baseRevision,expectedRecords:count.total,deviceStatus,...(muse?{museReceivers:muse.reference}:{}),...(input.authorizationOrigin?{authorizationOrigin:input.authorizationOrigin}:{})};
|
||||
const [owned]=await db.update(state).set({remoteResponsibility:true}).where(and(eq(state.id,"public"),eq(state.revision,captured.revision))).returning({id:state.id});
|
||||
if(!owned){pending=true;return;}
|
||||
let result = mcpClientMirrorResponseSchema.parse(await publishEnabled({...identity,operation:"begin",deviceKey}));
|
||||
if (!result.complete) {
|
||||
const resumeSequence=result.nextSequence,resumeDeviceSequence=result.nextDeviceSequence??0;
|
||||
const resumeSequence=result.nextSequence,resumeDeviceSequence=result.nextDeviceSequence??0,resumeMuseSequence=result.nextMuseSequence??0;
|
||||
let cursor:string|undefined, sequence=0, sent=0;
|
||||
while (true) {
|
||||
signal.throwIfAborted();
|
||||
@@ -130,6 +141,9 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick<ReturnType<ty
|
||||
for(const page of mcpClientMirrorDevicePages(identity,entries)){
|
||||
if(page.sequence>=resumeDeviceSequence)result=mcpClientMirrorResponseSchema.parse(await publishEnabled(page));
|
||||
}
|
||||
if(muse)for(const page of mcpClientMirrorMusePages(identity,muse.records)){
|
||||
if(page.sequence>=resumeMuseSequence)result=mcpClientMirrorResponseSchema.parse(await publishEnabled(page));
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
const [current]=await db.select({revision:state.revision}).from(state).where(eq(state.id,"public"));
|
||||
if(current&&Number.isSafeInteger(current.revision)&¤t.revision>captured.revision){pending=true;return;}
|
||||
@@ -138,6 +152,8 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick<ReturnType<ty
|
||||
}
|
||||
if(!result.complete||!result.receipt.enabled||(result.receipt.dotProfile??false)!==dotProfile||JSON.stringify(result.receipt.deviceStatus)!==JSON.stringify(deviceStatus)||result.receipt.instanceId!==instanceId||result.receipt.origin!==origin||result.receipt.revision!==captured.revision||result.receipt.generation!==mcpClientMirrorGeneration(result.receipt))throw new Error("MCP client mirror was not acknowledged");
|
||||
const receipt=result.receipt;
|
||||
if(JSON.stringify(receipt.museReceivers)!==JSON.stringify(muse?.reference))throw new Error("Muse receiver publication was not acknowledged");
|
||||
if(muse)await museReceiver(db).prepareHostedHandoff(signal);
|
||||
let retained=false;
|
||||
await db.transaction(async tx=>{
|
||||
await tx.execute(sql`SELECT pg_advisory_xact_lock(736721042)`);
|
||||
@@ -167,5 +183,6 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick<ReturnType<ty
|
||||
},
|
||||
hasPending:async()=>false,nextRunAt:()=>pending?Date.now()+5_000:null,
|
||||
});
|
||||
if(connector&&origin&&instanceId)stopImportWake=registerConnectionEventWake(db,()=>{pending=true;worker.wake();},{importsClientMetadata:true});
|
||||
return {worker,instanceId};
|
||||
}
|
||||
@@ -3,6 +3,7 @@ const digest = "f".repeat(64);
|
||||
const identity = {
|
||||
version: 1, dotProfile: "hosted-dot-v1", instanceId: "", origin: "", revision: maxInteger,
|
||||
baseRevision: maxInteger, expectedRecords: maxInteger, authorizationOrigin: "",
|
||||
museReceivers: {profile:"hosted-muse-v1",generation:digest,count:1000},
|
||||
deviceStatus: { keyId: digest, generation: digest, count: 1000 },
|
||||
};
|
||||
const bytes = (value: unknown) => Buffer.byteLength(JSON.stringify(value), "utf8");
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { museReceiverDiscoveryDocument,isMuseReceiverDiscoveryRequest } from "../../modules/external-agents/index.js";
|
||||
export type McpDiscoveryProfile = "personal-mcp" | "dot-mcp";
|
||||
export type McpDiscoverySnapshotProfile=McpDiscoveryProfile|"muse-agent";
|
||||
export interface McpDiscovery {
|
||||
origin: string;
|
||||
authorizationOrigin: string;
|
||||
profiles: McpDiscoveryProfile[];
|
||||
profiles: McpDiscoverySnapshotProfile[];
|
||||
}
|
||||
const profiles = ["personal-mcp","dot-mcp"] as const;
|
||||
const profiles = ["personal-mcp","dot-mcp","muse-agent"] as const;
|
||||
function origin(value: unknown): string {
|
||||
if (typeof value !== "string" || value.length > 2048) throw new Error("Invalid MCP discovery origin");
|
||||
const url = new URL(value);
|
||||
@@ -15,13 +17,14 @@ export function parseMcpDiscovery(value: unknown): McpDiscovery {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid MCP discovery snapshot");
|
||||
const row = value as Record<string,unknown>;
|
||||
const selected=row.profiles;
|
||||
if (Object.keys(row).sort().join() !== "authorizationOrigin,origin,profiles" || !Array.isArray(selected) || !selected.length || selected.length > 2
|
||||
if (Object.keys(row).sort().join() !== "authorizationOrigin,origin,profiles" || !Array.isArray(selected) || !selected.length || selected.length > 3
|
||||
|| selected.some((profile,index) => !profiles.includes(profile) || index > 0 && profiles.indexOf(profile) <= profiles.indexOf(selected[index-1]))) throw new Error("Invalid MCP discovery profiles");
|
||||
return { origin: origin(row.origin), authorizationOrigin: origin(row.authorizationOrigin), profiles: selected as McpDiscoveryProfile[] };
|
||||
return { origin: origin(row.origin), authorizationOrigin: origin(row.authorizationOrigin), profiles: selected as McpDiscoverySnapshotProfile[] };
|
||||
}
|
||||
export function mcpDiscoveryDocuments(raw: McpDiscovery): Array<{ path: string; document: Record<string,unknown> }> {
|
||||
const input = parseMcpDiscovery(raw), documents: Array<{ path: string; document: Record<string,unknown> }> = [];
|
||||
for (const profile of input.profiles) {
|
||||
if(profile==="muse-agent"){documents.push(museReceiverDiscoveryDocument(input));continue;}
|
||||
const dot = profile === "dot-mcp", endpoint = dot ? "/mcp/runner" : "/mcp/paperclip", oauthPath = dot ? "/mcp/runner/oauth" : "/mcp/oauth";
|
||||
const issuer = dot ? input.origin + oauthPath : input.origin, prefix = input.origin + oauthPath;
|
||||
const scopes = dot ? ["paperclip:agent","offline_access"] : ["paperclip:read","paperclip:write","paperclip:configure","offline_access"];
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { IdleMcpInspectionBudget } from "./idle-wake-proof.js";
|
||||
import { mcpClientMirrorGeneration,mcpClientMirrorReceiptSchema,type McpClientMirrorReceipt } from "./client-mirror-contract.js";
|
||||
import type { IdleDeadlineSnapshot } from "../idle-deadline-types.js";
|
||||
|
||||
export async function readIdleMcpClientMirror(tx:Pick<Db,"select">,context:{budget:IdleMcpInspectionBudget;enabled:boolean;origin?:string;instanceId?:string;managedStackId?:string;authorizationOrigin?:string;unsupportedProfiles?:boolean;dotEnabled?:boolean}):Promise<IdleDeadlineSnapshot&{receipt?:McpClientMirrorReceipt}>{
|
||||
export async function readIdleMcpClientMirror(tx:Pick<Db,"select">,context:{budget:IdleMcpInspectionBudget;enabled:boolean;origin?:string;instanceId?:string;managedStackId?:string;authorizationOrigin?:string;unsupportedProfiles?:boolean;dotEnabled?:boolean;personalEnabled?:boolean;museEnabled?:boolean}):Promise<IdleDeadlineSnapshot&{receipt?:McpClientMirrorReceipt}>{
|
||||
if(!context.managedStackId)return{blocked:context.enabled,state:context.enabled?"unconfigured-front-door":"absent",deadlines:[]};
|
||||
await context.budget.beforeRead();
|
||||
const[row]=await tx.select().from(state).where(eq(state.id,"public"));context.budget.check();
|
||||
@@ -25,6 +25,8 @@ export async function readIdleMcpClientMirror(tx:Pick<Db,"select">,context:{budg
|
||||
const dotReady = !context.dotEnabled || receipt.data.dotProfile === "hosted-dot-v1" && dot?.version === 1
|
||||
&& dot.profile === "hosted-dot-v1" && dot.stackId === context.managedStackId
|
||||
&& dot.instanceId === context.instanceId && dot.origin === context.origin;
|
||||
const ready=dotReady&&receipt.data.frontDoor==="tenant-personal-v1"&&receipt.data.deviceStatus!==undefined&&row.deviceCutoverAt instanceof Date&&Number.isFinite(row.deviceCutoverAt.getTime())&&row.deviceCutoverStackId===context.managedStackId&&(receipt.data.authorizationOrigin??receipt.data.origin)===receipt.data.origin&&!context.unsupportedProfiles;
|
||||
const museOnly=context.museEnabled&&!context.personalEnabled&&!context.dotEnabled;
|
||||
const originalReady=receipt.data.frontDoor==="tenant-personal-v1"&&receipt.data.deviceStatus!==undefined&&row.deviceCutoverAt instanceof Date&&Number.isFinite(row.deviceCutoverAt.getTime())&&row.deviceCutoverStackId===context.managedStackId&&(receipt.data.authorizationOrigin??receipt.data.origin)===receipt.data.origin;
|
||||
const ready=dotReady&&!context.unsupportedProfiles&&(museOnly?receipt.data.museReceivers?.profile==="hosted-muse-v1":originalReady);
|
||||
return{blocked:!ready,state:[ready?"tenant-facade-v1":"incomplete-front-door",receipt.data,row.deviceCutoverStackId,row.deviceCutoverAt?.toISOString()??null,...(context.dotEnabled?[row.dotDeviceCutover??null]:[])],receipt:receipt.data,deadlines:[]};
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
import { MUSE_RESOURCE_PATH } from "@paperclipai/shared";
|
||||
import { hasConnectionEventWakeReceiver } from "../connection-event-wake.js";
|
||||
import { readIdleMuseReceiverProof,type IdleMuseReceiverProof } from "../../modules/external-agents/index.js";
|
||||
import { readIdleMcpDeviceStatus } from "./idle-device-status.js";
|
||||
import { getCloudRuntimeIdentity } from "../cloud-runtime-identity.js";
|
||||
import { readIdleMcpDeviceCutover } from "./idle-device-cutover.js";
|
||||
@@ -21,6 +24,7 @@ export function registerIdleMcpOwners(owner: object, services: { config: PublicM
|
||||
}
|
||||
export interface IdleMcpSleepProof {
|
||||
ingress: IdleMcpWakeProof;
|
||||
muse?:IdleMuseReceiverProof;
|
||||
subscriptions: IdleMcpSubscriptionProof;
|
||||
retries: IdleMcpEventScheduleProof;
|
||||
frontDoor: IdleDeadlineSnapshot;
|
||||
@@ -37,13 +41,18 @@ export async function readIdleMcpSleepProof(tx: Pick<Db, "select">, owner: objec
|
||||
const services = owners.get(owner);
|
||||
await context.budget.beforeRead();
|
||||
const feature = await instanceSettingsService(tx as Db).getExperimentalReadOnly();
|
||||
const frontDoor = await readIdleMcpClientMirror(tx,{budget:context.budget,enabled:feature.enablePublicMcp||feature.enableOpenAiDot||feature.enableGrokBot&&feature.enableNativeRunner,origin:services?.config?.origin,instanceId:services?.clientMirrorInstanceId,managedStackId:getCloudRuntimeIdentity()?.stackId,authorizationOrigin:services?.config?.authorizationOrigin,dotEnabled:feature.enableOpenAiDot,unsupportedProfiles:feature.enableGrokBot&&feature.enableNativeRunner});
|
||||
const frontDoor = await readIdleMcpClientMirror(tx,{budget:context.budget,enabled:feature.enablePublicMcp||feature.enableOpenAiDot||(feature.enableMuse||feature.enableGrokBot)&&feature.enableNativeRunner,origin:services?.config?.origin,instanceId:services?.clientMirrorInstanceId,managedStackId:getCloudRuntimeIdentity()?.stackId,authorizationOrigin:services?.config?.authorizationOrigin,dotEnabled:feature.enableOpenAiDot,personalEnabled:feature.enablePublicMcp,museEnabled:feature.enableMuse&&feature.enableNativeRunner,unsupportedProfiles:feature.enableGrokBot&&feature.enableNativeRunner});
|
||||
const ingress = await readIdleMcpWakeProof(tx, { ...context,
|
||||
clientMirror:frontDoor.receipt,
|
||||
museResource:services?.config?services.config.origin+MUSE_RESOURCE_PATH:"",
|
||||
personalResource: services?.config?.resource ?? "", dotResource: services?.config ? services.config.origin + "/mcp/runner" : "",
|
||||
discovery: services?.config && (feature.enablePublicMcp || feature.enableOpenAiDot) ? { origin: services.config.origin, authorizationOrigin: services.config.authorizationOrigin ?? services.config.origin,
|
||||
profiles: [...(feature.enablePublicMcp ? ["personal-mcp" as const] : []), ...(feature.enableOpenAiDot ? ["dot-mcp" as const] : [])] } : undefined,
|
||||
personalEnabled: feature.enablePublicMcp, dotEnabled: feature.enableOpenAiDot });
|
||||
discovery: services?.config && (feature.enablePublicMcp || feature.enableOpenAiDot || feature.enableMuse&&feature.enableNativeRunner) ? { origin: services.config.origin, authorizationOrigin: services.config.authorizationOrigin ?? services.config.origin,
|
||||
profiles: [...(feature.enablePublicMcp ? ["personal-mcp" as const] : []), ...(feature.enableOpenAiDot ? ["dot-mcp" as const] : []),...(feature.enableMuse&&feature.enableNativeRunner?["muse-agent" as const]:[])] } : undefined,
|
||||
personalEnabled: feature.enablePublicMcp, dotEnabled: feature.enableOpenAiDot,museEnabled:feature.enableMuse&&feature.enableNativeRunner });
|
||||
const managedIdentity=getCloudRuntimeIdentity();
|
||||
const muse=await readIdleMuseReceiverProof(tx,{enabled:feature.enableMuse&&feature.enableNativeRunner,contactImportWakeVersion:hasConnectionEventWakeReceiver(owner,{importsClientMetadata:true})?1:undefined,
|
||||
namespace:managedIdentity&&services?.config&&services.clientMirrorInstanceId?{stackId:managedIdentity.stackId,origin:services.config.origin,instanceId:services.clientMirrorInstanceId}:undefined,
|
||||
receipt:frontDoor.receipt,now:context.now,budget:context.budget});
|
||||
const absent = { revision: "absent", reconciled: false };
|
||||
const personal = services?.personal?.reconciliationSnapshot() ?? absent, dot = services?.dot?.reconciliationSnapshot() ?? absent;
|
||||
const personalDestination = services?.personal?.createIdleDestinationInspector();
|
||||
@@ -55,8 +64,8 @@ export async function readIdleMcpSleepProof(tx: Pick<Db, "select">, owner: objec
|
||||
const legacyDevices=feature.enablePublicMcp||feature.enableOpenAiDot?await readIdleMcpDeviceCutover(tx,context):{blocked:false,state:"absent",deadlines:[]};
|
||||
const transfers = await readIdleMcpTransferSchedule(tx, context);
|
||||
const handoffs = await readIdleMcpAuthorizationHandoffs(tx, context);
|
||||
const schedule = { blocked: frontDoor.blocked || deviceStatus.blocked || legacyDevices.blocked || retries.blocked || transfers.blocked || handoffs.blocked, state: [frontDoor.state,deviceStatus.state,legacyDevices.state,retries.state,transfers.state,handoffs.state], deadlines: [...legacyDevices.deadlines,...retries.deadlines,...transfers.deadlines,...handoffs.deadlines] };
|
||||
const schedule = { blocked: muse.blocked || frontDoor.blocked || deviceStatus.blocked || legacyDevices.blocked || retries.blocked || transfers.blocked || handoffs.blocked, state: [muse.state,frontDoor.state,deviceStatus.state,legacyDevices.state,retries.state,transfers.state,handoffs.state], deadlines: [...muse.deadlines,...legacyDevices.deadlines,...retries.deadlines,...transfers.deadlines,...handoffs.deadlines] };
|
||||
context.budget.check();
|
||||
return { ingress, subscriptions, retries, frontDoor, deviceStatus,legacyDevices, transfers, handoffs, schedule,
|
||||
return { ingress,muse, subscriptions, retries, frontDoor, deviceStatus,legacyDevices, transfers, handoffs, schedule,
|
||||
generation: createHash("sha256").update(JSON.stringify([ingress.generation, subscriptions.generation, schedule])).digest("hex") };
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { createHash } from "node:crypto";
|
||||
import { PUBLIC_MCP_SCOPES, DOT_RUNNER_MCP_SCOPES } from "@paperclipai/shared";
|
||||
import { and, asc, eq, gt, isNull, or, sql } from "drizzle-orm";
|
||||
import {
|
||||
agents, authUsers, companies, companyMemberships, dotAgentBindings,
|
||||
agents, authUsers, companies, companyMemberships, dotAgentBindings,museAgentBindings,
|
||||
mcpOauthGrants, mcpOauthTokens, type Db,
|
||||
} from "@paperclipai/db";
|
||||
import { mcpRevocationAuthorityId, parseMcpRevocationIndexReceipt, type McpRevocationIndexReceipt } from "./revocation-index-contract.js";
|
||||
@@ -18,6 +18,13 @@ export interface IdleMcpWakeProof {
|
||||
dotBindingIds: string[];
|
||||
}
|
||||
export interface IdleMcpCredentialRow {
|
||||
museBindingId?:string|null;
|
||||
museStatus?:string|null;
|
||||
museGeneration?:number|null;
|
||||
museChallengeHash?:string|null;
|
||||
agentProvider?:string|null;
|
||||
agentMuseBindingId?:string|null;
|
||||
companyStatus?:string|null;
|
||||
grantId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
@@ -50,6 +57,8 @@ export interface IdleMcpWakeProofInput {
|
||||
dotResource: string;
|
||||
personalEnabled: boolean;
|
||||
dotEnabled: boolean;
|
||||
museEnabled?:boolean;
|
||||
museResource?:string;
|
||||
now: number;
|
||||
}
|
||||
|
||||
@@ -69,17 +78,21 @@ export function projectIdleMcpWakeProof(rows: IdleMcpCredentialRow[], input: Idl
|
||||
&& row.dotBindingId !== null && row.dotGeneration !== null && Number.isSafeInteger(row.dotGeneration) && row.dotGeneration > 0
|
||||
&& row.dotPairingHash === null && row.dotChallengeHash === null
|
||||
&& row.agentStatus !== null && !["terminated", "pending_approval"].includes(row.agentStatus);
|
||||
if (!personal && !dot) continue;
|
||||
const muse=Boolean(input.museEnabled&&row.resource===input.museResource&&row.purpose==="agent"&&row.scopes.includes("paperclip:agent")&&row.scopes.every(scope=>["paperclip:agent","offline_access"].includes(scope))
|
||||
&&row.membershipRole!=="viewer"&&row.companyStatus==="active"&&row.agentProvider==="muse"&&row.agentMuseBindingId===row.museBindingId
|
||||
&&row.museBindingId&&row.museStatus==="ready"&&row.museGeneration!==null&&row.museGeneration!==undefined&&Number.isSafeInteger(row.museGeneration)&&row.museGeneration>0
|
||||
&&row.museChallengeHash===null&&row.agentStatus!==null&&!["terminated","pending_approval"].includes(row.agentStatus));
|
||||
if (!personal && !dot&&!muse) continue;
|
||||
if (row.tokenKind !== "access" && row.tokenKind !== "refresh") throw new Error("Unknown MCP credential kind");
|
||||
if (row.tokenKind === "refresh" && row.tokenUsedAt !== null) continue;
|
||||
if (row.tokenExpiresAt === null ? !dot || row.tokenKind !== "refresh" : row.tokenExpiresAt.getTime() <= input.now) continue;
|
||||
tokens.push({ profile: personal ? "personal-mcp" : "dot-mcp", tokenKind: row.tokenKind,
|
||||
tokens.push({ profile: personal ? "personal-mcp" : muse?"muse-agent":"dot-mcp", tokenKind: row.tokenKind,
|
||||
tokenHash: row.tokenHash, expiresAt: row.tokenExpiresAt?.toISOString() ?? null, clientId: row.clientId });
|
||||
grantIds.add(row.grantId);
|
||||
if (dot) dotBindingIds.add(row.dotBindingId!);
|
||||
}
|
||||
const admission = createMcpWakeAdmission({ stackId: input.stackId, ownerId: input.ownerId,
|
||||
capabilityGeneration: input.capabilityGeneration, challenge: input.challenge, tokens, discovery: input.discovery, clientMirror: input.clientMirror,...(!input.personalEnabled&&!input.dotEnabled?{absent:true as const}:{}) });
|
||||
capabilityGeneration: input.capabilityGeneration, challenge: input.challenge, tokens, discovery: input.discovery, clientMirror: input.clientMirror,...(!input.personalEnabled&&!input.dotEnabled&&!input.museEnabled?{absent:true as const}:{}) });
|
||||
return { admission, generation: createHash("sha256").update(JSON.stringify([admission.generation, rows.map(({ tokenHash: _private, ...row }) => row)])).digest("hex"),
|
||||
grantIds: [...grantIds].sort(), dotBindingIds: [...dotBindingIds].sort() };
|
||||
}
|
||||
@@ -97,6 +110,8 @@ export async function readIdleMcpWakeProof(tx: Pick<Db, "select">, input: IdleMc
|
||||
dotBindingId: dotAgentBindings.id, dotProvider: dotAgentBindings.providerKind,
|
||||
dotStatus: dotAgentBindings.status, dotGeneration: dotAgentBindings.generation,
|
||||
dotPairingHash: dotAgentBindings.pairingCodeHash, dotChallengeHash: dotAgentBindings.challengeHash,
|
||||
museBindingId:museAgentBindings.id,museStatus:museAgentBindings.status,museGeneration:museAgentBindings.generation,museChallengeHash:museAgentBindings.challengeHash,
|
||||
agentProvider:sql<string>`${agents.adapterConfig}->>'provider'`,agentMuseBindingId:sql<string>`${agents.adapterConfig}->>'museBindingId'`,companyStatus:companies.status,
|
||||
agentStatus: agents.status, membershipRole: companyMemberships.membershipRole,
|
||||
}).from(mcpOauthTokens)
|
||||
.innerJoin(mcpOauthGrants, and(eq(mcpOauthGrants.id, mcpOauthTokens.grantId), isNull(mcpOauthGrants.revokedAt)))
|
||||
@@ -108,6 +123,7 @@ export async function readIdleMcpWakeProof(tx: Pick<Db, "select">, input: IdleMc
|
||||
.leftJoin(dotAgentBindings, and(eq(dotAgentBindings.grantId, mcpOauthGrants.id),
|
||||
eq(dotAgentBindings.companyId, mcpOauthGrants.companyId), eq(dotAgentBindings.agentId, mcpOauthGrants.agentId),
|
||||
eq(dotAgentBindings.operatorId, mcpOauthGrants.userId), isNull(dotAgentBindings.revokedAt)))
|
||||
.leftJoin(museAgentBindings,and(eq(museAgentBindings.grantId,mcpOauthGrants.id),eq(museAgentBindings.companyId,mcpOauthGrants.companyId),eq(museAgentBindings.agentId,mcpOauthGrants.agentId),eq(museAgentBindings.operatorId,mcpOauthGrants.userId),isNull(museAgentBindings.revokedAt)))
|
||||
.where(and(or(gt(mcpOauthTokens.expiresAt, new Date(input.now)), isNull(mcpOauthTokens.expiresAt)),
|
||||
|
||||
|
||||
@@ -119,7 +135,9 @@ export async function readIdleMcpWakeProof(tx: Pick<Db, "select">, input: IdleMc
|
||||
const authorities = await tx.select({ grant: mcpOauthGrants,
|
||||
dotBindingId: dotAgentBindings.id, dotProvider: dotAgentBindings.providerKind, dotStatus: dotAgentBindings.status,
|
||||
dotGeneration: dotAgentBindings.generation, dotPairingHash: dotAgentBindings.pairingCodeHash,
|
||||
dotChallengeHash: dotAgentBindings.challengeHash, agentStatus: agents.status,
|
||||
dotChallengeHash: dotAgentBindings.challengeHash,
|
||||
museBindingId:museAgentBindings.id,museStatus:museAgentBindings.status,museGeneration:museAgentBindings.generation,museChallengeHash:museAgentBindings.challengeHash,
|
||||
agentProvider:sql<string>`${agents.adapterConfig}->>'provider'`,agentMuseBindingId:sql<string>`${agents.adapterConfig}->>'museBindingId'`,companyStatus:companies.status,agentStatus: agents.status,
|
||||
membershipRole: companyMemberships.membershipRole,
|
||||
}).from(mcpOauthGrants)
|
||||
.innerJoin(companies, and(eq(companies.id, mcpOauthGrants.companyId), sql`${companies.status} <> 'archived'`))
|
||||
@@ -129,6 +147,7 @@ export async function readIdleMcpWakeProof(tx: Pick<Db, "select">, input: IdleMc
|
||||
.leftJoin(agents, and(eq(agents.id, mcpOauthGrants.agentId), eq(agents.companyId, mcpOauthGrants.companyId)))
|
||||
.leftJoin(dotAgentBindings, and(eq(dotAgentBindings.grantId, mcpOauthGrants.id), eq(dotAgentBindings.companyId, mcpOauthGrants.companyId),
|
||||
eq(dotAgentBindings.agentId, mcpOauthGrants.agentId), eq(dotAgentBindings.operatorId, mcpOauthGrants.userId), isNull(dotAgentBindings.revokedAt)))
|
||||
.leftJoin(museAgentBindings,and(eq(museAgentBindings.grantId,mcpOauthGrants.id),eq(museAgentBindings.companyId,mcpOauthGrants.companyId),eq(museAgentBindings.agentId,mcpOauthGrants.agentId),eq(museAgentBindings.operatorId,mcpOauthGrants.userId),isNull(museAgentBindings.revokedAt)))
|
||||
.where(isNull(mcpOauthGrants.revokedAt)).orderBy(asc(mcpOauthGrants.id)).limit(1001);
|
||||
if (authorities.length > 1000) throw new Error("Too many active MCP grant authorities");
|
||||
const grantIds: string[] = [], dotBindingIds: string[] = [], revocationAuthorities: McpRevocationIndexReceipt[] = [];
|
||||
@@ -142,7 +161,11 @@ export async function readIdleMcpWakeProof(tx: Pick<Db, "select">, input: IdleMc
|
||||
&& row.membershipRole !== "viewer" && row.dotProvider === "openai_dot" && ["connected", "ready"].includes(row.dotStatus ?? "")
|
||||
&& row.dotBindingId !== null && row.dotGeneration !== null && Number.isSafeInteger(row.dotGeneration) && row.dotGeneration > 0
|
||||
&& row.dotPairingHash === null && row.dotChallengeHash === null && row.agentStatus !== null && !["terminated", "pending_approval"].includes(row.agentStatus);
|
||||
if ((!personal && !dot) || !grant.revocationIndexReceipt) continue;
|
||||
const muse=Boolean(input.museEnabled&&grant.resource===input.museResource&&grant.purpose==="agent"&&grant.scopes.includes("paperclip:agent")&&grant.scopes.every(scope=>["paperclip:agent","offline_access"].includes(scope))
|
||||
&&row.membershipRole!=="viewer"&&row.companyStatus==="active"&&row.agentProvider==="muse"&&row.agentMuseBindingId===row.museBindingId
|
||||
&&row.museBindingId&&row.museStatus==="ready"&&row.museGeneration!==null&&Number.isSafeInteger(row.museGeneration)&&row.museGeneration>0&&row.museChallengeHash===null
|
||||
&&row.agentStatus!==null&&!["terminated","pending_approval"].includes(row.agentStatus));
|
||||
if ((!personal && !dot&&!muse) || !grant.revocationIndexReceipt) continue;
|
||||
const receipt = parseMcpRevocationIndexReceipt(grant.revocationIndexReceipt);
|
||||
if (receipt.revision !== grant.revocationRevision || receipt.authorityId !== mcpRevocationAuthorityId(grant.id, receipt.keyId)) continue;
|
||||
grantIds.push(grant.id); if (dot) dotBindingIds.push(row.dotBindingId!); revocationAuthorities.push(receipt);
|
||||
@@ -151,9 +174,9 @@ export async function readIdleMcpWakeProof(tx: Pick<Db, "select">, input: IdleMc
|
||||
const allowed = new Set(grantIds);
|
||||
const tokensForAdmission = rows.filter(row => allowed.has(row.grantId));
|
||||
const rebuilt = createMcpWakeAdmission({ stackId: input.stackId, ownerId: input.ownerId, capabilityGeneration: input.capabilityGeneration,
|
||||
challenge: input.challenge, revocationAuthorities, discovery: input.discovery, clientMirror: input.clientMirror,...(!input.personalEnabled&&!input.dotEnabled?{absent:true as const}:{}),
|
||||
challenge: input.challenge, revocationAuthorities, discovery: input.discovery, clientMirror: input.clientMirror,...(!input.personalEnabled&&!input.dotEnabled&&!input.museEnabled?{absent:true as const}:{}),
|
||||
tokens: tokensForAdmission.filter(row => !(row.tokenKind === "refresh" && row.tokenUsedAt !== null)).map(row => ({
|
||||
profile: row.resource === input.personalResource ? "personal-mcp" as const : "dot-mcp" as const,
|
||||
profile: row.resource === input.personalResource ? "personal-mcp" as const : row.resource===input.museResource?"muse-agent" as const:"dot-mcp" as const,
|
||||
tokenKind: row.tokenKind as "access" | "refresh", tokenHash: row.tokenHash, expiresAt: row.tokenExpiresAt?.toISOString() ?? null, clientId: row.clientId,
|
||||
})) });
|
||||
input.budget?.check();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { idleMuseWorkQuery,type IdleMuseReceiverProof } from "../../modules/external-agents/index.js";
|
||||
import { sql, type SQL } from "drizzle-orm";
|
||||
import { idleMcpHistoryChecks } from "./idle-history-proof.js";
|
||||
import type { IdleMcpWakeProof } from "./idle-wake-proof.js";
|
||||
@@ -10,11 +11,13 @@ import type { IdleDeadlineSnapshot } from "../idle-deadline-types.js";
|
||||
|
||||
export function idleMcpWorkQuery(reason: string, input: {
|
||||
ingress?: IdleMcpWakeProof;
|
||||
muse?:IdleMuseReceiverProof;
|
||||
subscriptions?: IdleMcpSubscriptionProof;
|
||||
retries?: IdleMcpEventScheduleProof;
|
||||
transfers?: IdleDeadlineSnapshot;
|
||||
handoffs?: IdleDeadlineSnapshot;
|
||||
}): SQL | undefined {
|
||||
const muse=idleMuseWorkQuery(reason,input.muse,input.ingress);if(muse)return muse;
|
||||
const check = idleMcpHistoryChecks.find(check => check.reason === reason);
|
||||
if (!check || !input.ingress) return;
|
||||
if (reason === "mcp_file_tickets" && input.transfers) return sql`SELECT 1 WHERE ${input.transfers.blocked}`;
|
||||
|
||||
@@ -54,7 +54,7 @@ export function parseMcpRevocationIndexRequest(value: unknown): McpRevocationInd
|
||||
|| typeof value.resource !== "string" || value.resource.length > 2048
|
||||
|| !digest(value.keyId) || !Number.isSafeInteger(value.revision) || Number(value.revision) < 0) throw new Error("Invalid MCP revocation identity");
|
||||
const url = new URL(value.resource);
|
||||
if (url.protocol !== "https:" || !["/mcp/runner", "/mcp/paperclip"].includes(url.pathname) || url.search || url.hash || url.username || url.password) throw new Error("Invalid MCP revocation resource");
|
||||
if (url.protocol !== "https:" || !["/mcp/runner", "/mcp/paperclip", "/api/muse/v1"].includes(url.pathname) || url.search || url.hash || url.username || url.password) throw new Error("Invalid MCP revocation resource");
|
||||
const common = ["authorityId", "companyId", "operatorId", "clientId", "resource", "keyId", "revision", "operation"];
|
||||
const fields = value.operation === "begin" ? ["key"] : value.operation === "append" ? ["entries"] : value.operation === "complete" ? [] : undefined;
|
||||
if (!fields || Object.keys(value).some(key => ![...common, ...fields].includes(key))) throw new Error("Unknown MCP revocation operation");
|
||||
|
||||
@@ -30,7 +30,7 @@ export function startMcpRevocationIndexSync(db: Db, coordinator: Pick<ReturnType
|
||||
|
||||
const managed = getCloudRuntimeIdentity();
|
||||
if (!client || !managed) { requested.clear(); return; }
|
||||
const resources = [managed.canonicalOrigin + "/mcp/paperclip", managed.canonicalOrigin + "/mcp/runner"];
|
||||
const resources = [managed.canonicalOrigin + "/mcp/paperclip", managed.canonicalOrigin + "/mcp/runner",managed.canonicalOrigin+"/api/muse/v1"];
|
||||
const assertCurrentAuthority = () => {
|
||||
const current = getCloudRuntimeIdentity(), currentConfig = paperclipCloudConnectorConfigFromEnv();
|
||||
if (!current || current.stackId !== managed.stackId || current.canonicalOrigin !== managed.canonicalOrigin
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
apiWakeFingerprint, createApiWakeAdmission,
|
||||
} from "../idle-api-wake-admission.js";
|
||||
|
||||
export const mcpWakeProfiles = ["personal-mcp", "dot-mcp"] as const;
|
||||
export const mcpWakeProfiles = ["personal-mcp", "dot-mcp", "muse-agent"] as const;
|
||||
export type McpWakeProfile = typeof mcpWakeProfiles[number];
|
||||
export type McpWakeTokenKind = "access" | "refresh";
|
||||
export interface McpWakeClaim {
|
||||
@@ -74,7 +74,7 @@ export function createMcpWakeAdmission(input: Context & {
|
||||
export function parseMcpWakeAdmission(value: unknown): McpWakeAdmission {
|
||||
if (!object(value) || !exact(value, ["version", "stackId", "ownerId", "capabilityGeneration", "challenge", "generation", "lanes", "revocationAuthorities", ...(object(value) && "discovery" in value ? ["discovery"] : []), ...(object(value) && "clientMirror" in value ? ["clientMirror"] : []), ...(object(value) && "absent" in value ? ["absent"] : [])])
|
||||
|| value.version !== 1 || !digest(value.challenge) || !digest(value.capabilityGeneration) || !digest(value.generation)
|
||||
|| !Array.isArray(value.lanes) || value.lanes.length > 4 || !Array.isArray(value.revocationAuthorities) || value.revocationAuthorities.length > 1000) throw new Error("Invalid MCP wake receipt");
|
||||
|| !Array.isArray(value.lanes) || value.lanes.length > 6 || !Array.isArray(value.revocationAuthorities) || value.revocationAuthorities.length > 1000) throw new Error("Invalid MCP wake receipt");
|
||||
const context = { stackId: value.stackId, ownerId: value.ownerId, capabilityGeneration: value.capabilityGeneration, challenge: value.challenge } as Context;
|
||||
|
||||
createApiWakeAdmission({ ...context, keys: [] });
|
||||
|
||||
Reference in new issue
Block a user