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} +
    + + +
    +
  • + ))} +
+

+ {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}? + + + + + +
+ ); +} + +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" ? ( - {denying ? null : mode === "edit" ? ( + {denying || plan ? null : mode === "edit" ? ( +
+ {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 ? ( +
+ ); +} 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 })} + /> + )}