Skip to content

armgit / pibot

Public Imported from GitHub
0

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.

feat(import): background import framework with preview, cancel and whole-batch undo

leen.zhou16f419b19095
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 779037e..9165c55 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -54,6 +54,8 @@
"@pibot/i18n": "workspace:*",
"@pibot/images": "workspace:*",
"@pibot/images-contract": "workspace:*",
+ "@pibot/import": "workspace:0.0.0",
+ "@pibot/import-contract": "workspace:*",
"@pibot/link": "workspace:*",
"@pibot/memory": "workspace:*",
"@pibot/models": "workspace:0.0.0",
diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json
index c4092f4..adc877b 100644
--- a/apps/desktop/tsconfig.json
+++ b/apps/desktop/tsconfig.json
@@ -72,6 +72,12 @@
{
"path": "../../packages/images-contract"
},
+ {
+ "path": "../../packages/import"
+ },
+ {
+ "path": "../../packages/import-contract"
+ },
{
"path": "../../packages/link"
},
diff --git a/packages/brain-app/package.json b/packages/brain-app/package.json
index 79ca5d4..c210220 100644
--- a/packages/brain-app/package.json
+++ b/packages/brain-app/package.json
@@ -21,6 +21,7 @@
"@pibot/office": "workspace:0.0.0",
"@pibot/orchestration": "workspace:0.0.0",
"@pibot/images": "workspace:0.0.0",
+ "@pibot/import": "workspace:0.0.0",
"@pibot/memory": "workspace:0.0.0",
"@pibot/plugin-sdk": "workspace:0.0.0",
"@pibot/credentials": "workspace:0.0.0",
diff --git a/packages/brain-app/src/index.ts b/packages/brain-app/src/index.ts
index 92312f7..1c6077f 100644
--- a/packages/brain-app/src/index.ts
+++ b/packages/brain-app/src/index.ts
@@ -4,6 +4,7 @@ import { computerUseCapability } from "@pibot/computer-use/brain";
import { credentialsCapability } from "@pibot/credentials/brain";
import { externalAgentsCapability } from "@pibot/external-agents/brain";
import { imagesCapability } from "@pibot/images/brain";
+import { importCapability } from "@pibot/import/brain";
import { memoryCapability } from "@pibot/memory/brain";
import { providersCapability } from "@pibot/models/brain";
import { officeCapability } from "@pibot/office/brain";
@@ -93,6 +94,7 @@ export function capabilities(
// Bots of kind "agent" (external coding agents over ACP).
externalAgentsCapability(),
memoryCapability(),
+ importCapability(),
credentialsCapability(),
// Plugin skills register through the generic capability port; their host must exist first.
skillsCapability(),
diff --git a/packages/brain-app/tsconfig.json b/packages/brain-app/tsconfig.json
index 7f462c3..b40c8bf 100644
--- a/packages/brain-app/tsconfig.json
+++ b/packages/brain-app/tsconfig.json
@@ -31,6 +31,9 @@
{
"path": "../images"
},
+ {
+ "path": "../import"
+ },
{
"path": "../memory"
},
diff --git a/packages/brain/src/conversations/chat/chat.ts b/packages/brain/src/conversations/chat/chat.ts
index 01ecaea..34c654a 100644
--- a/packages/brain/src/conversations/chat/chat.ts
+++ b/packages/brain/src/conversations/chat/chat.ts
@@ -368,6 +368,7 @@ export class ChatService {
: this.conversations.currentDm(botId);
if (!newTopic && (selected?.kind !== "dm" || selected.botId !== botId || selected.archivedAt))
throw new RpcError(-32602, "Unknown topic");
+ if (selected?.readOnly) throw new RpcError(-32602, "import_topic_read_only");
if (selected) this.queue.assertTopicAdmission(selected.id);
// The folders chosen on a new-topic draft must be this Bot's registered folders.
if (workplace) this.validateFolders(botId, workplace);
@@ -412,7 +413,7 @@ export class ChatService {
const quote = resolveMessageQuote(
this.db,
replyToMessageId,
- { botId, conversationId: selected?.id },
+ { botId, conversationId: selected?.id, importedSource: newTopic === true },
this.redactor,
);
const refs = quotedAttachmentIds(
@@ -456,7 +457,7 @@ export class ChatService {
resolveMessageQuote(
this.db,
replyToMessageId,
- { botId, conversationId: selected?.id },
+ { botId, conversationId: selected?.id, importedSource: newTopic === true },
this.redactor,
quote,
);
diff --git a/packages/brain/src/conversations/chat/message-quote.ts b/packages/brain/src/conversations/chat/message-quote.ts
index 0698455..9122e61 100644
--- a/packages/brain/src/conversations/chat/message-quote.ts
+++ b/packages/brain/src/conversations/chat/message-quote.ts
@@ -8,19 +8,20 @@ import type { BrainRedactor } from "../../core/privacy.ts";
export function resolveMessageQuote(
db: DatabaseSync,
id: string | undefined,
- scope: { botId?: string; groupId?: string; conversationId?: string },
+ scope: { botId?: string; groupId?: string; conversationId?: string; importedSource?: boolean },
redactor: BrainRedactor,
expected?: MessageQuote,
): MessageQuote | undefined {
if (!id) return;
const message = new MessagesRepo(db).get(id);
- const conversation = scope.conversationId
- ? new ConversationsRepo(db).get(scope.conversationId)
- : undefined;
+ const sourceId =
+ scope.conversationId ?? (scope.importedSource ? message?.conversationId : undefined);
+ const conversation = sourceId ? new ConversationsRepo(db).get(sourceId) : undefined;
if (
!message ||
!conversation ||
conversation.archivedAt ||
+ (scope.importedSource && !conversation.readOnly) ||
message.conversationId !== conversation.id ||
message.status === "streaming"
)
diff --git a/packages/brain/src/resources/workplaces/topic-workplace.ts b/packages/brain/src/resources/workplaces/topic-workplace.ts
index 256891f..6b9f9c1 100644
--- a/packages/brain/src/resources/workplaces/topic-workplace.ts
+++ b/packages/brain/src/resources/workplaces/topic-workplace.ts
@@ -87,6 +87,7 @@ export class TopicWorkplaceService {
if (!topic) throw new RpcError(-32602, "topic_not_found");
if (topic.kind !== "dm" || topic.botId !== botId) throw new RpcError(-32602, "topic_wrong_bot");
if (topic.archivedAt) throw new RpcError(-32602, "topic_archived");
+ if (topic.readOnly) throw new RpcError(-32602, "import_topic_read_only");
const place = this.local.workplaces.topic(topicId);
const resolved = await this.local.workplaces.context(botId, this.signal, place);
// Folder paths are stored canonical (workplaces.pick realpaths them), so the client's path
diff --git a/packages/client-core/src/audit/presentation.ts b/packages/client-core/src/audit/presentation.ts
index 2ba82e0..522cf9d 100644
--- a/packages/client-core/src/audit/presentation.ts
+++ b/packages/client-core/src/audit/presentation.ts
@@ -62,6 +62,7 @@ const kindGroups: Record<AuditKind, readonly [AuditGroup, ...AuditGroup[]]> = {
"acp.session.attach": ["run"],
"bot.updated": ["run"],
"feedback.opened": ["approval"],
+ "import.changed": ["file"],
"hook.finished": ["run"],
"remote.request": ["phone"],
"remote.changed": ["phone"],
@@ -331,6 +332,7 @@ export function auditSummary(
if (isFileCheckpoint(entry)) return t("audit.checkpoint.automatic");
const workflow = groupWorkflowSummary(entry, t);
if (workflow) return workflow;
+ if (entry.kind === "import.changed") return t("audit.conversationImport");
if (entry.kind === "feedback.opened") return t("appMenu.feedbackOpened");
// The stored summary carries both languages for exports; the page shows the reader's own.
if (entry.kind === "git.install") return gitInstallSummary(entry, t);
diff --git a/packages/i18n/src/sections/activity.ts b/packages/i18n/src/sections/activity.ts
index 695e84c..a30cf3b 100644
--- a/packages/i18n/src/sections/activity.ts
+++ b/packages/i18n/src/sections/activity.ts
@@ -1,5 +1,6 @@
export const activityZh = {
"audit.workflow.started": "群计划已登记",
+ "audit.conversationImport": "对话导入",
"audit.externalAgent.prewarmed": "外部 Agent 已预热",
"audit.workflow.migrated": "群计划已迁移",
"audit.workflow.recovered": "群计划已恢复",
@@ -321,6 +322,7 @@ export const activityZh = {
export const activityEn = {
"audit.workflow.started": "Group plan registered",
+ "audit.conversationImport": "Conversation import",
"audit.externalAgent.prewarmed": "External agent prewarmed",
"audit.workflow.migrated": "Group plan migrated",
"audit.workflow.recovered": "Group plan recovered",
diff --git a/packages/import-contract/package.json b/packages/import-contract/package.json
new file mode 100644
index 0000000..dc01e32
--- /dev/null
+++ b/packages/import-contract/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@pibot/import-contract",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "pibot": {
+ "layer": "cross"
+ },
+ "exports": {
+ ".": "./src/index.ts",
+ "./full": "./src/full.ts"
+ },
+ "scripts": {
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@pibot/protocol-base": "workspace:0.0.0",
+ "zod": "4.6.5"
+ }
+}
diff --git a/packages/import-contract/src/full.ts b/packages/import-contract/src/full.ts
new file mode 100644
index 0000000..c05f003
--- /dev/null
+++ b/packages/import-contract/src/full.ts
@@ -0,0 +1,7 @@
+// Implementation handlers use concrete types without pulling in the product protocol.
+import type { z } from "zod";
+import type { ImportMethods } from "./index.ts";
+
+export type ImportParams<K extends keyof typeof ImportMethods> = z.infer<
+ (typeof ImportMethods)[K]["params"]
+>;
diff --git a/packages/import-contract/src/index.ts b/packages/import-contract/src/index.ts
new file mode 100644
index 0000000..c544469
--- /dev/null
+++ b/packages/import-contract/src/index.ts
@@ -0,0 +1,50 @@
+// Desktop clients and the import worker share a content-free preview and progress contract.
+import { IdSchema } from "@pibot/protocol-base";
+import { z } from "zod";
+
+export const ImportSourceSchema = z.enum([
+ "fixture",
+ "chatgpt",
+ "claude",
+ "claude-code",
+ "codex",
+ "cursor",
+ "gemini",
+]);
+export type ImportSource = z.infer<typeof ImportSourceSchema>;
+
+const count = z.number().int().nonnegative().safe();
+export const ImportCountsSchema = z.strictObject({ topics: count, messages: count });
+export type ImportCounts = z.infer<typeof ImportCountsSchema>;
+
+const preview = ImportCountsSchema.extend({
+ importId: IdSchema,
+ source: ImportSourceSchema,
+ from: z.iso.datetime().nullable(),
+ through: z.iso.datetime().nullable(),
+});
+export type ImportPreview = z.infer<typeof preview>;
+
+export const ImportStatusSchema = ImportCountsSchema.extend({
+ importId: IdSchema,
+ source: ImportSourceSchema,
+ state: z.enum(["running", "completed", "cancelled", "failed", "undone"]),
+ reason: z
+ .enum(["source_changed", "format", "timeout", "target", "limit", "interrupted", "internal"])
+ .nullable(),
+});
+export type ImportStatus = z.infer<typeof ImportStatusSchema>;
+
+const importId = z.strictObject({ importId: IdSchema });
+const source = z.strictObject({ source: ImportSourceSchema });
+
+export const ImportMethods = {
+ "import.detect": { params: source, result: z.strictObject({ available: z.boolean() }) },
+ "import.preview": { params: source, result: preview.nullable() },
+ "import.start": { params: importId.extend({ botId: IdSchema }), result: ImportStatusSchema },
+ "import.status": { params: importId, result: ImportStatusSchema },
+ "import.cancel": { params: importId, result: ImportStatusSchema },
+ "import.undo": { params: importId, result: ImportStatusSchema },
+} as const;
+
+export const ImportEvents = { "import.progress": ImportStatusSchema } as const;
diff --git a/packages/import-contract/tsconfig.json b/packages/import-contract/tsconfig.json
new file mode 100644
index 0000000..648b821
--- /dev/null
+++ b/packages/import-contract/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "include": ["src/**/*.ts", "src/**/*.tsx"],
+ "compilerOptions": {
+ "composite": true,
+ "noEmit": false,
+ "declaration": true,
+ "declarationMap": false,
+ "emitDeclarationOnly": true,
+ "outDir": ".cache/tsc",
+ "tsBuildInfoFile": ".cache/tsc/tsconfig.tsbuildinfo",
+ "disableSourceOfProjectReferenceRedirect": true,
+ "noCheck": true
+ },
+ "references": [
+ {
+ "path": "../protocol-base"
+ }
+ ],
+ "exclude": ["**/*.test.ts", "**/*.test.tsx", "test/**"]
+}
diff --git a/packages/import/package.json b/packages/import/package.json
new file mode 100644
index 0000000..38b5956
--- /dev/null
+++ b/packages/import/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@pibot/import",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "pibot": {
+ "layer": "L2"
+ },
+ "exports": {
+ "./brain": "./src/brain/index.ts",
+ "./store": "./src/store/index.ts"
+ },
+ "scripts": {
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@pibot/brain": "workspace:0.0.0",
+ "@pibot/execution": "workspace:0.0.0",
+ "@pibot/import-contract": "workspace:0.0.0",
+ "@pibot/policy": "workspace:0.0.0",
+ "@pibot/protocol-base": "workspace:0.0.0",
+ "@pibot/storage": "workspace:0.0.0",
+ "zod": "4.6.5"
+ }
+}
diff --git a/packages/import/src/brain/adapter.ts b/packages/import/src/brain/adapter.ts
new file mode 100644
index 0000000..df0948a
--- /dev/null
+++ b/packages/import/src/brain/adapter.ts
@@ -0,0 +1,67 @@
+// Adapters yield bounded records rather than exposing provider-specific objects to storage.
+import type { ImportSource } from "@pibot/import-contract";
+import { z } from "zod";
+
+const time = z.iso.datetime({ offset: true }).transform((value) => new Date(value).toISOString());
+export const ImportTopicSchema = z.strictObject({
+ kind: z.literal("topic"),
+ title: z.string().max(200),
+ createdAt: time,
+ updatedAt: time,
+});
+export const ImportMessageSchema = z.strictObject({
+ kind: z.literal("message"),
+ role: z.enum(["user", "assistant"]),
+ text: z.string().max(65_536),
+ createdAt: time,
+});
+export const ImportRecordSchema = z.discriminatedUnion("kind", [
+ ImportTopicSchema,
+ ImportMessageSchema,
+]);
+export type ImportRecord = z.input<typeof ImportRecordSchema>;
+
+export const PreviewRecordSchema = z.discriminatedUnion("kind", [
+ z.strictObject({ kind: z.literal("topic"), createdAt: time, updatedAt: time }),
+ z.strictObject({ kind: z.literal("message"), createdAt: time }),
+]);
+export type PreviewRecord = z.input<typeof PreviewRecordSchema>;
+
+export type ImportInput = (signal: AbortSignal) => AsyncIterable<Buffer>;
+
+export interface ImportAdapter {
+ detect(signal: AbortSignal): AsyncIterable<boolean>;
+ preview(input: ImportInput, signal: AbortSignal): AsyncIterable<PreviewRecord>;
+ /** Every topic precedes its messages. Topics and messages from different topics never interleave. */
+ read(input: ImportInput, signal: AbortSignal): AsyncIterable<ImportRecord>;
+}
+
+export class ImportFailure extends Error {
+ constructor(readonly reason: "source_changed" | "format" | "target" | "limit") {
+ super(reason);
+ }
+}
+
+export function adapters(fixture: ImportAdapter): Record<ImportSource, ImportAdapter> {
+ const unsupported: ImportAdapter = {
+ async *detect(signal) {
+ signal.throwIfAborted();
+ yield false;
+ },
+ preview() {
+ throw new ImportFailure("format");
+ },
+ read() {
+ throw new ImportFailure("format");
+ },
+ };
+ return {
+ fixture,
+ chatgpt: unsupported,
+ claude: unsupported,
+ "claude-code": unsupported,
+ codex: unsupported,
+ cursor: unsupported,
+ gemini: unsupported,
+ };
+}
diff --git a/packages/import/src/brain/capability.ts b/packages/import/src/brain/capability.ts
new file mode 100644
index 0000000..9441681
--- /dev/null
+++ b/packages/import/src/brain/capability.ts
@@ -0,0 +1,46 @@
+// The desktop composition owns import registration, guarded source selection, and shutdown.
+import type { BrainCapability } from "@pibot/brain/kit";
+import type { ImportParams } from "@pibot/import-contract/full";
+import { RpcError, RpcErrorCodes } from "@pibot/protocol-base";
+import { ImportStore } from "../store/index.ts";
+import { ImportJobs } from "./jobs.ts";
+
+export function importCapability(): BrainCapability {
+ return {
+ id: "import",
+ register(ctx) {
+ const jobs = new ImportJobs(ctx, new ImportStore(ctx.db, ctx.redactor));
+ if (!ctx.host.pickFile) return { start: () => jobs.recover() };
+ ctx.sleep.participate({ idle: () => jobs.idle() });
+ const handle = ctx.rpc.handle;
+ const desktop = (source?: "acp") => {
+ if (source === "acp") throw new RpcError(RpcErrorCodes.unsupported, "import_desktop_only");
+ };
+ handle("import.detect", ({ source }: ImportParams<"import.detect">, request) => {
+ desktop(request.source);
+ return jobs.detect(source, request.signal);
+ });
+ handle("import.preview", ({ source }: ImportParams<"import.preview">, request) => {
+ desktop(request.source);
+ return jobs.preview(source, request.signal);
+ });
+ handle("import.start", ({ importId, botId }: ImportParams<"import.start">, request) => {
+ desktop(request.source);
+ return jobs.start(importId, botId);
+ });
+ handle("import.status", ({ importId }: ImportParams<"import.status">, request) => {
+ desktop(request.source);
+ return jobs.status(importId);
+ });
+ handle("import.cancel", ({ importId }: ImportParams<"import.cancel">, request) => {
+ desktop(request.source);
+ return jobs.cancel(importId);
+ });
+ handle("import.undo", ({ importId }: ImportParams<"import.undo">, request) => {
+ desktop(request.source);
+ return jobs.undo(importId);
+ });
+ return { start: () => jobs.recover(), stop: () => jobs.stop() };
+ },
+ };
+}
diff --git a/packages/import/src/brain/fixture.ts b/packages/import/src/brain/fixture.ts
new file mode 100644
index 0000000..9b2a303
--- /dev/null
+++ b/packages/import/src/brain/fixture.ts
@@ -0,0 +1,68 @@
+// The synthetic, size-limited JSON source exercises the same iterator boundary as larger exports.
+import { z } from "zod";
+import {
+ type ImportAdapter,
+ ImportFailure,
+ type ImportInput,
+ ImportMessageSchema,
+ ImportTopicSchema,
+} from "./adapter.ts";
+
+const fixture = z.object({
+ format: z.literal("pibot-import-fixture-v1"),
+ topics: z
+ .array(
+ z.object({
+ ...ImportTopicSchema.omit({ kind: true }).shape,
+ messages: z.array(z.object(ImportMessageSchema.omit({ kind: true }).shape)).max(1000),
+ }),
+ )
+ .max(100),
+});
+const MAX_BYTES = 256 * 1024;
+
+async function* records(input: ImportInput, signal: AbortSignal) {
+ const buffers: Buffer[] = [];
+ let bytes = 0;
+ for await (const chunk of input(signal)) {
+ bytes += chunk.length;
+ if (bytes > MAX_BYTES) throw new ImportFailure("limit");
+ buffers.push(chunk);
+ }
+ signal.throwIfAborted();
+ let raw: unknown;
+ try {
+ raw = JSON.parse(
+ new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(buffers, bytes)),
+ );
+ } catch (error) {
+ if (error instanceof SyntaxError || error instanceof TypeError)
+ throw new ImportFailure("format");
+ throw error;
+ }
+ const parsed = fixture.safeParse(raw);
+ if (!parsed.success) throw new ImportFailure("format");
+ for (const { messages, ...topic } of parsed.data.topics) {
+ signal.throwIfAborted();
+ yield { kind: "topic" as const, ...topic };
+ for (const message of messages) {
+ signal.throwIfAborted();
+ yield { kind: "message" as const, ...message };
+ }
+ }
+}
+
+export const fixtureAdapter: ImportAdapter = {
+ async *detect(signal) {
+ signal.throwIfAborted();
+ yield true;
+ },
+ async *preview(input, signal) {
+ for await (const record of records(input, signal)) {
+ if (record.kind === "topic")
+ yield { kind: "topic", createdAt: record.createdAt, updatedAt: record.updatedAt };
+ else yield { kind: "message", createdAt: record.createdAt };
+ }
+ },
+ read: records,
+};
diff --git a/packages/import/src/brain/index.ts b/packages/import/src/brain/index.ts
new file mode 100644
index 0000000..680d68a
--- /dev/null
+++ b/packages/import/src/brain/index.ts
@@ -0,0 +1,2 @@
+// The composition root only needs the capability factory.
+export { importCapability } from "./capability.ts";
diff --git a/packages/import/src/brain/jobs.ts b/packages/import/src/brain/jobs.ts
new file mode 100644
index 0000000..021f493
--- /dev/null
+++ b/packages/import/src/brain/jobs.ts
@@ -0,0 +1,217 @@
+// A single job owner keeps preview authorizations, progress, and cancellation consistent.
+import { randomUUID } from "node:crypto";
+import { setImmediate as yieldToLoop } from "node:timers/promises";
+import type { CapabilityContext } from "@pibot/brain/kit";
+import type {
+ ImportCounts,
+ ImportPreview,
+ ImportSource,
+ ImportStatus,
+} from "@pibot/import-contract";
+import { RpcError, RpcErrorCodes } from "@pibot/protocol-base";
+import type { ImportStore } from "../store/index.ts";
+import { adapters, ImportFailure, type ImportInput } from "./adapter.ts";
+import { fixtureAdapter } from "./fixture.ts";
+import { summarize, writeRecords } from "./records.ts";
+import { selectedInput } from "./source.ts";
+
+const JOB_MS = 5 * 60_000;
+const PREVIEW_MS = 90_000;
+const PREVIEW_VALID_MS = 10 * 60_000;
+const PROGRESS_MS = 200;
+
+type Selection = { preview: ImportPreview; input: ImportInput; expiresAt: number };
+type Running = { importId: string; controller: AbortController; done: Promise<ImportStatus> };
+
+function failureReason(error: unknown): NonNullable<ImportStatus["reason"]> {
+ if (error instanceof ImportFailure) return error.reason;
+ if (
+ error &&
+ typeof error === "object" &&
+ "code" in error &&
+ (error.code === "ENOENT" ||
+ error.code === "ELOOP" ||
+ error.code === "EACCES" ||
+ error.code === "EPERM")
+ )
+ return "source_changed";
+ return "internal";
+}
+
+export class ImportJobs {
+ private readonly adapters = adapters(fixtureAdapter);
+ private readonly closing = new AbortController();
+ private selection?: Selection;
+ private previewing?: Promise<ImportPreview | null>;
+ private active?: Running;
+
+ constructor(
+ private readonly ctx: CapabilityContext,
+ private readonly store: ImportStore,
+ ) {}
+
+ idle() {
+ return !this.active && !this.previewing;
+ }
+
+ recover() {
+ for (let id = this.store.unfinished(); typeof id === "string"; id = this.store.unfinished())
+ this.store.finish({ ...this.status(id), state: "failed", reason: "interrupted" });
+ }
+
+ async detect(source: ImportSource, caller: AbortSignal) {
+ const signal = AbortSignal.any([caller, this.closing.signal, AbortSignal.timeout(PREVIEW_MS)]);
+ for await (const available of this.adapters[source].detect(signal)) {
+ signal.throwIfAborted();
+ return { available: available && !!this.ctx.host.pickFile };
+ }
+ return { available: false };
+ }
+
+ async preview(source: ImportSource, caller: AbortSignal) {
+ this.closing.signal.throwIfAborted();
+ if (this.previewing) throw new RpcError(RpcErrorCodes.invalidParams, "import_preview_busy");
+ const work = this.openPreview(source, caller);
+ this.previewing = work;
+ try {
+ return await work;
+ } finally {
+ this.previewing = undefined;
+ }
+ }
+
+ private async openPreview(source: ImportSource, caller: AbortSignal) {
+ this.selection = undefined;
+ const deadline = AbortSignal.timeout(PREVIEW_MS);
+ const signal = AbortSignal.any([caller, this.closing.signal, deadline]);
+ try {
+ if (!(await this.detect(source, signal)).available)
+ throw new RpcError(RpcErrorCodes.unsupported, "import_source_unsupported");
+ const path = await this.ctx.host.pickFile?.(signal);
+ signal.throwIfAborted();
+ if (!path) return null;
+ const input = await selectedInput(this.ctx.local.deps, path, signal);
+ const summary = await summarize(this.adapters[source], input, signal);
+ const preview = { importId: randomUUID(), source, ...summary };
+ signal.throwIfAborted();
+ this.selection = { preview, input, expiresAt: Date.now() + PREVIEW_VALID_MS };
+ return preview;
+ } catch (error) {
+ if (error instanceof RpcError) throw error;
+ if (deadline.aborted)
+ throw new RpcError(RpcErrorCodes.invalidParams, "import_preview_timeout");
+ signal.throwIfAborted();
+ const reason = failureReason(error);
+ if (reason === "internal") throw error;
+ throw new RpcError(RpcErrorCodes.invalidParams, `import_${reason}`);
+ }
+ }
+
+ start(importId: string, botId: string) {
+ this.closing.signal.throwIfAborted();
+ const existing = this.store.get(importId);
+ if (existing) {
+ if (this.store.target(importId) !== botId)
+ throw new RpcError(RpcErrorCodes.invalidParams, "import_target");
+ return existing;
+ }
+ if (this.active || this.store.unfinished())
+ throw new RpcError(RpcErrorCodes.invalidParams, "import_busy");
+ if (!this.store.availableBot(botId))
+ throw new RpcError(RpcErrorCodes.invalidParams, "import_target");
+ const selection = this.selection;
+ if (!selection || selection.preview.importId !== importId || Date.now() > selection.expiresAt)
+ throw new RpcError(RpcErrorCodes.invalidParams, "import_preview_expired");
+ this.store.create(importId, selection.preview.source, botId);
+ this.selection = undefined;
+ const controller = new AbortController();
+ const done = this.run(selection, botId, controller.signal).finally(() => {
+ this.active = undefined;
+ });
+ this.active = { importId, controller, done };
+ // A later status/cancel call still receives the persisted result or the original failure.
+ void done.catch(() => this.ctx.logger.error("import_cleanup_failed"));
+ return this.status(importId);
+ }
+
+ status(importId: string) {
+ const status = this.store.get(importId);
+ if (!status) throw new RpcError(RpcErrorCodes.invalidParams, "import_unknown");
+ return status;
+ }
+
+ async cancel(importId: string) {
+ const status = this.status(importId);
+ if (status.state !== "running" || this.active?.importId !== importId) return status;
+ this.active.controller.abort();
+ return this.active.done;
+ }
+
+ undo(importId: string) {
+ const status = this.status(importId);
+ if (status.state === "undone") return status;
+ if (status.state !== "completed")
+ throw new RpcError(RpcErrorCodes.invalidParams, "import_not_completed");
+ return this.publish(this.store.finish({ ...status, state: "undone" }));
+ }
+
+ async stop() {
+ this.closing.abort();
+ this.selection = undefined;
+ // A picker rejection after shutdown is expected; the RPC caller owns that error.
+ await this.previewing?.catch(() => undefined);
+ await this.active?.done;
+ }
+
+ private async run(selection: Selection, botId: string, cancel: AbortSignal) {
+ const deadline = AbortSignal.timeout(JOB_MS);
+ const signal = AbortSignal.any([cancel, this.closing.signal, deadline]);
+ const { preview, input } = selection;
+ let state: "completed" | "cancelled" | "failed" = "completed";
+ let reason: ImportStatus["reason"] = null;
+ let last = -Infinity;
+ const progress = (counts: ImportCounts) => {
+ const now = performance.now();
+ if (now - last < PROGRESS_MS) return;
+ last = now;
+ this.publish({
+ importId: preview.importId,
+ source: preview.source,
+ ...counts,
+ state: "running",
+ reason: null,
+ });
+ };
+ try {
+ await yieldToLoop(undefined, { signal });
+ progress({ topics: 0, messages: 0 });
+ await writeRecords({
+ adapter: this.adapters[preview.source],
+ input,
+ preview,
+ botId,
+ store: this.store,
+ redactor: this.ctx.redactor,
+ signal,
+ progress,
+ });
+ signal.throwIfAborted();
+ if (!this.store.availableBot(botId)) throw new ImportFailure("target");
+ } catch (error) {
+ state = cancel.aborted || this.closing.signal.aborted ? "cancelled" : "failed";
+ reason = state === "cancelled" ? null : deadline.aborted ? "timeout" : failureReason(error);
+ if (reason === "internal") this.ctx.logger.error("import_job_failed");
+ }
+ return this.publish(this.store.finish({ ...this.status(preview.importId), state, reason }));
+ }
+
+ private publish(status: ImportStatus) {
+ try {
+ this.ctx.peer.emit("import.progress", status);
+ } catch {
+ // The caller can recover authoritative status after a disconnect or delivery failure.
+ this.ctx.logger.warn("import_progress_not_delivered");
+ }
+ return status;
+ }
+}
diff --git a/packages/import/src/brain/records.ts b/packages/import/src/brain/records.ts
new file mode 100644
index 0000000..e561f03
--- /dev/null
+++ b/packages/import/src/brain/records.ts
@@ -0,0 +1,131 @@
+// Bound adapter output and page writes so the brain remains responsive during large imports.
+import { setImmediate as yieldToLoop } from "node:timers/promises";
+import type { BrainRedactor } from "@pibot/brain/kit";
+import type { ImportPreview, ImportStatus } from "@pibot/import-contract";
+import type { ImportStore } from "../store/index.ts";
+import {
+ type ImportAdapter,
+ ImportFailure,
+ type ImportInput,
+ ImportRecordSchema,
+ PreviewRecordSchema,
+} from "./adapter.ts";
+
+const PAGE_RECORDS = 32;
+const MAX_TOPICS = 20_000;
+const MAX_MESSAGES = 500_000;
+const MAX_TEXT_BYTES = 512 * 1024 * 1024;
+
+class Summary {
+ readonly counts = { topics: 0, messages: 0 };
+ from: string | null = null;
+ through: string | null = null;
+
+ include(record: { kind: "topic" | "message"; createdAt: string; updatedAt?: string }) {
+ const { kind, createdAt, updatedAt = createdAt } = record;
+ if (kind === "topic") {
+ if (updatedAt < createdAt || ++this.counts.topics > MAX_TOPICS)
+ throw new ImportFailure(updatedAt < createdAt ? "format" : "limit");
+ } else if (!this.counts.topics || ++this.counts.messages > MAX_MESSAGES) {
+ throw new ImportFailure(this.counts.topics ? "limit" : "format");
+ }
+ if (!this.from || createdAt < this.from) this.from = createdAt;
+ if (!this.through || updatedAt > this.through) this.through = updatedAt;
+ }
+}
+
+export async function summarize(adapter: ImportAdapter, input: ImportInput, signal: AbortSignal) {
+ const summary = new Summary();
+ let pending = 0;
+ for await (const record of adapter.preview(input, signal)) {
+ signal.throwIfAborted();
+ const parsed = PreviewRecordSchema.safeParse(record);
+ if (!parsed.success) throw new ImportFailure("format");
+ summary.include(parsed.data);
+ if (++pending % PAGE_RECORDS === 0) await yieldToLoop(undefined, { signal });
+ }
+ signal.throwIfAborted();
+ return { ...summary.counts, from: summary.from, through: summary.through };
+}
+
+type WriteOptions = {
+ adapter: ImportAdapter;
+ input: ImportInput;
+ preview: ImportPreview;
+ botId: string;
+ store: ImportStore;
+ redactor: BrainRedactor;
+ signal: AbortSignal;
+ progress: (counts: Pick<ImportStatus, "topics" | "messages">) => void;
+};
+
+export async function writeRecords(opts: WriteOptions) {
+ const { adapter, input, preview, botId, store, signal, progress } = opts;
+ const { importId, source } = preview;
+ const summary = new Summary();
+ const page: Array<() => void> = [];
+ let conversationId: string | undefined;
+ let bytes = 0;
+ function flush() {
+ signal.throwIfAborted();
+ if (!page.length) return;
+ store.page(
+ importId,
+ () => {
+ if (!store.availableBot(botId)) throw new ImportFailure("target");
+ for (const write of page) write();
+ },
+ summary.counts,
+ );
+ page.length = 0;
+ progress(summary.counts);
+ }
+ for await (const record of adapter.read(input, signal)) {
+ signal.throwIfAborted();
+ const parsed = ImportRecordSchema.safeParse(record);
+ if (!parsed.success) throw new ImportFailure("format");
+ const item = parsed.data;
+ summary.include(item);
+ if (summary.counts.topics > preview.topics || summary.counts.messages > preview.messages)
+ throw new ImportFailure("source_changed");
+ bytes += Buffer.byteLength(item.kind === "topic" ? item.title : item.text);
+ if (bytes > MAX_TEXT_BYTES) throw new ImportFailure("limit");
+ if (item.kind === "topic") {
+ const title = redactImportText(opts.redactor, item.title).slice(0, 200);
+ page.push(() => {
+ conversationId = store.addTopic(importId, botId, source, { ...item, title });
+ });
+ } else {
+ const text = redactImportText(opts.redactor, item.text);
+ page.push(() => {
+ if (!conversationId) throw new ImportFailure("format");
+ store.addMessage(importId, botId, conversationId, { ...item, text });
+ });
+ }
+ if (page.length < PAGE_RECORDS) continue;
+ flush();
+ await yieldToLoop(undefined, { signal });
+ }
+ if (
+ summary.counts.topics !== preview.topics ||
+ summary.counts.messages !== preview.messages ||
+ summary.from !== preview.from ||
+ summary.through !== preview.through
+ )
+ throw new ImportFailure("source_changed");
+ flush();
+}
+
+function redactImportText(redactor: BrainRedactor, input: string) {
+ return redactor
+ .redact(input)
+ .replace(
+ /\b(password|passwd|api[_ -]?key|access[_ -]?token|refresh[_ -]?token)(["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;]+)/gi,
+ "$1$2[REDACTED]",
+ )
+ .replace(
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
+ "[REDACTED]",
+ )
+ .replace(/\bBearer[ \t]+[A-Za-z0-9_./+~=-]+/gi, "Bearer [REDACTED]");
+}
diff --git a/packages/import/src/brain/source.ts b/packages/import/src/brain/source.ts
new file mode 100644
index 0000000..0b0fd9a
--- /dev/null
+++ b/packages/import/src/brain/source.ts
@@ -0,0 +1,101 @@
+// Only the file chosen by the desktop user becomes readable by an import adapter.
+
+import type { BigIntStats } from "node:fs";
+import { constants } from "node:fs";
+import { lstat, open, realpath } from "node:fs/promises";
+import type { CapabilityContext } from "@pibot/brain/kit";
+import { sensitiveReadBoundary } from "@pibot/execution";
+import { nodeFileSystem, protectedPaths } from "@pibot/policy";
+import { ImportFailure, type ImportInput } from "./adapter.ts";
+
+type HostPaths = Pick<
+ CapabilityContext["local"]["deps"],
+ "dataDir" | "env" | "platform" | "userHome"
+>;
+const MAX_FILE_BYTES = 1024n * 1024n * 1024n;
+const CHUNK_BYTES = 64 * 1024;
+
+function sameFile(left: BigIntStats, right: BigIntStats) {
+ return (
+ right.isFile() &&
+ right.nlink === 1n &&
+ left.dev === right.dev &&
+ left.ino === right.ino &&
+ left.ctimeNs === right.ctimeNs &&
+ left.mtimeNs === right.mtimeNs &&
+ left.size === right.size
+ );
+}
+
+async function authorize(deps: HostPaths, path: string, resolved: string, signal: AbortSignal) {
+ signal.throwIfAborted();
+ const { platform, userHome, env, dataDir } = deps;
+ const sensitive = await sensitiveReadBoundary(platform, [userHome], env);
+ const policy = await protectedPaths(
+ {
+ platform,
+ home: userHome,
+ cwd: userHome,
+ roots: [path, resolved],
+ fs: nodeFileSystem,
+ signal,
+ },
+ [...sensitive.denyRead, dataDir],
+ );
+ signal.throwIfAborted();
+ if (policy.covers(path) || policy.covers(resolved)) throw new ImportFailure("source_changed");
+}
+
+export async function selectedInput(
+ deps: HostPaths,
+ path: string,
+ signal: AbortSignal,
+): Promise<ImportInput> {
+ const resolved = await realpath(path);
+ await authorize(deps, path, resolved, signal);
+ const selected = await lstat(path, { bigint: true });
+ if (!selected.isFile() || selected.nlink !== 1n) throw new ImportFailure("source_changed");
+ if (selected.size > MAX_FILE_BYTES) throw new ImportFailure("limit");
+ return (readSignal) => readSelected(deps, path, resolved, selected, readSignal);
+}
+
+async function* readSelected(
+ deps: HostPaths,
+ path: string,
+ resolved: string,
+ selected: BigIntStats,
+ signal: AbortSignal,
+) {
+ const current = await realpath(path);
+ await authorize(deps, path, current, signal);
+ if (current !== resolved || !sameFile(selected, await lstat(path, { bigint: true })))
+ throw new ImportFailure("source_changed");
+ signal.throwIfAborted();
+ const file = await open(
+ resolved,
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
+ );
+ try {
+ if (!sameFile(selected, await file.stat({ bigint: true })))
+ throw new ImportFailure("source_changed");
+ let remaining = Number(selected.size);
+ while (remaining > 0) {
+ signal.throwIfAborted();
+ const chunk = Buffer.allocUnsafe(Math.min(remaining, CHUNK_BYTES));
+ const { bytesRead } = await file.read(chunk);
+ if (!bytesRead) throw new ImportFailure("source_changed");
+ remaining -= bytesRead;
+ signal.throwIfAborted();
+ yield chunk.subarray(0, bytesRead);
+ }
+ if (
+ !sameFile(selected, await file.stat({ bigint: true })) ||
+ current !== (await realpath(path)) ||
+ !sameFile(selected, await lstat(path, { bigint: true }))
+ )
+ throw new ImportFailure("source_changed");
+ signal.throwIfAborted();
+ } finally {
+ await file.close();
+ }
+}
diff --git a/packages/import/src/store/index.ts b/packages/import/src/store/index.ts
new file mode 100644
index 0000000..155bd98
--- /dev/null
+++ b/packages/import/src/store/index.ts
@@ -0,0 +1,115 @@
+// A batch owns its imported rows, allowing atomic publication, rollback, and recovery.
+import { randomUUID } from "node:crypto";
+import type { DatabaseSync } from "node:sqlite";
+import { type ImportStatus, ImportStatusSchema } from "@pibot/import-contract";
+import { AuditRepo, transaction } from "@pibot/storage";
+
+type ImportedTopic = {
+ title: string;
+ createdAt: string;
+ updatedAt: string;
+};
+type ImportedMessage = {
+ role: "user" | "assistant";
+ text: string;
+ createdAt: string;
+};
+
+export class ImportStore {
+ private readonly audit: AuditRepo;
+
+ constructor(
+ private readonly db: DatabaseSync,
+ redactor: ConstructorParameters<typeof AuditRepo>[1],
+ ) {
+ this.audit = new AuditRepo(db, redactor);
+ }
+
+ availableBot(botId: string) {
+ return !!this.db.prepare("SELECT 1 FROM bots WHERE id=? AND archived_at IS NULL").get(botId);
+ }
+
+ get(id: string) {
+ const row = this.db
+ .prepare(`SELECT id AS importId, source, state, topics, messages, reason
+ FROM import_jobs WHERE id=?`)
+ .get(id);
+ return row ? ImportStatusSchema.parse(row) : undefined;
+ }
+
+ create(id: string, source: ImportStatus["source"], botId: string) {
+ this.db
+ .prepare("INSERT INTO import_jobs(id,source,bot_id,state) VALUES(?,?,?,'running')")
+ .run(id, source, botId);
+ }
+
+ target(id: string) {
+ return this.db.prepare("SELECT bot_id FROM import_jobs WHERE id=?").get(id)?.bot_id;
+ }
+
+ unfinished() {
+ return this.db.prepare("SELECT id FROM import_jobs WHERE state='running' LIMIT 1").get()?.id;
+ }
+
+ addTopic(batchId: string, botId: string, source: ImportStatus["source"], topic: ImportedTopic) {
+ const id = randomUUID();
+ this.db
+ .prepare(`INSERT INTO conversations
+ (id, kind, bot_id, title, created_at, updated_at, import_id, import_source)
+ VALUES (?, 'dm', ?, ?, ?, ?, ?, ?)`)
+ .run(id, botId, topic.title, topic.createdAt, topic.updatedAt, batchId, source);
+ return id;
+ }
+
+ addMessage(batchId: string, botId: string, conversationId: string, msg: ImportedMessage) {
+ this.db
+ .prepare(`INSERT INTO messages
+ (id, conversation_id, role, content, status, bot_id, created_at, updated_at, import_id)
+ VALUES (?, ?, ?, ?, 'done', ?, ?, ?, ?)`)
+ .run(
+ randomUUID(),
+ conversationId,
+ msg.role,
+ msg.text,
+ msg.role === "user" ? null : botId,
+ msg.createdAt,
+ msg.createdAt,
+ batchId,
+ );
+ }
+
+ page<T>(id: string, add: () => T, counts: Pick<ImportStatus, "topics" | "messages">) {
+ return transaction(this.db, () => {
+ const result = add();
+ this.db
+ .prepare("UPDATE import_jobs SET topics=?, messages=? WHERE id=?")
+ .run(counts.topics, counts.messages, id);
+ return result;
+ });
+ }
+
+ finish(status: ImportStatus & { state: Exclude<ImportStatus["state"], "running"> }) {
+ return transaction(this.db, () => {
+ const { importId, state, reason, source, topics, messages } = status;
+ if (state !== "completed") {
+ this.db.prepare("DELETE FROM messages WHERE import_id=?").run(importId);
+ this.db.prepare("DELETE FROM conversations WHERE import_id=?").run(importId);
+ }
+ this.db
+ .prepare("UPDATE import_jobs SET state=?,reason=? WHERE id=?")
+ .run(state, reason, importId);
+ const botId = this.target(importId);
+ if (typeof botId !== "string") throw new Error("import_job_missing");
+ this.audit.append({
+ botId,
+ kind: "import.changed",
+ summary: "Conversation import / 对话导入",
+ detail: {
+ actor: reason === "interrupted" ? "automatic" : "user",
+ conversationImport: { importId, source, state, topics, messages },
+ },
+ });
+ return status;
+ });
+ }
+}
diff --git a/packages/import/tsconfig.json b/packages/import/tsconfig.json
new file mode 100644
index 0000000..03a5d3e
--- /dev/null
+++ b/packages/import/tsconfig.json
@@ -0,0 +1,36 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "include": ["src/**/*.ts", "src/**/*.tsx"],
+ "compilerOptions": {
+ "composite": true,
+ "noEmit": false,
+ "declaration": true,
+ "declarationMap": false,
+ "emitDeclarationOnly": true,
+ "outDir": ".cache/tsc",
+ "tsBuildInfoFile": ".cache/tsc/tsconfig.tsbuildinfo",
+ "disableSourceOfProjectReferenceRedirect": true,
+ "noCheck": true
+ },
+ "references": [
+ {
+ "path": "../brain"
+ },
+ {
+ "path": "../execution"
+ },
+ {
+ "path": "../import-contract"
+ },
+ {
+ "path": "../policy"
+ },
+ {
+ "path": "../protocol-base"
+ },
+ {
+ "path": "../storage"
+ }
+ ],
+ "exclude": ["**/*.test.ts", "**/*.test.tsx", "test/**"]
+}
diff --git a/packages/protocol-base/src/app/search.ts b/packages/protocol-base/src/app/search.ts
index 141bf07..f1f2f5f 100644
--- a/packages/protocol-base/src/app/search.ts
+++ b/packages/protocol-base/src/app/search.ts
@@ -13,6 +13,8 @@ const SearchConversationSchema = ConversationSchema.pick({
botId: true,
groupId: true,
title: true,
+ readOnly: true,
+ importSource: true,
});
export const SearchMethods = {
"search.query": {
diff --git a/packages/protocol-base/src/chat/entities.ts b/packages/protocol-base/src/chat/entities.ts
index 6d2bf34..8e517e2 100644
--- a/packages/protocol-base/src/chat/entities.ts
+++ b/packages/protocol-base/src/chat/entities.ts
@@ -50,6 +50,8 @@ export const MessageSchema = z.strictObject({
tools: z.array(ToolCallRecordSchema).optional(),
});
export const ConversationSchema = z.strictObject({
+ readOnly: z.literal(true).optional(),
+ importSource: z.string().min(1).max(32).optional(),
workplaceFolderId: z
.union([z.literal("home"), IdSchema])
.nullable()
diff --git a/packages/protocol-base/src/permissions/audit.ts b/packages/protocol-base/src/permissions/audit.ts
index ccbbd30..f56e777 100644
--- a/packages/protocol-base/src/permissions/audit.ts
+++ b/packages/protocol-base/src/permissions/audit.ts
@@ -69,6 +69,7 @@ export const AuditKindSchema = z.enum([
"image.started",
"image.finished",
"messages.read",
+ "import.changed",
"grant.created",
"grant.revoked",
"policy.denied",
@@ -204,6 +205,15 @@ export const AuditAuthEventSchema = z.enum([
export type AuditAuthEvent = z.infer<typeof AuditAuthEventSchema>;
// Detail contains facts only. Tool output, prompts and file content have separate storage paths.
export const AuditDetailSchema = z.strictObject({
+ conversationImport: z
+ .strictObject({
+ importId: IdSchema,
+ source: z.string().min(1).max(32),
+ state: z.enum(["completed", "cancelled", "failed", "undone"]),
+ topics: count,
+ messages: count,
+ })
+ .optional(),
pluginInstall: z
.strictObject({
name: z.string().max(200),
diff --git a/packages/protocol/package.json b/packages/protocol/package.json
index 4877329..a8409e7 100644
--- a/packages/protocol/package.json
+++ b/packages/protocol/package.json
@@ -22,6 +22,7 @@
"@pibot/models-contract": "workspace:0.0.0",
"@pibot/office-contract": "workspace:0.0.0",
"@pibot/images-contract": "workspace:0.0.0",
+ "@pibot/import-contract": "workspace:0.0.0",
"@pibot/credentials-contract": "workspace:0.0.0",
"@pibot/skills-contract": "workspace:0.0.0",
"@pibot/computer-use-contract": "workspace:0.0.0",
diff --git a/packages/protocol/src/aggregate/api.ts b/packages/protocol/src/aggregate/api.ts
index 064aa4c..a70766b 100644
--- a/packages/protocol/src/aggregate/api.ts
+++ b/packages/protocol/src/aggregate/api.ts
@@ -17,6 +17,7 @@ import {
} from "@pibot/credentials-contract";
import { ExternalAgentEvents, ExternalAgentMethods } from "@pibot/external-agents-contract";
import { ImageArtifactMethods } from "@pibot/images-contract";
+import { ImportEvents, ImportMethods } from "@pibot/import-contract";
import { ModelProviderEvents, ModelProviderMethods } from "@pibot/models-contract";
import { OfficeMethods } from "@pibot/office-contract";
import {
@@ -184,6 +185,7 @@ const count = z.number().int().nonnegative().safe();
export const Events = {
...KernelEvents,
+ ...ImportEvents,
...ExternalAgentEvents,
...CapabilityEvents,
...RemoteEvents,
@@ -263,6 +265,7 @@ function eventSchema<K extends keyof typeof Events>(method: K) {
}
export const EventEnvelopeSchema = z.discriminatedUnion("method", [
eventSchema("acp.changed"),
+ eventSchema("import.progress"),
eventSchema("capabilities.changed"),
eventSchema("botHooks.changed"),
eventSchema("devices.changed"),
@@ -483,6 +486,7 @@ Omit<typeof KernelMethods, keyof typeof InboxMethods | keyof typeof AppMethods>
typeof ContinuationMethods &
typeof PersonalTodoMethods &
typeof OfficeMethods &
+ typeof ImportMethods &
typeof PreviewMethods &
typeof ChatRecoveryMethods &
typeof MessageActionMethods &
@@ -563,6 +567,7 @@ Omit<typeof KernelMethods, keyof typeof InboxMethods | keyof typeof AppMethods>
...ContinuationMethods,
...PersonalTodoMethods,
...OfficeMethods,
+ ...ImportMethods,
...PreviewMethods,
...ChatRecoveryMethods,
...MessageActionMethods,
diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts
index 15cb725..01d18f8 100644
--- a/packages/protocol/src/index.ts
+++ b/packages/protocol/src/index.ts
@@ -3,6 +3,7 @@ export * from "@pibot/computer-use-contract";
export * from "@pibot/credentials-contract";
export * from "@pibot/external-agents-contract";
export * from "@pibot/images-contract";
+export * from "@pibot/import-contract";
export * from "@pibot/models-contract";
export * from "@pibot/office-contract";
export * from "@pibot/plugins-contract";
diff --git a/packages/protocol/test/schemas.test.ts b/packages/protocol/test/schemas.test.ts
index 321fe79..7e55d62 100644
--- a/packages/protocol/test/schemas.test.ts
+++ b/packages/protocol/test/schemas.test.ts
@@ -436,7 +436,37 @@ const backgroundState = {
restartCount: 0,
at: date,
} as const;
+const importStatus = {
+ importId: id,
+ source: "fixture",
+ state: "running",
+ topics: 0,
+ messages: 0,
+ reason: null,
+} as const;
+
const methodCases = {
+ "import.detect": {
+ params: { source: "fixture" },
+ result: { available: true },
+ badParams: {},
+ badResult: {},
+ },
+ "import.preview": { params: { source: "fixture" }, result: null, badParams: {}, badResult: {} },
+ "import.start": {
+ params: { importId: id, botId: id },
+ result: importStatus,
+ badParams: {},
+ badResult: {},
+ },
+ "import.status": { params: { importId: id }, result: importStatus, badParams: {}, badResult: {} },
+ "import.cancel": { params: { importId: id }, result: importStatus, badParams: {}, badResult: {} },
+ "import.undo": {
+ params: { importId: id },
+ result: { ...importStatus, state: "undone" },
+ badParams: {},
+ badResult: {},
+ },
"acp.state": {
params: {},
result: { connected: false },
@@ -3848,6 +3878,7 @@ function browserHostCases() {
};
}
const eventCases = {
+ "import.progress": { payload: importStatus, bad: {} },
"acp.changed": { payload: { connected: false }, bad: { connected: true } },
"botHooks.changed": { payload: { botId: id }, bad: { botId: "invalid" } },
...remoteEventCases,
diff --git a/packages/protocol/tsconfig.json b/packages/protocol/tsconfig.json
index 123f512..84e2c3c 100644
--- a/packages/protocol/tsconfig.json
+++ b/packages/protocol/tsconfig.json
@@ -28,6 +28,9 @@
{
"path": "../images-contract"
},
+ {
+ "path": "../import-contract"
+ },
{
"path": "../models-contract"
},
diff --git a/packages/storage/migrations/0175_conversation_imports.sql b/packages/storage/migrations/0175_conversation_imports.sql
new file mode 100644
index 0000000..8185691
--- /dev/null
+++ b/packages/storage/migrations/0175_conversation_imports.sql
@@ -0,0 +1,69 @@
+-- Publish a completed batch atomically while allowing short transactions for individual pages.
+CREATE TABLE import_jobs (
+ id TEXT PRIMARY KEY,
+ source TEXT NOT NULL,
+ -- Like the audit log, keep the batch receipt after a Bot is deleted.
+ bot_id TEXT NOT NULL,
+ state TEXT NOT NULL CHECK(state IN ('running','completed','cancelled','failed','undone')),
+ topics INTEGER NOT NULL DEFAULT 0,
+ messages INTEGER NOT NULL DEFAULT 0,
+ reason TEXT
+);
+ALTER TABLE conversations ADD COLUMN import_id TEXT REFERENCES import_jobs(id);
+ALTER TABLE conversations ADD COLUMN import_source TEXT;
+ALTER TABLE messages ADD COLUMN import_id TEXT REFERENCES import_jobs(id);
+CREATE INDEX conversations_import_id ON conversations(import_id) WHERE import_id IS NOT NULL;
+CREATE INDEX messages_import_id ON messages(import_id) WHERE import_id IS NOT NULL;
+
+-- Ordinary chat writers must not attach live data to imported history, even through a new caller.
+CREATE TRIGGER import_topic_owner BEFORE INSERT ON conversations
+WHEN (NEW.import_id IS NULL AND NEW.import_source IS NOT NULL)
+ OR (NEW.import_id IS NOT NULL AND (
+ NEW.kind<>'dm' OR NEW.pi_session_file IS NOT NULL OR NOT EXISTS (
+ SELECT 1 FROM import_jobs WHERE id=NEW.import_id AND state='running'
+ AND source=NEW.import_source AND bot_id=NEW.bot_id
+ )
+ ))
+BEGIN
+ SELECT RAISE(ABORT, 'import_topic_read_only');
+END;
+CREATE TRIGGER import_message_owner BEFORE INSERT ON messages
+WHEN NEW.import_id IS NOT (SELECT import_id FROM conversations WHERE id=NEW.conversation_id)
+ OR (NEW.import_id IS NOT NULL AND NOT EXISTS (
+ SELECT 1 FROM import_jobs WHERE id=NEW.import_id AND state='running'
+ ))
+BEGIN
+ SELECT RAISE(ABORT, 'import_topic_read_only');
+END;
+CREATE TRIGGER import_message_read_only BEFORE UPDATE ON messages
+WHEN OLD.import_id IS NOT NULL OR NEW.import_id IS NOT NULL
+BEGIN
+ SELECT RAISE(ABORT, 'import_topic_read_only');
+END;
+-- Title, archive state, and activity time remain ordinary topic metadata.
+CREATE TRIGGER import_topic_read_only BEFORE UPDATE ON conversations
+WHEN (OLD.import_id IS NOT NULL OR NEW.import_id IS NOT NULL) AND NOT (
+ OLD.id IS NEW.id
+ AND OLD.bot_id IS NEW.bot_id
+ AND OLD.kind IS NEW.kind
+ AND OLD.group_id IS NEW.group_id
+ AND OLD.thread_of IS NEW.thread_of
+ AND OLD.import_id IS NEW.import_id
+ AND OLD.import_source IS NEW.import_source
+ AND OLD.pi_session_file IS NEW.pi_session_file
+ AND OLD.workplace_folder_id IS NEW.workplace_folder_id
+ AND OLD.workplace_revision IS NEW.workplace_revision
+ AND OLD.routine_id IS NEW.routine_id
+ AND OLD.internal_task_id IS NEW.internal_task_id
+ AND OLD.acp_session IS NEW.acp_session
+ AND OLD.yolo_at IS NEW.yolo_at
+ AND OLD.created_at IS NEW.created_at
+)
+BEGIN
+ SELECT RAISE(ABORT, 'import_topic_read_only');
+END;
+CREATE TRIGGER import_run_read_only BEFORE INSERT ON runs
+WHEN EXISTS (SELECT 1 FROM conversations WHERE id=NEW.conversation_id AND import_id IS NOT NULL)
+BEGIN
+ SELECT RAISE(ABORT, 'import_topic_read_only');
+END;
diff --git a/packages/storage/src/bots/memory-extraction-boundaries.ts b/packages/storage/src/bots/memory-extraction-boundaries.ts
index 3462861..eb30494 100644
--- a/packages/storage/src/bots/memory-extraction-boundaries.ts
+++ b/packages/storage/src/bots/memory-extraction-boundaries.ts
@@ -6,7 +6,7 @@ const topicOwner = `
FROM conversations c
LEFT JOIN groups g ON g.id=c.group_id AND g.archived_at IS NULL
JOIN bots b ON b.id=COALESCE(c.bot_id,g.coordinator_bot_id)
- WHERE c.kind IN ('dm','group') AND c.internal_task_id IS NULL
+ WHERE c.import_id IS NULL AND c.kind IN ('dm','group') AND c.internal_task_id IS NULL
AND b.archived_at IS NULL AND b.memory_extraction=1 AND b.kind IS NOT 'agent'
AND (c.kind='dm' OR EXISTS (
SELECT 1 FROM group_members gm WHERE gm.group_id=g.id AND gm.bot_id=b.id AND gm.left_at IS NULL
@@ -135,7 +135,7 @@ export function legacyDueTopics(
(SELECT COUNT(*) FROM messages m WHERE m.conversation_id=c.id AND m.role='user'
AND m.status='done') AS userCount
FROM conversations c LEFT JOIN groups g ON g.id=c.group_id
- WHERE c.kind IN ('dm','group')
+ WHERE c.import_id IS NULL AND c.kind IN ('dm','group')
)
SELECT t.conversationId, t.botId, t.groupId, t.lastMessageId, t.lastUserId, t.lastAt
FROM t JOIN bots b ON b.id=t.botId AND b.memory_extraction=1 AND b.archived_at IS NULL
diff --git a/packages/storage/src/bots/memory-extraction.ts b/packages/storage/src/bots/memory-extraction.ts
index 5b6edaa..0efde15 100644
--- a/packages/storage/src/bots/memory-extraction.ts
+++ b/packages/storage/src/bots/memory-extraction.ts
@@ -86,7 +86,8 @@ export class MemoryExtractionsRepo {
`INSERT INTO memory_extractions
(id, bot_id, conversation_id, group_id, status, reason, priority, source_message_id, created_at)
SELECT ?,?,?,?, 'queued', ?,?,?,?
- WHERE NOT EXISTS (
+ WHERE NOT EXISTS (SELECT 1 FROM conversations WHERE id=? AND import_id IS NOT NULL)
+ AND NOT EXISTS (
SELECT 1 FROM memory_extractions
WHERE conversation_id=? AND status='running'
AND (?=0 OR (reason=? AND source_message_id IS ?))
@@ -112,6 +113,7 @@ export class MemoryExtractionsRepo {
source,
at,
input.conversationId,
+ input.conversationId,
priority,
input.reason,
source,
diff --git a/packages/storage/src/conversations/chat-search.ts b/packages/storage/src/conversations/chat-search.ts
index c59995b..701d974 100644
--- a/packages/storage/src/conversations/chat-search.ts
+++ b/packages/storage/src/conversations/chat-search.ts
@@ -8,7 +8,7 @@ export type ChatSearchScope = { botId: string } | { botId: string; groupId: stri
const SHORT_QUERY_BATCH = 64;
const scopeFilter = `
EXISTS(SELECT 1 FROM bots b WHERE b.id=$bot AND b.archived_at IS NULL)
- AND c.internal_task_id IS NULL
+ AND c.internal_task_id IS NULL AND c.import_id IS NULL
AND (($group IS NULL AND c.kind='dm' AND c.bot_id=$bot AND (m.role='user' OR m.bot_id=$bot))
OR ($group IS NOT NULL AND c.kind='group' AND c.group_id=$group
AND EXISTS(SELECT 1 FROM group_members gm WHERE gm.group_id=$group
diff --git a/packages/storage/src/conversations/conversations.ts b/packages/storage/src/conversations/conversations.ts
index 0640344..d172346 100644
--- a/packages/storage/src/conversations/conversations.ts
+++ b/packages/storage/src/conversations/conversations.ts
@@ -16,12 +16,26 @@ import { TopicFoldersRepo } from "./topic-folders.ts";
export type Conversation = ProtocolConversation;
export type DmConversation = Conversation & { kind: "dm"; botId: string };
const columns =
- "id,kind,bot_id AS botId,pi_session_file AS piSessionFile,group_id AS groupId,thread_of AS threadOf,routine_id AS routineId,workplace_folder_id AS workplaceFolderId,workplace_revision AS workplaceRevision,title,archived_at AS archivedAt,created_at AS createdAt,updated_at AS updatedAt";
+ "id,kind,bot_id AS botId,pi_session_file AS piSessionFile,group_id AS groupId,thread_of AS threadOf,routine_id AS routineId,workplace_folder_id AS workplaceFolderId,workplace_revision AS workplaceRevision,title,archived_at AS archivedAt,created_at AS createdAt,updated_at AS updatedAt,import_source AS importSource";
+
+// The batch state is the publication barrier. Rows from an interrupted writer stay private.
+export const visibleImport =
+ "(import_id IS NULL OR import_id IN (SELECT id FROM import_jobs WHERE state='completed'))";
+
+export function importProjection(source: unknown) {
+ return typeof source === "string" ? { readOnly: true as const, importSource: source } : {};
+}
+
+function parseConversation({ importSource, ...row }: Record<string, unknown>) {
+ return ConversationSchema.parse({ ...row, ...importProjection(importSource) });
+}
export class ConversationsRepo {
constructor(private readonly db: DatabaseSync) {}
get(id: string): Conversation | undefined {
- const row = this.db.prepare(`SELECT ${columns} FROM conversations WHERE id=?`).get(id);
- return row ? ConversationSchema.parse(row) : undefined;
+ const row = this.db
+ .prepare(`SELECT ${columns} FROM conversations WHERE id=? AND ${visibleImport}`)
+ .get(id);
+ return row ? parseConversation(row) : undefined;
}
isInternal(id: string): boolean {
return !!this.db
@@ -34,15 +48,15 @@ export class ConversationsRepo {
botId === undefined
? this.db
.prepare(
- `SELECT ${columns} FROM conversations WHERE kind='dm' AND internal_task_id IS NULL ORDER BY rowid`,
+ `SELECT ${columns} FROM conversations WHERE kind='dm' AND internal_task_id IS NULL AND ${visibleImport} ORDER BY rowid`,
)
.all()
: this.db
.prepare(
- `SELECT ${columns} FROM conversations WHERE kind='dm' AND bot_id=? AND internal_task_id IS NULL ORDER BY rowid`,
+ `SELECT ${columns} FROM conversations WHERE kind='dm' AND bot_id=? AND internal_task_id IS NULL AND ${visibleImport} ORDER BY rowid`,
)
.all(botId);
- return rows.map((r) => ConversationSchema.parse(r) as DmConversation);
+ return rows.map((r) => parseConversation(r) as DmConversation);
}
topics(botId: string, page: Page = {}): DmConversation[] {
return readPage(this.db, "conversations", columns, "updated_at", page, [
@@ -50,7 +64,8 @@ export class ConversationsRepo {
["kind", "dm"],
["archived_at", null],
["internal_task_id", null],
- ]).map((r) => ConversationSchema.parse(r) as DmConversation);
+ ["import_id", null],
+ ]).map((r) => parseConversation(r) as DmConversation);
}
/**
* Every new topic owns its folders from the start: the given selection (a new-topic draft)
@@ -130,13 +145,13 @@ export class ConversationsRepo {
`SELECT ${columns} FROM conversations WHERE kind='group' AND group_id=? ORDER BY id=(SELECT conversation_id FROM group_current_topics WHERE group_id=?) DESC,archived_at IS NULL DESC,updated_at DESC,id DESC LIMIT 1`,
)
.get(groupId, groupId);
- return row ? ConversationSchema.parse(row) : undefined;
+ return row ? parseConversation(row) : undefined;
}
threads(groupId: string, page: Page = {}): Conversation[] {
return readPage(this.db, "conversations", columns, "created_at", page, [
["group_id", groupId],
["kind", "thread"],
- ]).map((r) => ConversationSchema.parse(r));
+ ]).map(parseConversation);
}
switchTopic(botId: string, topicId: string): DmConversation {
const topic = this.get(topicId);
@@ -147,6 +162,7 @@ export class ConversationsRepo {
this.isInternal(topicId)
)
throw new TypeError("Unknown topic");
+ if (topic.readOnly) return topic as DmConversation;
this.db
.prepare(
"INSERT INTO settings(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
@@ -163,6 +179,7 @@ export class ConversationsRepo {
return topic?.kind === "dm" &&
topic.botId === botId &&
!topic.archivedAt &&
+ !topic.readOnly &&
!this.isInternal(topic.id)
? (topic as DmConversation)
: this.latestChatTopic(botId);
@@ -194,10 +211,14 @@ export class ConversationsRepo {
});
}
ensureDm(botId: string): DmConversation {
- return transaction(
- this.db,
- () => this.list(botId).find((t) => !t.archivedAt) ?? this.create({ botId }),
- );
+ return transaction(this.db, () => {
+ const row = this.db
+ .prepare(`SELECT ${columns} FROM conversations
+ WHERE kind='dm' AND bot_id=? AND internal_task_id IS NULL AND archived_at IS NULL
+ AND import_id IS NULL ORDER BY rowid LIMIT 1`)
+ .get(botId);
+ return row ? (parseConversation(row) as DmConversation) : this.create({ botId });
+ });
}
archive(id: string): void {
this.db
@@ -211,6 +232,10 @@ export class ConversationsRepo {
}
remove(id: string): boolean {
return transaction(this.db, () => {
+ if (this.get(id)?.readOnly)
+ this.db
+ .prepare("DELETE FROM messages WHERE conversation_id=? AND import_id IS NOT NULL")
+ .run(id);
this.db.prepare("DELETE FROM bot_sessions WHERE conversation_id=?").run(id);
return this.db.prepare("DELETE FROM conversations WHERE id=?").run(id).changes > 0;
});
diff --git a/packages/storage/src/conversations/read-messages.ts b/packages/storage/src/conversations/read-messages.ts
index 5bb3c34..842b12b 100644
--- a/packages/storage/src/conversations/read-messages.ts
+++ b/packages/storage/src/conversations/read-messages.ts
@@ -8,7 +8,7 @@ import {
} from "@pibot/protocol-base";
// Scope is applied in SQL, never by loading another Bot's history and filtering it afterwards.
-const readable = `c.archived_at IS NULL AND c.internal_task_id IS NULL AND EXISTS(SELECT 1 FROM bots b WHERE b.id=$bot AND b.archived_at IS NULL)
+const readable = `c.archived_at IS NULL AND c.internal_task_id IS NULL AND c.import_id IS NULL AND EXISTS(SELECT 1 FROM bots b WHERE b.id=$bot AND b.archived_at IS NULL)
AND ((c.kind='dm' AND c.bot_id=$bot) OR (c.kind IN ('group','thread') AND
EXISTS(SELECT 1 FROM groups g JOIN group_members gm ON gm.group_id=g.id
WHERE g.id=c.group_id AND gm.bot_id=$bot AND gm.left_at IS NULL) AND
@@ -43,7 +43,7 @@ export class ReadMessagesRepo {
AND rr.decision_consumed_at IS NULL AND json_type(rr.wait_checkpoint,'$.drain')='object'
AND json_extract(rr.wait_checkpoint,'$.messageId')=m.id
AND json_extract(rr.wait_checkpoint,'$.conversationId')=c.id)))
- AND r.message_id=? AND c.id=? AND c.internal_task_id IS NULL AND m.role='assistant' AND m.status='streaming'
+ AND r.message_id=? AND c.id=? AND c.internal_task_id IS NULL AND c.import_id IS NULL AND m.role='assistant' AND m.status='streaming'
AND m.bot_id=r.bot_id AND m.run_id=r.id AND m.conversation_id=c.id
AND r.group_id IS c.group_id`)
.get(runId, botId, parkedRoutineId ?? null, messageId, conversationId);
diff --git a/packages/storage/src/conversations/topic-folders.ts b/packages/storage/src/conversations/topic-folders.ts
index 96a810c..d65f3a0 100644
--- a/packages/storage/src/conversations/topic-folders.ts
+++ b/packages/storage/src/conversations/topic-folders.ts
@@ -47,7 +47,7 @@ export class TopicFoldersRepo {
const currentId = current ? (JSON.parse(String(current.value)) as unknown) : undefined;
const candidate = this.db
.prepare(
- `SELECT c.id FROM conversations c WHERE c.kind='dm' AND c.bot_id=? AND c.archived_at IS NULL AND c.routine_id IS NULL AND c.internal_task_id IS NULL AND c.acp_session=0
+ `SELECT c.id FROM conversations c WHERE c.kind='dm' AND c.bot_id=? AND c.archived_at IS NULL AND c.routine_id IS NULL AND c.internal_task_id IS NULL AND c.acp_session=0 AND c.import_id IS NULL
AND id IS NOT ?
AND NOT EXISTS (
SELECT 1 FROM working_folders sf
diff --git a/packages/storage/src/conversations/topics.ts b/packages/storage/src/conversations/topics.ts
index ac5586b..4170128 100644
--- a/packages/storage/src/conversations/topics.ts
+++ b/packages/storage/src/conversations/topics.ts
@@ -7,7 +7,7 @@ import {
KernelMethods,
} from "@pibot/protocol-base";
import { transaction } from "../database/database.ts";
-import { ConversationsRepo } from "./conversations.ts";
+import { ConversationsRepo, importProjection } from "./conversations.ts";
import { TopicFoldersRepo } from "./topic-folders.ts";
export class TopicsRepo {
@@ -45,12 +45,13 @@ export class TopicsRepo {
const rows = this.db
.prepare(`SELECT * FROM (SELECT c.id,c.kind,c.bot_id AS botId,c.pi_session_file AS piSessionFile,
c.routine_id AS routineId,c.workplace_folder_id AS workplaceFolderId,c.workplace_revision AS workplaceRevision,c.group_id AS groupId,c.thread_of AS threadOf,c.title,c.archived_at AS archivedAt,
- c.created_at AS createdAt,c.updated_at AS updatedAt,wf.name AS workplaceFolderName,
+ c.created_at AS createdAt,c.updated_at AS updatedAt,c.import_source AS importSource,wf.name AS workplaceFolderName,
(SELECT COUNT(*) FROM messages m WHERE m.conversation_id=c.id) AS messageCount,
${sortAt} AS sortAt
FROM conversations c LEFT JOIN working_folders wf ON wf.bot_id=c.bot_id AND wf.id=c.workplace_folder_id
WHERE c.kind='dm' AND c.bot_id=? AND (CASE WHEN ? THEN c.archived_at IS NOT NULL ELSE c.archived_at IS NULL END) AND c.internal_task_id IS NULL
- AND (? OR c.routine_id IS NOT NULL OR c.id=? OR EXISTS(SELECT 1 FROM messages m WHERE m.conversation_id=c.id) OR EXISTS(SELECT 1 FROM conversation_retries cr WHERE cr.conversation_id=c.id AND cr.state='done'))
+ AND (c.import_id IS NULL OR c.import_id IN (SELECT id FROM import_jobs WHERE state='completed'))
+ AND (? OR c.routine_id IS NOT NULL OR c.import_id IS NOT NULL OR c.id=? OR EXISTS(SELECT 1 FROM messages m WHERE m.conversation_id=c.id) OR EXISTS(SELECT 1 FROM conversation_retries cr WHERE cr.conversation_id=c.id AND cr.state='done'))
AND instr(lower(c.title),lower(?))>0 AND (?=0 OR c.id=?)) t
WHERE t.sortAt IS NOT NULL AND (? IS NULL OR t.sortAt<? OR (t.sortAt=? AND t.id<?))
ORDER BY t.sortAt DESC,t.id DESC LIMIT ?`)
@@ -69,8 +70,9 @@ export class TopicsRepo {
limit,
);
return KernelMethods["topics.list"].result.parse(
- rows.map(({ sortAt: _sortAt, ...row }) => ({
+ rows.map(({ sortAt: _sortAt, importSource, ...row }) => ({
...row,
+ ...importProjection(importSource),
isCurrent: row.id === currentId,
workplaceFolderName:
typeof row.workplaceFolderName === "string"
@@ -126,6 +128,7 @@ export class TopicsRepo {
new ConversationsRepo(this.db).isInternal(topicId)
)
throw new TypeError("Unknown topic");
+ if (topic.readOnly) throw new TypeError("import_topic_read_only");
if (this.busy(topicId)) throw new TypeError("topic_workplace_busy");
new TopicFoldersRepo(this.db).set(botId, topicId, selection, options);
const updated = new ConversationsRepo(this.db).get(topicId);
diff --git a/packages/storage/src/settings/search.ts b/packages/storage/src/settings/search.ts
index ad44e98..355c2cf 100644
--- a/packages/storage/src/settings/search.ts
+++ b/packages/storage/src/settings/search.ts
@@ -13,6 +13,7 @@ const PAGE_BUDGET_MS = 120;
const SCAN_CHUNK = 400;
const visible = `c.archived_at IS NULL AND c.internal_task_id IS NULL
+ AND (c.import_id IS NULL OR c.import_id IN (SELECT id FROM import_jobs WHERE state='completed'))
AND (c.bot_id IS NULL OR EXISTS(SELECT 1 FROM bots b WHERE b.id=c.bot_id AND b.archived_at IS NULL))`;
const order = "ORDER BY m.created_at DESC,m.rowid DESC";
const seek = "AND (m.created_at,m.rowid)<($at,$row)";
@@ -62,7 +63,7 @@ export class SearchRepo {
? []
: this.db
.prepare(
- `SELECT id FROM conversations WHERE archived_at IS NULL AND internal_task_id IS NULL AND kind IN ('dm','group') AND title LIKE ? ESCAPE '\\' AND (bot_id IS NULL OR EXISTS(SELECT 1 FROM bots b WHERE b.id=conversations.bot_id AND b.archived_at IS NULL)) ORDER BY updated_at DESC,id DESC LIMIT ?`,
+ `SELECT id FROM conversations c WHERE ${visible} AND kind IN ('dm','group') AND title LIKE ? ESCAPE '\\' ORDER BY updated_at DESC,id DESC LIMIT ?`,
)
.all(pattern, limit);
const page =
@@ -71,12 +72,13 @@ export class SearchRepo {
: this.scanned(pattern, limit, from);
const conversations = new ConversationsRepo(this.db),
found = page.ids.map((id) => messages.get(id)).filter((m) => m !== undefined),
- pick = ({ id, kind, botId, groupId, title }: Conversation) => ({
+ pick = ({ id, kind, botId, groupId, title, readOnly, importSource }: Conversation) => ({
id,
kind,
botId,
groupId,
title,
+ ...(readOnly ? { readOnly, importSource } : {}),
});
return {
topics: topics
diff --git a/packages/storage/src/workspace/repositories.ts b/packages/storage/src/workspace/repositories.ts
index 3e23ae8..7c082ed 100644
--- a/packages/storage/src/workspace/repositories.ts
+++ b/packages/storage/src/workspace/repositories.ts
@@ -10,7 +10,7 @@ import {
} from "@pibot/protocol-base";
import { BotsRepo } from "../bots/bots.ts";
import { AttachmentsRepo } from "../conversations/attachments.ts";
-import { ConversationsRepo } from "../conversations/conversations.ts";
+import { ConversationsRepo, visibleImport } from "../conversations/conversations.ts";
import { routineTopicReference } from "../conversations/routine-topic-reference.ts";
import { SidebarRepo } from "../conversations/sidebar.ts";
import { transaction } from "../database/database.ts";
@@ -154,7 +154,9 @@ export class MessagesRepo {
) {}
get(id: string): Message | undefined {
- const row = this.db.prepare(`SELECT ${messageColumns} FROM messages WHERE id = ?`).get(id);
+ const row = this.db
+ .prepare(`SELECT ${messageColumns} FROM messages WHERE id = ? AND ${visibleImport}`)
+ .get(id);
return row ? this.withDetails([parseMessage(row)])[0] : undefined;
}
/** The program's own plan checkpoint only; explicit user pauses keep their original meaning. */
@@ -181,7 +183,7 @@ export class MessagesRepo {
if (!ids.length || ids.length > 50) throw new TypeError("Invalid message selection");
const rows = this.db
.prepare(
- `SELECT ${messageColumns} FROM messages WHERE conversation_id=? AND id IN (${ids.map(() => "?").join(",")}) ORDER BY created_at,rowid`,
+ `SELECT ${messageColumns} FROM messages WHERE conversation_id=? AND ${visibleImport} AND id IN (${ids.map(() => "?").join(",")}) ORDER BY created_at,rowid`,
)
.all(conversationId, ...ids);
return this.withDetails(rows.map(parseMessage));
@@ -713,12 +715,14 @@ export class MessagesRepo {
let rows: Record<string, unknown>[];
if (before !== undefined) {
const cursor = this.db
- .prepare("SELECT created_at, rowid FROM messages WHERE id = ? AND conversation_id = ?")
+ .prepare(
+ `SELECT created_at, rowid FROM messages WHERE id = ? AND conversation_id = ? AND ${visibleImport}`,
+ )
.get(before, conversationId);
if (!cursor) return [];
// UUIDs do not encode order; rowid preserves insertion order for equal millisecond timestamps.
rows = this.db
- .prepare(`SELECT ${messageColumns} FROM messages WHERE conversation_id = ?
+ .prepare(`SELECT ${messageColumns} FROM messages WHERE conversation_id = ? AND ${visibleImport}
AND (created_at < ? OR (created_at = ? AND rowid < ?)) ORDER BY created_at DESC, rowid DESC LIMIT ?`)
.all(
conversationId,
@@ -729,7 +733,7 @@ export class MessagesRepo {
);
} else {
rows = this.db
- .prepare(`SELECT ${messageColumns} FROM messages WHERE conversation_id = ?
+ .prepare(`SELECT ${messageColumns} FROM messages WHERE conversation_id = ? AND ${visibleImport}
ORDER BY created_at DESC, rowid DESC LIMIT ?`)
.all(conversationId, limit);
}
@@ -753,6 +757,8 @@ export class MessagesRepo {
remove(id: string): boolean {
return transaction(this.db, () => {
+ if (this.db.prepare("SELECT 1 FROM messages WHERE id=? AND import_id IS NOT NULL").get(id))
+ throw new TypeError("import_topic_read_only");
// Tool foreign keys must reject deletion before attachment files are irreversibly removed.
if (this.db.prepare("SELECT id FROM tool_calls WHERE message_id = ? LIMIT 1").get(id)) {
throw new TypeError("Cannot delete message with tool calls");
diff --git a/packages/storage/test/store.test.ts b/packages/storage/test/store.test.ts
index 1fc6e3d..4339f8f 100644
--- a/packages/storage/test/store.test.ts
+++ b/packages/storage/test/store.test.ts
@@ -176,6 +176,7 @@ describe("database and migrations", () => {
"groups",
"image_artifacts",
"image_workspace_receipts",
+ "import_jobs",
"knowledge_assignments",
"knowledge_managed_installations",
"knowledge_sources",
@@ -263,7 +264,7 @@ describe("database and migrations", () => {
"worktree_allocations",
]);
const versions = db.prepare("SELECT * FROM schema_migrations").all();
- expect(versions).toHaveLength(172);
+ expect(versions).toHaveLength(173);
expect(versions[0]?.version).toBe(1);
expect(String(versions[0]?.applied_at)).toMatch(/Z$/);
const bot = new BotsRepo(db).ensureMainBot();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7ce294b..f7ea6df 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -314,6 +314,12 @@ importers:
'@pibot/images-contract':
specifier: workspace:*
version: link:../../packages/images-contract
+ '@pibot/import':
+ specifier: workspace:0.0.0
+ version: link:../../packages/import
+ '@pibot/import-contract':
+ specifier: workspace:*
+ version: link:../../packages/import-contract
'@pibot/link':
specifier: workspace:*
version: link:../../packages/link
@@ -888,6 +894,9 @@ importers:
'@pibot/images':
specifier: workspace:0.0.0
version: link:../images
+ '@pibot/import':
+ specifier: workspace:0.0.0
+ version: link:../import
'@pibot/memory':
specifier: workspace:0.0.0
version: link:../memory
@@ -1317,6 +1326,39 @@ importers:
specifier: 4.6.5
version: 4.6.5
+ packages/import:
+ dependencies:
+ '@pibot/brain':
+ specifier: workspace:0.0.0
+ version: link:../brain
+ '@pibot/execution':
+ specifier: workspace:0.0.0
+ version: link:../execution
+ '@pibot/import-contract':
+ specifier: workspace:0.0.0
+ version: link:../import-contract
+ '@pibot/policy':
+ specifier: workspace:0.0.0
+ version: link:../policy
+ '@pibot/protocol-base':
+ specifier: workspace:0.0.0
+ version: link:../protocol-base
+ '@pibot/storage':
+ specifier: workspace:0.0.0
+ version: link:../storage
+ zod:
+ specifier: 4.6.5
+ version: 4.6.5
+
+ packages/import-contract:
+ dependencies:
+ '@pibot/protocol-base':
+ specifier: workspace:0.0.0
+ version: link:../protocol-base
+ zod:
+ specifier: 4.6.5
+ version: 4.6.5
+
packages/link:
dependencies:
'@noble/ciphers':
@@ -1617,6 +1659,9 @@ importers:
'@pibot/images-contract':
specifier: workspace:0.0.0
version: link:../images-contract
+ '@pibot/import-contract':
+ specifier: workspace:0.0.0
+ version: link:../import-contract
'@pibot/models-contract':
specifier: workspace:0.0.0
version: link:../models-contract
diff --git a/tools/dev/domain-boundaries.ts b/tools/dev/domain-boundaries.ts
index 53c21c5..7c58380 100644
--- a/tools/dev/domain-boundaries.ts
+++ b/tools/dev/domain-boundaries.ts
@@ -46,6 +46,8 @@ const modular: { src: string; root: string[] }[] = [
{ src: "packages/memory/src", root: [] },
{ src: "packages/orchestration/src", root: ["index.ts", "full.ts"] },
{ src: "packages/office/src", root: [] },
+ { src: "packages/import/src", root: [] },
+ { src: "packages/import-contract/src", root: ["index.ts", "full.ts"] },
{ src: "packages/images/src", root: [] },
{ src: "packages/external-agents/src", root: [] },
{ src: "packages/external-agents-contract/src", root: ["index.ts", "full.ts"] },
@@ -230,6 +232,7 @@ const capabilities = [
"routines",
"plugins",
"office",
+ "import",
"images",
"external-agents",
"credentials",
@@ -521,6 +524,7 @@ const adapterImports = new Map<string, ReadonlySet<string>>([
["@pibot/memory:brain", new Set(["@pibot/agent", "@pibot/brain"])],
["@pibot/models:brain", new Set(["@pibot/agent", "@pibot/brain"])],
["@pibot/models:ui", new Set(["@pibot/client-core", "@pibot/renderer-kit", "@pibot/ui"])],
+ ["@pibot/import:brain", new Set(["@pibot/brain"])],
["@pibot/office:brain", new Set(["@pibot/brain"])],
["@pibot/office:ui", new Set(["@pibot/renderer-kit", "@pibot/ui"])],
["@pibot/plugins:brain", new Set(["@pibot/agent", "@pibot/brain"])],
diff --git a/tsconfig.json b/tsconfig.json
index 3d78c92..0497eab 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -79,6 +79,12 @@
{
"path": "./packages/images-contract"
},
+ {
+ "path": "./packages/import"
+ },
+ {
+ "path": "./packages/import-contract"
+ },
{
"path": "./packages/link"
},