From 3d02b28c7f6d28dc28175b45c157593bd0f12535 Mon Sep 17 00:00:00 2001
From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com>
Date: Sun, 25 Oct 2026 06:25:06 +0530
Subject: [PATCH 1/8] Approvals that learn: suggest allow rules for actions you
keep approving
After 5+ unedited approvals of a tool (and no denial or edit in its last 10
decisions), Synapse offers an ordinary allow rule. Recipients sharing one
non-public email domain become an allEndWith condition; a single repo,
project, channel or team becomes equals. Send and destructive tools are
never suggested tool-wide. Tainted runs still ask, as before.
- core: pure suggestRules() with stable ids, plus unit tests
- server: GET /api/policy/suggestions, POST :id/accept and :id/dismiss
- db: user_settings.dismissed_suggestions text[]
- web: suggestion strip in the inbox, a prompt under a fresh approval,
and a Learned pill on rules in settings
---
apps/server/src/app.ts | 2 +
apps/server/src/routes/suggestions.ts | 99 +
apps/server/src/server.test.ts | 85 +
apps/web/app/(app)/inbox/page.tsx | 5 +
apps/web/app/(app)/settings/policy-editor.tsx | 7 +-
.../web/components/approval/learned-rules.tsx | 153 ++
apps/web/components/task/task-view.tsx | 22 +-
apps/web/lib/api.ts | 4 +
apps/web/lib/suggestions.ts | 60 +
docs/api.md | 10 +
packages/core/src/index.ts | 1 +
packages/core/src/suggest.test.ts | 209 ++
packages/core/src/suggest.ts | 222 ++
packages/db/drizzle/0004_learned_rules.sql | 1 +
packages/db/drizzle/meta/0004_snapshot.json | 1982 +++++++++++++++++
packages/db/drizzle/meta/_journal.json | 7 +
packages/db/src/schema.ts | 2 +
17 files changed, 2861 insertions(+), 10 deletions(-)
create mode 100644 apps/server/src/routes/suggestions.ts
create mode 100644 apps/web/components/approval/learned-rules.tsx
create mode 100644 apps/web/lib/suggestions.ts
create mode 100644 packages/core/src/suggest.test.ts
create mode 100644 packages/core/src/suggest.ts
create mode 100644 packages/db/drizzle/0004_learned_rules.sql
create mode 100644 packages/db/drizzle/meta/0004_snapshot.json
diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts
index f6c99b3..725ee2c 100644
--- a/apps/server/src/app.ts
+++ b/apps/server/src/app.ts
@@ -8,6 +8,7 @@ import { clientMetadataDocument, connections, oauthCallback } from "./routes/con
import { googleCallback, integrations } from "./routes/integrations";
import { models } from "./routes/models";
import { approvals, runs } from "./routes/runs";
+import { suggestions } from "./routes/suggestions";
import type { Services } from "./services";
export function createApp(services: Services) {
@@ -65,6 +66,7 @@ export function createApp(services: Services) {
api.route("/connections", connections);
api.route("/integrations/google/callback", googleCallback);
api.route("/integrations", integrations);
+ api.route("/policy/suggestions", suggestions);
api.route("/policy", policy);
api.route("/memories", memories);
api.route("/documents", documents);
diff --git a/apps/server/src/routes/suggestions.ts b/apps/server/src/routes/suggestions.ts
new file mode 100644
index 0000000..48c8779
--- /dev/null
+++ b/apps/server/src/routes/suggestions.ts
@@ -0,0 +1,99 @@
+import { type PastDecision, SUGGEST_LOOKBACK_DAYS, suggestRules } from "@synapse/core";
+import { PgRunStore, schema } from "@synapse/db";
+import { and, desc, eq, gte, isNotNull, ne, sql } from "drizzle-orm";
+import { Hono } from "hono";
+import { type AppEnv, apiError } from "../http";
+
+type Ctx = { var: AppEnv["Variables"] };
+
+/** Learned rules: offer an allow rule for actions the user keeps approving unchanged. */
+export const suggestions = new Hono()
+ .get("/", async (c) => {
+ const { suggestions } = await load(c);
+ return c.json({ suggestions });
+ })
+ .post("/:id/accept", async (c) => {
+ const { suggestions, store } = await load(c);
+ const s = suggestions.find((x) => x.id === c.req.param("id"));
+ if (!s) apiError(404, "not_found", "Suggestion not found.");
+ const { db } = c.var.services.database;
+ const userId = c.var.user.id;
+ // First among allow/ask rules so it takes effect; block rules still win regardless.
+ await db.transaction(async (tx) => {
+ await tx
+ .update(schema.policyRules)
+ .set({ position: sql`${schema.policyRules.position} + 1` })
+ .where(eq(schema.policyRules.userId, userId));
+ await tx.insert(schema.policyRules).values({
+ userId,
+ position: 0,
+ tool: s.tool,
+ decision: "allow",
+ when: s.when.length > 0 ? s.when : null,
+ note: s.note,
+ });
+ });
+ return c.json(await store.getPolicy(userId));
+ })
+ .post("/:id/dismiss", async (c) => {
+ const id = c.req.param("id");
+ const { suggestions, dismissed } = await load(c);
+ if (!suggestions.some((x) => x.id === id) && !dismissed.includes(id))
+ apiError(404, "not_found", "Suggestion not found.");
+ // Keep the list bounded; the oldest dismissals fall off first.
+ const next = [...dismissed.filter((d) => d !== id), id].slice(-200);
+ await c.var.services.database.db
+ .insert(schema.userSettings)
+ .values({ userId: c.var.user.id, dismissedSuggestions: next })
+ .onConflictDoUpdate({
+ target: schema.userSettings.userId,
+ set: { dismissedSuggestions: next },
+ });
+ return c.body(null, 204);
+ });
+
+async function load(c: Ctx) {
+ const { db } = c.var.services.database;
+ const userId = c.var.user.id;
+ const since = new Date(Date.now() - SUGGEST_LOOKBACK_DAYS * 24 * 3600_000);
+ const rows = await db
+ .select({
+ tool: schema.toolCalls.name,
+ effect: schema.toolCalls.effect,
+ input: schema.toolCalls.input,
+ inputEdited: schema.toolCalls.inputEdited,
+ status: schema.toolCalls.status,
+ decidedAt: schema.toolCalls.decidedAt,
+ preview: schema.toolCalls.preview,
+ })
+ .from(schema.toolCalls)
+ .where(
+ and(
+ eq(schema.toolCalls.userId, userId),
+ // Human decisions only; auto-allowed calls carry no decider.
+ eq(schema.toolCalls.decidedBy, userId),
+ isNotNull(schema.toolCalls.decidedAt),
+ gte(schema.toolCalls.decidedAt, since),
+ ne(schema.toolCalls.effect, "read"),
+ ),
+ )
+ .orderBy(desc(schema.toolCalls.decidedAt))
+ .limit(2000);
+ const decisions: PastDecision[] = rows.map((r) => ({
+ tool: r.tool,
+ effect: r.effect,
+ input: r.input,
+ inputEdited: r.inputEdited,
+ approved: r.status !== "denied",
+ decidedAt: r.decidedAt!,
+ preview: r.preview,
+ }));
+ const store = new PgRunStore(db);
+ const policy = await store.getPolicy(userId);
+ const [settings] = await db
+ .select({ dismissed: schema.userSettings.dismissedSuggestions })
+ .from(schema.userSettings)
+ .where(eq(schema.userSettings.userId, userId));
+ const dismissed = settings?.dismissed ?? [];
+ return { suggestions: suggestRules(decisions, policy.rules, dismissed), dismissed, store };
+}
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 8c2eddb..65c7334 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -2,6 +2,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
import type { SeqEvent } from "@synapse/core";
import { type ScriptedStep, scriptedModel } from "@synapse/core/testing";
import { schema } from "@synapse/db";
+import { eq } from "drizzle-orm";
import { createApp } from "./app";
import { loadConfig } from "./config";
import { createServices, type Services } from "./services";
@@ -437,3 +438,87 @@ test("model list covers the catalog, direct refs and the chain, with availabilit
clearCatalog();
}
});
+
+test("approvals that learn: suggest, accept, dismiss", async () => {
+ const me = api(await signUp("learner@example.com"));
+ const other = api(await signUp("bystander@example.com"));
+ const askForNotes = {
+ defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" },
+ rules: [{ tool: "memory_save", decision: "ask" }],
+ };
+ await me("/api/policy", { method: "PUT", json: askForNotes });
+ await other("/api/policy", { method: "PUT", json: askForNotes });
+
+ let n = 0;
+ async function startNote(who: typeof me, opts: { tainted?: boolean } = {}) {
+ const id = `learn${++n}`;
+ script([
+ { toolCalls: [{ name: "memory_save", input: { note: `fact ${n}` }, id }] },
+ { text: "Noted." },
+ ]);
+ const { json } = await who("/api/chats", { method: "POST", json: { content: "remember" } });
+ const runId = json!.runId as string;
+ if (opts.tainted)
+ await services.database.db
+ .update(schema.runs)
+ .set({ tainted: true })
+ .where(eq(schema.runs.id, runId));
+ await worker.processNow(runId);
+ return { runId, id };
+ }
+ async function approveNote(who: typeof me) {
+ const { runId, id } = await startNote(who);
+ const res = await who(`/api/runs/${runId}/tool-calls/${id}/decision`, {
+ method: "POST",
+ json: { approved: true },
+ });
+ expect(res.status).toBe(204);
+ await worker.processNow(runId);
+ }
+
+ for (let i = 0; i < 4; i++) await approveNote(me);
+ expect((await me("/api/policy/suggestions")).json!.suggestions).toEqual([]);
+ await approveNote(me);
+ const [s] = (await me("/api/policy/suggestions")).json!.suggestions;
+ expect(s).toMatchObject({ tool: "memory_save", effect: "write", count: 5, when: [] });
+ expect(s.sentence).toContain("You approved 5");
+ expect((await other("/api/policy/suggestions")).json!.suggestions).toEqual([]);
+
+ // Someone else can neither accept nor dismiss it.
+ const accept = `/api/policy/suggestions/${s.id}/accept`;
+ const dismiss = `/api/policy/suggestions/${s.id}/dismiss`;
+ expect((await other(accept, { method: "POST" })).status).toBe(404);
+ expect((await other(dismiss, { method: "POST" })).status).toBe(404);
+
+ const accepted = await me(accept, { method: "POST" });
+ expect(accepted.status).toBe(200);
+ expect(accepted.json!.rules).toEqual([
+ expect.objectContaining({
+ tool: "memory_save",
+ decision: "allow",
+ note: "Learned: you approved 5 of these",
+ }),
+ expect.objectContaining({ tool: "memory_save", decision: "ask" }),
+ ]);
+ expect((await me("/api/policy")).json!.rules).toHaveLength(2);
+ expect((await me("/api/policy/suggestions")).json!.suggestions).toEqual([]);
+
+ // Untainted: allowed without asking. Tainted: still asks.
+ const clean = await startNote(me);
+ expect((await me(`/api/runs/${clean.runId}`)).json!.run.status).toBe("completed");
+ const tainted = await startNote(me, { tainted: true });
+ expect((await me(`/api/runs/${tainted.runId}`)).json!.run.status).toBe("waiting");
+ expect((await me("/api/approvals")).json!.approvals).toEqual([
+ expect.objectContaining({ runId: tainted.runId, name: "memory_save" }),
+ ]);
+
+ // Dismissing hides it, also after more approvals.
+ for (let i = 0; i < 5; i++) await approveNote(other);
+ const [o] = (await other("/api/policy/suggestions")).json!.suggestions;
+ expect(o.id).toBe(s.id);
+ expect((await other(dismiss, { method: "POST" })).status).toBe(204);
+ expect((await other("/api/policy/suggestions")).json!.suggestions).toEqual([]);
+ await approveNote(other);
+ expect((await other("/api/policy/suggestions")).json!.suggestions).toEqual([]);
+ expect((await other("/api/policy")).json!.rules).toHaveLength(1);
+});
diff --git a/apps/web/app/(app)/inbox/page.tsx b/apps/web/app/(app)/inbox/page.tsx
index cb3167b..5aa93a1 100644
--- a/apps/web/app/(app)/inbox/page.tsx
+++ b/apps/web/app/(app)/inbox/page.tsx
@@ -10,6 +10,7 @@ import {
approvalTitle,
MiniStamp,
} from "@/components/approval/approval-card";
+import { LearnPrompt, SuggestionStrip } from "@/components/approval/learned-rules";
import { Markdown } from "@/components/markdown";
import { EffectPill, Kbd, Monogram, Skeleton, StatusDot } from "@/components/ui";
import { type Approval, api } from "@/lib/api";
@@ -142,6 +143,7 @@ export default function InboxPage() {
+
{loading ? (
{[0, 1, 2].map((i) => (
@@ -285,6 +287,9 @@ export default function InboxPage() {
edited={decided[current.toolCallId]!.edited}
phase="continuing"
/>
+ {decided[current.toolCallId]!.approved && !decided[current.toolCallId]!.edited ? (
+
+ ) : null}
{pending.length === 0 ? (
diff --git a/apps/web/app/(app)/settings/policy-editor.tsx b/apps/web/app/(app)/settings/policy-editor.tsx
index 865b3b8..4dfa828 100644
--- a/apps/web/app/(app)/settings/policy-editor.tsx
+++ b/apps/web/app/(app)/settings/policy-editor.tsx
@@ -4,7 +4,7 @@ import type { ArgMatcher, Decision, Effect, PolicyDefaults, PolicyRule } from "@
import { GripVertical, Plus, ShieldAlert, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useToast } from "@/components/toast";
-import { EffectPill, ErrorNote, Segmented, Skeleton } from "@/components/ui";
+import { EffectPill, ErrorNote, Pill, Segmented, Skeleton } from "@/components/ui";
import { api, errorMessage, type Policy } from "@/lib/api";
import { cx, humanToolName } from "@/lib/format";
import { useApi } from "@/lib/use-api";
@@ -436,6 +436,11 @@ export function PolicyEditor({ prefillTool }: { prefillTool?: string | null }) {
/>
+ {r.note.startsWith("Learned:") ? (
+
+ Learned
+
+ ) : null}
{r.tool && !/[*?]/.test(r.tool) ? (
{humanToolName(r.tool)}
) : r.tool ? (
diff --git a/apps/web/components/approval/learned-rules.tsx b/apps/web/components/approval/learned-rules.tsx
new file mode 100644
index 0000000..ef706d1
--- /dev/null
+++ b/apps/web/components/approval/learned-rules.tsx
@@ -0,0 +1,153 @@
+"use client";
+
+import type { RuleSuggestion } from "@synapse/core";
+import { Check, LoaderCircle } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { useToast } from "@/components/toast";
+import { errorMessage } from "@/lib/api";
+import { cx } from "@/lib/format";
+import { acceptSuggestion, dismissSuggestion, useSuggestions } from "@/lib/suggestions";
+
+const RULES_HREF = "/settings?section=rules";
+const CAVEAT = "Tasks that read outside content still ask.";
+
+function useDecide() {
+ const toast = useToast();
+ const [busy, setBusy] = useState
(null);
+ async function run(id: string, accept: boolean) {
+ if (busy) return false;
+ setBusy(id);
+ try {
+ if (accept) await acceptSuggestion(id);
+ else await dismissSuggestion(id);
+ return true;
+ } catch (err) {
+ toast(errorMessage(err), "error");
+ return false;
+ } finally {
+ setBusy(null);
+ }
+ }
+ return { busy, run };
+}
+
+/** Inbox: a quiet note at the top when the user keeps approving the same kind of action. */
+export function SuggestionStrip({ className }: { className?: string }) {
+ const suggestions = useSuggestions();
+ const toast = useToast();
+ const { busy, run } = useDecide();
+ if (!suggestions?.length) return null;
+ return (
+
+ You keep approving these
+ Allow them automatically?
+
+ {suggestions.slice(0, 3).map((s) => (
+
+ {s.sentence}
+ {s.examples[0] ? (
+
+ {s.examples[0]}
+
+ ) : null}
+
+ {
+ if (await run(s.id, true)) toast(`Now allowed: ${s.label}`, "success");
+ }}
+ >
+ {busy === s.id ? (
+
+ ) : (
+
+ )}
+ Allow
+
+ void run(s.id, false)}
+ >
+ Not now
+
+
+
+ ))}
+
+
+ {CAVEAT}{" "}
+
+ Approval rules
+
+
+
+ );
+}
+
+/**
+ * Under a fresh approval: if that approval tipped a suggestion for this tool, offer it once.
+ * Mounted after the stamp settles, so it never competes with the stamp.
+ */
+export function LearnPrompt({ tool, className }: { tool: string; className?: string }) {
+ const suggestions = useSuggestions(tool);
+ const { busy, run } = useDecide();
+ const [done, setDone] = useState(null);
+ const s = suggestions?.find((x) => x.tool === tool);
+
+ if (done) {
+ return (
+
+ Done. {capitalize(done.label)} are now allowed. {CAVEAT}{" "}
+
+ Approval rules
+
+
+ );
+ }
+ if (!s) return null;
+ return (
+
+
+ Always allow {s.label}?
+
+
+ {
+ if (await run(s.id, true)) setDone(s);
+ }}
+ >
+ {busy === s.id ? : null}
+ Allow
+
+ void run(s.id, false)}
+ >
+ No thanks
+
+
+
+ );
+}
+
+function capitalize(s: string) {
+ return s ? `${s[0]!.toUpperCase()}${s.slice(1)}` : s;
+}
diff --git a/apps/web/components/task/task-view.tsx b/apps/web/components/task/task-view.tsx
index 0ffd69c..db5ebeb 100644
--- a/apps/web/components/task/task-view.tsx
+++ b/apps/web/components/task/task-view.tsx
@@ -7,6 +7,7 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { ApprovalCard, ApprovalReceipt } from "@/components/approval/approval-card";
+import { LearnPrompt } from "@/components/approval/learned-rules";
import { Menu } from "@/components/overlay";
import { useToast } from "@/components/toast";
import { EmptyState, Skeleton, StatusPill, TaintShield, taskStatus } from "@/components/ui";
@@ -229,15 +230,18 @@ export function TaskView({ taskId }: { taskId: string }) {
const d = decided[part.toolCallId];
if (d) {
return (
-
+ <>
+
+ {d.approved && !d.edited ? : null}
+ >
);
}
if (part.status !== "awaiting_approval" || !runId) {
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index f42b179..94b85f4 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -7,6 +7,7 @@ import type {
Effect,
PolicyDefaults,
PolicyRule,
+ RuleSuggestion,
RunStatus,
ToolCallStatus,
ToolOutput,
@@ -375,6 +376,9 @@ export const api = {
policy: () => get("/api/policy"),
savePolicy: (body: Policy) => put("/api/policy", body),
+ suggestions: () => get<{ suggestions: RuleSuggestion[] }>("/api/policy/suggestions"),
+ acceptSuggestion: (id: string) => post(`/api/policy/suggestions/${enc(id)}/accept`),
+ dismissSuggestion: (id: string) => post(`/api/policy/suggestions/${enc(id)}/dismiss`),
memories: () => get<{ memories: Memory[] }>("/api/memories"),
addMemory: (content: string) => post<{ memory: Memory }>("/api/memories", { content }),
diff --git a/apps/web/lib/suggestions.ts b/apps/web/lib/suggestions.ts
new file mode 100644
index 0000000..7984465
--- /dev/null
+++ b/apps/web/lib/suggestions.ts
@@ -0,0 +1,60 @@
+"use client";
+
+import type { RuleSuggestion } from "@synapse/core";
+import { useEffect, useSyncExternalStore } from "react";
+import { api } from "@/lib/api";
+
+/**
+ * Learned-rule suggestions, shared by the inbox strip and the prompt after an approval, so
+ * accepting in one place clears the other.
+ */
+let current: RuleSuggestion[] | null = null;
+const listeners = new Set<() => void>();
+let generation = 0;
+
+function set(next: RuleSuggestion[]) {
+ current = next;
+ for (const fn of listeners) fn();
+}
+
+export async function refreshSuggestions(): Promise {
+ const gen = ++generation;
+ try {
+ const { suggestions } = await api.suggestions();
+ // A later refresh (e.g. right after an approval) wins over an earlier one.
+ if (gen === generation) set(suggestions);
+ } catch {
+ // Suggestions are a nicety; keep the last known list.
+ }
+}
+
+export async function acceptSuggestion(id: string) {
+ const policy = await api.acceptSuggestion(id);
+ generation++;
+ set((current ?? []).filter((s) => s.id !== id));
+ void refreshSuggestions();
+ return policy;
+}
+
+export async function dismissSuggestion(id: string) {
+ await api.dismissSuggestion(id);
+ generation++;
+ set((current ?? []).filter((s) => s.id !== id));
+}
+
+/** The current suggestions; `refreshKey` refetches when it changes (and on mount). */
+export function useSuggestions(refreshKey: string | number = ""): RuleSuggestion[] | null {
+ const list = useSyncExternalStore(
+ (fn) => {
+ listeners.add(fn);
+ return () => listeners.delete(fn);
+ },
+ () => current,
+ () => null,
+ );
+ // biome-ignore lint/correctness/useExhaustiveDependencies: refreshKey is the trigger
+ useEffect(() => {
+ void refreshSuggestions();
+ }, [refreshKey]);
+ return list;
+}
diff --git a/docs/api.md b/docs/api.md
index 77dca7f..0812f6c 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -96,6 +96,16 @@ Gmail and Google Calendar, without an MCP server. Needs `GOOGLE_CLIENT_ID` and
|---|---|---|---|
| GET | `/api/policy` | | `{ defaults: PolicyDefaults, rules: PolicyRule[] }` |
| PUT | `/api/policy` | `{ defaults, rules }` (rules in priority order) | same |
+| GET | `/api/policy/suggestions` | | `{ suggestions: RuleSuggestion[] }` |
+| POST | `/api/policy/suggestions/:id/accept` | | `{ defaults, rules }` — adds the allow rule first; `404` if not a current suggestion |
+| POST | `/api/policy/suggestions/:id/dismiss` | | `204` — hidden for good |
+
+Suggestions ("approvals that learn") come from your own decisions on non-read actions over the
+last 60 days: at least 5 unedited approvals of a tool, and no denial or edit among its last 10
+decisions. Recipients that all share one (non-public) email domain become an `allEndWith`
+condition; a single `repo`/`project`/`channel`/`team` becomes `equals`. Sending and
+destructive tools are only suggested with a condition. Learned rules are ordinary rules; a
+task that read outside content still asks.
## Memory
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 1fa6e6b..f27b47d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -5,5 +5,6 @@ export * from "./policy";
export * from "./prices";
export * from "./runtime";
export type * from "./store";
+export * from "./suggest";
export * from "./tools";
export type * from "./types";
diff --git a/packages/core/src/suggest.test.ts b/packages/core/src/suggest.test.ts
new file mode 100644
index 0000000..e6ec693
--- /dev/null
+++ b/packages/core/src/suggest.test.ts
@@ -0,0 +1,209 @@
+import { describe, expect, test } from "bun:test";
+import type { JSONValue } from "ai";
+import { evaluatePolicy, type PolicyRule } from "./policy";
+import { type PastDecision, suggestionId, suggestRules } from "./suggest";
+import type { Effect } from "./types";
+
+let clock = Date.parse("2026-10-01T00:00:00Z");
+
+function decision(
+ tool: string,
+ effect: Effect,
+ input: JSONValue,
+ extra: Partial = {},
+): PastDecision {
+ clock += 60_000;
+ return {
+ tool,
+ effect,
+ input,
+ inputEdited: false,
+ approved: true,
+ decidedAt: new Date(clock),
+ preview: null,
+ ...extra,
+ };
+}
+
+const email = (to: string | string[], extra: Partial = {}) =>
+ decision("gmail_send", "send", { to, subject: "Hi", body: "…" }, extra);
+
+const times = (n: number, fn: (i: number) => T) => Array.from({ length: n }, (_, i) => fn(i));
+
+describe("suggestRules", () => {
+ test("needs five unedited approvals", () => {
+ const four = times(4, (i) => email(`p${i}@acme.com`));
+ expect(suggestRules(four, [])).toEqual([]);
+ const five = [...four, email("q@acme.com", { preview: "Email q@acme.com" })];
+ const [s] = suggestRules(five, []);
+ expect(s).toMatchObject({
+ tool: "gmail_send",
+ effect: "send",
+ count: 5,
+ when: [{ path: "to", op: "allEndWith", value: ["@acme.com"] }],
+ label: "emails to @acme.com",
+ sentence: "You approved 5 emails to @acme.com without changes.",
+ note: "Learned: you approved 5 of these",
+ });
+ expect(s!.examples[0]).toBe("Email q@acme.com");
+ expect(s!.examples.length).toBeLessThanOrEqual(3);
+ });
+
+ test("edited approvals don't count toward the total", () => {
+ const old = times(3, () => email("a@acme.com", { inputEdited: true }));
+ const recent = times(10, () => email("a@acme.com"));
+ expect(suggestRules([...old, ...recent], [])[0]!.count).toBe(10);
+ });
+
+ test("a recent denial or edit suppresses the suggestion", () => {
+ const base = times(8, () => email("a@acme.com"));
+ expect(suggestRules(base, [])).toHaveLength(1);
+ expect(suggestRules([...base, email("a@acme.com", { approved: false })], [])).toEqual([]);
+ expect(suggestRules([...base, email("a@acme.com", { inputEdited: true })], [])).toEqual([]);
+ });
+
+ test("a denial older than the last ten decisions no longer suppresses", () => {
+ const old = email("a@acme.com", { approved: false });
+ const later = times(10, () => email("a@acme.com"));
+ expect(suggestRules([old, ...later], [])).toHaveLength(1);
+ });
+
+ test("mixed domains give no domain matcher; a send tool then gets no suggestion", () => {
+ const list = [...times(4, () => email(["a@acme.com"])), email(["a@acme.com", "x@other.io"])];
+ expect(suggestRules(list, [])).toEqual([]);
+ });
+
+ test("public mail domains and optional recipient fields don't generalize", () => {
+ expect(
+ suggestRules(
+ times(6, (i) => email(`f${i}@gmail.com`)),
+ [],
+ ),
+ ).toEqual([]);
+ const someCc = times(6, (i) =>
+ decision("gmail_send", "send", {
+ to: "a@acme.com",
+ ...(i % 2 ? { cc: ["b@acme.com"] } : {}),
+ }),
+ );
+ expect(suggestRules(someCc, [])).toEqual([]);
+ });
+
+ test("every recipient field is constrained", () => {
+ const list = times(5, () =>
+ decision("gmail_send", "send", { to: "a@acme.com", cc: ["b@acme.com", "c@ACME.com"] }),
+ );
+ expect(suggestRules(list, [])[0]!.when).toEqual([
+ { path: "to", op: "allEndWith", value: ["@acme.com"] },
+ { path: "cc", op: "allEndWith", value: ["@acme.com"] },
+ ]);
+ });
+
+ test("a single repo or channel becomes an equals matcher", () => {
+ const list = times(5, (i) =>
+ decision("github_create_issue", "write", { repo: "acme/web", title: `Bug ${i}` }),
+ );
+ const [s] = suggestRules(list, []);
+ expect(s!.when).toEqual([{ path: "repo", op: "equals", value: "acme/web" }]);
+ expect(s!.label).toBe("github_create_issue actions in acme/web");
+ });
+
+ test("write tools without a safe constraint get a tool-wide suggestion", () => {
+ const list = times(5, (i) => decision("memory_save", "write", { note: `n${i}` }));
+ expect(suggestRules(list, [])[0]).toMatchObject({ tool: "memory_save", when: [] });
+ });
+
+ test("destructive without a constraint gets none; with one it does", () => {
+ const loose = times(6, (i) =>
+ decision("gmail_trash", "destructive", { messageIds: [`m${i}`] }),
+ );
+ expect(suggestRules(loose, [])).toEqual([]);
+ const scoped = times(6, (i) =>
+ decision("github_delete_branch", "destructive", { repo: "acme/web", branch: `b${i}` }),
+ );
+ expect(suggestRules(scoped, [])[0]!.when).toEqual([
+ { path: "repo", op: "equals", value: "acme/web" },
+ ]);
+ });
+
+ test("reads are ignored", () => {
+ expect(
+ suggestRules(
+ times(9, () => decision("web_search", "read", { q: "x" })),
+ [],
+ ),
+ ).toEqual([]);
+ });
+
+ test("an existing equal or broader allow rule suppresses it; narrower or ask does not", () => {
+ const list = times(6, () => email("a@acme.com"));
+ const rule = (r: Partial): PolicyRule => ({
+ id: "r",
+ tool: "gmail_send",
+ decision: "allow",
+ ...r,
+ });
+ expect(suggestRules(list, [rule({})])).toEqual([]);
+ expect(suggestRules(list, [rule({ tool: "gmail_*" })])).toEqual([]);
+ expect(
+ suggestRules(list, [
+ rule({ when: [{ path: "to", op: "allEndWith", value: ["@ACME.com"] }] }),
+ ]),
+ ).toEqual([]);
+ expect(
+ suggestRules(list, [
+ rule({
+ when: [
+ { path: "to", op: "allEndWith", value: ["@acme.com"] },
+ { path: "subject", op: "equals", value: "Hi" },
+ ],
+ }),
+ ]),
+ ).toHaveLength(1);
+ expect(suggestRules(list, [rule({ decision: "ask" })])).toHaveLength(1);
+ });
+
+ test("dismissed suggestions stay hidden", () => {
+ const list = times(6, () => email("a@acme.com"));
+ const [s] = suggestRules(list, []);
+ expect(suggestRules(list, [], [s!.id])).toEqual([]);
+ expect(suggestRules(list, [], ["sg_other"])).toHaveLength(1);
+ });
+
+ test("ids are stable and differ by tool and matchers", () => {
+ const m = [{ path: "to", op: "allEndWith" as const, value: ["@acme.com"] }];
+ expect(suggestionId("gmail_send", m)).toBe(suggestionId("gmail_send", structuredClone(m)));
+ expect(suggestionId("gmail_send", m)).toMatch(/^sg_[0-9a-f]{16}$/);
+ expect(suggestionId("gmail_send", m)).not.toBe(suggestionId("gmail_create_draft", m));
+ expect(suggestionId("gmail_send", m)).not.toBe(
+ suggestionId("gmail_send", [{ ...m[0]!, value: ["@other.io"] }]),
+ );
+ const a = suggestRules(
+ times(5, () => email("a@acme.com")),
+ [],
+ );
+ const b = suggestRules(
+ times(7, () => email("z@acme.com")),
+ [],
+ );
+ expect(a[0]!.id).toBe(b[0]!.id);
+ });
+
+ test("the accepted rule allows matching calls, but never in a tainted run", () => {
+ const [s] = suggestRules(
+ times(5, () => email("a@acme.com")),
+ [],
+ );
+ const rule: PolicyRule = { id: "l", tool: s!.tool, decision: "allow", when: s!.when };
+ const call = { tool: "gmail_send", effect: "send" as const };
+ expect(
+ evaluatePolicy({ ...call, input: { to: "b@acme.com" }, tainted: false }, [rule]).decision,
+ ).toBe("allow");
+ expect(
+ evaluatePolicy({ ...call, input: { to: "b@evil.com" }, tainted: false }, [rule]).decision,
+ ).toBe("ask");
+ expect(
+ evaluatePolicy({ ...call, input: { to: "b@acme.com" }, tainted: true }, [rule]).decision,
+ ).toBe("ask");
+ });
+});
diff --git a/packages/core/src/suggest.ts b/packages/core/src/suggest.ts
new file mode 100644
index 0000000..0ecf58b
--- /dev/null
+++ b/packages/core/src/suggest.ts
@@ -0,0 +1,222 @@
+import type { JSONValue } from "ai";
+import { type ArgMatcher, getPath, globMatch, type PolicyRule } from "./policy";
+import type { Effect } from "./types";
+
+/**
+ * Approvals that learn. When a person keeps approving the same kind of action without
+ * changing it, offer an ordinary allow rule for it. Pure: the caller fetches decisions.
+ *
+ * Learned rules never weaken the Rule of Two: a tainted run still asks for every
+ * non-read call, whatever the rules say.
+ */
+
+/** One human decision on a non-read tool call. */
+export interface PastDecision {
+ tool: string;
+ effect: Effect;
+ input: JSONValue;
+ inputEdited: boolean;
+ approved: boolean;
+ decidedAt: Date;
+ /** One-line summary from the tool, if any. */
+ preview?: string | null;
+}
+
+export interface RuleSuggestion {
+ /** Stable: a hash of the tool and matchers. */
+ id: string;
+ tool: string;
+ effect: Effect;
+ when: ArgMatcher[];
+ /** Note stored on the rule when accepted. */
+ note: string;
+ /** Unedited approvals behind this suggestion. */
+ count: number;
+ /** What the rule covers, e.g. "emails to @acme.com". */
+ label: string;
+ /** e.g. "You approved 7 emails to @acme.com without changes." */
+ sentence: string;
+ /** Up to three recent previews. */
+ examples: string[];
+}
+
+export const SUGGEST_MIN_APPROVALS = 5;
+export const SUGGEST_RECENT_WINDOW = 10;
+export const SUGGEST_LOOKBACK_DAYS = 60;
+
+const RECIPIENT_FIELDS = ["to", "cc", "bcc", "recipients", "email", "attendees"];
+const SCOPE_FIELDS = ["repo", "repository", "project", "channel", "team"];
+
+/** Anyone can have an address here, so a domain rule would allow nearly everyone. */
+const PUBLIC_DOMAINS = new Set([
+ "gmail.com",
+ "googlemail.com",
+ "outlook.com",
+ "hotmail.com",
+ "live.com",
+ "msn.com",
+ "yahoo.com",
+ "icloud.com",
+ "me.com",
+ "aol.com",
+ "proton.me",
+ "protonmail.com",
+ "gmx.com",
+ "mail.com",
+ "yandex.com",
+ "zoho.com",
+ "fastmail.com",
+]);
+
+export function suggestRules(
+ decisions: PastDecision[],
+ rules: PolicyRule[],
+ dismissed: readonly string[] = [],
+): RuleSuggestion[] {
+ const byTool = new Map();
+ for (const d of decisions) {
+ if (d.effect === "read") continue;
+ const list = byTool.get(d.tool) ?? [];
+ list.push(d);
+ byTool.set(d.tool, list);
+ }
+
+ const out: RuleSuggestion[] = [];
+ for (const [tool, list] of byTool) {
+ list.sort((a, b) => b.decidedAt.getTime() - a.decidedAt.getTime());
+ const recent = list.slice(0, SUGGEST_RECENT_WINDOW);
+ if (recent.some((d) => !d.approved || d.inputEdited)) continue;
+ const clean = list.filter((d) => d.approved && !d.inputEdited);
+ if (clean.length < SUGGEST_MIN_APPROVALS) continue;
+
+ const effect = clean[0]!.effect;
+ const when = generalize(clean.map((d) => d.input));
+ // Sending and irreversible actions are never allowed tool-wide.
+ if (when.length === 0 && effect !== "write") continue;
+
+ const id = suggestionId(tool, when);
+ if (dismissed.includes(id)) continue;
+ if (alreadyAllowed(tool, when, rules)) continue;
+
+ const label = describe(tool, when);
+ out.push({
+ id,
+ tool,
+ effect,
+ when,
+ note: `Learned: you approved ${clean.length} of these`,
+ count: clean.length,
+ label,
+ sentence: `You approved ${clean.length} ${label} without changes.`,
+ examples: clean
+ .slice(0, 3)
+ .map((d) => d.preview?.trim() || clip(JSON.stringify(d.input)))
+ .filter(Boolean),
+ });
+ }
+ return out.sort((a, b) => b.count - a.count);
+}
+
+/** Matchers that cover every input, or [] when nothing safe generalizes. */
+export function generalize(inputs: JSONValue[]): ArgMatcher[] {
+ const when: ArgMatcher[] = [];
+
+ for (const path of RECIPIENT_FIELDS) {
+ const present = inputs.map((i) => getPath(i, path)).filter((v) => !isEmpty(v));
+ if (present.length === 0) continue;
+ // Seen on some calls but not others: a matcher would not fit, and dropping it would
+ // leave the field unconstrained. Give up on recipients entirely.
+ if (present.length !== inputs.length) return scopeOnly(inputs);
+ const domains = new Set();
+ for (const v of present) {
+ for (const item of Array.isArray(v) ? v : [v]) {
+ const domain = typeof item === "string" ? emailDomain(item) : null;
+ if (!domain) return scopeOnly(inputs);
+ domains.add(domain);
+ }
+ }
+ const [domain] = domains;
+ if (domains.size !== 1 || !domain || PUBLIC_DOMAINS.has(domain)) return scopeOnly(inputs);
+ when.push({ path, op: "allEndWith", value: [`@${domain}`] });
+ }
+
+ return [...when, ...scopeOnly(inputs)];
+}
+
+function scopeOnly(inputs: JSONValue[]): ArgMatcher[] {
+ const when: ArgMatcher[] = [];
+ for (const path of SCOPE_FIELDS) {
+ const values = inputs.map((i) => getPath(i, path));
+ const first = values[0];
+ if (typeof first === "string" && first !== "" && values.every((v) => v === first)) {
+ when.push({ path, op: "equals", value: first });
+ }
+ }
+ return when;
+}
+
+function emailDomain(address: string): string | null {
+ const m = /^[^@\s<>]+@([a-z0-9-]+(?:\.[a-z0-9-]+)+)$/i.exec(address.trim());
+ return m ? m[1]!.toLowerCase() : null;
+}
+
+function isEmpty(v: JSONValue | undefined): boolean {
+ return v === undefined || v === null || v === "" || (Array.isArray(v) && v.length === 0);
+}
+
+/**
+ * An existing allow rule for this tool whose matchers are all among ours (or none at all)
+ * already covers everything the suggestion would.
+ */
+function alreadyAllowed(tool: string, when: ArgMatcher[], rules: PolicyRule[]): boolean {
+ const keys = new Set(when.map(matcherKey));
+ return rules.some(
+ (r) =>
+ r.decision === "allow" &&
+ globMatch(r.tool, tool) &&
+ (r.when ?? []).every((m) => keys.has(matcherKey(m))),
+ );
+}
+
+function matcherKey(m: ArgMatcher): string {
+ const value =
+ m.op === "allEndWith" ? [...m.value].map((s) => s.toLowerCase()).sort() : (m.value as unknown);
+ return JSON.stringify([m.path, m.op, value]);
+}
+
+export function suggestionId(tool: string, when: ArgMatcher[]): string {
+ const key = JSON.stringify([tool, [...when.map(matcherKey)].sort()]);
+ return `sg_${fnv1a(key, 0x811c9dc5)}${fnv1a(key, 0x01000193)}`;
+}
+
+function fnv1a(s: string, seed: number): string {
+ let h = seed >>> 0;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h.toString(16).padStart(8, "0");
+}
+
+const NOUNS: Record = {
+ gmail_send: "emails",
+ gmail_create_draft: "drafts",
+ calendar_create_event: "invites",
+ calendar_update_event: "event changes",
+};
+
+function describe(tool: string, when: ArgMatcher[]): string {
+ const noun = NOUNS[tool] ?? `${tool} actions`;
+ const parts = when.map((m) => {
+ if (m.op === "allEndWith") return `to ${m.value.join(", ")}`;
+ if (m.op === "equals") return `in ${String(m.value)}`;
+ return `with ${m.path}`;
+ });
+ const recipients = [...new Set(parts.filter((p) => p.startsWith("to ")))];
+ const rest = parts.filter((p) => !p.startsWith("to "));
+ return [noun, ...recipients, ...rest].join(" ");
+}
+
+function clip(s: string, max = 120): string {
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
+}
diff --git a/packages/db/drizzle/0004_learned_rules.sql b/packages/db/drizzle/0004_learned_rules.sql
new file mode 100644
index 0000000..39b8aa7
--- /dev/null
+++ b/packages/db/drizzle/0004_learned_rules.sql
@@ -0,0 +1 @@
+ALTER TABLE "user_settings" ADD COLUMN "dismissed_suggestions" text[] DEFAULT '{}' NOT NULL;
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0004_snapshot.json b/packages/db/drizzle/meta/0004_snapshot.json
new file mode 100644
index 0000000..ed56bcc
--- /dev/null
+++ b/packages/db/drizzle/meta/0004_snapshot.json
@@ -0,0 +1,1982 @@
+{
+ "id": "03ce45b9-430f-4e00-9bc7-227ab1cad1bc",
+ "prevId": "d2a38152-0d01-4c13-8d97-f967bd21a076",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.automations": {
+ "name": "automations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"type\":\"schedule\"}'::jsonb"
+ },
+ "schedule": {
+ "name": "schedule",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UTC'"
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "next_run_at": {
+ "name": "next_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cursor": {
+ "name": "cursor",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "webhook_secret": {
+ "name": "webhook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_run_at": {
+ "name": "last_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "automations_user_idx": {
+ "name": "automations_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "automations_due_idx": {
+ "name": "automations_due_idx",
+ "columns": [
+ {
+ "expression": "next_run_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "enabled",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "automations_user_id_user_id_fk": {
+ "name": "automations_user_id_user_id_fk",
+ "tableFrom": "automations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "automations_chat_id_chats_id_fk": {
+ "name": "automations_chat_id_chats_id_fk",
+ "tableFrom": "automations",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chats": {
+ "name": "chats",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chats_user_updated_idx": {
+ "name": "chats_user_updated_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chats_user_id_user_id_fk": {
+ "name": "chats_user_id_user_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chunks": {
+ "name": "chunks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "context": {
+ "name": "context",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "embedding": {
+ "name": "embedding",
+ "type": "vector(1536)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tsv": {
+ "name": "tsv",
+ "type": "tsvector",
+ "primaryKey": false,
+ "notNull": true,
+ "generated": {
+ "as": "to_tsvector('english', coalesce(context, '') || ' ' || content)",
+ "type": "stored"
+ }
+ }
+ },
+ "indexes": {
+ "chunks_user_idx": {
+ "name": "chunks_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chunks_tsv_idx": {
+ "name": "chunks_tsv_idx",
+ "columns": [
+ {
+ "expression": "tsv",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ },
+ "chunks_embedding_idx": {
+ "name": "chunks_embedding_idx",
+ "columns": [
+ {
+ "expression": "embedding",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chunks_document_id_documents_id_fk": {
+ "name": "chunks_document_id_documents_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chunks_user_id_user_id_fk": {
+ "name": "chunks_user_id_user_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.connections": {
+ "name": "connections",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth": {
+ "name": "auth",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_effects": {
+ "name": "tool_effects",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "connections_user_name_idx": {
+ "name": "connections_user_name_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "connections_user_id_user_id_fk": {
+ "name": "connections_user_id_user_id_fk",
+ "tableFrom": "connections",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.documents": {
+ "name": "documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'processing'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "documents_user_idx": {
+ "name": "documents_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "documents_user_id_user_id_fk": {
+ "name": "documents_user_id_user_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.integrations": {
+ "name": "integrations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "account": {
+ "name": "account",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integrations_user_provider_idx": {
+ "name": "integrations_user_provider_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integrations_user_id_user_id_fk": {
+ "name": "integrations_user_id_user_id_fk",
+ "tableFrom": "integrations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.memories": {
+ "name": "memories",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "memories_user_idx": {
+ "name": "memories_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "memories_user_id_user_id_fk": {
+ "name": "memories_user_id_user_id_fk",
+ "tableFrom": "memories",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "bigserial",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'message'"
+ },
+ "cutoff_seq": {
+ "name": "cutoff_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message": {
+ "name": "message",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "messages_chat_seq_idx": {
+ "name": "messages_chat_seq_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_chat_id_chats_id_fk": {
+ "name": "messages_chat_id_chats_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_run_id_runs_id_fk": {
+ "name": "messages_run_id_runs_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pending_inputs": {
+ "name": "pending_inputs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigserial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "pending_inputs_chat_idx": {
+ "name": "pending_inputs_chat_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pending_inputs_chat_id_chats_id_fk": {
+ "name": "pending_inputs_chat_id_chats_id_fk",
+ "tableFrom": "pending_inputs",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.policy_rules": {
+ "name": "policy_rules",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "tool": {
+ "name": "tool",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "when": {
+ "name": "when",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "policy_rules_user_idx": {
+ "name": "policy_rules_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "policy_rules_user_id_user_id_fk": {
+ "name": "policy_rules_user_id_user_id_fk",
+ "tableFrom": "policy_rules",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.run_events": {
+ "name": "run_events",
+ "schema": "",
+ "columns": {
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event": {
+ "name": "event",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "run_events_run_id_runs_id_fk": {
+ "name": "run_events_run_id_runs_id_fk",
+ "tableFrom": "run_events",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "run_events_run_id_seq_pk": {
+ "name": "run_events_run_id_seq_pk",
+ "columns": [
+ "run_id",
+ "seq"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.runs": {
+ "name": "runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'queued'"
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'chat'"
+ },
+ "tainted": {
+ "name": "tainted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "steps": {
+ "name": "steps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cancel_requested": {
+ "name": "cancel_requested",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lease_owner": {
+ "name": "lease_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lease_expires_at": {
+ "name": "lease_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "runs_chat_idx": {
+ "name": "runs_chat_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_user_idx": {
+ "name": "runs_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_claimable_idx": {
+ "name": "runs_claimable_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lease_expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "status in ('queued', 'running')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_one_active_per_chat": {
+ "name": "runs_one_active_per_chat",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "status in ('queued', 'running', 'waiting')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "runs_chat_id_chats_id_fk": {
+ "name": "runs_chat_id_chats_id_fk",
+ "tableFrom": "runs",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "runs_user_id_user_id_fk": {
+ "name": "runs_user_id_user_id_fk",
+ "tableFrom": "runs",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tool_calls": {
+ "name": "tool_calls",
+ "schema": "",
+ "columns": {
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input": {
+ "name": "input",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input_edited": {
+ "name": "input_edited",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "effect": {
+ "name": "effect",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "preview": {
+ "name": "preview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_at": {
+ "name": "decided_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output": {
+ "name": "output",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "full_output": {
+ "name": "full_output",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "tool_calls_awaiting_idx": {
+ "name": "tool_calls_awaiting_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "status = 'awaiting_approval'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tool_calls_run_id_runs_id_fk": {
+ "name": "tool_calls_run_id_runs_id_fk",
+ "tableFrom": "tool_calls",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tool_calls_user_id_user_id_fk": {
+ "name": "tool_calls_user_id_user_id_fk",
+ "tableFrom": "tool_calls",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "tool_calls_run_id_id_pk": {
+ "name": "tool_calls_run_id_id_pk",
+ "columns": [
+ "run_id",
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_settings": {
+ "name": "user_settings",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "policy_defaults": {
+ "name": "policy_defaults",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "models": {
+ "name": "models",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "budgets": {
+ "name": "budgets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_keys": {
+ "name": "provider_keys",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "instructions": {
+ "name": "instructions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dismissed_suggestions": {
+ "name": "dismissed_suggestions",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_settings_user_id_user_id_fk": {
+ "name": "user_settings_user_id_user_id_fk",
+ "tableFrom": "user_settings",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 8a2c59d..daaf470 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -29,6 +29,13 @@
"when": 1792859791484,
"tag": "0003_triggers_and_integrations",
"breakpoints": true
+ },
+ {
+ "idx": 4,
+ "version": "7",
+ "when": 1792889495433,
+ "tag": "0004_learned_rules",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index dd283b1..2ab6e8d 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -113,6 +113,8 @@ export const userSettings = pgTable("user_settings", {
/** Bring-your-own provider keys, encrypted with the server secret. */
providerKeys: jsonb("provider_keys").$type>(),
instructions: text("instructions"),
+ /** Learned-rule suggestions the user said "not now" to, by suggestion id. */
+ dismissedSuggestions: text("dismissed_suggestions").array().notNull().default([]),
updatedAt: updatedAt(),
});
From 52378bdf5653960e83923570a15200cfe1a92ea3 Mon Sep 17 00:00:00 2001
From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com>
Date: Sun, 25 Oct 2026 06:26:54 +0530
Subject: [PATCH 2/8] Approve the plan, not every step
- Batch decisions: POST /api/runs/:id/tool-calls/decisions decides several
awaiting calls of one run atomically (decideToolCalls; decideToolCall now
delegates to it). Re-queues the run once when nothing is left awaiting.
- propose_plan built-in tool: always asks; approving with steps unticked sends
an edited input with only the kept steps. When it runs after a person's
sign-off, each kept step becomes a grant (tool + SHA-256 of canonical input)
in the new runs.plan_grants column.
- Runtime: a call exactly matching an unused grant is allowed ("Part of the
plan you approved"), even in a tainted run; block rules still win; each
grant is used once.
- Web: runs with 2+ open asks show one checklist card in the task view and
inbox; plan approvals render as a tickable list of steps.
- System prompt asks the agent to propose a plan before multi-step changes.
- Tests for grants (core) and batch + end-to-end plan flow (server).
---
apps/server/src/prompt.ts | 1 +
apps/server/src/routes/runs.ts | 47 +-
apps/server/src/server.test.ts | 146 ++
apps/web/app/(app)/inbox/page.tsx | 34 +
.../web/components/approval/approval-card.tsx | 40 +-
apps/web/components/approval/checklist.tsx | 381 ++++
apps/web/components/task/conversation.tsx | 7 +-
apps/web/components/task/task-view.tsx | 38 +
apps/web/lib/api.ts | 5 +
docs/api.md | 1 +
docs/architecture.md | 9 +
packages/core/src/index.ts | 1 +
packages/core/src/memory-store.ts | 3 +-
packages/core/src/plan.ts | 23 +
packages/core/src/runtime.test.ts | 78 +
packages/core/src/runtime.ts | 26 +-
packages/core/src/store.ts | 4 +-
packages/core/src/types.ts | 10 +
packages/db/drizzle/0004_plan_grants.sql | 1 +
packages/db/drizzle/meta/0004_snapshot.json | 1982 +++++++++++++++++
packages/db/drizzle/meta/_journal.json | 7 +
packages/db/src/runs.ts | 102 +-
packages/db/src/schema.ts | 6 +
packages/db/src/store.ts | 1 +
packages/tools/src/builtin/plan.ts | 109 +
packages/tools/src/index.ts | 3 +
26 files changed, 3013 insertions(+), 52 deletions(-)
create mode 100644 apps/web/components/approval/checklist.tsx
create mode 100644 packages/core/src/plan.ts
create mode 100644 packages/db/drizzle/0004_plan_grants.sql
create mode 100644 packages/db/drizzle/meta/0004_snapshot.json
create mode 100644 packages/tools/src/builtin/plan.ts
diff --git a/apps/server/src/prompt.ts b/apps/server/src/prompt.ts
index c730f26..5890141 100644
--- a/apps/server/src/prompt.ts
+++ b/apps/server/src/prompt.ts
@@ -9,6 +9,7 @@ How you work:
- Ask a short clarifying question only when a wrong guess would be costly (wrong recipient, wrong repository, irreversible change). Otherwise make a reasonable assumption and say what you assumed.
- When you draft something that will be sent or published (an email, a message, an issue), put the complete final content in the tool call. The user reviews exactly that on an approval card.
- Some actions need the user's approval. The system asks for it automatically; you do not need to ask in text first. If an action is denied, do not retry it in another form; acknowledge it and continue or ask what they want instead.
+- When a task needs several actions that change things (sending, writing, deleting), first call propose_plan with the exact calls you intend to make, so the user can approve them once. After approval, make exactly the approved calls with exactly the same inputs, and nothing the user removed. For a single action, just make the call.
- If a tool fails, read the error, fix your input once if it is clearly your mistake, and otherwise tell the user what failed.
- Keep answers concise and skimmable. Cite sources (page titles and URLs, document names) for facts you looked up.
diff --git a/apps/server/src/routes/runs.ts b/apps/server/src/routes/runs.ts
index 63654e6..cccb8cd 100644
--- a/apps/server/src/routes/runs.ts
+++ b/apps/server/src/routes/runs.ts
@@ -1,5 +1,12 @@
import { evaluatePolicy } from "@synapse/core";
-import { decideToolCall, PgRunStore, readEvents, requestCancel, schema } from "@synapse/db";
+import {
+ decideToolCall,
+ decideToolCalls,
+ PgRunStore,
+ readEvents,
+ requestCancel,
+ schema,
+} from "@synapse/db";
import type { JSONValue } from "ai";
import { and, asc, desc, eq } from "drizzle-orm";
import { Hono } from "hono";
@@ -153,6 +160,44 @@ export const runs = new Hono()
return c.body(null, 204);
})
+ // Several calls from one run decided at once (the grouped checklist). All or nothing.
+ .post("/:id/tool-calls/decisions", async (c) => {
+ const { decisions } = await body(
+ c,
+ z.object({
+ decisions: z
+ .array(
+ z.object({
+ toolCallId: z.string().min(1),
+ approved: z.boolean(),
+ reason: z.string().max(1000).optional(),
+ editedInput: z.json().optional(),
+ }),
+ )
+ .min(1)
+ .max(100),
+ }),
+ );
+ const runId = c.req.param("id");
+ if (new Set(decisions.map((d) => d.toolCallId)).size !== decisions.length)
+ apiError(400, "duplicate", "Each action can be decided once.");
+ for (const d of decisions)
+ if (d.approved && d.editedInput !== undefined)
+ await assertEditAllowed(c, runId, d.toolCallId, d.editedInput);
+ await decideToolCalls(c.var.services.database.db, {
+ userId: c.var.user.id,
+ runId,
+ decisions: decisions.map((d) => ({
+ toolCallId: d.toolCallId,
+ approved: d.approved,
+ ...(d.reason ? { reason: d.reason } : {}),
+ ...(d.approved && d.editedInput !== undefined ? { editedInput: d.editedInput } : {}),
+ })),
+ });
+ await c.var.services.wake(runId);
+ return c.body(null, 204);
+ })
+
.post("/:id/cancel", async (c) => {
const { mode } = await body(
c,
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 8c2eddb..979aab1 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -342,6 +342,152 @@ test("edited approvals are re-checked against block rules; unsafe patterns are r
expect(res.status).toBe(422);
});
+const ASK_MEMORY = {
+ defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" },
+ rules: [{ tool: "memory_save", decision: "ask" }],
+};
+const notes = (call: ReturnType) =>
+ call("/api/memories").then((r) =>
+ (r.json!.memories as { content: string }[]).map((m) => m.content).sort(),
+ );
+
+test("batch decisions: several calls in one step, decided atomically", async () => {
+ const cookie = await signUp("batch@example.com");
+ const me = api(cookie);
+ const other = api(await signUp("batch-eve@example.com"));
+ await me("/api/policy", { method: "PUT", json: ASK_MEMORY });
+ script([
+ {
+ toolCalls: [
+ { name: "memory_save", input: { note: "one" }, id: "b1" },
+ { name: "memory_save", input: { note: "two" }, id: "b2" },
+ { name: "memory_save", input: { note: "three" }, id: "b3" },
+ ],
+ },
+ { text: "Saved what you approved." },
+ ]);
+ const { json } = await me("/api/chats", { method: "POST", json: { content: "save 3" } });
+ const runId = json!.runId;
+ await worker.processNow(runId);
+ expect((await me("/api/approvals")).json!.approvals).toHaveLength(3);
+
+ const path = `/api/runs/${runId}/tool-calls/decisions`;
+ const decisions = [
+ { toolCallId: "b1", approved: true },
+ { toolCallId: "b2", approved: true, editedInput: { note: "two, edited" } },
+ { toolCallId: "b3", approved: false, reason: "not this one" },
+ ];
+ // Another user's run is invisible; duplicates and unknown ids change nothing.
+ expect((await other(path, { method: "POST", json: { decisions } })).status).toBe(404);
+ expect(
+ (
+ await me(path, {
+ method: "POST",
+ json: { decisions: [decisions[0], { toolCallId: "b1", approved: false }] },
+ })
+ ).status,
+ ).toBe(400);
+ expect(
+ (
+ await me(path, {
+ method: "POST",
+ json: { decisions: [decisions[0], { toolCallId: "nope", approved: true }] },
+ })
+ ).status,
+ ).toBe(409);
+ expect((await me("/api/approvals")).json!.approvals).toHaveLength(3);
+
+ expect((await me(path, { method: "POST", json: { decisions } })).status).toBe(204);
+ expect((await me(`/api/runs/${runId}`)).json!.run.status).toBe("queued");
+ // A second submit (double click, replay) conflicts.
+ expect((await me(path, { method: "POST", json: { decisions } })).status).toBe(409);
+
+ await worker.processNow(runId);
+ const detail = await me(`/api/runs/${runId}`);
+ expect(detail.json!.run.status).toBe("completed");
+ expect(
+ detail.json!.toolCalls.map((c: { id: string; status: string }) => [c.id, c.status]),
+ ).toEqual([
+ ["b1", "succeeded"],
+ ["b2", "succeeded"],
+ ["b3", "denied"],
+ ]);
+ expect(await notes(me)).toEqual(["one", "two, edited"]);
+ // Re-queued once: one pause, then straight through to the end.
+ const statuses = (await sse(cookie, runId)).flatMap((e) =>
+ e.type === "run.status" ? [e.status] : [],
+ );
+ expect(statuses).toEqual(["running", "waiting", "running", "completed"]);
+});
+
+test("propose_plan: approve with a step removed; the kept call runs, the other asks", async () => {
+ const me = api(await signUp("plan@example.com"));
+ await me("/api/policy", { method: "PUT", json: ASK_MEMORY });
+ const keep = { tool: "memory_save", input: { note: "likes tea" }, why: "You said so." };
+ const drop = { tool: "memory_save", input: { note: "likes coffee" }, why: "A guess." };
+ script([
+ {
+ toolCalls: [
+ {
+ name: "propose_plan",
+ input: { summary: "Save two notes", steps: [keep, drop] },
+ id: "plan1",
+ },
+ ],
+ },
+ {
+ toolCalls: [
+ { name: "memory_save", input: { note: "likes tea" }, id: "k1" },
+ { name: "memory_save", input: { note: "likes coffee" }, id: "u1" },
+ ],
+ },
+ { text: "Saved the note you approved." },
+ ]);
+ const { json } = await me("/api/chats", { method: "POST", json: { content: "save notes" } });
+ const runId = json!.runId;
+ await worker.processNow(runId);
+ const [asked] = (await me("/api/approvals")).json!.approvals;
+ expect(asked).toMatchObject({ toolCallId: "plan1", preview: "Save two notes" });
+
+ // Untick the second step: approve with an input holding only the kept one.
+ const res = await me(`/api/runs/${runId}/tool-calls/plan1/decision`, {
+ method: "POST",
+ json: { approved: true, input: { summary: "Save two notes", steps: [keep] } },
+ });
+ expect(res.status).toBe(204);
+ await worker.processNow(runId);
+
+ let detail = await me(`/api/runs/${runId}`);
+ expect(detail.json!.run.status).toBe("waiting");
+ expect(detail.json!.run.planGrants).toEqual([
+ { tool: "memory_save", inputHash: expect.any(String), usedBy: "k1" },
+ ]);
+ const byId = (id: string) =>
+ detail.json!.toolCalls.find((c: { id: string }) => c.id === id) as Record;
+ expect(byId("plan1")).toMatchObject({ status: "succeeded", inputEdited: true });
+ expect(JSON.stringify(byId("plan1").output)).toContain("do not do them");
+ expect(byId("k1")).toMatchObject({
+ status: "approved",
+ decision: "allow",
+ decisionReason: "Part of the plan you approved",
+ });
+ expect(byId("u1")).toMatchObject({ status: "awaiting_approval", decision: "ask" });
+ expect((await me("/api/approvals")).json!.approvals).toEqual([
+ expect.objectContaining({ toolCallId: "u1" }),
+ ]);
+
+ await me(`/api/runs/${runId}/tool-calls/u1/decision`, {
+ method: "POST",
+ json: { approved: false },
+ });
+ await worker.processNow(runId);
+ detail = await me(`/api/runs/${runId}`);
+ expect(detail.json!.run.status).toBe("completed");
+ expect(byId("k1")!.status).toBe("succeeded");
+ expect(byId("u1")!.status).toBe("denied");
+ expect(await notes(me)).toEqual(["likes tea"]);
+});
+
test("user budgets can only tighten the operator cap", async () => {
const { capBudget } = await import("./worker");
expect(capBudget(undefined, 2)).toBe(2);
diff --git a/apps/web/app/(app)/inbox/page.tsx b/apps/web/app/(app)/inbox/page.tsx
index cb3167b..7e2e8ce 100644
--- a/apps/web/app/(app)/inbox/page.tsx
+++ b/apps/web/app/(app)/inbox/page.tsx
@@ -10,6 +10,7 @@ import {
approvalTitle,
MiniStamp,
} from "@/components/approval/approval-card";
+import { ApprovalBatch, PLAN_TOOL } from "@/components/approval/checklist";
import { Markdown } from "@/components/markdown";
import { EffectPill, Kbd, Monogram, Skeleton, StatusDot } from "@/components/ui";
import { type Approval, api } from "@/lib/api";
@@ -68,6 +69,12 @@ export default function InboxPage() {
}, [ordered, pending, selected]);
const current = ordered.find((a) => a.toolCallId === selected) ?? null;
+ // Open asks from the same run sign off together as one checklist (plans keep their card).
+ const batch = useMemo(() => {
+ if (!current || decided[current.toolCallId] || current.name === PLAN_TOOL) return [];
+ const same = pending.filter((a) => a.runId === current.runId && a.name !== PLAN_TOOL);
+ return same.length >= 2 ? same.sort((a, b) => a.createdAt.localeCompare(b.createdAt)) : [];
+ }, [current, decided, pending]);
const tainted = (chatId: string) => tasks?.find((t) => t.id === chatId)?.tainted ?? false;
const move = useCallback(
@@ -111,6 +118,23 @@ export default function InboxPage() {
void reload();
}
+ function onBatchDecided(list: Approval[], outcome: Record) {
+ setKept((k) => ({ ...k, ...Object.fromEntries(list.map((a) => [a.toolCallId, a])) }));
+ setDecided((m) => ({
+ ...m,
+ ...Object.fromEntries(
+ list.map((a) => [
+ a.toolCallId,
+ { approved: outcome[a.toolCallId] ?? false, edited: false },
+ ]),
+ ),
+ }));
+ const done = new Set(list.map((a) => a.toolCallId));
+ const next = pending.find((x) => !done.has(x.toolCallId));
+ if (next && desktop) setSelected(next.toolCallId);
+ void reload();
+ }
+
const loading = approvals === null;
const empty = !loading && ordered.length === 0;
const signed = ordered.length - pending.length;
@@ -296,6 +320,16 @@ export default function InboxPage() {
) : null}
+ ) : batch.length > 0 ? (
+
a.toolCallId).join()}
+ handle={card}
+ runId={current.runId}
+ items={batch}
+ tainted={tainted(current.chatId)}
+ onDecided={(outcome) => onBatchDecided(batch, outcome)}
+ onConflict={() => void reload()}
+ />
) : (
void) | null>(null);
const root = useRef(null);
const denyInput = useRef(null);
+ /** A `propose_plan` call shows its steps as a checklist; unticked steps are left out. */
+ const plan = asPlan(name, input);
+ const [kept, setKept] = useState(() => plan?.steps.map(() => true) ?? []);
+ const keptCount = kept.filter(Boolean).length;
/** The input as currently edited, or an error. */
function edited(): { value: unknown } | { error: string } {
+ if (plan && mode === "view") {
+ if (keptCount === plan.steps.length) return { value: input };
+ if (keptCount === 0) return { error: "Tick at least one step, or deny the plan." };
+ return { value: { ...(input as object), steps: plan.steps.filter((_, i) => kept[i]) } };
+ }
if (mode !== "edit") return { value: input };
if (raw || !objectInput) {
try {
@@ -104,7 +114,7 @@ export function ApprovalCard(props: ApprovalCardProps) {
return fromDrafts(drafts);
}
const current = edited();
- const isEdited = mode === "edit" && "value" in current && !sameJson(current.value, input);
+ const isEdited = "value" in current && !sameJson(current.value, input);
function startEdit() {
setMode("edit");
@@ -193,7 +203,7 @@ export function ApprovalCard(props: ApprovalCardProps) {
useImperativeHandle(props.handle, () => ({
approve: () => void decide(true),
deny: openDeny,
- edit: () => (mode === "edit" || stamped ? undefined : startEdit()),
+ edit: () => (mode === "edit" || stamped || plan ? undefined : startEdit()),
}));
const title = approvalTitle(preview, name);
@@ -255,8 +265,14 @@ export function ApprovalCard(props: ApprovalCardProps) {
-
{mode === "edit" ? "Editing" : humanize(tool)}
- {isEdited ?
Edited : null}
+
+ {mode === "edit"
+ ? "Editing"
+ : plan
+ ? `Plan · ${keptCount} of ${plan.steps.length} steps`
+ : humanize(tool)}
+
+ {isEdited && !plan ?
Edited : null}
{objectInput || mode === "view" ? (
{prettyJson(input) || "(no input)"}
+ ) : plan ? (
+
) : (
)}
@@ -342,7 +360,15 @@ export function ApprovalCard(props: ApprovalCardProps) {
aria-keyshortcuts="Meta+Enter Control+Enter"
>
{busy === "approve" ? : }
- {busy === "approve" ? "Approving…" : isEdited ? "Approve edited" : "Approve"}
+ {busy === "approve"
+ ? "Approving…"
+ : plan
+ ? isEdited
+ ? `Approve ${keptCount} of ${plan.steps.length} steps`
+ : "Approve plan"
+ : isEdited
+ ? "Approve edited"
+ : "Approve"}
- {denying ? null : mode === "edit" ? (
+ {denying || plan ? null : mode === "edit" ? (
Discard edits
@@ -405,6 +431,8 @@ export function ApprovalCard(props: ApprovalCardProps) {
className={cx(
"ml-auto text-12 text-fg-muted underline-offset-2 transition-opacity hover:text-fg hover:underline",
stamped && "opacity-0",
+ // A plan only means something when a person signs it.
+ plan && "hidden",
)}
>
Always allow…
diff --git a/apps/web/components/approval/checklist.tsx b/apps/web/components/approval/checklist.tsx
new file mode 100644
index 0000000..5cd4960
--- /dev/null
+++ b/apps/web/components/approval/checklist.tsx
@@ -0,0 +1,381 @@
+"use client";
+
+import type { Effect } from "@synapse/core";
+import { Check, ChevronDown, CircleSlash, LoaderCircle, ShieldAlert } from "lucide-react";
+import {
+ type ReactNode,
+ type Ref,
+ useEffect,
+ useId,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from "react";
+import { useToast } from "@/components/toast";
+import { EffectPill, TAINT_SENTENCE } from "@/components/ui";
+import { ApiError, api, errorMessage } from "@/lib/api";
+import { cx, humanToolName } from "@/lib/format";
+import { type ApprovalHandle, approvalTitle, ToolSource } from "./approval-card";
+import { isPlainObject, PayloadView } from "./payload";
+
+/** The built-in tool whose approval is a checklist of steps. */
+export const PLAN_TOOL = "propose_plan";
+
+export interface PlanStep {
+ tool: string;
+ input: Record;
+ why: string;
+}
+
+/** A `propose_plan` input, or null when it isn't shaped like one (then show it raw). */
+export function asPlan(
+ name: string,
+ input: unknown,
+): { summary: string; steps: PlanStep[] } | null {
+ if (name !== PLAN_TOOL || !isPlainObject(input) || !Array.isArray(input.steps)) return null;
+ const steps = input.steps.filter(
+ (s): s is PlanStep => isPlainObject(s) && typeof s.tool === "string" && isPlainObject(s.input),
+ );
+ if (steps.length !== input.steps.length) return null;
+ return { summary: typeof input.summary === "string" ? input.summary : "", steps };
+}
+
+/** An inked tick box. */
+function Tick({
+ checked,
+ onChange,
+ label,
+ disabled,
+}: {
+ checked: boolean;
+ onChange: (v: boolean) => void;
+ label: string;
+ disabled?: boolean;
+}) {
+ return (
+
+ onChange(e.target.checked)}
+ className="peer size-[18px] cursor-pointer appearance-none rounded-[4px] border-[1.5px] border-line-strong bg-surface transition-colors outline-none checked:border-fg checked:bg-fg hover:border-fg focus-visible:ring-2 focus-visible:ring-accent/40 disabled:cursor-default disabled:opacity-50"
+ />
+
+
+ );
+}
+
+/** One line of a checklist: tick, what it is, and the full payload on demand. */
+function ChecklistRow({
+ checked,
+ onCheck,
+ title,
+ why,
+ meta,
+ input,
+ locked,
+}: {
+ checked: boolean;
+ onCheck: (v: boolean) => void;
+ title: string;
+ why?: string;
+ meta?: ReactNode;
+ input: unknown;
+ locked: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const id = useId();
+ return (
+
+
+
+
+
+ setOpen((o) => !o)}
+ className="group flex min-w-0 flex-1 items-start gap-2 text-left"
+ >
+
+
+ {title}
+
+ {why ? {why} : null}
+
+ {meta ? {meta} : null}
+
+
+
+ {open ? (
+
+ ) : null}
+
+ );
+}
+
+/** The steps of a plan, each tickable. Used inside the approval card for `propose_plan`. */
+export function PlanSteps({
+ steps,
+ kept,
+ onKept,
+ locked,
+}: {
+ steps: PlanStep[];
+ kept: boolean[];
+ onKept: (kept: boolean[]) => void;
+ locked: boolean;
+}) {
+ return (
+
+ {steps.map((s, i) => (
+ onKept(kept.map((k, j) => (j === i ? v : k)))}
+ title={`${i + 1}. ${humanToolName(s.tool)}`}
+ why={s.why}
+ input={s.input}
+ locked={locked}
+ />
+ ))}
+
+ );
+}
+
+export interface BatchItem {
+ toolCallId: string;
+ name: string;
+ effect: Effect;
+ input: unknown;
+ reason: string | null;
+ preview: string | null;
+}
+
+/** How long the stamp sits on the slip before the card resolves into receipts. */
+const STAMP_MS = 950;
+
+/**
+ * Several actions from one step of a task, signed off together. Ticked rows are approved,
+ * unticked ones denied, in one request; nothing reads as decided until the server says so.
+ */
+export function ApprovalBatch({
+ runId,
+ items,
+ tainted,
+ glow,
+ onDecided,
+ onConflict,
+ handle,
+ className,
+}: {
+ runId: string;
+ items: BatchItem[];
+ tainted?: boolean;
+ glow?: boolean;
+ /** Called after the server accepted the decisions, with each call's outcome. */
+ onDecided: (approved: Record) => void;
+ onConflict: () => void;
+ handle?: Ref;
+ className?: string;
+}) {
+ const toast = useToast();
+ const id = useId();
+ const [ticked, setTicked] = useState>({});
+ const [busy, setBusy] = useState<"approve" | "deny" | null>(null);
+ const [stamped, setStamped] = useState<"approved" | "denied" | null>(null);
+ const [error, setError] = useState(null);
+ const settle = useRef<(() => void) | null>(null);
+ const isTicked = (tid: string) => ticked[tid] ?? true;
+ const count = items.filter((a) => isTicked(a.toolCallId)).length;
+ const locked = busy !== null || stamped !== null;
+
+ useEffect(
+ () => () => {
+ const pending = settle.current;
+ settle.current = null;
+ pending?.();
+ },
+ [],
+ );
+
+ async function decide(all: "selected" | "deny") {
+ if (locked) return;
+ if (all === "selected" && count === 0) return setError("Tick at least one, or deny all.");
+ setError(null);
+ const outcome = Object.fromEntries(
+ items.map((a) => [a.toolCallId, all === "selected" && isTicked(a.toolCallId)]),
+ );
+ setBusy(all === "selected" ? "approve" : "deny");
+ try {
+ await api.decideMany(
+ runId,
+ items.map((a) => ({ toolCallId: a.toolCallId, approved: outcome[a.toolCallId]! })),
+ );
+ settle.current = () => onDecided(outcome);
+ setStamped(all === "selected" ? "approved" : "denied");
+ setTimeout(() => {
+ const pending = settle.current;
+ settle.current = null;
+ pending?.();
+ }, STAMP_MS);
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 409) {
+ toast("Already decided, or the task moved on. Refreshing.", "info");
+ onConflict();
+ } else setError(errorMessage(err));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ useImperativeHandle(handle, () => ({
+ approve: () => void decide("selected"),
+ deny: () => void decide("deny"),
+ edit: () => {},
+ }));
+
+ return (
+ {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ void decide("selected");
+ }
+ }}
+ className={cx("slip relative", className)}
+ >
+ {glow ? (
+
+ ) : null}
+
+
+
+ {stamped ? null : }
+
+
+ Needs your sign-off
+
+
+ {count} of {items.length} ticked
+
+
+
+
+
+ This task wants to do {items.length} things
+
+ {tainted ? (
+
+
+ {TAINT_SENTENCE}
+
+ ) : null}
+
+ Untick anything you don't want. Open a row to see exactly what it sends.
+
+
+
+ {items.map((a) => (
+ setTicked((t) => ({ ...t, [a.toolCallId]: v }))}
+ title={approvalTitle(a.preview, a.name)}
+ why={a.reason ?? undefined}
+ meta={
+
+
+
+
+ }
+ input={a.input}
+ locked={locked}
+ />
+ ))}
+
+
+ {error ? (
+
+ {error}
+
+ ) : null}
+
+
+
+
+ void decide("selected")}
+ aria-keyshortcuts="Meta+Enter Control+Enter"
+ >
+ {busy === "approve" ? : }
+ {busy === "approve"
+ ? "Approving…"
+ : count === items.length
+ ? "Approve all"
+ : `Approve ${count} selected`}
+
+ void decide("deny")}
+ >
+ {busy === "deny" ? : }
+ {busy === "deny" ? "Denying…" : "Deny all"}
+
+
+
+
+ {stamped === "approved"
+ ? "Signed off by you"
+ : stamped === "denied"
+ ? "Declined by you"
+ : "Your signature"}
+
+
+ {stamped ? (
+
+ {stamped === "approved" ? "Approved" : "Denied"}
+
+ ) : null}
+
+
+ );
+}
diff --git a/apps/web/components/task/conversation.tsx b/apps/web/components/task/conversation.tsx
index 90c5cd3..8ec1171 100644
--- a/apps/web/components/task/conversation.tsx
+++ b/apps/web/components/task/conversation.tsx
@@ -231,8 +231,11 @@ function AgentMessage({
return ;
case "steps":
return ;
- case "asked":
- return {renderAsked(b.part, message)}
;
+ case "asked": {
+ // Null when another block already shows this call (a grouped checklist).
+ const node = renderAsked(b.part, message);
+ return node == null ? null : {node}
;
+ }
}
return null;
})}
diff --git a/apps/web/components/task/task-view.tsx b/apps/web/components/task/task-view.tsx
index 0ffd69c..f3c8bd5 100644
--- a/apps/web/components/task/task-view.tsx
+++ b/apps/web/components/task/task-view.tsx
@@ -7,6 +7,7 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { ApprovalCard, ApprovalReceipt } from "@/components/approval/approval-card";
+import { ApprovalBatch, PLAN_TOOL } from "@/components/approval/checklist";
import { Menu } from "@/components/overlay";
import { useToast } from "@/components/toast";
import { EmptyState, Skeleton, StatusPill, TaintShield, taskStatus } from "@/components/ui";
@@ -240,6 +241,43 @@ export function TaskView({ taskId }: { taskId: string }) {
/>
);
}
+ // Two or more open asks from one step sign off together, as one checklist shown in
+ // place of the first. Plans keep their own card (they are a checklist already).
+ const group = runId
+ ? message.parts.filter(
+ (p): p is ToolPart =>
+ p.type === "tool" &&
+ p.status === "awaiting_approval" &&
+ p.name !== PLAN_TOOL &&
+ !decided[p.toolCallId],
+ )
+ : [];
+ if (runId && group.length >= 2 && group.some((p) => p.toolCallId === part.toolCallId)) {
+ if (group[0]!.toolCallId !== part.toolCallId) return null;
+ return (
+ p.toolCallId).join()}
+ runId={runId}
+ items={group}
+ tainted={tainted}
+ glow={initialAwaiting !== null && group.some((p) => !initialAwaiting.has(p.toolCallId))}
+ onDecided={(outcome) => {
+ setDecided((m) => ({
+ ...m,
+ ...Object.fromEntries(
+ Object.entries(outcome).map(([id, approved]) => [id, { approved, edited: false }]),
+ ),
+ }));
+ follow(runId);
+ void reloadWorkspace();
+ }}
+ onConflict={() => {
+ void snapshot();
+ void reloadWorkspace();
+ }}
+ />
+ );
+ }
if (part.status !== "awaiting_approval" || !runId) {
return (
post(`/api/runs/${enc(runId)}/tool-calls/${enc(toolCallId)}/decision`, body),
+ /** Decides several calls of one run at once; all or nothing (409 if any moved on). */
+ decideMany: (
+ runId: string,
+ decisions: { toolCallId: string; approved: boolean; reason?: string; editedInput?: unknown }[],
+ ) => post(`/api/runs/${enc(runId)}/tool-calls/decisions`, { decisions }),
cancel: (runId: string, mode: "now" | "after_step" = "now") =>
post(`/api/runs/${enc(runId)}/cancel`, { mode }),
runs: (limit = 50) => get<{ runs: RunRow[] }>(`/api/runs?limit=${limit}`),
diff --git a/docs/api.md b/docs/api.md
index 77dca7f..cfdb5db 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -40,6 +40,7 @@ agent reads it at its next step; if the run is waiting on approvals, those are d
|---|---|---|---|
| GET | `/api/runs/:id/events?after=` | | **SSE** stream (see below) |
| POST | `/api/runs/:id/tool-calls/:toolCallId/decision` | `{ approved: boolean, reason?: string, input?: unknown }` | `204`; `409` if no longer awaiting approval. `input` replaces the arguments (edited on the approval card) |
+| POST | `/api/runs/:id/tool-calls/decisions` | `{ decisions: { toolCallId, approved, reason?, editedInput? }[] }` | `204`; all or nothing in one transaction: `409` if any call is no longer awaiting approval, `400` on duplicate ids. The run is re-queued once when nothing is left awaiting |
| POST | `/api/runs/:id/cancel` | `{ mode: "now" \| "after_step" }` | `204` |
| GET | `/api/runs?limit=50` | | `{ runs: { id, chatId, chatTitle, status, trigger, model, steps, inputTokens, outputTokens, costUsd, error, createdAt, finishedAt }[] }` |
| GET | `/api/runs/:id` | | `{ run, toolCalls: { id, name, effect, status, decision, decisionReason, input, output, decidedBy, decidedAt, createdAt }[] }` (audit view) |
diff --git a/docs/architecture.md b/docs/architecture.md
index e1f49f8..81bd5ab 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -62,6 +62,15 @@ A run becomes tainted the first time a tool with `untrustedOutput` returns: web
and fetch, knowledge search, every MCP tool. This is a pragmatic form of the "Rule of Two":
an agent that has seen untrusted input and can act externally must have a human in the loop.
+**Plans.** For multi-step jobs the agent calls the built-in `propose_plan` with the exact
+calls it intends to make. The plan always asks; the person can untick steps, which approves
+it with an edited input holding only the kept steps. When it runs (and only if a person
+decided it), each kept step becomes a grant on the run (`runs.plan_grants`: tool name plus
+SHA-256 of the canonical, key-sorted input JSON). A later call whose tool and input hash
+match an unused grant is allowed with "Part of the plan you approved", even in a tainted
+run, because the person signed off on that exact payload. Each grant is used once, block
+rules still win, and anything that differs goes through normal policy.
+
## Streaming
Every runtime event is appended to `run_events` with a dense per-run `seq` (text deltas are
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 1fa6e6b..d45f5bf 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,6 +1,7 @@
export * from "./context";
export * from "./memory-store";
export * from "./models";
+export * from "./plan";
export * from "./policy";
export * from "./prices";
export * from "./runtime";
diff --git a/packages/core/src/memory-store.ts b/packages/core/src/memory-store.ts
index f595184..1059110 100644
--- a/packages/core/src/memory-store.ts
+++ b/packages/core/src/memory-store.ts
@@ -27,6 +27,7 @@ export class MemoryStore implements RunStore {
costUsd: 0,
error: null,
cancelRequested: null,
+ planGrants: [],
};
this.runs.set(run.id, run);
if (init.text) this.pushUser(init.chatId, run.id, init.text);
@@ -40,7 +41,7 @@ export class MemoryStore implements RunStore {
async getRun(runId: string) {
const run = this.runs.get(runId);
if (!run) throw new Error(`run ${runId} not found`);
- return { ...run };
+ return { ...run, planGrants: run.planGrants.map((g) => ({ ...g })) };
}
async updateRun(runId: string, patch: Partial) {
diff --git a/packages/core/src/plan.ts b/packages/core/src/plan.ts
new file mode 100644
index 0000000..bb98dfe
--- /dev/null
+++ b/packages/core/src/plan.ts
@@ -0,0 +1,23 @@
+import type { JSONValue } from "ai";
+
+/** Decision reason for a call that matched a step of a plan the user approved. */
+export const PLAN_GRANT_REASON = "Part of the plan you approved";
+
+/** JSON with object keys sorted at every level, so equal inputs serialise identically. */
+export function canonicalJson(value: JSONValue | undefined): string {
+ if (value === null || value === undefined || typeof value !== "object")
+ return JSON.stringify(value ?? null);
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
+ const obj = value as Record;
+ const keys = Object.keys(obj)
+ .filter((k) => obj[k] !== undefined)
+ .sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(",")}}`;
+}
+
+/** SHA-256 (hex) of the canonical JSON of a tool input. */
+export async function hashInput(value: JSONValue | undefined): Promise {
+ const bytes = new TextEncoder().encode(canonicalJson(value));
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
+}
diff --git a/packages/core/src/runtime.test.ts b/packages/core/src/runtime.test.ts
index 675b69c..240774a 100644
--- a/packages/core/src/runtime.test.ts
+++ b/packages/core/src/runtime.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, test } from "bun:test";
+import type { JSONValue } from "ai";
import { MemoryEvents, MemoryStore } from "./memory-store";
+import { canonicalJson, hashInput, PLAN_GRANT_REASON } from "./plan";
import { type RunAgentOptions, runAgent } from "./runtime";
import { type ScriptedStep, scriptedModel } from "./testing";
import { type ToolDefinition, ToolRegistry } from "./tools";
@@ -459,3 +461,79 @@ describe("review fixes", () => {
expect(store.toolCalls.get("p")!.status).toBe("unknown");
});
});
+
+describe("plan grants", () => {
+ const email = { to: "a@b.com", body: "hi" };
+ async function grant(store: MemoryStore, runId: string, tool: string, input: JSONValue) {
+ store.runs.get(runId)!.planGrants.push({ tool, inputHash: await hashInput(input) });
+ }
+
+ test("canonical hashing ignores key order", async () => {
+ expect(canonicalJson({ b: 1, a: { d: [1, { y: 2, x: 1 }], c: null } })).toBe(
+ '{"a":{"c":null,"d":[1,{"x":1,"y":2}]},"b":1}',
+ );
+ expect(await hashInput({ to: "a", body: "b" })).toBe(await hashInput({ body: "b", to: "a" }));
+ expect(await hashInput({ to: "a" })).not.toBe(await hashInput({ to: "b" }));
+ });
+
+ test("an exactly matching call runs without asking, and the grant is spent", async () => {
+ const { store, run, opts } = setup([
+ // Same input, keys in another order.
+ { toolCalls: [{ name: "send_email", input: { body: "hi", to: "a@b.com" }, id: "g1" }] },
+ { toolCalls: [{ name: "send_email", input: email, id: "g2" }] },
+ ]);
+ await grant(store, run.id, "send_email", email);
+ expect(await runAgent(opts)).toBe("waiting");
+ expect(store.toolCalls.get("g1")).toMatchObject({
+ status: "succeeded",
+ decision: "allow",
+ decisionReason: PLAN_GRANT_REASON,
+ });
+ // The same call again is not covered: each grant is used once.
+ expect(store.toolCalls.get("g2")!.status).toBe("awaiting_approval");
+ expect((await store.getRun(run.id)).planGrants).toEqual([
+ expect.objectContaining({ tool: "send_email", usedBy: "g1" }),
+ ]);
+ expect(executed).toEqual(['send_email:{"body":"hi","to":"a@b.com"}']);
+ });
+
+ test("a call with a different input still asks", async () => {
+ const { store, run, opts } = setup([
+ { toolCalls: [{ name: "send_email", input: { ...email, body: "hi!" }, id: "g1" }] },
+ ]);
+ await grant(store, run.id, "send_email", email);
+ expect(await runAgent(opts)).toBe("waiting");
+ expect(store.toolCalls.get("g1")!.status).toBe("awaiting_approval");
+ expect((await store.getRun(run.id)).planGrants[0]!.usedBy).toBeUndefined();
+ });
+
+ test("a block rule beats a grant", async () => {
+ const { store, run, opts } = setup([
+ { toolCalls: [{ name: "send_email", input: email, id: "g1" }] },
+ { text: "blocked" },
+ ]);
+ store.rules = [{ id: "no-email", tool: "send_*", decision: "block" }];
+ await grant(store, run.id, "send_email", email);
+ expect(await runAgent(opts)).toBe("completed");
+ expect(store.toolCalls.get("g1")).toMatchObject({ status: "denied", decision: "block" });
+ expect(executed).toEqual([]);
+ });
+
+ test("a grant holds in a tainted run, even next to an untrusted read", async () => {
+ const { store, run, opts } = setup([
+ { toolCalls: [{ name: "read_inbox", input: {} }] },
+ {
+ toolCalls: [
+ { name: "read_inbox", input: { q: "again" } },
+ { name: "send_email", input: email, id: "g1" },
+ ],
+ },
+ { toolCalls: [{ name: "send_email", input: { to: "x@evil.com" }, id: "x1" }] },
+ ]);
+ await grant(store, run.id, "send_email", email);
+ expect(await runAgent(opts)).toBe("waiting");
+ expect((await store.getRun(run.id)).tainted).toBe(true);
+ expect(store.toolCalls.get("g1")).toMatchObject({ status: "succeeded", decision: "allow" });
+ expect(store.toolCalls.get("x1")!.status).toBe("awaiting_approval");
+ });
+});
diff --git a/packages/core/src/runtime.ts b/packages/core/src/runtime.ts
index dae2930..c3b18a2 100644
--- a/packages/core/src/runtime.ts
+++ b/packages/core/src/runtime.ts
@@ -21,6 +21,7 @@ import {
toModelOutput,
} from "./context";
import { costUsd, isRetryable, type ModelSpec } from "./models";
+import { hashInput, PLAN_GRANT_REASON } from "./plan";
import { evaluatePolicy } from "./policy";
import type { EventSink, RunStore } from "./store";
import type { ToolDefinition, ToolRegistry } from "./tools";
@@ -261,10 +262,13 @@ async function settleToolCalls(
await Promise.all(reads.map((c) => execute(opts, run, c, limits, signal)));
// Writes proposed in the same step as an untrusted read were judged before the run was
- // tainted. Re-judge them now; anything auto-allowed goes back to the user.
+ // tainted. Re-judge them now; anything auto-allowed goes back to the user. Steps of an
+ // approved plan stay allowed: the user signed off on that exact input.
if (run.tainted && reads.length > 0) {
let asked = false;
- for (const c of writes.filter((w) => w.decision === "allow")) {
+ for (const c of writes.filter(
+ (w) => w.decision === "allow" && w.decisionReason !== PLAN_GRANT_REASON,
+ )) {
const reason =
"This step read untrusted content, so this action needs your approval before it runs.";
if (
@@ -520,6 +524,8 @@ async function streamOneStep(
const policy = await store.getPolicy(run.userId);
const toolCalls: Omit[] = [];
+ const grants = run.planGrants.map((g) => ({ ...g }));
+ let grantsUsed = false;
for (const part of content) {
if (part.type !== "tool-call") continue;
const def = opts.tools.get(part.toolName);
@@ -543,7 +549,7 @@ async function streamOneStep(
});
continue;
}
- const verdict = evaluatePolicy(
+ let verdict = evaluatePolicy(
{
tool: def.name,
effect: def.effect,
@@ -554,6 +560,17 @@ async function streamOneStep(
policy.rules,
policy.defaults,
);
+ // A call matching a step of an approved plan, exactly, was already signed off by the
+ // user: it runs without asking again, even in a tainted run. Block rules still win.
+ if (verdict.decision !== "block" && grants.some((g) => !g.usedBy && g.tool === def.name)) {
+ const hash = await hashInput(input);
+ const grant = grants.find((g) => !g.usedBy && g.tool === def.name && g.inputHash === hash);
+ if (grant) {
+ grant.usedBy = part.toolCallId;
+ grantsUsed = true;
+ verdict = { decision: "allow", reason: PLAN_GRANT_REASON, ruleId: null };
+ }
+ }
const status: ToolCallStatus =
verdict.decision === "allow"
? "approved"
@@ -573,6 +590,9 @@ async function streamOneStep(
});
}
+ // Spend grants before recording the calls: a crash in between costs a grant (the call
+ // asks instead), never lets one grant cover two calls.
+ if (grantsUsed) await store.updateRun(run.id, { planGrants: grants });
const stored = await store.appendAssistantStep({
id: messageId,
chatId: run.chatId,
diff --git a/packages/core/src/store.ts b/packages/core/src/store.ts
index 7ba6af3..08efb7a 100644
--- a/packages/core/src/store.ts
+++ b/packages/core/src/store.ts
@@ -20,7 +20,9 @@ export interface RunStore {
getRun(runId: string): Promise;
updateRun(
runId: string,
- patch: Partial>,
+ patch: Partial<
+ Pick
+ >,
): Promise;
addUsage(
runId: string,
diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts
index ce1d292..88b87cf 100644
--- a/packages/core/src/types.ts
+++ b/packages/core/src/types.ts
@@ -63,6 +63,16 @@ export interface RunRecord {
costUsd: number;
error: string | null;
cancelRequested: "now" | "after_step" | null;
+ /** Exact calls the user approved through `propose_plan`; each runs once without asking. */
+ planGrants: PlanGrant[];
+}
+
+/** One approved plan step: a tool name and the hash of its canonical input. */
+export interface PlanGrant {
+ tool: string;
+ inputHash: string;
+ /** Id of the tool call that used this grant. Unset while the grant is still open. */
+ usedBy?: string;
}
export interface StoredMessage {
diff --git a/packages/db/drizzle/0004_plan_grants.sql b/packages/db/drizzle/0004_plan_grants.sql
new file mode 100644
index 0000000..6785dba
--- /dev/null
+++ b/packages/db/drizzle/0004_plan_grants.sql
@@ -0,0 +1 @@
+ALTER TABLE "runs" ADD COLUMN "plan_grants" jsonb DEFAULT '[]'::jsonb NOT NULL;
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0004_snapshot.json b/packages/db/drizzle/meta/0004_snapshot.json
new file mode 100644
index 0000000..918ea58
--- /dev/null
+++ b/packages/db/drizzle/meta/0004_snapshot.json
@@ -0,0 +1,1982 @@
+{
+ "id": "9c59cfb0-5d2b-4583-982e-bb77a60cfd3e",
+ "prevId": "d2a38152-0d01-4c13-8d97-f967bd21a076",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.automations": {
+ "name": "automations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"type\":\"schedule\"}'::jsonb"
+ },
+ "schedule": {
+ "name": "schedule",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UTC'"
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "next_run_at": {
+ "name": "next_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cursor": {
+ "name": "cursor",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "webhook_secret": {
+ "name": "webhook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_run_at": {
+ "name": "last_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "automations_user_idx": {
+ "name": "automations_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "automations_due_idx": {
+ "name": "automations_due_idx",
+ "columns": [
+ {
+ "expression": "next_run_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "enabled",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "automations_user_id_user_id_fk": {
+ "name": "automations_user_id_user_id_fk",
+ "tableFrom": "automations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "automations_chat_id_chats_id_fk": {
+ "name": "automations_chat_id_chats_id_fk",
+ "tableFrom": "automations",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chats": {
+ "name": "chats",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chats_user_updated_idx": {
+ "name": "chats_user_updated_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chats_user_id_user_id_fk": {
+ "name": "chats_user_id_user_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chunks": {
+ "name": "chunks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "context": {
+ "name": "context",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "embedding": {
+ "name": "embedding",
+ "type": "vector(1536)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tsv": {
+ "name": "tsv",
+ "type": "tsvector",
+ "primaryKey": false,
+ "notNull": true,
+ "generated": {
+ "as": "to_tsvector('english', coalesce(context, '') || ' ' || content)",
+ "type": "stored"
+ }
+ }
+ },
+ "indexes": {
+ "chunks_user_idx": {
+ "name": "chunks_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chunks_tsv_idx": {
+ "name": "chunks_tsv_idx",
+ "columns": [
+ {
+ "expression": "tsv",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ },
+ "chunks_embedding_idx": {
+ "name": "chunks_embedding_idx",
+ "columns": [
+ {
+ "expression": "embedding",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chunks_document_id_documents_id_fk": {
+ "name": "chunks_document_id_documents_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chunks_user_id_user_id_fk": {
+ "name": "chunks_user_id_user_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.connections": {
+ "name": "connections",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth": {
+ "name": "auth",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_effects": {
+ "name": "tool_effects",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "connections_user_name_idx": {
+ "name": "connections_user_name_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "connections_user_id_user_id_fk": {
+ "name": "connections_user_id_user_id_fk",
+ "tableFrom": "connections",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.documents": {
+ "name": "documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'processing'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "documents_user_idx": {
+ "name": "documents_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "documents_user_id_user_id_fk": {
+ "name": "documents_user_id_user_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.integrations": {
+ "name": "integrations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "account": {
+ "name": "account",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integrations_user_provider_idx": {
+ "name": "integrations_user_provider_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integrations_user_id_user_id_fk": {
+ "name": "integrations_user_id_user_id_fk",
+ "tableFrom": "integrations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.memories": {
+ "name": "memories",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "memories_user_idx": {
+ "name": "memories_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "memories_user_id_user_id_fk": {
+ "name": "memories_user_id_user_id_fk",
+ "tableFrom": "memories",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "bigserial",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'message'"
+ },
+ "cutoff_seq": {
+ "name": "cutoff_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message": {
+ "name": "message",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "messages_chat_seq_idx": {
+ "name": "messages_chat_seq_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_chat_id_chats_id_fk": {
+ "name": "messages_chat_id_chats_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_run_id_runs_id_fk": {
+ "name": "messages_run_id_runs_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pending_inputs": {
+ "name": "pending_inputs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigserial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "pending_inputs_chat_idx": {
+ "name": "pending_inputs_chat_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pending_inputs_chat_id_chats_id_fk": {
+ "name": "pending_inputs_chat_id_chats_id_fk",
+ "tableFrom": "pending_inputs",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.policy_rules": {
+ "name": "policy_rules",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "tool": {
+ "name": "tool",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "when": {
+ "name": "when",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "policy_rules_user_idx": {
+ "name": "policy_rules_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "policy_rules_user_id_user_id_fk": {
+ "name": "policy_rules_user_id_user_id_fk",
+ "tableFrom": "policy_rules",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.run_events": {
+ "name": "run_events",
+ "schema": "",
+ "columns": {
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event": {
+ "name": "event",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "run_events_run_id_runs_id_fk": {
+ "name": "run_events_run_id_runs_id_fk",
+ "tableFrom": "run_events",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "run_events_run_id_seq_pk": {
+ "name": "run_events_run_id_seq_pk",
+ "columns": [
+ "run_id",
+ "seq"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.runs": {
+ "name": "runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'queued'"
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'chat'"
+ },
+ "tainted": {
+ "name": "tainted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "steps": {
+ "name": "steps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cancel_requested": {
+ "name": "cancel_requested",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "plan_grants": {
+ "name": "plan_grants",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "lease_owner": {
+ "name": "lease_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lease_expires_at": {
+ "name": "lease_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "runs_chat_idx": {
+ "name": "runs_chat_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_user_idx": {
+ "name": "runs_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_claimable_idx": {
+ "name": "runs_claimable_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lease_expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "status in ('queued', 'running')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_one_active_per_chat": {
+ "name": "runs_one_active_per_chat",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "status in ('queued', 'running', 'waiting')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "runs_chat_id_chats_id_fk": {
+ "name": "runs_chat_id_chats_id_fk",
+ "tableFrom": "runs",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "runs_user_id_user_id_fk": {
+ "name": "runs_user_id_user_id_fk",
+ "tableFrom": "runs",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tool_calls": {
+ "name": "tool_calls",
+ "schema": "",
+ "columns": {
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input": {
+ "name": "input",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input_edited": {
+ "name": "input_edited",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "effect": {
+ "name": "effect",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "preview": {
+ "name": "preview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_at": {
+ "name": "decided_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output": {
+ "name": "output",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "full_output": {
+ "name": "full_output",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "tool_calls_awaiting_idx": {
+ "name": "tool_calls_awaiting_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "status = 'awaiting_approval'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tool_calls_run_id_runs_id_fk": {
+ "name": "tool_calls_run_id_runs_id_fk",
+ "tableFrom": "tool_calls",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tool_calls_user_id_user_id_fk": {
+ "name": "tool_calls_user_id_user_id_fk",
+ "tableFrom": "tool_calls",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "tool_calls_run_id_id_pk": {
+ "name": "tool_calls_run_id_id_pk",
+ "columns": [
+ "run_id",
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_settings": {
+ "name": "user_settings",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "policy_defaults": {
+ "name": "policy_defaults",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "models": {
+ "name": "models",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "budgets": {
+ "name": "budgets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_keys": {
+ "name": "provider_keys",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "instructions": {
+ "name": "instructions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_settings_user_id_user_id_fk": {
+ "name": "user_settings_user_id_user_id_fk",
+ "tableFrom": "user_settings",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 8a2c59d..553e330 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -29,6 +29,13 @@
"when": 1792859791484,
"tag": "0003_triggers_and_integrations",
"breakpoints": true
+ },
+ {
+ "idx": 4,
+ "version": "7",
+ "when": 1792889509084,
+ "tag": "0004_plan_grants",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/runs.ts b/packages/db/src/runs.ts
index f7f7839..f22c2eb 100644
--- a/packages/db/src/runs.ts
+++ b/packages/db/src/runs.ts
@@ -1,3 +1,4 @@
+import type { PlanGrant } from "@synapse/core";
import type { JSONValue } from "ai";
import { and, asc, eq, inArray, isNull, lt, or, sql } from "drizzle-orm";
import type { Db } from "./client";
@@ -147,6 +148,13 @@ export async function sendMessage(
});
}
+export interface ToolCallDecision {
+ toolCallId: string;
+ approved: boolean;
+ reason?: string;
+ editedInput?: JSONValue;
+}
+
/**
* Approves or denies one awaiting tool call. Compare-and-set on status and owner, so a
* double click, a replayed request or another user's id is a no-op (ConflictError).
@@ -154,14 +162,20 @@ export async function sendMessage(
*/
export async function decideToolCall(
db: Db,
- args: {
- userId: string;
- runId: string;
- toolCallId: string;
- approved: boolean;
- reason?: string;
- editedInput?: JSONValue;
- },
+ args: { userId: string; runId: string } & ToolCallDecision,
+): Promise {
+ const { userId, runId, ...decision } = args;
+ await decideToolCalls(db, { userId, runId, decisions: [decision] });
+}
+
+/**
+ * Decides several awaiting calls of one run at once, all or nothing: if any call is not
+ * awaiting approval (already decided, someone else's, unknown), nothing changes and a
+ * ConflictError is thrown. The run is re-queued once, when none remain awaiting.
+ */
+export async function decideToolCalls(
+ db: Db,
+ args: { userId: string; runId: string; decisions: ToolCallDecision[] },
): Promise {
await db.transaction(async (tx) => {
const [run] = await tx
@@ -171,36 +185,39 @@ export async function decideToolCall(
.for("update");
if (!run) throw new NotFoundError("run not found");
- const updated = await tx
- .update(toolCalls)
- .set({
- status: args.approved ? "approved" : "denied",
- decidedBy: args.userId,
- decidedAt: new Date(),
- ...(args.approved && args.editedInput !== undefined
- ? { input: args.editedInput, inputEdited: true }
- : {}),
- ...(args.approved
- ? {}
- : {
- output: {
- type: "denied" as const,
- reason: args.reason
- ? `The user denied this action: ${args.reason}`
- : "The user denied this action.",
- },
- }),
- })
- .where(
- and(
- eq(toolCalls.runId, run.id),
- eq(toolCalls.id, args.toolCallId),
- eq(toolCalls.userId, args.userId),
- eq(toolCalls.status, "awaiting_approval"),
- ),
- )
- .returning({ id: toolCalls.id });
- if (updated.length === 0) throw new ConflictError("this action is no longer awaiting approval");
+ for (const d of args.decisions) {
+ const updated = await tx
+ .update(toolCalls)
+ .set({
+ status: d.approved ? "approved" : "denied",
+ decidedBy: args.userId,
+ decidedAt: new Date(),
+ ...(d.approved && d.editedInput !== undefined
+ ? { input: d.editedInput, inputEdited: true }
+ : {}),
+ ...(d.approved
+ ? {}
+ : {
+ output: {
+ type: "denied" as const,
+ reason: d.reason
+ ? `The user denied this action: ${d.reason}`
+ : "The user denied this action.",
+ },
+ }),
+ })
+ .where(
+ and(
+ eq(toolCalls.runId, run.id),
+ eq(toolCalls.id, d.toolCallId),
+ eq(toolCalls.userId, args.userId),
+ eq(toolCalls.status, "awaiting_approval"),
+ ),
+ )
+ .returning({ id: toolCalls.id });
+ if (updated.length === 0)
+ throw new ConflictError("this action is no longer awaiting approval");
+ }
const [{ remaining } = { remaining: 0 }] = await tx
.select({ remaining: sql`count(*)::int` })
@@ -215,6 +232,15 @@ export async function decideToolCall(
});
}
+/** Adds grants from an approved plan to the run; `propose_plan` calls this when it runs. */
+export async function addPlanGrants(db: Db, runId: string, grants: PlanGrant[]): Promise {
+ if (grants.length === 0) return;
+ await db
+ .update(runs)
+ .set({ planGrants: sql`${runs.planGrants} || ${JSON.stringify(grants)}::jsonb` })
+ .where(eq(runs.id, runId));
+}
+
export async function requestCancel(
db: Db,
args: { userId: string; runId: string; mode: "now" | "after_step" },
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index dd283b1..049fe91 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -2,6 +2,7 @@ import type {
ArgMatcher,
Decision,
Effect,
+ PlanGrant,
PolicyDefaults,
RunStatus,
ToolCallStatus,
@@ -169,6 +170,11 @@ export const runs = pgTable(
costUsd: doublePrecision("cost_usd").notNull().default(0),
error: text("error"),
cancelRequested: text("cancel_requested").$type<"now" | "after_step">(),
+ /**
+ * Steps of plans the user approved via `propose_plan` (tool + canonical input hash).
+ * A matching call runs once without asking; `usedBy` marks a spent grant.
+ */
+ planGrants: jsonb("plan_grants").$type().notNull().default([]),
/** Worker lease. A run with an expired lease is picked up again by another worker. */
leaseOwner: text("lease_owner"),
leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
diff --git a/packages/db/src/store.ts b/packages/db/src/store.ts
index 3334b36..b32916d 100644
--- a/packages/db/src/store.ts
+++ b/packages/db/src/store.ts
@@ -85,6 +85,7 @@ export class PgRunStore implements RunStore {
costUsd: r.costUsd,
error: r.error,
cancelRequested: r.cancelRequested,
+ planGrants: r.planGrants,
};
}
diff --git a/packages/tools/src/builtin/plan.ts b/packages/tools/src/builtin/plan.ts
new file mode 100644
index 0000000..bb29117
--- /dev/null
+++ b/packages/tools/src/builtin/plan.ts
@@ -0,0 +1,109 @@
+import { hashInput, type PlanGrant, type ToolDefinition } from "@synapse/core";
+import { addPlanGrants, type Db, schema } from "@synapse/db";
+import type { JSONValue } from "ai";
+import { and, eq } from "drizzle-orm";
+
+export const PLAN_TOOL = "propose_plan";
+const MAX_STEPS = 25;
+
+interface PlanStep {
+ tool: string;
+ input: Record;
+ why: string;
+}
+
+/**
+ * Lets the agent ask for one sign-off on a multi-step job. The plan always needs approval;
+ * the person can untick steps first (the approved input then holds only the kept steps).
+ * Running it records one grant per kept step, so exactly that call, with exactly that
+ * input, later runs once without asking again. Anything else goes through normal policy.
+ */
+export function planTool(db: Db): ToolDefinition {
+ return {
+ name: PLAN_TOOL,
+ description: `Propose the exact actions you intend to take before a task that changes several things (sends, writes, deletes). The user reviews the list once, may remove steps, and approves. Afterwards, make exactly the approved calls with exactly the same inputs; they then run without asking again. Up to ${MAX_STEPS} steps. Do not include read-only steps.`,
+ inputSchema: {
+ type: "object",
+ properties: {
+ summary: {
+ type: "string",
+ maxLength: 500,
+ description: "One sentence: what the plan does.",
+ },
+ steps: {
+ type: "array",
+ minItems: 1,
+ maxItems: MAX_STEPS,
+ items: {
+ type: "object",
+ properties: {
+ tool: { type: "string", description: "Name of the tool to call." },
+ input: { type: "object", description: "The exact input you will pass." },
+ why: { type: "string", maxLength: 300, description: "Why this step is needed." },
+ },
+ required: ["tool", "input", "why"],
+ additionalProperties: false,
+ },
+ },
+ },
+ required: ["summary", "steps"],
+ additionalProperties: false,
+ },
+ effect: "write",
+ defaultDecision: "ask",
+ untrustedOutput: false,
+ source: "builtin",
+ preview: (input) => String((input as { summary?: unknown }).summary ?? "").trim() || "A plan",
+ execute: async (input, ctx) => {
+ const steps = parseSteps(input);
+ if (typeof steps === "string") return { type: "error", value: steps };
+
+ // Grants only come from a person's sign-off. If a rule let the plan through without
+ // one, the steps still ask one by one.
+ const [call] = await db
+ .select({ decidedBy: schema.toolCalls.decidedBy })
+ .from(schema.toolCalls)
+ .where(and(eq(schema.toolCalls.runId, ctx.runId), eq(schema.toolCalls.id, ctx.toolCallId)));
+ if (!call?.decidedBy)
+ return {
+ type: "text",
+ value:
+ "The plan was noted but not signed off by the user, so each step will ask for approval when you make it.",
+ };
+ if (steps.length === 0)
+ return {
+ type: "text",
+ value: "The user approved none of the steps. Do not make any of the proposed calls.",
+ };
+
+ const grants: PlanGrant[] = await Promise.all(
+ steps.map(async (s) => ({ tool: s.tool, inputHash: await hashInput(s.input) })),
+ );
+ await addPlanGrants(db, ctx.runId, grants);
+ const list = steps.map((s, i) => `${i + 1}. ${s.tool} ${JSON.stringify(s.input)}`).join("\n");
+ return {
+ type: "text",
+ value: `The user approved these ${steps.length === 1 ? "step" : `${steps.length} steps`}:\n${list}\n\nNow make exactly these calls with exactly these inputs; they will run without asking again. Any change to a call means it asks again. If your plan had other steps, the user removed them: do not do them.`,
+ };
+ },
+ };
+}
+
+function parseSteps(input: JSONValue): PlanStep[] | string {
+ const steps = (input as { steps?: unknown } | null)?.steps;
+ if (!Array.isArray(steps)) return "steps must be a list.";
+ if (steps.length > MAX_STEPS) return `A plan can have at most ${MAX_STEPS} steps.`;
+ for (const s of steps) {
+ const step = s as Partial | null;
+ if (
+ typeof step?.tool !== "string" ||
+ typeof step.why !== "string" ||
+ typeof step.input !== "object" ||
+ step.input === null ||
+ Array.isArray(step.input)
+ )
+ return "Each step needs a tool name, an input object and a why.";
+ if (step.tool === PLAN_TOOL) return "A plan cannot contain another plan.";
+ }
+ return steps as PlanStep[];
+}
diff --git a/packages/tools/src/index.ts b/packages/tools/src/index.ts
index 93f7f5c..8d67028 100644
--- a/packages/tools/src/index.ts
+++ b/packages/tools/src/index.ts
@@ -2,6 +2,7 @@ import { type ToolDefinition, ToolRegistry } from "@synapse/core";
import type { Db, SecretBox } from "@synapse/db";
import { type Embedder, knowledgeTool } from "./builtin/knowledge";
import { memoryTools } from "./builtin/memory";
+import { planTool } from "./builtin/plan";
import { type WebSearchConfig, webFetchTool, webSearchTool } from "./builtin/web";
import { calendarTools } from "./google/calendar";
import { type GoogleAppConfig, GoogleClient } from "./google/client";
@@ -11,6 +12,7 @@ import type { OAuthAppConfig } from "./mcp/oauth";
export * from "./builtin/knowledge";
export { loadMemoryBlock } from "./builtin/memory";
+export { PLAN_TOOL } from "./builtin/plan";
export { htmlToText, type WebSearchConfig } from "./builtin/web";
export * from "./google/client";
export { buildMime, type MessageSummary, newMessagesSince } from "./google/gmail";
@@ -38,6 +40,7 @@ export async function buildToolset(cfg: ToolsetConfig, userId: string) {
webFetchTool(),
knowledgeTool(cfg.db, cfg.embedder),
...memoryTools(cfg.db),
+ planTool(cfg.db),
...(cfg.webSearch ? [webSearchTool(cfg.webSearch)] : []),
];
if (cfg.google) {
From 96854de43fa7b2cd728257a9663cbbbf4d1a9dd9 Mon Sep 17 00:00:00 2001
From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com>
Date: Sun, 25 Oct 2026 06:29:16 +0530
Subject: [PATCH 3/8] Learned rules check every email address, and respect
explicit ask rules
- New emailsEndWith condition: every address anywhere in the call (to, cc, bcc,
attendees, any field) must end with the domain, so an added bcc still asks
- No suggestion for a tool the user deliberately set to ask
- Index tool_calls (user_id, decided_at) for the suggestions query
---
apps/server/src/routes/account.ts | 5 ++
apps/web/app/(app)/settings/policy-editor.tsx | 24 ++++++---
packages/core/src/policy.ts | 33 +++++++++++-
packages/core/src/suggest.test.ts | 36 ++++++++-----
packages/core/src/suggest.ts | 52 ++++++++-----------
packages/db/src/schema.ts | 2 +
6 files changed, 101 insertions(+), 51 deletions(-)
diff --git a/apps/server/src/routes/account.ts b/apps/server/src/routes/account.ts
index 96311f4..045b3ce 100644
--- a/apps/server/src/routes/account.ts
+++ b/apps/server/src/routes/account.ts
@@ -12,6 +12,11 @@ const Matcher = z.discriminatedUnion("op", [
z.object({ path: z.string().min(1), op: z.literal("in"), value: z.array(z.json()) }),
z.object({ path: z.string().min(1), op: z.literal("allEndWith"), value: z.array(z.string()) }),
z.object({ path: z.string().min(1), op: z.literal("matches"), value: z.string().max(500) }),
+ z.object({
+ path: z.string().default("*"),
+ op: z.literal("emailsEndWith"),
+ value: z.array(z.string().min(2)).min(1),
+ }),
]);
const Defaults = z.object({
read: Decision,
diff --git a/apps/web/app/(app)/settings/policy-editor.tsx b/apps/web/app/(app)/settings/policy-editor.tsx
index 4dfa828..9a93472 100644
--- a/apps/web/app/(app)/settings/policy-editor.tsx
+++ b/apps/web/app/(app)/settings/policy-editor.tsx
@@ -12,6 +12,7 @@ import { useApi } from "@/lib/use-api";
const EFFECTS: Effect[] = ["read", "write", "send", "destructive"];
const OPS: { op: ArgMatcher["op"]; label: string; hint: string }[] = [
{ op: "allEndWith", label: "ends with", hint: "@acme.com, @acme.io" },
+ { op: "emailsEndWith", label: "every email address ends with", hint: "@acme.com" },
{ op: "equals", label: "is", hint: "main" },
{ op: "in", label: "is one of", hint: "a, b, c" },
{ op: "matches", label: "matches", hint: "^release/" },
@@ -57,7 +58,7 @@ function toDraft(rule: PolicyRule): DraftRule {
raw:
m.op === "matches"
? m.value
- : m.op === "allEndWith"
+ : m.op === "allEndWith" || m.op === "emailsEndWith"
? m.value.join(", ")
: m.op === "in"
? m.value.map((v) => (typeof v === "string" ? v : JSON.stringify(v))).join(", ")
@@ -75,6 +76,11 @@ const splitList = (raw: string) =>
.filter(Boolean);
function toMatcher(m: DraftMatcher, where: string): ArgMatcher {
+ if (m.op === "emailsEndWith") {
+ const value = splitList(m.raw);
+ if (value.length === 0) throw new Error(`${where}: give at least one ending`);
+ return { path: "*", op: "emailsEndWith", value };
+ }
const path = m.path.trim();
if (!path) throw new Error(`${where}: say which field the condition checks`);
switch (m.op) {
@@ -389,13 +395,15 @@ export function PolicyEditor({ prefillTool }: { prefillTool?: string | null }) {
className="inline-flex flex-wrap items-center gap-x-2 gap-y-2"
>
and
- updateMatcher(i, k, { path: v })}
- />
+ {m.op === "emailsEndWith" ? null : (
+ updateMatcher(i, k, { path: v })}
+ />
+ )}
matches(m, getPath(input, m.path)));
+ return (matchers ?? []).every((m) =>
+ matches(m, m.op === "emailsEndWith" ? input : getPath(input, m.path)),
+ );
}
function matches(m: ArgMatcher, value: JSONValue | undefined): boolean {
@@ -163,6 +171,13 @@ function matches(m: ArgMatcher, value: JSONValue | undefined): boolean {
)
);
}
+ case "emailsEndWith": {
+ const emails = emailsIn(value);
+ return (
+ emails.length > 0 &&
+ emails.every((e) => m.value.some((suffix) => e.endsWith(suffix.toLowerCase())))
+ );
+ }
case "matches":
return (
typeof value === "string" &&
@@ -172,6 +187,20 @@ function matches(m: ArgMatcher, value: JSONValue | undefined): boolean {
}
const MAX_MATCH_INPUT = 10_000;
+const EMAIL = /[^\s@<>"',;:()[\]]+@[a-z0-9-]+(?:\.[a-z0-9-]+)+/gi;
+
+/** Every email address in any string anywhere in a value, lowercased. */
+export function emailsIn(value: JSONValue | undefined): string[] {
+ const out: string[] = [];
+ const walk = (v: JSONValue | undefined) => {
+ if (typeof v === "string") {
+ for (const m of v.slice(0, MAX_MATCH_INPUT).matchAll(EMAIL)) out.push(m[0].toLowerCase());
+ } else if (Array.isArray(v)) v.forEach(walk);
+ else if (v && typeof v === "object") Object.values(v).forEach(walk);
+ };
+ walk(value);
+ return out;
+}
const MAX_PATTERN = 500;
/**
diff --git a/packages/core/src/suggest.test.ts b/packages/core/src/suggest.test.ts
index e6ec693..2cca73d 100644
--- a/packages/core/src/suggest.test.ts
+++ b/packages/core/src/suggest.test.ts
@@ -40,7 +40,7 @@ describe("suggestRules", () => {
tool: "gmail_send",
effect: "send",
count: 5,
- when: [{ path: "to", op: "allEndWith", value: ["@acme.com"] }],
+ when: [{ path: "*", op: "emailsEndWith", value: ["@acme.com"] }],
label: "emails to @acme.com",
sentence: "You approved 5 emails to @acme.com without changes.",
note: "Learned: you approved 5 of these",
@@ -73,7 +73,7 @@ describe("suggestRules", () => {
expect(suggestRules(list, [])).toEqual([]);
});
- test("public mail domains and optional recipient fields don't generalize", () => {
+ test("public mail domains don't generalize; an optional cc on the same domain does", () => {
expect(
suggestRules(
times(6, (i) => email(`f${i}@gmail.com`)),
@@ -86,17 +86,24 @@ describe("suggestRules", () => {
...(i % 2 ? { cc: ["b@acme.com"] } : {}),
}),
);
- expect(suggestRules(someCc, [])).toEqual([]);
+ expect(suggestRules(someCc, [])[0]!.when).toEqual([
+ { path: "*", op: "emailsEndWith", value: ["@acme.com"] },
+ ]);
});
- test("every recipient field is constrained", () => {
+ test("the learned rule checks every address, so an added bcc to an outsider still asks", () => {
const list = times(5, () =>
decision("gmail_send", "send", { to: "a@acme.com", cc: ["b@acme.com", "c@ACME.com"] }),
);
- expect(suggestRules(list, [])[0]!.when).toEqual([
- { path: "to", op: "allEndWith", value: ["@acme.com"] },
- { path: "cc", op: "allEndWith", value: ["@acme.com"] },
- ]);
+ const [s] = suggestRules(list, []);
+ const rule: PolicyRule = { id: "l", tool: s!.tool, decision: "allow", when: s!.when };
+ const send = (input: JSONValue) =>
+ evaluatePolicy({ tool: "gmail_send", effect: "send", input, tainted: false }, [rule])
+ .decision;
+ expect(send({ to: "z@acme.com" })).toBe("allow");
+ expect(send({ to: "z@acme.com", bcc: ["spy@evil.test"] })).toBe("ask");
+ expect(send({ to: ["z@acme.com"], attendees: [{ email: "x@evil.test" }] })).toBe("ask");
+ expect(send({ subject: "no recipients" })).toBe("ask");
});
test("a single repo or channel becomes an equals matcher", () => {
@@ -135,7 +142,7 @@ describe("suggestRules", () => {
).toEqual([]);
});
- test("an existing equal or broader allow rule suppresses it; narrower or ask does not", () => {
+ test("an existing equal or broader allow rule suppresses it; a narrower one does not", () => {
const list = times(6, () => email("a@acme.com"));
const rule = (r: Partial): PolicyRule => ({
id: "r",
@@ -147,20 +154,25 @@ describe("suggestRules", () => {
expect(suggestRules(list, [rule({ tool: "gmail_*" })])).toEqual([]);
expect(
suggestRules(list, [
- rule({ when: [{ path: "to", op: "allEndWith", value: ["@ACME.com"] }] }),
+ rule({ when: [{ path: "*", op: "emailsEndWith", value: ["@ACME.com"] }] }),
]),
).toEqual([]);
expect(
suggestRules(list, [
rule({
when: [
- { path: "to", op: "allEndWith", value: ["@acme.com"] },
+ { path: "*", op: "emailsEndWith", value: ["@acme.com"] },
{ path: "subject", op: "equals", value: "Hi" },
],
}),
]),
).toHaveLength(1);
- expect(suggestRules(list, [rule({ decision: "ask" })])).toHaveLength(1);
+ });
+
+ test("an explicit ask rule for the tool means no suggestion", () => {
+ const list = times(6, () => email("a@acme.com"));
+ expect(suggestRules(list, [{ id: "r", tool: "gmail_*", decision: "ask" }])).toEqual([]);
+ expect(suggestRules(list, [{ id: "r", tool: "slack_*", decision: "ask" }])).toHaveLength(1);
});
test("dismissed suggestions stay hidden", () => {
diff --git a/packages/core/src/suggest.ts b/packages/core/src/suggest.ts
index 0ecf58b..770cb7e 100644
--- a/packages/core/src/suggest.ts
+++ b/packages/core/src/suggest.ts
@@ -1,5 +1,5 @@
import type { JSONValue } from "ai";
-import { type ArgMatcher, getPath, globMatch, type PolicyRule } from "./policy";
+import { type ArgMatcher, emailsIn, getPath, globMatch, type PolicyRule } from "./policy";
import type { Effect } from "./types";
/**
@@ -97,6 +97,8 @@ export function suggestRules(
const id = suggestionId(tool, when);
if (dismissed.includes(id)) continue;
if (alreadyAllowed(tool, when, rules)) continue;
+ // The user said "ask" for this tool on purpose; a suggestion would quietly override it.
+ if (rules.some((r) => r.decision === "ask" && globMatch(r.tool, tool))) continue;
const label = describe(tool, when);
out.push({
@@ -119,28 +121,23 @@ export function suggestRules(
/** Matchers that cover every input, or [] when nothing safe generalizes. */
export function generalize(inputs: JSONValue[]): ArgMatcher[] {
- const when: ArgMatcher[] = [];
-
- for (const path of RECIPIENT_FIELDS) {
- const present = inputs.map((i) => getPath(i, path)).filter((v) => !isEmpty(v));
- if (present.length === 0) continue;
- // Seen on some calls but not others: a matcher would not fit, and dropping it would
- // leave the field unconstrained. Give up on recipients entirely.
- if (present.length !== inputs.length) return scopeOnly(inputs);
- const domains = new Set();
- for (const v of present) {
- for (const item of Array.isArray(v) ? v : [v]) {
- const domain = typeof item === "string" ? emailDomain(item) : null;
- if (!domain) return scopeOnly(inputs);
- domains.add(domain);
- }
- }
- const [domain] = domains;
- if (domains.size !== 1 || !domain || PUBLIC_DOMAINS.has(domain)) return scopeOnly(inputs);
- when.push({ path, op: "allEndWith", value: [`@${domain}`] });
+ const scope = scopeOnly(inputs);
+ // Only calls that address people get a recipient condition.
+ const addressed = inputs.every((i) =>
+ RECIPIENT_FIELDS.some((path) => !isEmpty(getPath(i, path))),
+ );
+ if (!addressed) return scope;
+ // One domain across every address anywhere in every approved call (to, cc, bcc, even the
+ // body). The rule checks the same way, so an added bcc to someone else still asks.
+ const domains = new Set();
+ for (const input of inputs) {
+ const emails = emailsIn(input);
+ if (emails.length === 0) return scope;
+ for (const e of emails) domains.add(e.slice(e.lastIndexOf("@") + 1));
}
-
- return [...when, ...scopeOnly(inputs)];
+ const [domain] = domains;
+ if (domains.size !== 1 || !domain || PUBLIC_DOMAINS.has(domain)) return scope;
+ return [{ path: "*", op: "emailsEndWith", value: [`@${domain}`] }, ...scope];
}
function scopeOnly(inputs: JSONValue[]): ArgMatcher[] {
@@ -155,11 +152,6 @@ function scopeOnly(inputs: JSONValue[]): ArgMatcher[] {
return when;
}
-function emailDomain(address: string): string | null {
- const m = /^[^@\s<>]+@([a-z0-9-]+(?:\.[a-z0-9-]+)+)$/i.exec(address.trim());
- return m ? m[1]!.toLowerCase() : null;
-}
-
function isEmpty(v: JSONValue | undefined): boolean {
return v === undefined || v === null || v === "" || (Array.isArray(v) && v.length === 0);
}
@@ -180,7 +172,9 @@ function alreadyAllowed(tool: string, when: ArgMatcher[], rules: PolicyRule[]):
function matcherKey(m: ArgMatcher): string {
const value =
- m.op === "allEndWith" ? [...m.value].map((s) => s.toLowerCase()).sort() : (m.value as unknown);
+ m.op === "allEndWith" || m.op === "emailsEndWith"
+ ? [...m.value].map((s) => s.toLowerCase()).sort()
+ : (m.value as unknown);
return JSON.stringify([m.path, m.op, value]);
}
@@ -208,7 +202,7 @@ const NOUNS: Record = {
function describe(tool: string, when: ArgMatcher[]): string {
const noun = NOUNS[tool] ?? `${tool} actions`;
const parts = when.map((m) => {
- if (m.op === "allEndWith") return `to ${m.value.join(", ")}`;
+ if (m.op === "allEndWith" || m.op === "emailsEndWith") return `to ${m.value.join(", ")}`;
if (m.op === "equals") return `in ${String(m.value)}`;
return `with ${m.path}`;
});
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index 7777dc0..d88ba8a 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -245,6 +245,8 @@ export const toolCalls = pgTable(
},
(t) => [
primaryKey({ columns: [t.runId, t.id] }),
+ // Learned-rule suggestions read a user's recent decisions.
+ index("tool_calls_user_decided_idx").on(t.userId, t.decidedAt),
index("tool_calls_awaiting_idx")
.on(t.userId, t.createdAt)
.where(sql`status = 'awaiting_approval'`),
From be6a2de7b9bf77b90fdca13304cf7b99ddd62b32 Mon Sep 17 00:00:00 2001
From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com>
Date: Sun, 25 Oct 2026 06:29:36 +0530
Subject: [PATCH 4/8] Batch approvals take edited input as "input", like single
approvals
---
apps/server/src/routes/runs.ts | 8 ++++----
apps/server/src/server.test.ts | 2 +-
apps/web/lib/api.ts | 2 +-
docs/api.md | 2 +-
4 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/apps/server/src/routes/runs.ts b/apps/server/src/routes/runs.ts
index cccb8cd..a56f373 100644
--- a/apps/server/src/routes/runs.ts
+++ b/apps/server/src/routes/runs.ts
@@ -171,7 +171,7 @@ export const runs = new Hono()
toolCallId: z.string().min(1),
approved: z.boolean(),
reason: z.string().max(1000).optional(),
- editedInput: z.json().optional(),
+ input: z.json().optional(),
}),
)
.min(1)
@@ -182,8 +182,8 @@ export const runs = new Hono()
if (new Set(decisions.map((d) => d.toolCallId)).size !== decisions.length)
apiError(400, "duplicate", "Each action can be decided once.");
for (const d of decisions)
- if (d.approved && d.editedInput !== undefined)
- await assertEditAllowed(c, runId, d.toolCallId, d.editedInput);
+ if (d.approved && d.input !== undefined)
+ await assertEditAllowed(c, runId, d.toolCallId, d.input);
await decideToolCalls(c.var.services.database.db, {
userId: c.var.user.id,
runId,
@@ -191,7 +191,7 @@ export const runs = new Hono()
toolCallId: d.toolCallId,
approved: d.approved,
...(d.reason ? { reason: d.reason } : {}),
- ...(d.approved && d.editedInput !== undefined ? { editedInput: d.editedInput } : {}),
+ ...(d.approved && d.input !== undefined ? { editedInput: d.input } : {}),
})),
});
await c.var.services.wake(runId);
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 21f7a7c..d040c6a 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -375,7 +375,7 @@ test("batch decisions: several calls in one step, decided atomically", async ()
const path = `/api/runs/${runId}/tool-calls/decisions`;
const decisions = [
{ toolCallId: "b1", approved: true },
- { toolCallId: "b2", approved: true, editedInput: { note: "two, edited" } },
+ { toolCallId: "b2", approved: true, input: { note: "two, edited" } },
{ toolCallId: "b3", approved: false, reason: "not this one" },
];
// Another user's run is invisible; duplicates and unknown ids change nothing.
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index 6818bba..71af11c 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -357,7 +357,7 @@ export const api = {
/** Decides several calls of one run at once; all or nothing (409 if any moved on). */
decideMany: (
runId: string,
- decisions: { toolCallId: string; approved: boolean; reason?: string; editedInput?: unknown }[],
+ decisions: { toolCallId: string; approved: boolean; reason?: string; input?: unknown }[],
) => post(`/api/runs/${enc(runId)}/tool-calls/decisions`, { decisions }),
cancel: (runId: string, mode: "now" | "after_step" = "now") =>
post(`/api/runs/${enc(runId)}/cancel`, { mode }),
diff --git a/docs/api.md b/docs/api.md
index 8e71c1b..945c026 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -40,7 +40,7 @@ agent reads it at its next step; if the run is waiting on approvals, those are d
|---|---|---|---|
| GET | `/api/runs/:id/events?after=` | | **SSE** stream (see below) |
| POST | `/api/runs/:id/tool-calls/:toolCallId/decision` | `{ approved: boolean, reason?: string, input?: unknown }` | `204`; `409` if no longer awaiting approval. `input` replaces the arguments (edited on the approval card) |
-| POST | `/api/runs/:id/tool-calls/decisions` | `{ decisions: { toolCallId, approved, reason?, editedInput? }[] }` | `204`; all or nothing in one transaction: `409` if any call is no longer awaiting approval, `400` on duplicate ids. The run is re-queued once when nothing is left awaiting |
+| POST | `/api/runs/:id/tool-calls/decisions` | `{ decisions: { toolCallId, approved, reason?, input? }[] }` (`input`: approve with edited input, same as the single route) | `204`; all or nothing in one transaction: `409` if any call is no longer awaiting approval, `400` on duplicate ids. The run is re-queued once when nothing is left awaiting |
| POST | `/api/runs/:id/cancel` | `{ mode: "now" \| "after_step" }` | `204` |
| GET | `/api/runs?limit=50` | | `{ runs: { id, chatId, chatTitle, status, trigger, model, steps, inputTokens, outputTokens, costUsd, error, createdAt, finishedAt }[] }` |
| GET | `/api/runs/:id` | | `{ run, toolCalls: { id, name, effect, status, decision, decisionReason, input, output, decidedBy, decidedAt, createdAt }[] }` (audit view) |
From 03f6aa3d9bc6f74f84ad1ed28e22a8cf53bafaa8 Mon Sep 17 00:00:00 2001
From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com>
Date: Sun, 25 Oct 2026 06:34:45 +0530
Subject: [PATCH 5/8] Undo window: approved sends and deletes wait a few
seconds, with an Undo
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
When a person approves an action that reaches other people or can't be
taken back (effect send or destructive), it now waits out a short window
before it runs, like undo send in Gmail.
- user_settings.undo_seconds (default 10, 0 is off, max 60), exposed in the
settings API and in Settings > General (Off / 5s / 10s / 30s).
- tool_calls.execute_after. decideToolCall opens the window through the
undoDelay/startUndoWindow helpers (database clock) and re-queues the run
with lease_expires_at at the end of the window (runnableAt), so no worker
takes it early. Auto-allowed calls, reads and writes never wait.
- Runtime: reads in a step run at once; writes run in proposal order and
stop at the first one still inside its window. runAgent then returns
"running"; the worker releases the run for nextUndoWaitMs and wakes
workers when it ends. approved -> executing stays the only way to run.
- POST /api/runs/:id/tool-calls/:toolCallId/undo: compare-and-set
approved -> denied while execute_after > now(), 409 after. The model is
told "The user undid this action before it ran." and the run resumes now.
- The decision endpoint returns { executeAfter }; run detail, chat
snapshots and tool.status events carry executeAfter. Stopping a task
inside the window cancels it at once.
- Web: receipts, inbox rows and home rows show "Sending in 9s · Undo"
with a fuse that respects reduced motion, then "Undone" or the normal
running/done state. The run panel shows the countdown too.
---
apps/server/src/routes/account.ts | 5 +-
apps/server/src/routes/chats.ts | 1 +
apps/server/src/routes/runs.ts | 65 +-
apps/server/src/server.test.ts | 2 +-
apps/server/src/undo.test.ts | 308 +++
apps/server/src/worker.ts | 18 +-
apps/web/app/(app)/inbox/page.tsx | 72 +-
apps/web/app/(app)/page.tsx | 40 +-
apps/web/app/(app)/settings/page.tsx | 29 +-
apps/web/app/globals.css | 16 +
.../web/components/approval/approval-card.tsx | 65 +-
.../components/approval/approval-compact.tsx | 82 +-
apps/web/components/approval/undo-window.tsx | 115 +
apps/web/components/task/run-panel.tsx | 25 +-
apps/web/components/task/task-view.tsx | 13 +-
apps/web/lib/api.ts | 14 +-
apps/web/lib/steps.ts | 5 +
docs/api.md | 7 +-
packages/core/src/memory-store.ts | 19 +-
packages/core/src/runtime.test.ts | 91 +-
packages/core/src/runtime.ts | 48 +-
packages/core/src/types.ts | 7 +
packages/core/src/ui.ts | 4 +
packages/db/drizzle/0004_undo_window.sql | 2 +
packages/db/drizzle/meta/0004_snapshot.json | 1988 +++++++++++++++++
packages/db/drizzle/meta/_journal.json | 7 +
packages/db/src/db.test.ts | 16 +-
packages/db/src/runs.ts | 157 +-
packages/db/src/schema.ts | 4 +
packages/db/src/store.ts | 3 +-
30 files changed, 3158 insertions(+), 70 deletions(-)
create mode 100644 apps/server/src/undo.test.ts
create mode 100644 apps/web/components/approval/undo-window.tsx
create mode 100644 packages/db/drizzle/0004_undo_window.sql
create mode 100644 packages/db/drizzle/meta/0004_snapshot.json
diff --git a/apps/server/src/routes/account.ts b/apps/server/src/routes/account.ts
index 96311f4..61092a9 100644
--- a/apps/server/src/routes/account.ts
+++ b/apps/server/src/routes/account.ts
@@ -1,5 +1,5 @@
import { unsafePatternReason } from "@synapse/core";
-import { schema } from "@synapse/db";
+import { DEFAULT_UNDO_SECONDS, MAX_UNDO_SECONDS, schema } from "@synapse/db";
import { ingestDocument, searchKnowledge } from "@synapse/tools";
import { and, asc, desc, eq, gte, sql } from "drizzle-orm";
import { Hono } from "hono";
@@ -233,6 +233,7 @@ export const settings = new Hono()
providerKeys: z
.partialRecord(z.enum(PROVIDERS), z.string().min(8).max(400).nullable())
.optional(),
+ undoSeconds: z.number().int().min(0).max(MAX_UNDO_SECONDS).optional(),
}),
);
const { db } = c.var.services.database;
@@ -250,6 +251,7 @@ export const settings = new Hono()
...(input.instructions !== undefined ? { instructions: input.instructions } : {}),
...(input.models ? { models: input.models } : {}),
...(input.budgets ? { budgets: input.budgets } : {}),
+ ...(input.undoSeconds !== undefined ? { undoSeconds: input.undoSeconds } : {}),
providerKeys: keys,
};
await db
@@ -273,6 +275,7 @@ async function loadSettings(c: { var: AppEnv["Variables"] }) {
perDayUsd: config.DAY_MAX_COST_USD,
},
providerKeys: Object.fromEntries(PROVIDERS.map((p) => [p, Boolean(s?.providerKeys?.[p])])),
+ undoSeconds: s?.undoSeconds ?? DEFAULT_UNDO_SECONDS,
};
}
diff --git a/apps/server/src/routes/chats.ts b/apps/server/src/routes/chats.ts
index e3da180..445980f 100644
--- a/apps/server/src/routes/chats.ts
+++ b/apps/server/src/routes/chats.ts
@@ -73,6 +73,7 @@ export const chats = new Hono()
output: r.output,
decidedBy: r.decidedBy,
preview: r.preview,
+ executeAfter: r.executeAfter?.toISOString() ?? null,
}))
: [];
const [run] = await db
diff --git a/apps/server/src/routes/runs.ts b/apps/server/src/routes/runs.ts
index 63654e6..44023c2 100644
--- a/apps/server/src/routes/runs.ts
+++ b/apps/server/src/routes/runs.ts
@@ -1,11 +1,19 @@
-import { evaluatePolicy } from "@synapse/core";
-import { decideToolCall, PgRunStore, readEvents, requestCancel, schema } from "@synapse/db";
+import { evaluatePolicy, type RunEvent, UNDO_DENIAL } from "@synapse/core";
+import {
+ decideToolCall,
+ PgRunStore,
+ readEvents,
+ requestCancel,
+ schema,
+ undoToolCall,
+} from "@synapse/db";
import type { JSONValue } from "ai";
import { and, asc, desc, eq } from "drizzle-orm";
import { Hono } from "hono";
import { streamSSE } from "hono/streaming";
import { z } from "zod";
import { type AppEnv, apiError, body } from "../http";
+import type { Services } from "../services";
const PAUSE_OR_END = new Set(["waiting", "completed", "failed", "cancelled"]);
const EVENT_PAGE = 1000;
@@ -53,6 +61,7 @@ export const runs = new Hono()
output: schema.toolCalls.output,
decidedBy: schema.toolCalls.decidedBy,
decidedAt: schema.toolCalls.decidedAt,
+ executeAfter: schema.toolCalls.executeAfter,
createdAt: schema.toolCalls.createdAt,
})
.from(schema.toolCalls)
@@ -141,15 +150,43 @@ export const runs = new Hono()
const runId = c.req.param("id");
if (input.approved && input.input !== undefined)
await assertEditAllowed(c, runId, c.req.param("toolCallId"), input.input);
- await decideToolCall(c.var.services.database.db, {
+ const toolCallId = c.req.param("toolCallId");
+ const decided = await decideToolCall(c.var.services.database.db, {
userId: c.var.user.id,
runId,
- toolCallId: c.req.param("toolCallId"),
+ toolCallId,
approved: input.approved,
...(input.reason ? { reason: input.reason } : {}),
...(input.input !== undefined ? { editedInput: input.input } : {}),
});
- await c.var.services.wake(runId);
+ const { services } = c.var;
+ const { executeAfter } = decided;
+ if (executeAfter) {
+ // Live viewers (another tab, the run panel) get the countdown too.
+ await emitNow(services, runId, {
+ type: "tool.status",
+ toolCallId,
+ status: "approved",
+ executeAfter: executeAfter.toISOString(),
+ });
+ }
+ if (decided.requeued && decided.runnableAt) {
+ // Parked until the window ends: it is queued, not waiting on you.
+ await emitNow(services, runId, { type: "run.status", status: "queued" });
+ wakeAt(services, runId, decided.runnableAt);
+ } else await services.wake(runId);
+ return c.json({ executeAfter: executeAfter?.toISOString() ?? null });
+ })
+
+ .post("/:id/tool-calls/:toolCallId/undo", async (c) => {
+ const runId = c.req.param("id");
+ const toolCallId = c.req.param("toolCallId");
+ const { services } = c.var;
+ await undoToolCall(services.database.db, { userId: c.var.user.id, runId, toolCallId });
+ const output = { type: "denied" as const, reason: UNDO_DENIAL };
+ await emitNow(services, runId, { type: "tool.status", toolCallId, status: "denied" });
+ await emitNow(services, runId, { type: "tool.result", toolCallId, output });
+ await services.wake(runId);
return c.body(null, 204);
})
@@ -191,6 +228,24 @@ export const approvals = new Hono().get("/", async (c) => {
return c.json({ approvals: rows });
});
+/**
+ * Appends an event for a run no worker may be driving (it is parked). Forgets the cached
+ * seq afterwards so a later writer on this instance re-reads the tail.
+ */
+async function emitNow(services: Services, runId: string, event: RunEvent) {
+ await services.events.emit(runId, event);
+ services.events.forget(runId);
+}
+
+/** Wakes workers when a run parked on an undo window becomes claimable, not on the next poll. */
+function wakeAt(services: Services, runId: string, at: Date) {
+ const timer = setTimeout(
+ () => void services.wake(runId).catch(() => {}),
+ Math.max(0, at.getTime() - Date.now()) + 25,
+ );
+ timer.unref?.();
+}
+
/** Edited arguments are re-checked against block rules: editing must not route around them. */
async function assertEditAllowed(
c: { var: AppEnv["Variables"] },
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 8c2eddb..3360240 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -164,7 +164,7 @@ test("policy block, approvals inbox and decisions over HTTP", async () => {
json: { approved: true, input: { note: "likes green tea" } },
})
).status,
- ).toBe(204);
+ ).toBe(200);
expect((await grace(path, { method: "POST", json: { approved: true } })).status).toBe(409);
await worker.processNow(runId);
diff --git a/apps/server/src/undo.test.ts b/apps/server/src/undo.test.ts
new file mode 100644
index 0000000..f86288b
--- /dev/null
+++ b/apps/server/src/undo.test.ts
@@ -0,0 +1,308 @@
+import { afterAll, beforeAll, expect, test } from "bun:test";
+import { UNDO_DENIAL } from "@synapse/core";
+import { type ScriptedStep, scriptedModel } from "@synapse/core/testing";
+import { readEvents, schema } from "@synapse/db";
+import { fakeGoogle } from "@synapse/tools/testing";
+import { and, eq } from "drizzle-orm";
+import { createApp } from "./app";
+import { loadConfig } from "./config";
+import { createServices, type Services } from "./services";
+import { Worker } from "./worker";
+
+const ORIGIN = "http://localhost:3000";
+const google = fakeGoogle({ email: "ada@example.com" });
+let services: Services;
+let app: ReturnType;
+let worker: Worker;
+let model = scriptedModel([]);
+const script = (steps: ScriptedStep[]) => {
+ model = scriptedModel(steps);
+};
+
+beforeAll(async () => {
+ services = await createServices(
+ loadConfig({
+ NODE_ENV: "test",
+ DATABASE_URL: "pglite://memory",
+ SYNAPSE_SECRET: "t".repeat(40),
+ PUBLIC_URL: ORIGIN,
+ GOOGLE_CLIENT_ID: "cid",
+ GOOGLE_CLIENT_SECRET: "secret",
+ }),
+ );
+ services.config.google!.fetch = google.fetch;
+ app = createApp(services);
+ worker = new Worker(services, () => [model]);
+});
+afterAll(() => services.close());
+
+type Call = (
+ path: string,
+ init?: { method?: string; json?: unknown },
+) => Promise<{
+ status: number;
+ // biome-ignore lint/suspicious/noExplicitAny: test responses are loosely typed JSON
+ json: any;
+}>;
+
+async function signUp(email: string): Promise {
+ const res = await app.request("/api/auth/sign-up/email", {
+ method: "POST",
+ headers: { "content-type": "application/json", origin: ORIGIN },
+ body: JSON.stringify({ email, password: "correct horse battery", name: email.split("@")[0] }),
+ });
+ expect(res.status).toBe(200);
+ const cookie = res.headers
+ .getSetCookie()
+ .map((c) => c.split(";")[0])
+ .join("; ");
+ return async (path, init = {}) => {
+ const r = await app.request(path, {
+ method: init.method ?? "GET",
+ headers: {
+ cookie,
+ origin: ORIGIN,
+ ...(init.json !== undefined ? { "content-type": "application/json" } : {}),
+ },
+ ...(init.json !== undefined ? { body: JSON.stringify(init.json) } : {}),
+ });
+ const text = await r.text();
+ return { status: r.status, json: text ? JSON.parse(text) : null };
+ };
+}
+
+async function connectedUser(email: string, undoSeconds?: number): Promise {
+ const me = await signUp(email);
+ const start = await me("/api/integrations/google/connect", { method: "POST", json: {} });
+ const state = new URL(start.json.url).searchParams.get("state")!;
+ await me(`/api/integrations/google/callback?code=abc&state=${encodeURIComponent(state)}`);
+ if (undoSeconds !== undefined) {
+ const res = await me("/api/settings", { method: "PUT", json: { undoSeconds } });
+ expect(res.json.undoSeconds).toBe(undoSeconds);
+ }
+ return me;
+}
+
+const sentTo = (to: string) =>
+ google.state.messages.filter((m) => m.labelIds.includes("SENT") && JSON.stringify(m).includes(to))
+ .length;
+
+const sendStep = (to: string, id: string): ScriptedStep => ({
+ toolCalls: [{ name: "gmail_send", id, input: { to: [to], subject: "Hi", body: "Hello" } }],
+});
+
+async function runOf(runId: string) {
+ const [run] = await services.database.db
+ .select()
+ .from(schema.runs)
+ .where(eq(schema.runs.id, runId));
+ return run!;
+}
+
+async function callOf(runId: string, id: string) {
+ const [call] = await services.database.db
+ .select()
+ .from(schema.toolCalls)
+ .where(and(eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.id, id)));
+ return call!;
+}
+
+/** Fast-forwards the undo window: the call is due and the run is claimable. */
+async function endWindow(runId: string, id: string) {
+ const past = new Date(Date.now() - 1000);
+ const { db } = services.database;
+ await db
+ .update(schema.toolCalls)
+ .set({ executeAfter: past })
+ .where(and(eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.id, id)));
+ await db.update(schema.runs).set({ leaseExpiresAt: past }).where(eq(schema.runs.id, runId));
+}
+
+/** Starts a task whose first step proposes one call, and drives it to the approval. */
+async function proposed(me: Call, first: ScriptedStep, then = "Done.") {
+ script([first, { text: then }]);
+ const { json } = await me("/api/chats", { method: "POST", json: { content: "Go" } });
+ await worker.processNow(json.runId);
+ expect((await runOf(json.runId)).status).toBe("waiting");
+ return json.runId as string;
+}
+
+test("settings expose the undo window, default 10s, capped at 60", async () => {
+ const me = await signUp("settings@example.com");
+ expect((await me("/api/settings")).json.undoSeconds).toBe(10);
+ expect((await me("/api/settings", { method: "PUT", json: { undoSeconds: 61 } })).status).toBe(
+ 422,
+ );
+ expect(
+ (await me("/api/settings", { method: "PUT", json: { undoSeconds: 0 } })).json.undoSeconds,
+ ).toBe(0);
+});
+
+test("an approved send waits out its window, then runs exactly once", async () => {
+ const me = await connectedUser("wait@example.com");
+ const runId = await proposed(me, sendStep("wait@x.test", "s1"));
+
+ const decided = await me(`/api/runs/${runId}/tool-calls/s1/decision`, {
+ method: "POST",
+ json: { approved: true },
+ });
+ expect(decided.status).toBe(200);
+ const executeAfter = Date.parse(decided.json.executeAfter);
+ expect(executeAfter - Date.now()).toBeGreaterThan(8_000);
+ expect(executeAfter - Date.now()).toBeLessThanOrEqual(10_500);
+
+ // Re-queued for when the window ends, so no worker takes it early.
+ const parked = await runOf(runId);
+ expect(parked.status).toBe("queued");
+ expect(parked.leaseExpiresAt!.getTime()).toBe(executeAfter);
+ expect(await worker.processNow(runId)).toBe(false);
+ expect(sentTo("wait@x.test")).toBe(0);
+
+ // The run detail and the event stream carry the deadline for a countdown.
+ const detail = await me(`/api/runs/${runId}`);
+ expect(detail.json.toolCalls[0]).toMatchObject({ status: "approved" });
+ expect(Date.parse(detail.json.toolCalls[0].executeAfter)).toBe(executeAfter);
+ const chat = await me(`/api/chats/${parked.chatId}`);
+ const part = chat.json.messages
+ .flatMap((m: { parts: unknown[] }) => m.parts)
+ .find((p: { toolCallId?: string }) => p.toolCallId === "s1");
+ expect(Date.parse(part.executeAfter)).toBe(executeAfter);
+ const log = await readEvents(services.database, runId, 0);
+ expect(log.slice(-2)).toMatchObject([
+ { type: "tool.status", toolCallId: "s1", status: "approved", executeAfter: expect.any(String) },
+ { type: "run.status", status: "queued" },
+ ]);
+
+ await endWindow(runId, "s1");
+ expect(await worker.processNow(runId)).toBe(true);
+ expect(sentTo("wait@x.test")).toBe(1);
+ expect(await callOf(runId, "s1")).toMatchObject({ status: "succeeded" });
+ expect((await runOf(runId)).status).toBe("completed");
+ expect(await worker.processNow(runId)).toBe(false);
+ expect(sentTo("wait@x.test")).toBe(1);
+
+ // Too late now.
+ const late = await me(`/api/runs/${runId}/tool-calls/s1/undo`, { method: "POST", json: {} });
+ expect(late.status).toBe(409);
+ expect(late.json.error.message).toContain("Too late to undo");
+});
+
+test("a worker that reaches a call early parks the run until the window ends", async () => {
+ const me = await connectedUser("early@example.com", 1);
+ const runId = await proposed(me, sendStep("early@x.test", "s1"));
+ await me(`/api/runs/${runId}/tool-calls/s1/decision`, {
+ method: "POST",
+ json: { approved: true },
+ });
+ // Something re-queued the run before the window ended (e.g. a stop-after-step request).
+ await services.database.db
+ .update(schema.runs)
+ .set({ leaseExpiresAt: null })
+ .where(eq(schema.runs.id, runId));
+ expect(await worker.processNow(runId)).toBe(true);
+ expect(sentTo("early@x.test")).toBe(0);
+ const parked = await runOf(runId);
+ expect(parked).toMatchObject({ status: "queued", leaseOwner: null, attempts: 0 });
+ const call = await callOf(runId, "s1");
+ expect(parked.leaseExpiresAt!.getTime()).toBeGreaterThan(Date.now());
+ expect(parked.leaseExpiresAt!.getTime()).toBeLessThanOrEqual(call.executeAfter!.getTime() + 50);
+
+ await Bun.sleep(Math.max(0, parked.leaseExpiresAt!.getTime() - Date.now()) + 20);
+ expect(await worker.processNow(runId)).toBe(true);
+ expect(sentTo("early@x.test")).toBe(1);
+ expect((await runOf(runId)).status).toBe("completed");
+});
+
+test("undo inside the window denies the send and the agent hears why", async () => {
+ const me = await connectedUser("undo@example.com");
+ const other = await connectedUser("other@example.com");
+ const runId = await proposed(me, sendStep("undo@x.test", "s1"), "Okay, I won't send it.");
+ await me(`/api/runs/${runId}/tool-calls/s1/decision`, {
+ method: "POST",
+ json: { approved: true },
+ });
+
+ const path = `/api/runs/${runId}/tool-calls/s1/undo`;
+ expect((await other(path, { method: "POST", json: {} })).status).toBe(404);
+ expect((await me(path, { method: "POST", json: {} })).status).toBe(204);
+ expect((await me(path, { method: "POST", json: {} })).status).toBe(409);
+
+ // Re-queued right away so the agent can respond.
+ expect((await runOf(runId)).leaseExpiresAt).toBeNull();
+ expect(await worker.processNow(runId)).toBe(true);
+ expect(sentTo("undo@x.test")).toBe(0);
+ expect(await callOf(runId, "s1")).toMatchObject({
+ status: "denied",
+ output: { type: "denied", reason: UNDO_DENIAL },
+ });
+ expect(JSON.stringify(model.calls[1]!.prompt)).toContain(UNDO_DENIAL);
+ expect((await runOf(runId)).status).toBe("completed");
+});
+
+test("undo window 0 runs approved sends at once", async () => {
+ const me = await connectedUser("off@example.com", 0);
+ const runId = await proposed(me, sendStep("off@x.test", "s1"));
+ const decided = await me(`/api/runs/${runId}/tool-calls/s1/decision`, {
+ method: "POST",
+ json: { approved: true },
+ });
+ expect(decided.json.executeAfter).toBeNull();
+ expect(await worker.processNow(runId)).toBe(true);
+ expect(sentTo("off@x.test")).toBe(1);
+ expect(
+ (await me(`/api/runs/${runId}/tool-calls/s1/undo`, { method: "POST", json: {} })).status,
+ ).toBe(409);
+});
+
+test("auto-allowed sends and approved writes are not delayed", async () => {
+ const me = await connectedUser("allow@example.com");
+ await me("/api/policy", {
+ method: "PUT",
+ json: {
+ defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" },
+ rules: [
+ { tool: "gmail_send", decision: "allow" },
+ { tool: "gmail_create_draft", decision: "ask" },
+ ],
+ },
+ });
+ script([sendStep("allow@x.test", "s1"), { text: "Sent." }]);
+ const { json } = await me("/api/chats", { method: "POST", json: { content: "Go" } });
+ await worker.processNow(json.runId);
+ expect(sentTo("allow@x.test")).toBe(1);
+ expect(await callOf(json.runId, "s1")).toMatchObject({ status: "succeeded", executeAfter: null });
+
+ const runId = await proposed(me, {
+ toolCalls: [
+ {
+ name: "gmail_create_draft",
+ id: "d1",
+ input: { to: ["draft@x.test"], subject: "Hi", body: "Hello" },
+ },
+ ],
+ });
+ const decided = await me(`/api/runs/${runId}/tool-calls/d1/decision`, {
+ method: "POST",
+ json: { approved: true },
+ });
+ expect(decided.json.executeAfter).toBeNull();
+ expect(await worker.processNow(runId)).toBe(true);
+ expect(await callOf(runId, "d1")).toMatchObject({ status: "succeeded", executeAfter: null });
+ expect(google.state.drafts.length).toBeGreaterThan(0);
+});
+
+test("stopping a task inside the window cancels the send at once", async () => {
+ const me = await connectedUser("stop@example.com");
+ const runId = await proposed(me, sendStep("stop@x.test", "s1"));
+ await me(`/api/runs/${runId}/tool-calls/s1/decision`, {
+ method: "POST",
+ json: { approved: true },
+ });
+ expect(
+ (await me(`/api/runs/${runId}/cancel`, { method: "POST", json: { mode: "now" } })).status,
+ ).toBe(204);
+ expect(await worker.processNow(runId)).toBe(true);
+ expect((await runOf(runId)).status).toBe("cancelled");
+ expect(await callOf(runId, "s1")).toMatchObject({ status: "denied" });
+ expect(sentTo("stop@x.test")).toBe(0);
+});
diff --git a/apps/server/src/worker.ts b/apps/server/src/worker.ts
index c89de9c..0f2972e 100644
--- a/apps/server/src/worker.ts
+++ b/apps/server/src/worker.ts
@@ -1,6 +1,7 @@
import {
createModel,
type ModelSpec,
+ nextUndoWaitMs,
type ProviderKeys,
parseModelRef,
runAgent,
@@ -82,6 +83,14 @@ export class Worker {
this.wakers.shift()?.();
}
+ /** Nudges idle workers when a parked run becomes claimable, instead of waiting for a poll. */
+ private wakeLater(runId: string, ms: number) {
+ const timer = setTimeout(() => {
+ if (!this.stopped) void this.s.wake(runId).catch(() => {});
+ }, ms + 25);
+ timer.unref?.();
+ }
+
private idle(): Promise {
return new Promise((resolve) => {
const done = () => {
@@ -246,8 +255,13 @@ export class Worker {
},
});
await events.flush(runId);
- if (status !== "running") await resetAttempts(db, runId);
- await releaseRun(db, runId, this.id);
+ await resetAttempts(db, runId);
+ // "running" means parked on an undo window: come back exactly when it ends. Read
+ // fresh so an undo that landed meanwhile resumes the run now.
+ const wait =
+ status === "running" ? nextUndoWaitMs(await new PgRunStore(db).listToolCalls(runId)) : 0;
+ await releaseRun(db, runId, this.id, wait);
+ if (wait > 0) this.wakeLater(runId, wait);
} catch (error) {
await events.flush(runId).catch(() => {});
if (controller.signal.aborted) {
diff --git a/apps/web/app/(app)/inbox/page.tsx b/apps/web/app/(app)/inbox/page.tsx
index cb3167b..6d7d383 100644
--- a/apps/web/app/(app)/inbox/page.tsx
+++ b/apps/web/app/(app)/inbox/page.tsx
@@ -10,6 +10,7 @@ import {
approvalTitle,
MiniStamp,
} from "@/components/approval/approval-card";
+import { UndoCountdown, type UndoTarget, useTimeLeft } from "@/components/approval/undo-window";
import { Markdown } from "@/components/markdown";
import { EffectPill, Kbd, Monogram, Skeleton, StatusDot } from "@/components/ui";
import { type Approval, api } from "@/lib/api";
@@ -22,6 +23,52 @@ interface Decided {
approved: boolean;
reason?: string;
edited: boolean;
+ /** Set when an approved send or delete waits out its undo window. */
+ executeAfter?: string | null;
+ /** Taken back inside the undo window. */
+ undone?: boolean;
+}
+
+function undoTarget(a: Approval, d: Decided): UndoTarget | null {
+ return d.executeAfter
+ ? { runId: a.runId, toolCallId: a.toolCallId, executeAfter: d.executeAfter }
+ : null;
+}
+
+/** A signed row whose send is still inside its undo window. */
+function rowUndo(a: Approval, d: Decided | undefined): UndoTarget | null {
+ return d?.approved && !d.undone ? undoTarget(a, d) : null;
+}
+
+/** The row's age, or nothing while its undo countdown sits in that corner. */
+function RowTime({ createdAt, undo }: { createdAt: string; undo: UndoTarget | null }) {
+ const left = useTimeLeft(undo?.executeAfter);
+ if (undo && left > 0) return null;
+ return (
+
+ {formatRelative(createdAt)}
+
+ );
+}
+
+/** "Sending in 9s · Undo" on the row itself, so it stays reachable after the pane moves on. */
+function RowUndo({
+ target,
+ effect,
+ onUndone,
+}: {
+ target: UndoTarget;
+ effect: Approval["effect"];
+ onUndone: () => void;
+}) {
+ return (
+
+ );
}
function isTyping(e: KeyboardEvent) {
@@ -103,6 +150,11 @@ export default function InboxPage() {
return () => document.removeEventListener("keydown", onKey);
}, [move, current, decided]);
+ function markUndone(id: string) {
+ setDecided((m) => (m[id] ? { ...m, [id]: { ...m[id], undone: true } } : m));
+ void reload();
+ }
+
function onDecided(a: Approval, d: Decided) {
setKept((k) => ({ ...k, [a.toolCallId]: a }));
setDecided((m) => ({ ...m, [a.toolCallId]: d }));
@@ -172,7 +224,7 @@ export default function InboxPage() {
const on = a.toolCallId === selected;
const { source } = splitToolName(a.name);
return (
-
+
{d ? (
-
- {d.approved ? "Approved" : "Denied"}
+
+ {d.undone ? "Undone" : d.approved ? "Approved" : "Denied"}
) : (
)}
-
- {formatRelative(a.createdAt)}
-
+
+ {rowUndo(a, d) ? (
+ markUndone(a.toolCallId)}
+ />
+ ) : null}
);
})}
@@ -283,6 +340,9 @@ export default function InboxPage() {
approved={decided[current.toolCallId]!.approved}
reason={decided[current.toolCallId]!.reason}
edited={decided[current.toolCallId]!.edited}
+ undo={undoTarget(current, decided[current.toolCallId]!)}
+ undone={decided[current.toolCallId]!.undone}
+ onUndone={() => markUndone(current.toolCallId)}
phase="continuing"
/>
{pending.length === 0 ? (
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index c242dfb..e806b18 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -17,7 +17,14 @@ import {
TaintShield,
taskStatus,
} from "@/components/ui";
-import { type Automation, api, type ChatSummary, type Connection, errorMessage } from "@/lib/api";
+import {
+ type Approval,
+ type Automation,
+ api,
+ type ChatSummary,
+ type Connection,
+ errorMessage,
+} from "@/lib/api";
import { describeCron } from "@/lib/cron";
import {
cx,
@@ -130,6 +137,15 @@ export default function HomePage() {
const running = (tasks ?? []).filter((t) => taskStatus(t.status) === "running").length;
const needs = approvals?.length ?? 0;
+ // Rows approved here stay while their undo window runs, even after a reload drops them.
+ const [held, setHeld] = useState>({});
+ const rows = useMemo(() => {
+ if (!approvals) return approvals;
+ const live = new Set(approvals.map((a) => a.toolCallId));
+ const kept = Object.values(held).filter((a) => !live.has(a.toolCallId));
+ return [...kept, ...approvals].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
+ }, [approvals, held]);
+ const listed = rows?.length ?? 0;
const name = firstName(user?.name);
const suggestions = useMemo(() => suggestionsFor(conns.data?.connections), [conns.data]);
@@ -226,7 +242,7 @@ export default function HomePage() {
/>
) : null}
- {needs > 0 || !showGuide ? (
+ {listed > 0 || !showGuide ? (
{approvals === null ? (
- ) : needs === 0 ? (
+ ) : listed === 0 ? (
@@ -260,15 +276,25 @@ export default function HomePage() {
) : (
- {approvals!.slice(0, 3).map((a) => (
+ {rows!.slice(0, 3).map((a) => (
- void reload()} />
+ setHeld((h) => ({ ...h, [a.toolCallId]: a }))}
+ onDone={() => {
+ setHeld((h) => {
+ const { [a.toolCallId]: _gone, ...rest } = h;
+ return rest;
+ });
+ void reload();
+ }}
+ />
))}
- {needs > 3 ? (
+ {listed > 3 ? (
- and {plural(needs - 3, "more")} in the inbox
+ and {plural(listed - 3, "more")} in the inbox
) : null}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 8c643d2..d3327a1 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -18,7 +18,7 @@ import {
import { useRouter } from "next/navigation";
import { type ReactNode, useEffect, useMemo, useState } from "react";
import { useToast } from "@/components/toast";
-import { ErrorNote, Field, Page, PageHeader, Pill, Skeleton } from "@/components/ui";
+import { ErrorNote, Field, Page, PageHeader, Pill, Segmented, Skeleton } from "@/components/ui";
import {
api,
errorMessage,
@@ -290,10 +290,37 @@ function General({ settings, save }: { settings: Settings; save: SaveFn }) {
setText(settings.instructions ?? "");
}}
/>
+
);
}
+const UNDO_OPTIONS = ["0", "5", "10", "30"] as const;
+
+/** Saved on click, like the theme: there's nothing to draft. */
+function UndoWindow({ settings, save }: { settings: Settings; save: SaveFn }) {
+ const [value, setValue] = useState(String(settings.undoSeconds));
+ useEffect(() => setValue(String(settings.undoSeconds)), [settings.undoSeconds]);
+ return (
+
+
+ label="Undo window"
+ value={value}
+ options={UNDO_OPTIONS.map((v) => ({ value: v, label: v === "0" ? "Off" : `${v}s` }))}
+ onChange={async (v) => {
+ const prev = value;
+ setValue(v);
+ if (!(await save({ undoSeconds: Number(v) }))) setValue(prev);
+ }}
+ />
+
+ );
+}
+
function Models({ settings, save, known }: { settings: Settings; save: SaveFn; known: string[] }) {
const [chain, setChain] = useState(settings.models.chain);
const [picking, setPicking] = useState(false);
diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css
index 8cbb203..057f03c 100644
--- a/apps/web/app/globals.css
+++ b/apps/web/app/globals.css
@@ -1090,3 +1090,19 @@ a:hover > .brand .brand-spark {
.tour-progress {
animation: tour-progress var(--dwell, 4800ms) linear both;
}
+
+/* Undo window: a fuse that burns down while an approved send can still be taken back. */
+@keyframes undo-fuse {
+ to {
+ transform: scaleX(0);
+ }
+}
+.undo-fuse {
+ transform-origin: left;
+ animation: undo-fuse var(--fuse, 10s) linear both;
+}
+@media (prefers-reduced-motion: reduce) {
+ .undo-fuse {
+ display: none;
+ }
+}
diff --git a/apps/web/components/approval/approval-card.tsx b/apps/web/components/approval/approval-card.tsx
index 12fdf79..b54fce5 100644
--- a/apps/web/components/approval/approval-card.tsx
+++ b/apps/web/components/approval/approval-card.tsx
@@ -25,6 +25,7 @@ import {
sameJson,
toDrafts,
} from "./payload";
+import { UndoCountdown, UndoFuse, type UndoTarget, useTimeLeft } from "./undo-window";
export interface ApprovalHandle {
approve: () => void;
@@ -44,7 +45,10 @@ export interface ApprovalCardProps {
/** One gentle amber glow when the card first appears. */
glow?: boolean;
/** Called after the server accepted the decision (204). */
- onDecided: (approved: boolean, info: { reason?: string; edited: boolean }) => void;
+ onDecided: (
+ approved: boolean,
+ info: { reason?: string; edited: boolean; executeAfter: string | null },
+ ) => void;
/** Called on 409 (already decided / run moved on) so the caller can refetch. */
onConflict: () => void;
handle?: Ref;
@@ -162,8 +166,12 @@ export function ApprovalCard(props: ApprovalCardProps) {
if (!approved && denyReason.trim()) body.reason = denyReason.trim();
setBusy(approved ? "approve" : "deny");
try {
- await api.decide(runId, toolCallId, body);
- const info = { reason: body.reason, edited: approved && isEdited };
+ const res = await api.decide(runId, toolCallId, body);
+ const info = {
+ reason: body.reason,
+ edited: approved && isEdited,
+ executeAfter: res?.executeAfter ?? null,
+ };
const onDecided = props.onDecided;
settle.current = () => onDecided(approved, info);
setStamped(approved ? "approved" : "denied");
@@ -442,6 +450,9 @@ export function ApprovalReceipt({
reason,
phase,
edited,
+ undo,
+ undone: undoneBefore,
+ onUndone,
className,
}: {
name: string;
@@ -452,8 +463,56 @@ export function ApprovalReceipt({
/** For approved calls: what happened after. */
phase?: "running" | "done" | "failed" | "unknown" | "continuing";
edited?: boolean;
+ /** Set while an approved send or delete waits out its undo window. */
+ undo?: UndoTarget | null;
+ /** The person took it back inside the window. */
+ undone?: boolean;
+ onUndone?: () => void;
className?: string;
}) {
+ const [undoneHere, setUndoneHere] = useState(false);
+ const left = useTimeLeft(undo?.executeAfter);
+ const undone = undoneBefore || undoneHere;
+ const waiting = approved && !undone && !!undo && left > 0 && phase !== "done";
+ if (undone) {
+ return (
+
+ Undone
+ {approvalTitle(preview, name)}
+
+ {effect === "send" ? "Not sent" : "Didn't run"}
+
+
+ );
+ }
+ if (waiting && undo) {
+ return (
+
+ Approved
+ {approvalTitle(preview, name)}
+ {
+ setUndoneHere(true);
+ onUndone?.();
+ }}
+ className="shrink-0 text-fg-muted"
+ />
+
+
+ );
+ }
const outcome = approved
? phase === "failed"
? "failed"
diff --git a/apps/web/components/approval/approval-compact.tsx b/apps/web/components/approval/approval-compact.tsx
index b7f9033..6dc2be7 100644
--- a/apps/web/components/approval/approval-compact.tsx
+++ b/apps/web/components/approval/approval-compact.tsx
@@ -7,26 +7,47 @@ import { useToast } from "@/components/toast";
import { EffectPill, Monogram } from "@/components/ui";
import { ApiError, type Approval, api, errorMessage } from "@/lib/api";
import { cx, formatDateTime, formatRelative, splitToolName } from "@/lib/format";
-import { approvalTitle } from "./approval-card";
+import { approvalTitle, MiniStamp } from "./approval-card";
+import { UndoCountdown, UndoFuse, type UndoTarget, useTimeLeft } from "./undo-window";
/** How long the stamp sits on the slip before the row leaves. */
const STAMP_MS = 800;
+/** How long "Undone" stays before the row leaves. */
+const UNDONE_MS = 1500;
/** Home's "Needs you" row: enough to decide simple things, a link for the rest. */
export function ApprovalCompact({
approval: a,
onDone,
+ onHold,
}: {
approval: Approval;
onDone: () => void;
+ /** The approved action waits out an undo window: keep this row until `onDone`. */
+ onHold?: () => void;
}) {
const toast = useToast();
const [busy, setBusy] = useState(false);
const [stamped, setStamped] = useState(false);
const [error, setError] = useState(null);
+ /** Undo window: shown after the stamp, until it ends or is undone. */
+ const [undo, setUndo] = useState(null);
+ const [undone, setUndone] = useState(false);
+ const left = useTimeLeft(undo?.executeAfter);
const settle = useRef<(() => void) | null>(null);
const { source } = splitToolName(a.name);
+ const doneRef = useRef(onDone);
+ doneRef.current = onDone;
+ const over = !!undo && (undone || left <= 0);
+
+ // The window ended (or was undone): let the row leave.
+ useEffect(() => {
+ if (!over) return;
+ const timer = setTimeout(() => doneRef.current(), undone ? UNDONE_MS : 0);
+ return () => clearTimeout(timer);
+ }, [over, undone]);
+
// If the row unmounts mid-stamp, still let the caller know.
useEffect(
() => () => {
@@ -42,10 +63,14 @@ export function ApprovalCompact({
setBusy(true);
setError(null);
try {
- await api.decide(a.runId, a.toolCallId, { approved: true });
+ const { executeAfter } = (await api.decide(a.runId, a.toolCallId, { approved: true })) ?? {
+ executeAfter: null,
+ };
+ if (executeAfter) onHold?.();
settle.current = () => {
toast("Approved", "success");
- onDone();
+ if (executeAfter) setUndo({ runId: a.runId, toolCallId: a.toolCallId, executeAfter });
+ else onDone();
};
setStamped(true);
setTimeout(() => {
@@ -89,23 +114,42 @@ export function ApprovalCompact({
{error ? {error}
: null}
-
-
- Review
-
-
void approve()}
+ {undo ? (
+
+ {undone ? "Undone" : "Approved"}
+ {undone ? (
+ {a.effect === "send" ? "Not sent" : "Didn't run"}
+ ) : (
+ setUndone(true)} />
+ )}
+ {undone ? null : }
+
+ ) : (
+
- {busy ? : }
- {busy ? "Approving…" : "Approve"}
-
-
- {stamped ? (
+
+ Review
+
+ void approve()}
+ >
+ {busy ? (
+
+ ) : (
+
+ )}
+ {busy ? "Approving…" : "Approve"}
+
+
+ )}
+ {stamped && !undo ? (
msLeft(deadline));
+ useEffect(() => {
+ setLeft(msLeft(deadline));
+ if (msLeft(deadline) <= 0) return;
+ const timer = setInterval(() => {
+ const next = msLeft(deadline);
+ setLeft(next);
+ if (next <= 0) clearInterval(timer);
+ }, 250);
+ return () => clearInterval(timer);
+ }, [deadline]);
+ return left;
+}
+
+/** True while an approved call still waits on its window. */
+export function inUndoWindow(executeAfter: string | null | undefined) {
+ return msLeft(executeAfter) > 0;
+}
+
+/**
+ * "Sending in 9s · Undo". Renders nothing once the window is over; the caller then shows
+ * the normal running/done state. `onUndone` fires after the server took it back.
+ */
+export function UndoCountdown({
+ target,
+ effect,
+ onUndone,
+ className,
+}: {
+ target: UndoTarget;
+ effect: Effect;
+ onUndone: () => void;
+ className?: string;
+}) {
+ const toast = useToast();
+ const left = useTimeLeft(target.executeAfter);
+ const [busy, setBusy] = useState(false);
+ if (left <= 0) return null;
+ const seconds = Math.ceil(left / 1000);
+ const verb = effect === "send" ? "Sending" : "Running";
+
+ async function undo() {
+ if (busy) return;
+ setBusy(true);
+ try {
+ await api.undo(target.runId, target.toolCallId);
+ onUndone();
+ } catch (err) {
+ toast(
+ err instanceof ApiError && err.status === 409
+ ? "Too late to undo: it already ran."
+ : errorMessage(err),
+ "error",
+ );
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+
+
+ {verb} in {seconds}s
+
+
+ ·
+
+ void undo()}
+ aria-label={`Undo. ${verb} in ${seconds} seconds`}
+ >
+ {busy ? "Undoing…" : "Undo"}
+
+
+ );
+}
+
+/** A thin fuse along the bottom edge that burns down with the window. Hidden for reduced motion. */
+export function UndoFuse({ executeAfter }: { executeAfter: string }) {
+ // Fixed at mount: the CSS animation runs the rest of the way on its own.
+ const [ms] = useState(() => msLeft(executeAfter));
+ if (ms <= 0) return null;
+ return (
+
+ );
+}
diff --git a/apps/web/components/task/run-panel.tsx b/apps/web/components/task/run-panel.tsx
index 528dd1b..35a9323 100644
--- a/apps/web/components/task/run-panel.tsx
+++ b/apps/web/components/task/run-panel.tsx
@@ -6,6 +6,7 @@ import { ChevronRight, ShieldAlert, User, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { approvalTitle } from "@/components/approval/approval-card";
import { PayloadView } from "@/components/approval/payload";
+import { useTimeLeft } from "@/components/approval/undo-window";
import { EffectPill, Monogram, StepStatusIcon, Tabs } from "@/components/ui";
import type { TaskRun } from "@/lib/api";
import {
@@ -18,7 +19,14 @@ import {
prettyJson,
splitToolName,
} from "@/lib/format";
-import { denialReason, policySummary, type Step, stepsOf, taintStepId } from "@/lib/steps";
+import {
+ denialReason,
+ isUndone,
+ policySummary,
+ type Step,
+ stepsOf,
+ taintStepId,
+} from "@/lib/steps";
export type PanelTab = "activity" | "details";
@@ -154,6 +162,19 @@ function ActivityTimeline({
);
}
+/** The step's status, with a live countdown while an approved send waits out its undo window. */
+function StepStatusText({ part: p }: { part: Step["part"] }) {
+ const left = useTimeLeft(p.status === "approved" ? p.executeAfter : null);
+ if (left > 0)
+ return (
+
+ {p.effect === "send" ? "Sending" : "Running"} in {Math.ceil(left / 1000)}s
+
+ );
+ if (isUndone(p.output)) return <>Undone>;
+ return <>{STATUS_TEXT[p.status] ?? p.status}>;
+}
+
function TimelineStep({ step, taint, focused }: { step: Step; taint: boolean; focused: boolean }) {
const p = step.part;
const [open, setOpen] = useState(focused);
@@ -193,7 +214,7 @@ function TimelineStep({ step, taint, focused }: { step: Step; taint: boolean; fo
["failed", "denied"].includes(p.status) && "text-danger",
)}
>
- {STATUS_TEXT[p.status] ?? p.status}
+
{p.decision === "ask" &&
p.status !== "awaiting_approval" &&
diff --git a/apps/web/components/task/task-view.tsx b/apps/web/components/task/task-view.tsx
index 0ffd69c..612bbad 100644
--- a/apps/web/components/task/task-view.tsx
+++ b/apps/web/components/task/task-view.tsx
@@ -12,7 +12,7 @@ import { useToast } from "@/components/toast";
import { EmptyState, Skeleton, StatusPill, TaintShield, taskStatus } from "@/components/ui";
import { ApiError, api, errorMessage, type TaskRun } from "@/lib/api";
import { cx, formatCost } from "@/lib/format";
-import { denialReason, receiptPhase, type ToolPart } from "@/lib/steps";
+import { denialReason, isUndone, receiptPhase, type ToolPart } from "@/lib/steps";
import { useMedia } from "@/lib/use-media";
import { useRunStream } from "@/lib/use-run-stream";
import { useWorkspace } from "@/lib/workspace";
@@ -28,6 +28,8 @@ interface Decided {
approved: boolean;
reason?: string;
edited: boolean;
+ /** Set when an approved send or delete waits out its undo window. */
+ executeAfter?: string | null;
}
const PANEL_KEY = "synapse-run-panel";
@@ -227,6 +229,11 @@ export function TaskView({ taskId }: { taskId: string }) {
function renderAsked(part: ToolPart, message: UiMessage) {
const runId = message.runId ?? run?.id;
const d = decided[part.toolCallId];
+ const executeAfter = d?.executeAfter ?? part.executeAfter;
+ const undo =
+ runId && executeAfter && (part.status === "approved" || part.status === "awaiting_approval")
+ ? { runId, toolCallId: part.toolCallId, executeAfter }
+ : null;
if (d) {
return (
);
@@ -248,6 +257,8 @@ export function TaskView({ taskId }: { taskId: string }) {
effect={part.effect}
approved={part.status !== "denied"}
reason={denialReason(part.output)}
+ undo={undo}
+ undone={isUndone(part.output)}
phase={receiptPhase(part)}
/>
);
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index f42b179..064f83e 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -164,6 +164,8 @@ export interface AuditToolCall {
inputEdited?: boolean;
decidedBy: string | null;
decidedAt: string | null;
+ /** Undo window: when an approved call runs (ISO), if it had to wait. */
+ executeAfter?: string | null;
createdAt: string;
}
@@ -240,6 +242,8 @@ export interface Settings {
models: { chain: string[]; defaultChain?: string[] };
budgets: { perRunUsd: number | null; perDayUsd: number | null };
providerKeys: Record;
+ /** Seconds an approved send or delete waits, with an Undo, before it runs. 0 is off. */
+ undoSeconds: number;
}
export interface SettingsUpdate {
@@ -247,6 +251,7 @@ export interface SettingsUpdate {
models?: { chain: string[] };
budgets?: { perRunUsd: number | null; perDayUsd: number | null };
providerKeys?: Partial>;
+ undoSeconds?: number;
}
export interface ModelInfo {
@@ -352,7 +357,14 @@ export const api = {
runId: string,
toolCallId: string,
body: { approved: boolean; reason?: string; input?: unknown },
- ) => post(`/api/runs/${enc(runId)}/tool-calls/${enc(toolCallId)}/decision`, body),
+ ) =>
+ post<{ executeAfter: string | null }>(
+ `/api/runs/${enc(runId)}/tool-calls/${enc(toolCallId)}/decision`,
+ body,
+ ),
+ /** Takes back an approved send or delete while its undo window is open (409 once it ran). */
+ undo: (runId: string, toolCallId: string) =>
+ post(`/api/runs/${enc(runId)}/tool-calls/${enc(toolCallId)}/undo`),
cancel: (runId: string, mode: "now" | "after_step" = "now") =>
post(`/api/runs/${enc(runId)}/cancel`, { mode }),
runs: (limit = 50) => get<{ runs: RunRow[] }>(`/api/runs?limit=${limit}`),
diff --git a/apps/web/lib/steps.ts b/apps/web/lib/steps.ts
index 79ea3ff..20f12f8 100644
--- a/apps/web/lib/steps.ts
+++ b/apps/web/lib/steps.ts
@@ -34,6 +34,11 @@ export function denialReason(output: ToolOutput | null, fallback?: string | null
return fallback ?? null;
}
+/** Denied because the person pressed Undo inside the undo window. */
+export function isUndone(output: ToolOutput | null): boolean {
+ return output?.type === "denied" && /^the user undid this action/i.test(output.reason);
+}
+
export function receiptPhase(p: ToolPart): "running" | "done" | "failed" | "unknown" {
if (p.status === "succeeded") return "done";
if (p.status === "failed") return "failed";
diff --git a/docs/api.md b/docs/api.md
index 77dca7f..d80524d 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -39,10 +39,11 @@ agent reads it at its next step; if the run is waiting on approvals, those are d
| Method | Path | Body | Response |
|---|---|---|---|
| GET | `/api/runs/:id/events?after=` | | **SSE** stream (see below) |
-| POST | `/api/runs/:id/tool-calls/:toolCallId/decision` | `{ approved: boolean, reason?: string, input?: unknown }` | `204`; `409` if no longer awaiting approval. `input` replaces the arguments (edited on the approval card) |
+| POST | `/api/runs/:id/tool-calls/:toolCallId/decision` | `{ approved: boolean, reason?: string, input?: unknown }` | `{ executeAfter: string \| null }`; `409` if no longer awaiting approval. `input` replaces the arguments (edited on the approval card). Approving a `send` or `destructive` call opens the user's undo window: it runs at `executeAfter`, not before |
+| POST | `/api/runs/:id/tool-calls/:toolCallId/undo` | | `204`; `409` once the window has ended ("Too late to undo: it already ran."). The call is denied and the agent is told the user undid it |
| POST | `/api/runs/:id/cancel` | `{ mode: "now" \| "after_step" }` | `204` |
| GET | `/api/runs?limit=50` | | `{ runs: { id, chatId, chatTitle, status, trigger, model, steps, inputTokens, outputTokens, costUsd, error, createdAt, finishedAt }[] }` |
-| GET | `/api/runs/:id` | | `{ run, toolCalls: { id, name, effect, status, decision, decisionReason, input, output, decidedBy, decidedAt, createdAt }[] }` (audit view) |
+| GET | `/api/runs/:id` | | `{ run, toolCalls: { id, name, effect, status, decision, decisionReason, input, output, decidedBy, decidedAt, executeAfter, createdAt }[] }` (audit view) |
| GET | `/api/approvals` | | `{ approvals: { runId, chatId, chatTitle, toolCallId, name, effect, input, reason, preview, createdAt }[] }` — `preview` is a one-line human summary from the tool, `reason` explains why approval is needed — everything awaiting the user |
### Event stream
@@ -119,7 +120,7 @@ Gmail and Google Calendar, without an MCP server. Needs `GOOGLE_CLIENT_ID` and
| Method | Path | Body | Response |
|---|---|---|---|
-| GET | `/api/settings` | | `{ instructions: string \| null, models: { chain: string[] }, budgets: { perRunUsd, perDayUsd }, providerKeys: Record<"anthropic"\|"openai"\|"google"\|"gateway", boolean> }` — keys are write-only |
+| GET | `/api/settings` | | `{ instructions: string \| null, models: { chain: string[] }, budgets: { perRunUsd, perDayUsd }, providerKeys: Record<"anthropic"\|"openai"\|"google"\|"gateway", boolean>, undoSeconds: number }` — keys are write-only; `undoSeconds` (0–60, default 10, 0 is off) is the undo window for sends and deletes |
| PUT | `/api/settings` | partial of the above; `providerKeys` values are strings to set, `null` to clear | same as GET |
| GET | `/api/usage?days=30` | | `{ days: { date, costUsd, runs, inputTokens, outputTokens }[] }` |
| GET | `/api/models` | | `{ models: ModelEntry[], updatedAt: string \| null }` |
diff --git a/packages/core/src/memory-store.ts b/packages/core/src/memory-store.ts
index f595184..33b3f35 100644
--- a/packages/core/src/memory-store.ts
+++ b/packages/core/src/memory-store.ts
@@ -1,5 +1,6 @@
import type { PolicyDefaults, PolicyRule } from "./policy";
import { SAFE_DEFAULTS } from "./policy";
+import { UNDO_DENIAL } from "./runtime";
import type { EventSink, RunStore } from "./store";
import type { RunEvent, RunRecord, StoredMessage, ToolCallRecord } from "./types";
@@ -124,15 +125,29 @@ export class MemoryStore implements RunStore {
return { rules: this.rules, defaults: this.defaults };
}
- /** Test helper mirroring the decision endpoint: approve or deny one awaiting call. */
- decide(id: string, approved: boolean, reason?: string) {
+ /**
+ * Test helper mirroring the decision endpoint: approve or deny one awaiting call.
+ * `undoMs` opens an undo window on an approval.
+ */
+ decide(id: string, approved: boolean, reason?: string, undoMs = 0) {
const call = this.toolCalls.get(id);
if (call?.status !== "awaiting_approval") return false;
call.status = approved ? "approved" : "denied";
+ if (approved && undoMs > 0) call.executeAfter = new Date(Date.now() + undoMs).toISOString();
if (!approved)
call.output = { type: "denied", reason: reason ?? "The user denied this action." };
return true;
}
+
+ /** Test helper mirroring the undo endpoint: approved → denied while the window is open. */
+ undo(id: string) {
+ const call = this.toolCalls.get(id);
+ if (call?.status !== "approved" || !call.executeAfter) return false;
+ if (Date.parse(call.executeAfter) <= Date.now()) return false;
+ call.status = "denied";
+ call.output = { type: "denied", reason: UNDO_DENIAL };
+ return true;
+ }
}
export class MemoryEvents implements EventSink {
diff --git a/packages/core/src/runtime.test.ts b/packages/core/src/runtime.test.ts
index 675b69c..6c76bdb 100644
--- a/packages/core/src/runtime.test.ts
+++ b/packages/core/src/runtime.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import { MemoryEvents, MemoryStore } from "./memory-store";
-import { type RunAgentOptions, runAgent } from "./runtime";
+import { nextUndoWaitMs, type RunAgentOptions, runAgent, UNDO_DENIAL } from "./runtime";
import { type ScriptedStep, scriptedModel } from "./testing";
import { type ToolDefinition, ToolRegistry } from "./tools";
@@ -459,3 +459,92 @@ describe("review fixes", () => {
expect(store.toolCalls.get("p")!.status).toBe("unknown");
});
});
+
+describe("undo window", () => {
+ const past = () => new Date(Date.now() - 1).toISOString();
+
+ test("an approved send waits for its window, then runs exactly once", async () => {
+ const { store, events, run, m, opts } = setup([
+ { toolCalls: [{ name: "send_email", input: { to: "a@b.com" }, id: "c1" }] },
+ { text: "Sent." },
+ ]);
+ expect(await runAgent(opts)).toBe("waiting");
+ store.decide("c1", true, undefined, 10_000);
+
+ expect(await runAgent(opts)).toBe("running");
+ expect(executed).toEqual([]);
+ expect(store.toolCalls.get("c1")!.status).toBe("approved");
+ expect(m.calls).toHaveLength(1);
+ const wait = nextUndoWaitMs(await store.listToolCalls(run.id));
+ expect(wait).toBeGreaterThan(9_000);
+ expect(wait).toBeLessThanOrEqual(10_000);
+ expect(events.events.at(-1)).toMatchObject({
+ type: "tool.status",
+ toolCallId: "c1",
+ status: "approved",
+ executeAfter: store.toolCalls.get("c1")!.executeAfter,
+ });
+
+ store.toolCalls.get("c1")!.executeAfter = past();
+ expect(await runAgent(opts)).toBe("completed");
+ expect(await runAgent(opts)).toBe("completed");
+ expect(executed).toEqual(['send_email:{"to":"a@b.com"}']);
+ expect(nextUndoWaitMs(await store.listToolCalls(run.id))).toBe(0);
+ });
+
+ test("undo inside the window denies the call and tells the model", async () => {
+ const { store, m, opts } = setup([
+ { toolCalls: [{ name: "send_email", input: { to: "a@b.com" }, id: "c1" }] },
+ { text: "Okay, not sending." },
+ ]);
+ await runAgent(opts);
+ store.decide("c1", true, undefined, 10_000);
+ expect(await runAgent(opts)).toBe("running");
+ expect(store.undo("c1")).toBe(true);
+ expect(store.undo("c1")).toBe(false);
+ expect(await runAgent(opts)).toBe("completed");
+ expect(executed).toEqual([]);
+ expect(store.toolCalls.get("c1")).toMatchObject({ status: "denied" });
+ expect(JSON.stringify(m.calls[1]!.prompt)).toContain(UNDO_DENIAL);
+ });
+
+ test("reads in the same step run now; later writes wait behind the delayed one", async () => {
+ const { store, opts } = setup([
+ {
+ toolCalls: [
+ { name: "send_email", input: { to: "a@b.com" }, id: "s1" },
+ { name: "search", input: { q: "x" }, id: "r1" },
+ { name: "send_email", input: { to: "c@d.com" }, id: "s2" },
+ ],
+ },
+ { text: "done" },
+ ]);
+ expect(await runAgent(opts)).toBe("waiting");
+ store.decide("s1", true, undefined, 10_000);
+ store.decide("s2", true); // no window (e.g. undo turned off between decisions)
+ expect(await runAgent(opts)).toBe("running");
+ expect(executed).toEqual(["search"]);
+ expect(store.toolCalls.get("s2")!.status).toBe("approved");
+
+ store.toolCalls.get("s1")!.executeAfter = past();
+ expect(await runAgent(opts)).toBe("completed");
+ expect(executed).toEqual([
+ "search",
+ 'send_email:{"to":"a@b.com"}',
+ 'send_email:{"to":"c@d.com"}',
+ ]);
+ });
+
+ test("stopping the run inside the window denies the waiting call", async () => {
+ const { store, run, opts } = setup([
+ { toolCalls: [{ name: "send_email", input: { to: "a@b.com" }, id: "c1" }] },
+ ]);
+ await runAgent(opts);
+ store.decide("c1", true, undefined, 10_000);
+ expect(await runAgent(opts)).toBe("running");
+ store.runs.get(run.id)!.cancelRequested = "now";
+ expect(await runAgent(opts)).toBe("cancelled");
+ expect(executed).toEqual([]);
+ expect(store.toolCalls.get("c1")!.status).toBe("denied");
+ });
+});
diff --git a/packages/core/src/runtime.ts b/packages/core/src/runtime.ts
index dae2930..82c3b9b 100644
--- a/packages/core/src/runtime.ts
+++ b/packages/core/src/runtime.ts
@@ -64,6 +64,9 @@ export class RunInterruptedError extends Error {
const NEW_MESSAGE_DENIAL = "The user sent a new message instead of approving this action.";
+/** What the model is told when the person undoes an approved action inside its undo window. */
+export const UNDO_DENIAL = "The user undid this action before it ran.";
+
export interface RunAgentOptions {
runId: string;
store: RunStore;
@@ -81,10 +84,33 @@ export interface RunAgentOptions {
const TERMINAL: ToolCallStatus[] = ["succeeded", "failed", "denied", "unknown"];
+/** How long until this approved call's undo window ends; 0 when it may run now. */
+export function undoRemainingMs(call: Pick, now = Date.now()) {
+ if (!call.executeAfter) return 0;
+ return Math.max(0, Date.parse(call.executeAfter) - now);
+}
+
+/**
+ * When `runAgent` returns "running", the run is parked on an undo window: this is how long
+ * until the earliest approved call may run. The caller re-queues the run for then.
+ */
+export function nextUndoWaitMs(calls: ToolCallRecord[], now = Date.now()): number {
+ let wait = 0;
+ for (const c of calls) {
+ if (c.status !== "approved") continue;
+ const ms = undoRemainingMs(c, now);
+ if (ms > 0 && (wait === 0 || ms < wait)) wait = ms;
+ }
+ return wait;
+}
+
/**
* Advances a run until it completes, fails, is cancelled, or pauses for approvals.
* Safe to call again at any point (after a crash, an approval, or a new message):
* all progress lives in the store, nothing is held in memory between calls.
+ *
+ * Returns "running" when an approved action is still inside its undo window: nothing more
+ * can happen until it ends, so the caller should come back after `nextUndoWaitMs`.
*/
export async function runAgent(opts: RunAgentOptions): Promise {
const limits = { ...DEFAULT_LIMITS, ...opts.limits };
@@ -128,6 +154,11 @@ export async function runAgent(opts: RunAgentOptions): Promise {
await setStatus("running");
continue;
}
+ if (pending === "delayed") {
+ run = await store.getRun(runId);
+ if (run.cancelRequested === "now") return await cancel(opts, run, setStatus);
+ return "running";
+ }
if (run.cancelRequested === "after_step") return await cancel(opts, run, setStatus);
// 2. Steering: messages the user sent while we were busy join the conversation now.
@@ -231,7 +262,7 @@ async function settleToolCalls(
run: RunRecord,
limits: RuntimeLimits,
signal: AbortSignal,
-): Promise<"waiting" | "settled"> {
+): Promise<"waiting" | "delayed" | "settled"> {
const calls = await opts.store.listToolCalls(run.id);
// Crash recovery: a call left "executing" was interrupted. Reads are safe to repeat;
@@ -256,8 +287,8 @@ async function settleToolCalls(
if (calls.some((c) => c.status === "awaiting_approval")) return "waiting";
const approved = calls.filter((c) => c.status === "approved");
- const reads = approved.filter((c) => c.effect === "read");
- const writes = approved.filter((c) => c.effect !== "read");
+ const reads = approved.filter((c) => c.effect === "read" && undoRemainingMs(c) === 0);
+ const writes = approved.filter((c) => !reads.includes(c));
await Promise.all(reads.map((c) => execute(opts, run, c, limits, signal)));
// Writes proposed in the same step as an untrusted read were judged before the run was
@@ -297,8 +328,19 @@ async function settleToolCalls(
}
}
+ // Writes run in the order the model proposed them. One still inside its undo window holds
+ // back the rest, so a later write never overtakes an earlier one.
for (const c of writes) {
if (signal.aborted) break;
+ if (undoRemainingMs(c) > 0) {
+ await opts.events.emit(run.id, {
+ type: "tool.status",
+ toolCallId: c.id,
+ status: "approved",
+ executeAfter: c.executeAfter ?? null,
+ });
+ return "delayed";
+ }
await execute(opts, run, c, limits, signal);
}
diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts
index ce1d292..c9e6ca6 100644
--- a/packages/core/src/types.ts
+++ b/packages/core/src/types.ts
@@ -41,6 +41,11 @@ export interface ToolCallRecord {
/** Output as given back to the model (already size-capped). */
output: ToolOutput | null;
decidedBy: string | null;
+ /**
+ * Undo window (ISO time): an approved call does not run before this. Set when a person
+ * approves a send or destructive action; null or absent means it may run now.
+ */
+ executeAfter?: string | null;
}
export type ToolOutput =
@@ -103,6 +108,8 @@ export type RunEvent =
status: ToolCallStatus;
decision?: Decision;
reason?: string | null;
+ /** For approved calls in an undo window: when it will run (ISO time). */
+ executeAfter?: string | null;
}
| { type: "tool.result"; toolCallId: string; output: ToolOutput }
| {
diff --git a/packages/core/src/ui.ts b/packages/core/src/ui.ts
index ebc7f27..eb799ea 100644
--- a/packages/core/src/ui.ts
+++ b/packages/core/src/ui.ts
@@ -28,6 +28,8 @@ export type UiPart =
reason: string | null;
output: ToolOutput | null;
preview: string | null;
+ /** Undo window: an approved call waits until this time (ISO) before it runs. */
+ executeAfter?: string | null;
};
export interface UiMessage {
@@ -99,6 +101,7 @@ export function toUiMessages(rows: StoredMessage[], calls: ToolCallRecord[]): Ui
reason: rec?.decisionReason ?? null,
output: rec?.output ?? null,
preview: rec?.preview ?? null,
+ ...(rec?.executeAfter ? { executeAfter: rec.executeAfter } : {}),
});
}
}
@@ -236,6 +239,7 @@ export function applyEvent(state: ChatState, e: SeqEvent): ChatState {
status: e.status,
...(e.decision ? { decision: e.decision } : {}),
...(e.reason !== undefined ? { reason: e.reason } : {}),
+ ...(e.executeAfter !== undefined ? { executeAfter: e.executeAfter } : {}),
});
case "approval.requested":
return updateTool(next, e.toolCallId, {
diff --git a/packages/db/drizzle/0004_undo_window.sql b/packages/db/drizzle/0004_undo_window.sql
new file mode 100644
index 0000000..76ff294
--- /dev/null
+++ b/packages/db/drizzle/0004_undo_window.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "tool_calls" ADD COLUMN "execute_after" timestamp with time zone;--> statement-breakpoint
+ALTER TABLE "user_settings" ADD COLUMN "undo_seconds" integer DEFAULT 10 NOT NULL;
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0004_snapshot.json b/packages/db/drizzle/meta/0004_snapshot.json
new file mode 100644
index 0000000..f03a17f
--- /dev/null
+++ b/packages/db/drizzle/meta/0004_snapshot.json
@@ -0,0 +1,1988 @@
+{
+ "id": "3e59264e-95ce-4687-b7ac-7b8dd1d8d2bf",
+ "prevId": "d2a38152-0d01-4c13-8d97-f967bd21a076",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.automations": {
+ "name": "automations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"type\":\"schedule\"}'::jsonb"
+ },
+ "schedule": {
+ "name": "schedule",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UTC'"
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "next_run_at": {
+ "name": "next_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cursor": {
+ "name": "cursor",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "webhook_secret": {
+ "name": "webhook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_run_at": {
+ "name": "last_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "automations_user_idx": {
+ "name": "automations_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "automations_due_idx": {
+ "name": "automations_due_idx",
+ "columns": [
+ {
+ "expression": "next_run_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "enabled",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "automations_user_id_user_id_fk": {
+ "name": "automations_user_id_user_id_fk",
+ "tableFrom": "automations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "automations_chat_id_chats_id_fk": {
+ "name": "automations_chat_id_chats_id_fk",
+ "tableFrom": "automations",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chats": {
+ "name": "chats",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chats_user_updated_idx": {
+ "name": "chats_user_updated_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chats_user_id_user_id_fk": {
+ "name": "chats_user_id_user_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chunks": {
+ "name": "chunks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "context": {
+ "name": "context",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "embedding": {
+ "name": "embedding",
+ "type": "vector(1536)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tsv": {
+ "name": "tsv",
+ "type": "tsvector",
+ "primaryKey": false,
+ "notNull": true,
+ "generated": {
+ "as": "to_tsvector('english', coalesce(context, '') || ' ' || content)",
+ "type": "stored"
+ }
+ }
+ },
+ "indexes": {
+ "chunks_user_idx": {
+ "name": "chunks_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chunks_tsv_idx": {
+ "name": "chunks_tsv_idx",
+ "columns": [
+ {
+ "expression": "tsv",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ },
+ "chunks_embedding_idx": {
+ "name": "chunks_embedding_idx",
+ "columns": [
+ {
+ "expression": "embedding",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chunks_document_id_documents_id_fk": {
+ "name": "chunks_document_id_documents_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chunks_user_id_user_id_fk": {
+ "name": "chunks_user_id_user_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.connections": {
+ "name": "connections",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth": {
+ "name": "auth",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_effects": {
+ "name": "tool_effects",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "connections_user_name_idx": {
+ "name": "connections_user_name_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "connections_user_id_user_id_fk": {
+ "name": "connections_user_id_user_id_fk",
+ "tableFrom": "connections",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.documents": {
+ "name": "documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'processing'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "documents_user_idx": {
+ "name": "documents_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "documents_user_id_user_id_fk": {
+ "name": "documents_user_id_user_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.integrations": {
+ "name": "integrations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "account": {
+ "name": "account",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integrations_user_provider_idx": {
+ "name": "integrations_user_provider_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integrations_user_id_user_id_fk": {
+ "name": "integrations_user_id_user_id_fk",
+ "tableFrom": "integrations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.memories": {
+ "name": "memories",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "memories_user_idx": {
+ "name": "memories_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "memories_user_id_user_id_fk": {
+ "name": "memories_user_id_user_id_fk",
+ "tableFrom": "memories",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "bigserial",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'message'"
+ },
+ "cutoff_seq": {
+ "name": "cutoff_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message": {
+ "name": "message",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "messages_chat_seq_idx": {
+ "name": "messages_chat_seq_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_chat_id_chats_id_fk": {
+ "name": "messages_chat_id_chats_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_run_id_runs_id_fk": {
+ "name": "messages_run_id_runs_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pending_inputs": {
+ "name": "pending_inputs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigserial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "pending_inputs_chat_idx": {
+ "name": "pending_inputs_chat_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pending_inputs_chat_id_chats_id_fk": {
+ "name": "pending_inputs_chat_id_chats_id_fk",
+ "tableFrom": "pending_inputs",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.policy_rules": {
+ "name": "policy_rules",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "tool": {
+ "name": "tool",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "when": {
+ "name": "when",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "policy_rules_user_idx": {
+ "name": "policy_rules_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "policy_rules_user_id_user_id_fk": {
+ "name": "policy_rules_user_id_user_id_fk",
+ "tableFrom": "policy_rules",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.run_events": {
+ "name": "run_events",
+ "schema": "",
+ "columns": {
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event": {
+ "name": "event",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "run_events_run_id_runs_id_fk": {
+ "name": "run_events_run_id_runs_id_fk",
+ "tableFrom": "run_events",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "run_events_run_id_seq_pk": {
+ "name": "run_events_run_id_seq_pk",
+ "columns": [
+ "run_id",
+ "seq"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.runs": {
+ "name": "runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'queued'"
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'chat'"
+ },
+ "tainted": {
+ "name": "tainted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "steps": {
+ "name": "steps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cancel_requested": {
+ "name": "cancel_requested",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lease_owner": {
+ "name": "lease_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lease_expires_at": {
+ "name": "lease_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "runs_chat_idx": {
+ "name": "runs_chat_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_user_idx": {
+ "name": "runs_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_claimable_idx": {
+ "name": "runs_claimable_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lease_expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "status in ('queued', 'running')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "runs_one_active_per_chat": {
+ "name": "runs_one_active_per_chat",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "status in ('queued', 'running', 'waiting')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "runs_chat_id_chats_id_fk": {
+ "name": "runs_chat_id_chats_id_fk",
+ "tableFrom": "runs",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "runs_user_id_user_id_fk": {
+ "name": "runs_user_id_user_id_fk",
+ "tableFrom": "runs",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tool_calls": {
+ "name": "tool_calls",
+ "schema": "",
+ "columns": {
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input": {
+ "name": "input",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input_edited": {
+ "name": "input_edited",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "effect": {
+ "name": "effect",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "preview": {
+ "name": "preview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_at": {
+ "name": "decided_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execute_after": {
+ "name": "execute_after",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output": {
+ "name": "output",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "full_output": {
+ "name": "full_output",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "tool_calls_awaiting_idx": {
+ "name": "tool_calls_awaiting_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "status = 'awaiting_approval'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tool_calls_run_id_runs_id_fk": {
+ "name": "tool_calls_run_id_runs_id_fk",
+ "tableFrom": "tool_calls",
+ "tableTo": "runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tool_calls_user_id_user_id_fk": {
+ "name": "tool_calls_user_id_user_id_fk",
+ "tableFrom": "tool_calls",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "tool_calls_run_id_id_pk": {
+ "name": "tool_calls_run_id_id_pk",
+ "columns": [
+ "run_id",
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_settings": {
+ "name": "user_settings",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "policy_defaults": {
+ "name": "policy_defaults",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "models": {
+ "name": "models",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "budgets": {
+ "name": "budgets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_keys": {
+ "name": "provider_keys",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "instructions": {
+ "name": "instructions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "undo_seconds": {
+ "name": "undo_seconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 10
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_settings_user_id_user_id_fk": {
+ "name": "user_settings_user_id_user_id_fk",
+ "tableFrom": "user_settings",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 8a2c59d..4ff1042 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -29,6 +29,13 @@
"when": 1792859791484,
"tag": "0003_triggers_and_integrations",
"breakpoints": true
+ },
+ {
+ "idx": 4,
+ "version": "7",
+ "when": 1792889484602,
+ "tag": "0004_undo_window",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/db.test.ts b/packages/db/src/db.test.ts
index 707de5b..b96a943 100644
--- a/packages/db/src/db.test.ts
+++ b/packages/db/src/db.test.ts
@@ -13,7 +13,7 @@ import {
requestCancel,
sendMessage,
} from "./runs";
-import { automations, chats, pendingInputs, runs, user } from "./schema";
+import { automations, chats, pendingInputs, runs, toolCalls, user } from "./schema";
import { PgRunStore } from "./store";
let database: Database;
@@ -67,7 +67,7 @@ describe("postgres store", () => {
await expect(
decideToolCall(database.db, { userId: "u2", runId, toolCallId: "c1", approved: true }),
).rejects.toThrow();
- await decideToolCall(database.db, {
+ const { executeAfter } = await decideToolCall(database.db, {
userId: "u1",
runId,
toolCallId: "c1",
@@ -78,8 +78,20 @@ describe("postgres store", () => {
decideToolCall(database.db, { userId: "u1", runId, toolCallId: "c1", approved: true }),
).rejects.toBeInstanceOf(ConflictError);
+ // A send waits out the default 10s undo window; the run is queued for when it ends.
const [queued] = await database.db.select().from(runs).where(eq(runs.id, runId));
expect(queued!.status).toBe("queued");
+ expect(executeAfter!.getTime() - Date.now()).toBeGreaterThan(8_000);
+ expect(queued!.leaseExpiresAt).toEqual(executeAfter);
+ expect(await runAgent(opts)).toBe("running");
+ expect((await store.listToolCalls(runId))[0]).toMatchObject({
+ status: "approved",
+ executeAfter: executeAfter!.toISOString(),
+ });
+ await database.db
+ .update(toolCalls)
+ .set({ executeAfter: new Date(Date.now() - 1) })
+ .where(eq(toolCalls.runId, runId));
expect(await runAgent(opts)).toBe("completed");
const calls = await store.listToolCalls(runId);
diff --git a/packages/db/src/runs.ts b/packages/db/src/runs.ts
index f7f7839..672e202 100644
--- a/packages/db/src/runs.ts
+++ b/packages/db/src/runs.ts
@@ -1,7 +1,8 @@
+import { type Effect, UNDO_DENIAL } from "@synapse/core";
import type { JSONValue } from "ai";
import { and, asc, eq, inArray, isNull, lt, or, sql } from "drizzle-orm";
import type { Db } from "./client";
-import { chats, messages, pendingInputs, runs, toolCalls } from "./schema";
+import { chats, messages, pendingInputs, runs, toolCalls, userSettings } from "./schema";
export class NotFoundError extends Error {}
@@ -147,10 +148,65 @@ export async function sendMessage(
});
}
+export const DEFAULT_UNDO_SECONDS = 10;
+export const MAX_UNDO_SECONDS = 60;
+
+/**
+ * Seconds a person-approved call waits, with an Undo, before it runs. Only actions that
+ * reach other people or can't be taken back (send, destructive) wait; 0 means run now.
+ * Calls auto-allowed by policy never go through here.
+ */
+export function undoDelay(
+ effect: Effect,
+ settings: { undoSeconds?: number | null } | null | undefined,
+): number {
+ if (effect !== "send" && effect !== "destructive") return 0;
+ const seconds = settings?.undoSeconds ?? DEFAULT_UNDO_SECONDS;
+ return Math.max(0, Math.min(MAX_UNDO_SECONDS, Math.floor(seconds)));
+}
+
+/** Opens the undo window on an approved call. Uses the database clock, like undo does. */
+export async function startUndoWindow(
+ tx: Db,
+ runId: string,
+ toolCallId: string,
+ seconds: number,
+): Promise {
+ if (seconds <= 0) return null;
+ const [row] = await tx
+ .update(toolCalls)
+ .set({ executeAfter: sql`now() + (${seconds}::int * interval '1 second')` })
+ .where(
+ and(
+ eq(toolCalls.runId, runId),
+ eq(toolCalls.id, toolCallId),
+ eq(toolCalls.status, "approved"),
+ ),
+ )
+ .returning({ executeAfter: toolCalls.executeAfter });
+ return row?.executeAfter ?? null;
+}
+
+/**
+ * When a waiting run is re-queued: null if a worker can make progress now, otherwise the
+ * end of the earliest undo window (so no worker picks the run up early).
+ */
+export async function runnableAt(tx: Db, runId: string): Promise {
+ const [row] = await tx
+ .select({
+ ready: sql`coalesce(bool_or(${toolCalls.executeAfter} is null or ${toolCalls.executeAfter} <= now()), true)`,
+ next: sql`min(${toolCalls.executeAfter})`,
+ })
+ .from(toolCalls)
+ .where(and(eq(toolCalls.runId, runId), eq(toolCalls.status, "approved")));
+ return !row || row.ready || !row.next ? null : new Date(row.next);
+}
+
/**
* Approves or denies one awaiting tool call. Compare-and-set on status and owner, so a
* double click, a replayed request or another user's id is a no-op (ConflictError).
- * When no approvals remain, the run is re-queued.
+ * Approving a send or destructive action opens the user's undo window (`executeAfter`).
+ * When no approvals remain, the run is re-queued, for after the window if it must wait.
*/
export async function decideToolCall(
db: Db,
@@ -162,8 +218,15 @@ export async function decideToolCall(
reason?: string;
editedInput?: JSONValue;
},
-): Promise {
- await db.transaction(async (tx) => {
+): Promise<{
+ /** End of the undo window this approval opened, if any. */
+ executeAfter: Date | null;
+ /** The run was re-queued (no approvals left)... */
+ requeued: boolean;
+ /** ...and no worker may take it before this time (null: now). */
+ runnableAt: Date | null;
+}> {
+ return db.transaction(async (tx) => {
const [run] = await tx
.select({ id: runs.id, status: runs.status })
.from(runs)
@@ -199,19 +262,94 @@ export async function decideToolCall(
eq(toolCalls.status, "awaiting_approval"),
),
)
- .returning({ id: toolCalls.id });
+ .returning({ id: toolCalls.id, effect: toolCalls.effect });
if (updated.length === 0) throw new ConflictError("this action is no longer awaiting approval");
+ let executeAfter: Date | null = null;
+ if (args.approved) {
+ const [settings] = await tx
+ .select({ undoSeconds: userSettings.undoSeconds })
+ .from(userSettings)
+ .where(eq(userSettings.userId, args.userId));
+ const seconds = undoDelay(updated[0]!.effect, settings);
+ executeAfter = await startUndoWindow(tx as unknown as Db, run.id, args.toolCallId, seconds);
+ }
+
const [{ remaining } = { remaining: 0 }] = await tx
.select({ remaining: sql`count(*)::int` })
.from(toolCalls)
.where(and(eq(toolCalls.runId, run.id), eq(toolCalls.status, "awaiting_approval")));
if (remaining === 0 && run.status === "waiting") {
+ const at = await runnableAt(tx as unknown as Db, run.id);
await tx
.update(runs)
- .set({ status: "queued", leaseExpiresAt: null })
+ .set({ status: "queued", leaseExpiresAt: at })
.where(eq(runs.id, run.id));
+ return { executeAfter, requeued: true, runnableAt: at };
}
+ return { executeAfter, requeued: false, runnableAt: null };
+ });
+}
+
+/**
+ * Undoes an approved call while its undo window is open: compare-and-set approved → denied
+ * only while `execute_after` is still in the future (database clock). The worker's own
+ * approved → executing transition is the other side of the race, so exactly one wins.
+ * A parked run is re-queued at once so the agent can respond.
+ */
+export async function undoToolCall(
+ db: Db,
+ args: { userId: string; runId: string; toolCallId: string },
+): Promise {
+ await db.transaction(async (tx) => {
+ const [run] = await tx
+ .select({ id: runs.id })
+ .from(runs)
+ .where(and(eq(runs.id, args.runId), eq(runs.userId, args.userId)))
+ .for("update");
+ if (!run) throw new NotFoundError("run not found");
+
+ const undone = await tx
+ .update(toolCalls)
+ .set({
+ status: "denied",
+ decidedAt: new Date(),
+ output: { type: "denied" as const, reason: UNDO_DENIAL },
+ })
+ .where(
+ and(
+ eq(toolCalls.runId, run.id),
+ eq(toolCalls.id, args.toolCallId),
+ eq(toolCalls.userId, args.userId),
+ eq(toolCalls.status, "approved"),
+ sql`${toolCalls.executeAfter} > now()`,
+ ),
+ )
+ .returning({ id: toolCalls.id });
+ if (undone.length === 0) {
+ const [call] = await tx
+ .select({ status: toolCalls.status })
+ .from(toolCalls)
+ .where(
+ and(
+ eq(toolCalls.runId, run.id),
+ eq(toolCalls.id, args.toolCallId),
+ eq(toolCalls.userId, args.userId),
+ ),
+ );
+ if (!call) throw new NotFoundError("action not found");
+ throw new ConflictError(
+ call.status === "denied"
+ ? "Nothing to undo: this action won't run."
+ : "Too late to undo: it already ran.",
+ );
+ }
+
+ // Only a run no worker holds: never hand a leased run to a second worker.
+ await tx
+ .update(runs)
+ .set({ leaseExpiresAt: await runnableAt(tx as unknown as Db, run.id) })
+ .where(and(eq(runs.id, run.id), eq(runs.status, "queued"), isNull(runs.leaseOwner)));
});
}
@@ -225,10 +363,11 @@ export async function requestCancel(
.where(
and(eq(runs.id, args.runId), eq(runs.userId, args.userId), inArray(runs.status, [...ACTIVE])),
)
- .returning({ id: runs.id, status: runs.status });
+ .returning({ id: runs.id, status: runs.status, leaseOwner: runs.leaseOwner });
if (!run) throw new ConflictError("run is not active");
- // A paused run has no worker; queue it so a worker records the cancellation.
- if (run.status === "waiting") {
+ // A paused run has no worker; queue it so a worker records the cancellation. That includes
+ // a run parked on an undo window, which would otherwise only stop when the window ends.
+ if (run.status === "waiting" || (run.status === "queued" && run.leaseOwner === null)) {
await db
.update(runs)
.set({ status: "queued", leaseExpiresAt: null })
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index dd283b1..692c591 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -113,6 +113,8 @@ export const userSettings = pgTable("user_settings", {
/** Bring-your-own provider keys, encrypted with the server secret. */
providerKeys: jsonb("provider_keys").$type>(),
instructions: text("instructions"),
+ /** Seconds an approved send or destructive action waits, with an Undo, before it runs. 0 disables. */
+ undoSeconds: integer("undo_seconds").notNull().default(10),
updatedAt: updatedAt(),
});
@@ -230,6 +232,8 @@ export const toolCalls = pgTable(
preview: text("preview"),
decidedBy: text("decided_by"),
decidedAt: timestamp("decided_at", { withTimezone: true }),
+ /** Undo window: an approved call does not run before this time. */
+ executeAfter: timestamp("execute_after", { withTimezone: true }),
output: jsonb("output").$type(),
fullOutput: jsonb("full_output").$type(),
createdAt: createdAt(),
diff --git a/packages/db/src/store.ts b/packages/db/src/store.ts
index 3334b36..f203fd5 100644
--- a/packages/db/src/store.ts
+++ b/packages/db/src/store.ts
@@ -49,6 +49,7 @@ function toRecord(r: ToolCallRow): ToolCallRecord {
output: r.output,
decidedBy: r.decidedBy,
preview: r.preview,
+ executeAfter: r.executeAfter?.toISOString() ?? null,
};
}
@@ -157,7 +158,7 @@ export class PgRunStore implements RunStore {
.returning();
if (args.toolCalls.length > 0) {
await tx.insert(toolCalls).values(
- args.toolCalls.map((c) => ({
+ args.toolCalls.map(({ executeAfter: _undo, ...c }) => ({
...c,
runId: args.runId,
userId: run!.userId,
From cd8ddf5da615187ae5bd3a3875a678c8068d63f0 Mon Sep 17 00:00:00 2001
From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com>
Date: Sun, 25 Oct 2026 06:46:39 +0530
Subject: [PATCH 6/8] Live updates reach the page after approvals; clearer plan
and batch copy
- Run event streams send Cache-Control: no-transform. Next's rewrite proxy gzips
responses and held back small writes, so status changes after an approval (and
the undo countdown) didn't arrive until something else was sent
- Batch approvals open undo windows per call, emit them live, and park the run
- Plan cards explain what approving does; a reason shared by every batch row is said once
---
apps/server/src/routes/runs.ts | 6 +++++-
apps/web/components/approval/approval-card.tsx | 10 ++++++++--
apps/web/components/approval/checklist.tsx | 8 ++++++--
3 files changed, 19 insertions(+), 5 deletions(-)
diff --git a/apps/server/src/routes/runs.ts b/apps/server/src/routes/runs.ts
index c07026c..ab07418 100644
--- a/apps/server/src/routes/runs.ts
+++ b/apps/server/src/routes/runs.ts
@@ -85,7 +85,7 @@ export const runs = new Hono()
: 0;
c.header("x-accel-buffering", "no");
- return streamSSE(c, async (stream) => {
+ const response = streamSSE(c, async (stream) => {
let wake: (() => void) | null = null;
let pending = true; // read once immediately
const unsubscribe = bus.subscribe(run.id, () => {
@@ -137,6 +137,10 @@ export const runs = new Hono()
clearInterval(ping);
}
});
+ // A compressing proxy (Next's rewrites gzip by default) buffers small writes, so a
+ // single status change could sit unsent until more output came. no-transform opts out.
+ response.headers.set("cache-control", "no-cache, no-transform");
+ return response;
})
.post("/:id/tool-calls/:toolCallId/decision", async (c) => {
diff --git a/apps/web/components/approval/approval-card.tsx b/apps/web/components/approval/approval-card.tsx
index b48c2d8..291df48 100644
--- a/apps/web/components/approval/approval-card.tsx
+++ b/apps/web/components/approval/approval-card.tsx
@@ -16,7 +16,7 @@ import { useToast } from "@/components/toast";
import { EffectPill, Monogram, Pill, TAINT_SENTENCE } from "@/components/ui";
import { ApiError, api, errorMessage } from "@/lib/api";
import { cx, humanize, humanToolName, prettyJson, splitToolName } from "@/lib/format";
-import { asPlan, PlanSteps } from "./checklist";
+import { asPlan, PLAN_TOOL, PlanSteps } from "./checklist";
import {
type Drafts,
fromDrafts,
@@ -267,7 +267,13 @@ export function ApprovalCard(props: ApprovalCardProps) {
{TAINT_SENTENCE}
) : null}
- {reason ? {reason}
: null}
+ {reason ? (
+
+ {name === PLAN_TOOL
+ ? "Approve once: the steps you keep then run without asking again."
+ : reason}
+
+ ) : null}
) : null}
diff --git a/apps/web/components/approval/checklist.tsx b/apps/web/components/approval/checklist.tsx
index 5cd4960..5538984 100644
--- a/apps/web/components/approval/checklist.tsx
+++ b/apps/web/components/approval/checklist.tsx
@@ -208,6 +208,9 @@ export function ApprovalBatch({
const settle = useRef<(() => void) | null>(null);
const isTicked = (tid: string) => ticked[tid] ?? true;
const count = items.filter((a) => isTicked(a.toolCallId)).length;
+ // One reason for every row (the usual case) is said once, not repeated on each line.
+ const reasons = new Set(items.map((a) => a.reason ?? ""));
+ const sharedReason = reasons.size === 1 ? [...reasons][0] || null : null;
const locked = busy !== null || stamped !== null;
useEffect(
@@ -299,7 +302,8 @@ export function ApprovalBatch({
) : null}
- Untick anything you don't want. Open a row to see exactly what it sends.
+ {sharedReason ? `${sharedReason} ` : ""}Untick anything you don't want. Open a row to see
+ exactly what it sends.
@@ -309,7 +313,7 @@ export function ApprovalBatch({
checked={isTicked(a.toolCallId)}
onCheck={(v) => setTicked((t) => ({ ...t, [a.toolCallId]: v }))}
title={approvalTitle(a.preview, a.name)}
- why={a.reason ?? undefined}
+ why={sharedReason ? undefined : (a.reason ?? undefined)}
meta={
From 7dcb12ea64d3ce2f71720c38a47d29b204523f3b Mon Sep 17 00:00:00 2001
From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com>
Date: Sun, 25 Oct 2026 06:46:47 +0530
Subject: [PATCH 7/8] Test that run event streams opt out of proxy compression
---
apps/server/src/server.test.ts | 2 ++
1 file changed, 2 insertions(+)
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 369c84b..4db5142 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -67,6 +67,8 @@ async function sse(cookie: string, runId: string, after = 0): Promise
Date: Sun, 25 Oct 2026 06:47:34 +0530
Subject: [PATCH 8/8] README: plans, batch approval, learned rules, undo window
---
README.md | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/README.md b/README.md
index 818844a..c51656d 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,10 @@ Agent products that act in your tools share three problems: approvals that live
- Automations triggered by a cron schedule, new Gmail messages matching a search, or a secret webhook URL
- MCP connections over Streamable HTTP with OAuth 2.1 + PKCE, or bearer tokens; presets for GitHub, Linear, Notion, Atlassian, Sentry
- Approval inbox, editable approvals, deny-with-reason, cancel now / after this step
+- Approve a plan, not every step: the agent proposes the exact actions it will take, you untick what you don't want, and the kept actions run without asking again (even after the task read outside content, because you saw each one)
+- Several pending actions from one step can be ticked and signed off together
+- Approvals that learn: after you approve the same kind of action unchanged a few times, Synapse offers a visible, removable rule ("emails where every address is @acme.com"). Tasks that read outside content still ask
+- Undo window: approved sends and deletes wait a few seconds (default 10, configurable) with an Undo button
- Knowledge base: upload docs, hybrid full-text + vector search (pgvector, reciprocal rank fusion)
- Memory you can read and edit; the agent can add notes, but not from a tainted run without asking
- Web search (Tavily, Brave or Exa) and SSRF-guarded web fetch