Aller au contenu principal

API de fichiers OPFS

@grant CAT.agent.opfs

L'API de fichiers OPFS (Origin Private File System) permet à un script de lire et d'écrire des fichiers dans l'espace de travail de l'Agent. Tous les chemins sont relatifs au répertoire agents/workspace/.

write — écrire un fichier

const result = await CAT.agent.opfs.write(path, content);

Paramètres :

ParamètreTypeDescription
pathstringChemin du fichier (obligatoire) ; prend en charge les répertoires imbriqués
contentstring | BlobContenu du fichier

Formats content pris en charge :

FormatDescription
Chaîne de texte simpleEnregistrée comme fichier texte UTF-8
Chaîne d'URL de donnéesDécodée automatiquement et enregistrée en binaire (ex. data:image/png;base64,...)
Objet BlobDonnées binaires enregistrées directement

Retourne WriteResult :

ChampTypeDescription
pathstringChemin où le fichier a été enregistré
sizenumberTaille du fichier (octets)
// Write a text file
await CAT.agent.opfs.write("data/config.json", JSON.stringify({ key: "value" }));

// Write a binary file (data URL)
const canvas = document.createElement("canvas");
const dataUrl = canvas.toDataURL("image/png");
await CAT.agent.opfs.write("images/chart.png", dataUrl);

Les répertoires parents sont créés automatiquement s'ils n'existent pas. Si le fichier existe déjà, son contenu est écrasé.

read — lire un fichier

const result = await CAT.agent.opfs.read(path, format?);

Paramètres :

ParamètreTypeDéfautDescription
pathstringChemin du fichier (obligatoire)
format"text" | "blob""text"Format de lecture

Retourne ReadResult :

ChampTypePrésent quandDescription
pathstringtoujourschemin du fichier
sizenumbertoujoursTaille du fichier
contentstringformat="text"Contenu texte du fichier
dataBlobformat="blob"L'objet Blob du fichier (transféré via un clone structuré)
mimeTypestringformat="blob"Type MIME détecté automatiquement

Deux modes de lecture :

// Text mode — suited to JSON and text files
const config = await CAT.agent.opfs.read("data/config.json");
const data = JSON.parse(config.content);

// Blob mode — suited to images and binary files
const image = await CAT.agent.opfs.read("images/chart.png", "blob");
// image.data is a real Blob object (not a scope-restricted blob: URL)
// Create a local URL with URL.createObjectURL(image.data) in whatever
// context needs it, or hand the Blob directly to any API that accepts one

Détection automatique du type MIME :

ExtensionType MIME
.jpg / .jpegimage/jpeg
.pngimage/png
.gifimage/gif
.webpimage/webp
.svgimage/svg+xml
.mp3audio/mpeg
.wavaudio/wav
.mp4video/mp4
.pdfapplication/pdf
.jsonapplication/json
.txttext/plain
.htmltext/html
.csstext/css
.jsapplication/javascript
autreapplication/octet-stream

list — lister un répertoire

const entries = await CAT.agent.opfs.list(path?);

Paramètres :

ParamètreTypeDéfautDescription
pathstring""Chemin du répertoire ; une chaîne vide signifie le répertoire racine

Retourne FileEntry[] :

ChampTypeDescription
namestringNom du fichier/répertoire
type"file" | "directory"Type
sizenumberTaille du fichier (type file uniquement)
const entries = await CAT.agent.opfs.list("data/");
for (const entry of entries) {
if (entry.type === "file") {
console.log(`${entry.name} (${entry.size} bytes)`);
} else {
console.log(`${entry.name}/`);
}
}

delete — supprimer un fichier ou un répertoire

const result = await CAT.agent.opfs.delete(path);

Prend en charge la suppression récursive d'un répertoire et de tout ce qu'il contient.

Retourne :

{ success: true }

readAttachment — lire une pièce jointe

const result = await CAT.agent.opfs.readAttachment(attachmentId);

Lit les données d'une pièce jointe (images, fichiers, etc.) d'une conversation. L'ID de la pièce jointe provient de ContentBlock.attachmentId dans un message.

Paramètres :

ParamètreTypeDescription
attachmentIdstringID de la pièce jointe (obligatoire)

Retourne :

ChampTypeDescription
idstringID de la pièce jointe
dataBlobDonnées binaires de la pièce jointe
sizenumberTaille du fichier (octets)
mimeTypestringType MIME
// Read an image attachment the AI generated in a conversation
const messages = await conv.getMessages();
const lastMsg = messages[messages.length - 1];
const imageBlock = lastMsg.content.find(b => b.type === "image");
if (imageBlock) {
const attachment = await CAT.agent.opfs.readAttachment(imageBlock.attachmentId);
console.log(`Attachment size: ${attachment.size}, type: ${attachment.mimeType}`);
}

Travailler avec des données Blob

  • read(path, "blob") retourne un vrai objet Blob transféré via clone structuré — et non une URL blob: limitée à l'origine de l'extension, donc aucune restriction d'accès entre contextes à craindre
  • Pour obtenir une URL temporaire utilisable dans une page, appelez URL.createObjectURL(result.data) ; appelez URL.revokeObjectURL() lorsque vous en avez terminé
  • Vous pouvez aussi passer le Blob directement à toute API Web qui accepte un Blob/File (par ex. body de fetch, FormData.append, un DataTransfer pour <input type="file">)