Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
import { createHash } from "node:crypto";
import { join } from "node:path";
import type { DatabaseSync } from "node:sqlite";
import {
AbsolutePathSchema,
CanonicalTimeSchema,
canonicalImageModelId,
IdSchema,
} from "@pibot/protocol-base";
import { z } from "zod";
import { BotsRepo } from "../bots/bots.ts";
import { AttachmentsRepo } from "../conversations/attachments.ts";
import { transaction } from "../database/database.ts";
import { RunsRepo } from "../runs/runs.ts";
import { MessagesRepo } from "../workspace/repositories.ts";
import { resolveArtifactSource } from "./image-artifact-access.ts";
import { markArtifactGenerated } from "./image-artifact-generation.ts";
import {
type ImageArtifactActor,
type ImageArtifactModel,
ImageArtifactModelSchema,
type ImageArtifactReceipt,
ImageArtifactReceiptSchema,
type ImageArtifactRecord,
type ImageArtifactTarget,
ImageArtifactTargetSchema,
imageArtifactFingerprint,
} from "./image-artifact-types.ts";
const receiptKeySchema = z.tuple([IdSchema, IdSchema, IdSchema, AbsolutePathSchema]);
const extensions: Record<string, string> = {
"image/png": "png",
"image/jpeg": "jpg",
"image/webp": "webp",
"image/gif": "gif",
};
/** These private records are generated by brain; a renderer/model claim is never an adapter. */
export class ImageArtifactsRepo {
constructor(private readonly db: DatabaseSync) {}
capture(rawTarget: ImageArtifactTarget, rawModel: ImageArtifactModel): ImageArtifactRecord {
const target = ImageArtifactTargetSchema.parse(rawTarget),
model = ImageArtifactModelSchema.parse(rawModel);
return transaction(this.db, () => {
const existing = this.get(target.source.runId);
if (existing) {
if (
imageArtifactFingerprint(existing.target) !== imageArtifactFingerprint(target) ||
imageArtifactFingerprint(existing.model) !== imageArtifactFingerprint(model)
)
throw new TypeError("image_artifact_conflict");
return existing;
}
const source = target.source,
run = new RunsRepo(this.db).get(source.runId),
message = new MessagesRepo(this.db).get(source.messageId),
bot = new BotsRepo(this.db).get(source.botId);
if (
!bot ||
bot.archivedAt ||
bot.category !== "image" ||
bot.modelProvider !== model.provider ||
canonicalImageModelId(model.provider, bot.modelId ?? "") !== model.id ||
run?.status !== "running" ||
message?.status !== "streaming" ||
message.role !== "assistant" ||
message.runId !== run.id ||
message.botId !== source.botId ||
run.botId !== source.botId ||
run.messageId !== source.messageId ||
run.conversationId !== source.conversationId ||
message.conversationId !== source.conversationId ||
run.groupId !== (source.groupId ?? null) ||
run.taskId !== (source.taskId ?? null) ||
run.cycleId !== (source.cycleId ?? null)
)
throw new TypeError("image_artifact_source_invalid");
const createdAt = new Date().toISOString();
this.db
.prepare(
"INSERT INTO image_artifacts(source_run_id,source_message_id,source_bot_id,target,model,created_at) VALUES (?,?,?,?,?,?)",
)
.run(
source.runId,
source.messageId,
source.botId,
JSON.stringify(target),
JSON.stringify(model),
createdAt,
);
return { target, model, createdAt };
});
}
get(sourceRunId: string): ImageArtifactRecord | undefined {
const row = this.db
.prepare(
"SELECT target,model,created_at AS createdAt,generation_succeeded_at AS generatedAt FROM image_artifacts WHERE source_run_id=?",
)
.get(IdSchema.parse(sourceRunId));
return row
? {
target: ImageArtifactTargetSchema.parse(JSON.parse(String(row.target))),
model: ImageArtifactModelSchema.parse(JSON.parse(String(row.model))),
createdAt: String(row.createdAt),
...(row.generatedAt ? { generatedAt: CanonicalTimeSchema.parse(row.generatedAt) } : {}),
}
: undefined;
}
markGenerated(sourceRunId: string): void {
transaction(this.db, () => markArtifactGenerated(this.db, this.get(sourceRunId), sourceRunId));
}
resolveSource(sourceRunId: string, actor: ImageArtifactActor, attachmentIds?: string[]) {
const artifact = this.get(sourceRunId);
if (!artifact) throw new TypeError("image_artifact_missing");
return resolveArtifactSource(this.db, artifact, actor, attachmentIds);
}
deliveryAliases(sourceRunId: string, before?: string, limit = 50) {
if (!Number.isInteger(limit) || limit < 1 || limit > 50)
throw new TypeError("image_alias_limit");
if (before) IdSchema.parse(before);
const artifact = this.get(sourceRunId);
if (!artifact?.target.source.groupId) return [];
const messages = new MessagesRepo(this.db),
source = messages.get(artifact.target.source.messageId);
if (!source || source.runId !== sourceRunId || source.botId !== artifact.target.source.botId)
throw new TypeError("image_artifact_source_invalid");
const ids =
source.attachments?.filter((item) => item.kind === "image").map((item) => item.id) ?? [];
if (!ids.length || ids.length > 5) return [];
const rows = this.db
.prepare(
`SELECT DISTINCT m.id FROM message_attachment_links l JOIN messages m ON m.id=l.message_id JOIN conversations c ON c.id=m.conversation_id WHERE l.attachment_id IN (${ids.map(() => "?").join(",")}) AND c.group_id=? AND m.role='assistant' AND m.status='done' AND m.id>? ORDER BY m.id LIMIT ?`,
)
.all(...ids, artifact.target.source.groupId, before ?? "", limit);
return rows.flatMap((row) => {
const message = messages.get(String(row.id));
return message ? [message] : [];
});
}
link(sourceRunId: string, targetMessageId: string, attachmentIds: string[]): void {
transaction(this.db, () => {
const messages = new MessagesRepo(this.db),
target = messages.get(IdSchema.parse(targetMessageId));
const run = target?.runId ? new RunsRepo(this.db).get(target.runId) : undefined;
if (
target?.role !== "assistant" ||
target.status !== "streaming" ||
!target.botId ||
run?.status !== "running" ||
run.messageId !== target.id ||
run.botId !== target.botId ||
run.conversationId !== target.conversationId
)
throw new TypeError("image_link_operation_invalid");
const conversation = this.db
.prepare("SELECT group_id AS groupId,kind FROM conversations WHERE id=?")
.get(target.conversationId);
const actor = {
botId: target.botId,
conversationId: target.conversationId,
groupId: conversation?.groupId ? String(conversation.groupId) : undefined,
threadId: conversation?.kind === "thread" ? target.conversationId : undefined,
};
const source = this.resolveSource(sourceRunId, actor, attachmentIds);
if (run.groupId !== (actor.groupId ?? null))
throw new TypeError("image_link_operation_invalid");
const present = new Set(target.attachments?.map((item) => item.id) ?? []);
const added = source.attachments.filter((item) => !present.has(item.metadata.id));
if (present.size + added.length > 5) throw new TypeError("image_link_limit");
for (const attachment of added)
this.db
.prepare(
"INSERT OR IGNORE INTO message_attachment_links(message_id,attachment_id) VALUES (?,?)",
)
.run(target.id, attachment.metadata.id);
});
}
/** A crash leaves a claim only until its operation run is recovered to a terminal state. */
tryClaim(sourceRunId: string, operationRunId: string): boolean {
IdSchema.parse(sourceRunId);
IdSchema.parse(operationRunId);
return transaction(this.db, () => {
const row = this.db
.prepare("SELECT saving_run_id AS runId FROM image_artifacts WHERE source_run_id=?")
.get(sourceRunId);
if (!row) throw new TypeError("image_artifact_missing");
const operation = new RunsRepo(this.db).get(operationRunId);
if (operation?.status !== "running") throw new TypeError("image_save_operation_invalid");
if (row.runId) {
const previous = new RunsRepo(this.db).get(String(row.runId));
if (previous && ["queued", "running", "waiting"].includes(previous.status)) return false;
}
return (
this.db
.prepare("UPDATE image_artifacts SET saving_run_id=? WHERE source_run_id=?")
.run(operationRunId, sourceRunId).changes === 1
);
});
}
release(sourceRunId: string, operationRunId: string): void {
this.db
.prepare(
"UPDATE image_artifacts SET saving_run_id=NULL WHERE source_run_id=? AND saving_run_id=?",
)
.run(sourceRunId, operationRunId);
}
receiptGet(key: string): ImageArtifactReceipt | undefined {
this.receiptIdentity(key);
const row = this.db
.prepare("SELECT receipt FROM image_workspace_receipts WHERE key=?")
.get(key);
return row ? ImageArtifactReceiptSchema.parse(JSON.parse(String(row.receipt))) : undefined;
}
receiptPut(key: string, raw: ImageArtifactReceipt): undefined {
const receipt = ImageArtifactReceiptSchema.parse(raw);
transaction(this.db, () => {
const { sourceRunId, attachmentId, path, identityKey, parent } = this.receiptIdentity(key);
const attachment = new AttachmentsRepo(this.db).get(attachmentId);
if (
receipt.path !== path ||
receipt.identityKey !== identityKey ||
receipt.bytes !== attachment?.metadata.size ||
receipt.parentDevice !== parent?.device ||
receipt.parentInode !== parent?.inode
)
throw new TypeError("image_receipt_invalid");
const existing = this.receiptGet(key);
if (existing && imageArtifactFingerprint(existing) !== imageArtifactFingerprint(receipt))
throw new TypeError("image_receipt_conflict");
this.db
.prepare(
"INSERT INTO image_workspace_receipts(key,source_run_id,attachment_id,receipt,created_at) VALUES (?,?,?,?,?) ON CONFLICT(key) DO NOTHING",
)
.run(key, sourceRunId, attachmentId, JSON.stringify(receipt), new Date().toISOString());
});
return undefined;
}
private receiptIdentity(key: string) {
const [botId, sourceRunId, attachmentId, path] = receiptKeySchema.parse(JSON.parse(key));
const record = this.get(sourceRunId),
attachment = new AttachmentsRepo(this.db).get(attachmentId);
const source = record?.target.source;
const usage = source ? new MessagesRepo(this.db).get(source.messageId)?.usage : undefined;
if (
!record?.generatedAt ||
source?.botId !== botId ||
attachment?.botId !== botId ||
attachment.messageId !== source.messageId ||
attachment.metadata.kind !== "image" ||
!usage ||
typeof usage !== "object" ||
Array.isArray(usage) ||
usage.imageGeneration !== true
)
throw new TypeError("image_receipt_source_invalid");
const extension = extensions[attachment.metadata.mimeType];
const identityKey = createHash("sha256")
.update(JSON.stringify([sourceRunId, attachmentId]))
.digest("hex");
if (!extension || path !== join(record.target.cwd, `pibot-image-${identityKey}.${extension}`))
throw new TypeError("image_receipt_path_invalid");
return {
sourceRunId,
attachmentId,
path,
identityKey,
parent: record.target.boundary.roots.find((root) => root.canonicalPath === record.target.cwd),
};
}
}