Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(plugins): let pi.session reach every session through .all grants

Tioit-Wang9385d43b1909
diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjs
index 722624d78..2a6e6fb3a 100644
--- a/apps/desktop/electron/main/plugin-host-process.mjs
+++ b/apps/desktop/electron/main/plugin-host-process.mjs
@@ -343,6 +343,13 @@ function buildApi() {
importBatch: (input) => call("session.importBatch", [input ?? {}]),
rename: (input) => call("session.rename", [input ?? {}]),
delete: (input) => call("session.delete", [input ?? {}]),
+ // Message-level writes (`session.update.all` / `session.delete.all`, ADR
+ // 0339). The plugin supplies no scope: the main-process gateway derives it
+ // from the granted permissions.
+ appendMessage: (input) => call("session.appendMessage", [input ?? {}]),
+ replaceMessages: (input) => call("session.replaceMessages", [input ?? {}]),
+ deleteMessage: (input) => call("session.deleteMessage", [input ?? {}]),
+ truncateFrom: (input) => call("session.truncateFrom", [input ?? {}]),
},
// Read-only usage facts (`usage.read`). The main-process dispatch owns
// the permission check and parameter bounds; the host returns per-turn
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index f82a55257..da553c4fa 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -16,6 +16,15 @@ import { pluginNetFetch, parseFetchRedirect, type PluginFetchTransport } from ".
import type { LoadedSkillDocument } from "./skill-document";
import { assertLocalPluginRoot, pluginFsReadOptions, readRemotePluginFiles, type PluginRemoteFilesRead } from "./plugin-remote-files";
import { getModuleDirectory } from "./module-path";
+import {
+ SESSION_WRITE_GRANTS,
+ describeSessionWriteProblem,
+ resolveSessionScope,
+ type SessionAccessScope,
+ type SessionAccessVerb,
+ type SessionWriteApi,
+ type SessionWriteShape,
+} from "./plugin-session-access";
import {
busTopicAllowed,
isDeniedFsPath,
@@ -511,6 +520,10 @@ export type PluginHostServices = {
importBatch: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
rename: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
delete: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
+ appendMessage: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
+ replaceMessages: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
+ deleteMessage: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
+ truncateFrom: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
};
/**
* The session the user is looking at, as the shell shows it. Read from the
@@ -647,6 +660,10 @@ const HOST_API_ALLOWLIST = new Set([
"session.importBatch",
"session.rename",
"session.delete",
+ "session.appendMessage",
+ "session.replaceMessages",
+ "session.deleteMessage",
+ "session.truncateFrom",
"usage.listTurns",
"agent.complete",
"providers.oauth.prompt",
@@ -1060,6 +1077,25 @@ function normalizePluginSessionInput(
return { ...(input as Record<string, unknown>) };
}
+/**
+ * Bound one message-level write payload (ADR 0339).
+ *
+ * The policy lives in `plugin-session-access` so it can be tested without a
+ * plugin host; this wrapper only turns a problem into the broker's own error and
+ * strips a scope the plugin must never set for itself.
+ */
+function normalizePluginMessageWriteInput(
+ input: unknown,
+ shape: SessionWriteShape,
+): Record<string, unknown> {
+ const rejected = describeSessionWriteProblem(input, shape);
+ if (rejected) throw apiError(rejected.code, rejected.message);
+ const record = { ...(input as Record<string, unknown>) };
+ // A plugin never chooses its own scope: the gateway sets it from the grants.
+ delete record.scope;
+ return record;
+}
+
/** Longest session or turn id a plugin may name, matching the host's own bound. */
const MAX_SESSION_ID_CHARS = 128;
@@ -3230,45 +3266,84 @@ export class PluginRuntime {
return this.services.providerOAuthNotify(pluginId, loginId, event as PluginProviderOAuthEvent);
}
case "session.list": {
- this.assertPermission(loaded, "session.read.own");
+ const scope = this.assertSessionScope(loaded, "read", api);
const input = normalizePluginSessionInput(args[0] ?? {}, "other");
- if (input.source !== undefined) this.sessionSource(loaded, input.source);
+ // A declared source only bounds the `.own` importer; `.all` reaches every
+ // session but has no source declaration to check it against.
+ if (scope === "own" && input.source !== undefined) {
+ this.sessionSource(loaded, input.source);
+ }
if (!this.services.session?.list) {
throw apiError("UNSUPPORTED", "host api not available: session.list");
}
- return this.services.session.list(loaded.manifest.id, input);
+ return this.services.session.list(loaded.manifest.id, { ...input, scope });
}
case "session.get": {
- this.assertPermission(loaded, "session.read.own");
+ const scope = this.assertSessionScope(loaded, "read", api);
const input = normalizePluginSessionInput(args[0] ?? {}, "other");
if (!this.services.session?.get) {
throw apiError("UNSUPPORTED", "host api not available: session.get");
}
- return this.services.session.get(loaded.manifest.id, input);
+ return this.services.session.get(loaded.manifest.id, { ...input, scope });
}
case "session.listMessages": {
- this.assertPermission(loaded, "session.read.own");
+ const scope = this.assertSessionScope(loaded, "read", api);
const input = normalizePluginSessionInput(args[0] ?? {}, "other");
if (!this.services.session?.listMessages) {
throw apiError("UNSUPPORTED", "host api not available: session.listMessages");
}
- return this.services.session.listMessages(loaded.manifest.id, input);
+ return this.services.session.listMessages(loaded.manifest.id, { ...input, scope });
}
case "session.rename": {
- this.assertPermission(loaded, "session.update.own");
+ const scope = this.assertSessionScope(loaded, "update", api);
const input = normalizePluginSessionInput(args[0] ?? {}, "other");
if (!this.services.session?.rename) {
throw apiError("UNSUPPORTED", "host api not available: session.rename");
}
- return this.services.session.rename(loaded.manifest.id, input);
+ return this.services.session.rename(loaded.manifest.id, { ...input, scope });
}
case "session.delete": {
- this.assertPermission(loaded, "session.delete.own");
+ const scope = this.assertSessionScope(loaded, "delete", api);
const input = normalizePluginSessionInput(args[0] ?? {}, "other");
if (!this.services.session?.delete) {
throw apiError("UNSUPPORTED", "host api not available: session.delete");
}
- return this.services.session.delete(loaded.manifest.id, input);
+ return this.services.session.delete(loaded.manifest.id, { ...input, scope });
+ }
+ // Message-level writes (ADR 0339). These have no `.own` form: rewriting a
+ // transcript is only ever an `.all` capability, so each case names its
+ // grant directly.
+ case "session.appendMessage": {
+ const scope = this.assertSessionWriteScope(loaded, "appendMessage", api);
+ const input = normalizePluginMessageWriteInput(args[0] ?? {}, "message");
+ if (!this.services.session?.appendMessage) {
+ throw apiError("UNSUPPORTED", "host api not available: session.appendMessage");
+ }
+ return this.services.session.appendMessage(loaded.manifest.id, { ...input, scope });
+ }
+ case "session.replaceMessages": {
+ const scope = this.assertSessionWriteScope(loaded, "replaceMessages", api);
+ const input = normalizePluginMessageWriteInput(args[0] ?? {}, "messages");
+ if (!this.services.session?.replaceMessages) {
+ throw apiError("UNSUPPORTED", "host api not available: session.replaceMessages");
+ }
+ return this.services.session.replaceMessages(loaded.manifest.id, { ...input, scope });
+ }
+ case "session.deleteMessage": {
+ const scope = this.assertSessionWriteScope(loaded, "deleteMessage", api);
+ const input = normalizePluginMessageWriteInput(args[0] ?? {}, "messageId");
+ if (!this.services.session?.deleteMessage) {
+ throw apiError("UNSUPPORTED", "host api not available: session.deleteMessage");
+ }
+ return this.services.session.deleteMessage(loaded.manifest.id, { ...input, scope });
+ }
+ case "session.truncateFrom": {
+ const scope = this.assertSessionWriteScope(loaded, "truncateFrom", api);
+ const input = normalizePluginMessageWriteInput(args[0] ?? {}, "truncate");
+ if (!this.services.session?.truncateFrom) {
+ throw apiError("UNSUPPORTED", "host api not available: session.truncateFrom");
+ }
+ return this.services.session.truncateFrom(loaded.manifest.id, { ...input, scope });
}
case "usage.listTurns": {
// Read-only completed-turn facts (spec 07-plugins/03 §usage): flat
@@ -4919,6 +4994,66 @@ export class PluginRuntime {
}
}
+ /**
+ * Resolve and audit the session-data scope for one call (ADR 0339).
+ *
+ * `*.all` is a separate grant from `*.own`, never a widening of it, and it
+ * wins when a manifest declares both. The audit line records the scope that
+ * actually authorised the call, which is what lets an operator tell an
+ * imported-session read from a read of the user's own conversation.
+ */
+ private assertSessionScope(
+ loaded: LoadedPlugin,
+ verb: SessionAccessVerb,
+ api: string,
+ ): SessionAccessScope {
+ this.toolInvocations.current(loaded);
+ const scope = resolveSessionScope(loaded.permissions, verb);
+ if (!scope) {
+ const own = `session.${verb}.own`;
+ const all = `session.${verb}.all`;
+ this.services.audit?.({
+ pluginId: loaded.manifest.id,
+ api,
+ ok: false,
+ errorCode: "PERMISSION_DENIED",
+ required: `${own}|${all}`,
+ ts: Date.now(),
+ });
+ throw apiError("PERMISSION_DENIED", `missing permission: ${own} or ${all}`);
+ }
+ this.auditSessionCall(loaded, api, scope);
+ return scope;
+ }
+
+ /**
+ * Message-level writes have no `.own` form, so the grant is named exactly.
+ * `key` picks the grant from the one policy table in `plugin-session-access`.
+ */
+ private assertSessionWriteScope(
+ loaded: LoadedPlugin,
+ key: SessionWriteApi,
+ api: string,
+ ): SessionAccessScope {
+ this.assertPermission(loaded, SESSION_WRITE_GRANTS[key]);
+ this.auditSessionCall(loaded, api, "all");
+ return "all";
+ }
+
+ private auditSessionCall(
+ loaded: LoadedPlugin,
+ api: string,
+ scope: "own" | "all",
+ ): void {
+ this.services.audit?.({
+ pluginId: loaded.manifest.id,
+ api,
+ ok: true,
+ scope,
+ ts: Date.now(),
+ });
+ }
+
private assertHasOAuthProvider(loaded: LoadedPlugin): void {
const providers = (loaded.manifest.contributes?.providers ?? []) as PluginProviderContrib[];
if (!providers.some((provider) => provider.authKind === "oauth")) {
diff --git a/apps/desktop/electron/main/plugin-session-access.ts b/apps/desktop/electron/main/plugin-session-access.ts
new file mode 100644
index 000000000..e8c71c09d
--- /dev/null
+++ b/apps/desktop/electron/main/plugin-session-access.ts
@@ -0,0 +1,148 @@
+/**
+ * Session-access policy for the plugin broker (ADR 0339).
+ *
+ * Keeping it here — as pure functions over a granted-permission set and a raw
+ * request payload — is deliberate: the `.all` family is the widest grant the
+ * plugin platform can hand out, and the decision "which sessions may this call
+ * touch" is worth testing without standing up a plugin process, a host RPC
+ * channel, or Electron.
+ */
+
+/** The three session verbs that have both an `.own` and an `.all` grant. */
+export const SESSION_ACCESS_VERBS = ["read", "update", "delete"] as const;
+
+export type SessionAccessVerb = (typeof SESSION_ACCESS_VERBS)[number];
+
+/** The scope a call may address, or `null` when the plugin holds neither grant. */
+export type SessionAccessScope = "own" | "all";
+
+/**
+ * Resolve the scope one granted-permission set buys for a session verb.
+ *
+ * `.all` is a separate grant, never a widening of `.own`, and it wins when a
+ * manifest declares both: a plugin that asked for the whole directory does not
+ * get a narrower answer because it also kept the old one.
+ */
+export function resolveSessionScope(
+ permissions: ReadonlySet<string>,
+ verb: SessionAccessVerb,
+): SessionAccessScope | null {
+ if (permissions.has(`session.${verb}.all`)) return "all";
+ if (permissions.has(`session.${verb}.own`)) return "own";
+ return null;
+}
+
+/**
+ * The grant each message-level write needs. These have no `.own` form: writing
+ * into a transcript is only ever an `.all` capability.
+ */
+export const SESSION_WRITE_GRANTS = {
+ appendMessage: "session.update.all",
+ replaceMessages: "session.update.all",
+ deleteMessage: "session.delete.all",
+ truncateFrom: "session.delete.all",
+} as const satisfies Record<string, string>;
+
+export type SessionWriteApi = keyof typeof SESSION_WRITE_GRANTS;
+
+/** Which part of one write payload a caller is shaping. */
+export type SessionWriteShape = "message" | "messages" | "messageId" | "truncate";
+
+/** A rejected payload, in the shape the plugin broker turns into `apiError`. */
+export type SessionAccessProblem = { code: string; message: string };
+
+/** Host ceilings, restated here so a plugin gets a typed error before dispatch. */
+export const MAX_SESSION_ID_CHARS = 128;
+export const MAX_MUTATION_MESSAGES = 2_000;
+export const MAX_MUTATION_CONTENT_BYTES = 512 * 1024;
+const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
+
+/**
+ * Bound one message-level write payload.
+ *
+ * Returns `null` when the payload is acceptable and the problem otherwise, so
+ * the caller keeps ownership of how the failure is raised and audited. The host
+ * re-checks every rule here; this copy exists so a payload is refused before it
+ * crosses the RPC boundary, not after.
+ */
+export function describeSessionWriteProblem(
+ input: unknown,
+ shape: SessionWriteShape,
+): SessionAccessProblem | null {
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
+ return problem("input must be an object");
+ }
+ const record = input as Record<string, unknown>;
+ const sessionId = record.sessionId;
+ if (
+ typeof sessionId !== "string" ||
+ !sessionId.trim() ||
+ sessionId.length > MAX_SESSION_ID_CHARS
+ ) {
+ return problem("sessionId must be a non-empty string");
+ }
+ switch (shape) {
+ case "message":
+ return describeMessagesProblem([record.message], "message");
+ case "messages":
+ return describeMessagesProblem(record.messages, "messages");
+ case "messageId":
+ return typeof record.messageId === "string" && record.messageId.trim()
+ ? null
+ : problem("messageId must be a non-empty string");
+ default: {
+ const { fromMessageId, keepCount } = record;
+ if (fromMessageId !== undefined && typeof fromMessageId !== "string") {
+ return problem("fromMessageId must be a string");
+ }
+ if (
+ keepCount !== undefined &&
+ (typeof keepCount !== "number" || !Number.isInteger(keepCount) || keepCount < 0)
+ ) {
+ return problem("keepCount must be a non-negative integer");
+ }
+ return fromMessageId === undefined && keepCount === undefined
+ ? problem("fromMessageId or keepCount is required")
+ : null;
+ }
+ }
+}
+
+function problem(message: string, code = "INVALID_PARAMS"): SessionAccessProblem {
+ return { code, message };
+}
+
+function describeMessagesProblem(value: unknown, field: string): SessionAccessProblem | null {
+ if (!Array.isArray(value)) return problem(`${field} must be an array`);
+ if (value.length > MAX_MUTATION_MESSAGES) {
+ return problem(
+ `${field} must contain at most ${MAX_MUTATION_MESSAGES} entries`,
+ "LIMIT_EXCEEDED",
+ );
+ }
+ for (const entry of value) {
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
+ return problem(`${field} entries must be objects`);
+ }
+ const row = entry as Record<string, unknown>;
+ if (!["user", "assistant", "tool"].includes(String(row.role))) {
+ return problem(`${field} role is invalid`);
+ }
+ if (typeof row.content !== "string") {
+ return problem(`${field} content must be a string`);
+ }
+ if (Buffer.byteLength(row.content, "utf8") > MAX_MUTATION_CONTENT_BYTES) {
+ return problem(`${field} content exceeds 512 KiB`, "LIMIT_EXCEEDED");
+ }
+ if (typeof row.createdAt !== "string" || !RFC3339.test(row.createdAt)) {
+ return problem(`${field} createdAt must be RFC3339`);
+ }
+ if (
+ row.id !== undefined &&
+ (typeof row.id !== "string" || !row.id.trim() || row.id.length > MAX_SESSION_ID_CHARS)
+ ) {
+ return problem(`${field} id must be a non-empty string`);
+ }
+ }
+ return null;
+}
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 2d94c6c56..5e78660eb 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -160,19 +160,28 @@ export function createPluginServices({
throw Object.assign(new Error("host unavailable"), { code: "UNSUPPORTED" });
}
const result = await getHost()!.call(method, { ...input, pluginId });
+ const body = (result ?? {}) as Record<string, unknown>;
const changed =
- (method === "plugin.session.import" &&
- (result as { imported?: unknown })?.imported === true) ||
- (method === "plugin.session.importBatch" &&
- Number((result as { imported?: unknown })?.imported ?? 0) > 0) ||
- (method === "plugin.session.rename" &&
- (result as { updated?: unknown })?.updated === true) ||
- (method === "plugin.session.setAutoTitle" &&
- (result as { updated?: unknown })?.updated === true) ||
- (method === "plugin.session.delete" &&
- (result as { deleted?: unknown })?.deleted === true);
+ (method === "plugin.session.import" && body.imported === true) ||
+ (method === "plugin.session.importBatch" && Number(body.imported ?? 0) > 0) ||
+ (method === "plugin.session.rename" && body.updated === true) ||
+ (method === "plugin.session.setAutoTitle" && body.updated === true) ||
+ (method === "plugin.session.delete" && body.deleted === true) ||
+ // Message-level writes (ADR 0339) also change what the user sees in the
+ // open transcript, so they announce themselves like the session writes.
+ (method === "plugin.session.appendMessage" && typeof body.messageId === "string") ||
+ (method === "plugin.session.replaceMessages" && typeof body.messageCount === "number") ||
+ (method === "plugin.session.deleteMessage" && typeof body.deletedCount === "number") ||
+ (method === "plugin.session.truncateFrom" && typeof body.keptCount === "number");
if (changed) {
- sendToRenderer(IPC.event.sessionsChanged, { reason: method, pluginId });
+ // `sessionId` scopes the refresh to the session that actually changed, so
+ // the shell can repaint an open transcript without re-selecting it.
+ const sessionId = typeof input.sessionId === "string" ? input.sessionId : undefined;
+ sendToRenderer(IPC.event.sessionsChanged, {
+ reason: method,
+ pluginId,
+ ...(sessionId ? { sessionId } : {}),
+ });
}
return result;
};
@@ -396,6 +405,14 @@ export function createPluginServices({
callPluginSessionHost("plugin.session.importBatch", pluginId, input),
rename: (pluginId, input) => callPluginSessionHost("plugin.session.rename", pluginId, input),
delete: (pluginId, input) => callPluginSessionHost("plugin.session.delete", pluginId, input),
+ appendMessage: (pluginId, input) =>
+ callPluginSessionHost("plugin.session.appendMessage", pluginId, input),
+ replaceMessages: (pluginId, input) =>
+ callPluginSessionHost("plugin.session.replaceMessages", pluginId, input),
+ deleteMessage: (pluginId, input) =>
+ callPluginSessionHost("plugin.session.deleteMessage", pluginId, input),
+ truncateFrom: (pluginId, input) =>
+ callPluginSessionHost("plugin.session.truncateFrom", pluginId, input),
},
project: {
create: (pluginId, input) => callPluginProjectHost(pluginId, input),
diff --git a/apps/desktop/resources/skills/plugin-development.md b/apps/desktop/resources/skills/plugin-development.md
index 5e36eb066..3648a6cc9 100644
--- a/apps/desktop/resources/skills/plugin-development.md
+++ b/apps/desktop/resources/skills/plugin-development.md
@@ -181,6 +181,12 @@ when working in the host repository. Major gates include:
skill catalogs/bodies; `agent.complete` for quota-spending one-shot completions.
- `models.list`, `usage.read`, `session.read`, and the separate ownership-scoped
`session.import`, `session.read.own`, `session.update.own`, `session.delete.own`.
+ `session.read.all`, `session.update.all`, and `session.delete.all` are the
+ wider family: they carry the same verbs over every live session, including the
+ conversations the user created in this app, and they are what
+ `pi.session.appendMessage` / `replaceMessages` / `deleteMessage` /
+ `truncateFrom` require. Declaring both a `.own` and a `.all` grant behaves as
+ `.all`; the user approves the wider name at install.
- `provider.register` for manifest providers, `provider.oauth` for OAuth callbacks,
`composer.transform` for draft transformations, `composer.suggest` for one
dismissible placeholder line; these do not implicitly grant transcript reads.
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index 236fc447d..30fe74dfc 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -813,6 +813,17 @@ export function useAppShellRuntime() {
}
if (event.selectSessionId) {
await useAppStore.getState().selectSession(event.selectSessionId);
+ } else if (event.sessionId) {
+ // A plugin message write named the session it changed. The sidebar
+ // refresh above cannot repaint an open transcript, so re-read it —
+ // but only when the user is looking at it and no turn owns it.
+ const current = useAppStore.getState();
+ if (
+ current.activeSessionId === event.sessionId &&
+ current.runningSessions[event.sessionId] !== true
+ ) {
+ await current.selectSession(event.sessionId, { record: false });
+ }
}
})
.catch(() => undefined);
diff --git a/apps/desktop/src/features/plugins/model.ts b/apps/desktop/src/features/plugins/model.ts
index 644cc4353..7239ca557 100644
--- a/apps/desktop/src/features/plugins/model.ts
+++ b/apps/desktop/src/features/plugins/model.ts
@@ -58,6 +58,11 @@ export const PERMISSION_RISK: Record<string, RiskTier> = {
"session.autoTitle": "high",
"session.import": "high",
"session.delete.own": "high",
+ // The `.all` family reaches the user's own conversations, so every verb sits
+ // at the top tier the matrix gives the imported-only delete (ADR 0339).
+ "session.read.all": "high",
+ "session.update.all": "high",
+ "session.delete.all": "high",
"browser.cdp": "high",
// Reading is a tier below writing because what makes a read dangerous is
// where the data can go, and outbound requests are declared separately.
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index cb003fc31..8bf3eab31 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -2081,6 +2081,11 @@ export const api = {
pluginId?: string;
projectPath?: string | null;
selectSessionId?: string;
+ /**
+ * The one session whose transcript changed. A plugin message write names
+ * it so the shell can repaint an already open transcript (ADR 0339).
+ */
+ sessionId?: string;
}) => void,
) => {
if (!window.piDesktop?.on) return () => undefined;
@@ -2091,6 +2096,7 @@ export const api = {
pluginId?: string;
projectPath?: string | null;
selectSessionId?: string;
+ sessionId?: string;
},
),
);
diff --git a/apps/desktop/test/plugin-session-access.test.mjs b/apps/desktop/test/plugin-session-access.test.mjs
new file mode 100644
index 000000000..6661eca30
--- /dev/null
+++ b/apps/desktop/test/plugin-session-access.test.mjs
@@ -0,0 +1,163 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+const {
+ MAX_MUTATION_MESSAGES,
+ SESSION_WRITE_GRANTS,
+ describeSessionWriteProblem,
+ resolveSessionScope,
+} = await import("../electron/main/plugin-session-access.ts");
+
+const granted = (...names) => new Set(names);
+const message = (overrides = {}) => ({
+ role: "user",
+ content: "hello",
+ createdAt: "2026-01-01T00:00:01Z",
+ ...overrides,
+});
+
+test("a session verb needs its own grant and .all wins over .own", () => {
+ assert.equal(resolveSessionScope(granted(), "read"), null);
+ assert.equal(resolveSessionScope(granted("session.read.own"), "read"), "own");
+ assert.equal(resolveSessionScope(granted("session.read.all"), "read"), "all");
+ // Declaring both never narrows the answer, and never widens `.own` by accident.
+ assert.equal(
+ resolveSessionScope(granted("session.read.own", "session.read.all"), "read"),
+ "all",
+ );
+});
+
+test("one verb's grant never lends reach to another", () => {
+ const permissions = granted("session.read.all");
+ assert.equal(resolveSessionScope(permissions, "read"), "all");
+ assert.equal(resolveSessionScope(permissions, "update"), null);
+ assert.equal(resolveSessionScope(permissions, "delete"), null);
+ // `session.autoTitle` is the narrow title path and implies no session scope.
+ assert.equal(resolveSessionScope(granted("session.autoTitle"), "read"), null);
+});
+
+test("message-level writes name their grant and have no .own form", () => {
+ assert.deepEqual(SESSION_WRITE_GRANTS, {
+ appendMessage: "session.update.all",
+ replaceMessages: "session.update.all",
+ deleteMessage: "session.delete.all",
+ truncateFrom: "session.delete.all",
+ });
+ assert.equal(resolveSessionScope(granted("session.update.own"), "update"), "own");
+ // `.own` never satisfies a message write: the gateway asks for the exact name.
+ assert.ok(!Object.values(SESSION_WRITE_GRANTS).includes("session.update.own"));
+});
+
+test("an acceptable message-level payload passes every shape", () => {
+ assert.equal(
+ describeSessionWriteProblem(
+ { sessionId: "s1", message: message({ id: "m1" }) },
+ "message",
+ ),
+ null,
+ );
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", messages: [message()] }, "messages"),
+ null,
+ );
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", messageId: "m1" }, "messageId"),
+ null,
+ );
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", keepCount: 0 }, "truncate"),
+ null,
+ );
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", fromMessageId: "m2" }, "truncate"),
+ null,
+ );
+});
+
+test("the session id is required before anything else is considered", () => {
+ for (const sessionId of [undefined, null, "", " ", 7, "x".repeat(129)]) {
+ const problem = describeSessionWriteProblem({ sessionId, messageId: "m1" }, "messageId");
+ assert.equal(problem?.code, "INVALID_PARAMS");
+ assert.match(problem?.message ?? "", /sessionId/);
+ }
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1" }, "messageId")?.code,
+ "INVALID_PARAMS",
+ );
+});
+
+test("message rows are bounded like the importer bounds them", () => {
+ assert.equal(
+ describeSessionWriteProblem(
+ { sessionId: "s1", message: message({ role: "system" }) },
+ "message",
+ )?.code,
+ "INVALID_PARAMS",
+ );
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", message: message({ content: 7 }) }, "message")
+ ?.code,
+ "INVALID_PARAMS",
+ );
+ assert.equal(
+ describeSessionWriteProblem(
+ { sessionId: "s1", message: message({ content: "x".repeat(512 * 1024 + 1) }) },
+ "message",
+ )?.code,
+ "LIMIT_EXCEEDED",
+ );
+ assert.equal(
+ describeSessionWriteProblem(
+ { sessionId: "s1", message: message({ createdAt: "yesterday" }) },
+ "message",
+ )?.code,
+ "INVALID_PARAMS",
+ );
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", message: message({ id: "" }) }, "message")
+ ?.code,
+ "INVALID_PARAMS",
+ );
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", message: undefined }, "message")?.code,
+ "INVALID_PARAMS",
+ );
+});
+
+test("a message array is capped at the host ceiling", () => {
+ const tooMany = Array.from({ length: MAX_MUTATION_MESSAGES + 1 }, () => message());
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", messages: tooMany }, "messages")?.code,
+ "LIMIT_EXCEEDED",
+ );
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", messages: "nope" }, "messages")?.message,
+ "messages must be an array",
+ );
+});
+
+test("truncate needs exactly one bound and a sane count", () => {
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1" }, "truncate")?.message,
+ "fromMessageId or keepCount is required",
+ );
+ for (const keepCount of [-1, 1.5, "3", null]) {
+ const problem = describeSessionWriteProblem({ sessionId: "s1", keepCount }, "truncate");
+ if (keepCount === null) {
+ // `null` is not a bound either: the field is absent or an integer.
+ assert.equal(problem?.message, "keepCount must be a non-negative integer");
+ } else {
+ assert.equal(problem?.message, "keepCount must be a non-negative integer");
+ }
+ }
+ assert.equal(
+ describeSessionWriteProblem({ sessionId: "s1", fromMessageId: 5 }, "truncate")?.message,
+ "fromMessageId must be a string",
+ );
+});
diff --git a/apps/desktop/test/plugin-session-api.test.mjs b/apps/desktop/test/plugin-session-api.test.mjs
index c08257bf1..236e8bbc7 100644
--- a/apps/desktop/test/plugin-session-api.test.mjs
+++ b/apps/desktop/test/plugin-session-api.test.mjs
@@ -106,7 +106,7 @@ test("plugin session API enforces own permissions and declared sources", async (
assert.equal(calls[0][0], "import");
assert.equal(calls[0][1], "demo.session");
assert.equal(calls[0][2].sourceLabel, "legacy");
- assert.deepEqual(calls[1], ["list", "demo.session", { source: "legacy" }]);
+ assert.deepEqual(calls[1], ["list", "demo.session", { source: "legacy", scope: "own" }]);
assert.match(runtime.drainToasts().at(-1) ?? "", /source:PERMISSION_DENIED/);
});
@@ -525,3 +525,260 @@ test("plugin usage listTurns is refused without the usage.read permission", asyn
assert.deepEqual(calls, []);
assert.deepEqual(runtime.drainToasts(), ["listTurns:PERMISSION_DENIED"]);
});
+
+test("session .all grants reach the host as scope all while .own stays own", async (t) => {
+ const calls = [];
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ session: {
+ get: async (pluginId, input) => {
+ calls.push([pluginId, input]);
+ return { sessionId: "s1" };
+ },
+ },
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+ const main = `
+ module.exports = {
+ async onLoad() {
+ await pi.commands.register({
+ id: "read",
+ title: "Read",
+ run: async () => { await pi.session.get({ sessionId: "s1" }); }
+ });
+ }
+ };
+ `;
+ const own = writePlugin({ id: "demo.own", permissions: ["session.read.own"], main });
+ await runtime.loadFromPath(own, ["session.read.own"]);
+ await runCommand(runtime, "read");
+ await runtime.unload("demo.own");
+
+ // Declaring both never widens `.own` by accident: `.all` simply wins.
+ const both = writePlugin({
+ id: "demo.both",
+ permissions: ["session.read.own", "session.read.all"],
+ main,
+ });
+ await runtime.loadFromPath(both, ["session.read.own", "session.read.all"]);
+ await runCommand(runtime, "read");
+
+ assert.deepEqual(calls, [
+ ["demo.own", { sessionId: "s1", scope: "own" }],
+ ["demo.both", { sessionId: "s1", scope: "all" }],
+ ]);
+});
+
+test("a plugin cannot choose its own session scope", async (t) => {
+ const calls = [];
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ session: {
+ get: async (pluginId, input) => {
+ calls.push([pluginId, input]);
+ return { sessionId: "s1" };
+ },
+ },
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+ const dir = writePlugin({
+ id: "demo.smuggle",
+ permissions: ["session.read.own"],
+ main: `
+ module.exports = {
+ async onLoad() {
+ await pi.commands.register({
+ id: "smuggle",
+ title: "Smuggle",
+ run: async () => { await pi.session.get({ sessionId: "s1", scope: "all" }); }
+ });
+ }
+ };
+ `,
+ });
+ await runtime.loadFromPath(dir, ["session.read.own"]);
+ await runCommand(runtime, "smuggle");
+ assert.deepEqual(calls, [["demo.smuggle", { sessionId: "s1", scope: "own" }]]);
+});
+
+test("message-level writes need an .all grant and forward the host scope", async (t) => {
+ const calls = [];
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ session: {
+ appendMessage: async (pluginId, input) => {
+ calls.push(["append", pluginId, input]);
+ return { messageId: "m1" };
+ },
+ replaceMessages: async (pluginId, input) => {
+ calls.push(["replace", pluginId, input]);
+ return { messageCount: 1 };
+ },
+ deleteMessage: async (pluginId, input) => {
+ calls.push(["delete", pluginId, input]);
+ return { deleted: true, deletedCount: 1 };
+ },
+ truncateFrom: async (pluginId, input) => {
+ calls.push(["truncate", pluginId, input]);
+ return { keptCount: 0, discardedCount: 1 };
+ },
+ },
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+ const dir = writePlugin({
+ id: "demo.message-writer",
+ permissions: ["session.update.all", "session.delete.all"],
+ main: `
+ const message = { role: "user", content: "hi", createdAt: "2026-01-01T00:00:01Z" };
+ module.exports = {
+ async onLoad() {
+ await pi.commands.register({
+ id: "write",
+ title: "Write",
+ run: async () => {
+ await pi.session.appendMessage({ sessionId: "s1", message });
+ await pi.session.replaceMessages({ sessionId: "s1", messages: [message] });
+ await pi.session.deleteMessage({ sessionId: "s1", messageId: "m1" });
+ await pi.session.truncateFrom({ sessionId: "s1", keepCount: 0 });
+ // A retained scope field is dropped, never forwarded.
+ await pi.session.appendMessage({ sessionId: "s1", scope: "own", message });
+ }
+ });
+ }
+ };
+ `,
+ });
+ await runtime.loadFromPath(dir, ["session.update.all", "session.delete.all"]);
+ await runCommand(runtime, "write");
+
+ const message = { role: "user", content: "hi", createdAt: "2026-01-01T00:00:01Z" };
+ assert.deepEqual(calls, [
+ ["append", "demo.message-writer", { sessionId: "s1", message, scope: "all" }],
+ ["replace", "demo.message-writer", { sessionId: "s1", messages: [message], scope: "all" }],
+ ["delete", "demo.message-writer", { sessionId: "s1", messageId: "m1", scope: "all" }],
+ ["truncate", "demo.message-writer", { sessionId: "s1", keepCount: 0, scope: "all" }],
+ ["append", "demo.message-writer", { sessionId: "s1", message, scope: "all" }],
+ ]);
+});
+
+test("message-level writes are refused without an .all grant", async (t) => {
+ const calls = [];
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ session: {
+ appendMessage: async () => calls.push("append"),
+ replaceMessages: async () => calls.push("replace"),
+ deleteMessage: async () => calls.push("delete"),
+ truncateFrom: async () => calls.push("truncate"),
+ },
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+ const dir = writePlugin({
+ id: "demo.reader",
+ permissions: ["session.read.own"],
+ main: `
+ const message = { role: "user", content: "hi", createdAt: "2026-01-01T00:00:01Z" };
+ module.exports = {
+ async onLoad() {
+ await pi.commands.register({
+ id: "try-write",
+ title: "Try write",
+ run: async () => {
+ for (const [name, call] of [
+ ["append", () => pi.session.appendMessage({ sessionId: "s1", message })],
+ ["replace", () => pi.session.replaceMessages({ sessionId: "s1", messages: [message] })],
+ ["delete", () => pi.session.deleteMessage({ sessionId: "s1", messageId: "m1" })],
+ ["truncate", () => pi.session.truncateFrom({ sessionId: "s1", keepCount: 0 })]
+ ]) {
+ try { await call(); }
+ catch (error) { await pi.ui.showToast(name + ":" + error.code); }
+ }
+ }
+ });
+ }
+ };
+ `,
+ });
+ await runtime.loadFromPath(dir, ["session.read.own"]);
+ await runCommand(runtime, "try-write");
+ assert.deepEqual(calls, []);
+ assert.deepEqual(runtime.drainToasts(), [
+ "append:PERMISSION_DENIED",
+ "replace:PERMISSION_DENIED",
+ "delete:PERMISSION_DENIED",
+ "truncate:PERMISSION_DENIED",
+ ]);
+});
+
+test("message-level write bounds are rejected before host dispatch", async (t) => {
+ const calls = [];
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ session: {
+ appendMessage: async (pluginId, input) => {
+ calls.push(["append", pluginId, input]);
+ return { messageId: "m1" };
+ },
+ truncateFrom: async (pluginId, input) => {
+ calls.push(["truncate", pluginId, input]);
+ return { keptCount: 0, discardedCount: 0 };
+ },
+ },
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+ const dir = writePlugin({
+ id: "demo.bounds",
+ permissions: ["session.update.all", "session.delete.all"],
+ main: `
+ const ok = { role: "user", content: "hi", createdAt: "2026-01-01T00:00:01Z" };
+ module.exports = {
+ async onLoad() {
+ await pi.commands.register({
+ id: "bounds",
+ title: "Bounds",
+ run: async () => {
+ const cases = [
+ ["role", () => pi.session.appendMessage({ sessionId: "s1", message: { ...ok, role: "system" } })],
+ ["content", () => pi.session.appendMessage({ sessionId: "s1", message: { ...ok, content: "x".repeat(512 * 1024 + 1) } })],
+ ["time", () => pi.session.appendMessage({ sessionId: "s1", message: { ...ok, createdAt: "yesterday" } })],
+ ["count", () => pi.session.replaceMessages({ sessionId: "s1", messages: Array.from({ length: 2001 }, () => ok) })],
+ ["truncate", () => pi.session.truncateFrom({ sessionId: "s1" })],
+ ["session", () => pi.session.appendMessage({ sessionId: "", message: ok })]
+ ];
+ for (const [name, call] of cases) {
+ try { await call(); }
+ catch (error) { await pi.ui.showToast(name + ":" + error.code); }
+ }
+ }
+ });
+ }
+ };
+ `,
+ });
+ await runtime.loadFromPath(dir, ["session.update.all", "session.delete.all"]);
+ await runCommand(runtime, "bounds");
+ assert.deepEqual(calls, []);
+ assert.deepEqual(runtime.drainToasts(), [
+ "role:INVALID_PARAMS",
+ "content:LIMIT_EXCEEDED",
+ "time:INVALID_PARAMS",
+ "count:LIMIT_EXCEEDED",
+ "truncate:INVALID_PARAMS",
+ "session:INVALID_PARAMS",
+ ]);
+});
diff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rs
index 27ce49108..00d8e1ebe 100644
--- a/crates/host-core/src/plugin_sessions.rs
+++ b/crates/host-core/src/plugin_sessions.rs
@@ -1,13 +1,16 @@
//! Host-owned P0/P1 session API for plugins.
//!
-//! This module deliberately does not reuse the renderer's session RPCs. Every
-//! query is scoped by the `(plugin_id, source_id, external_id)` origin sidecar,
-//! and imported sessions do not acquire project/provider bindings unless an
+//! This module deliberately does not reuse the renderer's session RPCs. A call
+//! is either scoped to the `(plugin_id, source_id, external_id)` origin sidecar
+//! (`SessionScope::Own`, the ADR 0200 boundary) or — for a plugin holding a
+//! `*.all` grant — to every live session (`SessionScope::All`, ADR 0339).
+//! Imported sessions do not acquire project/provider bindings unless an
//! explicit host-created project id is supplied.
use anyhow::{anyhow, Result};
use chrono::DateTime;
-use rusqlite::{params, OptionalExtension};
+use rusqlite::types::Value as SqlValue;
+use rusqlite::{params, params_from_iter, OptionalExtension};
use serde::Deserialize;
use serde_json::{json, Map, Value};
use std::collections::{HashMap, HashSet};
@@ -34,6 +37,51 @@ pub const MAX_MESSAGE_LIMIT: usize = 500;
pub const DEFAULT_CONTENT_LIMIT: usize = 64_000;
pub const MAX_CONTENT_LIMIT: usize = 512_000;
+/// Which sessions one `pi.session` call may address.
+///
+/// Electron main resolves the scope from the plugin's granted permissions and
+/// sends the literal `scope` parameter; host-core holds no permission data of
+/// its own (ADR 0200), so it enforces exactly the scope it is handed. An absent
+/// parameter means [`SessionScope::Own`], which keeps any caller that predates
+/// ADR 0339 on the original ownership boundary.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionScope {
+ /// Only sessions imported by the calling plugin (ADR 0200).
+ Own,
+ /// Every live session, imported or user-created (ADR 0339).
+ All,
+}
+
+impl SessionScope {
+ /// Read `scope` from an RPC payload. Unknown values are rejected rather than
+ /// coerced, so a typo can never widen access.
+ pub fn from_params(params_value: &Value) -> Result<Self> {
+ match params_value.get("scope") {
+ None | Some(Value::Null) => Ok(SessionScope::Own),
+ Some(Value::String(value)) if value == "own" => Ok(SessionScope::Own),
+ Some(Value::String(value)) if value == "all" => Ok(SessionScope::All),
+ Some(_) => Err(invalid("scope must be \"own\" or \"all\"")),
+ }
+ }
+
+ fn owns_only(self) -> bool {
+ self == SessionScope::Own
+ }
+}
+
+/// `originKind` of a session, from whether an import origin row exists.
+fn origin_kind(imported: bool) -> &'static str {
+ if imported {
+ "imported"
+ } else {
+ "created"
+ }
+}
+
+/// `source` of a session. A user-created session carries no import source, so it
+/// reports `desktop` instead of an empty string.
+const SESSION_SOURCE_EXPR: &str = "COALESCE(NULLIF(s.source, ''), 'desktop')";
+
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PluginMessageInput {
@@ -764,27 +812,37 @@ fn history_from_json(raw: Option<String>) -> Value {
.unwrap_or_else(|| json!({ "projectPath": null, "modelId": null, "providerId": null }))
}
+/// The `sessionId` every addressing call carries, bounded like a turn id.
+fn session_id_param(params_value: &Value) -> Result<String> {
+ required_text(
+ params_value
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .unwrap_or_default(),
+ "sessionId",
+ 128,
+ )
+}
+
struct SessionViewParams {
session_id: String,
title: String,
source: String,
- external_id: String,
+ external_id: Option<String>,
project_id: Option<i64>,
message_count: i64,
created_at: i64,
updated_at: i64,
+ imported: bool,
+ model_id: Option<String>,
+ provider_id: Option<String>,
}
-type OwnedSessionRow = (
- String,
- String,
- String,
- i64,
- i64,
- i64,
- Option<i64>,
- Option<String>,
-);
+/// A conversation is model-bound only when the session row carries both halves
+/// of the binding; an imported session has neither.
+fn model_bound(provider_id: &Option<String>, model_id: &Option<String>) -> bool {
+ provider_id.is_some() && model_id.is_some()
+}
fn session_view(params: SessionViewParams) -> Value {
let SessionViewParams {
@@ -796,6 +854,9 @@ fn session_view(params: SessionViewParams) -> Value {
message_count,
created_at,
updated_at,
+ imported,
+ model_id,
+ provider_id,
} = params;
json!({
"sessionId": session_id,
@@ -804,14 +865,22 @@ fn session_view(params: SessionViewParams) -> Value {
"externalId": external_id,
"projectId": project_id,
"messageCount": message_count,
- "originKind": "imported",
- "bound": { "workspace": project_id.is_some(), "model": false },
+ "originKind": origin_kind(imported),
+ "bound": {
+ "workspace": project_id.is_some(),
+ "model": model_bound(&provider_id, &model_id),
+ },
"createdAt": ms_to_ts(created_at),
"updatedAt": ms_to_ts(updated_at),
})
}
-pub fn list(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Value> {
+pub fn list(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
validate_payload(params_value)?;
let page_limit = match params_value.get("limit") {
None => DEFAULT_LIST_LIMIT,
@@ -839,61 +908,50 @@ pub fn list(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Valu
.and_then(Value::as_str)
.map(|value| strict_timestamp(value, "updatedAfter").map(|(_, ms)| ms))
.transpose()?;
- let mut sql = String::from(
- "SELECT s.id, s.title, s.source, oi.external_id, s.project_id, s.last_seq,
- s.created_at, s.updated_at
+ // The origin sidecar is LEFT-joined so an `All` caller also sees sessions
+ // that no plugin imported. Each predicate is pushed together with its bind,
+ // which keeps the positional `?` numbering correct for every combination.
+ let mut binds: Vec<SqlValue> = Vec::new();
+ let mut sql = format!(
+ "SELECT s.id, s.title, {SESSION_SOURCE_EXPR}, oi.external_id, s.project_id,
+ s.last_seq, s.created_at, s.updated_at, oi.session_id,
+ s.model_id, s.provider_id
FROM sessions s
- JOIN session_import_origins oi ON oi.session_id = s.id
- WHERE oi.plugin_id = ?1 AND s.deleted_at IS NULL",
+ LEFT JOIN session_import_origins oi ON oi.session_id = s.id
+ WHERE s.deleted_at IS NULL"
);
- if source.is_some() {
- sql.push_str(" AND oi.source_id = ?2");
- }
- if updated_after.is_some() {
- sql.push_str(if source.is_some() {
- " AND s.updated_at > ?3"
- } else {
- " AND s.updated_at > ?2"
- });
+ if scope.owns_only() {
+ sql.push_str(" AND oi.plugin_id = ?");
+ binds.push(SqlValue::Text(plugin_id.to_string()));
}
- sql.push_str(if source.is_some() && updated_after.is_some() {
- " ORDER BY s.updated_at DESC, s.id DESC LIMIT ?4 OFFSET ?5"
- } else if source.is_some() || updated_after.is_some() {
- " ORDER BY s.updated_at DESC, s.id DESC LIMIT ?3 OFFSET ?4"
- } else {
- " ORDER BY s.updated_at DESC, s.id DESC LIMIT ?2 OFFSET ?3"
- });
+ if let Some(source) = source {
+ sql.push_str(&format!(" AND {SESSION_SOURCE_EXPR} = ?"));
+ binds.push(SqlValue::Text(source));
+ }
+ if let Some(updated_after) = updated_after {
+ sql.push_str(" AND s.updated_at > ?");
+ binds.push(SqlValue::Integer(updated_after));
+ }
+ sql.push_str(" ORDER BY s.updated_at DESC, s.id DESC LIMIT ? OFFSET ?");
+ binds.push(SqlValue::Integer(page_limit as i64));
+ binds.push(SqlValue::Integer(offset as i64));
let mut stmt = db.conn().prepare(&sql)?;
- let mut rows = match (source, updated_after) {
- (Some(source), Some(updated_after)) => stmt.query(params![
- plugin_id,
- source,
- updated_after,
- page_limit as i64,
- offset as i64
- ])?,
- (Some(source), None) => {
- stmt.query(params![plugin_id, source, page_limit as i64, offset as i64])?
- }
- (None, Some(updated_after)) => stmt.query(params![
- plugin_id,
- updated_after,
- page_limit as i64,
- offset as i64
- ])?,
- (None, None) => stmt.query(params![plugin_id, page_limit as i64, offset as i64])?,
- };
+ let mut rows = stmt.query(params_from_iter(binds))?;
let mut items = Vec::new();
while let Some(row) = rows.next()? {
+ let origin_session_id: Option<String> = row.get(8)?;
items.push(session_view(SessionViewParams {
session_id: row.get(0)?,
title: row.get(1)?,
- source: row.get::<_, Option<String>>(2)?.unwrap_or_default(),
+ source: row.get(2)?,
external_id: row.get(3)?,
project_id: row.get(4)?,
message_count: row.get(5)?,
created_at: row.get(6)?,
updated_at: row.get(7)?,
+ imported: origin_session_id.is_some(),
+ model_id: row.get(9)?,
+ provider_id: row.get(10)?,
}));
}
let next_cursor = (items.len() == page_limit).then(|| (offset + items.len()).to_string());
@@ -905,33 +963,101 @@ pub fn list(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Valu
Ok(Value::Object(response))
}
-fn own_session_row(
+/// One session as the plugin surface sees it, resolved under a scope.
+struct PluginSessionRow {
+ title: String,
+ source: String,
+ external_id: Option<String>,
+ message_count: i64,
+ created_at: i64,
+ updated_at: i64,
+ project_id: Option<i64>,
+ origin_json: Option<String>,
+ imported: bool,
+ model_id: Option<String>,
+ provider_id: Option<String>,
+}
+
+fn session_row(
db: &Database,
plugin_id: &str,
session_id: &str,
-) -> Result<Option<OwnedSessionRow>> {
- Ok(db
+ scope: SessionScope,
+) -> Result<Option<PluginSessionRow>> {
+ // `?1` is bound in both variants: SQLite numbers positional parameters by
+ // the highest index used, so the `All` statement keeps an unused hole while
+ // both share one bind list.
+ let mut sql = format!(
+ "SELECT s.title, {SESSION_SOURCE_EXPR}, oi.external_id,
+ s.last_seq, s.created_at, s.updated_at, s.project_id, oi.origin_json,
+ oi.session_id, s.model_id, s.provider_id
+ FROM sessions s
+ LEFT JOIN session_import_origins oi ON oi.session_id = s.id
+ WHERE s.id = ?2 AND s.deleted_at IS NULL"
+ );
+ if scope.owns_only() {
+ sql.push_str(" AND oi.plugin_id = ?1");
+ }
+ let row = db
.conn()
- .prepare_cached(
- "SELECT s.title, s.source, oi.external_id, s.last_seq,
- s.created_at, s.updated_at, s.project_id, oi.origin_json
- FROM sessions s
- JOIN session_import_origins oi ON oi.session_id = s.id
- WHERE oi.plugin_id = ?1 AND s.id = ?2 AND s.deleted_at IS NULL",
- )?
+ .prepare_cached(&sql)?
.query_row(params![plugin_id, session_id], |row| {
Ok((
- row.get(0)?,
- row.get(1)?,
- row.get(2)?,
- row.get(3)?,
- row.get(4)?,
- row.get(5)?,
- row.get(6)?,
- row.get(7)?,
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, Option<String>>(2)?,
+ row.get::<_, i64>(3)?,
+ row.get::<_, i64>(4)?,
+ row.get::<_, i64>(5)?,
+ row.get::<_, Option<i64>>(6)?,
+ row.get::<_, Option<String>>(7)?,
+ row.get::<_, Option<String>>(8)?,
+ row.get::<_, Option<String>>(9)?,
+ row.get::<_, Option<String>>(10)?,
))
})
- .optional()?)
+ .optional()?;
+ Ok(row.map(
+ |(
+ title,
+ source,
+ external_id,
+ message_count,
+ created_at,
+ updated_at,
+ project_id,
+ origin_json,
+ origin_session_id,
+ model_id,
+ provider_id,
+ )| PluginSessionRow {
+ title,
+ source,
+ external_id,
+ message_count,
+ created_at,
+ updated_at,
+ project_id,
+ origin_json,
+ imported: origin_session_id.is_some(),
+ model_id,
+ provider_id,
+ },
+ ))
+}
+
+/// Assert that a live (not trashed) session is addressable under `scope`.
+fn require_session(
+ db: &Database,
+ plugin_id: &str,
+ session_id: &str,
+ scope: SessionScope,
+) -> Result<()> {
+ if session_row(db, plugin_id, session_id, scope)?.is_some() {
+ Ok(())
+ } else {
+ Err(not_found("session not found"))
+ }
}
fn owns_session(db: &Database, plugin_id: &str, session_id: &str) -> Result<bool> {
@@ -947,49 +1073,58 @@ fn owns_session(db: &Database, plugin_id: &str, session_id: &str) -> Result<bool
.query_row(params![plugin_id, session_id], |row| row.get(0))?)
}
-pub fn get(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Value> {
+/// Existence check for the delete path, which must still see a trashed row:
+/// `trash` then `purge` is the documented lifecycle of the same session.
+fn deletable_session(
+ db: &Database,
+ plugin_id: &str,
+ session_id: &str,
+ scope: SessionScope,
+) -> Result<bool> {
+ if scope.owns_only() {
+ return owns_session(db, plugin_id, session_id);
+ }
+ Ok(db
+ .conn()
+ .prepare_cached("SELECT EXISTS(SELECT 1 FROM sessions WHERE id = ?1)")?
+ .query_row(params![session_id], |row| row.get(0))?)
+}
+
+pub fn get(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
validate_payload(params_value)?;
- let session_id = required_text(
- params_value
- .get("sessionId")
- .and_then(Value::as_str)
- .unwrap_or_default(),
- "sessionId",
- 128,
- )?;
- let Some((
- title,
- source,
- external_id,
- message_count,
- created_at,
- updated_at,
- project_id,
- origin_json,
- )) = own_session_row(db, plugin_id, &session_id)?
- else {
+ let session_id = session_id_param(params_value)?;
+ let Some(row) = session_row(db, plugin_id, &session_id, scope)? else {
return Err(not_found("session not found"));
};
- let project_path = project_id
+ let project_path = row
+ .project_id
.map(|id| db.project_path(id))
.transpose()?
.flatten();
- let history = history_from_json(origin_json);
+ let history = history_from_json(row.origin_json);
Ok(json!({
"sessionId": session_id,
- "title": title,
- "source": source,
- "externalId": external_id,
- "originKind": "imported",
- "projectId": project_id,
+ "title": row.title,
+ "source": row.source,
+ "externalId": row.external_id,
+ "originKind": origin_kind(row.imported),
+ "projectId": row.project_id,
"projectPath": project_path,
- "modelId": Value::Null,
- "providerId": Value::Null,
- "bound": { "workspace": project_id.is_some(), "model": false },
+ "modelId": row.model_id,
+ "providerId": row.provider_id,
+ "bound": {
+ "workspace": row.project_id.is_some(),
+ "model": model_bound(&row.provider_id, &row.model_id),
+ },
"history": history,
- "messageCount": message_count,
- "createdAt": ms_to_ts(created_at),
- "updatedAt": ms_to_ts(updated_at),
+ "messageCount": row.message_count,
+ "createdAt": ms_to_ts(row.created_at),
+ "updatedAt": ms_to_ts(row.updated_at),
}))
}
@@ -1000,7 +1135,7 @@ fn truncate_chars(value: &str, limit: usize) -> (String, bool) {
(result, truncated)
}
-fn plugin_message(record: MessageRecord, content_limit: usize) -> Value {
+fn plugin_message(record: MessageRecord, content_limit: usize, imported: bool) -> Value {
let message = sessions::record_to_ui(record);
let (content, content_truncated) = truncate_chars(&message.content, content_limit);
let mut result = json!({
@@ -1008,7 +1143,7 @@ fn plugin_message(record: MessageRecord, content_limit: usize) -> Value {
"role": message.role,
"content": content,
"createdAt": message.created_at,
- "origin": "external",
+ "origin": if imported { "external" } else { "desktop" },
});
if content_truncated {
result["contentTruncated"] = Value::Bool(true);
@@ -1025,19 +1160,17 @@ fn plugin_message(record: MessageRecord, content_limit: usize) -> Value {
result
}
-pub fn list_messages(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Value> {
+pub fn list_messages(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
validate_payload(params_value)?;
- let session_id = required_text(
- params_value
- .get("sessionId")
- .and_then(Value::as_str)
- .unwrap_or_default(),
- "sessionId",
- 128,
- )?;
- if own_session_row(db, plugin_id, &session_id)?.is_none() {
+ let session_id = session_id_param(params_value)?;
+ let Some(row) = session_row(db, plugin_id, &session_id, scope)? else {
return Err(not_found("session not found"));
- }
+ };
let page_limit = match params_value.get("limit") {
None => DEFAULT_MESSAGE_LIMIT,
Some(value) => value
@@ -1081,7 +1214,7 @@ pub fn list_messages(db: &Database, plugin_id: &str, params_value: &Value) -> Re
records[offset..end]
.iter()
.cloned()
- .map(|record| plugin_message(record, content_limit))
+ .map(|record| plugin_message(record, content_limit, row.imported))
.collect::<Vec<_>>()
};
let next_cursor = (end < records.len()).then(|| end.to_string());
@@ -1093,16 +1226,14 @@ pub fn list_messages(db: &Database, plugin_id: &str, params_value: &Value) -> Re
Ok(Value::Object(response))
}
-pub fn rename(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Value> {
+pub fn rename(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
validate_payload(params_value)?;
- let session_id = required_text(
- params_value
- .get("sessionId")
- .and_then(Value::as_str)
- .unwrap_or_default(),
- "sessionId",
- 128,
- )?;
+ let session_id = session_id_param(params_value)?;
let title = required_text(
params_value
.get("title")
@@ -1111,13 +1242,17 @@ pub fn rename(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Va
"title",
MAX_TITLE_CHARS,
)?;
- if own_session_row(db, plugin_id, &session_id)?.is_none() {
- return Err(not_found("session not found"));
- }
- db.conn().execute(
- "UPDATE sessions SET title = ?1 WHERE id = ?2 AND deleted_at IS NULL",
+ require_session(db, plugin_id, &session_id, scope)?;
+ // Claiming the manual title source is what stops the auto-title plugin from
+ // later replacing a title a plugin — and therefore the user — chose.
+ let changed = db.conn().execute(
+ "UPDATE sessions SET title = ?1, title_source = 'manual'
+ WHERE id = ?2 AND deleted_at IS NULL",
params![title, session_id],
)?;
+ if changed == 0 {
+ return Err(not_found("session not found"));
+ }
Ok(json!({ "updated": true }))
}
@@ -1177,16 +1312,14 @@ pub fn set_auto_title(db: &Database, plugin_id: &str, params_value: &Value) -> R
Ok(json!({ "updated": updated }))
}
-pub fn delete(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Value> {
+pub fn delete(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
validate_payload(params_value)?;
- let session_id = required_text(
- params_value
- .get("sessionId")
- .and_then(Value::as_str)
- .unwrap_or_default(),
- "sessionId",
- 128,
- )?;
+ let session_id = session_id_param(params_value)?;
let mode = params_value
.get("mode")
.and_then(Value::as_str)
@@ -1194,40 +1327,251 @@ pub fn delete(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Va
if !matches!(mode, "trash" | "purge") {
return Err(invalid("mode must be trash or purge"));
}
- if !owns_session(db, plugin_id, &session_id)? {
+ // A trashed row is still addressable: trash then purge is the documented
+ // lifecycle of the same session.
+ if !deletable_session(db, plugin_id, &session_id, scope)? {
return Err(not_found("session not found"));
}
- if mode == "purge" {
- let changed = db.conn().execute(
- "DELETE FROM sessions WHERE id = ?1 AND EXISTS (
- SELECT 1 FROM session_import_origins
- WHERE session_id = ?1 AND plugin_id = ?2
- )",
- params![session_id, plugin_id],
- )?;
- if changed == 0 {
- return Err(not_found("session not found"));
+ // The ownership predicate is the scope's job; the statement must not embed a
+ // second copy of it or an `All` delete would match zero rows.
+ let changed = if mode == "purge" {
+ match scope {
+ SessionScope::Own => db.conn().execute(
+ "DELETE FROM sessions WHERE id = ?1 AND EXISTS (
+ SELECT 1 FROM session_import_origins
+ WHERE session_id = ?1 AND plugin_id = ?2
+ )",
+ params![session_id, plugin_id],
+ )?,
+ SessionScope::All => db
+ .conn()
+ .execute("DELETE FROM sessions WHERE id = ?1", params![session_id])?,
}
- transcripts::remove_session_files(db.data_dir(), &session_id);
} else {
- db.conn().execute(
- "UPDATE sessions SET deleted_at = ?1
- WHERE id = ?2 AND EXISTS (
- SELECT 1 FROM session_import_origins
- WHERE session_id = ?2 AND plugin_id = ?3
- )",
- params![now_ms(), session_id, plugin_id],
- )?;
+ match scope {
+ SessionScope::Own => db.conn().execute(
+ "UPDATE sessions SET deleted_at = ?1
+ WHERE id = ?2 AND EXISTS (
+ SELECT 1 FROM session_import_origins
+ WHERE session_id = ?2 AND plugin_id = ?3
+ )",
+ params![now_ms(), session_id, plugin_id],
+ )?,
+ SessionScope::All => db.conn().execute(
+ "UPDATE sessions SET deleted_at = ?1 WHERE id = ?2",
+ params![now_ms(), session_id],
+ )?,
+ }
+ };
+ if changed == 0 {
+ return Err(not_found("session not found"));
+ }
+ if mode == "purge" {
+ transcripts::remove_session_files(db.data_dir(), &session_id);
}
Ok(json!({ "deleted": true }))
}
+// ---------------------------------------------------------------------------
+// Message-level writes (`session.update.all` / `session.delete.all`, ADR 0339)
+// ---------------------------------------------------------------------------
+
+/// One message a plugin writes. Same shape as a `session.import` message, plus
+/// an optional `id`: host-core still generates the id when the plugin omits it,
+/// but a caller that supplies one gets retry-safe idempotency.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct PluginMutationMessageInput {
+ id: Option<String>,
+ role: String,
+ content: String,
+ created_at: String,
+ model_id: Option<String>,
+ provider_id: Option<String>,
+ tool_name: Option<String>,
+ tool_call_id: Option<String>,
+ tool_status: Option<String>,
+ tool_args: Option<Value>,
+ tool_result: Option<Value>,
+}
+
+impl PluginMutationMessageInput {
+ fn as_import_input(&self) -> PluginMessageInput {
+ PluginMessageInput {
+ role: self.role.clone(),
+ content: self.content.clone(),
+ created_at: self.created_at.clone(),
+ model_id: self.model_id.clone(),
+ provider_id: self.provider_id.clone(),
+ tool_name: self.tool_name.clone(),
+ tool_call_id: self.tool_call_id.clone(),
+ tool_status: self.tool_status.clone(),
+ tool_args: self.tool_args.clone(),
+ tool_result: self.tool_result.clone(),
+ }
+ }
+}
+
+/// Validate a plugin-written message batch with the same rules `session.import`
+/// applies, so a mutation can never store a row the importer would reject.
+fn parse_mutations(items: &[Value]) -> Result<Vec<UiMessage>> {
+ if items.len() > MAX_IMPORT_MESSAGES {
+ return Err(limit(format!(
+ "messages must contain at most {MAX_IMPORT_MESSAGES} entries"
+ )));
+ }
+ let mut previous_ms = None;
+ let mut tool_call_map = HashMap::new();
+ let mut messages = Vec::with_capacity(items.len());
+ for item in items {
+ let input: PluginMutationMessageInput = serde_json::from_value(item.clone())
+ .map_err(|error| invalid(format!("invalid message: {error}")))?;
+ let mut message = parse_message(
+ &input.as_import_input(),
+ &mut previous_ms,
+ &mut tool_call_map,
+ )?;
+ if let Some(id) = input.id.as_deref() {
+ message.id = required_text(id, "message.id", 128)?;
+ }
+ messages.push(message);
+ }
+ Ok(messages)
+}
+
+/// A transcript rewrite must not race the turn that is writing it. `appendMessage`
+/// is deliberately exempt: appending is how a turn's own rows land.
+fn refuse_running_turn(db: &Database, session_id: &str) -> Result<()> {
+ if sessions::running_turn(db, session_id)? {
+ return Err(code_error(
+ "TURN_RUNNING",
+ "cannot rewrite a session transcript during a running turn",
+ ));
+ }
+ Ok(())
+}
+
+fn mutation_messages(params_value: &Value) -> Result<Vec<UiMessage>> {
+ let items = params_value
+ .get("messages")
+ .and_then(Value::as_array)
+ .ok_or_else(|| invalid("messages must be an array"))?;
+ parse_mutations(items)
+}
+
+/// Append one message to any session the caller can address.
+pub fn append_message(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
+ validate_payload(params_value)?;
+ let session_id = session_id_param(params_value)?;
+ require_session(db, plugin_id, &session_id, scope)?;
+ let raw = params_value
+ .get("message")
+ .ok_or_else(|| invalid("message required"))?;
+ let mut messages = parse_mutations(std::slice::from_ref(raw))?;
+ let message = messages.pop().ok_or_else(|| invalid("message required"))?;
+ sessions::append_message(db, &session_id, &message, None)?;
+ Ok(json!({ "messageId": message.id }))
+}
+
+/// Replace the whole live transcript with the supplied messages.
+pub fn replace_messages(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
+ validate_payload(params_value)?;
+ let session_id = session_id_param(params_value)?;
+ require_session(db, plugin_id, &session_id, scope)?;
+ refuse_running_turn(db, &session_id)?;
+ let messages = mutation_messages(params_value)?;
+ sessions::replace_messages(db, &session_id, &messages)?;
+ Ok(json!({ "messageCount": messages.len() }))
+}
+
+/// Delete one message, or — when it is a user prompt — the prompt and its
+/// replies. A missing target is a successful no-op, matching the renderer path.
+pub fn delete_message(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
+ validate_payload(params_value)?;
+ let session_id = session_id_param(params_value)?;
+ require_session(db, plugin_id, &session_id, scope)?;
+ let message_id = required_text(
+ params_value
+ .get("messageId")
+ .and_then(Value::as_str)
+ .unwrap_or_default(),
+ "messageId",
+ 128,
+ )?;
+ refuse_running_turn(db, &session_id)?;
+ let result = sessions::delete_message(db, &session_id, &message_id)?;
+ Ok(json!({
+ "deleted": result.deleted,
+ "deletedCount": result.deleted_count,
+ }))
+}
+
+/// Keep the prefix before `fromMessageId` (or the first `keepCount` messages)
+/// and discard the rest. No transcript snapshot crosses the process boundary.
+pub fn truncate_from(
+ db: &Database,
+ plugin_id: &str,
+ scope: SessionScope,
+ params_value: &Value,
+) -> Result<Value> {
+ validate_payload(params_value)?;
+ let session_id = session_id_param(params_value)?;
+ require_session(db, plugin_id, &session_id, scope)?;
+ let from_message_id = params_value
+ .get("fromMessageId")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|id| !id.is_empty());
+ let keep_count = match params_value.get("keepCount") {
+ None | Some(Value::Null) => None,
+ Some(value) => Some(
+ value
+ .as_i64()
+ .ok_or_else(|| invalid("keepCount must be a number"))?,
+ ),
+ };
+ if from_message_id.is_none() && keep_count.is_none() {
+ return Err(invalid("fromMessageId or keepCount required"));
+ }
+ refuse_running_turn(db, &session_id)?;
+ let result = sessions::truncate_from(db, &session_id, from_message_id, keep_count)?;
+ Ok(json!({
+ "keptCount": result.kept_count,
+ "discardedCount": result.discarded_count,
+ }))
+}
+
#[cfg(test)]
mod tests {
use super::*;
use crate::db::Database;
use tempfile::tempdir;
+ /// The ADR 0200 boundary: only sessions this plugin imported.
+ fn own() -> SessionScope {
+ SessionScope::Own
+ }
+
+ /// The ADR 0339 boundary: every live session, imported or user-created.
+ fn all() -> SessionScope {
+ SessionScope::All
+ }
+
fn db() -> (tempfile::TempDir, Database) {
let dir = tempdir().unwrap();
let db = Database::open_in_dir(dir.path()).unwrap();
@@ -1269,6 +1613,48 @@ mod tests {
sessions::append_message(db, session_id, &message, None).unwrap();
}
+ fn import_owned(db: &Database, plugin_id: &str, external_id: &str) -> String {
+ let mut input = item(external_id, "2026-01-01T00:00:01Z");
+ input["source"] = json!("legacy");
+ import(db, plugin_id, &input).unwrap()["sessionId"]
+ .as_str()
+ .unwrap()
+ .to_string()
+ }
+
+ /// A user-created, model-bound conversation: exactly the shape the ADR 0200
+ /// ownership filter could never reach.
+ fn user_session(db: &Database) -> String {
+ sessions::create_session_with_options(
+ db,
+ sessions::SessionCreateOptions {
+ provider_id: Some("provider".into()),
+ model_id: Some("model".into()),
+ ..Default::default()
+ },
+ )
+ .unwrap()
+ .id
+ }
+
+ fn message(role: &str, content: &str, second: u8) -> Value {
+ json!({
+ "role": role,
+ "content": content,
+ "createdAt": format!("2026-01-01T00:00:{second:02}Z")
+ })
+ }
+
+ fn run_turn(db: &Database, session_id: &str) {
+ db.conn()
+ .execute(
+ "INSERT INTO turns (id, session_id, status, started_at)
+ VALUES ('turn-1', ?1, 'running', ?2)",
+ params![session_id, now_ms()],
+ )
+ .unwrap();
+ }
+
#[test]
fn import_is_host_owned_idempotent_and_keeps_history_unbound() {
let (_dir, db) = db();
@@ -1292,7 +1678,7 @@ mod tests {
let second = import(&db, "plugin.one", &request).unwrap();
assert_eq!(second["sessionId"], id);
assert_eq!(second["skipped"], true);
- let detail = get(&db, "plugin.one", &json!({ "sessionId": id })).unwrap();
+ let detail = get(&db, "plugin.one", own(), &json!({ "sessionId": id })).unwrap();
assert_eq!(detail["projectPath"], Value::Null);
assert_eq!(detail["modelId"], Value::Null);
assert_eq!(detail["history"]["projectPath"], "/history/project");
@@ -1310,12 +1696,18 @@ mod tests {
let result = import(&db, "plugin.one", &input).unwrap();
let session_id = result["sessionId"].as_str().unwrap();
- let detail = get(&db, "plugin.one", &json!({ "sessionId": session_id })).unwrap();
+ let detail = get(
+ &db,
+ "plugin.one",
+ own(),
+ &json!({ "sessionId": session_id }),
+ )
+ .unwrap();
assert_eq!(detail["projectId"], project_id);
assert_eq!(detail["projectPath"], "/history/project");
assert_eq!(detail["bound"]["workspace"], true);
- let listed = list(&db, "plugin.one", &json!({})).unwrap();
+ let listed = list(&db, "plugin.one", own(), &json!({})).unwrap();
assert_eq!(listed["items"][0]["projectId"], project_id);
assert_eq!(listed["items"][0]["bound"]["workspace"], true);
@@ -1328,8 +1720,13 @@ mod tests {
)
.unwrap();
let batch_session_id = batch["results"][0]["sessionId"].as_str().unwrap();
- let batch_detail =
- get(&db, "plugin.one", &json!({ "sessionId": batch_session_id })).unwrap();
+ let batch_detail = get(
+ &db,
+ "plugin.one",
+ own(),
+ &json!({ "sessionId": batch_session_id }),
+ )
+ .unwrap();
assert_eq!(batch_detail["projectId"], project_id);
assert_eq!(batch_detail["bound"]["workspace"], true);
}
@@ -1404,10 +1801,11 @@ mod tests {
.as_str()
.unwrap()
.to_string();
- assert!(get(&db, "plugin.two", &json!({ "sessionId": id })).is_err());
+ assert!(get(&db, "plugin.two", own(), &json!({ "sessionId": id })).is_err());
assert!(delete(
&db,
"plugin.one",
+ own(),
&json!({ "sessionId": id, "mode": "purge" })
)
.is_ok());
@@ -1419,33 +1817,30 @@ mod tests {
#[test]
fn list_rename_trash_and_purge_follow_plugin_ownership() {
let (_dir, db) = db();
- let mut input = item("lifecycle", "2026-01-01T00:00:01Z");
- input["source"] = json!("legacy");
- let id = import(&db, "plugin.one", &input).unwrap()["sessionId"]
- .as_str()
- .unwrap()
- .to_string();
+ let id = import_owned(&db, "plugin.one", "lifecycle");
- let listed = list(&db, "plugin.one", &json!({ "source": "legacy" })).unwrap();
+ let listed = list(&db, "plugin.one", own(), &json!({ "source": "legacy" })).unwrap();
assert_eq!(listed["items"].as_array().unwrap().len(), 1);
assert_eq!(
- list(&db, "plugin.two", &json!({})).unwrap()["items"],
+ list(&db, "plugin.two", own(), &json!({})).unwrap()["items"],
json!([])
);
rename(
&db,
"plugin.one",
+ own(),
&json!({ "sessionId": id, "title": "Renamed" }),
)
.unwrap();
assert_eq!(
- get(&db, "plugin.one", &json!({ "sessionId": id })).unwrap()["title"],
+ get(&db, "plugin.one", own(), &json!({ "sessionId": id })).unwrap()["title"],
"Renamed"
);
assert!(rename(
&db,
"plugin.two",
+ own(),
&json!({ "sessionId": id, "title": "Nope" }),
)
.unwrap_err()
@@ -1455,24 +1850,25 @@ mod tests {
delete(
&db,
"plugin.one",
+ own(),
&json!({ "sessionId": id, "mode": "trash" }),
)
.unwrap();
- assert!(list(&db, "plugin.one", &json!({})).unwrap()["items"]
+ assert!(list(&db, "plugin.one", own(), &json!({})).unwrap()["items"]
.as_array()
.unwrap()
.is_empty());
- assert!(get(&db, "plugin.one", &json!({ "sessionId": id })).is_err());
+ assert!(get(&db, "plugin.one", own(), &json!({ "sessionId": id })).is_err());
delete(
&db,
"plugin.one",
+ own(),
&json!({ "sessionId": id, "mode": "purge" }),
)
.unwrap();
- let reimported = import(&db, "plugin.one", &input).unwrap();
- assert_eq!(reimported["imported"], true);
- assert_ne!(reimported["sessionId"], id);
+ let reimported = import_owned(&db, "plugin.one", "lifecycle");
+ assert_ne!(reimported, id);
}
#[test]
@@ -1546,7 +1942,8 @@ mod tests {
}]);
input["source"] = json!("legacy");
let id = import(&db, "plugin.one", &input).unwrap()["sessionId"].clone();
- let messages = list_messages(&db, "plugin.one", &json!({ "sessionId": id })).unwrap();
+ let messages =
+ list_messages(&db, "plugin.one", own(), &json!({ "sessionId": id })).unwrap();
assert_eq!(
messages["items"][0]["tool"]["args"],
json!({ "keep": true })
@@ -1577,6 +1974,7 @@ mod tests {
let page = list_messages(
&db,
"plugin.one",
+ own(),
&json!({
"sessionId": id,
"limit": 1,
@@ -1588,4 +1986,387 @@ mod tests {
assert_eq!(page["items"][0]["contentTruncated"], true);
assert_eq!(page["nextCursor"], "1");
}
+
+ #[test]
+ fn scope_parameter_defaults_to_own_and_rejects_unknown_values() {
+ assert_eq!(SessionScope::from_params(&json!({})).unwrap(), own());
+ assert_eq!(
+ SessionScope::from_params(&json!({ "scope": "own" })).unwrap(),
+ own()
+ );
+ assert_eq!(
+ SessionScope::from_params(&json!({ "scope": "all" })).unwrap(),
+ all()
+ );
+ assert!(SessionScope::from_params(&json!({ "scope": "everything" }))
+ .unwrap_err()
+ .to_string()
+ .starts_with("INVALID_PARAMS"));
+ assert!(SessionScope::from_params(&json!({ "scope": true }))
+ .unwrap_err()
+ .to_string()
+ .starts_with("INVALID_PARAMS"));
+ }
+
+ #[test]
+ fn own_scope_stays_blind_to_a_user_created_session() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ append_text_message(&db, &id, "u1", "user", "hi", 1);
+
+ assert_eq!(
+ list(&db, "plugin.one", own(), &json!({})).unwrap()["items"],
+ json!([])
+ );
+ assert!(get(&db, "plugin.one", own(), &json!({ "sessionId": id }))
+ .unwrap_err()
+ .to_string()
+ .starts_with("NOT_FOUND"));
+ assert!(list_messages(&db, "plugin.one", own(), &json!({ "sessionId": id })).is_err());
+ assert!(rename(
+ &db,
+ "plugin.one",
+ own(),
+ &json!({ "sessionId": id, "title": "Nope" }),
+ )
+ .is_err());
+ assert!(delete(
+ &db,
+ "plugin.one",
+ own(),
+ &json!({ "sessionId": id, "mode": "purge" }),
+ )
+ .is_err());
+ // The refusal is a property of the scope, not of the write: the row and
+ // its title survive every rejected call above.
+ assert_eq!(
+ db.conn()
+ .query_row(
+ "SELECT title FROM sessions WHERE id = ?1",
+ params![id],
+ |row| row.get::<_, String>(0)
+ )
+ .unwrap(),
+ "New task"
+ );
+ assert_eq!(
+ db.conn()
+ .query_row("SELECT COUNT(*) FROM sessions", [], |row| row
+ .get::<_, i64>(0))
+ .unwrap(),
+ 1
+ );
+ }
+
+ #[test]
+ fn all_scope_reads_a_user_created_session_with_its_real_metadata() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ append_text_message(&db, &id, "u1", "user", "hi", 1);
+ append_text_message(&db, &id, "a1", "assistant", "hello", 2);
+
+ let detail = get(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ assert_eq!(detail["originKind"], "created");
+ assert_eq!(detail["source"], "desktop");
+ assert_eq!(detail["externalId"], Value::Null);
+ assert_eq!(detail["modelId"], "model");
+ assert_eq!(detail["providerId"], "provider");
+ assert_eq!(detail["bound"]["model"], true);
+ assert_eq!(detail["messageCount"], 2);
+ // The import-time snapshot stays empty rather than inventing a binding.
+ assert_eq!(detail["history"]["modelId"], Value::Null);
+
+ let listed = list(&db, "plugin.one", all(), &json!({})).unwrap();
+ assert_eq!(listed["items"].as_array().unwrap().len(), 1);
+ assert_eq!(listed["items"][0]["originKind"], "created");
+ assert_eq!(listed["items"][0]["source"], "desktop");
+ assert_eq!(listed["items"][0]["externalId"], Value::Null);
+ assert_eq!(listed["items"][0]["bound"]["model"], true);
+
+ assert_eq!(
+ list(&db, "plugin.one", all(), &json!({ "source": "desktop" })).unwrap()["items"]
+ .as_array()
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert_eq!(
+ list(&db, "plugin.one", all(), &json!({ "source": "legacy" })).unwrap()["items"],
+ json!([])
+ );
+
+ let messages =
+ list_messages(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ assert_eq!(messages["items"][0]["origin"], "desktop");
+ assert_eq!(messages["items"][1]["content"], "hello");
+ }
+
+ #[test]
+ fn all_scope_reads_an_imported_session_as_imported() {
+ let (_dir, db) = db();
+ let id = import_owned(&db, "plugin.one", "theirs");
+ let detail = get(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ assert_eq!(detail["originKind"], "imported");
+ assert_eq!(detail["source"], "legacy");
+ assert_eq!(detail["bound"]["model"], false);
+ let messages =
+ list_messages(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ assert_eq!(messages["items"][0]["origin"], "external");
+ // A second plugin without an import grant reaches the same row through
+ // `.all`, which is the whole point of ADR 0339.
+ assert!(get(&db, "plugin.two", all(), &json!({ "sessionId": id })).is_ok());
+ }
+
+ #[test]
+ fn all_scope_renames_and_deletes_a_user_created_session() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ append_text_message(&db, &id, "u1", "user", "first prompt", 1);
+
+ rename(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "title": "Plugin named" }),
+ )
+ .unwrap();
+ assert_eq!(
+ get(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap()["title"],
+ "Plugin named"
+ );
+ // A plugin-chosen title must not be replaceable by the auto-title
+ // plugin afterwards, so the write claims the manual title source.
+ assert_eq!(
+ auto_title_context(&db, "plugin.title", &json!({ "sessionId": id })).unwrap(),
+ Value::Null
+ );
+
+ delete(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "mode": "trash" }),
+ )
+ .unwrap();
+ assert!(get(&db, "plugin.one", all(), &json!({ "sessionId": id })).is_err());
+ assert_eq!(
+ list(&db, "plugin.one", all(), &json!({})).unwrap()["items"],
+ json!([])
+ );
+
+ delete(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "mode": "purge" }),
+ )
+ .unwrap();
+ assert_eq!(
+ db.conn()
+ .query_row("SELECT COUNT(*) FROM sessions", [], |row| row
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+ }
+
+ #[test]
+ fn all_scope_append_message_is_idempotent_per_message_id() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ let request = json!({
+ "sessionId": id,
+ "message": {
+ "id": "plugin-message-1",
+ "role": "user",
+ "content": "suggested follow-up",
+ "createdAt": "2026-01-01T00:00:01Z"
+ }
+ });
+ let first = append_message(&db, "plugin.one", all(), &request).unwrap();
+ assert_eq!(first["messageId"], "plugin-message-1");
+ // A retry after a lost reply must not duplicate the row.
+ append_message(&db, "plugin.one", all(), &request).unwrap();
+ let messages =
+ list_messages(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ assert_eq!(messages["items"].as_array().unwrap().len(), 1);
+ assert_eq!(messages["items"][0]["id"], "plugin-message-1");
+ }
+
+ #[test]
+ fn all_scope_replace_messages_rewrites_the_transcript() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ append_text_message(&db, &id, "u1", "user", "one", 1);
+ append_text_message(&db, &id, "a1", "assistant", "two", 2);
+ append_text_message(&db, &id, "u2", "user", "three", 3);
+
+ let replaced = replace_messages(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({
+ "sessionId": id,
+ "messages": [message("user", "rewritten", 1), message("assistant", "reply", 2)]
+ }),
+ )
+ .unwrap();
+ assert_eq!(replaced["messageCount"], 2);
+
+ let messages =
+ list_messages(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ let contents = messages["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|item| item["content"].as_str().unwrap_or_default().to_string())
+ .collect::<Vec<_>>();
+ assert_eq!(contents, vec!["rewritten", "reply"]);
+ assert_eq!(
+ get(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap()["messageCount"],
+ 2
+ );
+ }
+
+ #[test]
+ fn all_scope_delete_message_removes_a_prompt_and_its_replies() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ append_text_message(&db, &id, "u1", "user", "keep", 1);
+ append_text_message(&db, &id, "a1", "assistant", "kept reply", 2);
+ append_text_message(&db, &id, "u2", "user", "drop", 3);
+ append_text_message(&db, &id, "a2", "assistant", "dropped reply", 4);
+
+ let deleted = delete_message(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "messageId": "u2" }),
+ )
+ .unwrap();
+ assert_eq!(deleted["deleted"], true);
+ assert_eq!(deleted["deletedCount"], 2);
+
+ let messages =
+ list_messages(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ let ids = messages["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|item| item["id"].as_str().unwrap_or_default().to_string())
+ .collect::<Vec<_>>();
+ assert_eq!(ids, vec!["u1", "a1"]);
+
+ // A missing target is a successful no-op, so a retried delete is safe.
+ let again = delete_message(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "messageId": "u2" }),
+ )
+ .unwrap();
+ assert_eq!(again["deleted"], false);
+ }
+
+ #[test]
+ fn all_scope_truncate_from_keeps_the_prefix() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ append_text_message(&db, &id, "u1", "user", "one", 1);
+ append_text_message(&db, &id, "a1", "assistant", "two", 2);
+ append_text_message(&db, &id, "u2", "user", "three", 3);
+
+ let truncated = truncate_from(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "fromMessageId": "u2" }),
+ )
+ .unwrap();
+ assert_eq!(truncated["keptCount"], 2);
+ assert_eq!(truncated["discardedCount"], 1);
+ let messages =
+ list_messages(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ assert_eq!(messages["items"].as_array().unwrap().len(), 2);
+
+ assert!(
+ truncate_from(&db, "plugin.one", all(), &json!({ "sessionId": id }))
+ .unwrap_err()
+ .to_string()
+ .starts_with("INVALID_PARAMS")
+ );
+ }
+
+ #[test]
+ fn message_writes_refuse_a_running_turn() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ append_text_message(&db, &id, "u1", "user", "one", 1);
+ run_turn(&db, &id);
+
+ for error in [
+ replace_messages(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "messages": [message("user", "x", 1)] }),
+ )
+ .unwrap_err(),
+ delete_message(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "messageId": "u1" }),
+ )
+ .unwrap_err(),
+ truncate_from(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "keepCount": 0 }),
+ )
+ .unwrap_err(),
+ ] {
+ assert!(
+ error.to_string().starts_with("TURN_RUNNING"),
+ "unexpected error: {error}"
+ );
+ }
+ // Nothing was rewritten while the turn owned the transcript.
+ let messages =
+ list_messages(&db, "plugin.one", all(), &json!({ "sessionId": id })).unwrap();
+ assert_eq!(messages["items"].as_array().unwrap().len(), 1);
+ }
+
+ #[test]
+ fn message_writes_bound_their_payload() {
+ let (_dir, db) = db();
+ let id = user_session(&db);
+ let too_many = (0..=MAX_IMPORT_MESSAGES)
+ .map(|_| message("user", "x", 1))
+ .collect::<Vec<_>>();
+ assert!(replace_messages(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({ "sessionId": id, "messages": too_many }),
+ )
+ .unwrap_err()
+ .to_string()
+ .starts_with("LIMIT_EXCEEDED"));
+
+ let huge = "x".repeat(MAX_CONTENT_BYTES + 1);
+ assert!(append_message(
+ &db,
+ "plugin.one",
+ all(),
+ &json!({
+ "sessionId": id,
+ "message": { "role": "user", "content": huge, "createdAt": "2026-01-01T00:00:01Z" }
+ }),
+ )
+ .unwrap_err()
+ .to_string()
+ .starts_with("LIMIT_EXCEEDED"));
+ }
}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 865bcf5cb..7a04a9425 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -719,14 +719,30 @@ fn plugin_session_rpc_err(error: impl ToString) -> JsonRpcError {
.unwrap_or_else(|| "INTERNAL".to_string());
let rpc_code = match code.as_str() {
"INVALID_PARAMS" | "LIMIT_EXCEEDED" => 1002,
+ "PERMISSION_DENIED" => 1003,
"NOT_FOUND" => 1007,
- "CONFLICT" => 1008,
+ "CONFLICT" | "TURN_RUNNING" => 1008,
"RATE_LIMITED" => 1006,
_ => 1000,
};
rpc_err(rpc_code, message, &code)
}
+/// Every `plugin.session.*` arm needs the calling plugin; Electron main is the
+/// only caller that can supply it (ADR 0200).
+fn plugin_session_plugin_id(params: &Value) -> Result<&str, JsonRpcError> {
+ params
+ .get("pluginId")
+ .and_then(Value::as_str)
+ .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))
+}
+
+/// The access scope Electron main resolved from the plugin's grants (ADR 0339).
+/// Host-core holds no permission data, so it enforces exactly what it is handed.
+fn plugin_session_scope(params: &Value) -> Result<plugin_sessions::SessionScope, JsonRpcError> {
+ plugin_sessions::SessionScope::from_params(params).map_err(plugin_session_rpc_err)
+}
+
/// Optional session `/fast` switch (ADR 0334). Absent or null leaves the
/// stored value; anything but a boolean is rejected rather than coerced.
fn fast_mode_param(params: &Value) -> Result<Option<bool>, JsonRpcError> {
@@ -3348,66 +3364,86 @@ async fn handle_request(
Ok(result)
}
"plugin.session.list" => {
- let plugin_id = params
- .get("pluginId")
- .and_then(Value::as_str)
- .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
+ let plugin_id = plugin_session_plugin_id(&params)?;
+ let scope = plugin_session_scope(&params)?;
let st = state.lock().await;
- plugin_sessions::list(&st.db, plugin_id, &params).map_err(plugin_session_rpc_err)
+ plugin_sessions::list(&st.db, plugin_id, scope, &params).map_err(plugin_session_rpc_err)
}
"plugin.session.get" => {
- let plugin_id = params
- .get("pluginId")
- .and_then(Value::as_str)
- .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
+ let plugin_id = plugin_session_plugin_id(&params)?;
+ let scope = plugin_session_scope(&params)?;
let st = state.lock().await;
- plugin_sessions::get(&st.db, plugin_id, &params).map_err(plugin_session_rpc_err)
+ plugin_sessions::get(&st.db, plugin_id, scope, &params).map_err(plugin_session_rpc_err)
}
"plugin.session.listMessages" => {
- let plugin_id = params
- .get("pluginId")
- .and_then(Value::as_str)
- .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
+ let plugin_id = plugin_session_plugin_id(&params)?;
+ let scope = plugin_session_scope(&params)?;
let st = state.lock().await;
- plugin_sessions::list_messages(&st.db, plugin_id, &params)
+ plugin_sessions::list_messages(&st.db, plugin_id, scope, &params)
.map_err(plugin_session_rpc_err)
}
"plugin.session.autoTitleContext" => {
- let plugin_id = params
- .get("pluginId")
- .and_then(Value::as_str)
- .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
+ let plugin_id = plugin_session_plugin_id(&params)?;
let st = state.lock().await;
plugin_sessions::auto_title_context(&st.db, plugin_id, &params)
.map_err(plugin_session_rpc_err)
}
"plugin.session.setAutoTitle" => {
- let plugin_id = params
- .get("pluginId")
- .and_then(Value::as_str)
- .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
+ let plugin_id = plugin_session_plugin_id(&params)?;
let st = state.lock().await;
plugin_sessions::set_auto_title(&st.db, plugin_id, &params)
.map_err(plugin_session_rpc_err)
}
"plugin.session.rename" => {
- let plugin_id = params
- .get("pluginId")
- .and_then(Value::as_str)
- .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
+ let plugin_id = plugin_session_plugin_id(&params)?;
+ let scope = plugin_session_scope(&params)?;
let st = state.lock().await;
- plugin_sessions::rename(&st.db, plugin_id, &params).map_err(plugin_session_rpc_err)
+ plugin_sessions::rename(&st.db, plugin_id, scope, &params)
+ .map_err(plugin_session_rpc_err)
}
"plugin.session.delete" => {
- let plugin_id = params
- .get("pluginId")
- .and_then(Value::as_str)
- .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
+ let plugin_id = plugin_session_plugin_id(&params)?;
+ let scope = plugin_session_scope(&params)?;
let mut st = state.lock().await;
+ // Ownership no longer bounds the target under `.all`, so the
+ // frequency brake is what stays (ADR 0339 §5).
if !st.allow_plugin_delete(plugin_id) {
return Err(rpc_err(1006, "plugin delete rate exceeded", "RATE_LIMITED"));
}
- plugin_sessions::delete(&st.db, plugin_id, &params).map_err(plugin_session_rpc_err)
+ plugin_sessions::delete(&st.db, plugin_id, scope, &params)
+ .map_err(plugin_session_rpc_err)
+ }
+
+ // Message-level writes (ADR 0339). Every arm charges the shared message
+ // write budget before touching a transcript, and host-core itself
+ // refuses a rewrite while a turn owns the session.
+ "plugin.session.appendMessage"
+ | "plugin.session.replaceMessages"
+ | "plugin.session.deleteMessage"
+ | "plugin.session.truncateFrom" => {
+ let plugin_id = plugin_session_plugin_id(&params)?;
+ let scope = plugin_session_scope(&params)?;
+ let mut st = state.lock().await;
+ if !st.allow_plugin_message_write(plugin_id) {
+ return Err(rpc_err(
+ 1006,
+ "plugin message write rate exceeded",
+ "RATE_LIMITED",
+ ));
+ }
+ match method {
+ "plugin.session.appendMessage" => {
+ plugin_sessions::append_message(&st.db, plugin_id, scope, &params)
+ }
+ "plugin.session.replaceMessages" => {
+ plugin_sessions::replace_messages(&st.db, plugin_id, scope, &params)
+ }
+ "plugin.session.deleteMessage" => {
+ plugin_sessions::delete_message(&st.db, plugin_id, scope, &params)
+ }
+ _ => plugin_sessions::truncate_from(&st.db, plugin_id, scope, &params),
+ }
+ .map_err(plugin_session_rpc_err)
}
// Plugin usage is a read-only facts domain: a keyset page of completed
@@ -7385,6 +7421,154 @@ mod tests {
.unwrap();
}
+ #[tokio::test]
+ async fn plugin_session_rpc_serves_all_scope_and_message_writes() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let mut app_state = AppState::open(data_dir.path()).unwrap();
+ app_state.handshook = true;
+ let state = Arc::new(Mutex::new(app_state));
+ let (tx, _rx) = mpsc::unbounded_channel();
+
+ // A user-created conversation carries no import origin row, so `.own` can
+ // never reach it and `.all` is the only path (ADR 0339).
+ let session_id = {
+ let st = state.lock().await;
+ sessions::create_session_with_options(
+ &st.db,
+ sessions::SessionCreateOptions {
+ provider_id: Some("provider".into()),
+ model_id: Some("model".into()),
+ ..Default::default()
+ },
+ )
+ .unwrap()
+ .id
+ };
+
+ // `.own` reports the row as missing, which is exactly today's behaviour.
+ let hidden = handle_request(
+ state.clone(),
+ "plugin.session.get",
+ json!({ "pluginId": "plugin.one", "sessionId": session_id }),
+ tx.clone(),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(hidden.code, 1007);
+
+ let detail = handle_request(
+ state.clone(),
+ "plugin.session.get",
+ json!({ "pluginId": "plugin.one", "scope": "all", "sessionId": session_id }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(detail["originKind"], "created");
+ assert_eq!(detail["source"], "desktop");
+ assert_eq!(detail["externalId"], Value::Null);
+ assert_eq!(detail["modelId"], "model");
+
+ // An unknown scope is a client error rather than a silent widening.
+ let unknown = handle_request(
+ state.clone(),
+ "plugin.session.list",
+ json!({ "pluginId": "plugin.one", "scope": "everything" }),
+ tx.clone(),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(unknown.code, 1002);
+
+ let appended = handle_request(
+ state.clone(),
+ "plugin.session.appendMessage",
+ json!({
+ "pluginId": "plugin.one",
+ "scope": "all",
+ "sessionId": session_id,
+ "message": {
+ "role": "user",
+ "content": "hello from a plugin",
+ "createdAt": "2026-01-01T00:00:01Z"
+ }
+ }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert!(appended["messageId"]
+ .as_str()
+ .is_some_and(|id| !id.is_empty()));
+
+ let replaced = handle_request(
+ state.clone(),
+ "plugin.session.replaceMessages",
+ json!({
+ "pluginId": "plugin.one",
+ "scope": "all",
+ "sessionId": session_id,
+ "messages": [
+ { "role": "user", "content": "rewritten", "createdAt": "2026-01-01T00:00:01Z" },
+ { "role": "assistant", "content": "reply", "createdAt": "2026-01-01T00:00:02Z" }
+ ]
+ }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(replaced["messageCount"], 2);
+
+ let messages = handle_request(
+ state.clone(),
+ "plugin.session.listMessages",
+ json!({ "pluginId": "plugin.one", "scope": "all", "sessionId": session_id }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(messages["items"][0]["origin"], "desktop");
+ let ids = messages["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|item| item["id"].as_str().unwrap_or_default().to_string())
+ .collect::<Vec<_>>();
+ assert_eq!(ids.len(), 2);
+
+ let deleted = handle_request(
+ state.clone(),
+ "plugin.session.deleteMessage",
+ json!({
+ "pluginId": "plugin.one",
+ "scope": "all",
+ "sessionId": session_id,
+ "messageId": ids[1]
+ }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(deleted["deleted"], true);
+ assert_eq!(deleted["deletedCount"], 1);
+
+ let truncated = handle_request(
+ state,
+ "plugin.session.truncateFrom",
+ json!({
+ "pluginId": "plugin.one",
+ "scope": "all",
+ "sessionId": session_id,
+ "keepCount": 0
+ }),
+ tx,
+ )
+ .await
+ .unwrap();
+ assert_eq!(truncated["keptCount"], 0);
+ assert_eq!(truncated["discardedCount"], 1);
+ }
+
#[tokio::test]
async fn plugin_usage_rpc_serves_read_only_fact_rows() {
let data_dir = tempfile::tempdir().unwrap();
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index 6f3ff34cb..834a6d483 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -13,7 +13,7 @@ use crate::transcripts::{self, CompactionRecord, MessageRecord, RevisionRecord};
mod fork_files;
mod history_mutations;
pub use history_mutations::{
- activate_message_revision_canonical, delete_message, retract_pending_prompt,
+ activate_message_revision_canonical, delete_message, retract_pending_prompt, running_turn,
};
mod model_system;
mod usage;
diff --git a/crates/host-core/src/sessions/history_mutations.rs b/crates/host-core/src/sessions/history_mutations.rs
index e3d105f73..5eaa393b0 100644
--- a/crates/host-core/src/sessions/history_mutations.rs
+++ b/crates/host-core/src/sessions/history_mutations.rs
@@ -31,7 +31,7 @@ fn not_retracted(reason: &'static str) -> RetractPendingPromptResult {
}
}
-fn running_turn(db: &Database, session_id: &str) -> Result<bool> {
+pub fn running_turn(db: &Database, session_id: &str) -> Result<bool> {
Ok(db.conn().query_row(
"SELECT EXISTS(SELECT 1 FROM turns WHERE session_id=?1 AND status='running')",
params![session_id],
diff --git a/crates/host-core/src/state.rs b/crates/host-core/src/state.rs
index fe166c336..4d2c30267 100644
--- a/crates/host-core/src/state.rs
+++ b/crates/host-core/src/state.rs
@@ -25,6 +25,7 @@ const PLUGIN_IMPORT_RATE_WINDOW: Duration = Duration::from_secs(60);
const PLUGIN_IMPORT_RATE_LIMIT: usize = 10;
const PLUGIN_BATCH_IMPORT_RATE_LIMIT: usize = 5;
const PLUGIN_DELETE_RATE_LIMIT: usize = 20;
+const PLUGIN_MESSAGE_WRITE_RATE_LIMIT: usize = 60;
pub struct AppState {
pub data_dir: std::path::PathBuf,
@@ -61,6 +62,9 @@ pub struct AppState {
pub plugin_import_rates: HashMap<String, Vec<Instant>>,
pub plugin_batch_import_rates: HashMap<String, Vec<Instant>>,
pub plugin_delete_rates: HashMap<String, Vec<Instant>>,
+ /// Message-level rewrites are one row at a time but each one rewrites the
+ /// transcript, so they get their own, wider window (ADR 0339).
+ pub plugin_message_write_rates: HashMap<String, Vec<Instant>>,
/// Chat-started processes detached from their turn (dev servers, etc.).
/// Lives with the host process; `shutdown` stops every running task.
pub background_tasks: crate::background_tasks::BackgroundTaskRegistry,
@@ -162,6 +166,7 @@ impl AppState {
plugin_import_rates: HashMap::new(),
plugin_batch_import_rates: HashMap::new(),
plugin_delete_rates: HashMap::new(),
+ plugin_message_write_rates: HashMap::new(),
tool_budget: ToolBudget::new(),
active_bash_cancellations: HashMap::new(),
active_tool_cancellations: HashMap::new(),
@@ -211,6 +216,16 @@ impl AppState {
)
}
+ /// One budget for every plugin message-level rewrite: append, replace,
+ /// delete, and truncate each cost one slot.
+ pub fn allow_plugin_message_write(&mut self, plugin_id: &str) -> bool {
+ Self::rate_allowed(
+ &mut self.plugin_message_write_rates,
+ plugin_id,
+ PLUGIN_MESSAGE_WRITE_RATE_LIMIT,
+ )
+ }
+
pub fn register_pending_permission(
&mut self,
request_id: &str,
diff --git a/docs/adr/0200-plugin-owned-session-api.md b/docs/adr/0200-plugin-owned-session-api.md
index f366759c2..b74ecbb4d 100644
--- a/docs/adr/0200-plugin-owned-session-api.md
+++ b/docs/adr/0200-plugin-owned-session-api.md
@@ -3,6 +3,8 @@
- Status: Accepted
- Date: 2026-09-09
- Decision: D367
+- Amended: 2026-10-20 (ADR 0339 adds the `session.*.all` grants and the
+ message-level writes; the ownership boundary below still governs `.own`)
## Context
@@ -57,3 +59,31 @@ list/get/rename, message paging/truncation, tool reserved-key scrubbing,
trash-to-purge lifecycle, migration-compatible schema creation, and rate
limits. Full UI E2E execution remains deferred per repository policy; scenarios
E2E-214 and E2E-215 are recorded in the E2E plan.
+
+## Amendment (ADR 0339)
+
+The ownership premise above — "a plugin can only query or mutate its own rows" —
+is no longer the only boundary the host can express. ADR 0339 adds
+`session.read.all`, `session.update.all`, and `session.delete.all`, which carry
+the same verbs over every live session, and it adds message-level writes
+(`appendMessage`, `replaceMessages`, `deleteMessage`, `truncateFrom`) that this
+ADR deferred as P2/P3.
+
+What changes for this ADR:
+
+- Everything here still describes `.own` exactly as written. An installed plugin
+ keeps that reach; `.all` is a separate grant that a user approves at install,
+ and it wins only when a manifest declares both.
+- "Host-core generates message ids" no longer holds for a plugin-supplied
+ `message.id` used as a retry key; the host still generates the id when the
+ caller omits one.
+- The P2/P3 deferral in the Decision and Consequences no longer covers message
+ mutation. Session creation, arbitrary re-binding, provider/model binding,
+ batch delete, and tags remain deferred.
+- Ownership is still enforced in the queries, but no longer always: the P0/P1
+ SQL keeps its `plugin_id` predicate only for `.own`, and the `list`,
+ `trash`, and `purge` statements now follow the scope Electron sends instead
+ of hard-coding it.
+
+See [ADR 0339](0339-plugin-session-all-scope.md) for the decision, the risk
+argument, and the alternatives.
diff --git a/docs/adr/0323-plugin-owned-session-titles.md b/docs/adr/0323-plugin-owned-session-titles.md
index eb3266458..b332e8c5b 100644
--- a/docs/adr/0323-plugin-owned-session-titles.md
+++ b/docs/adr/0323-plugin-owned-session-titles.md
@@ -4,6 +4,9 @@
- Date: 2026-10-08
- Supersedes: ADR 0186
- Amended: 2026-10-08 (D654 restores the deterministic first-prompt fallback)
+- Amended: 2026-10-20 (ADR 0339 adds `session.read.all`, so the rejected
+ "give the plugin a broader session read" alternative below no longer fails
+ for the reason recorded here)
## Context
@@ -70,6 +73,11 @@ model-composed title moves to the plugin.
spend model tokens and mutate titles when the optional plugin is absent.
- Give the plugin `session.read` or `session.read.own`: rejected because those
permissions either expose a general transcript projection or only imported
- sessions and do not match the required boundary.
+ sessions and do not match the required boundary. *(Corrected by ADR 0339: the
+ reason this alternative failed was that no grant described "read the user's
+ own session". `session.read.all` now does, so a title plugin that wants more
+ than the first turn can say so at install and ask for that grant instead.
+ `session.autoTitle` stays the narrow path and this ADR's boundary is
+ unchanged for plugins that keep it.)*
- Run a second title flow in Electron main: rejected because title policy and
user-configured prompts/models belong to the plugin after this change.
diff --git a/docs/adr/0339-plugin-session-all-scope.md b/docs/adr/0339-plugin-session-all-scope.md
new file mode 100644
index 000000000..ca78aa488
--- /dev/null
+++ b/docs/adr/0339-plugin-session-all-scope.md
@@ -0,0 +1,170 @@
+# ADR 0339: Let a granted plugin reach every session, not only its imports
+
+- Status: Accepted
+- Date: 2026-10-20
+- Decision: D680
+- Amends: ADR 0200, ADR 0323
+- Related: [spec 07-plugins/03 §plugin-owned and host-wide sessions](../spec/07-plugins/03-plugin-api.md) · [13-plugin-permissions-matrix](../spec/07-plugins/13-plugin-permissions-matrix.md)
+
+## Context
+
+`pi.session` was built for external conversation import (ADR 0200): every read
+and write is filtered by `session_import_origins.plugin_id`, so a plugin can
+only reach sessions it imported itself. That boundary was correct for the
+feature it shipped with, and it is now a capability gap.
+
+A plugin that legitimately needs the user's own conversation cannot express it.
+The shipped composer-suggestion flow (ADR 0333) reads the session with
+`pi.session.getLlmContext`, which only exists inside a plugin tool invocation,
+and the alternative — `pi.session.listMessages` — is refused for a session no
+plugin imported. The workaround for session titles (ADR 0323) made the gap
+explicit: it invented a narrower `session.autoTitle` permission *because* the
+existing two could not describe "a plugin may read a user's session". ADR 0323
+recorded the rejection in those words.
+
+Meanwhile the platform already accepts the underlying idea: `auto_title_context`
+reads any session in the database under a plugin-named permission, and the
+`turns`-based `usage.read` listing exposes every session's title and per-turn
+counters. The missing piece was never safety — it was a grant name that says
+what it grants, so the install review can state it plainly.
+
+The permission model itself already answers the risk question: a plugin is
+granted exactly the permissions its manifest declares, the install and update
+review lists every one of them and marks the ones an update adds, and a
+mismatched grant is refused outright. Consent happens at install, not at each
+call.
+
+## Decision
+
+1. Add three permissions — `session.read.all`, `session.update.all`,
+ `session.delete.all` — that carry the same three verbs as the `.own` family
+ over **every live session**, including the conversations the user created in
+ this app.
+
+2. Keep `.own` exactly as it is. `.all` is an addition, never a widening: an
+ installed plugin keeps the reach its user reviewed. A manifest may declare
+ both, and `.all` wins, because asking for the whole directory and the narrow
+ slice at once is asking for the whole directory.
+
+3. Split the enforcement so the ownership predicate stops being a second,
+ implicit permission. Electron main resolves the scope from the granted
+ permissions and sends the literal `scope` (`"own"` | `"all"`) to host-core;
+ host-core enforces exactly the scope it is handed, and an absent parameter
+ means `"own"`. Host-core still holds no permission data of its own — the
+ ADR 0200 division stays intact — and an unknown `scope` value is an
+ `INVALID_PARAMS` error rather than a silent widening.
+
+4. Fix the queries that only worked because the boundary was narrow:
+ `list` becomes a `LEFT JOIN` on the origin sidecar so a session with no
+ origin row is reachable; `get` reports the real `originKind`, `modelId`,
+ `providerId`, and `bound.model` instead of the import projection; messages
+ report `origin: "external"` or `"desktop"`; and the `EXISTS` predicates
+ inside the `purge` and `trash` statements follow the scope instead of
+ hard-coding ownership.
+
+5. Expose message-level writes for the first time, because "modify any content"
+ was not a capability `pi.session` had: `appendMessage` and
+ `replaceMessages` under `session.update.all`, `deleteMessage` and
+ `truncateFrom` under `session.delete.all`. They delegate to the existing
+ host-core transcript operations, so revision archiving, inflight
+ checkpoints, and the JSONL rewrite path are unchanged. A rewrite is refused
+ with `TURN_RUNNING` while a turn owns the session; `appendMessage` is exempt
+ because appending is how a turn's own rows land.
+
+6. Keep the brakes that are not about ownership: session delete stays at
+ 20 calls/minute per plugin, the four message-level writes share a
+ 60 calls/minute budget, and the existing import limits are untouched.
+
+7. Keep `session.autoTitle` as it is. It stays the narrow title path and does
+ not imply a read grant; a plugin that wants the transcript asks for
+ `session.read.all` and says so at install.
+
+## Consequences
+
+- A plugin can now read, rename, rewrite, and delete the user's own
+ conversations. That is the point, and it is a genuinely high-risk grant: the
+ matrix puts all three at `high`, `HIGH_RISK_PERMISSIONS` in the devkit carries
+ them, and the runtime-risk map mirrors the matrix so the UI cannot drift.
+- `rename` now claims the manual title source. Without that, a `.all` rename of
+ a still-default-titled session could be overwritten later by the
+ `session.autoTitle` plugin, which would quietly discard a title a plugin — and
+ therefore the user — chose.
+- A session outside the caller's scope is `NOT_FOUND`, not
+ `PERMISSION_DENIED`. The distinction matters: a permission error would let an
+ `.own` plugin probe for the existence of sessions it may not see.
+- `PluginSessionListItem.externalId` and `PluginSessionGetResult.externalId`
+ widen to `string | null`, and `PluginSessionMessageResult.origin` widens to
+ `"external" | "desktop"`. Both are read-type widenings: they are `null` (or
+ `"desktop"`) only for the sessions a `.all` holder can reach, so `.own`
+ consumers see exactly what they saw before.
+- Audit records now name the scope that authorised a session call. Before this
+ change `plugin.session.list`/`get`/`listMessages`/`rename`/`delete` emitted no
+ audit entry at all, which was already a gap; the new breadth makes it
+ unacceptable, so every session call audits one line with `scope`.
+- The renderer learns which session changed. `sessionsChanged` now carries an
+ optional `sessionId`, and the shell re-reads an open transcript when that id is
+ the active session and no turn is running. Without it a plugin rewrite would be
+ invisible until the user reselected the conversation.
+- `sessions::running_turn` becomes crate-visible so the plugin boundary and the
+ renderer path share one definition of "a turn owns this session".
+
+## Alternatives considered
+
+### Widen the existing `.own` permissions instead of adding `.all`
+
+Rejected. The install review is the consent surface, and a user who approved
+"only the sessions this plugin imported" did not approve "every conversation I
+ever had". Silently widening a stored grant changes what an existing install is
+allowed to do without anyone agreeing to it, which is exactly the failure the
+default-deny rule exists to prevent.
+
+### Route plugin reads through `session.read` (the `getLlmContext` projection)
+
+Rejected. That permission is scoped to an in-flight tool invocation and returns
+a compaction-aware projection of the prompt, not a session. Reusing it would
+mean either letting a plugin name an arbitrary session id under a grant that
+promises no such thing, or keeping the unusable boundary.
+
+### Give the plugin direct session RPC access
+
+Rejected. It hands the plugin a generic host channel and removes the pluginId
+provenance the audit relies on. The scope split keeps one endpoint per verb and
+keeps Electron main as the only caller that can claim a plugin identity.
+
+### Loosen the ownership filter and let the permission name alone carry the risk
+
+Rejected. Removing the check without a scope would make every existing `.own`
+grant a full-grant, which is the first alternative again. The scope parameter is
+what keeps old grants old.
+
+### Keep message-level writes out of scope
+
+Rejected for this change. The requirement is "read and modify any session's
+content", and a plugin that can rename a session but not append to it still
+cannot run the composer-suggestion flow this ADR unblocks. The four methods
+delegate to host-core operations the renderer already uses, so the new surface
+is a contract and a permission, not a second transcript writer.
+
+### Publish an `expectedRevision` precondition for message writes
+
+Rejected for now. No session-wide revision counter exists; `revision` in this
+codebase names a regenerate family, not a transcript version. A precondition
+would have to be invented, persisted, and migrated, and a wrong guess would make
+legitimate writes fail. `TURN_RUNNING` covers the one concurrent writer that
+actually exists — the running turn — and the audit line covers the rest.
+
+## Verification
+
+- `crates/host-core/src/plugin_sessions.rs` unit tests cover scope parsing,
+ `.own` regression (a user-created session stays invisible), `.all` reads with
+ the corrected metadata, `.all` rename/trash/purge, message-level
+ append/replace/delete/truncate, running-turn refusal, and payload bounds.
+- `crates/host-core/src/rpc/mod.rs` covers the dispatch: `.own` reports
+ `NOT_FOUND`, `.all` serves the same row, an unknown scope is `INVALID_PARAMS`,
+ and the four message-level arms round-trip.
+- `apps/desktop/test/plugin-session-access.test.mjs` covers the broker policy:
+ scope resolution, `.all` winning over `.own`, the message-write grants, and
+ payload rejection.
+- `apps/desktop/test/plugin-session-api.test.mjs` covers the gateway end to end
+ through a real plugin process, including a plugin that tries to set its own
+ scope and gets `own` anyway.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8f3d83276..cdb4e7e4d 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -398,3 +398,4 @@ Each ADR includes:
| 0338 | [A user-supplied video owns the boot surface, served over a host-owned scheme](0338-user-supplied-startup-animation.md) | Accepted (D679) |
| model-reasoning-effort-override | [Model reasoning effort override](model-reasoning-effort-override.md) | Proposed |
+| 0339 | [Let a granted plugin reach every session, not only its imports](0339-plugin-session-all-scope.md) | Accepted (D680; amends ADR 0200 and ADR 0323) |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 8b9777038..ed207dbff 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -19245,6 +19245,54 @@ host-created files. The full app's file-preview viewer is covered separately.
`apps/desktop/test/main-wiring-contract.test.mjs`; the interactive Electron
scenario remains a manual validation run.
+### E2E-268: A plugin reads and rewrites a session the user created
+
+- **Preconditions**: A development plugin that declares
+ `session.read.all`, `session.update.all`, and `session.delete.all`, and whose
+ commands call `pi.session.list()`, `pi.session.get()`,
+ `pi.session.listMessages()`, `pi.session.rename()`,
+ `pi.session.appendMessage()`, `pi.session.replaceMessages()`,
+ `pi.session.deleteMessage()`, and `pi.session.truncateFrom()`. One ordinary
+ session the user created and typed two prompts into, plus the same manifest
+ edited down to only the `.own` grants.
+- **Steps**:
+ 1. Install the `.all` build and run each read command against the user's own
+ session.
+ 2. Run `rename`, then check the session title in the sidebar and whether the
+ auto-title plugin can still rename it.
+ 3. Run `appendMessage` while the session is idle, and again while a turn is
+ running.
+ 4. Run `replaceMessages`, `deleteMessage`, and `truncateFrom` on the same
+ session, watching the open transcript between calls.
+ 5. Reinstall the `.own`-only build and repeat steps 1 and 4, including a call
+ that passes `scope: "all"` itself.
+ 6. Check the app log for one audit line per call.
+- **Expected**: With `.all`, `list` returns the user's session with
+ `originKind: "created"`, `source: "desktop"`, `externalId: null`, the real
+ `modelId`/`providerId`/`bound.model`, and messages reporting
+ `origin: "desktop"`; `get` and `listMessages` agree with it. `rename`
+ succeeds and the auto-title plugin can no longer replace that title.
+ `appendMessage` adds one row while idle and returns its `messageId`; a repeat
+ with the same id adds nothing. While a turn runs, `appendMessage` still
+ appends and the three transcript rewrites fail with `TURN_RUNNING`.
+ `replaceMessages` and `truncateFrom` repaint the open transcript without
+ reselecting the session, `deleteMessage` on a user prompt removes the prompt
+ and its replies, and a repeated delete reports `deleted: false`. With `.own`
+ the same session is `NOT_FOUND` for every call, nothing in the transcript
+ changes, and the plugin's own `scope: "all"` is ignored — the call still runs
+ as `own`. Every audited line names the scope that authorised it.
+- **Specs linked**: `07-plugins/03-plugin-api.md` §plugin-owned and host-wide
+ sessions; `07-plugins/13-plugin-permissions-matrix.md` §2;
+ `07-plugins/04-plugin-security.md` §5; ADR 0339, ADR 0200 (amendment).
+- **Acceptance**: A plugin that declares the `.all` grants can read and rewrite
+ the user's own conversations, the user sees the result in the open transcript,
+ and a plugin that declares only `.own` keeps exactly the ADR 0200 reach.
+- **Status**: Draft. Host-core coverage in the `plugin_sessions` and
+ `plugin_session` tests, broker policy in
+ `apps/desktop/test/plugin-session-access.test.mjs`, and the plugin-process
+ path in `apps/desktop/test/plugin-session-api.test.mjs`; the interactive
+ Electron scenario remains a manual validation run.
+
### E2E-FAST-MODE: `/fast` asks for the priority tier only on an allowed model
- **Preconditions**: A ChatGPT subscription (Codex) account and a Responses
diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.md
index f18999f86..62c2a3495 100644
--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md
+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md
@@ -417,6 +417,9 @@ type PluginPermission =
| "session.read.own"
| "session.update.own"
| "session.delete.own"
+ | "session.read.all"
+ | "session.update.all"
+ | "session.delete.all"
| "session.autoTitle"
| "usage.read"
| "audio.capture.background"
diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.md
index b7ca69172..e5b259268 100644
--- a/docs/spec/07-plugins/03-plugin-api.md
+++ b/docs/spec/07-plugins/03-plugin-api.md
@@ -740,14 +740,27 @@ update makes the result `{ updated: false }`. Both methods require
`session.autoTitle`, which is high risk because the first-turn text can be sent
to a model by a plugin holding `agent.complete`.
-### plugin-owned sessions (P0/P1; requires the matching permission)
-
-Plugins may import and manage only sessions whose origin belongs to that same
-plugin. The source must be declared in `manifest.contributes.sessionSources`;
-the host supplies the localized source label and generates the durable session
-and message ids. Imported sessions never bind a workspace, provider, or model;
-they bind a project only when the caller supplies an existing `projectId`. The
-original import values remain available in `get().history`.
+### plugin-owned and host-wide sessions (requires the matching permission)
+
+Plugins address sessions through two grants that share one set of verbs:
+
+- `session.read.own` / `session.update.own` / `session.delete.own` — the
+ ADR 0200 boundary: only sessions whose origin belongs to the calling plugin.
+- `session.read.all` / `session.update.all` / `session.delete.all` — every live
+ session, including the conversations the user created in this app (ADR 0339).
+
+`.all` is a separate grant, never a widening of `.own`, so an existing install
+keeps exactly the reach it was reviewed for. A manifest may declare both, and
+`.all` wins. The Electron broker resolves the scope from the granted
+permissions; a plugin never passes one, and a `scope` field in the payload is
+dropped. Every call is audited with the scope that authorised it.
+
+Import additionally requires the source to be declared in
+`manifest.contributes.sessionSources`; the host supplies the localized source
+label and generates the durable session and message ids. Imported sessions never
+bind a workspace, provider, or model; they bind a project only when the caller
+supplies an existing `projectId`. The original import values remain available in
+`get().history`.
```ts
type PluginSessionSourceContrib = {
@@ -785,6 +798,7 @@ pi.session.importBatch(input: {
mode?: "skip" | "fail"
}): Promise<PluginSessionBatchImportResult>
+// session.read.own or session.read.all
pi.session.list(input?: {
limit?: number; cursor?: string; source?: string; updatedAfter?: string
}): Promise<PluginSessionListResult>
@@ -793,37 +807,93 @@ pi.session.listMessages(input: {
sessionId: string; limit?: number; cursor?: string
order?: "asc" | "desc"; contentLimit?: number
}): Promise<PluginSessionMessageListResult>
+
+// session.update.own or session.update.all
pi.session.rename(input: { sessionId: string; title: string }): Promise<{ updated: boolean }>
+
+// session.delete.own or session.delete.all
pi.session.delete(input: {
sessionId: string; mode?: "trash" | "purge"
}): Promise<{ deleted: boolean }>
+
+// Message-level writes exist only under `.all`: rewriting a transcript is never
+// an imported-session operation.
+type PluginSessionMessageInput = {
+ id?: string // host-generated when omitted; a supplied id makes a retry a no-op
+ role: "user" | "assistant" | "tool"
+ content: string
+ createdAt: string // monotonic within one call, newest last
+ modelId?: string
+ providerId?: string
+ toolName?: string
+ toolCallId?: string
+ toolStatus?: "success" | "error"
+ toolArgs?: unknown
+ toolResult?: unknown
+}
+
+// session.update.all
+pi.session.appendMessage(input: {
+ sessionId: string; message: PluginSessionMessageInput
+}): Promise<{ messageId: string }>
+pi.session.replaceMessages(input: {
+ sessionId: string; messages: PluginSessionMessageInput[] // at most 2,000
+}): Promise<{ messageCount: number }>
+
+// session.delete.all
+pi.session.deleteMessage(input: {
+ sessionId: string; messageId: string
+}): Promise<{ deleted: boolean; deletedCount: number }>
+pi.session.truncateFrom(input: {
+ sessionId: string; fromMessageId?: string; keepCount?: number
+}): Promise<{ keptCount: number; discardedCount: number }>
```
Import is idempotent on `(pluginId, source, externalId)`. `skip` batches
continue per item; `fail` batches validate and commit atomically. `trash` hides
the session while retaining its transcript and origin; `purge` removes both and
-allows a later re-import. Reads, rename, and delete are ownership-scoped, and
-undeclared sources fail with `PERMISSION_DENIED`.
+allows a later re-import. Reads, rename, and delete are scope-checked, and
+undeclared sources fail with `PERMISSION_DENIED`. A session outside the scope is
+reported as `NOT_FOUND`, never as a permission error, so a plugin cannot probe
+for the existence of a row it may not see.
+
+Non-imported sessions report their real shape instead of an import projection:
+`originKind` is `"created"`, `source` is `"desktop"`, `externalId` is `null`,
+`modelId` / `providerId` / `bound.model` come from the session row, and every
+message carries `origin: "desktop"`. Imported sessions keep
+`originKind: "imported"`, their declared source id, and `origin: "external"`.
When a session has an explicit project binding, `projectId` and
`bound.workspace` report that binding, and `get().projectPath` resolves the
bound project's current path. The original import `projectPath` remains in
`get().history`.
-After a successful import, rename, or delete, Electron main emits one
-host-owned `sessionsChanged` event for the affected mutation. The renderer
-refreshes its authoritative session list and the Projects page refreshes its
-durable project index from that list. Plugins do not emit or coordinate this
-event themselves. A project created through this API is not automatically
-opened as a sidebar tab, preserving the existing closed-project behavior.
+After a successful import, rename, delete, or message-level write, Electron main
+emits one host-owned `sessionsChanged` event for the affected mutation, naming
+the `sessionId` it touched so the shell can repaint an open transcript. The
+renderer refreshes its authoritative session list and the Projects page
+refreshes its durable project index from that list. Plugins do not emit or
+coordinate this event themselves. A project created through this API is not
+automatically opened as a sidebar tab, preserving the existing closed-project
+behavior.
+
+`rename` claims the manual title source, so an installed `session.autoTitle`
+plugin cannot replace a title this plugin — and therefore the user — chose.
The host enforces a 2,000-message/session, 100-session/batch, 512 KiB/message,
256 KiB/tool-value, 32 MiB/payload, and JSON-depth-8 limit. Import is limited
to 10 calls/minute plus 5 batch calls/minute per plugin; delete is limited to
-20 calls/minute. Tool `__pi*` and `piDesktop.*` object keys are removed before
-storage. P2/P3 operations (session create, message mutation, arbitrary re-binding,
-provider/model binding, batch delete, and tags) are intentionally not part of
-this contract.
+20 calls/minute; the four message-level writes share a 60 calls/minute budget.
+Tool `__pi*` and `piDesktop.*` object keys are removed before storage.
+
+Every message-level rewrite is refused with `TURN_RUNNING` while a turn owns the
+session, because the running agent is writing the same transcript; retry after
+the turn settles. `appendMessage` is the documented exception — appending is how
+a turn's own rows land. `deleteMessage` on a user prompt removes that prompt and
+its replies, and a missing target is a success with `deleted: false`, so a
+retried delete is safe. Remaining P3 operations (session create, arbitrary
+re-binding, provider/model binding, batch delete, and tags) are intentionally
+not part of this contract.
### usage (requires `usage.read`)
diff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.md
index 0a342c532..e9d6ff821 100644
--- a/docs/spec/07-plugins/04-plugin-security.md
+++ b/docs/spec/07-plugins/04-plugin-security.md
@@ -163,7 +163,11 @@ Plugins cannot access:
- Other plugins' data
- Host secrets through a general-purpose API; `provider.oauth` grants access
only to the callback's own declared provider credential
-- The host's full session database (unless a controlled API exists in the future)
+- The host's full session database through any general-purpose surface. A
+ controlled API exists: `pi.session` with the `.own` grants (imported sessions
+ only) or the `session.*.all` grants (every live session, approved at install
+ and audited per call). There is no other path to sessions, no SQLite handle,
+ and no transcript file access
## 5.1 Inter-plugin message bus
diff --git a/docs/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/spec/07-plugins/13-plugin-permissions-matrix.md
index 415f60f18..6f921b3fb 100644
--- a/docs/spec/07-plugins/13-plugin-permissions-matrix.md
+++ b/docs/spec/07-plugins/13-plugin-permissions-matrix.md
@@ -53,6 +53,9 @@ Provide a permission–capability–risk–default-policy reference table for re
| `session.read.own` | medium | `pi.session.list`, `pi.session.get`, `pi.session.listMessages` | Confirm at install | Reads only sessions imported by the calling plugin; no cross-plugin access |
| `session.update.own` | medium | `pi.session.rename` | Confirm at install | Renames only the calling plugin's active imported sessions |
| `session.delete.own` | high | `pi.session.delete` | Confirm at install | Trash/purge only the calling plugin's imported sessions; rate-limited |
+| `session.read.all` | high | `pi.session.list`, `pi.session.get`, `pi.session.listMessages` | Confirm at install | Reads **any** live session, including the conversations the user created in this app: title, project, model binding, and full message history with tool payloads. `.all` is a separate grant from `session.read.own` and wins when both are declared; the audit line records which scope authorised the call (ADR 0339) |
+| `session.update.all` | high | `pi.session.rename`, `pi.session.appendMessage`, `pi.session.replaceMessages` | Confirm at install | Renames any session and rewrites its transcript: append, replace, or delete-single-message. Rewrites are refused while a turn is running (`TURN_RUNNING`) and rate-limited. A rename claims the manual title source, so `session.autoTitle` cannot overwrite it afterwards |
+| `session.delete.all` | high | `pi.session.delete`, `pi.session.deleteMessage`, `pi.session.truncateFrom` | Confirm at install | Trash/purge any session and cut or delete its messages. Keeps the session-delete rate limit; message rewrites share a 60/min message-write budget |
| `usage.read` | medium | `pi.usage.listTurns` | Confirm at install | Read-only listing of completed-turn facts (per-turn token counters and identifiers, keyset-paginated); no message body and no write path |
| `agent.complete` | high | `pi.agent.complete` | Confirm at install | Host-owned one-shot; spends user quota; `includeSessionContext` also needs `session.read` |
| `speech.adapter.register` | high | `pi.speech.registerAdapter` / `unregisterAdapter` | Confirm at install | Registers a speech protocol. Handles stay in the guest; HTTP plans are executed by the host with the bound provider key and must stay on that origin. Built-in protocol ids are reserved |
@@ -127,6 +130,13 @@ plugin, so it carries three bounds the other modes do not:
`appearance:changed`, `session:modelChanged`, `session:turnEnded`,
`session:activated`, and `plugin:settingsChanged` arrive on the existing plugin event channel, and subscribing to an unknown
event name does not error
+- `session.read.all` / `session.update.all` / `session.delete.all` each replace
+ the matching `.own` grant rather than extending it: a manifest may declare
+ both, and `.all` wins. Message-level writes (`pi.session.appendMessage`,
+ `replaceMessages`, `deleteMessage`, `truncateFrom`) exist only under `.all`,
+ because rewriting a transcript is never an imported-session operation
+ (ADR 0339). `session.autoTitle` stays the narrow title path and does not
+ imply any session read grant
## 3A. Plan operating-state rule
@@ -190,6 +200,9 @@ plugin's row (Files), so "Edit files" is followed by the list.
| `desktop.control` | Control the desktop | 控制桌面操作 |
| `net.anyHost` | Access any network address | 访问任意网络地址 |
| `session.autoTitle` | Read first-turn title context and update automatic titles | 读取首轮标题上下文并更新自动标题 |
+| `session.read.all` | Read any conversation, including yours | 读取任意会话,包括你自己的对话 |
+| `session.update.all` | Rewrite any conversation, including its messages | 改写任意会话,包括修改其消息 |
+| `session.delete.all` | Delete any conversation, including yours | 删除任意会话,包括你自己的对话 |
These permissions have no catalog entry today and are shown as their raw key:
`ui.settings`, `session.import`, `session.read.own`, `session.update.own`, `session.delete.own`, `ui.view`, `project.create`.
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index c6701e9f4..bf3b96286 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -428,6 +428,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.
| D236 | One desktop instance per data directory | **Electron main takes `app.requestSingleInstanceLock()` during module evaluation — after `app.setName`, because the lock lives under the name-derived `userData` path, and before the logger, the persistence outbox, or any other data-directory access. A launch that does not take the lock calls `app.quit()` and boots nothing: the readiness and `before-quit` handlers both return early, so it creates no window, tray, child process, or log line inside the running instance's data directory. The lock holder answers `second-instance` by restoring and focusing its main window through the same path as the tray's Show action, which recreates a window that was closed or hidden into the tray. The lock is requested only when `PI_DESKTOP_DATA_DIR` is unset, so E2E harnesses, the capture rig, and deliberate side-by-side profiles keep the current start-anytime behavior. No IPC channel, host protocol, or storage schema changes.** | A second launch booted a complete second app: another host-core over the single-writer `pi.sqlite` (D002), another outbox and log tree in the same directory, another tray, launcher-chord registration, and updater, leaving two shells divergent over one database. Relaunching the app is a request to see the one already running, and scoping the lock to the installation keeps isolated-data-directory runs launchable (ADR 0094). |
| D367 | Host-owned plugin session import and ownership API | **`pi.session` gains `import`, `importBatch`, `list`, `get`, `listMessages`, `rename`, and `delete`; `contributes.sessionSources` is required for every source; host-core generates ids and scopes every operation to `(pluginId, source, externalId)` ownership; imports never activate project/provider/model bindings. Schema v14 adds `session_import_origins` and `sessions.deleted_at`; protocol v11 is unchanged. Trash keeps the transcript for owner-only purge.** | External-history plugins need durable import/read/update/delete, and the in-flight `session.getLlmContext` and core `session.import` boundaries are not safe plugin ownership boundaries (ADR 0200, E2E-214 / E2E-215) |
| D368 | Explicit plugin project ids and host-owned session refresh | **Permission-gated `pi.project.create({ path })` creates or reuses a project and returns its host-generated id without activating the workspace; import items may bind an existing `projectId`, omitted ids stay unbound, and historical origin paths never become tool roots. Electron main emits `pi-desktop/session/event/changed` after successful plugin imports, renames, and deletes; the renderer reuses `refreshSessions()`, skipped imports emit nothing, and closed project tabs are not reopened.** | Exposing `workspace.set` to plugins would change the user's active workspace, and plugin writes need a host-owned renderer refresh path (ADR 0201, E2E-216) |
+| D680 | Plugin session scope: `.all` grants and message-level writes | **`pi.session` gains `session.read.all`, `session.update.all`, and `session.delete.all`, which carry `list`/`get`/`listMessages`, `rename`, and `delete` over every live session instead of only the calling plugin's imports. `.all` is a separate grant, never a widening of `.own`, and it wins when a manifest declares both. Electron main resolves the scope from the grants and sends `scope` to host-core, which enforces exactly that and treats an absent value as `own`; `list` becomes a `LEFT JOIN` on the origin sidecar, `get`/messages report the real `originKind`, `source`, `externalId`, model binding, and `origin` instead of the import projection, and the `trash`/`purge` statements follow the scope instead of an embedded `EXISTS`. Message-level writes arrive as `appendMessage`/`replaceMessages` (`session.update.all`) and `deleteMessage`/`truncateFrom` (`session.delete.all`), delegating to the existing host-core transcript operations, refusing a rewrite with `TURN_RUNNING` while a turn owns the session, and sharing a 60/min budget. `rename` now claims the manual title source. Every session call audits the authorising scope; `sessionsChanged` names the changed session.** | The ADR 0200 ownership filter made a legitimate "read the user's own conversation" capability inexpressible, so ADR 0323 had to invent a narrower title permission and ADR 0333's shipped suggestion flow cannot read the session it runs on; widening `.own` instead would silently expand grants users reviewed as "only the sessions this plugin imported" (ADR 0339) |
| D370 | Local MCP control plane for desktop operations | *(amended by D372)* **An opt-in Streamable HTTP MCP server inside Electron Main binds to `127.0.0.1`, authenticates with a persistent random bearer token, validates supplied Origins against loopback hostnames, writes a mode-restricted connection manifest, and delegates to the same registered IPC handlers the renderer uses. Named tools cover the project/session/Agent flow; `pi_desktop_invoke` reaches a risk-tagged operation catalog; dangerous operations require `confirm: true`; successful external mutations reuse the renderer session-change event. Local-only and fail-soft at startup.** | An external Agent needs to drive the running desktop without a second permission or persistence implementation and without touching the deferred remote Gateway / WebUI boundary (ADR 0203, E2E-220) |
| D372 | Tightened local MCP control-plane boundary | **Amend D370 / ADR 0203: the first-version catalog is the project/session/Agent/workspace flow plus reviewed reads; secret-shaped arguments are stripped; `session/configure` is dangerous; listen addresses are asserted loopback; protocol versions are negotiated rather than echoed; results including `structuredContent` are bounded; renderer session refresh is mutation-only.** | The first catalog still exposed native pickers, secret-write provider/OAuth/MCP paths, and unconfirmed `session/configure`, and treated session reads as renderer mutations (E2E-220) |
| D377 | Plugin desktop control requires native user consent | **A `dangerous` desktop operation invoked through `pi.desktop.invoke` needs the plugin's `confirm: true` and then the user's answer to a host-owned native dialog that shows only the catalog operation id, description, and a bounded argument preview; dismissal, Deny, and a host without a dialog service fail with `PERMISSION_DENIED`. `read`/`write` operations and the MCP contract (D372) are unchanged.** | The controller's `confirm` flag is set by the caller, so a plugin (or a model behind it) could delete sessions or switch a session to `auto` with no human in the loop, and any plugin-drawn confirmation card can be relabeled by a prompt-injected transcript (ADR 0208, E2E-236) |
@@ -8148,3 +8149,43 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
over `pi-startup:` under the page CSP, playback advances, the reveal hands
over an interactive shell, and an unplayable file yields the shell in about a
second rather than holding the window.
+
+## 2026-10-20 — Plugin session scope: `.all` grants and message-level writes (D680)
+
+- D680 / ADR 0339 opens `pi.session` beyond the ADR 0200 import boundary. Three
+ new permissions — `session.read.all`, `session.update.all`,
+ `session.delete.all` — carry the existing verbs over every live session,
+ including the conversations the user created in this app.
+- `.all` is an addition, not a widening. An installed plugin keeps exactly the
+ reach its user reviewed; a manifest may declare both, and `.all` wins.
+- The ownership predicate stops being a second, implicit permission. Electron
+ main resolves the scope from the granted permissions and sends it; host-core
+ enforces exactly that, treats an absent `scope` as `own`, and rejects an
+ unknown value with `INVALID_PARAMS`.
+- The queries that only worked because the boundary was narrow are fixed:
+ `list` left-joins the origin sidecar, `get` and messages report the real
+ `originKind` / `source` / `externalId` / model binding / `origin` instead of
+ the import projection, and the `trash` and `purge` statements follow the
+ scope instead of an embedded `EXISTS`.
+- Message-level writes exist for the first time: `appendMessage` and
+ `replaceMessages` under `session.update.all`, `deleteMessage` and
+ `truncateFrom` under `session.delete.all`. They delegate to the host-core
+ transcript operations, so revision archiving, inflight checkpoints, and the
+ JSONL rewrite path are unchanged.
+- A rewrite is refused with `TURN_RUNNING` while a turn owns the session.
+ `appendMessage` is exempt, because appending is how a turn's own rows land.
+- `rename` claims the manual title source, so an installed `session.autoTitle`
+ plugin cannot replace a title the user's plugin chose.
+- Every session call now audits the scope that authorised it. Before this
+ change `list`/`get`/`listMessages`/`rename`/`delete` emitted no audit entry.
+- `sessionsChanged` carries the changed `sessionId`, and the shell re-reads an
+ open transcript when that id is active and no turn is running.
+- Not changed: `.own` semantics, the import contract and its limits, the
+ `session.autoTitle` boundary, database schema, and persisted formats. The
+ delete rate limit stays at 20/minute; the four message writes share a
+ 60/minute budget.
+- Covered by the `plugin_sessions` and `plugin_session` host-core tests,
+ `apps/desktop/test/plugin-session-access.test.mjs`, and
+ `apps/desktop/test/plugin-session-api.test.mjs`. See ADR 0339, ADR 0200's
+ amendment, ADR 0323's corrected alternative, `03-plugin-api.md` §plugin-owned
+ and host-wide sessions, `13-plugin-permissions-matrix.md` §2, and E2E-268.
diff --git a/docs/zh-CN/adr/index.md b/docs/zh-CN/adr/index.md
index 675000a17..819244994 100644
--- a/docs/zh-CN/adr/index.md
+++ b/docs/zh-CN/adr/index.md
@@ -316,6 +316,7 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索
| 0311 | [在 Host 受理时重新核验 Live Work 工作空间身份](/adr/0311-live-work-workspace-admission-guard) | 已实现候选 |
| 0312 | [会话级 Todo 清单](/adr/0312-session-scoped-todo-checklist) | 已接受实施 |
| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](/adr/registry-header-variable-spelling) | Proposed |
+| 0339 | [插件可访问任意会话(新增 .all 权限)](/adr/0339-plugin-session-all-scope) | 已接受(修订 ADR 0200、ADR 0323;D680) |
## 什么时候看 ADR
diff --git a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
index ca1b1188b..45cd8dc2c 100644
--- a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
+++ b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
@@ -393,6 +393,9 @@ type PluginPermission =
| "session.read.own"
| "session.update.own"
| "session.delete.own"
+| "session.read.all"
+| "session.update.all"
+| "session.delete.all"
| "session.autoTitle"
| "usage.read"
| "audio.capture.background"
diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.md
index 39411a578..3f1896174 100644
--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md
+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md
@@ -721,6 +721,29 @@ Projects 页面也会据此刷新持久项目索引;插件不需要、也不
5 次批量导入和 20 次删除。写入前会移除工具 `__pi*` 与 `piDesktop.*` 对象键。
P2/P3(会话创建、消息变更、任意重新绑定、provider/model 绑定、批量删除、标签)不属于本次接口。
+自 ADR 0339 起,同一组动词还有 `.all` 授权:`session.read.all`、
+`session.update.all`、`session.delete.all`。它们覆盖**所有活动会话**,包括用户
+在本应用中自己创建的对话。`.all` 是与 `.own` 并列的独立授权,不会放宽 `.own`;
+清单同时声明两者时 `.all` 生效。作用域由 Electron main 依据授权解析后传给
+host-core,插件不能自行指定(payload 里的 `scope` 会被丢弃),host-core 只执行
+收到的那个值,缺省视为 `own`。越界会话一律返回 `NOT_FOUND` 而非
+`PERMISSION_DENIED`,以免插件借错误码探测它看不到的会话。每次调用都会在审计中
+记录授权作用域。
+
+非导入会话按真实形态返回:`originKind` 为 `"created"`、`source` 为
+`"desktop"`、`externalId` 为 `null`、`modelId`/`providerId`/`bound.model` 取自
+会话行,消息的 `origin` 为 `"desktop"`;导入会话仍是 `"imported"`、其声明的
+来源 id 与 `"external"`。
+
+消息级写入只在 `.all` 下存在:`pi.session.appendMessage`、`replaceMessages`
+(`session.update.all`)与 `pi.session.deleteMessage`、`truncateFrom`
+(`session.delete.all`)。它们复用宿主已有的记录操作,因此在回合运行期间会以
+`TURN_RUNNING` 拒绝改写(`appendMessage` 例外,追加本身就是回合写入自身行的
+方式),并共用每分钟 60 次的写入预算。消息可携带可选 `id`,用同一 id 重试是
+幂等的;`deleteMessage` 删除用户提示时会连同其回复一并删除,目标不存在时返回
+`deleted: false` 而不是报错。`rename` 现在会占用手动标题来源,
+`session.autoTitle` 插件之后无法覆盖该标题。
+
### 用量(需要 `usage.read`)
面向用户仍可见的未删除会话,提供只读的**已完成回合事实行**。宿主只提供
diff --git a/docs/zh-CN/spec/07-plugins/04-plugin-security.md b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
index 2a2e7abc0..104b36bb0 100644
--- a/docs/zh-CN/spec/07-plugins/04-plugin-security.md
+++ b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
@@ -138,7 +138,7 @@ CSS 不能执行脚本,却仍可能误导用户:主题是塑造用户所见
插件无法访问:
- 其他插件的数据
- 宿主机密的通用访问接口;`provider.oauth` 仅允许回调访问自己声明的 provider 凭据
-- 主机的完整会话数据库(除非将来存在受控的 API)
+- 主机完整会话数据库的任何通用接口。存在受控 API:`pi.session` 的 `.own` 授权(仅本插件导入的会话)或 `session.*.all` 授权(所有活动会话,安装时批准并逐次审计)。除此之外没有别的会话访问路径,也没有 SQLite 句柄或记录文件访问
## 5.1 插件间消息总线
diff --git a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
index cfab7f0bc..753d77956 100644
--- a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
+++ b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
@@ -56,6 +56,9 @@
| `session.read.own` | 中等 | `pi.session.list`、`pi.session.get`、`pi.session.listMessages` | 安装时确认 | 只能读取本插件导入的会话;不能跨插件访问 |
| `session.update.own` | 中等 | `pi.session.rename` | 安装时确认 | 只能重命名本插件拥有的活动导入会话 |
| `session.delete.own` | 高 | `pi.session.delete` | 安装时确认 | 只能回收或清除本插件导入的会话;有频率限制 |
+| `session.read.all` | 高 | `pi.session.list`、`pi.session.get`、`pi.session.listMessages` | 安装时确认 | 可读取**任意**活动会话,包括用户在本应用中自己创建的对话:标题、项目、模型绑定,以及含工具负载的完整消息记录。`.all` 是与 `session.read.own` 并列的独立授权,两者都声明时 `.all` 生效;审计行会记录本次调用依据的作用域(ADR 0339) |
+| `session.update.all` | 高 | `pi.session.rename`、`pi.session.appendMessage`、`pi.session.replaceMessages` | 安装时确认 | 可重命名任意会话并改写其记录:追加、替换或删除单条消息。回合运行期间拒绝改写(`TURN_RUNNING`),并有频率限制。重命名会占用「手动标题」来源,`session.autoTitle` 之后无法覆盖 |
+| `session.delete.all` | 高 | `pi.session.delete`、`pi.session.deleteMessage`、`pi.session.truncateFrom` | 安装时确认 | 可回收或清除任意会话,并截断或删除其消息。保留会话删除频率限制;消息改写共用每分钟 60 次的预算 |
| `usage.read` | 中等 | `pi.usage.listTurns` | 安装时确认 | 已完成 turn 事实行的只读列举(每回合 token 计数与标识符,keyset 分页);不含消息正文,无写路径 |
| `agent.complete` | 高 | `pi.agent.complete` | 安装时确认 | 宿主代发一次性补全;消耗用户额度;`includeSessionContext` 还需要 `session.read` |
| `speech.adapter.register` | 高 | `pi.speech.registerAdapter` / `unregisterAdapter` | 安装时确认 | 注册语音协议。handle 留在插件进程;HTTP 计划由宿主用绑定密钥代发且必须同 origin |
@@ -179,6 +182,9 @@ manifest 里的字段负责回答「能做到多远」。两个字段都由主
| `desktop.control` | Control the desktop | 控制桌面操作 |
| `net.anyHost` | Access any network address | 访问任意网络地址 |
| `session.autoTitle` | Read first-turn title context and update automatic titles | 读取首轮标题上下文并更新自动标题 |
+| `session.read.all` | Read any conversation, including yours | 读取任意会话,包括你自己的对话 |
+| `session.update.all` | Rewrite any conversation, including its messages | 改写任意会话,包括修改其消息 |
+| `session.delete.all` | Delete any conversation, including yours | 删除任意会话,包括你自己的对话 |
以下权限目前没有语言包条目,显示为原始权限名:
`ui.settings`、`session.import`、`session.read.own`、`session.update.own`、`session.delete.own`、`ui.view`、`project.create`。
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index acc04f3ee..9eb6219f1 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -428,6 +428,7 @@
| D236 | 每个数据目录只允许一个桌面实例 | **Electron 主进程在模块求值期间调用 `app.requestSingleInstanceLock()` —— 在 `app.setName` 之后(锁位于由应用名派生的 `userData` 路径下),且在 logger、持久化 outbox 或任何其他数据目录访问之前。没有拿到锁的启动直接调用 `app.quit()` 且不引导任何东西:readiness 与 `before-quit` 处理器都提前返回,因此它不会在运行中实例的数据目录内创建窗口、托盘、子进程或日志行。持有锁的实例通过与托盘“显示”操作相同的路径响应 `second-instance`,恢复并聚焦主窗口,若窗口已关闭或隐藏到托盘则重新创建。只有在未设置 `PI_DESKTOP_DATA_DIR` 时才请求该锁,因此 E2E 测试装置、截图装置和有意并行的 profile 保持原有的随时启动行为。IPC 通道、宿主协议和存储架构均未变化。** | 第二次启动会引导出一个完整的第二份应用:在单写者 `pi.sqlite`(D002)上再开一个 host-core,在同一目录下再建一份 outbox 和日志树,再加一个托盘、一次启动器快捷键注册和一个更新器,导致两个 shell 在同一个数据库上出现分歧。再次启动应用是想看到已经在运行的那一个,把锁的作用域限定在安装本身也让使用独立数据目录的运行仍可启动(ADR 0094)。 |
| D367 | 宿主拥有的插件会话导入与归属 API | **`pi.session` 增加 `import`、`importBatch`、`list`、`get`、`listMessages`、`rename`、`delete`;每个来源必须声明 `contributes.sessionSources`;host-core 生成 id,并把所有操作限定在 `(pluginId, source, externalId)` 归属内;导入永不激活项目/provider/模型绑定。Schema v14 增加 `session_import_origins` 与 `sessions.deleted_at`;协议 v11 不变。回收站保留转录,仅属主可清除。** | 外部历史插件需要持久的导入/读取/更新/删除,而进行中的 `session.getLlmContext` 与核心 `session.import` 边界不是安全的插件归属边界(ADR 0200,E2E-214 / E2E-215) |
| D368 | 显式插件项目 id 与宿主拥有的会话刷新 | **受权限门控的 `pi.project.create({ path })` 创建或复用项目并返回宿主生成的 id,不激活工作区;导入项可绑定已有 `projectId`,省略则保持未绑定,历史来源路径永不成为工具根。Electron main 在插件导入、重命名、删除成功后发出 `pi-desktop/session/event/changed`;渲染器复用 `refreshSessions()`,跳过的导入不发事件,已关闭的项目标签不会重新打开。** | 向插件暴露 `workspace.set` 会改变用户的活动工作区,且插件写入需要宿主拥有的渲染器刷新路径(ADR 0201,E2E-216) |
+| D680 | 插件会话作用域:`.all` 权限与消息级写入 | **`pi.session` 增加 `session.read.all`、`session.update.all`、`session.delete.all`,让 `list`/`get`/`listMessages`、`rename`、`delete` 覆盖所有活动会话,而不再只限于本插件导入的会话。`.all` 是与 `.own` 并列的独立授权,不会放宽 `.own`;两者都声明时 `.all` 生效。Electron main 按授权解析作用域并把 `scope` 发给 host-core,host-core 只执行收到的那个值,缺省视为 `own`;`list` 改为对来源边表做 `LEFT JOIN`,`get` 与消息返回真实的 `originKind`、`source`、`externalId`、模型绑定与 `origin`,而不是导入投影,`trash`/`purge` 语句按作用域而不是内嵌 `EXISTS` 执行。消息级写入首次开放:`appendMessage`/`replaceMessages`(`session.update.all`)与 `deleteMessage`/`truncateFrom`(`session.delete.all`),复用既有 host-core 记录操作,回合运行期间以 `TURN_RUNNING` 拒绝改写,并共用每分钟 60 次预算。`rename` 改为占用手动标题来源。每次会话调用都会审计其授权作用域;`sessionsChanged` 会带上变更的会话 id。** | ADR 0200 的归属过滤让「读取用户自己的会话」这一合法能力无法表达,ADR 0323 因此不得不另造一个更窄的标题权限,ADR 0333 已交付的建议流程也读不到它所在的会话;直接放宽 `.own` 则会在用户不知情的情况下放大其审核过的「仅本插件导入的会话」授权(ADR 0339) |
| D370 | 桌面操作的本地 MCP 控制平面 | *(由 D372 修订)* **Electron Main 内可选启用的 Streamable HTTP MCP 服务器绑定 `127.0.0.1`,用持久随机 bearer token 认证,按回环主机名校验 Origin,写入受模式限制的连接清单,并委托给渲染器使用的同一组已注册 IPC 处理器。命名工具覆盖项目/会话/Agent 流程;`pi_desktop_invoke` 可达带风险标记的操作目录;危险操作需要 `confirm: true`;成功的外部变更复用渲染器会话变更事件。仅本地且启动时失败软着陆。** | 外部 Agent 需要驱动运行中的桌面,又不能有第二套权限或持久化实现,也不能触碰推迟的远程 Gateway / WebUI 边界(ADR 0203,E2E-220) |
| D372 | 收紧本地 MCP 控制平面边界 | **修订 D370 / ADR 0203:首版目录为项目/会话/Agent/工作区流程加已审阅的读取;剥离秘密形态的参数;`session/configure` 视为危险;监听地址断言为回环;协议版本协商而非回显;包含 `structuredContent` 的结果有界;渲染器会话刷新仅限变更操作。** | 首版目录仍暴露原生选择器、写秘密的 provider/OAuth/MCP 路径与未确认的 `session/configure`,并把会话读取当作渲染器变更(E2E-220) |
| D377 | 插件桌面控制需要原生用户同意 | **通过 `pi.desktop.invoke` 调用的 `dangerous` 桌面操作,需要插件给出 `confirm: true`,然后由用户在宿主拥有的原生对话框中作答;该对话框只显示目录中的操作 id、描述和有界的参数预览;关闭对话框、拒绝,以及没有对话框服务的宿主都以 `PERMISSION_DENIED` 失败。`read`/`write` 操作与 MCP 契约(D372)不变。** | 控制器的 `confirm` 标志由调用方设置,因此插件(或其背后的模型)可以在没有人参与的情况下删除会话或把会话切到 `auto`,而任何由插件绘制的确认卡片都可能被提示注入的成绩单改换标签(ADR 0208,E2E-236) |
@@ -5688,3 +5689,34 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
- `pnpm test:e2e:startup-animation` 用生成的 VP9 片段启动真实应用,断言源码检查无法
覆盖的部分:Chromium 能在页面 CSP 下解码经 `pi-startup:` 提供的字节、播放会推进、
渐显会交出可交互的主界面,以及不可播放的文件会在约一秒内交出主界面而不是占住窗口。
+
+## 2026-10-20 —— 插件会话作用域:`.all` 权限与消息级写入(D680)
+
+- D680 / ADR 0339 把 `pi.session` 从 ADR 0200 的导入归属边界扩开。三个新权限
+ `session.read.all`、`session.update.all`、`session.delete.all` 让既有动词覆盖
+ 所有活动会话,包括用户在本应用中自己创建的对话。
+- `.all` 是新增而非放宽:已安装插件保留其用户审核过的可达范围;清单可同时声明
+ 两者,此时 `.all` 生效。
+- 归属判断不再是隐式的第二权限:Electron main 依据授权解析作用域并下发,
+ host-core 只执行收到的值,缺省按 `own`,未知值以 `INVALID_PARAMS` 拒绝。
+- 修正了只因边界过窄才能工作的查询:`list` 对来源边表做 `LEFT JOIN`,`get` 与
+ 消息返回真实的 `originKind`/`source`/`externalId`/模型绑定/`origin`,`trash` 与
+ `purge` 语句按作用域而非内嵌 `EXISTS` 执行。
+- 首次开放消息级写入:`appendMessage`、`replaceMessages`(`session.update.all`)
+ 与 `deleteMessage`、`truncateFrom`(`session.delete.all`),复用 host-core 记录
+ 操作,因此修订归档、inflight 检查点与 JSONL 重写路径保持不变。
+- 回合运行期间以 `TURN_RUNNING` 拒绝改写;`appendMessage` 例外,因为追加正是
+ 回合写入自身行的方式。
+- `rename` 占用手动标题来源,已安装的 `session.autoTitle` 插件之后无法覆盖用户
+ 插件选定的标题。
+- 每次会话调用都会审计其授权作用域;此前 `list`/`get`/`listMessages`/`rename`/
+ `delete` 完全没有审计记录。
+- `sessionsChanged` 会带上变更的 `sessionId`,当该会话正是当前打开的会话且没有
+ 回合在跑时,外壳会重新读取转录以重绘。
+- 未改动:`.own` 语义、导入契约与其限额、`session.autoTitle` 边界、数据库
+ schema 与持久化格式。删除限流仍为每分钟 20 次;四个消息写入共用每分钟 60 次。
+- 覆盖:host-core 的 `plugin_sessions` 与 `plugin_session` 测试、
+ `apps/desktop/test/plugin-session-access.test.mjs`、
+ `apps/desktop/test/plugin-session-api.test.mjs`。见 ADR 0339、ADR 0200 修订、
+ ADR 0323 更正后的备选方案、`03-plugin-api.md` §插件拥有与全量会话、
+ `13-plugin-permissions-matrix.md` 第 2 节与 E2E-268。
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 07d3f3ddc..c93a1bf2b 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -2514,7 +2514,10 @@ sklm: {
"bus.subscribe": "Nachrichten von anderen Plugins empfangen",
"browser.cdp": "Den Arbeitspanel-Browser steuern",
"usage.read": "Nutzungsstatistiken lesen",
- "session.autoTitle": "Kontext des ersten Durchlaufs lesen und automatische Titel ändern"
+ "session.autoTitle": "Kontext des ersten Durchlaufs lesen und automatische Titel ändern",
+ "session.read.all": "Beliebige Unterhaltungen lesen, auch deine eigenen",
+ "session.update.all": "Beliebige Unterhaltungen umschreiben, auch ihre Nachrichten",
+ "session.delete.all": "Beliebige Unterhaltungen löschen, auch deine eigenen",
},
"permissionHelp": {
"ui.panel": "Lässt das Plugin sein eigenes Panel innerhalb der App anzeigen.",
@@ -2560,6 +2563,12 @@ sklm: {
"Listet Nutzungsdaten abgeschlossener Runden auf (Token-Zähler pro Runde, seitenweise). Nachrichteninhalte sind nicht enthalten.",
"session.autoTitle":
"Kann nur die erste Eingabe und Antwort geeigneter Sitzungen lesen und den Titel ändern, sofern er nicht manuell geändert wurde. Das vollständige Transkript bleibt unzugänglich.",
+ "session.read.all":
+ "Kann alle Sitzungen auflisten und Titel, Projekt, Modell sowie den vollständigen Nachrichtenverlauf lesen, auch die Unterhaltungen, die du selbst erstellt hast. Es kann nichts ändern.",
+ "session.update.all":
+ "Kann jede Sitzung umbenennen und ihre Nachrichten anhängen, ersetzen oder entfernen. Es schreibt den gespeicherten Verlauf neu, sodass sich eine Unterhaltung auch ohne deine Nachricht ändern kann.",
+ "session.delete.all":
+ "Kann jede Sitzung in den Papierkorb verschieben oder endgültig löschen, zusammen mit ihren Verlaufsdateien. Ratenbegrenzt, ansonsten unbeschränkt.",
}
},
"extensions": {
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 615a82399..c5c0eae8b 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -2536,6 +2536,9 @@ importConfirm: "Imported extensions run inside the agent process with the same a
"browser.cdp": "Control the work-panel browser",
"usage.read": "Read usage statistics",
"session.autoTitle": "Read first-turn title context and update automatic titles",
+ "session.read.all": "Read any conversation, including yours",
+ "session.update.all": "Rewrite any conversation, including its messages",
+ "session.delete.all": "Delete any conversation, including yours",
},
permissionHelp: {
"ui.panel": "Lets the plugin show its own panel inside the app.",
@@ -2598,6 +2601,12 @@ importConfirm: "Imported extensions run inside the agent process with the same a
"Lists completed-turn usage facts (paginated token counters and session titles). No message content is included.",
"session.autoTitle":
"Can read only the first prompt and reply for eligible sessions, then replace an automatic title if it has not been manually changed. It cannot read the full transcript.",
+ "session.read.all":
+ "Can list every session and read its title, project, model, and full message history, including the conversations you created yourself. It cannot change anything.",
+ "session.update.all":
+ "Can rename any session and append, replace, or remove its messages. It rewrites the stored transcript, so a conversation can change without you sending a message.",
+ "session.delete.all":
+ "Can move any session to the trash or delete it permanently, together with its transcript files. Rate-limited, but otherwise unrestricted.",
},
},
/**
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 364aaa259..ce43ea6e5 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -2514,7 +2514,10 @@ sklm: {
"bus.subscribe": "Recibir mensajes de otros complementos",
"browser.cdp": "Controlar el navegador del panel de trabajo",
"usage.read": "Leer estadísticas de uso",
- "session.autoTitle": "Leer el contexto del primer turno y actualizar títulos automáticos"
+ "session.autoTitle": "Leer el contexto del primer turno y actualizar títulos automáticos",
+ "session.read.all": "Leer cualquier conversación, incluidas las tuyas",
+ "session.update.all": "Reescribir cualquier conversación, incluidos sus mensajes",
+ "session.delete.all": "Eliminar cualquier conversación, incluidas las tuyas",
},
"permissionHelp": {
"ui.panel": "Permite que el complemento muestre su propio panel dentro de la aplicación.",
@@ -2560,6 +2563,12 @@ sklm: {
"Enumera los datos de uso de los turnos completados (contadores de tokens por turno, paginados). No incluye el contenido de los mensajes.",
"session.autoTitle":
"Solo puede leer el primer mensaje y la primera respuesta de las sesiones aptas y actualizar el título si nadie lo cambió manualmente. No puede leer la transcripción completa.",
+ "session.read.all":
+ "Puede listar todas las sesiones y leer su título, proyecto, modelo e historial completo de mensajes, incluidas las conversaciones que creaste tú. No puede modificar nada.",
+ "session.update.all":
+ "Puede renombrar cualquier sesión y añadir, reemplazar o eliminar sus mensajes. Reescribe el historial almacenado, así que una conversación puede cambiar sin que envíes un mensaje.",
+ "session.delete.all":
+ "Puede mover cualquier sesión a la papelera o eliminarla de forma permanente, junto con sus archivos de historial. Con límite de frecuencia, pero sin más restricciones.",
}
},
"extensions": {
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 9f6c303e5..e4a7bd292 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -2514,7 +2514,10 @@ sklm: {
"bus.subscribe": "Recevoir des messages d'autres plugins",
"browser.cdp": "Contrôler le navigateur du panneau de travail",
"usage.read": "Lire les statistiques d'utilisation",
- "session.autoTitle": "Lire le contexte du premier tour et modifier les titres automatiques"
+ "session.autoTitle": "Lire le contexte du premier tour et modifier les titres automatiques",
+ "session.read.all": "Lire n'importe quelle conversation, y compris les vôtres",
+ "session.update.all": "Réécrire n'importe quelle conversation, y compris ses messages",
+ "session.delete.all": "Supprimer n'importe quelle conversation, y compris les vôtres",
},
"permissionHelp": {
"ui.panel": "Permet au plugin d'afficher son propre panneau dans l'application.",
@@ -2560,6 +2563,12 @@ sklm: {
"Liste les données d'utilisation des tours terminés (compteurs de tokens par tour, paginés). Aucun contenu de message n'est inclus.",
"session.autoTitle":
"Peut lire uniquement le premier message et la première réponse des sessions admissibles, puis modifier le titre s'il n'a pas été changé manuellement. Ne peut pas lire la transcription complète.",
+ "session.read.all":
+ "Peut lister toutes les sessions et lire leur titre, projet, modèle et historique complet des messages, y compris les conversations que vous avez créées. Il ne peut rien modifier.",
+ "session.update.all":
+ "Peut renommer n'importe quelle session et ajouter, remplacer ou supprimer ses messages. Il réécrit l'historique stocké : une conversation peut donc changer sans que vous envoyiez un message.",
+ "session.delete.all":
+ "Peut déplacer n'importe quelle session dans la corbeille ou la supprimer définitivement, avec ses fichiers d'historique. Limité en fréquence, mais sans autre restriction.",
}
},
"extensions": {
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 62cb57500..9ab97e7b3 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -2532,6 +2532,9 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
"browser.cdp": "작업 패널 브라우저 제어",
"usage.read": "사용량 통계 읽기",
"session.autoTitle": "첫 턴 제목 맥락 읽기 및 자동 제목 업데이트",
+ "session.read.all": "모든 대화 읽기(직접 만든 대화 포함)",
+ "session.update.all": "모든 대화 재작성(메시지 수정 포함)",
+ "session.delete.all": "모든 대화 삭제(직접 만든 대화 포함)",
},
permissionHelp: {
"ui.panel": "플러그인이 앱 안에 자체 패널을 표시할 수 있습니다.",
@@ -2590,6 +2593,12 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
"완료된 턴의 사용량 팩트를 페이지별로 나열합니다(턴당 토큰 카운터). 메시지 내용은 포함되지 않습니다.",
"session.autoTitle":
"대상 세션의 첫 요청과 첫 답변만 읽고, 사용자가 직접 바꾸지 않은 경우에만 자동 제목을 업데이트할 수 있습니다. 전체 대화 기록은 읽을 수 없습니다.",
+ "session.read.all":
+ "모든 세션을 나열하고 제목, 프로젝트, 모델, 전체 메시지 기록을 읽을 수 있으며 사용자가 직접 만든 대화도 포함됩니다. 변경은 할 수 없습니다.",
+ "session.update.all":
+ "모든 세션의 이름을 바꾸고 메시지를 추가·교체·삭제할 수 있습니다. 저장된 기록을 다시 쓰므로 사용자가 메시지를 보내지 않아도 대화가 바뀔 수 있습니다.",
+ "session.delete.all":
+ "모든 세션을 휴지통으로 옮기거나 기록 파일과 함께 영구 삭제할 수 있습니다. 빈도 제한이 있을 뿐 그 밖의 제한은 없습니다.",
},
},
/**
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 81a32b845..87b10be56 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -2480,7 +2480,10 @@ export const ptBR = {
"bus.subscribe": "Receber mensagens de outros plugins",
"browser.cdp": "Controlar o navegador do painel de trabalho",
"usage.read": "Ler estatísticas de uso",
- "session.autoTitle": "Ler o contexto do primeiro turno e atualizar títulos automáticos"
+ "session.autoTitle": "Ler o contexto do primeiro turno e atualizar títulos automáticos",
+ "session.read.all": "Ler qualquer conversa, incluindo as suas",
+ "session.update.all": "Reescrever qualquer conversa, incluindo suas mensagens",
+ "session.delete.all": "Excluir qualquer conversa, incluindo as suas",
},
permissionHelp: {
"ui.panel": "Permite que o plugin exiba seu próprio painel no aplicativo.",
@@ -2525,6 +2528,12 @@ export const ptBR = {
"browser.cdp": "Pode navegar pelo navegador do painel de trabalho, ler páginas, executar JavaScript e enviar comandos permitidos do Chrome DevTools. Métodos de cookies e armazenamento são bloqueados.",
"usage.read": "Lista dados de uso de rodadas concluídas (contagens paginadas de tokens e títulos de sessões). Nenhum conteúdo das mensagens é incluído.",
"session.autoTitle": "Pode ler apenas a primeira solicitação e resposta de sessões elegíveis e atualizar o título se ele não tiver sido alterado manualmente. Não pode ler a transcrição completa.",
+ "session.read.all":
+ "Pode listar todas as sessões e ler título, projeto, modelo e histórico completo de mensagens, incluindo as conversas que você criou. Não pode alterar nada.",
+ "session.update.all":
+ "Pode renomear qualquer sessão e acrescentar, substituir ou remover suas mensagens. Reescreve o histórico armazenado, então uma conversa pode mudar sem você enviar uma mensagem.",
+ "session.delete.all":
+ "Pode mover qualquer sessão para a lixeira ou excluí-la definitivamente, junto com seus arquivos de histórico. Limitado por frequência, mas sem outras restrições.",
}
},
extensions: {
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index ec4f6b65c..cac9ac95a 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -2526,6 +2526,9 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
"browser.cdp": "Çalışma paneli tarayıcısını kontrol et",
"usage.read": "Kullanım istatistiklerini oku",
"session.autoTitle": "İlk tur başlık bağlamını oku ve otomatik başlıkları güncelle",
+ "session.read.all": "Sizin oluşturduklarınız dahil her sohbeti oku",
+ "session.update.all": "Sizin oluşturduklarınız dahil her sohbeti, mesajlarıyla birlikte yeniden yaz",
+ "session.delete.all": "Sizin oluşturduklarınız dahil her sohbeti sil",
},
permissionHelp: {
"ui.panel": "Eklentinin uygulama içinde kendi panelini göstermesini sağlar.",
@@ -2584,6 +2587,12 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
"Tamamlanan turların kullanım verilerini sayfalı olarak listeler (tur başına token sayaçları). Mesaj içeriği dahil değildir.",
"session.autoTitle":
"Yalnızca uygun oturumların ilk istemini ve ilk yanıtını okuyabilir; başlık elle değiştirilmemişse otomatik başlığı günceller. Tam dökümü okuyamaz.",
+ "session.read.all":
+ "Tüm oturumları listeleyebilir; başlık, proje, model ve tam mesaj geçmişini okuyabilir — kendi oluşturduğunuz sohbetler dahil. Hiçbir şeyi değiştiremez.",
+ "session.update.all":
+ "Her oturumun adını değiştirebilir; mesajlarını ekleyebilir, değiştirebilir veya kaldırabilir. Kaydedilmiş geçmişi yeniden yazdığı için siz mesaj göndermeden de sohbet değişebilir.",
+ "session.delete.all":
+ "Her oturumu çöp kutusuna taşıyabilir veya geçmiş dosyalarıyla birlikte kalıcı olarak silebilir. Hız sınırı vardır, bunun dışında kısıtlama yoktur.",
},
},
/**
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 6d72b69c5..7aa3ff00a 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -2509,6 +2509,9 @@ sklm: {
"browser.cdp": "控制工作面板浏览器",
"usage.read": "读取用量统计",
"session.autoTitle": "读取首轮标题上下文并更新自动标题",
+ "session.read.all": "读取任意会话,包括你自己的对话",
+ "session.update.all": "改写任意会话,包括修改其消息",
+ "session.delete.all": "删除任意会话,包括你自己的对话",
},
permissionHelp: {
"ui.panel": "允许插件在应用内显示独立面板。",
@@ -2557,6 +2560,12 @@ sklm: {
"分页列出已完成回合的用量事实(每回合 token 计数与会话标题)。不包含任何消息内容。",
"session.autoTitle":
"只能读取符合条件会话的首条提示和首条回复,并仅在标题未被手动修改时更新;不能读取完整会话记录。",
+ "session.read.all":
+ "可以列出全部会话并读取其标题、项目、模型与完整消息记录,包括你自己创建的对话。但不能修改任何内容。",
+ "session.update.all":
+ "可以重命名任意会话,并追加、替换或删除其消息。它会重写已存储的会话记录,因此无需你发送消息也能改变对话内容。",
+ "session.delete.all":
+ "可以把任意会话移入回收站或永久删除,并同时删除其记录文件。受频率限制,除此之外不受其他限制。",
},
},
extensions: {
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 4a5e77068..0d50df4e0 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -2509,6 +2509,9 @@ sklm: {
"browser.cdp": "控制工作面板瀏覽器",
"usage.read": "讀取用量統計",
"session.autoTitle": "讀取首輪標題內容並更新自動標題",
+ "session.read.all": "讀取任意工作階段,包括你自己的對話",
+ "session.update.all": "改寫任意工作階段,包括修改其訊息",
+ "session.delete.all": "刪除任意工作階段,包括你自己的對話",
},
permissionHelp: {
"ui.panel": "允許外掛在應用內顯示獨立面板。",
@@ -2556,6 +2559,12 @@ sklm: {
"分頁列出已完成回合的用量事實(每回合的 token 計數)。不包含任何訊息內容。",
"session.autoTitle":
"僅能讀取符合條件工作階段的首則提示和首則回覆,並只在標題未被手動修改時更新;無法讀取完整對話記錄。",
+ "session.read.all":
+ "可以列出全部工作階段並讀取其標題、專案、模型與完整訊息記錄,包括你自己建立的對話。但不能修改任何內容。",
+ "session.update.all":
+ "可以重新命名任意工作階段,並附加、替換或刪除其訊息。它會重寫已儲存的工作階段記錄,因此無需你送出訊息也能改變對話內容。",
+ "session.delete.all":
+ "可以把任意工作階段移入回收筒或永久刪除,並同時刪除其記錄檔案。受頻率限制,除此之外不受其他限制。",
},
},
extensions: {
diff --git a/packages/plugin-devkit/src/check.ts b/packages/plugin-devkit/src/check.ts
index 3ce105155..070b6a60f 100644
--- a/packages/plugin-devkit/src/check.ts
+++ b/packages/plugin-devkit/src/check.ts
@@ -45,6 +45,9 @@ export const HIGH_RISK_PERMISSIONS = [
"session.autoTitle",
"session.import",
"session.delete.own",
+ "session.read.all",
+ "session.update.all",
+ "session.delete.all",
"mcp.server.local",
"mcp.server.remote",
"browser.cdp",
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index 1d70c45a9..2ce290023 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -391,7 +391,8 @@ export type PluginSessionListItem = {
sessionId: string;
title: string;
source: string;
- externalId: string;
+ /** The import source's id; `null` for a session this plugin did not import. */
+ externalId: string | null;
projectId: number | null;
messageCount: number;
originKind: "imported" | "created";
@@ -408,8 +409,8 @@ export type PluginSessionListResult = {
export type PluginSessionGetResult = {
sessionId: string;
title: string;
- source: string;
- externalId: string;
+ /** The import source's id; `null` for a session this plugin did not import. */
+ externalId: string | null;
originKind: "imported" | "created";
projectId: number | null;
projectPath: string | null;
@@ -472,7 +473,8 @@ export type PluginSessionMessageResult = {
content: string;
contentTruncated?: boolean;
createdAt: string;
- origin: "external";
+ /** `external` for imported history, `desktop` for a host-created session. */
+ origin: "external" | "desktop";
tool?: {
name: string;
callId: string;
@@ -487,6 +489,49 @@ export type PluginSessionMessageListResult = {
nextCursor?: string;
};
+/**
+ * One message a plugin writes (`session.update.all`). The `id` is optional:
+ * the host generates one when it is absent, and a supplied id makes a retried
+ * write idempotent instead of appending the row twice.
+ */
+export type PluginSessionMessageInput = {
+ id?: string;
+ role: "user" | "assistant" | "tool";
+ content: string;
+ /** Monotonic RFC3339 within one call, newest last. */
+ createdAt: string;
+ modelId?: string;
+ providerId?: string;
+ toolName?: string;
+ toolCallId?: string;
+ toolStatus?: "success" | "error";
+ toolArgs?: unknown;
+ toolResult?: unknown;
+};
+
+/** Result of `pi.session.appendMessage`. */
+export type PluginSessionAppendResult = {
+ messageId: string;
+};
+
+/** Result of `pi.session.replaceMessages`. */
+export type PluginSessionReplaceResult = {
+ /** Rows the rewritten transcript now holds. */
+ messageCount: number;
+};
+
+/** Result of `pi.session.deleteMessage`; a missing target is a no-op, not an error. */
+export type PluginSessionDeleteMessageResult = {
+ deleted: boolean;
+ deletedCount: number;
+};
+
+/** Result of `pi.session.truncateFrom`. */
+export type PluginSessionTruncateResult = {
+ keptCount: number;
+ discardedCount: number;
+};
+
/** Resolve a plugin label using the active PI-Desktop locale. */
export function resolvePluginLocalizedString(
value: string | PluginLocalizedString | undefined,
@@ -1467,6 +1512,37 @@ export type PluginHostApi = {
sessionId: string;
mode?: "trash" | "purge";
}) => Promise<{ deleted: boolean }>;
+ /**
+ * Message-level writes. Each one needs `session.update.all` and rewrites the
+ * live transcript, so the host refuses while a turn owns the session
+ * (`TURN_RUNNING`) and rate-limits the whole group.
+ */
+ appendMessage: (input: {
+ sessionId: string;
+ message: PluginSessionMessageInput;
+ }) => Promise<PluginSessionAppendResult>;
+ replaceMessages: (input: {
+ sessionId: string;
+ /** At most 2,000 entries; the whole live transcript is rewritten. */
+ messages: PluginSessionMessageInput[];
+ }) => Promise<PluginSessionReplaceResult>;
+ /**
+ * Delete one message, or — when it is a user prompt — that prompt and its
+ * replies. Needs `session.delete.all`; a missing target is a no-op.
+ */
+ deleteMessage: (input: {
+ sessionId: string;
+ messageId: string;
+ }) => Promise<PluginSessionDeleteMessageResult>;
+ /**
+ * Keep the prefix before `fromMessageId` (or the first `keepCount` messages)
+ * and discard the rest. Needs `session.delete.all`.
+ */
+ truncateFrom: (input: {
+ sessionId: string;
+ fromMessageId?: string;
+ keepCount?: number;
+ }) => Promise<PluginSessionTruncateResult>;
};
/**
* Read-only completed-turn facts served by the host (`usage.read`). Flat
@@ -1620,6 +1696,13 @@ export const PLUGIN_PERMISSIONS = [
"session.read.own",
"session.update.own",
"session.delete.own",
+ // The `.all` family (ADR 0339): the same three verbs over every live session,
+ // including the user's own conversations. A separate grant rather than a
+ // wider `.own`, so an existing install never silently gains reach. `all` wins
+ // when a manifest declares both.
+ "session.read.all",
+ "session.update.all",
+ "session.delete.all",
"session.autoTitle",
// Read-only usage facts (pi.usage.listTurns):
// completed-turn counters and session titles, never message bodies.