From 05263a8f356f7ffd3d8cac5d3b258f1f288da730 Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 06:55:10 +0530 Subject: [PATCH 01/10] Phase 3 foundation: one decision service for every channel, and a notifier - decisions.ts: decide()/undo() used by the web routes now, and by push and Slack next. Edited inputs are re-checked against block rules; every decision records where it was made (tool_calls.decided_via) - notify/: NotificationChannel interface and a Notifier that announces each new approval once (tool_calls.notified_at, compare-and-set) and reports decisions back - The worker announces approvals when a run starts waiting --- apps/server/src/decisions.ts | 140 ++ apps/server/src/notify/notifier.ts | 93 + apps/server/src/notify/types.ts | 49 + apps/server/src/routes/runs.ts | 147 +- apps/server/src/server.test.ts | 53 + apps/server/src/services.ts | 7 +- apps/server/src/worker.ts | 5 + .../db/drizzle/0005_approval_channels.sql | 2 + packages/db/drizzle/meta/0005_snapshot.json | 2035 +++++++++++++++++ packages/db/drizzle/meta/_journal.json | 7 + packages/db/src/runs.ts | 9 +- packages/db/src/schema.ts | 4 + 12 files changed, 2427 insertions(+), 124 deletions(-) create mode 100644 apps/server/src/decisions.ts create mode 100644 apps/server/src/notify/notifier.ts create mode 100644 apps/server/src/notify/types.ts create mode 100644 packages/db/drizzle/0005_approval_channels.sql create mode 100644 packages/db/drizzle/meta/0005_snapshot.json diff --git a/apps/server/src/decisions.ts b/apps/server/src/decisions.ts new file mode 100644 index 0000000..928741c --- /dev/null +++ b/apps/server/src/decisions.ts @@ -0,0 +1,140 @@ +import { evaluatePolicy, type RunEvent, UNDO_DENIAL } from "@synapse/core"; +import { decideToolCalls, PgRunStore, schema, undoToolCall } from "@synapse/db"; +import type { JSONValue } from "ai"; +import { and, eq } from "drizzle-orm"; +import type { DecisionSource } from "./notify/types"; +import type { Services } from "./services"; + +export class DecisionInputError extends Error { + constructor( + readonly status: 400 | 404 | 422, + readonly code: string, + message: string, + ) { + super(message); + } +} + +export interface Decision { + toolCallId: string; + approved: boolean; + reason?: string; + /** Approve with this input instead of the agent's. */ + input?: JSONValue; +} + +/** + * Applies a person's decisions on one run's awaiting calls, wherever they were made (web, + * phone, Slack). All or nothing; then tells live viewers, wakes the run (or parks it until + * an undo window ends) and lets notification channels update what they showed. + */ +export async function decide( + services: Services, + args: { userId: string; runId: string; decisions: Decision[]; via: DecisionSource }, +): Promise<{ executeAfter: Record }> { + const { userId, runId, decisions, via } = args; + if (new Set(decisions.map((d) => d.toolCallId)).size !== decisions.length) + throw new DecisionInputError(400, "duplicate", "Each action can be decided once."); + for (const d of decisions) + if (d.approved && d.input !== undefined) + await assertEditAllowed(services, userId, runId, d.toolCallId, d.input); + + const decided = await decideToolCalls(services.database.db, { + userId, + runId, + decisions: decisions.map((d) => ({ + toolCallId: d.toolCallId, + approved: d.approved, + ...(d.reason ? { reason: d.reason } : {}), + ...(d.approved && d.input !== undefined ? { editedInput: d.input } : {}), + })), + via, + }); + for (const [toolCallId, at] of Object.entries(decided.executeAfter)) + await emitNow(services, runId, { + type: "tool.status", + toolCallId, + status: "approved", + executeAfter: at.toISOString(), + }); + if (decided.requeued && decided.runnableAt) { + // Parked until the undo window ends: it is queued, not waiting on anyone. + await emitNow(services, runId, { type: "run.status", status: "queued" }); + wakeAt(services, runId, decided.runnableAt); + } else await services.wake(runId); + + await services.notifier.resolved( + decisions.map((d) => ({ + userId, + runId, + toolCallId: d.toolCallId, + approved: d.approved, + via, + executeAfter: decided.executeAfter[d.toolCallId] ?? null, + })), + ); + return { + executeAfter: Object.fromEntries( + Object.entries(decided.executeAfter).map(([id, at]) => [id, at.toISOString()]), + ), + }; +} + +/** Takes back an approved send or delete while its undo window is open. */ +export async function undo( + services: Services, + args: { userId: string; runId: string; toolCallId: string }, +) { + await undoToolCall(services.database.db, args); + const output = { type: "denied" as const, reason: UNDO_DENIAL }; + await emitNow(services, args.runId, { + type: "tool.status", + toolCallId: args.toolCallId, + status: "denied", + }); + await emitNow(services, args.runId, { type: "tool.result", toolCallId: args.toolCallId, output }); + await services.wake(args.runId); +} + +/** An edited input must not turn an allowed action into one the user's rules block. */ +async function assertEditAllowed( + services: Services, + userId: string, + runId: string, + toolCallId: string, + input: JSONValue, +) { + const { db } = services.database; + const [call] = await db + .select({ name: schema.toolCalls.name, effect: schema.toolCalls.effect }) + .from(schema.toolCalls) + .where( + and( + eq(schema.toolCalls.runId, runId), + eq(schema.toolCalls.id, toolCallId), + eq(schema.toolCalls.userId, userId), + ), + ); + if (!call) throw new DecisionInputError(404, "not_found", "Action not found."); + const policy = await new PgRunStore(db).getPolicy(userId); + const verdict = evaluatePolicy( + { tool: call.name, effect: call.effect, input, tainted: true }, + policy.rules, + policy.defaults, + ); + if (verdict.decision === "block") + throw new DecisionInputError(422, "blocked", `The edited action is blocked: ${verdict.reason}`); +} + +export async function emitNow(services: Services, runId: string, event: RunEvent) { + await services.events.emit(runId, event); + services.events.forget(runId); +} + +function wakeAt(services: Services, runId: string, at: Date) { + const timer = setTimeout( + () => void services.wake(runId).catch(() => {}), + Math.max(0, at.getTime() - Date.now()) + 25, + ); + timer.unref?.(); +} diff --git a/apps/server/src/notify/notifier.ts b/apps/server/src/notify/notifier.ts new file mode 100644 index 0000000..e6e0733 --- /dev/null +++ b/apps/server/src/notify/notifier.ts @@ -0,0 +1,93 @@ +import { schema } from "@synapse/db"; +import { and, eq, inArray, isNull } from "drizzle-orm"; +import { log } from "../log"; +import type { Services } from "../services"; +import type { NotificationChannel, PendingApproval, ResolvedApproval } from "./types"; + +/** + * Tells people about new approvals through every registered channel. Each awaiting call is + * announced once: `notified_at` is claimed with a compare-and-set, so several workers + * finishing steps of the same run never double-notify. + */ +export class Notifier { + private readonly channels: NotificationChannel[] = []; + + constructor(private readonly services: () => Services) {} + + add(channel: NotificationChannel) { + this.channels.push(channel); + } + + get names(): string[] { + return this.channels.map((c) => c.name); + } + + /** Announces the run's awaiting calls that haven't been announced yet. */ + async announce(runId: string): Promise { + const { database, config } = this.services(); + const { db } = database; + const claimed = await db + .update(schema.toolCalls) + .set({ notifiedAt: new Date() }) + .where( + and( + eq(schema.toolCalls.runId, runId), + eq(schema.toolCalls.status, "awaiting_approval"), + isNull(schema.toolCalls.notifiedAt), + ), + ) + .returning({ id: schema.toolCalls.id }); + if (claimed.length === 0) return []; + + const rows = await db + .select({ + userId: schema.toolCalls.userId, + runId: schema.toolCalls.runId, + chatId: schema.runs.chatId, + chatTitle: schema.chats.title, + toolCallId: schema.toolCalls.id, + name: schema.toolCalls.name, + effect: schema.toolCalls.effect, + preview: schema.toolCalls.preview, + input: schema.toolCalls.input, + reason: schema.toolCalls.decisionReason, + tainted: schema.runs.tainted, + createdAt: schema.toolCalls.createdAt, + }) + .from(schema.toolCalls) + .innerJoin(schema.runs, eq(schema.runs.id, schema.toolCalls.runId)) + .innerJoin(schema.chats, eq(schema.chats.id, schema.runs.chatId)) + .where( + and( + eq(schema.toolCalls.runId, runId), + inArray( + schema.toolCalls.id, + claimed.map((c) => c.id), + ), + ), + ); + const approvals: PendingApproval[] = rows.map((r) => ({ + ...r, + url: `${config.PUBLIC_URL}/t/${r.chatId}`, + })); + await this.each("notify", (c) => c.notify(approvals)); + return approvals; + } + + async resolved(decided: ResolvedApproval[]) { + if (decided.length === 0) return; + await this.each("resolved", (c) => c.resolved?.(decided)); + } + + private async each(what: string, fn: (c: NotificationChannel) => Promise | undefined) { + await Promise.all( + this.channels.map(async (c) => { + try { + await fn(c); + } catch (error) { + log.warn("notification channel failed", { channel: c.name, what, error: String(error) }); + } + }), + ); + } +} diff --git a/apps/server/src/notify/types.ts b/apps/server/src/notify/types.ts new file mode 100644 index 0000000..5906490 --- /dev/null +++ b/apps/server/src/notify/types.ts @@ -0,0 +1,49 @@ +import type { Effect } from "@synapse/core"; +import type { JSONValue } from "ai"; + +/** One action waiting for a person, as notification channels see it. */ +export interface PendingApproval { + userId: string; + runId: string; + chatId: string; + chatTitle: string | null; + toolCallId: string; + name: string; + effect: Effect; + /** One line from the tool, e.g. "Email bob@acme.com: Re: Sync". */ + preview: string | null; + input: JSONValue; + /** Why the policy asked. */ + reason: string | null; + /** The task had read outside content when this was proposed. */ + tainted: boolean; + createdAt: Date; + /** Where to open it in the web app. */ + url: string; +} + +/** What happened to an action, so channels can update what they showed (e.g. a Slack message). */ +export interface ResolvedApproval { + userId: string; + runId: string; + toolCallId: string; + approved: boolean; + /** Where the decision was made. */ + via: DecisionSource; + /** Set when a send or delete waits out its undo window. */ + executeAfter: Date | null; +} + +export type DecisionSource = "web" | "push" | "slack" | "email"; + +/** + * A way to reach a person about approvals: web push, Slack, email. Channels decide for + * themselves whether a user has them set up; `notify` is called for every new approval. + * Failures are logged and never block the run or other channels. + */ +export interface NotificationChannel { + readonly name: string; + notify(approvals: PendingApproval[]): Promise; + /** Optional: the approvals were decided (anywhere). */ + resolved?(decided: ResolvedApproval[]): Promise; +} diff --git a/apps/server/src/routes/runs.ts b/apps/server/src/routes/runs.ts index ab07418..1a41804 100644 --- a/apps/server/src/routes/runs.ts +++ b/apps/server/src/routes/runs.ts @@ -1,20 +1,10 @@ -import { evaluatePolicy, type RunEvent, UNDO_DENIAL } from "@synapse/core"; -import { - decideToolCall, - decideToolCalls, - PgRunStore, - readEvents, - requestCancel, - schema, - undoToolCall, -} from "@synapse/db"; -import type { JSONValue } from "ai"; +import { readEvents, requestCancel, schema } from "@synapse/db"; import { and, asc, desc, eq } from "drizzle-orm"; import { Hono } from "hono"; import { streamSSE } from "hono/streaming"; import { z } from "zod"; +import { type Decision, DecisionInputError, decide, undo } from "../decisions"; import { type AppEnv, apiError, body } from "../http"; -import type { Services } from "../services"; const PAUSE_OR_END = new Set(["waiting", "completed", "failed", "cancelled"]); const EVENT_PAGE = 1000; @@ -152,46 +142,17 @@ export const runs = new Hono() input: z.json().optional(), }), ); - const runId = c.req.param("id"); - if (input.approved && input.input !== undefined) - await assertEditAllowed(c, runId, c.req.param("toolCallId"), input.input); const toolCallId = c.req.param("toolCallId"); - const decided = await decideToolCall(c.var.services.database.db, { - userId: c.var.user.id, - runId, - toolCallId, - approved: input.approved, - ...(input.reason ? { reason: input.reason } : {}), - ...(input.input !== undefined ? { editedInput: input.input } : {}), - }); - const { services } = c.var; - const { executeAfter } = decided; - if (executeAfter) { - // Live viewers (another tab, the run panel) get the countdown too. - await emitNow(services, runId, { - type: "tool.status", - toolCallId, - status: "approved", - executeAfter: executeAfter.toISOString(), - }); - } - if (decided.requeued && decided.runnableAt) { - // Parked until the window ends: it is queued, not waiting on you. - await emitNow(services, runId, { type: "run.status", status: "queued" }); - wakeAt(services, runId, decided.runnableAt); - } else await services.wake(runId); - return c.json({ executeAfter: executeAfter?.toISOString() ?? null }); + const { executeAfter } = await decided(c, [{ toolCallId, ...input }]); + return c.json({ executeAfter: executeAfter[toolCallId] ?? null }); }) .post("/:id/tool-calls/:toolCallId/undo", async (c) => { - const runId = c.req.param("id"); - const toolCallId = c.req.param("toolCallId"); - const { services } = c.var; - await undoToolCall(services.database.db, { userId: c.var.user.id, runId, toolCallId }); - const output = { type: "denied" as const, reason: UNDO_DENIAL }; - await emitNow(services, runId, { type: "tool.status", toolCallId, status: "denied" }); - await emitNow(services, runId, { type: "tool.result", toolCallId, output }); - await services.wake(runId); + await undo(c.var.services, { + userId: c.var.user.id, + runId: c.req.param("id"), + toolCallId: c.req.param("toolCallId"), + }); return c.body(null, 204); }) @@ -213,39 +174,7 @@ export const runs = new Hono() .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.input !== undefined) - await assertEditAllowed(c, runId, d.toolCallId, d.input); - const { services } = c.var; - const decided = await decideToolCalls(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.input !== undefined ? { editedInput: d.input } : {}), - })), - }); - for (const [toolCallId, at] of Object.entries(decided.executeAfter)) - await emitNow(services, runId, { - type: "tool.status", - toolCallId, - status: "approved", - executeAfter: at.toISOString(), - }); - if (decided.requeued && decided.runnableAt) { - await emitNow(services, runId, { type: "run.status", status: "queued" }); - wakeAt(services, runId, decided.runnableAt); - } else await services.wake(runId); - return c.json({ - executeAfter: Object.fromEntries( - Object.entries(decided.executeAfter).map(([id, at]) => [id, at.toISOString()]), - ), - }); + return c.json(await decided(c, decisions)); }) .post("/:id/cancel", async (c) => { @@ -290,49 +219,23 @@ export const approvals = new Hono().get("/", async (c) => { * Appends an event for a run no worker may be driving (it is parked). Forgets the cached * seq afterwards so a later writer on this instance re-reads the tail. */ -async function emitNow(services: Services, runId: string, event: RunEvent) { - await services.events.emit(runId, event); - services.events.forget(runId); -} - -/** Wakes workers when a run parked on an undo window becomes claimable, not on the next poll. */ -function wakeAt(services: Services, runId: string, at: Date) { - const timer = setTimeout( - () => void services.wake(runId).catch(() => {}), - Math.max(0, at.getTime() - Date.now()) + 25, - ); - timer.unref?.(); -} - -/** Edited arguments are re-checked against block rules: editing must not route around them. */ -async function assertEditAllowed( - c: { var: AppEnv["Variables"] }, - runId: string, - toolCallId: string, - input: JSONValue, +/** Applies decisions made in the web app, turning input problems into API errors. */ +async function decided( + c: { var: AppEnv["Variables"]; req: { param(name: "id"): string } }, + decisions: Decision[], ) { - const { db } = c.var.services.database; - const [call] = await db - .select({ name: schema.toolCalls.name, effect: schema.toolCalls.effect }) - .from(schema.toolCalls) - .where( - and( - eq(schema.toolCalls.runId, runId), - eq(schema.toolCalls.id, toolCallId), - eq(schema.toolCalls.userId, c.var.user.id), - ), - ); - if (!call) apiError(404, "not_found", "Action not found."); - const policy = await new PgRunStore(db).getPolicy(c.var.user.id); - const verdict = evaluatePolicy( - { tool: call.name, effect: call.effect, input, tainted: true }, - policy.rules, - policy.defaults, - ); - if (verdict.decision === "block") - apiError(422, "blocked", `The edited action is blocked: ${verdict.reason}`); + try { + return await decide(c.var.services, { + userId: c.var.user.id, + runId: c.req.param("id"), + decisions, + via: "web", + }); + } catch (error) { + if (error instanceof DecisionInputError) apiError(error.status, error.code, error.message); + throw error; + } } - async function ownRun(c: { var: AppEnv["Variables"] }, id: string) { const [run] = await c.var.services.database.db .select() diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 4db5142..a5551f8 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -5,6 +5,7 @@ import { schema } from "@synapse/db"; import { eq } from "drizzle-orm"; import { createApp } from "./app"; import { loadConfig } from "./config"; +import type { PendingApproval, ResolvedApproval } from "./notify/types"; import { createServices, type Services } from "./services"; import { Worker } from "./worker"; @@ -670,3 +671,55 @@ test("approvals that learn: suggest, accept, dismiss", async () => { expect((await other("/api/policy/suggestions")).json!.suggestions).toEqual([]); expect((await other("/api/policy")).json!.rules).toHaveLength(1); }); + +test("new approvals are announced once to notification channels, and decisions reported back", async () => { + const me = api(await signUp("notify@example.com")); + await me("/api/policy", { + method: "PUT", + json: { + defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" }, + rules: [{ tool: "memory_save", decision: "ask" }], + }, + }); + const seen: PendingApproval[] = []; + const resolved: ResolvedApproval[] = []; + services.notifier.add({ + name: "test", + notify: async (a) => { + seen.push(...a); + }, + resolved: async (r) => { + resolved.push(...r); + }, + }); + script([ + { toolCalls: [{ name: "memory_save", input: { note: "likes tea" }, id: "n1" }] }, + { text: "Saved." }, + ]); + const { json } = await me("/api/chats", { method: "POST", json: { content: "remember tea" } }); + const runId = json!.runId as string; + await worker.processNow(runId); + expect(seen).toHaveLength(1); + expect(seen[0]).toMatchObject({ + runId, + toolCallId: "n1", + name: "memory_save", + chatTitle: "remember tea", + }); + expect(seen[0]!.url).toBe(`${ORIGIN}/t/${seen[0]!.chatId}`); + // Announcing again finds nothing new. + expect(await services.notifier.announce(runId)).toEqual([]); + + await me(`/api/runs/${runId}/tool-calls/n1/decision`, { + method: "POST", + json: { approved: true }, + }); + expect(resolved).toEqual([ + expect.objectContaining({ toolCallId: "n1", approved: true, via: "web", executeAfter: null }), + ]); + const [row] = await services.database.db + .select({ via: schema.toolCalls.decidedVia }) + .from(schema.toolCalls) + .where(eq(schema.toolCalls.id, "n1")); + expect(row?.via).toBe("web"); +}); diff --git a/apps/server/src/services.ts b/apps/server/src/services.ts index b9a9d78..ca448ff 100644 --- a/apps/server/src/services.ts +++ b/apps/server/src/services.ts @@ -2,6 +2,7 @@ import { createDatabase, type Database, EVENTS_CHANNEL, EventLog, SecretBox } fr import { createEmbedder, type ToolsetConfig } from "@synapse/tools"; import { type Auth, createAuth } from "./auth"; import type { Config } from "./config"; +import { Notifier } from "./notify/notifier"; export const RUNS_CHANNEL = "synapse_runs"; @@ -44,6 +45,8 @@ export interface Services { events: EventLog; bus: EventBus; toolset: ToolsetConfig; + /** Tells people about approvals through push, Slack and other channels. */ + notifier: Notifier; /** Wakes idle workers (on any instance) when a run becomes runnable. */ wake: (runId: string) => Promise; close: () => Promise; @@ -54,7 +57,7 @@ export async function createServices(config: Config): Promise { await database.migrate(); const box = await SecretBox.fromSecret(config.secret); const { bus, stop } = await EventBus.create(database); - return { + const services: Services = { config, database, box, @@ -69,10 +72,12 @@ export async function createServices(config: Config): Promise { embedder: config.embedding ? createEmbedder(config.embedding) : null, google: config.google, }, + notifier: new Notifier(() => services), wake: (runId) => database.notify(RUNS_CHANNEL, runId), close: async () => { await stop(); await database.close(); }, }; + return services; } diff --git a/apps/server/src/worker.ts b/apps/server/src/worker.ts index 0f2972e..4b40571 100644 --- a/apps/server/src/worker.ts +++ b/apps/server/src/worker.ts @@ -262,6 +262,11 @@ export class Worker { status === "running" ? nextUndoWaitMs(await new PgRunStore(db).listToolCalls(runId)) : 0; await releaseRun(db, runId, this.id, wait); if (wait > 0) this.wakeLater(runId, wait); + // New approvals: tell the person wherever they are (phone, Slack…). + if (status === "waiting") + await this.s.notifier.announce(runId).catch((error) => { + log.warn("announcing approvals failed", { runId, error: String(error) }); + }); } catch (error) { await events.flush(runId).catch(() => {}); if (controller.signal.aborted) { diff --git a/packages/db/drizzle/0005_approval_channels.sql b/packages/db/drizzle/0005_approval_channels.sql new file mode 100644 index 0000000..77bd858 --- /dev/null +++ b/packages/db/drizzle/0005_approval_channels.sql @@ -0,0 +1,2 @@ +ALTER TABLE "tool_calls" ADD COLUMN "decided_via" text;--> statement-breakpoint +ALTER TABLE "tool_calls" ADD COLUMN "notified_at" timestamp with time zone; \ No newline at end of file diff --git a/packages/db/drizzle/meta/0005_snapshot.json b/packages/db/drizzle/meta/0005_snapshot.json new file mode 100644 index 0000000..796326a --- /dev/null +++ b/packages/db/drizzle/meta/0005_snapshot.json @@ -0,0 +1,2035 @@ +{ + "id": "a1782b93-d749-4af8-8532-db47b083aa61", + "prevId": "dd48e649-c1d4-4adc-9d5e-5a5aab170395", + "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 + }, + "decided_via": { + "name": "decided_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notified_at": { + "name": "notified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execute_after": { + "name": "execute_after", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "full_output": { + "name": "full_output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_calls_user_decided_idx": { + "name": "tool_calls_user_decided_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "decided_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "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": "'{}'" + }, + "undo_seconds": { + "name": "undo_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_settings_user_id_user_id_fk": { + "name": "user_settings_user_id_user_id_fk", + "tableFrom": "user_settings", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index 51936c8..207d5be 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1792890418069, "tag": "0004_trust_that_grows", "breakpoints": true + }, + { + "idx": 5, + "version": "7", + "when": 1792891462021, + "tag": "0005_approval_channels", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/runs.ts b/packages/db/src/runs.ts index 2845eff..203b6bd 100644 --- a/packages/db/src/runs.ts +++ b/packages/db/src/runs.ts @@ -245,7 +245,13 @@ export async function decideToolCall( */ export async function decideToolCalls( db: Db, - args: { userId: string; runId: string; decisions: ToolCallDecision[] }, + args: { + userId: string; + runId: string; + decisions: ToolCallDecision[]; + /** Where the person decided (web, push, slack…), for the audit log. */ + via?: string; + }, ): Promise { return db.transaction(async (tx) => { const [run] = await tx @@ -268,6 +274,7 @@ export async function decideToolCalls( status: d.approved ? "approved" : "denied", decidedBy: args.userId, decidedAt: new Date(), + decidedVia: args.via ?? "web", ...(d.approved && d.editedInput !== undefined ? { input: d.editedInput, inputEdited: true } : {}), diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 96e5870..a7f1252 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -240,6 +240,10 @@ export const toolCalls = pgTable( preview: text("preview"), decidedBy: text("decided_by"), decidedAt: timestamp("decided_at", { withTimezone: true }), + /** Where the person decided: web, push, slack, email. */ + decidedVia: text("decided_via"), + /** When notification channels were told this call needs a person. */ + notifiedAt: timestamp("notified_at", { withTimezone: true }), /** Undo window: an approved call does not run before this time. */ executeAfter: timestamp("execute_after", { withTimezone: true }), output: jsonb("output").$type(), From 6ef07026ecf3a7956f59773603233e83242d0577 Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 06:55:40 +0530 Subject: [PATCH 02/10] Approvals carry their notification recipients --- apps/server/src/notify/notifier.ts | 1 + apps/server/src/notify/types.ts | 6 ++++++ apps/server/src/server.test.ts | 1 + 3 files changed, 8 insertions(+) diff --git a/apps/server/src/notify/notifier.ts b/apps/server/src/notify/notifier.ts index e6e0733..aeff49b 100644 --- a/apps/server/src/notify/notifier.ts +++ b/apps/server/src/notify/notifier.ts @@ -68,6 +68,7 @@ export class Notifier { ); const approvals: PendingApproval[] = rows.map((r) => ({ ...r, + recipients: [r.userId], url: `${config.PUBLIC_URL}/t/${r.chatId}`, })); await this.each("notify", (c) => c.notify(approvals)); diff --git a/apps/server/src/notify/types.ts b/apps/server/src/notify/types.ts index 5906490..0fce921 100644 --- a/apps/server/src/notify/types.ts +++ b/apps/server/src/notify/types.ts @@ -3,7 +3,13 @@ import type { JSONValue } from "ai"; /** One action waiting for a person, as notification channels see it. */ export interface PendingApproval { + /** Whose task it is. */ userId: string; + /** + * Who should hear about it: the requester today; team admins when a team rule says an + * admin must sign off. Channels deliver to these people, not to `userId`. + */ + recipients: string[]; runId: string; chatId: string; chatTitle: string | null; diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index a5551f8..7783702 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -706,6 +706,7 @@ test("new approvals are announced once to notification channels, and decisions r name: "memory_save", chatTitle: "remember tea", }); + expect(seen[0]!.recipients).toEqual([seen[0]!.userId]); expect(seen[0]!.url).toBe(`${ORIGIN}/t/${seen[0]!.chatId}`); // Announcing again finds nothing new. expect(await services.notifier.announce(runId)).toEqual([]); From b6f568659d0a3b210d248c6545d65bae5154e653 Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:04:16 +0530 Subject: [PATCH 03/10] Approve from Slack - Connect Slack per user (OAuth v2, bot scopes chat:write, im:write, users:read); state is sealed and bound to the user; the bot token is sealed; disconnect revokes and deletes - Slack notification channel: Block Kit DM per recipient with Approve / Deny / Open in Synapse, input summary, policy reason and a warning for tainted tasks; message ts stored in slack_messages and rewritten when the action is decided anywhere - POST /api/slack/interactions: signature (v0 HMAC, 5 min skew, constant time) checked over the raw body first; only the connected Slack user can act, only on actions sent to them; acks at once and decides via decide(..., via: "slack"); double clicks show the current state - Connections page Slack card (connect, test DM, disconnect, setup guidance), docs/slack.md with an app manifest, .env.example, docs/api.md, README --- .env.example | 7 + README.md | 1 + apps/server/src/app.ts | 6 +- apps/server/src/config.ts | 16 + apps/server/src/notify/slack-api.ts | 233 ++ apps/server/src/notify/slack-testing.ts | 146 ++ apps/server/src/notify/slack.ts | 494 ++++ apps/server/src/routes/integrations.ts | 2 + apps/server/src/routes/slack.ts | 128 ++ apps/server/src/services.ts | 6 + apps/server/src/slack.test.ts | 310 +++ apps/web/app/(app)/connections/page.tsx | 148 +- apps/web/lib/api.ts | 18 +- docs/api.md | 12 +- docs/slack.md | 85 + packages/db/drizzle/0006_slack.sql | 28 + packages/db/drizzle/meta/0006_snapshot.json | 2239 +++++++++++++++++++ packages/db/drizzle/meta/_journal.json | 7 + packages/db/src/schema.ts | 45 + 19 files changed, 3923 insertions(+), 8 deletions(-) create mode 100644 apps/server/src/notify/slack-api.ts create mode 100644 apps/server/src/notify/slack-testing.ts create mode 100644 apps/server/src/notify/slack.ts create mode 100644 apps/server/src/routes/slack.ts create mode 100644 apps/server/src/slack.test.ts create mode 100644 docs/slack.md create mode 100644 packages/db/drizzle/0006_slack.sql create mode 100644 packages/db/drizzle/meta/0006_snapshot.json diff --git a/.env.example b/.env.example index 634b76c..5f72002 100644 --- a/.env.example +++ b/.env.example @@ -56,5 +56,12 @@ GOOGLE_CLIENT_SECRET= # How often email triggers check for new mail, in seconds (min 30). # TRIGGER_POLL_SECONDS=120 +# ── Slack (optional) ───────────────────────────────────────────────────────── +# Approve and deny from Slack DMs. All three from your Slack app's Basic Information page; +# PUBLIC_URL must be public https for Slack to reach it. Setup: docs/slack.md +SLACK_CLIENT_ID= +SLACK_CLIENT_SECRET= +SLACK_SIGNING_SECRET= + # Allow MCP servers / web_fetch on private networks (self-hosted MCP on your LAN). SYNAPSE_ALLOW_PRIVATE_NETWORK=false diff --git a/README.md b/README.md index c51656d..a517e66 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Agent products that act in your tools share three problems: approvals that live - Approve a plan, not every step: the agent proposes the exact actions it will take, you untick what you don't want, and the kept actions run without asking again (even after the task read outside content, because you saw each one) - Several pending actions from one step can be ticked and signed off together - Approvals that learn: after you approve the same kind of action unchanged a few times, Synapse offers a visible, removable rule ("emails where every address is @acme.com"). Tasks that read outside content still ask +- Approve from Slack: approvals arrive as a DM with Approve and Deny buttons, and the message updates wherever you decide ([setup](docs/slack.md)) - Undo window: approved sends and deletes wait a few seconds (default 10, configurable) with an Undo button - Knowledge base: upload docs, hybrid full-text + vector search (pgvector, reciprocal rank fusion) - Memory you can read and edit; the agent can add notes, but not from a tainted run without asking diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 725ee2c..8a06e73 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 { slackIntegration, slackInteractions } from "./routes/slack"; import { suggestions } from "./routes/suggestions"; import type { Services } from "./services"; @@ -47,7 +48,7 @@ export function createApp(services: Services) { github: Boolean(config.GITHUB_CLIENT_ID), google: Boolean(config.GOOGLE_CLIENT_ID), }, - integrations: { google: Boolean(config.google) }, + integrations: { google: Boolean(config.google), slack: Boolean(config.slack) }, features: { webSearch: Boolean(config.webSearch), embeddings: Boolean(config.embedding) }, models: config.SYNAPSE_MODELS, }), @@ -56,6 +57,8 @@ export function createApp(services: Services) { app.on(["GET", "POST"], "/api/auth/*", (c) => services.auth.handler(c.req.raw)); // Public: authenticated by the secret token in the URL, not a session. app.route("/api/hooks", hooks); + // Public: authenticated by Slack's request signature. + app.route("/api/slack/interactions", slackInteractions); const api = new Hono(); api.use(requireUser); @@ -65,6 +68,7 @@ export function createApp(services: Services) { api.route("/connections/oauth/callback", oauthCallback); api.route("/connections", connections); api.route("/integrations/google/callback", googleCallback); + api.route("/integrations/slack", slackIntegration); api.route("/integrations", integrations); api.route("/policy/suggestions", suggestions); api.route("/policy", policy); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 131effa..695d8e5 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -3,6 +3,7 @@ import { dirname } from "node:path"; import { parseModelRef } from "@synapse/core"; import type { GoogleAppConfig, WebSearchConfig } from "@synapse/tools"; import { z } from "zod"; +import type { SlackAppConfig } from "./notify/slack-api"; const csv = z.string().transform((s) => s @@ -57,6 +58,10 @@ const Env = z.object({ /** One Google OAuth app serves both "Sign in with Google" and the Gmail/Calendar integration. */ GOOGLE_CLIENT_ID: z.string().optional(), GOOGLE_CLIENT_SECRET: z.string().optional(), + /** Slack app for approving from Slack (docs/slack.md). All three are needed. */ + SLACK_CLIENT_ID: z.string().optional(), + SLACK_CLIENT_SECRET: z.string().optional(), + SLACK_SIGNING_SECRET: z.string().optional(), /** How often email triggers check for new mail. */ TRIGGER_POLL_SECONDS: z.coerce.number().int().min(30).default(120), }); @@ -94,9 +99,20 @@ export function loadConfig(env: Record = process.env } : null; + const slack: SlackAppConfig | null = + parsed.SLACK_CLIENT_ID && parsed.SLACK_CLIENT_SECRET && parsed.SLACK_SIGNING_SECRET + ? { + clientId: parsed.SLACK_CLIENT_ID, + clientSecret: parsed.SLACK_CLIENT_SECRET, + signingSecret: parsed.SLACK_SIGNING_SECRET, + publicUrl: parsed.PUBLIC_URL, + } + : null; + return { ...parsed, google, + slack, SYNAPSE_MODELS: models, SYNAPSE_SUMMARY_MODEL: summaryModel, secret, diff --git a/apps/server/src/notify/slack-api.ts b/apps/server/src/notify/slack-api.ts new file mode 100644 index 0000000..3573ec0 --- /dev/null +++ b/apps/server/src/notify/slack-api.ts @@ -0,0 +1,233 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; +import { type Db, type SecretBox, schema } from "@synapse/db"; +import { and, eq, ne } from "drizzle-orm"; + +/** Bot scopes: post and update DMs, open the DM with the person who connected. */ +export const SLACK_SCOPES = ["chat:write", "im:write", "users:read"]; + +const AUTHORIZE_URL = "https://slack.com/oauth/v2/authorize"; +const API = "https://slack.com/api"; + +export interface SlackAppConfig { + clientId: string; + clientSecret: string; + /** Verifies that interactions really come from Slack. */ + signingSecret: string; + /** Slack redirects to /api/integrations/slack/callback. */ + publicUrl: string; + /** Test hook. Defaults to global fetch. */ + fetch?: typeof fetch; +} + +export class SlackAuthError extends Error {} + +/** A Slack Web API call that came back `ok: false`. */ +export class SlackApiError extends Error { + constructor( + readonly method: string, + readonly code: string, + ) { + super(`Slack ${method} failed: ${code}`); + } +} + +interface FlowState { + userId: string; + exp: number; +} + +export function slackRedirectUri(app: SlackAppConfig): string { + return `${app.publicUrl}/api/integrations/slack/callback`; +} + +/** The URL that starts the install. The user it belongs to is sealed into `state`. */ +export async function slackAuthorizationUrl( + app: SlackAppConfig, + box: SecretBox, + userId: string, +): Promise { + const state = await box.seal( + JSON.stringify({ userId, exp: Date.now() + 10 * 60_000 } satisfies FlowState), + ); + const url = new URL(AUTHORIZE_URL); + url.search = new URLSearchParams({ + client_id: app.clientId, + scope: SLACK_SCOPES.join(","), + redirect_uri: slackRedirectUri(app), + state, + }).toString(); + return url.toString(); +} + +interface OAuthAccess { + ok: boolean; + error?: string; + access_token?: string; + token_type?: string; + scope?: string; + bot_user_id?: string; + team?: { id: string; name: string }; + authed_user?: { id: string }; +} + +/** Exchanges the callback code and saves the Slack account for the user who started it. */ +export async function completeSlackAuth( + app: SlackAppConfig, + db: Db, + box: SecretBox, + args: { userId: string; code: string; state: string }, +): Promise<{ team: string }> { + let flow: FlowState; + try { + flow = JSON.parse(await box.open(args.state)) as FlowState; + } catch { + throw new SlackAuthError("This Slack link is invalid. Try connecting again."); + } + if (flow.userId !== args.userId) + throw new SlackAuthError("This Slack link belongs to another user."); + if (flow.exp < Date.now()) + throw new SlackAuthError("This Slack link expired. Try connecting again."); + + const res = await (app.fetch ?? fetch)(`${API}/oauth.v2.access`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + client_id: app.clientId, + client_secret: app.clientSecret, + code: args.code, + redirect_uri: slackRedirectUri(app), + }), + signal: AbortSignal.timeout(10_000), + }); + const token = (await res.json()) as OAuthAccess; + if (!token.ok || !token.access_token || !token.team || !token.authed_user?.id) + throw new SlackAuthError(`Slack sign-in failed: ${token.error ?? `HTTP ${res.status}`}`); + const granted = (token.scope ?? "").split(","); + if (SLACK_SCOPES.some((s) => !granted.includes(s))) + throw new SlackAuthError("Slack did not grant the permissions Synapse needs. Try again."); + + // One Slack person answers for one Synapse user. + const [taken] = await db + .select({ userId: schema.slackAccounts.userId }) + .from(schema.slackAccounts) + .where( + and( + eq(schema.slackAccounts.teamId, token.team.id), + eq(schema.slackAccounts.slackUserId, token.authed_user.id), + ne(schema.slackAccounts.userId, args.userId), + ), + ); + if (taken) + throw new SlackAuthError("That Slack account is already connected to another Synapse user."); + + const values = { + teamId: token.team.id, + teamName: token.team.name, + slackUserId: token.authed_user.id, + botUserId: token.bot_user_id ?? null, + botToken: await box.seal(token.access_token), + scopes: token.scope ?? "", + status: "active" as const, + lastError: null, + }; + await db + .insert(schema.slackAccounts) + .values({ userId: args.userId, ...values }) + .onConflictDoUpdate({ target: schema.slackAccounts.userId, set: values }); + return { team: token.team.name }; +} + +/** + * Deletes the user's Slack account. The bot token is revoked at Slack unless someone else + * on this server uses the same workspace install (Slack issues one bot token per workspace). + */ +export async function disconnectSlack( + app: SlackAppConfig | null, + db: Db, + box: SecretBox, + userId: string, +) { + const [row] = await db + .select() + .from(schema.slackAccounts) + .where(eq(schema.slackAccounts.userId, userId)); + if (!row) return; + const [shared] = await db + .select({ userId: schema.slackAccounts.userId }) + .from(schema.slackAccounts) + .where( + and(eq(schema.slackAccounts.teamId, row.teamId), ne(schema.slackAccounts.userId, userId)), + ); + if (app && !shared) { + try { + await slackCall(app, await box.open(row.botToken), "auth.revoke", {}); + } catch { + // Revocation is a courtesy; the token is deleted either way. + } + } + await db.delete(schema.slackAccounts).where(eq(schema.slackAccounts.userId, userId)); +} + +/** Calls a Slack Web API method with a bot token; throws SlackApiError when `ok` is false. */ +export async function slackCall>( + app: SlackAppConfig, + token: string, + method: string, + body: Record, +): Promise { + const res = await (app.fetch ?? fetch)(`${API}/${method}`, { + method: "POST", + headers: { + authorization: `Bearer ${token}`, + "content-type": "application/json; charset=utf-8", + }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(10_000), + }); + const json = (await res.json().catch(() => ({ ok: false, error: `http_${res.status}` }))) as { + ok: boolean; + error?: string; + }; + if (!json.ok) throw new SlackApiError(method, json.error ?? `http_${res.status}`); + return json as T; +} + +/** Posts to an interaction's `response_url` (no token; Slack scopes the URL to the message). */ +export async function slackRespond(app: SlackAppConfig, responseUrl: string, body: unknown) { + const url = new URL(responseUrl); + // Only ever post back to Slack, whatever the (signed) payload says. + if (url.protocol !== "https:" || !/(^|\.)slack\.com$/.test(url.hostname)) return; + await (app.fetch ?? fetch)(url, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(10_000), + }); +} + +/** Requests older than this are refused, so a captured request can't be replayed later. */ +export const MAX_SKEW_SECONDS = 5 * 60; + +/** + * Checks Slack's request signature: `v0=` + hex HMAC-SHA256 of `v0::` + * keyed with the signing secret, compared in constant time. + */ +export function verifySlackSignature( + signingSecret: string, + args: { timestamp: string | undefined; signature: string | undefined; body: string }, + now = Date.now(), +): boolean { + const { timestamp, signature, body } = args; + if (!timestamp || !signature || !/^\d+$/.test(timestamp)) return false; + if (Math.abs(now / 1000 - Number(timestamp)) > MAX_SKEW_SECONDS) return false; + const expected = Buffer.from( + `v0=${createHmac("sha256", signingSecret).update(`v0:${timestamp}:${body}`).digest("hex")}`, + ); + const given = Buffer.from(signature); + return given.length === expected.length && timingSafeEqual(given, expected); +} + +/** Signs a request body the way Slack does. For tests and the fake. */ +export function signSlackRequest(signingSecret: string, body: string, timestamp: number) { + return `v0=${createHmac("sha256", signingSecret).update(`v0:${timestamp}:${body}`).digest("hex")}`; +} diff --git a/apps/server/src/notify/slack-testing.ts b/apps/server/src/notify/slack-testing.ts new file mode 100644 index 0000000..a014211 --- /dev/null +++ b/apps/server/src/notify/slack-testing.ts @@ -0,0 +1,146 @@ +import { signSlackRequest } from "./slack-api"; + +/** + * An in-memory stand-in for the slice of Slack's Web API the integration uses: OAuth v2, + * conversations.open, chat.postMessage, chat.update, auth.revoke and response_url posts. + * Pass `fake.fetch` as `SlackAppConfig.fetch` in tests. + */ +export interface FakeSlackMessage { + channel: string; + ts: string; + text: string; + // biome-ignore lint/suspicious/noExplicitAny: Block Kit JSON, inspected loosely in tests + blocks: any[]; + updates: number; +} + +export function fakeSlack(opts: { teamId?: string; teamName?: string } = {}) { + const state = { + teamId: opts.teamId ?? "T1", + teamName: opts.teamName ?? "Acme", + /** The Slack user the next OAuth exchange returns as `authed_user`. */ + nextUser: "U1", + /** Scopes the next OAuth exchange grants. */ + grantedScope: "chat:write,im:write,users:read", + tokens: new Set(), + revoked: [] as string[], + messages: [] as FakeSlackMessage[], + /** Bodies posted to response_url. */ + responses: [] as Record[], + /** Requests seen, as "method" (e.g. "chat.postMessage"). */ + calls: [] as string[], + }; + let n = 0; + + const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); + + async function handle(url: URL, init: RequestInit): Promise { + const raw = typeof init.body === "string" ? init.body : (init.body?.toString() ?? ""); + if (url.host === "hooks.slack.com") { + state.calls.push("response_url"); + state.responses.push(JSON.parse(raw) as Record); + return new Response("ok"); + } + if (url.host !== "slack.com") return json({ ok: false, error: "unknown_host" }, 404); + const method = url.pathname.replace(/^\/api\//, ""); + state.calls.push(method); + + if (method === "oauth.v2.access") { + const p = new URLSearchParams(raw); + if (!p.get("code") || !p.get("client_secret")) + return json({ ok: false, error: "invalid_code" }); + const token = `xoxb-${state.teamId}-${++n}`; + state.tokens.add(token); + return json({ + ok: true, + access_token: token, + token_type: "bot", + scope: state.grantedScope, + bot_user_id: "B1", + app_id: "A1", + team: { id: state.teamId, name: state.teamName }, + authed_user: { id: state.nextUser }, + }); + } + + const auth = new Headers(init.headers).get("authorization") ?? ""; + const token = auth.replace(/^Bearer /, ""); + if (!state.tokens.has(token)) return json({ ok: false, error: "invalid_auth" }); + const body = (raw ? JSON.parse(raw) : {}) as Record; + + if (method === "auth.revoke") { + state.tokens.delete(token); + state.revoked.push(token); + return json({ ok: true, revoked: true }); + } + if (method === "conversations.open") + return json({ ok: true, channel: { id: `D-${String(body.users)}` } }); + if (method === "chat.postMessage") { + const m: FakeSlackMessage = { + channel: String(body.channel), + ts: `${1700000000 + ++n}.000100`, + text: String(body.text ?? ""), + blocks: (body.blocks as unknown[]) ?? [], + updates: 0, + }; + state.messages.push(m); + return json({ ok: true, channel: m.channel, ts: m.ts }); + } + if (method === "chat.update") { + const m = state.messages.find((x) => x.channel === body.channel && x.ts === body.ts); + if (!m) return json({ ok: false, error: "message_not_found" }); + m.text = String(body.text ?? ""); + m.blocks = (body.blocks as unknown[]) ?? []; + m.updates++; + return json({ ok: true, channel: m.channel, ts: m.ts }); + } + return json({ ok: false, error: "unknown_method" }); + } + + const f = (async (input: string | URL | Request, init: RequestInit = {}) => + handle(new URL(input instanceof Request ? input.url : input.toString()), init)) as typeof fetch; + + return { + state, + fetch: f, + /** Messages sent to a Slack user's DM. */ + dms: (slackUserId: string) => state.messages.filter((m) => m.channel === `D-${slackUserId}`), + /** + * The request Slack would send when `user` clicks `actionId` on `message`, signed with + * `signingSecret` (pass another secret or an old timestamp to test rejection). + */ + click( + message: FakeSlackMessage, + actionId: "approve" | "deny", + o: { signingSecret: string; user?: string; team?: string; timestamp?: number }, + ) { + const button = message.blocks + .find((b) => b.type === "actions") + ?.elements.find((e: { action_id: string }) => e.action_id === actionId); + const payload = { + type: "block_actions", + team: { id: o.team ?? state.teamId }, + user: { id: o.user ?? "U1", team_id: o.team ?? state.teamId }, + channel: { id: message.channel }, + container: { type: "message", message_ts: message.ts, channel_id: message.channel }, + response_url: `https://hooks.slack.com/actions/${state.teamId}/1/abc`, + actions: [{ action_id: actionId, block_id: "decision", value: button?.value }], + }; + const body = new URLSearchParams({ payload: JSON.stringify(payload) }).toString(); + const ts = o.timestamp ?? Math.floor(Date.now() / 1000); + return { + method: "POST", + headers: { + "content-type": "application/x-www-form-urlencoded", + "x-slack-request-timestamp": String(ts), + "x-slack-signature": signSlackRequest(o.signingSecret, body, ts), + }, + body, + }; + }, + }; +} diff --git a/apps/server/src/notify/slack.ts b/apps/server/src/notify/slack.ts new file mode 100644 index 0000000..ee9e6af --- /dev/null +++ b/apps/server/src/notify/slack.ts @@ -0,0 +1,494 @@ +import type { Effect } from "@synapse/core"; +import { ConflictError, NotFoundError, schema } from "@synapse/db"; +import type { JSONValue } from "ai"; +import { and, eq, inArray } from "drizzle-orm"; +import { DecisionInputError, decide } from "../decisions"; +import { log } from "../log"; +import type { Services } from "../services"; +import { SlackApiError, type SlackAppConfig, slackCall, slackRespond } from "./slack-api"; +import type { + DecisionSource, + NotificationChannel, + PendingApproval, + ResolvedApproval, +} from "./types"; + +/** Slack block, loosely typed: we only build a handful of kinds. */ +type Block = Record; + +/** What a button carries back. Untrusted: checked against the clicking user's own DMs. */ +interface ActionRef { + r: string; + t: string; +} + +/** The parts of a Slack `block_actions` payload we read. */ +export interface SlackInteraction { + type: string; + team?: { id?: string } | null; + user?: { id?: string; team_id?: string }; + response_url?: string; + actions?: { action_id?: string; value?: string }[]; +} + +/** Slack errors that mean the stored token no longer works. */ +const DEAD_TOKEN = new Set(["invalid_auth", "account_inactive", "token_revoked", "not_authed"]); + +/** + * Approvals as Slack DMs, with Approve / Deny buttons. Each recipient who connected Slack + * gets a message; it is rewritten once the action is decided anywhere. + */ +export class SlackChannel implements NotificationChannel { + readonly name = "slack"; + private readonly inflight = new Set>(); + + constructor(private readonly services: () => Services) {} + + private get app(): SlackAppConfig | null { + return this.services().config.slack; + } + + /** Runs work after the HTTP response (Slack wants an answer within 3 seconds). */ + later(work: () => Promise) { + const p = work() + .catch((error) => log.warn("slack: background work failed", { error: String(error) })) + .finally(() => this.inflight.delete(p)); + this.inflight.add(p); + } + + /** Resolves when background work has finished. For tests and shutdown. */ + async settled() { + while (this.inflight.size > 0) await Promise.allSettled([...this.inflight]); + } + + async notify(approvals: PendingApproval[]) { + const app = this.app; + if (!app || approvals.length === 0) return; + const { db } = this.services().database; + const recipients = [...new Set(approvals.flatMap((a) => a.recipients))]; + const accounts = await db + .select() + .from(schema.slackAccounts) + .where( + and( + inArray(schema.slackAccounts.userId, recipients), + eq(schema.slackAccounts.status, "active"), + ), + ); + for (const account of accounts) { + const mine = approvals.filter((a) => a.recipients.includes(account.userId)); + try { + const token = await this.services().box.open(account.botToken); + const channel = await openDm(app, token, account.slackUserId); + for (const a of mine) { + const posted = await slackCall<{ channel: string; ts: string }>( + app, + token, + "chat.postMessage", + { + channel, + text: `Synapse needs your OK: ${a.preview ?? humanize(a.name)}`, + blocks: approvalBlocks(a), + unfurl_links: false, + unfurl_media: false, + }, + ); + await db + .insert(schema.slackMessages) + .values({ + runId: a.runId, + toolCallId: a.toolCallId, + userId: account.userId, + channel: posted.channel, + ts: posted.ts, + }) + .onConflictDoNothing(); + } + } catch (error) { + await this.failed(account.userId, error); + } + } + } + + async resolved(decided: ResolvedApproval[]) { + for (const d of decided) + await this.rewrite(d.runId, d.toolCallId, (recipient) => + outcomeText({ + approved: d.approved, + via: d.via, + byYou: d.via === "slack" && recipient === d.userId, + executeAfter: d.executeAfter, + }), + ); + } + + /** Rewrites a call's messages to show where it stands now (after "already decided"). */ + async refresh(runId: string, toolCallId: string) { + const call = await loadCall(this.services(), runId, toolCallId); + if (!call || call.status === "awaiting_approval") return; + const approved = call.status !== "denied"; + await this.rewrite(runId, toolCallId, (recipient) => + outcomeText({ + approved, + via: (call.decidedVia ?? "web") as DecisionSource, + byYou: call.decidedVia === "slack" && call.decidedBy === recipient, + executeAfter: call.status === "approved" ? call.executeAfter : null, + done: + call.status === "succeeded" + ? "done" + : call.status === "failed" || call.status === "unknown" + ? "failed" + : null, + }), + ); + } + + private async rewrite(runId: string, toolCallId: string, text: (recipient: string) => string) { + const app = this.app; + if (!app) return; + const { db } = this.services().database; + const sent = await db + .select({ + userId: schema.slackMessages.userId, + channel: schema.slackMessages.channel, + ts: schema.slackMessages.ts, + botToken: schema.slackAccounts.botToken, + }) + .from(schema.slackMessages) + .innerJoin(schema.slackAccounts, eq(schema.slackAccounts.userId, schema.slackMessages.userId)) + .where( + and(eq(schema.slackMessages.runId, runId), eq(schema.slackMessages.toolCallId, toolCallId)), + ); + if (sent.length === 0) return; + const call = await loadCall(this.services(), runId, toolCallId); + if (!call) return; + for (const m of sent) { + const line = text(m.userId); + try { + await slackCall(app, await this.services().box.open(m.botToken), "chat.update", { + channel: m.channel, + ts: m.ts, + text: `${line}: ${call.preview ?? humanize(call.name)}`, + blocks: decidedBlocks(call, line), + }); + } catch (error) { + await this.failed(m.userId, error); + } + } + } + + /** + * A verified button click. Acts only for the Synapse user who connected this Slack + * identity, and only on an action that was sent to them. + */ + async handleInteraction(payload: SlackInteraction) { + const app = this.app; + if (!app || payload.type !== "block_actions") return; + const action = payload.actions?.[0]; + if (action?.action_id !== "approve" && action?.action_id !== "deny") return; + const ref = parseRef(action.value); + const teamId = payload.team?.id ?? payload.user?.team_id; + const slackUserId = payload.user?.id; + const refuse = (text: string) => + payload.response_url + ? slackRespond(app, payload.response_url, { + response_type: "ephemeral", + replace_original: false, + text, + }) + : Promise.resolve(); + if (!ref || !teamId || !slackUserId) return; + + const { db } = this.services().database; + const [account] = await db + .select({ userId: schema.slackAccounts.userId }) + .from(schema.slackAccounts) + .where( + and( + eq(schema.slackAccounts.teamId, teamId), + eq(schema.slackAccounts.slackUserId, slackUserId), + eq(schema.slackAccounts.status, "active"), + ), + ); + if (!account) return refuse("Your Slack account isn't connected to Synapse."); + const [sent] = await db + .select({ runId: schema.slackMessages.runId }) + .from(schema.slackMessages) + .where( + and( + eq(schema.slackMessages.runId, ref.r), + eq(schema.slackMessages.toolCallId, ref.t), + eq(schema.slackMessages.userId, account.userId), + ), + ); + if (!sent) return refuse("Only the person this was sent to can decide it."); + + try { + await decide(this.services(), { + userId: account.userId, + runId: ref.r, + decisions: [{ toolCallId: ref.t, approved: action.action_id === "approve" }], + via: "slack", + }); + } catch (error) { + if (error instanceof ConflictError) return this.refresh(ref.r, ref.t); + // e.g. sent to someone who may see it but not decide it here (not the task's owner). + if (error instanceof NotFoundError) + return refuse("This one can't be decided from Slack. Open it in Synapse."); + if (error instanceof DecisionInputError) return refuse(error.message); + throw error; + } + } + + /** Sends a hello DM so people can see where approvals will land. */ + async sendTest(userId: string): Promise { + const app = this.app; + if (!app) return false; + const [account] = await this.services() + .database.db.select() + .from(schema.slackAccounts) + .where(eq(schema.slackAccounts.userId, userId)); + if (!account) return false; + try { + const token = await this.services().box.open(account.botToken); + const channel = await openDm(app, token, account.slackUserId); + await slackCall(app, token, "chat.postMessage", { + channel, + text: "Synapse is connected. When a task needs your OK, it will ask here.", + blocks: [ + section( + "*Synapse is connected.* When a task needs your OK, it will ask here, with Approve and Deny buttons.", + ), + context(`<${this.services().config.PUBLIC_URL}/connections|Manage in Synapse>`), + ], + }); + if (account.status !== "active") + await this.services() + .database.db.update(schema.slackAccounts) + .set({ status: "active", lastError: null }) + .where(eq(schema.slackAccounts.userId, userId)); + return true; + } catch (error) { + await this.failed(userId, error); + throw error; + } + } + + private async failed(userId: string, error: unknown) { + log.warn("slack: delivery failed", { userId, error: String(error) }); + if (error instanceof SlackApiError && DEAD_TOKEN.has(error.code)) + await this.services() + .database.db.update(schema.slackAccounts) + .set({ status: "error", lastError: "Slack access was revoked. Reconnect Slack." }) + .where(eq(schema.slackAccounts.userId, userId)); + } +} + +async function openDm(app: SlackAppConfig, token: string, slackUserId: string) { + const res = await slackCall<{ channel: { id: string } }>(app, token, "conversations.open", { + users: slackUserId, + }); + return res.channel.id; +} + +interface CallInfo { + name: string; + effect: Effect; + preview: string | null; + title: string | null; + url: string; + status: string; + decidedVia: string | null; + decidedBy: string | null; + executeAfter: Date | null; +} + +async function loadCall( + services: Services, + runId: string, + toolCallId: string, +): Promise { + const [row] = await services.database.db + .select({ + name: schema.toolCalls.name, + effect: schema.toolCalls.effect, + preview: schema.toolCalls.preview, + title: schema.chats.title, + chatId: schema.chats.id, + status: schema.toolCalls.status, + decidedVia: schema.toolCalls.decidedVia, + decidedBy: schema.toolCalls.decidedBy, + executeAfter: schema.toolCalls.executeAfter, + }) + .from(schema.toolCalls) + .innerJoin(schema.runs, eq(schema.runs.id, schema.toolCalls.runId)) + .innerJoin(schema.chats, eq(schema.chats.id, schema.runs.chatId)) + .where(and(eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.id, toolCallId))); + if (!row) return null; + return { ...row, url: `${services.config.PUBLIC_URL}/t/${row.chatId}` }; +} + +function parseRef(value: string | undefined): ActionRef | null { + try { + const v = JSON.parse(value ?? "") as Partial; + return typeof v.r === "string" && typeof v.t === "string" && v.r && v.t + ? { r: v.r, t: v.t } + : null; + } catch { + return null; + } +} + +// ── Rendering ────────────────────────────────────────────────────────────── + +const PLACE: Record = { + web: "in the web app", + push: "from your phone", + slack: "in Slack", + email: "by email", +}; + +/** The status line that replaces the buttons, e.g. "Approved by you · sending in 10s". */ +export function outcomeText(o: { + approved: boolean; + via: DecisionSource; + byYou: boolean; + executeAfter: Date | null; + done?: "done" | "failed" | null; + now?: number; +}): string { + const where = o.byYou ? "by you" : (PLACE[o.via] ?? "elsewhere"); + if (!o.approved) return `Denied ${where}`; + let line = `Approved ${where}`; + const wait = o.executeAfter + ? Math.round((o.executeAfter.getTime() - (o.now ?? Date.now())) / 1000) + : 0; + if (wait > 0) line += ` · sending in ${wait}s (undo in Synapse)`; + if (o.done === "done") line += " · done"; + if (o.done === "failed") line += " · it failed, see Synapse"; + return line; +} + +/** Slack mrkdwn: these three must be escaped so text can't become links or mentions. */ +export function esc(s: string) { + return s.replace(/&/g, "&").replace(//g, ">"); +} + +function clip(s: string, n: number) { + const flat = s.trim(); + return flat.length > n ? `${flat.slice(0, n - 1)}…` : flat; +} + +function humanize(name: string) { + const s = name.replace(/[_-]+/g, " "); + return s.charAt(0).toUpperCase() + s.slice(1); +} + +const section = (text: string): Block => ({ + type: "section", + text: { type: "mrkdwn", text: clip(text, 2900) }, +}); +const context = (text: string): Block => ({ + type: "context", + elements: [{ type: "mrkdwn", text: clip(text, 2900) }], +}); + +function str(v: JSONValue | undefined): string | null { + if (v === undefined || v === null) return null; + if (typeof v === "string") return v; + if (Array.isArray(v) && v.every((x) => typeof x === "string")) return v.join(", "); + return JSON.stringify(v); +} + +/** A short rendering of the input: email-shaped inputs as an email, others as key fields. */ +export function renderInput(input: JSONValue): string | null { + if (input === null || typeof input !== "object" || Array.isArray(input)) { + const s = str(input); + return s ? `\`${esc(clip(s, 300))}\`` : null; + } + const o = input as Record; + const lines: string[] = []; + if ("to" in o || "subject" in o) { + for (const key of ["to", "cc", "bcc", "subject"] as const) { + const v = str(o[key]); + if (v) + lines.push( + `*${key === "subject" ? "Subject" : key.charAt(0).toUpperCase() + key.slice(1)}:* ${esc(clip(v, 200))}`, + ); + } + const body = str(o.body ?? o.text ?? o.message); + if (body) { + const first = body + .split(/\r?\n/) + .filter((l) => l.trim()) + .slice(0, 5); + lines.push(...first.map((l) => `> ${esc(clip(l, 200))}`)); + if (body.split(/\r?\n/).filter((l) => l.trim()).length > first.length) lines.push("> …"); + } + return lines.join("\n") || null; + } + const entries = Object.entries(o).filter(([, v]) => v !== null && v !== undefined); + for (const [k, v] of entries.slice(0, 6)) + lines.push(`*${esc(humanize(k))}:* ${esc(clip(str(v) ?? "", 160))}`); + if (entries.length > 6) lines.push(`_…and ${entries.length - 6} more_`); + return lines.join("\n") || null; +} + +/** The DM asking for an OK. */ +export function approvalBlocks(a: PendingApproval): Block[] { + const value = JSON.stringify({ r: a.runId, t: a.toolCallId } satisfies ActionRef); + const input = renderInput(a.input); + return [ + { type: "header", text: { type: "plain_text", text: "Synapse needs your OK" } }, + section(`*${esc(a.preview ?? humanize(a.name))}*`), + context( + `Task: ${esc(clip(a.chatTitle ?? "Untitled task", 150))} · \`${esc(a.name)}\` (${a.effect})`, + ), + ...(input ? [section(input)] : []), + ...(a.reason ? [context(`Why it asks: ${esc(clip(a.reason, 300))}`)] : []), + ...(a.tainted + ? [ + section( + "*Careful:* this task read outside content (an email or a web page) before proposing this. Check it is what you want.", + ), + ] + : []), + { + type: "actions", + block_id: "decision", + elements: [ + { + type: "button", + action_id: "approve", + style: "primary", + text: { type: "plain_text", text: "Approve" }, + value, + }, + { + type: "button", + action_id: "deny", + style: "danger", + text: { type: "plain_text", text: "Deny" }, + value, + }, + { + type: "button", + action_id: "open", + text: { type: "plain_text", text: "Open in Synapse" }, + url: a.url, + }, + ], + }, + ]; +} + +/** The same message once decided: no buttons, a status line instead. */ +export function decidedBlocks(call: CallInfo, line: string): Block[] { + return [ + section(`*${esc(call.preview ?? humanize(call.name))}*`), + context( + `Task: ${esc(clip(call.title ?? "Untitled task", 150))} · <${call.url}|Open in Synapse>`, + ), + section(`*${esc(line)}*`), + ]; +} diff --git a/apps/server/src/routes/integrations.ts b/apps/server/src/routes/integrations.ts index 32388fd..d06503b 100644 --- a/apps/server/src/routes/integrations.ts +++ b/apps/server/src/routes/integrations.ts @@ -8,6 +8,7 @@ import { import { and, eq } from "drizzle-orm"; import { Hono } from "hono"; import { type AppEnv, apiError } from "../http"; +import { slackStatus } from "./slack"; /** What the Google integration adds, for the Connections page. */ const GOOGLE_TOOLS = [ @@ -48,6 +49,7 @@ export const integrations = new Hono() } : null, }, + slack: await slackStatus(c), }); }) diff --git a/apps/server/src/routes/slack.ts b/apps/server/src/routes/slack.ts new file mode 100644 index 0000000..d878fb2 --- /dev/null +++ b/apps/server/src/routes/slack.ts @@ -0,0 +1,128 @@ +import { schema } from "@synapse/db"; +import { eq } from "drizzle-orm"; +import { Hono } from "hono"; +import { type AppEnv, apiError } from "../http"; +import { log } from "../log"; +import type { SlackInteraction } from "../notify/slack"; +import { + completeSlackAuth, + disconnectSlack, + SlackApiError, + SlackAuthError, + slackAuthorizationUrl, + verifySlackSignature, +} from "../notify/slack-api"; + +const NOT_CONFIGURED = + "Slack isn't set up on this server. Set SLACK_CLIENT_ID, SLACK_CLIENT_SECRET and SLACK_SIGNING_SECRET (see docs/slack.md)."; + +/** The signed-in user's Slack connection, for GET /api/integrations. */ +export async function slackStatus(c: { var: AppEnv["Variables"] }) { + const [row] = await c.var.services.database.db + .select() + .from(schema.slackAccounts) + .where(eq(schema.slackAccounts.userId, c.var.user.id)); + return { + available: Boolean(c.var.services.config.slack), + connection: row + ? { + team: row.teamName, + status: row.status, + lastError: row.lastError, + connectedAt: row.createdAt, + } + : null, + }; +} + +/** Connect, disconnect and test; behind requireUser. */ +export const slackIntegration = new Hono() + .post("/connect", async (c) => { + const slack = c.var.services.config.slack; + if (!slack) apiError(422, "not_configured", NOT_CONFIGURED); + return c.json({ url: await slackAuthorizationUrl(slack, c.var.services.box, c.var.user.id) }); + }) + + /** + * Slack's redirect target. It must land in the browser session that started the flow, + * and the sealed state names that user. + */ + .get("/callback", async (c) => { + const { config, database, box } = c.var.services; + const back = (q: string) => c.redirect(`${config.PUBLIC_URL}/connections?${q}`); + const code = c.req.query("code"); + const error = c.req.query("error"); + if (!config.slack) return back("error=not_configured"); + if (error || !code) + return back( + `error=${encodeURIComponent(error === "access_denied" ? "You cancelled the Slack install." : (error ?? "missing_code"))}`, + ); + try { + await completeSlackAuth(config.slack, database.db, box, { + userId: c.var.user.id, + code, + state: c.req.query("state") ?? "", + }); + return back("connected=slack"); + } catch (e) { + const message = e instanceof SlackAuthError ? e.message : "Slack sign-in failed. Try again."; + if (!(e instanceof SlackAuthError)) log.warn("slack: oauth failed", { error: String(e) }); + return back(`error=${encodeURIComponent(message)}`); + } + }) + + .post("/test", async (c) => { + const slack = c.var.services.slack; + if (!slack) apiError(422, "not_configured", NOT_CONFIGURED); + try { + if (!(await slack.sendTest(c.var.user.id))) + apiError(422, "slack_not_connected", "Connect Slack first."); + } catch (e) { + if (e instanceof SlackApiError) + apiError(422, "slack_error", `Slack refused the message (${e.code}). Try reconnecting.`); + throw e; + } + return c.json({ ok: true }); + }) + + .delete("/", async (c) => { + await disconnectSlack( + c.var.services.config.slack, + c.var.services.database.db, + c.var.services.box, + c.var.user.id, + ); + return c.body(null, 204); + }); + +/** Button clicks are small; anything bigger is not from Slack. */ +const MAX_BODY = 64 * 1024; + +/** + * Slack's interactivity Request URL. Public: authenticated by Slack's request signature, + * checked over the raw body before anything is parsed. Answers at once and does the work + * afterwards, since Slack gives up after 3 seconds. + */ +export const slackInteractions = new Hono().post("/", async (c) => { + const { config, slack: channel } = c.var.services; + if (!config.slack || !channel) return c.json({ error: { code: "not_configured" } }, 404); + if (Number(c.req.header("content-length") ?? 0) > MAX_BODY) + return c.json({ error: { code: "too_large" } }, 413); + const raw = await c.req.text(); + if (raw.length > MAX_BODY) return c.json({ error: { code: "too_large" } }, 413); + const ok = verifySlackSignature(config.slack.signingSecret, { + timestamp: c.req.header("x-slack-request-timestamp"), + signature: c.req.header("x-slack-signature"), + body: raw, + }); + if (!ok) return c.json({ error: { code: "unauthorized", message: "Bad signature." } }, 401); + + let payload: SlackInteraction; + try { + payload = JSON.parse(new URLSearchParams(raw).get("payload") ?? "") as SlackInteraction; + } catch { + return c.json({ error: { code: "invalid_request" } }, 400); + } + channel.later(() => channel.handleInteraction(payload)); + return c.body(null, 200); +}); diff --git a/apps/server/src/services.ts b/apps/server/src/services.ts index ca448ff..2265feb 100644 --- a/apps/server/src/services.ts +++ b/apps/server/src/services.ts @@ -3,6 +3,7 @@ import { createEmbedder, type ToolsetConfig } from "@synapse/tools"; import { type Auth, createAuth } from "./auth"; import type { Config } from "./config"; import { Notifier } from "./notify/notifier"; +import { SlackChannel } from "./notify/slack"; export const RUNS_CHANNEL = "synapse_runs"; @@ -47,6 +48,8 @@ export interface Services { toolset: ToolsetConfig; /** Tells people about approvals through push, Slack and other channels. */ notifier: Notifier; + /** Set when a Slack app is configured; also registered with the notifier. */ + slack: SlackChannel | null; /** Wakes idle workers (on any instance) when a run becomes runnable. */ wake: (runId: string) => Promise; close: () => Promise; @@ -73,11 +76,14 @@ export async function createServices(config: Config): Promise { google: config.google, }, notifier: new Notifier(() => services), + slack: config.slack ? new SlackChannel(() => services) : null, wake: (runId) => database.notify(RUNS_CHANNEL, runId), close: async () => { + await services.slack?.settled(); await stop(); await database.close(); }, }; + if (services.slack) services.notifier.add(services.slack); return services; } diff --git a/apps/server/src/slack.test.ts b/apps/server/src/slack.test.ts new file mode 100644 index 0000000..c2c875e --- /dev/null +++ b/apps/server/src/slack.test.ts @@ -0,0 +1,310 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { type ScriptedStep, scriptedModel } from "@synapse/core/testing"; +import { schema } from "@synapse/db"; +import { and, eq } from "drizzle-orm"; +import { createApp } from "./app"; +import { loadConfig } from "./config"; +import { outcomeText, renderInput } from "./notify/slack"; +import { verifySlackSignature } from "./notify/slack-api"; +import { fakeSlack } from "./notify/slack-testing"; +import { createServices, type Services } from "./services"; +import { Worker } from "./worker"; + +const ORIGIN = "http://localhost:3000"; +const SIGNING = "signing-secret-123"; +const slack = fakeSlack({ teamId: "T1", teamName: "Acme" }); +let services: Services; +let app: ReturnType; +let worker: Worker; +let model = scriptedModel([]); +const script = (steps: ScriptedStep[]) => { + model = scriptedModel(steps); +}; + +beforeAll(async () => { + services = await createServices( + loadConfig({ + NODE_ENV: "test", + DATABASE_URL: "pglite://memory", + SYNAPSE_SECRET: "t".repeat(40), + PUBLIC_URL: ORIGIN, + SLACK_CLIENT_ID: "cid", + SLACK_CLIENT_SECRET: "csecret", + SLACK_SIGNING_SECRET: SIGNING, + }), + ); + services.config.slack!.fetch = slack.fetch; + app = createApp(services); + worker = new Worker(services, () => [model]); +}); +afterAll(() => services.close()); + +async function signUp(email: string) { + const res = await app.request("/api/auth/sign-up/email", { + method: "POST", + headers: { "content-type": "application/json", origin: ORIGIN }, + body: JSON.stringify({ email, password: "correct horse battery", name: email.split("@")[0] }), + }); + expect(res.status).toBe(200); + const cookie = res.headers + .getSetCookie() + .map((c) => c.split(";")[0]) + .join("; "); + return async (path: string, init: { method?: string; json?: unknown } = {}) => { + const r = await app.request(path, { + method: init.method ?? "GET", + headers: { + cookie, + origin: ORIGIN, + ...(init.json !== undefined ? { "content-type": "application/json" } : {}), + }, + ...(init.json !== undefined ? { body: JSON.stringify(init.json) } : {}), + }); + const text = await r.text(); + return { + status: r.status, + location: r.headers.get("location"), + json: + text && r.headers.get("content-type")?.includes("json") + ? // biome-ignore lint/suspicious/noExplicitAny: test responses are loosely typed JSON + (JSON.parse(text) as any) + : null, + }; + }; +} +type Client = Awaited>; + +async function connectSlack(me: Client, slackUser: string) { + slack.state.nextUser = slackUser; + const start = await me("/api/integrations/slack/connect", { method: "POST", json: {} }); + expect(start.status).toBe(200); + const url = new URL(start.json.url); + expect(url.host).toBe("slack.com"); + expect(url.searchParams.get("scope")).toBe("chat:write,im:write,users:read"); + expect(url.searchParams.get("redirect_uri")).toBe(`${ORIGIN}/api/integrations/slack/callback`); + const state = url.searchParams.get("state")!; + const back = await me( + `/api/integrations/slack/callback?code=abc&state=${encodeURIComponent(state)}`, + ); + expect(back.location).toBe(`${ORIGIN}/connections?connected=slack`); +} + +/** Starts a task whose one action (saving a memory) waits for approval. */ +async function ask(me: Client, note = "likes tea", content = "remember tea") { + await me("/api/policy", { + method: "PUT", + json: { + defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" }, + rules: [{ tool: "memory_save", decision: "ask" }], + }, + }); + script([{ toolCalls: [{ name: "memory_save", input: { note }, id: "n1" }] }, { text: "Saved." }]); + const { json } = await me("/api/chats", { method: "POST", json: { content } }); + const runId = json.runId as string; + await worker.processNow(runId); + return runId; +} + +const call = async (runId: string) => + ( + await services.database.db + .select() + .from(schema.toolCalls) + .where(and(eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.id, "n1"))) + )[0]!; + +async function click(req: ReturnType) { + const res = await app.request("/api/slack/interactions", req); + await services.slack!.settled(); + return res; +} + +const lastBlockText = (m: { blocks: { text?: { text: string } }[] }) => + m.blocks.map((b) => b.text?.text ?? "").join("\n"); + +test("connecting Slack over HTTP is bound to the user who started it", async () => { + const me = await signUp("slack-connect@example.com"); + const before = await me("/api/integrations"); + expect(before.json.slack).toEqual({ available: true, connection: null }); + + const start = await me("/api/integrations/slack/connect", { method: "POST", json: {} }); + const state = new URL(start.json.url).searchParams.get("state")!; + const eve = await signUp("slack-eve@example.com"); + const stolen = await eve( + `/api/integrations/slack/callback?code=x&state=${encodeURIComponent(state)}`, + ); + expect(decodeURIComponent(stolen.location!)).toContain("belongs to another user"); + expect((await eve("/api/integrations")).json.slack.connection).toBeNull(); + + const cancelled = await me("/api/integrations/slack/callback?error=access_denied"); + expect(decodeURIComponent(cancelled.location!)).toContain("You cancelled"); + + await connectSlack(me, "U-conn"); + const after = await me("/api/integrations"); + expect(after.json.slack.connection).toMatchObject({ team: "Acme", status: "active" }); + const [row] = await services.database.db.select().from(schema.slackAccounts); + expect(row?.botToken.startsWith("xoxb-")).toBe(false); // sealed at rest + + // The same Slack person can't answer for a second Synapse user. + slack.state.nextUser = "U-conn"; + const again = await eve("/api/integrations/slack/connect", { method: "POST", json: {} }); + const s2 = new URL(again.json.url).searchParams.get("state")!; + const dup = await eve(`/api/integrations/slack/callback?code=y&state=${encodeURIComponent(s2)}`); + expect(decodeURIComponent(dup.location!)).toContain("already connected"); + + const test = await me("/api/integrations/slack/test", { method: "POST", json: {} }); + expect(test.status).toBe(200); + expect(slack.dms("U-conn").at(-1)?.text).toContain("Synapse is connected"); + + expect((await me("/api/integrations/slack", { method: "DELETE" })).status).toBe(204); + expect(slack.state.revoked).toHaveLength(1); + expect((await me("/api/integrations")).json.slack.connection).toBeNull(); +}); + +test("an approval is DMed with buttons, and a signed click from the right person approves it", async () => { + const me = await signUp("slack-ada@example.com"); + await connectSlack(me, "U-ada"); + const runId = await ask(me, "likes green tea"); + + const dms = slack.dms("U-ada"); + expect(dms).toHaveLength(1); + const msg = dms[0]!; + expect(msg.blocks[0]).toEqual({ + type: "header", + text: { type: "plain_text", text: "Synapse needs your OK" }, + }); + const text = lastBlockText(msg); + expect(text).toContain("likes green tea"); + const actions = msg.blocks.find((b) => b.type === "actions"); + expect(actions.elements.map((e: { action_id: string }) => e.action_id)).toEqual([ + "approve", + "deny", + "open", + ]); + expect(actions.elements[0].style).toBe("primary"); + expect(actions.elements[1].style).toBe("danger"); + expect(actions.elements[2].url).toStartWith(`${ORIGIN}/t/`); + const [stored] = await services.database.db + .select() + .from(schema.slackMessages) + .where(eq(schema.slackMessages.runId, runId)); + expect(stored).toMatchObject({ toolCallId: "n1", channel: msg.channel, ts: msg.ts }); + + // Forged and stale requests are refused before anything is read. + const forged = await click(slack.click(msg, "approve", { signingSecret: "wrong" })); + expect(forged.status).toBe(401); + const stale = await click( + slack.click(msg, "approve", { + signingSecret: SIGNING, + user: "U-ada", + timestamp: Math.floor(Date.now() / 1000) - 6 * 60, + }), + ); + expect(stale.status).toBe(401); + const tampered = slack.click(msg, "approve", { signingSecret: SIGNING, user: "U-ada" }); + tampered.body = tampered.body.replace("approve", "deny"); + expect((await click(tampered)).status).toBe(401); + expect((await call(runId)).status).toBe("awaiting_approval"); + + // Another Slack user (connected to nobody here) is refused. + const other = await click(slack.click(msg, "approve", { signingSecret: SIGNING, user: "U-x" })); + expect(other.status).toBe(200); + expect((await call(runId)).status).toBe("awaiting_approval"); + expect(slack.state.responses.at(-1)).toMatchObject({ response_type: "ephemeral" }); + + // Clicked on the message as it was, before it updated (a double click, or a second device). + const late = slack.click(msg, "deny", { signingSecret: SIGNING, user: "U-ada" }); + const ok = await click(slack.click(msg, "approve", { signingSecret: SIGNING, user: "U-ada" })); + expect(ok.status).toBe(200); + const decided = await call(runId); + expect(decided).toMatchObject({ decidedVia: "slack" }); + expect(["approved", "succeeded"]).toContain(decided.status); + expect(msg.updates).toBe(1); + expect(lastBlockText(msg)).toContain("Approved by you"); + expect(msg.blocks.some((b) => b.type === "actions")).toBe(false); + + // A double click shows the current state instead of failing. + const twice = await click(late); + expect(twice.status).toBe(200); + expect(msg.updates).toBe(2); + expect(lastBlockText(msg)).toContain("Approved by you"); + expect((await call(runId)).decidedVia).toBe("slack"); +}); + +test("a connected Slack user can't decide someone else's action", async () => { + const bob = await signUp("slack-bob@example.com"); + const mal = await signUp("slack-mal@example.com"); + await connectSlack(bob, "U-bob"); + await connectSlack(mal, "U-mal"); + const runId = await ask(bob); + const msg = slack.dms("U-bob").at(-1)!; + expect(slack.dms("U-mal")).toHaveLength(0); + const res = await click(slack.click(msg, "approve", { signingSecret: SIGNING, user: "U-mal" })); + expect(res.status).toBe(200); + expect((await call(runId)).status).toBe("awaiting_approval"); + expect(String(slack.state.responses.at(-1)?.text)).toContain("Only the person"); + expect(msg.updates).toBe(0); + + // Denying from Slack. + await click(slack.click(msg, "deny", { signingSecret: SIGNING, user: "U-bob" })); + expect(await call(runId)).toMatchObject({ status: "denied", decidedVia: "slack" }); + expect(lastBlockText(msg)).toContain("Denied by you"); +}); + +test("deciding in the web app updates the Slack message", async () => { + const me = await signUp("slack-web@example.com"); + await connectSlack(me, "U-web"); + const runId = await ask(me); + const msg = slack.dms("U-web").at(-1)!; + const res = await me(`/api/runs/${runId}/tool-calls/n1/decision`, { + method: "POST", + json: { approved: true }, + }); + expect(res.status).toBe(200); + expect(msg.updates).toBe(1); + expect(lastBlockText(msg)).toContain("Approved in the web app"); + expect(msg.blocks.some((b) => b.type === "actions")).toBe(false); +}); + +test("nothing is sent to people without Slack", async () => { + const me = await signUp("slack-none@example.com"); + const before = slack.state.calls.length; + const runId = await ask(me); + expect((await call(runId)).status).toBe("awaiting_approval"); + expect(slack.state.calls.slice(before)).toEqual([]); +}); + +test("rendering: email inputs, key fields, outcome lines, signatures", () => { + const email = renderInput({ + to: ["bob@acme.com"], + subject: "Re: ", + body: "Hi Bob,\n\nSee you at 3.\nline 3\nline 4\nline 5\nline 6", + })!; + expect(email).toContain("*To:* bob@acme.com"); + expect(email).toContain("*Subject:* Re: <Sync>"); + expect(email).toContain("> Hi Bob,"); + expect(email).toContain("> …"); + expect(renderInput({ note: "x".repeat(500) })!.length).toBeLessThan(200); + // Untrusted text can't smuggle in a link or a mention. + expect(renderInput({ note: " <@U1>" })).not.toContain("<"); + + const now = Date.now(); + expect( + outcomeText({ + approved: true, + via: "slack", + byYou: true, + executeAfter: new Date(now + 10_000), + now, + }), + ).toBe("Approved by you · sending in 10s (undo in Synapse)"); + expect(outcomeText({ approved: false, via: "push", byYou: false, executeAfter: null })).toBe( + "Denied from your phone", + ); + + const ts = Math.floor(now / 1000); + expect(verifySlackSignature("s", { timestamp: String(ts), signature: "v0=00", body: "" })).toBe( + false, + ); + expect(verifySlackSignature("s", { timestamp: undefined, signature: "x", body: "" })).toBe(false); +}); diff --git a/apps/web/app/(app)/connections/page.tsx b/apps/web/app/(app)/connections/page.tsx index 0568bcb..c99af85 100644 --- a/apps/web/app/(app)/connections/page.tsx +++ b/apps/web/app/(app)/connections/page.tsx @@ -38,6 +38,7 @@ import { errorMessage, type GoogleIntegration, type Preset, + type SlackIntegration, } from "@/lib/api"; import { hostOf, humanize } from "@/lib/format"; import { useApi } from "@/lib/use-api"; @@ -82,6 +83,7 @@ export default function ConnectionsPage() { const connected = q.get("connected"); const error = q.get("error"); if (connected === "google") toast("Google connected", "success"); + else if (connected === "slack") toast("Slack connected", "success"); else if (connected) toast("Connection authorized", "success"); if (error) toast(error.includes(" ") ? error : `Authorization failed: ${error}`, "error"); if (q.has("add")) setAdding(true); @@ -125,10 +127,16 @@ export default function ConnectionsPage() { Built in {integrations.data ? ( - void integrations.reload()} - /> +
+ void integrations.reload()} + /> + void integrations.reload()} + /> +
) : ( )} @@ -743,3 +751,135 @@ function GoogleCard({ google, onChange }: { google: GoogleIntegration; onChange: ); } + +const SLACK_SETUP = "https://github.com/Taskmaster-1/SynapseAI/blob/main/docs/slack.md"; + +function SlackCard({ slack, onChange }: { slack: SlackIntegration; onChange: () => void }) { + const toast = useToast(); + const [busy, setBusy] = useState<"connect" | "disconnect" | "test" | null>(null); + const conn = slack.connection; + const connected = conn?.status === "active"; + + async function connect() { + setBusy("connect"); + try { + const { url } = await api.connectSlack(); + startOAuth(url); + } catch (err) { + toast(errorMessage(err), "error"); + setBusy(null); + } + } + + async function run(label: "disconnect" | "test", fn: () => Promise) { + setBusy(label); + try { + await fn(); + } catch (err) { + toast(errorMessage(err), "error"); + } finally { + setBusy(null); + } + } + + const disconnect = () => { + if (!window.confirm("Disconnect Slack? Approvals stop arriving as Slack messages.")) return; + void run("disconnect", async () => { + await api.disconnectSlack(); + toast("Slack disconnected", "success"); + onChange(); + }); + }; + + const test = () => + void run("test", async () => { + await api.testSlack(); + toast("Sent. Check your Slack messages from Synapse.", "success"); + onChange(); + }); + + return ( +
+
+ +
+
Slack
+
+ {conn + ? `${conn.team} workspace` + : "Approve or deny from a Slack message when a task needs your OK."} +
+
+
+ {conn ? : null} + {!slack.available ? ( + + Setup guide + + + ) : conn ? ( + <> + {connected ? ( + + ) : ( + + )} + + + ) : ( + + )} +
+
+ {conn?.lastError && !connected ? ( +

{conn.lastError}

+ ) : null} +

+ {!slack.available ? ( + <> + This server has no Slack app yet. Whoever runs it creates one from the manifest in the + guide and sets SLACK_CLIENT_ID,{" "} + SLACK_CLIENT_SECRET and{" "} + SLACK_SIGNING_SECRET. + + ) : connected ? ( + "When a task needs your OK, Synapse messages you in Slack. Only you can press its buttons, and the message updates wherever you decide." + ) : ( + "Synapse messages you directly; it can't read your channels or messages." + )} +

+
+ ); +} diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts index c071c64..63d8d0d 100644 --- a/apps/web/lib/api.ts +++ b/apps/web/lib/api.ts @@ -328,6 +328,18 @@ export interface GoogleIntegration { } | null; } +export interface SlackIntegration { + /** False when the server has no Slack app configured. */ + available: boolean; + connection: { + /** Workspace name. */ + team: string; + status: "active" | "error"; + lastError: string | null; + connectedAt: string; + } | null; +} + // ---------- Endpoints ---------- export interface SessionUser { @@ -416,9 +428,13 @@ export const api = { searchDocuments: (q: string, signal?: AbortSignal) => get<{ results: SearchResult[] }>(`/api/documents/search?q=${enc(q)}`, { signal }), - integrations: () => get<{ google: GoogleIntegration }>("/api/integrations"), + integrations: () => + get<{ google: GoogleIntegration; slack: SlackIntegration }>("/api/integrations"), connectGoogle: () => post<{ url: string }>("/api/integrations/google/connect", {}), disconnectGoogle: () => del("/api/integrations/google"), + connectSlack: () => post<{ url: string }>("/api/integrations/slack/connect", {}), + testSlack: () => post<{ ok: true }>("/api/integrations/slack/test", {}), + disconnectSlack: () => del("/api/integrations/slack"), automations: () => get<{ automations: Automation[] }>("/api/automations"), createAutomation: (body: AutomationInput) => post<{ automation: Automation }>("/api/automations", body), diff --git a/docs/api.md b/docs/api.md index c7a03cd..cc980da 100644 --- a/docs/api.md +++ b/docs/api.md @@ -15,8 +15,9 @@ Types referenced below (`UiMessage`, `UiPart`, `SeqEvent`, `RunStatus`, `Effect` | Method | Path | Response | |---|---|---| | GET | `/api/health` | `{ ok: true }` | -| GET | `/api/config` | `{ auth: { emailPassword: boolean, github: boolean, google: boolean }, integrations: { google: boolean }, features: { webSearch: boolean, embeddings: boolean }, models: string[] }` | +| GET | `/api/config` | `{ auth: { emailPassword: boolean, github: boolean, google: boolean }, integrations: { google: boolean, slack: boolean }, features: { webSearch: boolean, embeddings: boolean }, models: string[] }` | | GET | `/oauth/client-metadata.json` | OAuth client metadata document for MCP servers | +| POST | `/api/slack/interactions` | Slack's interactivity endpoint (button clicks). Authenticated by Slack's `X-Slack-Signature` over the raw body, rejected (`401`) when wrong or more than 5 minutes old. Answers `200` at once and decides in the background | | POST | `/api/hooks/:automationId/:token` | Starts a task for a webhook automation. Any body (JSON is pretty-printed for the agent, capped at 16 KB). `202 { ok, taskId }`; `404` for an unknown id or wrong token, `409` when paused, `413` over 256 KB, `429` over 60 per hour | ## Chats @@ -87,10 +88,17 @@ Gmail and Google Calendar, without an MCP server. Needs `GOOGLE_CLIENT_ID` and | Method | Path | Body | Response | |---|---|---|---| -| GET | `/api/integrations` | | `{ google: { available, tools: { name, effect, title }[], connection: { account, status, lastError, connectedAt } \| null } }` | +| GET | `/api/integrations` | | `{ google: { available, tools: { name, effect, title }[], connection: { account, status, lastError, connectedAt } \| null }, slack: { available, connection: { team, status, lastError, connectedAt } \| null } }` | | POST | `/api/integrations/google/connect` | | `{ url }` — open it in the browser; Google redirects back to the callback | | GET | `/api/integrations/google/callback?code&state` | | redirects to `${PUBLIC_URL}/connections?connected=google` or `?error=` | | DELETE | `/api/integrations/google` | | `204` — revokes the grant at Google and deletes the tokens | +| POST | `/api/integrations/slack/connect` | | `{ url }` — Slack's install page; needs `SLACK_CLIENT_ID`, `SLACK_CLIENT_SECRET`, `SLACK_SIGNING_SECRET` ([setup](slack.md)), else `422 not_configured` | +| GET | `/api/integrations/slack/callback?code&state` | | redirects to `${PUBLIC_URL}/connections?connected=slack` or `?error=` | +| POST | `/api/integrations/slack/test` | | `{ ok: true }` — sends a test DM (`422 slack_not_connected`, `422 slack_error`) | +| DELETE | `/api/integrations/slack` | | `204` — revokes the bot token at Slack and deletes it | + +With Slack connected, each approval addressed to you arrives as a Slack DM with Approve and +Deny; decisions made there are recorded with `decidedVia: "slack"`. ## Policy diff --git a/docs/slack.md b/docs/slack.md new file mode 100644 index 0000000..e307d15 --- /dev/null +++ b/docs/slack.md @@ -0,0 +1,85 @@ +# Approve from Slack + +When a task needs your OK, Synapse can message you in Slack with **Approve**, **Deny** and +**Open in Synapse** buttons. Whoever runs the server creates one Slack app (about five +minutes); after that, each user connects their own Slack from **Connections → Slack**. + +What it can and can't do: + +- It only sends you direct messages, and only about your own approvals. It can't read your + channels or messages. +- Only the Slack person who connected it can press the buttons. A click is acted on only when + Slack's request signature checks out, it is less than five minutes old, and the action was + sent to that person. Button contents are treated as untrusted; ownership is checked again + when the decision is recorded. +- The message updates wherever you decide (web, phone or Slack): "Approved by you · sending in + 10s", "Denied", "Approved in the web app". Undo stays in the web app. +- The bot token is encrypted with `SYNAPSE_SECRET`. Disconnecting deletes it and revokes it at + Slack (unless someone else on this server uses the same workspace install, since Slack issues + one bot token per workspace). + +## Requirements + +Slack must be able to reach your server: `PUBLIC_URL` has to be a public **https** URL +(Slack refuses plain http for interactivity). For local development, use a tunnel such as +`cloudflared tunnel --url http://localhost:3000` and set `PUBLIC_URL` to the tunnel's URL. +The web app forwards `/api/*` to the API server unchanged, which the signature check needs. + +## 1. Create the Slack app + +Open [api.slack.com/apps](https://api.slack.com/apps) → **Create New App → From a manifest**, +pick a workspace, and paste this, replacing `https://synapse.example.com` with your +`PUBLIC_URL`: + +```yaml +display_information: + name: Synapse + description: Asks before it acts. Approve or deny from Slack. +features: + bot_user: + display_name: Synapse + always_online: false + app_home: + messages_tab_enabled: true + messages_tab_read_only_enabled: true +oauth_config: + redirect_urls: + - https://synapse.example.com/api/integrations/slack/callback + scopes: + bot: + - chat:write + - im:write + - users:read +settings: + interactivity: + is_enabled: true + request_url: https://synapse.example.com/api/slack/interactions + org_deploy_enabled: false + socket_mode_enabled: false + token_rotation_enabled: false +``` + +To let people in other workspaces connect, turn on **Manage Distribution → Activate Public +Distribution**. For a single workspace this isn't needed. + +## 2. Configure the server + +From **Basic Information → App Credentials**: + +```sh +SLACK_CLIENT_ID=1234567890.1234567890 +SLACK_CLIENT_SECRET=... +SLACK_SIGNING_SECRET=... +``` + +All three are required. Restart the server; the Connections page now shows **Connect Slack**. +Connect, then press **Send a test DM** to check that messages arrive. + +## Troubleshooting + +- **Buttons do nothing / "This app responded with status code 401"**: the signing secret is + wrong, or the server clock is more than five minutes off. +- **"Slack refused the message (invalid_auth)"**: the app was uninstalled or reinstalled with a + new token. Disconnect and connect again. +- **No message for an approval**: check the Slack card says Connected. Approvals go to the + people who should decide them; each needs their own Slack connected. diff --git a/packages/db/drizzle/0006_slack.sql b/packages/db/drizzle/0006_slack.sql new file mode 100644 index 0000000..6001fd2 --- /dev/null +++ b/packages/db/drizzle/0006_slack.sql @@ -0,0 +1,28 @@ +CREATE TABLE "slack_accounts" ( + "user_id" text PRIMARY KEY NOT NULL, + "team_id" text NOT NULL, + "team_name" text NOT NULL, + "slack_user_id" text NOT NULL, + "bot_user_id" text, + "bot_token" text NOT NULL, + "scopes" text DEFAULT '' NOT NULL, + "status" text NOT NULL, + "last_error" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "slack_messages" ( + "run_id" text NOT NULL, + "tool_call_id" text NOT NULL, + "user_id" text NOT NULL, + "channel" text NOT NULL, + "ts" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "slack_messages_run_id_tool_call_id_user_id_pk" PRIMARY KEY("run_id","tool_call_id","user_id") +); +--> statement-breakpoint +ALTER TABLE "slack_accounts" ADD CONSTRAINT "slack_accounts_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "slack_messages" ADD CONSTRAINT "slack_messages_run_id_runs_id_fk" FOREIGN KEY ("run_id") REFERENCES "public"."runs"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "slack_messages" ADD CONSTRAINT "slack_messages_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "slack_accounts_team_user_idx" ON "slack_accounts" USING btree ("team_id","slack_user_id"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0006_snapshot.json b/packages/db/drizzle/meta/0006_snapshot.json new file mode 100644 index 0000000..28e0090 --- /dev/null +++ b/packages/db/drizzle/meta/0006_snapshot.json @@ -0,0 +1,2239 @@ +{ + "id": "06a786bd-a015-465c-8564-465bf2238032", + "prevId": "a1782b93-d749-4af8-8532-db47b083aa61", + "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.slack_accounts": { + "name": "slack_accounts", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team_name": { + "name": "team_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_user_id": { + "name": "slack_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bot_user_id": { + "name": "bot_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "bot_token": { + "name": "bot_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "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": { + "slack_accounts_team_user_idx": { + "name": "slack_accounts_team_user_idx", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "slack_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_accounts_user_id_user_id_fk": { + "name": "slack_accounts_user_id_user_id_fk", + "tableFrom": "slack_accounts", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_messages": { + "name": "slack_messages", + "schema": "", + "columns": { + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_call_id": { + "name": "tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ts": { + "name": "ts", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "slack_messages_run_id_runs_id_fk": { + "name": "slack_messages_run_id_runs_id_fk", + "tableFrom": "slack_messages", + "tableTo": "runs", + "columnsFrom": [ + "run_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_messages_user_id_user_id_fk": { + "name": "slack_messages_user_id_user_id_fk", + "tableFrom": "slack_messages", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "slack_messages_run_id_tool_call_id_user_id_pk": { + "name": "slack_messages_run_id_tool_call_id_user_id_pk", + "columns": [ + "run_id", + "tool_call_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "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 + }, + "decided_via": { + "name": "decided_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notified_at": { + "name": "notified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execute_after": { + "name": "execute_after", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "full_output": { + "name": "full_output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_calls_user_decided_idx": { + "name": "tool_calls_user_decided_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "decided_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "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": "'{}'" + }, + "undo_seconds": { + "name": "undo_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_settings_user_id_user_id_fk": { + "name": "user_settings_user_id_user_id_fk", + "tableFrom": "user_settings", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index 207d5be..16368ab 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1792891462021, "tag": "0005_approval_channels", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1792891725994, + "tag": "0006_slack", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index a7f1252..fce2f5f 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -344,6 +344,51 @@ export const integrations = pgTable( (t) => [uniqueIndex("integrations_user_provider_idx").on(t.userId, t.provider)], ); +/** + * Slack, connected per user to approve from a DM. The bot token is sealed; the Slack user + * who installed it (`slackUserId` in `teamId`) is the only Slack identity that may act for + * this Synapse user. + */ +export const slackAccounts = pgTable( + "slack_accounts", + { + userId: text("user_id") + .primaryKey() + .references(() => user.id, { onDelete: "cascade" }), + teamId: text("team_id").notNull(), + teamName: text("team_name").notNull(), + slackUserId: text("slack_user_id").notNull(), + botUserId: text("bot_user_id"), + /** Sealed bot token (xoxb-…). */ + botToken: text("bot_token").notNull(), + scopes: text("scopes").notNull().default(""), + status: text("status").$type<"active" | "error">().notNull(), + lastError: text("last_error"), + createdAt: createdAt(), + updatedAt: updatedAt(), + }, + (t) => [uniqueIndex("slack_accounts_team_user_idx").on(t.teamId, t.slackUserId)], +); + +/** The Slack DM sent about an approval, per recipient, so it can be updated once decided. */ +export const slackMessages = pgTable( + "slack_messages", + { + runId: text("run_id") + .notNull() + .references(() => runs.id, { onDelete: "cascade" }), + toolCallId: text("tool_call_id").notNull(), + /** The Synapse user it was sent to. */ + userId: text("user_id") + .notNull() + .references(() => user.id, { onDelete: "cascade" }), + channel: text("channel").notNull(), + ts: text("ts").notNull(), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.runId, t.toolCallId, t.userId] })], +); + // ── Knowledge & memory ───────────────────────────────────────────────────── export const memories = pgTable( From 637a72ef56339fe67c9411044f957b5e40e2587a Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:08:49 +0530 Subject: [PATCH 04/10] Approve from your phone: Web Push, installable app, email alerts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PWA: app/manifest.ts, icons rasterized from the brand glyph (paper #F4F1EA), apple-icon, appleWebApp metadata; public/sw.js registered in production builds (or NEXT_PUBLIC_ENABLE_SW=true), no caching - Web Push (web-push 3.6.7, VAPID): push_subscriptions table with sealed keys; /api/push config, subscriptions (list/upsert/delete) and test; endpoints limited to known push services; 404/410 forgets the device. Dev generates VAPID keys once into .data/vapid.json, production never does - PushChannel: one notification per approval (tag = toolCallId, Approve/Deny actions), one summary per person when several arrive at once, delivered to every recipient's devices; skips anything already decided; no lock-screen Approve for sends/deletes when the undo window is off - Service worker Approve/Deny posts the decision with via: "push" (the decision route now accepts via: web|push), shows "Approved · sending in Ns" with Undo, and opens the task if anything fails - Email alerts (nodemailer 10.1.0) when SMTP_URL and EMAIL_FROM are set, opt-in via user_settings.email_alerts; preview, why, task link, no approve links - Settings → Notifications: device permission flow with iOS Home Screen guidance, device list, send a test, email toggle; graceful unsupported/denied/unconfigured - docs/notifications.md, docs/api.md, .env.example; tests with a fake push sender and fake SMTP transport --- .env.example | 14 + apps/server/package.json | 13 +- apps/server/src/app.ts | 9 +- apps/server/src/config.ts | 58 + apps/server/src/http.ts | 2 +- apps/server/src/notify.test.ts | 431 ++++ apps/server/src/notify/email.ts | 123 + apps/server/src/notify/push.ts | 267 ++ apps/server/src/routes/account.ts | 3 + apps/server/src/routes/push.ts | 105 + apps/server/src/routes/runs.ts | 10 +- apps/server/src/services.ts | 35 +- apps/web/app/(app)/settings/notifications.tsx | 301 +++ apps/web/app/(app)/settings/page.tsx | 16 +- apps/web/app/apple-icon.png | Bin 0 -> 1486 bytes apps/web/app/layout.tsx | 4 + apps/web/app/manifest.ts | 27 + apps/web/components/service-worker.tsx | 19 + apps/web/lib/api.ts | 28 +- apps/web/lib/push.ts | 102 + apps/web/next.config.ts | 13 + apps/web/public/icons/badge-96.png | Bin 0 -> 650 bytes apps/web/public/icons/icon-192.png | Bin 0 -> 2123 bytes apps/web/public/icons/icon-512.png | Bin 0 -> 5966 bytes apps/web/public/icons/icon-maskable-512.png | Bin 0 -> 4107 bytes apps/web/public/sw.js | 159 ++ bun.lock | 39 + docs/api.md | 27 +- docs/notifications.md | 110 + packages/db/drizzle/0006_push.sql | 15 + packages/db/drizzle/meta/0006_snapshot.json | 2142 +++++++++++++++++ packages/db/drizzle/meta/_journal.json | 7 + packages/db/src/schema.ts | 26 + 33 files changed, 4089 insertions(+), 16 deletions(-) create mode 100644 apps/server/src/notify.test.ts create mode 100644 apps/server/src/notify/email.ts create mode 100644 apps/server/src/notify/push.ts create mode 100644 apps/server/src/routes/push.ts create mode 100644 apps/web/app/(app)/settings/notifications.tsx create mode 100644 apps/web/app/apple-icon.png create mode 100644 apps/web/app/manifest.ts create mode 100644 apps/web/components/service-worker.tsx create mode 100644 apps/web/lib/push.ts create mode 100644 apps/web/public/icons/badge-96.png create mode 100644 apps/web/public/icons/icon-192.png create mode 100644 apps/web/public/icons/icon-512.png create mode 100644 apps/web/public/icons/icon-maskable-512.png create mode 100644 apps/web/public/sw.js create mode 100644 docs/notifications.md create mode 100644 packages/db/drizzle/0006_push.sql create mode 100644 packages/db/drizzle/meta/0006_snapshot.json diff --git a/.env.example b/.env.example index 634b76c..13ed297 100644 --- a/.env.example +++ b/.env.example @@ -56,5 +56,19 @@ GOOGLE_CLIENT_SECRET= # How often email triggers check for new mail, in seconds (min 30). # TRIGGER_POLL_SECONDS=120 +# ── Notifications (optional) ───────────────────────────────────────────────── +# Web Push for approvals on phones and desktops. Setup: docs/notifications.md +# Generate a pair: bunx web-push generate-vapid-keys +# Unset in development: a pair is generated once into .data/vapid.json. Production: off until set. +# VAPID_PUBLIC_KEY= +# VAPID_PRIVATE_KEY= +# Contact for push services: mailto:you@example.com (or an https URL). Required in production. +# VAPID_SUBJECT=mailto:you@example.com +# Email alerts (each user opts in under Settings → Notifications). +# SMTP_URL=smtps://user:password@smtp.example.com:465 +# EMAIL_FROM=Synapse +# Web app: register the service worker under `next dev` too (it always is in production builds). +# NEXT_PUBLIC_ENABLE_SW=true + # Allow MCP servers / web_fetch on private networks (self-hosted MCP on your LAN). SYNAPSE_ALLOW_PRIVATE_NETWORK=false diff --git a/apps/server/package.json b/apps/server/package.json index ca238a6..0c3f3f5 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -9,13 +9,18 @@ "seed": "bun src/seed.ts" }, "dependencies": { - "better-auth": "1.7.6", - "hono": "4.13.9", - "zod": "4.6.5", "@synapse/core": "workspace:*", "@synapse/db": "workspace:*", "@synapse/tools": "workspace:*", "ai": "7.0.116", - "drizzle-orm": "0.45.3" + "better-auth": "1.7.6", + "drizzle-orm": "0.45.3", + "hono": "4.13.9", + "nodemailer": "10.1.0", + "web-push": "3.6.7", + "zod": "4.6.5" + }, + "devDependencies": { + "@types/web-push": "3.6.4" } } diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 725ee2c..8dbc761 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -7,6 +7,7 @@ import { chats } from "./routes/chats"; import { clientMetadataDocument, connections, oauthCallback } from "./routes/connections"; import { googleCallback, integrations } from "./routes/integrations"; import { models } from "./routes/models"; +import { push } from "./routes/push"; import { approvals, runs } from "./routes/runs"; import { suggestions } from "./routes/suggestions"; import type { Services } from "./services"; @@ -48,7 +49,12 @@ export function createApp(services: Services) { google: Boolean(config.GOOGLE_CLIENT_ID), }, integrations: { google: Boolean(config.google) }, - features: { webSearch: Boolean(config.webSearch), embeddings: Boolean(config.embedding) }, + features: { + webSearch: Boolean(config.webSearch), + embeddings: Boolean(config.embedding), + push: Boolean(services.push), + emailAlerts: Boolean(services.email), + }, models: config.SYNAPSE_MODELS, }), ); @@ -74,6 +80,7 @@ export function createApp(services: Services) { api.route("/usage", usage); api.route("/models", models); api.route("/automations", automations); + api.route("/push", push); api.get("/me", (c) => c.json({ user: c.var.user })); app.route("/api", api); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 131effa..6d33e3b 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; import { parseModelRef } from "@synapse/core"; import type { GoogleAppConfig, WebSearchConfig } from "@synapse/tools"; +import webpush from "web-push"; import { z } from "zod"; const csv = z.string().transform((s) => @@ -11,6 +12,10 @@ const csv = z.string().transform((s) => .filter(Boolean), ); +/** An empty value (`KEY=` in a .env file) counts as unset. */ +const optional = (schema: T) => + z.preprocess((v) => (v === "" ? undefined : v), schema.optional()); + const Env = z.object({ NODE_ENV: z.enum(["development", "production", "test"]).default("development"), PORT: z.coerce.number().default(8787), @@ -59,6 +64,18 @@ const Env = z.object({ GOOGLE_CLIENT_SECRET: z.string().optional(), /** How often email triggers check for new mail. */ TRIGGER_POLL_SECONDS: z.coerce.number().int().min(30).default(120), + + /** Web Push (VAPID). Generate with `bunx web-push generate-vapid-keys`; dev makes its own. */ + VAPID_PUBLIC_KEY: optional(z.string().min(40)), + VAPID_PRIVATE_KEY: optional(z.string().min(20)), + /** Who push services can contact about this sender: "mailto:you@example.com" or an https URL. */ + VAPID_SUBJECT: optional( + z.string().regex(/^(mailto:.+@.+|https:\/\/.+)$/, "must be mailto:… or https://…"), + ), + /** Email alerts over SMTP, e.g. smtps://user:pass@smtp.example.com:465. */ + SMTP_URL: optional(z.string().url()), + /** Sender for email alerts, e.g. "Synapse ". */ + EMAIL_FROM: optional(z.string().min(3)), }); export type Config = ReturnType; @@ -97,6 +114,11 @@ export function loadConfig(env: Record = process.env return { ...parsed, google, + push: pushConfig(parsed), + email: + parsed.SMTP_URL && parsed.EMAIL_FROM + ? { smtpUrl: parsed.SMTP_URL, from: parsed.EMAIL_FROM } + : null, SYNAPSE_MODELS: models, SYNAPSE_SUMMARY_MODEL: summaryModel, secret, @@ -150,3 +172,39 @@ function devSecret(parsed: z.infer): string { writeFileSync(path, secret, { mode: 0o600 }); return secret; } + +export interface PushConfig { + publicKey: string; + privateKey: string; + subject: string; +} + +/** + * VAPID keys from the environment. In development, unset keys are generated once and kept + * in .data/vapid.json (like the dev secret) so subscriptions survive restarts; production + * and tests never generate them, so push stays off until configured. + */ +function pushConfig(parsed: z.infer): PushConfig | null { + const { VAPID_PUBLIC_KEY: publicKey, VAPID_PRIVATE_KEY: privateKey } = parsed; + if (Boolean(publicKey) !== Boolean(privateKey)) + throw new Error("Set both VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY, or neither"); + const fallbackSubject = parsed.PUBLIC_URL.startsWith("https://") + ? parsed.PUBLIC_URL + : "mailto:synapse@localhost.localdomain"; + if (publicKey && privateKey) { + if (parsed.NODE_ENV === "production" && !parsed.VAPID_SUBJECT) + throw new Error("VAPID_SUBJECT (mailto:you@example.com) is required with VAPID keys"); + return { publicKey, privateKey, subject: parsed.VAPID_SUBJECT ?? fallbackSubject }; + } + if (parsed.NODE_ENV !== "development") return null; + return { ...devVapidKeys(), subject: parsed.VAPID_SUBJECT ?? fallbackSubject }; +} + +function devVapidKeys(): { publicKey: string; privateKey: string } { + const path = ".data/vapid.json"; + if (existsSync(path)) return JSON.parse(readFileSync(path, "utf8")); + mkdirSync(dirname(path), { recursive: true }); + const keys = webpush.generateVAPIDKeys(); + writeFileSync(path, JSON.stringify(keys), { mode: 0o600 }); + return keys; +} diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 9997599..64f6e21 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -14,7 +14,7 @@ export interface AppEnv { } export function apiError( - status: 400 | 401 | 403 | 404 | 409 | 413 | 422 | 429 | 500, + status: 400 | 401 | 403 | 404 | 409 | 413 | 422 | 429 | 500 | 503, code: string, message: string, ): never { diff --git a/apps/server/src/notify.test.ts b/apps/server/src/notify.test.ts new file mode 100644 index 0000000..f7b99e7 --- /dev/null +++ b/apps/server/src/notify.test.ts @@ -0,0 +1,431 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { type ScriptedStep, scriptedModel } from "@synapse/core/testing"; +import { schema } from "@synapse/db"; +import { eq } from "drizzle-orm"; +import webpush from "web-push"; +import { createApp } from "./app"; +import { loadConfig } from "./config"; +import type { MailMessage } from "./notify/email"; +import type { PushMessage, PushSender } from "./notify/push"; +import { createServices } from "./services"; +import { Worker } from "./worker"; + +const ORIGIN = "http://localhost:3000"; +const vapid = webpush.generateVAPIDKeys(); + +interface Sent { + endpoint: string; + keys: { p256dh: string; auth: string }; + message: PushMessage; + ttlSeconds: number; +} + +/** A server with fake delivery: pushes and emails are recorded, never sent. */ +async function harness(env: Record) { + const pushes: Sent[] = []; + const mails: MailMessage[] = []; + /** Status the fake push service answers with, per endpoint (default 201). */ + const status = new Map(); + const sender: PushSender = async (target, payload, options) => { + pushes.push({ + endpoint: target.endpoint, + keys: target.keys, + message: JSON.parse(payload), + ttlSeconds: options.ttlSeconds, + }); + return { statusCode: status.get(target.endpoint) ?? 201 }; + }; + const services = await createServices( + loadConfig({ + NODE_ENV: "test", + DATABASE_URL: "pglite://memory", + SYNAPSE_SECRET: "t".repeat(40), + PUBLIC_URL: ORIGIN, + ...env, + }), + { + pushSender: sender, + mailTransport: { + sendMail: async (m) => { + mails.push(m); + }, + }, + }, + ); + const app = createApp(services); + let model = scriptedModel([]); + const worker = new Worker(services, () => [model]); + + async function signUp(email: string) { + const res = await app.request("/api/auth/sign-up/email", { + method: "POST", + headers: { "content-type": "application/json", origin: ORIGIN }, + body: JSON.stringify({ email, password: "correct horse battery", name: email.split("@")[0] }), + }); + expect(res.status).toBe(200); + const cookie = res.headers + .getSetCookie() + .map((c) => c.split(";")[0]) + .join("; "); + const call = async (path: string, init: { method?: string; json?: unknown } = {}) => { + const r = await app.request(path, { + method: init.method ?? "GET", + headers: { + cookie, + origin: ORIGIN, + "user-agent": + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1", + ...(init.json !== undefined ? { "content-type": "application/json" } : {}), + }, + ...(init.json !== undefined ? { body: JSON.stringify(init.json) } : {}), + }); + const text = await r.text(); + // biome-ignore lint/suspicious/noExplicitAny: test responses are loosely typed JSON + return { status: r.status, json: text ? (JSON.parse(text) as any) : null }; + }; + // Every memory_save asks, so a task stops for approval. + await call("/api/policy", { + method: "PUT", + json: { + defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" }, + rules: [{ tool: "memory_save", decision: "ask" }], + }, + }); + return call; + } + + /** Starts a task whose first step proposes these calls, and drives it to the approval. */ + async function asks(me: Awaited>, step: ScriptedStep) { + model = scriptedModel([step, { text: "Done." }]); + const { json } = await me("/api/chats", { method: "POST", json: { content: "Remember" } }); + await worker.processNow(json.runId); + const [run] = await services.database.db + .select() + .from(schema.runs) + .where(eq(schema.runs.id, json.runId)); + expect(run!.status).toBe("waiting"); + return { runId: json.runId as string, chatId: json.chat.id as string }; + } + + return { services, pushes, mails, status, signUp, asks }; +} + +let n = 0; +/** A browser PushSubscription.toJSON() on a real push service host. */ +function device(host = "fcm.googleapis.com") { + n++; + return { + endpoint: `https://${host}/fcm/send/device-${n}-${crypto.randomUUID()}`, + keys: { + p256dh: webpush.generateVAPIDKeys().publicKey, + auth: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64url"), + }, + }; +} + +const save = (id: string, note = "likes tea"): ScriptedStep => ({ + toolCalls: [{ name: "memory_save", input: { note }, id }], +}); + +describe("configured: push and email", () => { + let h: Awaited>; + beforeAll(async () => { + h = await harness({ + VAPID_PUBLIC_KEY: vapid.publicKey, + VAPID_PRIVATE_KEY: vapid.privateKey, + VAPID_SUBJECT: "mailto:ops@example.com", + SMTP_URL: "smtp://mail.example.com:2525", + EMAIL_FROM: "Synapse ", + }); + }); + afterAll(() => h.services.close()); + + test("config exposes the public key; the app reports both channels", async () => { + const me = await h.signUp("config@example.com"); + expect((await me("/api/push/config")).json).toEqual({ + enabled: true, + publicKey: vapid.publicKey, + }); + expect((await me("/api/config")).json.features).toMatchObject({ + push: true, + emailAlerts: true, + }); + expect(h.services.notifier.names).toEqual(["push", "email"]); + }); + + test("subscriptions: create (upsert), list, keys sealed at rest, remove", async () => { + const me = await h.signUp("subs@example.com"); + const phone = device(); + const created = await me("/api/push/subscriptions", { method: "POST", json: phone }); + expect(created.status).toBe(201); + expect(created.json.subscription).toMatchObject({ + endpoint: phone.endpoint, + label: "Safari on iPhone", + lastUsedAt: null, + }); + // Same device again: still one row. + const again = await me("/api/push/subscriptions", { + method: "POST", + json: { ...phone, label: "My phone" }, + }); + expect(again.json.subscription.id).toBe(created.json.subscription.id); + const list = await me("/api/push/subscriptions"); + expect(list.json.subscriptions).toHaveLength(1); + expect(list.json.subscriptions[0].label).toBe("My phone"); + expect(JSON.stringify(list.json)).not.toContain(phone.keys.auth); + + const [row] = await h.services.database.db + .select() + .from(schema.pushSubscriptions) + .where(eq(schema.pushSubscriptions.endpoint, phone.endpoint)); + expect(row!.p256dh).not.toBe(phone.keys.p256dh); + expect(await h.services.box.open(row!.auth)).toBe(phone.keys.auth); + + // Someone else can't remove it. + const other = await h.signUp("subs-other@example.com"); + await other(`/api/push/subscriptions/${row!.id}`, { method: "DELETE" }); + expect((await me("/api/push/subscriptions")).json.subscriptions).toHaveLength(1); + expect((await me(`/api/push/subscriptions/${row!.id}`, { method: "DELETE" })).status).toBe(204); + expect((await me("/api/push/subscriptions")).json.subscriptions).toEqual([]); + }); + + test("only real push services are accepted as endpoints", async () => { + const me = await h.signUp("ssrf@example.com"); + for (const endpoint of [ + "http://fcm.googleapis.com/fcm/send/x", + "https://169.254.169.254/latest/meta-data", + "https://localhost:8787/api/health", + "https://fcm.googleapis.com.evil.test/x", + "https://fcm.googleapis.com:8443/x", + ]) { + const res = await me("/api/push/subscriptions", { + method: "POST", + json: { ...device(), endpoint }, + }); + expect(res.status).toBe(422); + } + for (const host of ["web.push.apple.com", "updates.push.services.mozilla.com"]) { + const res = await me("/api/push/subscriptions", { method: "POST", json: device(host) }); + expect(res.status).toBe(201); + } + }); + + test("a run asks → one push to each of the recipient's devices; others untouched", async () => { + const me = await h.signUp("ada@example.com"); + const other = await h.signUp("bob@example.com"); + const phone = device(); + const laptop = device("updates.push.services.mozilla.com"); + const bobs = device(); + await me("/api/push/subscriptions", { method: "POST", json: phone }); + await me("/api/push/subscriptions", { method: "POST", json: laptop }); + await other("/api/push/subscriptions", { method: "POST", json: bobs }); + + h.pushes.length = 0; + const { runId, chatId } = await h.asks(me, save("p1")); + expect(h.pushes.map((p) => p.endpoint).sort()).toEqual( + [laptop.endpoint, phone.endpoint].sort(), + ); + const sent = h.pushes.find((p) => p.endpoint === phone.endpoint)!; + // Keys were unsealed for encryption. + expect(sent.keys).toEqual(phone.keys); + expect(sent.ttlSeconds).toBeGreaterThan(0); + expect(sent.message).toEqual({ + title: "Synapse needs your OK", + body: "Remember: likes tea", + tag: "p1", + data: { url: `${ORIGIN}/t/${chatId}`, runId, toolCallId: "p1", effect: "write" }, + actions: [ + { action: "approve", title: "Approve" }, + { action: "deny", title: "Deny" }, + ], + }); + expect(h.pushes.some((p) => p.endpoint === bobs.endpoint)).toBe(false); + + const subs = (await me("/api/push/subscriptions")).json.subscriptions; + expect(subs.every((s: { lastUsedAt: string | null }) => s.lastUsedAt !== null)).toBe(true); + const bobSubs = (await other("/api/push/subscriptions")).json.subscriptions; + expect(bobSubs).toHaveLength(1); + expect(bobSubs[0].lastUsedAt).toBeNull(); + + // Announced once: another pass sends nothing. + await h.services.notifier.announce(runId); + expect(h.pushes).toHaveLength(2); + }); + + test("several approvals at once → one summary per device", async () => { + const me = await h.signUp("summary@example.com"); + const phone = device(); + await me("/api/push/subscriptions", { method: "POST", json: phone }); + h.pushes.length = 0; + const { chatId } = await h.asks(me, { + toolCalls: [ + { name: "memory_save", input: { note: "a" }, id: "s1" }, + { name: "memory_save", input: { note: "b" }, id: "s2" }, + ], + }); + expect(h.pushes).toHaveLength(1); + expect(h.pushes[0]!.message).toMatchObject({ + title: "Synapse needs your OK on 2 actions", + data: { url: `${ORIGIN}/t/${chatId}` }, + }); + expect(h.pushes[0]!.message.actions).toBeUndefined(); + }); + + test("a push service answering 410 or 404 forgets that device only", async () => { + const me = await h.signUp("gone@example.com"); + const gone = device(); + const missing = device(); + const fine = device(); + for (const d of [gone, missing, fine]) + await me("/api/push/subscriptions", { method: "POST", json: d }); + h.status.set(gone.endpoint, 410); + h.status.set(missing.endpoint, 404); + const test = await me("/api/push/test", { method: "POST", json: {} }); + expect(test.json).toEqual({ sent: 1, removed: 2 }); + const left = (await me("/api/push/subscriptions")).json.subscriptions; + expect(left.map((s: { endpoint: string }) => s.endpoint)).toEqual([fine.endpoint]); + + // A 5xx is logged, not a reason to forget the device. + h.status.set(fine.endpoint, 503); + expect((await me("/api/push/test", { method: "POST", json: {} })).json).toEqual({ + sent: 0, + removed: 0, + }); + expect((await me("/api/push/subscriptions")).json.subscriptions).toHaveLength(1); + }); + + test("approving from a notification is recorded as via push; other sources are refused", async () => { + const me = await h.signUp("lockscreen@example.com"); + const { runId } = await h.asks(me, save("v1")); + const bad = await me(`/api/runs/${runId}/tool-calls/v1/decision`, { + method: "POST", + json: { approved: true, via: "slack" }, + }); + expect(bad.status).toBe(422); + const ok = await me(`/api/runs/${runId}/tool-calls/v1/decision`, { + method: "POST", + json: { approved: true, via: "push" }, + }); + expect(ok.status).toBe(200); + const [row] = await h.services.database.db + .select({ via: schema.toolCalls.decidedVia, status: schema.toolCalls.status }) + .from(schema.toolCalls) + .where(eq(schema.toolCalls.id, "v1")); + expect(row).toEqual({ via: "push", status: "approved" }); + }); + + test("nothing is pushed for an approval already decided", async () => { + const me = await h.signUp("decided@example.com"); + await me("/api/push/subscriptions", { method: "POST", json: device() }); + const { runId } = await h.asks(me, save("d1")); + await me(`/api/runs/${runId}/tool-calls/d1/decision`, { + method: "POST", + json: { approved: false }, + }); + h.pushes.length = 0; + const [userRow] = await h.services.database.db + .select({ id: schema.user.id }) + .from(schema.user) + .where(eq(schema.user.email, "decided@example.com")); + await h.services.push!.notify([ + { + userId: userRow!.id, + recipients: [userRow!.id], + runId, + chatId: "c", + chatTitle: null, + toolCallId: "d1", + name: "memory_save", + effect: "write", + preview: null, + input: {}, + reason: null, + tainted: false, + createdAt: new Date(), + url: `${ORIGIN}/t/c`, + }, + ]); + expect(h.pushes).toEqual([]); + }); + + test("email alerts go out only when the person turned them on, with no approve link", async () => { + const me = await h.signUp("mail@example.com"); + expect((await me("/api/settings")).json.emailAlerts).toBe(false); + h.mails.length = 0; + await h.asks(me, save("e0")); + expect(h.mails).toEqual([]); + + const on = await me("/api/settings", { method: "PUT", json: { emailAlerts: true } }); + expect(on.json.emailAlerts).toBe(true); + const { chatId } = await h.asks(me, save("e1", "Ada's birthday is in May")); + expect(h.mails).toHaveLength(1); + const mail = h.mails[0]!; + expect(mail.to).toBe("mail@example.com"); + expect(mail.from).toBe("Synapse "); + expect(mail.subject).toStartWith("Synapse needs your OK"); + expect(mail.text).toContain(`${ORIGIN}/t/${chatId}`); + expect(mail.text).toContain("Why it's asking:"); + // Only the task link: nothing a mail scanner could "click" to approve. + const links = [...mail.html.matchAll(/href="([^"]+)"/g)].map((m) => m[1]); + expect(links).toEqual([`${ORIGIN}/t/${chatId}`]); + for (const body of [mail.text, mail.html]) { + expect(body).not.toContain("/decision"); + expect(body).not.toContain("approved="); + expect(body).not.toMatch(/\/api\//); + } + expect(mail.html).not.toContain("birthday"); + }); +}); + +describe("not configured", () => { + let h: Awaited>; + beforeAll(async () => { + h = await harness({}); + }); + afterAll(() => h.services.close()); + + test("no channels; push routes explain; nothing is sent", async () => { + expect(h.services.notifier.names).toEqual([]); + const me = await h.signUp("plain@example.com"); + expect((await me("/api/push/config")).json).toEqual({ enabled: false, publicKey: null }); + expect((await me("/api/config")).json.features).toMatchObject({ + push: false, + emailAlerts: false, + }); + const sub = await me("/api/push/subscriptions", { method: "POST", json: device() }); + expect(sub.status).toBe(503); + expect(sub.json.error.message).toContain("VAPID_PUBLIC_KEY"); + expect((await me("/api/push/test", { method: "POST", json: {} })).status).toBe(503); + + await me("/api/settings", { method: "PUT", json: { emailAlerts: true } }); + await h.asks(me, save("q1")); + expect(h.pushes).toEqual([]); + expect(h.mails).toEqual([]); + }); +}); + +describe("config", () => { + test("VAPID keys come in pairs; production needs a subject; tests never generate keys", () => { + const base = { NODE_ENV: "test", SYNAPSE_SECRET: "x".repeat(32) }; + expect(loadConfig(base).push).toBeNull(); + expect(() => loadConfig({ ...base, VAPID_PUBLIC_KEY: vapid.publicKey })).toThrow(); + expect(() => + loadConfig({ + ...base, + NODE_ENV: "production", + VAPID_PUBLIC_KEY: vapid.publicKey, + VAPID_PRIVATE_KEY: vapid.privateKey, + }), + ).toThrow("VAPID_SUBJECT"); + expect(() => loadConfig({ ...base, VAPID_SUBJECT: "ops@example.com" })).toThrow(); + expect( + loadConfig({ + ...base, + VAPID_PUBLIC_KEY: vapid.publicKey, + VAPID_PRIVATE_KEY: vapid.privateKey, + VAPID_SUBJECT: "mailto:ops@example.com", + }).push, + ).toEqual({ ...vapid, subject: "mailto:ops@example.com" }); + expect(loadConfig({ ...base, SMTP_URL: "smtp://x.test" }).email).toBeNull(); + }); +}); diff --git a/apps/server/src/notify/email.ts b/apps/server/src/notify/email.ts new file mode 100644 index 0000000..4f10a17 --- /dev/null +++ b/apps/server/src/notify/email.ts @@ -0,0 +1,123 @@ +import { schema } from "@synapse/db"; +import { and, eq, inArray } from "drizzle-orm"; +import nodemailer from "nodemailer"; +import { log } from "../log"; +import type { Services } from "../services"; +import type { NotificationChannel, PendingApproval } from "./types"; + +export interface MailMessage { + from: string; + to: string; + subject: string; + text: string; + html: string; +} + +/** Anything that can send a message: nodemailer's SMTP transport, or a fake in tests. */ +export interface MailTransport { + sendMail(message: MailMessage): Promise; +} + +export function smtpTransport(smtpUrl: string): MailTransport { + return nodemailer.createTransport(smtpUrl); +} + +/** + * Email alerts, for people who turned them on in Settings. One email per recipient per + * batch, to their account address. Deliberately no approve/deny links: mail scanners open + * every link in a message, so the only link is to the task, where a person decides. + */ +export class EmailChannel implements NotificationChannel { + readonly name = "email"; + + constructor( + private readonly services: () => Services, + private readonly from: string, + private readonly transport: MailTransport, + ) {} + + async notify(approvals: PendingApproval[]): Promise { + const recipients = [...new Set(approvals.flatMap((a) => a.recipients))]; + if (recipients.length === 0) return; + const people = await this.services() + .database.db.select({ id: schema.user.id, email: schema.user.email, name: schema.user.name }) + .from(schema.user) + .innerJoin(schema.userSettings, eq(schema.userSettings.userId, schema.user.id)) + .where(and(inArray(schema.user.id, recipients), eq(schema.userSettings.emailAlerts, true))); + await Promise.all( + people.map(async (person) => { + const items = approvals.filter((a) => a.recipients.includes(person.id)); + try { + await this.transport.sendMail({ from: this.from, to: person.email, ...render(items) }); + } catch (error) { + log.warn("alert email failed", { userId: person.id, error: String(error) }); + } + }), + ); + } +} + +export function render(items: PendingApproval[]): Pick { + const first = items[0]!; + const subject = + items.length === 1 + ? `Synapse needs your OK: ${oneLine(first.preview ?? first.name, 80)}` + : `Synapse needs your OK on ${items.length} actions`; + const intro = + items.length === 1 + ? "A task is waiting for you before it acts." + : `${items.length} actions are waiting for you before they run.`; + const footer = + "Open the task to approve, edit or deny. For your safety this email has no approve " + + "buttons: mail scanners open links, and an approval should always be yours."; + + const text = [ + intro, + "", + ...items.flatMap((a) => [ + `• ${a.preview ?? a.name}`, + ` Action: ${a.name} (${a.effect})`, + ...(a.chatTitle ? [` Task: ${a.chatTitle}`] : []), + ` Why it's asking: ${why(a)}`, + ` Open: ${a.url}`, + "", + ]), + footer, + ].join("\n"); + + const html = ` +
+

${esc(intro)}

+${items + .map( + (a) => `
+

${esc(a.preview ?? a.name)}

+

${esc(a.name)} · ${esc(a.effect)}${a.chatTitle ? ` · ${esc(a.chatTitle)}` : ""}

+

Why it's asking: ${esc(why(a))}

+Open the task +
`, + ) + .join("\n")} +

${esc(footer)}

+
`; + return { subject, text, html }; +} + +function why(a: PendingApproval) { + const reason = a.reason ?? `${a.effect} actions ask first`; + return a.tainted + ? `${reason}. The task had read outside content (an email or web page) by then.` + : reason; +} + +function oneLine(s: string, max: number) { + const flat = s.replace(/\s+/g, " ").trim(); + return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat; +} + +function esc(s: string) { + return s.replace( + /[&<>"']/g, + (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!, + ); +} diff --git a/apps/server/src/notify/push.ts b/apps/server/src/notify/push.ts new file mode 100644 index 0000000..504b6f3 --- /dev/null +++ b/apps/server/src/notify/push.ts @@ -0,0 +1,267 @@ +import type { Effect } from "@synapse/core"; +import { DEFAULT_UNDO_SECONDS, schema } from "@synapse/db"; +import { and, eq, inArray } from "drizzle-orm"; +import webpush from "web-push"; +import type { PushConfig } from "../config"; +import { log } from "../log"; +import type { Services } from "../services"; +import type { NotificationChannel, PendingApproval } from "./types"; + +/** What the service worker receives (public/sw.js reads exactly these fields). */ +export interface PushMessage { + title: string; + body: string; + /** Replaces an earlier notification with the same tag on the device. */ + tag: string; + data: { + url: string; + runId?: string; + toolCallId?: string; + effect?: Effect; + }; + /** Shown as buttons where the platform supports them (not on iOS). */ + actions?: { action: "approve" | "deny"; title: string }[]; +} + +export interface PushTarget { + endpoint: string; + keys: { p256dh: string; auth: string }; +} + +/** Delivers one encrypted message to one device; resolves with the push service's status. */ +export type PushSender = ( + target: PushTarget, + payload: string, + options: { vapid: PushConfig; ttlSeconds: number; urgency: "normal" | "high" }, +) => Promise<{ statusCode: number }>; + +/** The real sender: standards Web Push with VAPID through the `web-push` package. */ +export const webPushSender: PushSender = async ( + target, + payload, + { vapid, ttlSeconds, urgency }, +) => { + try { + const res = await webpush.sendNotification(target, payload, { + vapidDetails: { + subject: vapid.subject, + publicKey: vapid.publicKey, + privateKey: vapid.privateKey, + }, + TTL: ttlSeconds, + urgency, + timeout: 10_000, + }); + return { statusCode: res.statusCode }; + } catch (error) { + if (error instanceof webpush.WebPushError) return { statusCode: error.statusCode }; + throw error; + } +}; + +/** + * Only real push services: the server POSTs to whatever endpoint a browser hands over, so + * anything else (an internal address) is refused. Covers Chrome/Edge/Android (FCM), + * Firefox (Mozilla), Safari and iOS (Apple) and Windows (WNS). + */ +const PUSH_HOSTS = [ + "fcm.googleapis.com", + "android.googleapis.com", + "updates.push.services.mozilla.com", + ".push.services.mozilla.com", + "web.push.apple.com", + ".push.apple.com", + ".notify.windows.com", +]; + +export function isPushEndpoint(endpoint: string): boolean { + let url: URL; + try { + url = new URL(endpoint); + } catch { + return false; + } + if (url.protocol !== "https:" || url.port !== "") return false; + return PUSH_HOSTS.some((h) => + h.startsWith(".") ? url.hostname.endsWith(h) : url.hostname === h, + ); +} + +const PREVIEW_MAX = 180; +/** An approval nobody acts on for a day is stale on the lock screen. */ +const TTL_SECONDS = 24 * 3600; + +/** + * Web Push: one notification per approval, or one summary when several arrive at once for + * one person. Delivered to every device each recipient subscribed; devices the push + * service no longer knows (404/410) are forgotten. + */ +export class PushChannel implements NotificationChannel { + readonly name = "push"; + + constructor( + private readonly services: () => Services, + readonly config: PushConfig, + private readonly send: PushSender = webPushSender, + ) {} + + async notify(approvals: PendingApproval[]): Promise { + const open = await this.stillWaiting(approvals); + if (open.length === 0) return; + const byRecipient = new Map(); + for (const a of open) + for (const r of new Set(a.recipients)) byRecipient.set(r, [...(byRecipient.get(r) ?? []), a]); + const undo = await this.undoSeconds(open.map((a) => a.userId)); + await Promise.all( + [...byRecipient].map(([recipient, items]) => + this.sendToUser(recipient, this.message(items, undo)), + ), + ); + } + + /** Sends one message to all of a user's devices. */ + async sendToUser( + userId: string, + message: PushMessage, + ): Promise<{ sent: number; removed: number }> { + const { database, box } = this.services(); + const subs = await database.db + .select() + .from(schema.pushSubscriptions) + .where(eq(schema.pushSubscriptions.userId, userId)); + const payload = JSON.stringify(message); + let sent = 0; + let removed = 0; + await Promise.all( + subs.map(async (sub) => { + try { + const target = { + endpoint: sub.endpoint, + keys: { p256dh: await box.open(sub.p256dh), auth: await box.open(sub.auth) }, + }; + const { statusCode } = await this.send(target, payload, { + vapid: this.config, + ttlSeconds: TTL_SECONDS, + urgency: "high", + }); + if (statusCode === 404 || statusCode === 410) { + await database.db + .delete(schema.pushSubscriptions) + .where(eq(schema.pushSubscriptions.id, sub.id)); + removed++; + } else if (statusCode >= 200 && statusCode < 300) { + await database.db + .update(schema.pushSubscriptions) + .set({ lastUsedAt: new Date() }) + .where(eq(schema.pushSubscriptions.id, sub.id)); + sent++; + } else { + log.warn("push rejected", { subscription: sub.id, statusCode }); + } + } catch (error) { + log.warn("push failed", { subscription: sub.id, error: String(error) }); + } + }), + ); + return { sent, removed }; + } + + private message(items: PendingApproval[], undo: Map): PushMessage { + const { config } = this.services(); + const first = items[0]!; + if (items.length === 1) { + // A send or delete approved from the lock screen still waits out the undo window; + // with no window, it has to be opened and approved in the app. + const risky = first.effect === "send" || first.effect === "destructive"; + const approvable = !risky || (undo.get(first.userId) ?? DEFAULT_UNDO_SECONDS) > 0; + return { + title: "Synapse needs your OK", + body: clip(first.preview ?? describe(first)), + tag: first.toolCallId, + data: { + url: first.url, + runId: first.runId, + toolCallId: first.toolCallId, + effect: first.effect, + }, + actions: approvable + ? [ + { action: "approve", title: "Approve" }, + { action: "deny", title: "Deny" }, + ] + : [{ action: "deny", title: "Deny" }], + }; + } + const sameTask = items.every((a) => a.chatId === first.chatId); + return { + title: `Synapse needs your OK on ${items.length} actions`, + body: clip(items.map((a) => `• ${a.preview ?? describe(a)}`).join("\n"), 300), + tag: sameTask ? `run:${first.runId}` : "approvals", + data: { url: sameTask ? first.url : `${config.PUBLIC_URL}/approvals` }, + }; + } + + /** Never announce something already decided (e.g. approved on another device). */ + private async stillWaiting(approvals: PendingApproval[]) { + if (approvals.length === 0) return []; + const rows = await this.services() + .database.db.select({ runId: schema.toolCalls.runId, id: schema.toolCalls.id }) + .from(schema.toolCalls) + .where( + and( + inArray(schema.toolCalls.runId, [...new Set(approvals.map((a) => a.runId))]), + eq(schema.toolCalls.status, "awaiting_approval"), + ), + ); + const open = new Set(rows.map((r) => `${r.runId}/${r.id}`)); + return approvals.filter((a) => open.has(`${a.runId}/${a.toolCallId}`)); + } + + private async undoSeconds(userIds: string[]) { + const rows = await this.services() + .database.db.select({ + userId: schema.userSettings.userId, + undoSeconds: schema.userSettings.undoSeconds, + }) + .from(schema.userSettings) + .where(inArray(schema.userSettings.userId, [...new Set(userIds)])); + return new Map(rows.map((r) => [r.userId, r.undoSeconds])); + } +} + +function describe(a: PendingApproval) { + return a.chatTitle ? `${a.name} in “${a.chatTitle}”` : a.name; +} + +function clip(text: string, max = PREVIEW_MAX) { + return text.length > max ? `${text.slice(0, max - 1)}…` : text; +} + +/** "Safari on iPhone" from a User-Agent header, for the device list. */ +export function deviceLabel(userAgent: string | undefined | null): string | null { + if (!userAgent) return null; + const os = /iPhone/.test(userAgent) + ? "iPhone" + : /iPad/.test(userAgent) + ? "iPad" + : /Android/.test(userAgent) + ? "Android" + : /Mac OS X/.test(userAgent) + ? "Mac" + : /Windows/.test(userAgent) + ? "Windows" + : /Linux/.test(userAgent) + ? "Linux" + : null; + const browser = /Edg\//.test(userAgent) + ? "Edge" + : /Firefox\/|FxiOS/.test(userAgent) + ? "Firefox" + : /Chrome\/|CriOS/.test(userAgent) + ? "Chrome" + : /Safari\//.test(userAgent) + ? "Safari" + : null; + if (browser && os) return `${browser} on ${os}`; + return browser ?? os ?? userAgent.slice(0, 60); +} diff --git a/apps/server/src/routes/account.ts b/apps/server/src/routes/account.ts index 929c035..cb314da 100644 --- a/apps/server/src/routes/account.ts +++ b/apps/server/src/routes/account.ts @@ -239,6 +239,7 @@ export const settings = new Hono() .partialRecord(z.enum(PROVIDERS), z.string().min(8).max(400).nullable()) .optional(), undoSeconds: z.number().int().min(0).max(MAX_UNDO_SECONDS).optional(), + emailAlerts: z.boolean().optional(), }), ); const { db } = c.var.services.database; @@ -257,6 +258,7 @@ export const settings = new Hono() ...(input.models ? { models: input.models } : {}), ...(input.budgets ? { budgets: input.budgets } : {}), ...(input.undoSeconds !== undefined ? { undoSeconds: input.undoSeconds } : {}), + ...(input.emailAlerts !== undefined ? { emailAlerts: input.emailAlerts } : {}), providerKeys: keys, }; await db @@ -281,6 +283,7 @@ async function loadSettings(c: { var: AppEnv["Variables"] }) { }, providerKeys: Object.fromEntries(PROVIDERS.map((p) => [p, Boolean(s?.providerKeys?.[p])])), undoSeconds: s?.undoSeconds ?? DEFAULT_UNDO_SECONDS, + emailAlerts: s?.emailAlerts ?? false, }; } diff --git a/apps/server/src/routes/push.ts b/apps/server/src/routes/push.ts new file mode 100644 index 0000000..15e1e68 --- /dev/null +++ b/apps/server/src/routes/push.ts @@ -0,0 +1,105 @@ +import { schema } from "@synapse/db"; +import { and, desc, eq } from "drizzle-orm"; +import { Hono } from "hono"; +import { z } from "zod"; +import { type AppEnv, apiError, body } from "../http"; +import { deviceLabel, isPushEndpoint } from "../notify/push"; + +function enabledPush(c: { var: AppEnv["Variables"] }) { + const { push } = c.var.services; + if (!push) + apiError( + 503, + "push_not_configured", + "Push notifications aren't set up on this server (VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY).", + ); + return push; +} + +const listColumns = { + id: schema.pushSubscriptions.id, + endpoint: schema.pushSubscriptions.endpoint, + label: schema.pushSubscriptions.userAgent, + createdAt: schema.pushSubscriptions.createdAt, + lastUsedAt: schema.pushSubscriptions.lastUsedAt, +}; + +export const push = new Hono() + .get("/config", (c) => { + const { push } = c.var.services; + return c.json({ enabled: Boolean(push), publicKey: push?.config.publicKey ?? null }); + }) + + .get("/subscriptions", async (c) => { + const rows = await c.var.services.database.db + .select(listColumns) + .from(schema.pushSubscriptions) + .where(eq(schema.pushSubscriptions.userId, c.var.user.id)) + .orderBy(desc(schema.pushSubscriptions.createdAt)); + return c.json({ subscriptions: rows }); + }) + + // The browser's PushSubscription.toJSON(). Re-subscribing the same device is an upsert, + // and a device that signs in to another account moves to it. + .post("/subscriptions", async (c) => { + enabledPush(c); + const input = await body( + c, + z.object({ + endpoint: z.string().url().max(2048), + keys: z.object({ + p256dh: z.string().regex(/^[A-Za-z0-9_-]{80,100}=*$/), + auth: z.string().regex(/^[A-Za-z0-9_-]{16,32}=*$/), + }), + label: z.string().trim().min(1).max(80).optional(), + }), + ); + if (!isPushEndpoint(input.endpoint)) + apiError(422, "invalid_endpoint", "That isn't a known browser push service."); + const { database, box } = c.var.services; + const values = { + userId: c.var.user.id, + endpoint: input.endpoint, + p256dh: await box.seal(input.keys.p256dh), + auth: await box.seal(input.keys.auth), + userAgent: input.label ?? deviceLabel(c.req.header("user-agent")), + }; + const [row] = await database.db + .insert(schema.pushSubscriptions) + .values(values) + .onConflictDoUpdate({ + target: schema.pushSubscriptions.endpoint, + set: { + userId: values.userId, + p256dh: values.p256dh, + auth: values.auth, + userAgent: values.userAgent, + }, + }) + .returning(listColumns); + return c.json({ subscription: row }, 201); + }) + + .delete("/subscriptions/:id", async (c) => { + await c.var.services.database.db + .delete(schema.pushSubscriptions) + .where( + and( + eq(schema.pushSubscriptions.id, c.req.param("id")), + eq(schema.pushSubscriptions.userId, c.var.user.id), + ), + ); + return c.body(null, 204); + }) + + .post("/test", async (c) => { + const channel = enabledPush(c); + const { config } = c.var.services; + const result = await channel.sendToUser(c.var.user.id, { + title: "Synapse", + body: "Notifications work. This is where approvals will show up.", + tag: "synapse-test", + data: { url: `${config.PUBLIC_URL}/settings#notifications` }, + }); + return c.json(result); + }); diff --git a/apps/server/src/routes/runs.ts b/apps/server/src/routes/runs.ts index 1a41804..ff16cd8 100644 --- a/apps/server/src/routes/runs.ts +++ b/apps/server/src/routes/runs.ts @@ -140,10 +140,13 @@ export const runs = new Hono() approved: z.boolean(), reason: z.string().max(1000).optional(), input: z.json().optional(), + /** Where it was decided: the app, or a notification's Approve/Deny button. */ + via: z.enum(["web", "push"]).default("web"), }), ); const toolCallId = c.req.param("toolCallId"); - const { executeAfter } = await decided(c, [{ toolCallId, ...input }]); + const { via, ...decision } = input; + const { executeAfter } = await decided(c, [{ toolCallId, ...decision }], via); return c.json({ executeAfter: executeAfter[toolCallId] ?? null }); }) @@ -219,17 +222,18 @@ export const approvals = new Hono().get("/", async (c) => { * Appends an event for a run no worker may be driving (it is parked). Forgets the cached * seq afterwards so a later writer on this instance re-reads the tail. */ -/** Applies decisions made in the web app, turning input problems into API errors. */ +/** Applies decisions made in the web app (or from its notifications), turning input problems into API errors. */ async function decided( c: { var: AppEnv["Variables"]; req: { param(name: "id"): string } }, decisions: Decision[], + via: "web" | "push" = "web", ) { try { return await decide(c.var.services, { userId: c.var.user.id, runId: c.req.param("id"), decisions, - via: "web", + via, }); } catch (error) { if (error instanceof DecisionInputError) apiError(error.status, error.code, error.message); diff --git a/apps/server/src/services.ts b/apps/server/src/services.ts index ca448ff..f47dce2 100644 --- a/apps/server/src/services.ts +++ b/apps/server/src/services.ts @@ -2,7 +2,9 @@ import { createDatabase, type Database, EVENTS_CHANNEL, EventLog, SecretBox } fr import { createEmbedder, type ToolsetConfig } from "@synapse/tools"; import { type Auth, createAuth } from "./auth"; import type { Config } from "./config"; +import { EmailChannel, type MailTransport, smtpTransport } from "./notify/email"; import { Notifier } from "./notify/notifier"; +import { PushChannel, type PushSender, webPushSender } from "./notify/push"; export const RUNS_CHANNEL = "synapse_runs"; @@ -47,12 +49,25 @@ export interface Services { toolset: ToolsetConfig; /** Tells people about approvals through push, Slack and other channels. */ notifier: Notifier; + /** Web Push, when VAPID keys are configured. */ + push: PushChannel | null; + /** Email alerts, when SMTP is configured. */ + email: EmailChannel | null; /** Wakes idle workers (on any instance) when a run becomes runnable. */ wake: (runId: string) => Promise; close: () => Promise; } -export async function createServices(config: Config): Promise { +/** Swappable delivery, so tests never touch the network. */ +export interface ServiceOptions { + pushSender?: PushSender; + mailTransport?: MailTransport; +} + +export async function createServices( + config: Config, + options: ServiceOptions = {}, +): Promise { const database = await createDatabase(config.DATABASE_URL); await database.migrate(); const box = await SecretBox.fromSecret(config.secret); @@ -73,11 +88,29 @@ export async function createServices(config: Config): Promise { google: config.google, }, notifier: new Notifier(() => services), + push: null, + email: null, wake: (runId) => database.notify(RUNS_CHANNEL, runId), close: async () => { await stop(); await database.close(); }, }; + if (config.push) { + services.push = new PushChannel( + () => services, + config.push, + options.pushSender ?? webPushSender, + ); + services.notifier.add(services.push); + } + if (config.email) { + services.email = new EmailChannel( + () => services, + config.email.from, + options.mailTransport ?? smtpTransport(config.email.smtpUrl), + ); + services.notifier.add(services.email); + } return services; } diff --git a/apps/web/app/(app)/settings/notifications.tsx b/apps/web/app/(app)/settings/notifications.tsx new file mode 100644 index 0000000..26769d4 --- /dev/null +++ b/apps/web/app/(app)/settings/notifications.tsx @@ -0,0 +1,301 @@ +"use client"; + +import { BellRing, Smartphone } from "lucide-react"; +import { type ReactNode, useCallback, useEffect, useState } from "react"; +import { useToast } from "@/components/toast"; +import { Pill, Skeleton, Switch } from "@/components/ui"; +import { api, errorMessage, type Settings, type SettingsUpdate } from "@/lib/api"; +import { formatRelative } from "@/lib/format"; +import { + currentSubscription, + isIOS, + PermissionError, + type PushSupport, + pushSupport, + subscribe, +} from "@/lib/push"; +import { useApi } from "@/lib/use-api"; + +type SaveFn = (update: SettingsUpdate, message?: string) => Promise; + +export function Notifications({ + settings, + save, + emailConfigured, +}: { + settings: Settings; + save: SaveFn; + emailConfigured: boolean; +}) { + return ( +
+ + +
+ ); +} + +function PushSection() { + const toast = useToast(); + const config = useApi(() => api.pushConfig()); + const devices = useApi(() => api.pushDevices()); + const [support, setSupport] = useState(null); + const [permission, setPermission] = useState(null); + const [endpoint, setEndpoint] = useState(null); + const [busy, setBusy] = useState(false); + + const refreshDevice = useCallback(async () => { + const s = pushSupport(); + setSupport(s); + if (typeof Notification !== "undefined") setPermission(Notification.permission); + if (s === "supported") + setEndpoint((await currentSubscription().catch(() => null))?.endpoint ?? null); + }, []); + useEffect(() => { + void refreshDevice(); + }, [refreshDevice]); + + const list = devices.data?.subscriptions ?? []; + const thisDevice = endpoint ? list.find((d) => d.endpoint === endpoint) : undefined; + + async function turnOn() { + const key = config.data?.publicKey; + if (!key) return; + setBusy(true); + try { + const sub = await subscribe(key); + await api.addPushDevice(sub.toJSON()); + toast("Notifications are on for this device", "success"); + } catch (err) { + toast(err instanceof PermissionError ? err.message : errorMessage(err), "error"); + } finally { + await refreshDevice(); + await devices.reload(); + setBusy(false); + } + } + + async function remove(id: string, local: boolean) { + setBusy(true); + try { + if (local) await (await currentSubscription())?.unsubscribe(); + await api.removePushDevice(id); + toast(local ? "Notifications are off for this device" : "Device removed", "success"); + } catch (err) { + toast(errorMessage(err), "error"); + } finally { + await refreshDevice(); + await devices.reload(); + setBusy(false); + } + } + + async function test() { + setBusy(true); + try { + const { sent } = await api.testPush(); + toast( + sent === 0 + ? "No device took the test. Turn notifications on first." + : `Sent to ${sent} device${sent === 1 ? "" : "s"}`, + sent === 0 ? "error" : "success", + ); + } catch (err) { + toast(errorMessage(err), "error"); + } finally { + await devices.reload(); + setBusy(false); + } + } + + let deviceState: ReactNode; + if (config.loading && !config.data) deviceState = ; + else if (config.error) deviceState = {errorMessage(config.error)}; + else if (!config.data?.enabled) + deviceState = ( + + Push needs VAPID keys. Generate a pair with{" "} + bunx web-push generate-vapid-keys, then set{" "} + VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY and VAPID_SUBJECT (a + mailto: address) and restart. See docs/notifications.md. + + ); + else if (support === null) deviceState = ; + else if (support === "needs-install") + deviceState = ( + + On iPhone and iPad, notifications only work from the installed app. Tap Share, then{" "} + Add to Home Screen, open Synapse from there and come back + to this page. + + ); + else if (support === "unsupported") + deviceState = ( + + Try Chrome, Edge, Firefox or Safari 16+. + {isIOS() ? " On iPhone, use Safari and add Synapse to your Home Screen." : ""} + + ); + else if (support === "disabled") + deviceState = ( + + The service worker only runs in production builds. To try it with{" "} + next dev, set{" "} + NEXT_PUBLIC_ENABLE_SW=true. + + ); + else if (permission === "denied" && !thisDevice) + deviceState = ( + + This browser was told not to show notifications from Synapse. Allow them in the site + settings (the icon next to the address), then reload this page. + + ); + else + deviceState = ( +
+ +
+

+ {thisDevice ? "On for this device" : "Off for this device"} +

+

+ {thisDevice + ? "Approvals show up here, even when Synapse is closed." + : "Get a notification when a task needs your OK."} +

+
+ {thisDevice ? ( + + ) : ( + + )} +
+ ); + + return ( +
+

Push notifications

+

+ Approve or deny right from the notification. Sends and deletes still wait out your undo + window, so a lock-screen “Approve” can be taken back. +

+ {deviceState} + + {list.length > 0 ? ( +
+
+ Your devices + +
+
    + {list.map((d) => { + const local = d.id === thisDevice?.id; + return ( +
  • + +
    +
    + + {d.label ?? "Unknown device"} + + {local ? This device : null} +
    +

    + Added {formatRelative(d.createdAt)} + {d.lastUsedAt ? ` · last notified ${formatRelative(d.lastUsedAt)}` : ""} +

    +
    + +
  • + ); + })} +
+
+ ) : null} +
+ ); +} + +function EmailAlerts({ + settings, + save, + configured, +}: { + settings: Settings; + save: SaveFn; + configured: boolean; +}) { + const [on, setOn] = useState(settings.emailAlerts); + useEffect(() => setOn(settings.emailAlerts), [settings.emailAlerts]); + return ( +
+

Email alerts

+
+
+

Email me when something needs my OK

+

+ {configured ? ( + "Sent to your account email, with a link to the task. There are no approve buttons in email: mail scanners open links, so you decide in the app." + ) : ( + <> + Not set up on this server: it needs SMTP_URL and EMAIL_FROM. + + )} +

+
+ { + setOn(v); + if (!(await save({ emailAlerts: v }, v ? "Email alerts on" : "Email alerts off"))) + setOn(!v); + }} + /> +
+
+ ); +} + +function Note({ title, children }: { title?: string; children: ReactNode }) { + return ( +
+ {title ?

{title}

: null} + {children} +
+ ); +} + +function Env({ children }: { children: ReactNode }) { + return {children}; +} diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index d3327a1..e72feee 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -3,6 +3,7 @@ import { ArrowDown, ArrowUp, + Bell, Check, Cpu, Monitor, @@ -32,9 +33,10 @@ import { type ThemePref, useTheme } from "@/lib/theme"; import { useApi } from "@/lib/use-api"; import { useWorkspace } from "@/lib/workspace"; import { MAX_CHAIN, ModelPicker, modelFromRef, priceLabel } from "./model-picker"; +import { Notifications } from "./notifications"; import { PolicyEditor } from "./policy-editor"; -type Section = "general" | "models" | "budgets" | "rules" | "appearance"; +type Section = "general" | "notifications" | "models" | "budgets" | "rules" | "appearance"; const SECTIONS: { id: Section; label: string; icon: ReactNode; blurb: string }[] = [ { @@ -43,6 +45,12 @@ const SECTIONS: { id: Section; label: string; icon: ReactNode; blurb: string }[] icon: , blurb: "Who you are and how you like to work.", }, + { + id: "notifications", + label: "Notifications", + icon: , + blurb: "Hear about approvals on your phone, or by email.", + }, { id: "models", label: "Models & keys", @@ -184,6 +192,12 @@ export default function SettingsPage() { ) : section === "general" ? ( + ) : section === "notifications" ? ( + ) : section === "models" ? ( ) : ( diff --git a/apps/web/app/apple-icon.png b/apps/web/app/apple-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..1cf38153254b65e63bae50d21b3f2050dfbbbd18 GIT binary patch literal 1486 zcmb7^X)xP)7{?RxZ>W;CsI#n{(V|$?Q7IL7OGQ%+8iI*dG>%ds)Fy(NTG24wu4Aid z|7uItk*;leI8$vMTSRId6~`8>r2fw;Rz4dGpXXavF2)hy!Mlc4Wzx#lZXkV3EWS? z432Ac^Q^NjL;!~#;C5#PBM{12!O>N=tZz)ROt^JQ7h*Tu`hRe3LtN`Leg!-da zQ#zYWBS%S`$+sqleo^|PxtEhZ%}I))`B`ob9Dl&?(sIT4enBN#c^kOJS3u)!06tYUAp8qv-A(ChM6ES75hBUjinT1E?w?&U19gDGq5Lhe)29!p9wLg-7}@Kz z6(AF)OCC)q)}Em+FV6cKh4uU1+Zes+@(AEx5q#TGm_qE7aZ+Utpxr3G{!r(A=f&j$ z&(PXT9yj>lT4tJ9F{i~hL#AZgjW63FwuyW@>2(;=KuDkFCC7!@IVhvimzK>%GcA^t zI@SA7=a_+HfLmteUu=M>W>w4h0hL=Y!dML_r~PK4g(|hIjghwtEI+A^0xcY>2q`dP z^jRzN2n6S^B;lcGkPQ*Ex(q?UR-~XSHFH={ROOp``?n3^!GWqHu0I0Q*l>X087mF1 zIO%<#X~|DT7sHb_Dt;?==k!l&0z}PpA7&sl&VW3Uy5f4(SdQ2i=Z>-fY9?JaAn9Q{ zgbvM)H&@onTKwlGU=5=T$MsG7=@?!Mr4hP#x$}Z1*cA&st)CumM19Un6W7x8M~+Bq z?%BW^KsA>XsZBS|+&Nw#*~AGsnU=}!TLJ!Idt? zNW>U27T%vOAw!pMYN7mn(u~j|;Ho4L*iUSfOb| z7J4CUzju{SaM&3ny5(J^KYi&o2^#{X^86C-x_lfS8aXwUc^qWZyK%8pmP=l?;$4P@ zXB`;nr$gJ=qOGv@1dW~q^2G;qAq|&V_1js65H^Do-kNwGy}I<06d_1>Q!ljc7>b{a z99wdlp}(0}56K9a$}w8UQ-&8u&Dv0%&m|huCNN%lv4H!SK;}eK*^Wg-b;G8!^8*w@ z4K7Bf*TO8`%(p3nyO(PC*Xxh@g3puzb+$DLtK3liF~*eknK)|L9htB4^f{S6B#-%% zO^TbU*N(w{pGv=#+g@RXa_(ap``31vfay)7^G!Z$iO)*sytJelGwWUnxYE$1)x>9d zP(sP|%zQn*k=4be3HQ+j-Cj0=>a?J}bNK)-fzFmtUR}i-OFboT?eV!=0_y@vU-tXU z2Bpe;Rc}m?Vnac$*WjiJCP=NJK#w@(2qNKe&#swvM3gA{tZtetuC<2lmL}&z2suauy2rf1V&+(pUwaaeZLqXR3+cDlhjT88>x4H3(lB5#ql}i) zPv1yqOU#Z2ypq6&Epa0W2+O4J6Co_Go*sYj9 zK33!*RLqx-rPKxPpKO}AgS)Y)FXH%NNO8@-uBH6+xBwybeai?7H}@uSoI}i!6%K)C zc{A-v7_ChTLR}T~&e4qmt6k%qkW}%|#Wc91sGMFCFaOzb{cM@M9V;c_7&Yp7E?dHk zr+oU5S0`ZVOIfG%df`M>ihRD>bq;ugsdO8g4la~$HeCz9mo1iG^l#)IZn2}1%3)EP zGqb*L0F4zsFH?w#0`r1;T$R@b0B`z2AdLnj8Lhc5+X{ NPIzKHcy19{e*?*Fw6OpH literal 0 HcmV?d00001 diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 020a4a3..e7c2cee 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -3,6 +3,7 @@ import "@fontsource-variable/geist-mono"; import type { Metadata, Viewport } from "next"; import { Instrument_Serif } from "next/font/google"; import type { ReactNode } from "react"; +import { ServiceWorker } from "@/components/service-worker"; import { ToastProvider } from "@/components/toast"; import { THEME_BOOT_SCRIPT } from "@/lib/theme-boot"; import "./globals.css"; @@ -18,6 +19,8 @@ const serif = Instrument_Serif({ export const metadata: Metadata = { title: { default: "Synapse", template: "%s · Synapse" }, description: "An agent workspace: hand off tasks, watch them happen, approve what acts.", + // Installed to the Home Screen (iOS needs this for push notifications). + appleWebApp: { capable: true, title: "Synapse", statusBarStyle: "default" }, }; export const viewport: Viewport = { @@ -36,6 +39,7 @@ export default function RootLayout({ children }: { children: ReactNode }) { {children} + ); diff --git a/apps/web/app/manifest.ts b/apps/web/app/manifest.ts new file mode 100644 index 0000000..060b186 --- /dev/null +++ b/apps/web/app/manifest.ts @@ -0,0 +1,27 @@ +import type { MetadataRoute } from "next"; + +/** Installable app: Home Screen on iOS and Android, an app window on desktop. */ +export default function manifest(): MetadataRoute.Manifest { + return { + id: "/", + name: "Synapse", + short_name: "Synapse", + description: "Hand off tasks, watch them happen, approve what acts.", + start_url: "/", + scope: "/", + display: "standalone", + background_color: "#F4F1EA", + theme_color: "#F4F1EA", + icons: [ + { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" }, + { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" }, + { + src: "/icons/icon-maskable-512.png", + sizes: "512x512", + type: "image/png", + purpose: "maskable", + }, + ], + shortcuts: [{ name: "Approvals", url: "/approvals" }], + }; +} diff --git a/apps/web/components/service-worker.tsx b/apps/web/components/service-worker.tsx new file mode 100644 index 0000000..8e8d5fd --- /dev/null +++ b/apps/web/components/service-worker.tsx @@ -0,0 +1,19 @@ +"use client"; + +import { useEffect } from "react"; +import { registerServiceWorker, SW_ENABLED } from "@/lib/push"; + +/** + * Registers public/sw.js, which shows approval notifications and handles their + * Approve/Deny buttons. Production builds only (or NEXT_PUBLIC_ENABLE_SW=true), so + * development never serves stale code from a worker. It caches nothing. + */ +export function ServiceWorker() { + useEffect(() => { + if (!SW_ENABLED || !("serviceWorker" in navigator)) return; + registerServiceWorker().catch(() => { + // Unsupported context (e.g. plain http on a LAN address): push just stays off. + }); + }, []); + return null; +} diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts index c071c64..696bd6b 100644 --- a/apps/web/lib/api.ts +++ b/apps/web/lib/api.ts @@ -99,7 +99,7 @@ const enc = encodeURIComponent; export interface AppConfig { auth: { emailPassword: boolean; github: boolean; google: boolean; signup?: boolean }; - features: { webSearch: boolean; embeddings: boolean }; + features: { webSearch: boolean; embeddings: boolean; push?: boolean; emailAlerts?: boolean }; models: string[]; } @@ -245,6 +245,8 @@ export interface Settings { providerKeys: Record; /** Seconds an approved send or delete waits, with an Undo, before it runs. 0 is off. */ undoSeconds: number; + /** Email the account address when something needs approval. */ + emailAlerts: boolean; } export interface SettingsUpdate { @@ -253,6 +255,22 @@ export interface SettingsUpdate { budgets?: { perRunUsd: number | null; perDayUsd: number | null }; providerKeys?: Partial>; undoSeconds?: number; + emailAlerts?: boolean; +} + +export interface PushConfig { + enabled: boolean; + /** VAPID public key (base64url), for PushManager.subscribe. */ + publicKey: string | null; +} + +export interface PushDevice { + id: string; + endpoint: string; + /** e.g. "Safari on iPhone". */ + label: string | null; + createdAt: string; + lastUsedAt: string | null; } export interface ModelInfo { @@ -434,4 +452,12 @@ export const api = { models: () => get<{ models: ModelInfo[]; updatedAt: string | null }>("/api/models"), saveSettings: (body: SettingsUpdate) => put("/api/settings", body), usage: (days = 30) => get<{ days: UsageDay[] }>(`/api/usage?days=${days}`), + + pushConfig: () => get("/api/push/config"), + pushDevices: () => get<{ subscriptions: PushDevice[] }>("/api/push/subscriptions"), + /** Body is the browser's PushSubscription.toJSON(); re-subscribing a device is an upsert. */ + addPushDevice: (subscription: PushSubscriptionJSON) => + post<{ subscription: PushDevice }>("/api/push/subscriptions", subscription), + removePushDevice: (id: string) => del(`/api/push/subscriptions/${enc(id)}`), + testPush: () => post<{ sent: number; removed: number }>("/api/push/test"), }; diff --git a/apps/web/lib/push.ts b/apps/web/lib/push.ts new file mode 100644 index 0000000..e73b1fb --- /dev/null +++ b/apps/web/lib/push.ts @@ -0,0 +1,102 @@ +/** + * Browser side of Web Push: the service worker (public/sw.js), permission and the + * PushManager subscription for this device. + */ + +/** The worker is only registered in production builds, or in dev with NEXT_PUBLIC_ENABLE_SW=true. */ +export const SW_ENABLED = + process.env.NODE_ENV === "production" || process.env.NEXT_PUBLIC_ENABLE_SW === "true"; + +export type PushSupport = + | "supported" + /** iOS/iPadOS Safari: push only works once the app is on the Home Screen. */ + | "needs-install" + | "unsupported" + /** Built without the service worker (development). */ + | "disabled"; + +export function isIOS(): boolean { + if (typeof navigator === "undefined") return false; + // iPadOS reports itself as a Mac with touch. + return ( + /iPad|iPhone|iPod/.test(navigator.userAgent) || + (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1) + ); +} + +export function isStandalone(): boolean { + if (typeof window === "undefined") return false; + return ( + window.matchMedia("(display-mode: standalone)").matches || + (navigator as Navigator & { standalone?: boolean }).standalone === true + ); +} + +export function pushSupport(): PushSupport { + if (typeof window === "undefined") return "unsupported"; + const apis = "serviceWorker" in navigator && "PushManager" in window && "Notification" in window; + if (!apis) return isIOS() && !isStandalone() ? "needs-install" : "unsupported"; + if (!SW_ENABLED) return "disabled"; + return "supported"; +} + +export function registerServiceWorker(): Promise { + return navigator.serviceWorker.register("/sw.js", { scope: "/", updateViaCache: "none" }); +} + +/** This device's current subscription, if any. */ +export async function currentSubscription(): Promise { + const reg = await navigator.serviceWorker.getRegistration("/"); + return (await reg?.pushManager.getSubscription()) ?? null; +} + +/** Asks for permission (must run from a user gesture on iOS) and subscribes this device. */ +export async function subscribe(publicKey: string): Promise { + const permission = await Notification.requestPermission(); + if (permission !== "granted") throw new PermissionError(permission); + const reg = await registerServiceWorker(); + await navigator.serviceWorker.ready; + let sub = await reg.pushManager.getSubscription(); + // A subscription made with another server key can't receive our pushes. + if (sub && !sameKey(sub, publicKey)) { + await sub.unsubscribe(); + sub = null; + } + return ( + sub ?? + reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: base64UrlToBytes(publicKey), + }) + ); +} + +export class PermissionError extends Error { + constructor(readonly permission: NotificationPermission) { + super( + permission === "denied" + ? "Notifications are blocked for this site. Allow them in your browser's site settings." + : "Notifications weren't allowed.", + ); + } +} + +function sameKey(sub: PushSubscription, publicKey: string) { + const key = sub.options.applicationServerKey; + if (!key) return false; + return bytesToBase64Url(new Uint8Array(key)) === publicKey.replace(/=+$/, ""); +} + +function base64UrlToBytes(value: string): Uint8Array { + const padded = value.replace(/-/g, "+").replace(/_/g, "/"); + const raw = atob(padded + "=".repeat((4 - (padded.length % 4)) % 4)); + const out = new Uint8Array(new ArrayBuffer(raw.length)); + for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i); + return out; +} + +function bytesToBase64Url(bytes: Uint8Array): string { + let s = ""; + for (const b of bytes) s += String.fromCharCode(b); + return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index f908ec7..f9bb69d 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -7,6 +7,19 @@ const config: NextConfig = { poweredByHeader: false, // @synapse/core ships TypeScript source. transpilePackages: ["@synapse/core"], + async headers() { + return [ + { + // Browsers must always fetch the latest worker; it only ever runs our own code. + source: "/sw.js", + headers: [ + { key: "Content-Type", value: "application/javascript; charset=utf-8" }, + { key: "Cache-Control", value: "no-cache, no-store, must-revalidate" }, + { key: "Content-Security-Policy", value: "default-src 'self'; script-src 'self'" }, + ], + }, + ]; + }, async rewrites() { // Same-origin proxy so Better Auth session cookies work without CORS. return [ diff --git a/apps/web/public/icons/badge-96.png b/apps/web/public/icons/badge-96.png new file mode 100644 index 0000000000000000000000000000000000000000..66f5a340622b5f46a7767337e0815f72d66aceac GIT binary patch literal 650 zcmV;50(Jd~P)H3FyI>Y=ZdoH#6JZ+PAF_M`&k7a7|<&k(4+8j z=A#W6(ZX(58+OTW4DbgS;8FUu0rdd})F@2|`pP{3dx4cEbc*74D7q;@cG8dUm|Wo%ue`_&St6k$*GFi$9!BT zNH^netP;f3Kh;8wnI>GF=WpA{_=vjPD(B+Qr*9$Bnz=CDY*MKpM%%g}m>g*|P${0F z)`kVPbc$z+g)DEF@uX8cQ|zPh2CFi?K7PdzX-EAfK~Z<)+q`CJ58blXJ9nY&Jod0OWZ|;s6uM9l~Da zT>fnyn)j?~LB`{q`<^zxcS31)Aag_U#fI%y_keP^O6xo~^D99e-D!5Mf&5X1u?Z#W z+L=(Hs$B}(pr&1e*9{fzOyDwvp$S}qGc_j?(E3*k3W4Yr*xH&0{{R3 k0000000000006L!2g&e@s0yWdE&u=k07*qoM6N<$f~UAFEC2ui literal 0 HcmV?d00001 diff --git a/apps/web/public/icons/icon-192.png b/apps/web/public/icons/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..020fd64a0cb639ef7cba9e63554f92ff0deaa2b4 GIT binary patch literal 2123 zcmZ`*c{tR27ytf#O=iYA2$4I6glr=%x*=oBSYpDUQsbg1%WFwO#u$@bpG06@x~XyYo< z?4N=X6QS!+FcJWioV|^u`;~uYi#jt@$r$#!MVPb$n_s8W!^ElBt^4Og0Z zw%^e^m%FzXr;%zTXBm;U8&N*ZzF1UrG4Bj!}mCf zGlyRryfhO#Wyolywq0(~(#C4x>U#fHTn5rU4}_p^JY?iLTJclc8(O06fY$=7*xInREgFhQ@G-2l1G*MIER6%R zC1gp=6=r8OzV?V&{lXhIO9l^39nmt5H)cDvT#gxyDua@n(?*-sYvu78BW;I z7!-VOQXPD=ix8Z=&{h9pxgFm-EQMjqM&wD$^2;t{mwTYV96jOio^)Fnf#WCHW2}!b zfV8eT87W-23m~S)z4%4mKL|{@Q#v3?$X$&ROUM>)v)Tm{zCPI^eeJT%K8Qrn9I^+* zq&O62lvO4e-^#;TX#n?up~}7dgPsfwZTY@22I!V_9D8cq+i)L1k{XlA$Djk3Gc{&ACqy_;91I%h5956z6^)zH-A<6HnZC}XZ%>+=4o=Fz{PFd9mV?aD)%e)%BnoNE22f_aS%*L5@8`mSWmXEyA8!N?PCOaI&!e~K z)1immV-_4u#bjFO4t(yWn|x9evt2;Y=iC5dhoe`Q3OSUpvEz31`_^^l>MD?At|?D} zSs*_YKQ5o|l4uS56pEkEy$C7cs!iPbT#TO$#d&TPVAHMxv7H9dhOb!h>+h4IRZquq zoYvxe6JoIN>p|X9bEF(uvF3^R42M-O|$0Gw6lS*JdphZ0Mtl zZ?PjuSI@BU3Ej=;xUm)a3S<*5dWZcVEm5~tV_a&x`o5H2pl!qpqHnz`dWVZl3+H^{ z*?wB%&%D3kaeG5S+q*qwK=0@hu6S?pFz@){+8@|+Jl6M^ecl4icnR4Jt6(KKAI=Q= zE?%@A%OCc0Mh>Ge#=!R`LF>CZHK1|*#EA?7t%pOwB~FwK?InKH;ix5o5(jF|&EkNU zqh;n_t!X9Ic6p-h`0XV@_l!E#q>y;}q|81%;lYq+T&Po{JS65>b%fqD_nciV73zL9 z6J-<wQk&R3{5#FOc9f;h8M@LTivwNVr!h< zuyQ45fUnMo2TxWh0VAr_{f=*tP(MEXnr?I-HyKQAXL6(XiKXAib*kVkL-fubx*BPQL9mr*e41sB9G=f0<=!F29P5yS^`b(H3bv~`Fr%o4;L*(9u2c5z7}}6A&(ZJ4L97P zrOW)Zl{|2?&-syVb2i|qT&*bokOM(9BoT@zbt2Zz+=JVr3Vmf+u7phAZ#VT zP;{{Twg-}AVaL2;a|uc$kr0O%42tt2!5%4`k!pMu=H^-l9x`pgjr>A6r}_!`=l%kW z^0a*+Qo`ToB1ZyE<5HaIA!5q8^+oRCVcHH9+DNhjl8wd=h|v8`H&byanB)jjII z{%2h+V=VyCUAyKd4*&`pQh-TEWF)R}0$|#dwLh)g6xZ6{AxZb?-p?5Ps(){qWl|pZ zue@6;FZbtPnsd3)S8LrbKk`xqJhxg~yRz^z4>&GXH0op8plWaP1&R<7t`-8CzW6^w43Z)_MshziMU6xT&yhbyf#Bd|%Mu9vhxh3d?m>)CMIq-d|{K-BsRK;1|t>v!AD0o75jH zQ&IKJz$8XsE4ceWvW*KF&2*zb>?+P@YVo19aXyb~nvw|StSGM)vP?%F+-iTCTJVew zzLZ6MO32raELbcXFBqrROYad?2EHY1NTd2*(NQ_fG6JpAfJ1gNDu;F_i%y3yv!y~GSy-=U9J&(jhi-{gS6zlLN*f6w+TFZYW%AgPzbV5~B@H|V& zHUzzPb1;9FR7qmI-caHSRaCD_A%4&;BQYWdKSF|NW7ET=8zdF4wkOQmNQ!7-N4aR2 z-1qr0;IAIf(;yP;=#W;<_khR%5JYML#)&r-P;gkYg}Ize|HFg=^Z%7a73HW0pL+m^ z+H44?!|XoVX)@E&jtU+vX;9q18t?^e20#y|!KKCZ6edjHj%ffqoep!qO_gY}z-@9k zeKwK+0JAkAvx5n1{wWC~Fpen(Km)+h!vBY`&^{yq5%C>1`Qd$Cq#qh<8FdQDW(1& zgVQKTua3$Ey#T}mKPJMoJosx#C4F>Mn;OkP7TKmeaTo%bXq4Ul;mSxsf?Y{;@r#2r zAl4tv{-V?M=G@#*`zHa|n~vSHi}Rk>YwqZclwPm7R~Ak7_F)S((AI*O{(oY1TbIq8 z_2Dbx9g)xbP^&iXNiQ-_)yH+JFP#f;>sfX)*LqC^-X2(Y7CDiT5`d=qce0W zVlN)c+=_^(mAhWY5FpK8$e)QZLDaZWD4vFppSB-lFf=p)Ql^m851qB5k1RwMU(%+s zpU*h-E_%VYQbrzQ|Rz7_@P>dkVTY!Gu5^jCA;p+UOVKt zVt|wU)j8`B#dt2`1N^S9NOvfF@KML;OsJ8o^k@C)z3$ zx&Y)Iqdwj%VgmkdR-)`F(dMFtD2VZ^nD9&vPya9M7ChTmf4{qnAV*PVPfq#!+kw;< z8(HFaqqsKHUK__u3Wy&22&EzjRkD$pOR>TdYexJK@>SGA(zR!1{5Dj4Jd`TDgz*@ohD=t z{freaC~@+i0Ve6F_@k%%zSef~9kmC$`NO&NJrN`dl07@(RJ})&$r3B&EAI6CFu4W5 zUmsezs)twAlicwilcRP0n^)DHM*z0ekXsYq-&Q>$d>=OQ&sBDAMdq>n__pJ=_bi2_ zMx)vK9p54+qfB1#&;wsqD2e;dvR%r*%>U|>EG#5?$K>9lRw!sMbVSS)DpR_3K1|y( zF65Jw>nZ%ZA&Hlu`n_h##D0x%` zB2$Y)Yxus&LRRsaSL2CazCr4)WXQY2$0t)pCd>eiTBw?(@%+KC(Su~RaSvrU<(_%qW9xde}GQ@%8NsVgfLsxtpdCey7dFV^`X4fl~ZZ0%)id3(1r zSN^_8;d;-X>!3h4#$>$dY{V`9!MgIL4WTm*kGBM#?(?`|D-)hKJkLv2T zj?aE84#-d~eEZn|@v1OOl6h61{pa15oruj`u{Q4knbKV}QELD}PtJPZ z?|5?R_1r2&SGx0V&03bbONC^A4u7Q)Mr>_}za9}>&+UJ1U46vr(S85&`OiDqOM-Kv zX<(etCVVYyzi0K>h*_%@G;XnfF!P6>a~&v9I`^1Ize`HA8zbJ;L+W?t^xomSW>74> zsw%IP7TKG14qJHEj_fp6m>rO}8-V!JsnAWGv0u}d9CVGEBXca1M|;%er2Hkbja>6}mk+~}oNvL ze2C9)$aZO5Shw3+W(K@UKVKqp!MTG#?D3k?^flPyUem$f4Yqk3fVE5;qx1U{Il$ZY zX0^ovm6swJJs*{i>Qiuodx_WlCWn+}Q5fAJ^4xn;xRGWniyDn?AaRZUUtdE+51>SEI%f;_Fkatm9c zOTl|?D7~Mw7Q}GXkhl0n`*UJ0_+0Ih1RevzYMY#LX45mL;{Cu8cW4TmOLzC*-O`5xBuz5(6LI6Gif)0HaY}$EcYJ@1qDti_IJT}N7$j0*N zN!70Jo0;GD7HqApX)C7Yof|<9|B@rv3Y|3-xiMVyj{SwTZoiPmpF(nAwxNa_z32B` z;z_m*on-Z}cS0-y0xxY#Lam?ByO+?Hm$WVYba!Blb>JWa6ByYzg$bG#K?!nch@`Hej|`T2~hdC1-SwXgn2#Bk9_N2K9`dymsor!L>VoJtWj-h~fay_>$E z!sH&dW-4Wqf=VHDebMM<_Vizo4$(sB`M%d$8^0Nl9H8syxi=^;;Ot5eEhNg9^e3vl zBzla~&8Cn99N%1?{q_)X-}3xrb`y;PA@O}L>~tP!eiy-cQy7tVWjIW8rfGBC3MS-J zHq4}4ka1(RXvXNme3QT!^>u~!RtN7XW zLbVkHi^soI^|uqp+@b@o%f^Q_(QOvnSbJLSpY|i3XS-hQxq8tFqJ!> zLXI$(SyhXrlh);NV-@?AGY$g&unhZK>t(C?!P9E7yr#w#l!FkRZp`3DAPKLhW3JT3 zWex8Fb!cE;Z^PbPM6AeWpR^B^wXGI(~u=SV3cWCa~tT0im1i^8f z<*HGV5OV0CczfrKzYj9?q<#Lynfyg``Jb(#oBjMEb>QJl^Yt{RI&@!(H|rjpNM1a) z9EC26^37}<+F$0uPL35EWQ=cNDq4GZfeKx_Cc}{D^tPDAvSdIF<Y2njhnDQ5Z2Xyzc-uu zetft|p9%Fzi;}iXO|=_KuaZ6)2ng{*Q1lk*K5CO+3rm*vbv3uWK|vtklz8)Ryyw1{ zrIwGf6{?8;4}v-$4qE&F5GE=;{)cRQI@VcYg27eCV^G|!?oi{ARHPfv0_(k~us*q# zM*N{>_!lba*BJl1drkfCcDB47^{Bh9PdkN}_KzGZ`s(+&!W52It9}FVz8|5}`pI0} z6~iq!uyYUQqXiD(C=VBx&VUK^pnky857F7ZP>)J2O$W%Lh{PEfaUo-a7HDA@#}yN} zplrPj?if;LRjdH_OHV2TeTRj2`{)?{N6ZFo_|c9DX-gd~A)kso+(){ac8b=aF90(} zUf%mC4C-2q;Tz{(rx8ge8n9~mjY&}c?R&uHh?A}kC{qWKrIyw(<711ec`@pfRJV1I zbFYw=RKTly_(!Oi=+~Abq}ULp|KV`e`%u&c)|QQvTBbb7IvTOQWx#jDLx%}#)5!JW z$+!&%qAtlI`rneCE+Vn62C?2~{2GGMGRMvk?B975J#%&CfMNT@l{qXpQLf6KL>X)M zfuPHkJA9iJc9NK6OmMP1K6=M)3^=dagjr)-{Kl1id8%j)z)xJ``(kjsxK~1736ZA* z9_H@LG0I=Yf|rt^*sIMot|90!O+&X=GmXBoFrMYb9h#?z11Ask=%5~EfvTB_IXH(xod1 zLZ0Y-f>WP+R<;t>m{kqSSL4mUWr(&k176~#3=DIInXa`u-8Y{`<@Djg z+pr;P3Ml05~|r0TK~Dh7%e_0Wf_U;N!JAp}D_Rn6ajlDv)c_7Wmc&UCATQ zI(3l#`x?H%;;9^`9cw1qlG1LH4<2W3YP!;5c_@#t?fBiT6N`T1_#1zJ(rR(0S9pAx zCS6!@m3y>KlOh~S-jX5eiTqR1Hh1Wr&`o$On74oJ6hJ#2oJ;~VXdMB71OO9`ASE&Y zC>#;Mzr6ay?H`PM6#9qlf8+F7JTWAkKp*)V&cFKh!8!_LQ$J3R4`=>n>GK(Xd?5a5 z_!E5lz|-<_XU6PWQ^uAk6YAU0+LqG%aM6Xh-X86lLzT-Sb(um_1gzu~M(8$9sR(7V zW2>&!K6BK3dE&NMb=A$4z13kH@5(0mq%QzyrW0QWEmEb}X?@{+Q12muHPQss+zvTKSYff+Wn z6w8G@t8`BE)io5DbD1$BYJ6k9k@`M;{Wjl&QVPUC6E3xNRcSQtNy*O@=>T;58J*2H zRg3D3WlNztF=hofdB2qLO8?zL2#8Ed-; zG=L7buRNcb#+FWez{3+j{dSLAE<+OW-N?LN1Of9l>{rg-87U5kJ5I&{{~sIrQ|yX8 z>yu&G)Hjq?Uh~o=#a0ybLI)FurE6ey<(W9YtYt>8ftvg8SA>-Rm6|ni*%zA~NkGub zeqeBbXF&jx0mhF|Z{8FFSXug0)oJ6tE*vDXt42+28LTuHnc%?sqRwk62xQ#JIZ%T} zeM!RsnKE}#hyvHOV#JFC(8fQd+6WN803$Jd zV3V@~&=q*t=O+ zy1_1@{7FUD1kni~^8(qpjW}rL`uM!?Xug8mOG3cO*L~0VMz5v=Isik^5h~RFsNO>p z6iT|(FypjQw>Kwdj|R$gakn_}Vcw#=9LCFLFUSU;qd5k^jB0%;dk2fkJol5N1TOo& z@VI@qSaU0w>vy3kI!5Y!Z%%A0b~@#4<;$WnMoXf|o0t%S|)pr*}Yno`% z0cg3Q=XGvrw9Osegz97m~CdX&U2-69FPq9GLO+ac4$toX|6|RU&>PD37-6 z6BR@X-NxRDYKc1D?jWjjcSvEc7z-zM;u$Yq{5(b`4I~ZE5>zl?;16hW2YMrA(&k~w zY$7{Y3j?$z*V}brP;vt)F^UYwKR0Dmob>r_%`nimMcb-fh!4Gs% zdi23|x4O6`h+wIv0Op~#q`0c}MBQ=eonCM|K#$3HhclI(388DkWQ_JtD+ICmg8FKuzCJJb^Qm7P{gbl6M*KILnjILT0 zgzp-0DDH&@vQJQ8IN;R5ZW(wnysLNZxC()kNyTbvp(LVt z2p@ibBMY`0Vk!Z!ipBO7ZAig3*2XNojwl^Woa#|%|NLC-GE23HYe#mL4fcjyHE!s* z_lyC{eaRwNL3{YO4jW`R$2x2I6`PZmKlVs|b*$*_h~*#NyK3V4H>W7r8T(Z7*P#Zv z2o+&I_M+J!((^A`?~U{rPN~Bkv)v|t-7XYT-Rte=oEvmID`)JZ%!%zEokIam0!OW- ztOGqA+oq`$Td<=QM>F?laAxn5nG)FqFg$ah;Zjk} zrD8O!b&kCGmse$s?AfC>6mY%FT4#TIuQ?9t6YNJb>~^Ga>Jm68g$%9O9FSw9F;i<>z+EkNm%;wbV+Aww(0<2ee0*q z*B(?Xyi=)d zo^6P}y!nBG1JHeKZ$++3t{Kh5LE#OQHS9>stE)@RQdz~s2=Q`wC7gn~UJIJY-Le?;T6E7hu^idu^88PK>$H zVoC-^`LC)T+62M0Ac1>Ce+wkvu`?5YSZxH=`Yx-=NY?3#cBY~rufQRON1Cy)d8s&z zLI903QZ!0?li$uXRunby%l0r}{AV&RKJUfofFNYN$&P%#vt=-#)^>lSgK7;xm>COB z6*vlFC{B+G@!N_wJ<1if6}P6AG65@IkhG$G&h24oIVOCQl|R81qkdDfhWV(lHj;xr z4XLX5DjK~qP1gvxQ#yBw5n5d7?F(Y<` zWhURQ%Q^>jeX-7h7fl9E_2G*t1bMgXpPAnuA)ZyvEtuP;{t>U^?g|g3W5S?E(w#bB zvbx^N3E&i4^W4agz140b5+EZ*hutiB&e+2EbaM-y0~xF&d_&H`qU8g;>y$3aGyo{9 zVk!+V2@QR((nERHa8GGdV!fa(w<-3?d>D?iX9H)=6L?^fazIkW8ABcgLmYFT1CtkC zX3RNhyRGb!FJlpVWtJAwMT!wX8)W1WQMZ2bUnk30a%24Z@Nsz>`bbpZETlN;`f{fqI!T8D^jr94)5k2JN|ggvX*ZYmJ#hIgi?DD6F7ItlIU#|`7s_a<`WE9n z^%`NzH*XI8K-4NMM8pylohJ)Y6$Pspl)ZMvQ z=mFc_|Nmk7gr6wr7c6z`_5|Rm&$_!~r$~Sbe self.skipWaiting()); +self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim())); + +/** Notification buttons, where the platform has them (not iOS/macOS Safari). */ +function maxActions() { + return self.Notification?.maxActions || 0; +} + +/** Only ever open pages of this app, whatever a payload says. */ +function sameOriginUrl(url) { + try { + const u = new URL(url || "/", self.location.origin); + return u.origin === self.location.origin ? u.href : self.location.origin; + } catch { + return self.location.origin; + } +} + +function show(title, options) { + const actions = maxActions() > 0 ? (options.actions || []).slice(0, maxActions()) : []; + return self.registration.showNotification(title, { + icon: ICON, + badge: BADGE, + ...options, + actions, + }); +} + +self.addEventListener("push", (event) => { + let msg; + try { + msg = event.data ? event.data.json() : null; + } catch { + msg = null; + } + if (!msg) msg = { title: "Synapse", body: "Something needs your attention.", data: {} }; + const data = msg.data || {}; + event.waitUntil( + show(msg.title, { + body: msg.body, + tag: msg.tag, + data, + actions: msg.actions, + // Stays until handled where supported: it is waiting on you. + requireInteraction: Boolean(data.toolCallId), + }), + ); +}); + +self.addEventListener("notificationclick", (event) => { + const notification = event.notification; + const data = notification.data || {}; + const url = sameOriginUrl(data.url); + notification.close(); + const action = event.action; + if ((action === "approve" || action === "deny") && data.runId && data.toolCallId) { + event.waitUntil(decide(action === "approve", data, notification.body, url)); + } else if (action === "undo" && data.runId && data.toolCallId) { + event.waitUntil(undo(data, url)); + } else { + event.waitUntil(focusOrOpen(url)); + } +}); + +function callPath(data, suffix) { + return `/api/runs/${encodeURIComponent(data.runId)}/tool-calls/${encodeURIComponent(data.toolCallId)}/${suffix}`; +} + +/** Same-origin call with the session cookie; throws on anything but success. */ +async function post(path, body) { + const res = await fetch(path, { + method: "POST", + credentials: "include", + headers: { "content-type": "application/json", accept: "application/json" }, + body: JSON.stringify(body), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const text = await res.text(); + return text ? JSON.parse(text) : {}; +} + +async function decide(approved, data, body, url) { + let result; + try { + result = await post(callPath(data, "decision"), { approved, via: "push" }); + } catch { + // Signed out, already decided elsewhere, or offline: let the person see it in the app. + return focusOrOpen(url); + } + if (!approved || !result.executeAfter) return; + // A send or delete waits out the undo window: say so, and offer Undo where possible. + const seconds = Math.max(1, Math.round((Date.parse(result.executeAfter) - Date.now()) / 1000)); + const verb = data.effect === "send" ? "sending" : "running"; + return show(`Approved · ${verb} in ${seconds}s`, { + body: body || "Tap to open the task.", + tag: data.toolCallId, + data: { ...data, approved: true }, + actions: [{ action: "undo", title: "Undo" }], + silent: true, + }); +} + +async function undo(data, url) { + try { + await post(callPath(data, "undo"), {}); + await show("Undone", { + body: "It won't run. Open the task to tell Synapse what to do instead.", + tag: data.toolCallId, + data: { url: data.url }, + silent: true, + }); + } catch { + // Too late, or signed out: show the task as it is. + await focusOrOpen(url); + } +} + +async function focusOrOpen(url) { + const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); + for (const client of windows) { + if (client.url === url && "focus" in client) return client.focus(); + } + const any = windows.find((c) => "navigate" in c && "focus" in c); + if (any) { + try { + await any.navigate(url); + return any.focus(); + } catch { + // Not controlled by this worker: fall through to a new window. + } + } + return self.clients.openWindow(url); +} + +/** The push service rotated this device's subscription: register the new one. */ +self.addEventListener("pushsubscriptionchange", (event) => { + event.waitUntil( + (async () => { + const res = await fetch("/api/push/config", { credentials: "include" }); + if (!res.ok) return; + const config = await res.json(); + if (!config.enabled || !config.publicKey) return; + const sub = await self.registration.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: config.publicKey, + }); + await post("/api/push/subscriptions", sub.toJSON()); + })(), + ); +}); diff --git a/bun.lock b/bun.lock index f506d36..f9d9f8d 100644 --- a/bun.lock +++ b/bun.lock @@ -21,8 +21,13 @@ "better-auth": "1.7.6", "drizzle-orm": "0.45.3", "hono": "4.13.9", + "nodemailer": "10.1.0", + "web-push": "3.6.7", "zod": "4.6.5", }, + "devDependencies": { + "@types/web-push": "3.6.4", + }, }, "apps/web": { "name": "@synapse/web", @@ -380,6 +385,8 @@ "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="], + "@types/web-push": ["@types/web-push@3.6.4", "", { "dependencies": { "@types/node": "*" } }, "sha512-GnJmSr40H3RAnj0s34FNTcJi1hmWFV5KXugE0mYWnYhgTAHLJ/dJKAwDmvPJYMke0RplY2XE9LnM4hqSqKIjhQ=="], + "@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="], "@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="], @@ -388,12 +395,16 @@ "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], + "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + "ai": ["ai@7.0.116", "", { "dependencies": { "@ai-sdk/gateway": "4.0.94", "@ai-sdk/provider": "4.0.18", "@ai-sdk/provider-utils": "5.0.49" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-gmkVGPzTNPcJixBiG9zUvP3gmvwko85dHiKrxFKK0zcVJIIu1FP6YDo3jna+ZrC2twMAsUPLr5htCwZjCINH3Q=="], "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + "asn1.js": ["asn1.js@5.4.1", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0", "safer-buffer": "^2.1.0" } }, "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA=="], + "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], "baseline-browser-mapping": ["baseline-browser-mapping@2.11.28", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-br0LOmjJqr6Rt4AEkadbcNf67Zpo7EPwKsWbjnRrJIa1QYFHQBqM4C7F2WTbV8ahTEcg1Eo+Y0aWjjORInYFyA=="], @@ -402,8 +413,12 @@ "better-call": ["better-call@1.4.0", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-bBKOT4vv1kZLDgxVePdilk/Jwkn+dtRRsmi3DzHcDP+WnswyVl6dR59l2HEeP/0cB+bDoopASAesWDPIdd/zZA=="], + "bn.js": ["bn.js@4.12.5", "", {}, "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ=="], + "body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="], + "buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="], + "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], "bun-types": ["bun-types@1.4.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="], @@ -466,6 +481,8 @@ "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + "ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="], + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], @@ -536,6 +553,10 @@ "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + "http_ece": ["http_ece@1.2.0", "", {}, "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA=="], + + "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], @@ -572,6 +593,10 @@ "jsonrepair": ["jsonrepair@3.15.0", "", { "bin": { "jsonrepair": "bin/cli.js" } }, "sha512-wy8OTjwsJwQRnQJkKnMJJ9vcytRdBPAgIF/Hy6+s1dAj42BHMKiyL8JzEieIl3JY7idt8eyHwBWTO8mh/+mtwA=="], + "jwa": ["jwa@2.0.1", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="], + + "jws": ["jws@4.0.1", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="], + "kysely": ["kysely@0.29.6", "", {}, "sha512-hHaB8C/rfzDDtr/t8YZwxAuPJTT0zHyaPoVzcXwDYhYNAgH/4sIfVhi/XLLIY+bL/FqaIJnjATDbi8ObSELmxg=="], "lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], @@ -704,6 +729,10 @@ "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], + "minimalistic-assert": ["minimalistic-assert@1.0.1", "", {}, "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="], + + "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], @@ -714,6 +743,8 @@ "next": ["next@16.3.6", "", { "dependencies": { "@next/env": "16.3.6", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.3.6", "@next/swc-darwin-x64": "16.3.6", "@next/swc-linux-arm64-gnu": "16.3.6", "@next/swc-linux-arm64-musl": "16.3.6", "@next/swc-linux-x64-gnu": "16.3.6", "@next/swc-linux-x64-musl": "16.3.6", "@next/swc-win32-arm64-msvc": "16.3.6", "@next/swc-win32-x64-msvc": "16.3.6", "sharp": "^0.35.4" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-L+otWM/aQbYTx98aZhgEoMb4bZAXx1YVW4UMA/vuCyCoWG5HJyZUili8QAkqzrcC+5///tsz3s0M+SlyB5bLMw=="], + "nodemailer": ["nodemailer@10.1.0", "", {}, "sha512-fXW8AulB25aOTuwfRYV6lqHyfz2VM4rr4SGXH03mE7x5znEUpzL5mu6anARUpZN7744Ziwkmr4AxSLPJsBQspg=="], + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], "object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="], @@ -770,6 +801,8 @@ "router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="], + "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], @@ -858,6 +891,8 @@ "vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="], + "web-push": ["web-push@3.6.7", "", { "dependencies": { "asn1.js": "^5.3.0", "http_ece": "1.2.0", "https-proxy-agent": "^7.0.0", "jws": "^4.0.0", "minimist": "^1.2.5" }, "bin": { "web-push": "src/cli.js" } }, "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A=="], + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], @@ -884,6 +919,8 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "@types/web-push/@types/node": ["@types/node@26.6.5", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg=="], + "better-call/@better-auth/utils": ["@better-auth/utils@0.5.0", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="], "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], @@ -946,6 +983,8 @@ "@esbuild-kit/core-utils/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.18.20", "", { "os": "win32", "cpu": "x64" }, "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ=="], + "@types/web-push/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "bun-types/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], "tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], diff --git a/docs/api.md b/docs/api.md index c7a03cd..98a2ee5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -4,7 +4,7 @@ All endpoints live under `/api`, return JSON, and require a session cookie (Bett mounted at `/api/auth/*`) unless noted. Every query is scoped to the signed-in user; ids belonging to someone else return `404`. -Errors: `{ "error": { "code": string, "message": string } }` with status 400/401/404/409/422/500. +Errors: `{ "error": { "code": string, "message": string } }` with status 400/401/404/409/422/500/503. Types referenced below (`UiMessage`, `UiPart`, `SeqEvent`, `RunStatus`, `Effect`, `ToolOutput`, `PolicyRule`, `PolicyDefaults`) are exported from `@synapse/core` and @@ -15,7 +15,7 @@ Types referenced below (`UiMessage`, `UiPart`, `SeqEvent`, `RunStatus`, `Effect` | Method | Path | Response | |---|---|---| | GET | `/api/health` | `{ ok: true }` | -| GET | `/api/config` | `{ auth: { emailPassword: boolean, github: boolean, google: boolean }, integrations: { google: boolean }, features: { webSearch: boolean, embeddings: boolean }, models: string[] }` | +| GET | `/api/config` | `{ auth: { emailPassword: boolean, github: boolean, google: boolean }, integrations: { google: boolean }, features: { webSearch: boolean, embeddings: boolean, push: boolean, emailAlerts: boolean }, models: string[] }` — `push`/`emailAlerts`: the server has VAPID keys / SMTP configured | | GET | `/oauth/client-metadata.json` | OAuth client metadata document for MCP servers | | POST | `/api/hooks/:automationId/:token` | Starts a task for a webhook automation. Any body (JSON is pretty-printed for the agent, capped at 16 KB). `202 { ok, taskId }`; `404` for an unknown id or wrong token, `409` when paused, `413` over 256 KB, `429` over 60 per hour | @@ -39,7 +39,7 @@ agent reads it at its next step; if the run is waiting on approvals, those are d | Method | Path | Body | Response | |---|---|---|---| | GET | `/api/runs/:id/events?after=` | | **SSE** stream (see below) | -| POST | `/api/runs/:id/tool-calls/:toolCallId/decision` | `{ approved: boolean, reason?: string, input?: unknown }` | `{ executeAfter: string \| null }`; `409` if no longer awaiting approval. `input` replaces the arguments (edited on the approval card). Approving a `send` or `destructive` call opens the user's undo window: it runs at `executeAfter`, not before | +| POST | `/api/runs/:id/tool-calls/:toolCallId/decision` | `{ approved: boolean, reason?: string, input?: unknown, via?: "web" \| "push" }` | `{ executeAfter: string \| null }`; `409` if no longer awaiting approval. `input` replaces the arguments (edited on the approval card). Approving a `send` or `destructive` call opens the user's undo window: it runs at `executeAfter`, not before. `via` (default `"web"`; anything else is `422`) records where it was decided: the service worker sends `"push"` for a notification's Approve/Deny button | | POST | `/api/runs/:id/tool-calls/:toolCallId/undo` | | `204`; `409` once the window has ended ("Too late to undo: it already ran."). The call is denied and the agent is told the user undid it | | POST | `/api/runs/:id/tool-calls/decisions` | `{ decisions: { toolCallId, approved, reason?, input? }[] }` (`input`: approve with edited input, same as the single route) | `{ executeAfter: Record }` for calls that opened an undo window; 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` | @@ -131,7 +131,7 @@ task that read outside content still asks. | Method | Path | Body | Response | |---|---|---|---| -| GET | `/api/settings` | | `{ instructions: string \| null, models: { chain: string[] }, budgets: { perRunUsd, perDayUsd }, providerKeys: Record<"anthropic"\|"openai"\|"google"\|"gateway", boolean>, undoSeconds: number }` — keys are write-only; `undoSeconds` (0–60, default 10, 0 is off) is the undo window for sends and deletes | +| GET | `/api/settings` | | `{ instructions: string \| null, models: { chain: string[] }, budgets: { perRunUsd, perDayUsd }, providerKeys: Record<"anthropic"\|"openai"\|"google"\|"gateway", boolean>, undoSeconds: number, emailAlerts: boolean }` — keys are write-only; `undoSeconds` (0–60, default 10, 0 is off) is the undo window for sends and deletes; `emailAlerts` (default false) emails the account address about new approvals when SMTP is configured | | PUT | `/api/settings` | partial of the above; `providerKeys` values are strings to set, `null` to clear | same as GET | | GET | `/api/usage?days=30` | | `{ days: { date, costUsd, runs, inputTokens, outputTokens }[] }` | | GET | `/api/models` | | `{ models: ModelEntry[], updatedAt: string \| null }` | @@ -144,6 +144,25 @@ price table and the server's configured chain. `available` means the server or t for that provider. Available models come first, then newest. `updatedAt` is the last catalog sync (`null` if it never synced; built-in prices are used then). +## Notifications + +Web Push for approvals (setup: [notifications.md](notifications.md)). Routes other than +`GET /api/push/config` and the list/remove routes answer `503 push_not_configured` when the +server has no VAPID keys. + +| Method | Path | Body | Response | +|---|---|---|---| +| GET | `/api/push/config` | | `{ enabled: boolean, publicKey: string \| null }` — the VAPID public key for `PushManager.subscribe` | +| GET | `/api/push/subscriptions` | | `{ subscriptions: { id, endpoint, label: string \| null, createdAt, lastUsedAt: string \| null }[] }` — this user's devices | +| POST | `/api/push/subscriptions` | the browser's `PushSubscription.toJSON()`: `{ endpoint, keys: { p256dh, auth } }`, plus optional `label` (default: derived from the User-Agent, e.g. "Safari on iPhone") | `201 { subscription }`. Upserts by endpoint (a device signed in to another account moves to it). Keys are sealed at rest. `422 invalid_endpoint` unless the endpoint is an https URL on a known push service (FCM, Mozilla, Apple, WNS) | +| DELETE | `/api/push/subscriptions/:id` | | `204` | +| POST | `/api/push/test` | | `{ sent: number, removed: number }` — a test notification to every device; `removed` counts devices the push service no longer knows (404/410), which are deleted | + +Each approval is pushed once (to every device of each of its recipients) when a run starts +waiting: `{ title, body, tag: toolCallId, data: { url, runId, toolCallId, effect }, actions: [approve, deny] }`; +several at once for one person become one summary without buttons. Email alerts are a user +setting (`emailAlerts` in `/api/settings`). + ## Automations Prompts that run when their trigger fires. Anything that needs approval waits in the diff --git a/docs/notifications.md b/docs/notifications.md new file mode 100644 index 0000000..cb24659 --- /dev/null +++ b/docs/notifications.md @@ -0,0 +1,110 @@ +# Notifications: approve from your phone + +When a task stops to ask, Synapse can tell you where you are: + +- **Web Push** to your phone or desktop, with **Approve** and **Deny** right on the + notification. Works in the installed app (Home Screen on iOS and Android) and in desktop + browsers. +- **Email alerts**, optional per person, with a link to the task. + +Each approval is announced once, when the run starts waiting. Several approvals at once +become one summary notification per person. + +## Web Push + +### 1. VAPID keys + +Push services only accept messages signed with your server's VAPID key pair. Generate one: + +```bash +bunx web-push generate-vapid-keys +``` + +and set: + +```bash +VAPID_PUBLIC_KEY=BK... # "Public Key" +VAPID_PRIVATE_KEY=... # "Private Key", keep it secret +VAPID_SUBJECT=mailto:you@example.com # how push services can reach you; required in production +``` + +In development (`NODE_ENV=development`, the default) you can skip this: the server generates a +pair once and keeps it in `.data/vapid.json`, next to the dev secret. Production never generates +keys; push stays off until they are set. + +Keep the pair stable. Changing it invalidates every device's subscription: people have to turn +notifications on again in Settings. + +### 2. HTTPS and the service worker + +Push needs a secure origin: `https://`, or `http://localhost` while developing. The web app +registers its service worker (`/sw.js`) in production builds. To try it under `next dev`, set +`NEXT_PUBLIC_ENABLE_SW=true` for the web app (on localhost, so the browser treats it as secure). + +The worker caches nothing and never intercepts requests: it only shows notifications and +handles their buttons. + +### 3. Turn it on + +**Settings → Notifications → Turn on.** The browser asks for permission and the device appears +under "Your devices". **Send a test** checks the whole path. Each person turns it on per +device; remove old devices from the same list. + +### iPhone and iPad + +iOS and iPadOS (16.4 and later) deliver Web Push only to apps on the Home Screen: + +1. Open Synapse in Safari. +2. Tap **Share → Add to Home Screen**. +3. Open Synapse from the Home Screen, sign in, and turn notifications on in Settings. + +iOS does not show notification buttons, so tapping a notification opens the task, where you +approve or deny. Android, Windows, macOS Chrome/Edge/Firefox show **Approve** and **Deny**. + +### Approving from the lock screen + +**Approve** and **Deny** call the same decision API as the app, with your session cookie, and +are recorded with `decided_via = "push"`. If that fails (you were signed out, someone already +decided, you're offline) the task opens instead. + +Sends and deletes still wait out your undo window (Settings → General, 10 seconds by +default): the notification turns into "Approved · sending in 10s" with an **Undo** button. If +your undo window is off, a send or delete can't be approved from a notification; it offers +**Deny** only, and tapping opens the task. + +### What is sent + +The payload is encrypted end to end to the device (the push service can't read it) and holds +the action's one-line preview, the task link and ids, never the full input. Notifications +expire after 24 hours if the device is offline. When a push service says a device is gone +(HTTP 404/410) its subscription is deleted. + +For safety the server only delivers to known push services (Google FCM, Mozilla, Apple, Windows +WNS) over HTTPS; other endpoints are refused when a device subscribes. + +## Email alerts + +Set an SMTP server and a sender: + +```bash +SMTP_URL=smtps://user:password@smtp.example.com:465 # or smtp://…:587 for STARTTLS +EMAIL_FROM=Synapse +``` + +Then each person can turn on **Settings → Notifications → Email me when something needs my +OK**. Alerts go to the account's email address and contain the preview, why Synapse is asking, +and a link to the task, in plain text and simple HTML. + +There are **no approve or deny links** in email, on purpose: mail security scanners open every +link in a message, so a one-click link would approve things nobody looked at. You decide in the +app. + +## Environment + +| Variable | | +|---|---| +| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | Web Push key pair; both or neither. Dev generates one if unset | +| `VAPID_SUBJECT` | `mailto:` address or `https://` URL; required with keys in production | +| `SMTP_URL` | SMTP connection URL for email alerts | +| `EMAIL_FROM` | Sender for email alerts; email is on only when this and `SMTP_URL` are set | +| `NEXT_PUBLIC_ENABLE_SW` | Web app: register the service worker under `next dev` | diff --git a/packages/db/drizzle/0006_push.sql b/packages/db/drizzle/0006_push.sql new file mode 100644 index 0000000..c1bb1eb --- /dev/null +++ b/packages/db/drizzle/0006_push.sql @@ -0,0 +1,15 @@ +CREATE TABLE "push_subscriptions" ( + "id" text PRIMARY KEY NOT NULL, + "user_id" text NOT NULL, + "endpoint" text NOT NULL, + "p256dh" text NOT NULL, + "auth" text NOT NULL, + "user_agent" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "last_used_at" timestamp with time zone, + CONSTRAINT "push_subscriptions_endpoint_unique" UNIQUE("endpoint") +); +--> statement-breakpoint +ALTER TABLE "user_settings" ADD COLUMN "email_alerts" boolean DEFAULT false NOT NULL;--> statement-breakpoint +ALTER TABLE "push_subscriptions" ADD CONSTRAINT "push_subscriptions_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "push_subscriptions_user_idx" ON "push_subscriptions" USING btree ("user_id"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0006_snapshot.json b/packages/db/drizzle/meta/0006_snapshot.json new file mode 100644 index 0000000..14f603d --- /dev/null +++ b/packages/db/drizzle/meta/0006_snapshot.json @@ -0,0 +1,2142 @@ +{ + "id": "8476e6ba-8045-4c61-8bab-f811569ae060", + "prevId": "a1782b93-d749-4af8-8532-db47b083aa61", + "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.push_subscriptions": { + "name": "push_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "push_subscriptions_user_idx": { + "name": "push_subscriptions_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "push_subscriptions_user_id_user_id_fk": { + "name": "push_subscriptions_user_id_user_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "nullsNotDistinct": false, + "columns": [ + "endpoint" + ] + } + }, + "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 + }, + "decided_via": { + "name": "decided_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notified_at": { + "name": "notified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execute_after": { + "name": "execute_after", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "full_output": { + "name": "full_output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_calls_user_decided_idx": { + "name": "tool_calls_user_decided_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "decided_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "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": "'{}'" + }, + "undo_seconds": { + "name": "undo_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "email_alerts": { + "name": "email_alerts", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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 207d5be..c5a199d 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1792891462021, "tag": "0005_approval_channels", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1792891793494, + "tag": "0006_push", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index a7f1252..f47e979 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -118,6 +118,8 @@ export const userSettings = pgTable("user_settings", { dismissedSuggestions: text("dismissed_suggestions").array().notNull().default([]), /** Seconds an approved send or destructive action waits, with an Undo, before it runs. 0 disables. */ undoSeconds: integer("undo_seconds").notNull().default(10), + /** Email the account address when something needs approval (needs SMTP configured). */ + emailAlerts: boolean("email_alerts").notNull().default(false), updatedAt: updatedAt(), }); @@ -344,6 +346,30 @@ export const integrations = pgTable( (t) => [uniqueIndex("integrations_user_provider_idx").on(t.userId, t.provider)], ); +/** + * Web Push subscriptions: one per browser or installed app. The endpoint is the push + * service URL for that device; the keys encrypt payloads to it and are sealed at rest. + */ +export const pushSubscriptions = pgTable( + "push_subscriptions", + { + id: id(), + userId: text("user_id") + .notNull() + .references(() => user.id, { onDelete: "cascade" }), + endpoint: text("endpoint").notNull().unique(), + /** Sealed. */ + p256dh: text("p256dh").notNull(), + /** Sealed. */ + auth: text("auth").notNull(), + /** A readable device name, e.g. "Safari on iPhone". */ + userAgent: text("user_agent"), + createdAt: createdAt(), + lastUsedAt: timestamp("last_used_at", { withTimezone: true }), + }, + (t) => [index("push_subscriptions_user_idx").on(t.userId)], +); + // ── Knowledge & memory ───────────────────────────────────────────────────── export const memories = pgTable( From 241f45fb1b95649f54d1e5a7e12d99738b15d641 Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:16:08 +0530 Subject: [PATCH 05/10] Team workspaces: shared rules, admin sign-off, invite links, audit export A team's rules are evaluated alongside each member's own and the strictest answer wins (block > ask an admin decides > ask > allow); a team block can't be overridden and plan grants can't stand in for an admin. Calls a team rule reserves for an admin go to the team's owners and admins (decide path, notifier recipients, admin inbox); the member sees them waiting. Invite by single-use link, roles with a last-owner guard, team rules editor, and a formula-safe RFC 4180 audit CSV. Tasks, connections and memory stay personal. --- README.md | 3 +- apps/server/src/app.ts | 2 + apps/server/src/decisions.ts | 42 +- apps/server/src/http.ts | 5 +- apps/server/src/notify/notifier.ts | 28 +- apps/server/src/notify/types.ts | 3 + apps/server/src/routes/account.ts | 20 +- apps/server/src/routes/chats.ts | 1 + apps/server/src/routes/runs.ts | 3 + apps/server/src/routes/workspace.ts | 511 ++++ apps/server/src/teams.test.ts | 554 ++++ apps/web/app/(app)/inbox/page.tsx | 98 +- apps/web/app/(app)/settings/page.tsx | 17 +- apps/web/app/(app)/settings/policy-editor.tsx | 242 +- apps/web/app/(app)/settings/team.tsx | 446 +++ apps/web/app/(auth)/auth-form.tsx | 11 +- apps/web/app/join/[token]/join-team.tsx | 107 + apps/web/app/join/[token]/page.tsx | 9 + .../web/components/approval/approval-card.tsx | 234 +- apps/web/components/shell/mobile.tsx | 4 +- apps/web/components/shell/rail.tsx | 4 +- apps/web/components/task/task-view.tsx | 17 +- apps/web/lib/api.ts | 59 + apps/web/lib/workspace.tsx | 74 +- docs/api.md | 38 +- docs/teams.md | 114 + packages/core/src/memory-store.ts | 6 +- packages/core/src/policy.test.ts | 138 +- packages/core/src/policy.ts | 103 + packages/core/src/runtime.test.ts | 46 + packages/core/src/runtime.ts | 24 +- packages/core/src/store.ts | 7 +- packages/core/src/types.ts | 7 + packages/core/src/ui.ts | 4 + packages/db/drizzle/0006_teams.sql | 53 + packages/db/drizzle/meta/0006_snapshot.json | 2447 +++++++++++++++++ packages/db/drizzle/meta/_journal.json | 7 + packages/db/src/index.ts | 1 + packages/db/src/runs.ts | 80 +- packages/db/src/schema.ts | 77 + packages/db/src/store.ts | 4 + packages/db/src/workspaces.ts | 63 + 42 files changed, 5473 insertions(+), 240 deletions(-) create mode 100644 apps/server/src/routes/workspace.ts create mode 100644 apps/server/src/teams.test.ts create mode 100644 apps/web/app/(app)/settings/team.tsx create mode 100644 apps/web/app/join/[token]/join-team.tsx create mode 100644 apps/web/app/join/[token]/page.tsx create mode 100644 docs/teams.md create mode 100644 packages/db/drizzle/0006_teams.sql create mode 100644 packages/db/drizzle/meta/0006_snapshot.json create mode 100644 packages/db/src/workspaces.ts diff --git a/README.md b/README.md index c51656d..089381a 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Agent products that act in your tools share three problems: approvals that live - Several pending actions from one step can be ticked and signed off together - Approvals that learn: after you approve the same kind of action unchanged a few times, Synapse offers a visible, removable rule ("emails where every address is @acme.com"). Tasks that read outside content still ask - Undo window: approved sends and deletes wait a few seconds (default 10, configurable) with an Undo button +- Team workspaces: one set of rules for everyone in the team (the strictest answer wins, a team block can't be overridden), risky actions routed to an admin for sign-off, invite links, and a CSV audit export. Tasks, connections and memory stay personal ([how it works](docs/teams.md)) - Knowledge base: upload docs, hybrid full-text + vector search (pgvector, reciprocal rank fusion) - Memory you can read and edit; the agent can add notes, but not from a tainted run without asking - Web search (Tavily, Brave or Exa) and SSRF-guarded web fetch @@ -106,7 +107,7 @@ Defaults: `read` → allow, `write`/`send`/`destructive` → ask. Rules are eval ] ``` -Taint overrides `allow` for anything but reads. MCP tools inherit effects from their annotations (`readOnlyHint`, `destructiveHint`); tools that declare nothing are treated as destructive until you say otherwise on the Connections page. +Taint overrides `allow` for anything but reads. In a [team workspace](docs/teams.md), the team's rules are evaluated alongside yours and the strictest answer wins. MCP tools inherit effects from their annotations (`readOnlyHint`, `destructiveHint`); tools that declare nothing are treated as destructive until you say otherwise on the Connections page. ## Evals diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 725ee2c..d731708 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -9,6 +9,7 @@ import { googleCallback, integrations } from "./routes/integrations"; import { models } from "./routes/models"; import { approvals, runs } from "./routes/runs"; import { suggestions } from "./routes/suggestions"; +import { workspace } from "./routes/workspace"; import type { Services } from "./services"; export function createApp(services: Services) { @@ -74,6 +75,7 @@ export function createApp(services: Services) { api.route("/usage", usage); api.route("/models", models); api.route("/automations", automations); + api.route("/workspace", workspace); api.get("/me", (c) => c.json({ user: c.var.user })); app.route("/api", api); diff --git a/apps/server/src/decisions.ts b/apps/server/src/decisions.ts index 928741c..42c2123 100644 --- a/apps/server/src/decisions.ts +++ b/apps/server/src/decisions.ts @@ -1,5 +1,5 @@ -import { evaluatePolicy, type RunEvent, UNDO_DENIAL } from "@synapse/core"; -import { decideToolCalls, PgRunStore, schema, undoToolCall } from "@synapse/db"; +import { evaluateComposedPolicy, type RunEvent, UNDO_DENIAL } from "@synapse/core"; +import { assertMayDecide, decideToolCalls, PgRunStore, schema, undoToolCall } from "@synapse/db"; import type { JSONValue } from "ai"; import { and, eq } from "drizzle-orm"; import type { DecisionSource } from "./notify/types"; @@ -65,7 +65,9 @@ export async function decide( await services.notifier.resolved( decisions.map((d) => ({ - userId, + // Whose task it is; a team admin may have decided it for them. + userId: decided.ownerId, + decidedBy: userId, runId, toolCallId: d.toolCallId, approved: d.approved, @@ -96,7 +98,10 @@ export async function undo( await services.wake(args.runId); } -/** An edited input must not turn an allowed action into one the user's rules block. */ +/** + * An edited input must not turn an allowed action into one the requester's rules (or their + * team's) block, nor slip past a team rule that needs an admin. + */ async function assertEditAllowed( services: Services, userId: string, @@ -105,25 +110,42 @@ async function assertEditAllowed( input: JSONValue, ) { const { db } = services.database; + const [run] = await db + .select({ id: schema.runs.id, userId: schema.runs.userId }) + .from(schema.runs) + .where(eq(schema.runs.id, runId)); + if (!run) throw new DecisionInputError(404, "not_found", "Run not found."); + // Same check as the decision itself, so nobody learns about calls they can't decide. + await assertMayDecide(db, run, { userId, decisions: [{ toolCallId, approved: true }] }); const [call] = await db - .select({ name: schema.toolCalls.name, effect: schema.toolCalls.effect }) + .select({ + name: schema.toolCalls.name, + effect: schema.toolCalls.effect, + approver: schema.toolCalls.approver, + }) .from(schema.toolCalls) .where( and( eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.id, toolCallId), - eq(schema.toolCalls.userId, userId), + eq(schema.toolCalls.userId, run.userId), ), ); if (!call) throw new DecisionInputError(404, "not_found", "Action not found."); - const policy = await new PgRunStore(db).getPolicy(userId); - const verdict = evaluatePolicy( + const policy = await new PgRunStore(db).getPolicy(run.userId); + const verdict = evaluateComposedPolicy( { tool: call.name, effect: call.effect, input, tainted: true }, - policy.rules, - policy.defaults, + policy, + policy.teamRules, ); if (verdict.decision === "block") throw new DecisionInputError(422, "blocked", `The edited action is blocked: ${verdict.reason}`); + if (verdict.approver === "admin" && call.approver !== "admin") + throw new DecisionInputError( + 422, + "needs_admin", + "With that change, your team requires an admin to approve this.", + ); } export async function emitNow(services: Services, runId: string, event: RunEvent) { diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 9997599..783a99a 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -1,4 +1,4 @@ -import { ConflictError, NotFoundError } from "@synapse/db"; +import { ConflictError, ForbiddenError, NotFoundError } from "@synapse/db"; import type { Context } from "hono"; import { createMiddleware } from "hono/factory"; import { HTTPException } from "hono/http-exception"; @@ -54,6 +54,9 @@ export function onError(err: Error, c: Context): Response { } if (err instanceof NotFoundError) return c.json({ error: { code: "not_found", message: err.message } }, 404); + // e.g. a member deciding a call their team reserved for an admin. + if (err instanceof ForbiddenError) + return c.json({ error: { code: "forbidden", message: err.message } }, 403); if (err instanceof ConflictError) return c.json({ error: { code: "conflict", message: err.message } }, 409); log.error("unhandled", { path: c.req.path, error: err.stack ?? String(err) }); diff --git a/apps/server/src/notify/notifier.ts b/apps/server/src/notify/notifier.ts index aeff49b..e98e223 100644 --- a/apps/server/src/notify/notifier.ts +++ b/apps/server/src/notify/notifier.ts @@ -1,4 +1,4 @@ -import { schema } from "@synapse/db"; +import { membershipOf, schema, workspaceAdminIds } from "@synapse/db"; import { and, eq, inArray, isNull } from "drizzle-orm"; import { log } from "../log"; import type { Services } from "../services"; @@ -52,6 +52,7 @@ export class Notifier { input: schema.toolCalls.input, reason: schema.toolCalls.decisionReason, tainted: schema.runs.tainted, + approver: schema.toolCalls.approver, createdAt: schema.toolCalls.createdAt, }) .from(schema.toolCalls) @@ -66,11 +67,26 @@ export class Notifier { ), ), ); - const approvals: PendingApproval[] = rows.map((r) => ({ - ...r, - recipients: [r.userId], - url: `${config.PUBLIC_URL}/t/${r.chatId}`, - })); + // Team workspaces: a call a team rule reserves for an admin goes to the requester's + // workspace owners and admins (the requester too, if they are one), not to the + // requester. Everything else goes to the requester. Admins open it from their inbox. + // If the requester has left the team since, its rules no longer govern them: theirs again. + const recipientsFor = async (userId: string, approver: "admin" | null): Promise => { + if (approver !== "admin") return [userId]; + const membership = await membershipOf(db, userId); + return membership ? workspaceAdminIds(db, membership.workspaceId) : [userId]; + }; + const approvals: PendingApproval[] = await Promise.all( + rows.map(async ({ approver, ...r }) => ({ + ...r, + recipients: await recipientsFor(r.userId, approver), + // Admins can't open a member's task (tasks stay personal); they decide in the inbox. + url: + approver === "admin" + ? `${config.PUBLIC_URL}/inbox` + : `${config.PUBLIC_URL}/t/${r.chatId}`, + })), + ); await this.each("notify", (c) => c.notify(approvals)); return approvals; } diff --git a/apps/server/src/notify/types.ts b/apps/server/src/notify/types.ts index 0fce921..03c4b0b 100644 --- a/apps/server/src/notify/types.ts +++ b/apps/server/src/notify/types.ts @@ -30,7 +30,10 @@ export interface PendingApproval { /** What happened to an action, so channels can update what they showed (e.g. a Slack message). */ export interface ResolvedApproval { + /** Whose task it is. */ userId: string; + /** Who decided: the requester, or a team admin for calls a team rule reserves for one. */ + decidedBy?: string; runId: string; toolCallId: string; approved: boolean; diff --git a/apps/server/src/routes/account.ts b/apps/server/src/routes/account.ts index 929c035..939a1ad 100644 --- a/apps/server/src/routes/account.ts +++ b/apps/server/src/routes/account.ts @@ -24,7 +24,8 @@ const Defaults = z.object({ send: Decision, destructive: Decision, }); -const Rule = z.object({ +/** A personal policy rule; team rules (routes/workspace.ts) extend it. */ +export const Rule = z.object({ id: z.string().optional(), tool: z.string().min(1).max(128), decision: Decision, @@ -32,18 +33,23 @@ const Rule = z.object({ note: z.string().max(300).optional(), }); +/** Refuses rules whose regex patterns could hang the policy check. */ +export function assertSafePatterns(rules: z.infer[]) { + for (const rule of rules) { + for (const m of rule.when ?? []) { + const problem = m.op === "matches" ? unsafePatternReason(m.value) : null; + if (problem) apiError(422, "invalid_pattern", `Rule for ${rule.tool}: ${problem}`); + } + } +} + // ── Policy ───────────────────────────────────────────────────────────────── export const policy = new Hono() .get("/", async (c) => c.json(await loadPolicy(c.var.services.database.db, c.var.user.id))) .put("/", async (c) => { const input = await body(c, z.object({ defaults: Defaults, rules: z.array(Rule).max(200) })); - for (const rule of input.rules) { - for (const m of rule.when ?? []) { - const problem = m.op === "matches" ? unsafePatternReason(m.value) : null; - if (problem) apiError(422, "invalid_pattern", `Rule for ${rule.tool}: ${problem}`); - } - } + assertSafePatterns(input.rules); const { db } = c.var.services.database; const userId = c.var.user.id; await db.transaction(async (tx) => { diff --git a/apps/server/src/routes/chats.ts b/apps/server/src/routes/chats.ts index 445980f..e04cdd6 100644 --- a/apps/server/src/routes/chats.ts +++ b/apps/server/src/routes/chats.ts @@ -72,6 +72,7 @@ export const chats = new Hono() decisionReason: r.decisionReason, output: r.output, decidedBy: r.decidedBy, + approver: r.approver, preview: r.preview, executeAfter: r.executeAfter?.toISOString() ?? null, })) diff --git a/apps/server/src/routes/runs.ts b/apps/server/src/routes/runs.ts index 1a41804..1abbb31 100644 --- a/apps/server/src/routes/runs.ts +++ b/apps/server/src/routes/runs.ts @@ -51,6 +51,7 @@ export const runs = new Hono() inputEdited: schema.toolCalls.inputEdited, output: schema.toolCalls.output, decidedBy: schema.toolCalls.decidedBy, + approver: schema.toolCalls.approver, decidedAt: schema.toolCalls.decidedAt, executeAfter: schema.toolCalls.executeAfter, createdAt: schema.toolCalls.createdAt, @@ -200,6 +201,8 @@ export const approvals = new Hono().get("/", async (c) => { input: schema.toolCalls.input, reason: schema.toolCalls.decisionReason, preview: schema.toolCalls.preview, + /** "admin": the person's team requires an admin to decide; they only wait. */ + approver: schema.toolCalls.approver, createdAt: schema.toolCalls.createdAt, }) .from(schema.toolCalls) diff --git a/apps/server/src/routes/workspace.ts b/apps/server/src/routes/workspace.ts new file mode 100644 index 0000000..fe10713 --- /dev/null +++ b/apps/server/src/routes/workspace.ts @@ -0,0 +1,511 @@ +import { isAdminRole, loadTeamRules, membershipOf, schema } from "@synapse/db"; +import { and, asc, count, desc, eq, gt, gte, isNull, lt, sql } from "drizzle-orm"; +import { alias } from "drizzle-orm/pg-core"; +import { Hono } from "hono"; +import { z } from "zod"; +import { type AppEnv, apiError, body } from "../http"; +import { assertSafePatterns, Rule } from "./account"; + +/** + * Team workspaces: one shared set of rules on top of everyone's own, admin sign-off for + * risky actions, and an audit export. Tasks, connections and memory stay personal. + * + * Roles: owner (everything, incl. owners), admin (manage members, invites and rules; decide + * admin-required calls), member (read the team, its rules; leave). + */ + +type Role = schema.WorkspaceRole; +type Ctx = { var: AppEnv["Variables"] }; + +const Name = z.string().trim().min(1).max(80); +const TeamRule = Rule.extend({ approver: z.enum(["admin"]).nullable().optional() }); +const INVITE_DAYS = 7; +const AUDIT_MAX_ROWS = 50_000; + +async function membership(c: Ctx) { + const m = await membershipOf(c.var.services.database.db, c.var.user.id); + if (!m) apiError(404, "no_workspace", "You're not in a team workspace."); + return m; +} + +async function adminMembership(c: Ctx) { + const m = await membership(c); + if (!isAdminRole(m.role)) apiError(403, "forbidden", "Only team owners and admins can do that."); + return m; +} + +async function loadWorkspace(c: Ctx, workspaceId: string, role: Role) { + const { db } = c.var.services.database; + const [workspace] = await db + .select({ + id: schema.workspaces.id, + name: schema.workspaces.name, + createdAt: schema.workspaces.createdAt, + }) + .from(schema.workspaces) + .where(eq(schema.workspaces.id, workspaceId)); + const members = await db + .select({ + userId: schema.workspaceMembers.userId, + name: schema.user.name, + email: schema.user.email, + role: schema.workspaceMembers.role, + joinedAt: schema.workspaceMembers.joinedAt, + }) + .from(schema.workspaceMembers) + .innerJoin(schema.user, eq(schema.user.id, schema.workspaceMembers.userId)) + .where(eq(schema.workspaceMembers.workspaceId, workspaceId)) + .orderBy(asc(schema.workspaceMembers.joinedAt)); + return { workspace, role, members }; +} + +/** Invite tokens: 32 random bytes, base64url. Only the SHA-256 is stored. */ +function newToken(): string { + return Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url"); +} + +async function hashToken(token: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)); + return Buffer.from(digest).toString("hex"); +} + +function inviteStatus(i: { + usedAt: Date | null; + revokedAt: Date | null; + expiresAt: Date; +}): "used" | "revoked" | "expired" | "active" { + if (i.usedAt) return "used"; + if (i.revokedAt) return "revoked"; + if (i.expiresAt.getTime() <= Date.now()) return "expired"; + return "active"; +} + +export const workspace = new Hono() + // ── Workspace ──────────────────────────────────────────────────────────── + .get("/", async (c) => { + const m = await membershipOf(c.var.services.database.db, c.var.user.id); + if (!m) return c.json({ workspace: null, role: null, members: [] }); + return c.json(await loadWorkspace(c, m.workspaceId, m.role)); + }) + + .post("/", async (c) => { + const { name } = await body(c, z.object({ name: Name })); + const { db } = c.var.services.database; + const userId = c.var.user.id; + if (await membershipOf(db, userId)) + apiError(409, "already_member", "You're already in a team workspace. Leave it first."); + const workspaceId = await db.transaction(async (tx) => { + const [ws] = await tx + .insert(schema.workspaces) + .values({ name, createdBy: userId }) + .returning({ id: schema.workspaces.id }); + // The unique user_id makes a concurrent second create fail here, not succeed twice. + await tx + .insert(schema.workspaceMembers) + .values({ workspaceId: ws!.id, userId, role: "owner" }); + return ws!.id; + }); + return c.json(await loadWorkspace(c, workspaceId, "owner"), 201); + }) + + .patch("/", async (c) => { + const { name } = await body(c, z.object({ name: Name })); + const m = await adminMembership(c); + await c.var.services.database.db + .update(schema.workspaces) + .set({ name }) + .where(eq(schema.workspaces.id, m.workspaceId)); + return c.json(await loadWorkspace(c, m.workspaceId, m.role)); + }) + + // ── Invites ────────────────────────────────────────────────────────────── + .post("/invites", async (c) => { + const input = await body( + c, + z.object({ + role: z.enum(["admin", "member"]).default("member"), + expiresInDays: z.number().int().min(1).max(30).default(INVITE_DAYS), + }), + ); + const m = await adminMembership(c); + const token = newToken(); + const [invite] = await c.var.services.database.db + .insert(schema.workspaceInvites) + .values({ + workspaceId: m.workspaceId, + tokenHash: await hashToken(token), + role: input.role, + expiresAt: new Date(Date.now() + input.expiresInDays * 24 * 3600_000), + createdBy: c.var.user.id, + }) + .returning({ + id: schema.workspaceInvites.id, + role: schema.workspaceInvites.role, + expiresAt: schema.workspaceInvites.expiresAt, + createdAt: schema.workspaceInvites.createdAt, + }); + // The token is only ever shown here. + const link = `${c.var.services.config.PUBLIC_URL}/join/${token}`; + return c.json({ invite: { ...invite, status: "active" }, link }, 201); + }) + + .get("/invites", async (c) => { + const m = await adminMembership(c); + const usedBy = alias(schema.user, "used_by_user"); + const rows = await c.var.services.database.db + .select({ + id: schema.workspaceInvites.id, + role: schema.workspaceInvites.role, + expiresAt: schema.workspaceInvites.expiresAt, + createdAt: schema.workspaceInvites.createdAt, + usedAt: schema.workspaceInvites.usedAt, + revokedAt: schema.workspaceInvites.revokedAt, + usedByEmail: usedBy.email, + }) + .from(schema.workspaceInvites) + .leftJoin(usedBy, eq(usedBy.id, schema.workspaceInvites.usedBy)) + .where(eq(schema.workspaceInvites.workspaceId, m.workspaceId)) + .orderBy(desc(schema.workspaceInvites.createdAt)) + .limit(100); + return c.json({ invites: rows.map((r) => ({ ...r, status: inviteStatus(r) })) }); + }) + + .delete("/invites/:id", async (c) => { + const m = await adminMembership(c); + await c.var.services.database.db + .update(schema.workspaceInvites) + .set({ revokedAt: new Date() }) + .where( + and( + eq(schema.workspaceInvites.id, c.req.param("id")), + eq(schema.workspaceInvites.workspaceId, m.workspaceId), + isNull(schema.workspaceInvites.usedAt), + isNull(schema.workspaceInvites.revokedAt), + ), + ); + return c.body(null, 204); + }) + + .post("/join", async (c) => { + const { token } = await body(c, z.object({ token: z.string().min(16).max(200) })); + const { db } = c.var.services.database; + const userId = c.var.user.id; + const tokenHash = await hashToken(token); + const [invite] = await db + .select() + .from(schema.workspaceInvites) + .where(eq(schema.workspaceInvites.tokenHash, tokenHash)); + if (!invite) apiError(404, "invite_not_found", "This invite link isn't valid."); + const status = inviteStatus(invite); + if (status !== "active") + apiError( + 409, + `invite_${status}`, + status === "used" + ? "This invite link has already been used." + : status === "revoked" + ? "This invite link was revoked." + : "This invite link has expired.", + ); + const current = await membershipOf(db, userId); + if (current) + apiError( + 409, + current.workspaceId === invite.workspaceId ? "already_joined" : "already_member", + current.workspaceId === invite.workspaceId + ? "You're already in this team." + : "You're already in a team workspace. Leave it first.", + ); + + await db.transaction(async (tx) => { + // Single use: claim the invite with a compare-and-set, so two people can't share one. + const claimed = await tx + .update(schema.workspaceInvites) + .set({ usedBy: userId, usedAt: new Date() }) + .where( + and( + eq(schema.workspaceInvites.id, invite.id), + isNull(schema.workspaceInvites.usedAt), + isNull(schema.workspaceInvites.revokedAt), + gt(schema.workspaceInvites.expiresAt, new Date()), + ), + ) + .returning({ id: schema.workspaceInvites.id }); + if (claimed.length === 0) + apiError(409, "invite_used", "This invite link is no longer valid."); + await tx + .insert(schema.workspaceMembers) + .values({ workspaceId: invite.workspaceId, userId, role: invite.role }); + }); + return c.json(await loadWorkspace(c, invite.workspaceId, invite.role)); + }) + + // ── Members ────────────────────────────────────────────────────────────── + .patch("/members/:userId", async (c) => { + const { role } = await body(c, z.object({ role: z.enum(["owner", "admin", "member"]) })); + const m = await adminMembership(c); + const targetId = c.req.param("userId"); + const { db } = c.var.services.database; + await db.transaction(async (tx) => { + // Lock the team's memberships so two demotions can't both pass the last-owner check. + const members = await tx + .select({ userId: schema.workspaceMembers.userId, role: schema.workspaceMembers.role }) + .from(schema.workspaceMembers) + .where(eq(schema.workspaceMembers.workspaceId, m.workspaceId)) + .for("update"); + const target = members.find((x) => x.userId === targetId); + if (!target) apiError(404, "not_found", "That person isn't in your team."); + if (m.role !== "owner" && (role === "owner" || target.role === "owner")) + apiError(403, "forbidden", "Only an owner can make or change owners."); + const owners = members.filter((x) => x.role === "owner").length; + if (target.role === "owner" && role !== "owner" && owners <= 1) + apiError( + 409, + "last_owner", + "A team needs at least one owner. Make someone else owner first.", + ); + await tx + .update(schema.workspaceMembers) + .set({ role }) + .where( + and( + eq(schema.workspaceMembers.workspaceId, m.workspaceId), + eq(schema.workspaceMembers.userId, targetId), + ), + ); + }); + const after = await membership(c); + return c.json(await loadWorkspace(c, after.workspaceId, after.role)); + }) + + .delete("/members/:userId", async (c) => { + const m = await membership(c); + const targetId = c.req.param("userId"); + const self = targetId === c.var.user.id; + if (!self && !isAdminRole(m.role)) + apiError(403, "forbidden", "Only team owners and admins can remove people."); + const { db } = c.var.services.database; + await db.transaction(async (tx) => { + const members = await tx + .select({ userId: schema.workspaceMembers.userId, role: schema.workspaceMembers.role }) + .from(schema.workspaceMembers) + .where(eq(schema.workspaceMembers.workspaceId, m.workspaceId)) + .for("update"); + const target = members.find((x) => x.userId === targetId); + if (!target) apiError(404, "not_found", "That person isn't in your team."); + if (!self && target.role === "owner" && m.role !== "owner") + apiError(403, "forbidden", "Only an owner can remove an owner."); + // The last person out takes the workspace with them; otherwise someone must own it. + if (members.length === 1) { + await tx.delete(schema.workspaces).where(eq(schema.workspaces.id, m.workspaceId)); + return; + } + if (target.role === "owner" && members.filter((x) => x.role === "owner").length <= 1) + apiError( + 409, + "last_owner", + "A team needs at least one owner. Make someone else owner first.", + ); + await tx + .delete(schema.workspaceMembers) + .where( + and( + eq(schema.workspaceMembers.workspaceId, m.workspaceId), + eq(schema.workspaceMembers.userId, targetId), + ), + ); + }); + return c.body(null, 204); + }) + + // ── Team rules ─────────────────────────────────────────────────────────── + .get("/rules", async (c) => { + const m = await membership(c); + const rules = await loadTeamRules(c.var.services.database.db, m.workspaceId); + return c.json({ rules, canEdit: isAdminRole(m.role) }); + }) + + .put("/rules", async (c) => { + const input = await body(c, z.object({ rules: z.array(TeamRule).max(200) })); + const m = await adminMembership(c); + assertSafePatterns(input.rules); + const { db } = c.var.services.database; + await db.transaction(async (tx) => { + await tx + .delete(schema.workspaceRules) + .where(eq(schema.workspaceRules.workspaceId, m.workspaceId)); + if (input.rules.length > 0) { + await tx.insert(schema.workspaceRules).values( + input.rules.map((r, position) => ({ + workspaceId: m.workspaceId, + position, + tool: r.tool, + decision: r.decision, + when: r.when ?? null, + note: r.note ?? null, + // An approver only means something on an ask. + approver: r.decision === "ask" && r.approver === "admin" ? ("admin" as const) : null, + })), + ); + } + }); + return c.json({ rules: await loadTeamRules(db, m.workspaceId), canEdit: true }); + }) + + // ── Admin inbox ────────────────────────────────────────────────────────── + .get("/approvals", async (c) => { + const m = await adminMembership(c); + const rows = await c.var.services.database.db + .select({ + runId: schema.toolCalls.runId, + chatId: schema.runs.chatId, + chatTitle: schema.chats.title, + toolCallId: schema.toolCalls.id, + name: schema.toolCalls.name, + effect: schema.toolCalls.effect, + input: schema.toolCalls.input, + reason: schema.toolCalls.decisionReason, + preview: schema.toolCalls.preview, + approver: schema.toolCalls.approver, + createdAt: schema.toolCalls.createdAt, + requester: { + id: schema.user.id, + name: schema.user.name, + email: schema.user.email, + }, + }) + .from(schema.toolCalls) + .innerJoin( + schema.workspaceMembers, + and( + eq(schema.workspaceMembers.userId, schema.toolCalls.userId), + eq(schema.workspaceMembers.workspaceId, m.workspaceId), + ), + ) + .innerJoin(schema.user, eq(schema.user.id, schema.toolCalls.userId)) + .innerJoin(schema.runs, eq(schema.runs.id, schema.toolCalls.runId)) + .innerJoin(schema.chats, eq(schema.chats.id, schema.runs.chatId)) + .where( + and( + eq(schema.toolCalls.status, "awaiting_approval"), + eq(schema.toolCalls.approver, "admin"), + ), + ) + .orderBy(desc(schema.toolCalls.createdAt)); + return c.json({ approvals: rows }); + }) + + // ── Audit export ───────────────────────────────────────────────────────── + .get("/audit.csv", async (c) => { + const m = await adminMembership(c); + const { from, to } = auditRange(c.req.query("from"), c.req.query("to")); + const decider = alias(schema.user, "decider"); + const { db } = c.var.services.database; + const where = and( + gte(schema.toolCalls.createdAt, from), + lt(schema.toolCalls.createdAt, to), + // Only what a member did while in the team, not their history from before. + gte(schema.toolCalls.createdAt, schema.workspaceMembers.joinedAt), + ); + const membersJoin = and( + eq(schema.workspaceMembers.userId, schema.toolCalls.userId), + eq(schema.workspaceMembers.workspaceId, m.workspaceId), + ); + const [{ total } = { total: 0 }] = await db + .select({ total: count() }) + .from(schema.toolCalls) + .innerJoin(schema.workspaceMembers, membersJoin) + .where(where); + if (total > AUDIT_MAX_ROWS) + apiError( + 422, + "too_many_rows", + `That range has ${total} actions; export at most ${AUDIT_MAX_ROWS} at a time.`, + ); + const rows = await db + .select({ + time: schema.toolCalls.createdAt, + member: schema.user.email, + task: schema.chats.title, + tool: schema.toolCalls.name, + effect: schema.toolCalls.effect, + decision: schema.toolCalls.decision, + status: schema.toolCalls.status, + decidedBy: decider.email, + decidedVia: schema.toolCalls.decidedVia, + reason: schema.toolCalls.decisionReason, + }) + .from(schema.toolCalls) + .innerJoin(schema.workspaceMembers, membersJoin) + .innerJoin(schema.user, eq(schema.user.id, schema.toolCalls.userId)) + .innerJoin(schema.runs, eq(schema.runs.id, schema.toolCalls.runId)) + .innerJoin(schema.chats, eq(schema.chats.id, schema.runs.chatId)) + .leftJoin(decider, eq(decider.id, schema.toolCalls.decidedBy)) + .where(where) + .orderBy(asc(schema.toolCalls.createdAt), sql`${schema.toolCalls.id}`); + const csv = toCsv( + [ + "time", + "member", + "task", + "tool", + "effect", + "decision", + "status", + "decided_by", + "decided_via", + "reason", + ], + rows.map((r) => [ + r.time.toISOString(), + r.member, + r.task, + r.tool, + r.effect, + r.decision, + r.status, + r.decidedBy, + r.decidedVia, + r.reason, + ]), + ); + const day = (d: Date) => d.toISOString().slice(0, 10); + return c.body(csv, 200, { + "content-type": "text/csv; charset=utf-8", + "content-disposition": `attachment; filename="synapse-audit-${day(from)}-to-${day(new Date(to.getTime() - 1))}.csv"`, + "cache-control": "no-store", + }); + }); + +/** + * `from` and `to` are dates (YYYY-MM-DD, `to` inclusive) or ISO times. Default: the last + * 30 days. At most a year at a time. + */ +export function auditRange(fromQ?: string, toQ?: string): { from: Date; to: Date } { + const parse = (q: string, endOfDay: boolean) => { + const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(q); + const d = new Date(dateOnly ? `${q}T00:00:00.000Z` : q); + if (Number.isNaN(d.getTime())) apiError(422, "invalid_date", `Not a date: ${q}`); + return dateOnly && endOfDay ? new Date(d.getTime() + 24 * 3600_000) : d; + }; + const to = toQ ? parse(toQ, true) : new Date(); + const from = fromQ ? parse(fromQ, false) : new Date(to.getTime() - 30 * 24 * 3600_000); + if (from >= to) apiError(422, "invalid_range", "`from` must be before `to`."); + if (to.getTime() - from.getTime() > 366 * 24 * 3600_000) + apiError(422, "invalid_range", "Export at most a year at a time."); + return { from, to }; +} + +/** + * RFC 4180 CSV (CRLF line ends, fields with quotes, commas or line breaks quoted, quotes + * doubled). Cells that a spreadsheet would run as a formula (= + - @, tab, CR) get a + * leading `'`: tool inputs and task titles come from the model and from outside content. + */ +export function toCsv(header: string[], rows: (string | null | undefined)[][]): string { + const cell = (value: string | null | undefined) => { + let s = value ?? ""; + if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`; + return /[",\r\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s; + }; + return `${[header, ...rows].map((r) => r.map(cell).join(",")).join("\r\n")}\r\n`; +} diff --git a/apps/server/src/teams.test.ts b/apps/server/src/teams.test.ts new file mode 100644 index 0000000..efe0fa8 --- /dev/null +++ b/apps/server/src/teams.test.ts @@ -0,0 +1,554 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { type ScriptedStep, scriptedModel } from "@synapse/core/testing"; +import { schema } from "@synapse/db"; +import { and, eq } from "drizzle-orm"; +import { createApp } from "./app"; +import { loadConfig } from "./config"; +import type { PendingApproval, ResolvedApproval } from "./notify/types"; +import { auditRange, toCsv } from "./routes/workspace"; +import { createServices, type Services } from "./services"; +import { Worker } from "./worker"; + +const ORIGIN = "http://localhost:3000"; +let services: Services; +let app: ReturnType; +let worker: Worker; +let model = scriptedModel([]); +const script = (steps: ScriptedStep[]) => { + model = scriptedModel(steps); +}; +const seen: PendingApproval[] = []; +const resolved: ResolvedApproval[] = []; + +beforeAll(async () => { + services = await createServices( + loadConfig({ + NODE_ENV: "test", + DATABASE_URL: "pglite://memory", + SYNAPSE_SECRET: "t".repeat(40), + PUBLIC_URL: ORIGIN, + }), + ); + app = createApp(services); + worker = new Worker(services, () => [model]); + services.notifier.add({ + name: "test", + notify: async (a) => { + seen.push(...a); + }, + resolved: async (r) => { + resolved.push(...r); + }, + }); +}); +afterAll(() => services.close()); + +interface Person { + id: string; + email: string; + call: ( + path: string, + init?: { method?: string; json?: unknown }, + ) => Promise<{ + status: number; + // biome-ignore lint/suspicious/noExplicitAny: test responses are loosely typed JSON + json: any; + text: string; + headers: Headers; + }>; +} + +async function signUp(email: string): Promise { + const res = await app.request("/api/auth/sign-up/email", { + method: "POST", + headers: { "content-type": "application/json", origin: ORIGIN }, + body: JSON.stringify({ email, password: "correct horse battery", name: email.split("@")[0] }), + }); + expect(res.status).toBe(200); + const { user } = (await res.json()) as { user: { id: string } }; + const cookie = res.headers + .getSetCookie() + .map((c) => c.split(";")[0]) + .join("; "); + return { + id: user.id, + email, + call: async (path, init = {}) => { + const r = await app.request(path, { + method: init.method ?? "GET", + headers: { + cookie, + origin: ORIGIN, + ...(init.json !== undefined ? { "content-type": "application/json" } : {}), + }, + ...(init.json !== undefined ? { body: JSON.stringify(init.json) } : {}), + }); + const text = await r.text(); + let json = null; + try { + json = text ? JSON.parse(text) : null; + } catch {} + return { status: r.status, json, text, headers: r.headers }; + }, + }; +} + +/** Creates an invite as `admin` and joins it as `who`. */ +async function invite(admin: Person, who: Person, role: "admin" | "member" = "member") { + const created = await admin.call("/api/workspace/invites", { method: "POST", json: { role } }); + expect(created.status).toBe(201); + const token = (created.json.link as string).split("/join/")[1]!; + const joined = await who.call("/api/workspace/join", { method: "POST", json: { token } }); + expect(joined.status).toBe(200); + return token; +} + +describe("workspaces", () => { + test("create, invite by link, join; bad tokens are refused", async () => { + const owner = await signUp("owner@acme.com"); + const ann = await signUp("ann@acme.com"); + const bo = await signUp("bo@acme.com"); + const cy = await signUp("cy@acme.com"); + + expect((await owner.call("/api/workspace")).json).toEqual({ + workspace: null, + role: null, + members: [], + }); + expect( + (await owner.call("/api/workspace", { method: "POST", json: { name: " " } })).status, + ).toBe(422); + const created = await owner.call("/api/workspace", { + method: "POST", + json: { name: "Acme" }, + }); + expect(created.status).toBe(201); + expect(created.json).toMatchObject({ + workspace: { name: "Acme" }, + role: "owner", + members: [{ userId: owner.id, email: "owner@acme.com", role: "owner" }], + }); + // One workspace per person. + expect( + (await owner.call("/api/workspace", { method: "POST", json: { name: "Again" } })).status, + ).toBe(409); + + // The link carries the token once; only its hash is stored. + const res = await owner.call("/api/workspace/invites", { method: "POST", json: {} }); + expect(res.status).toBe(201); + expect(res.json.link).toMatch(new RegExp(`^${ORIGIN}/join/[A-Za-z0-9_-]{40,}$`)); + const token = res.json.link.split("/join/")[1]; + const [stored] = await services.database.db + .select() + .from(schema.workspaceInvites) + .where(eq(schema.workspaceInvites.id, res.json.invite.id)); + expect(stored!.tokenHash).not.toContain(token); + expect(JSON.stringify((await owner.call("/api/workspace/invites")).json)).not.toContain(token); + + expect( + (await ann.call("/api/workspace/join", { method: "POST", json: { token: "x".repeat(43) } })) + .status, + ).toBe(404); + const join = await ann.call("/api/workspace/join", { method: "POST", json: { token } }); + expect(join.status).toBe(200); + expect(join.json.role).toBe("member"); + // Used: single use. + const reused = await bo.call("/api/workspace/join", { method: "POST", json: { token } }); + expect(reused).toMatchObject({ status: 409, json: { error: { code: "invite_used" } } }); + + // Revoked. + const r2 = await owner.call("/api/workspace/invites", { method: "POST", json: {} }); + expect( + (await owner.call(`/api/workspace/invites/${r2.json.invite.id}`, { method: "DELETE" })) + .status, + ).toBe(204); + const revoked = await bo.call("/api/workspace/join", { + method: "POST", + json: { token: r2.json.link.split("/join/")[1] }, + }); + expect(revoked).toMatchObject({ status: 409, json: { error: { code: "invite_revoked" } } }); + + // Expired. + const r3 = await owner.call("/api/workspace/invites", { method: "POST", json: {} }); + await services.database.db + .update(schema.workspaceInvites) + .set({ expiresAt: new Date(Date.now() - 1000) }) + .where(eq(schema.workspaceInvites.id, r3.json.invite.id)); + const expired = await bo.call("/api/workspace/join", { + method: "POST", + json: { token: r3.json.link.split("/join/")[1] }, + }); + expect(expired).toMatchObject({ status: 409, json: { error: { code: "invite_expired" } } }); + + const list = (await owner.call("/api/workspace/invites")).json.invites; + expect(list.map((i: { status: string }) => i.status).sort()).toEqual([ + "expired", + "revoked", + "used", + ]); + + // Members can't invite; strangers can't see anything. + expect((await ann.call("/api/workspace/invites", { method: "POST", json: {} })).status).toBe( + 403, + ); + expect((await ann.call("/api/workspace/invites")).status).toBe(403); + expect((await cy.call("/api/workspace/rules")).status).toBe(404); + expect((await ann.call("/api/workspace")).json.members).toHaveLength(2); + }); + + test("roles: last owner stays, admins can't make owners, members can't write rules", async () => { + const owner = await signUp("o@roles.com"); + const admin = await signUp("a@roles.com"); + const member = await signUp("m@roles.com"); + await owner.call("/api/workspace", { method: "POST", json: { name: "Roles" } }); + await invite(owner, admin, "admin"); + await invite(admin, member); + + // The last owner can't leave or step down. + const leave = await owner.call(`/api/workspace/members/${owner.id}`, { method: "DELETE" }); + expect(leave).toMatchObject({ status: 409, json: { error: { code: "last_owner" } } }); + const demote = await owner.call(`/api/workspace/members/${owner.id}`, { + method: "PATCH", + json: { role: "admin" }, + }); + expect(demote).toMatchObject({ status: 409, json: { error: { code: "last_owner" } } }); + + // Admins manage members and admins, never owners. + expect( + ( + await admin.call(`/api/workspace/members/${member.id}`, { + method: "PATCH", + json: { role: "owner" }, + }) + ).status, + ).toBe(403); + expect( + ( + await admin.call(`/api/workspace/members/${owner.id}`, { + method: "PATCH", + json: { role: "member" }, + }) + ).status, + ).toBe(403); + expect( + (await admin.call(`/api/workspace/members/${owner.id}`, { method: "DELETE" })).status, + ).toBe(403); + // Members can't change or remove anyone, or rename the team. + expect( + ( + await member.call(`/api/workspace/members/${admin.id}`, { + method: "PATCH", + json: { role: "member" }, + }) + ).status, + ).toBe(403); + expect( + (await member.call("/api/workspace", { method: "PATCH", json: { name: "X" } })).status, + ).toBe(403); + expect( + (await admin.call("/api/workspace", { method: "PATCH", json: { name: "Roles Inc" } })).json + .workspace.name, + ).toBe("Roles Inc"); + + // Members can read team rules but not write them. + const put = await member.call("/api/workspace/rules", { + method: "PUT", + json: { rules: [{ tool: "*", decision: "allow" }] }, + }); + expect(put.status).toBe(403); + expect((await member.call("/api/workspace/rules")).json).toEqual({ rules: [], canEdit: false }); + // Rules are validated like personal ones, incl. regex safety. + const unsafe = await admin.call("/api/workspace/rules", { + method: "PUT", + json: { + rules: [ + { tool: "*", decision: "block", when: [{ path: "q", op: "matches", value: "(a+)+$" }] }, + ], + }, + }); + expect(unsafe).toMatchObject({ status: 422, json: { error: { code: "invalid_pattern" } } }); + const ok = await admin.call("/api/workspace/rules", { + method: "PUT", + json: { + rules: [ + { tool: "gmail_*", decision: "ask", approver: "admin", note: "Outside email" }, + { tool: "web_*", decision: "allow", approver: "admin" }, + ], + }, + }); + expect(ok.status).toBe(200); + expect(ok.json.rules).toEqual([ + expect.objectContaining({ tool: "gmail_*", decision: "ask", approver: "admin" }), + expect.not.objectContaining({ approver: "admin" }), + ]); + + // An owner can hand over ownership, then step down. + expect( + ( + await owner.call(`/api/workspace/members/${admin.id}`, { + method: "PATCH", + json: { role: "owner" }, + }) + ).status, + ).toBe(200); + const stepped = await owner.call(`/api/workspace/members/${owner.id}`, { + method: "PATCH", + json: { role: "member" }, + }); + expect(stepped.json.role).toBe("member"); + + // Anyone may leave; an admin may remove a member. + expect( + (await admin.call(`/api/workspace/members/${member.id}`, { method: "DELETE" })).status, + ).toBe(204); + expect((await member.call("/api/workspace")).json.workspace).toBeNull(); + expect( + (await owner.call(`/api/workspace/members/${owner.id}`, { method: "DELETE" })).status, + ).toBe(204); + // The last person out takes the workspace with them. + expect( + (await admin.call(`/api/workspace/members/${admin.id}`, { method: "DELETE" })).status, + ).toBe(204); + expect( + await services.database.db + .select() + .from(schema.workspaces) + .where(eq(schema.workspaces.name, "Roles Inc")), + ).toEqual([]); + }); + + test("an admin-required call: the member waits, admins are told, an admin decides", async () => { + const owner = await signUp("boss@team.com"); + const admin = await signUp("lead@team.com"); + const member = await signUp("dev@team.com"); + const outsider = await signUp("x@other.com"); + await owner.call("/api/workspace", { method: "POST", json: { name: "Team" } }); + await invite(owner, admin, "admin"); + await invite(owner, member); + await owner.call("/api/workspace/rules", { + method: "PUT", + json: { rules: [{ tool: "memory_save", decision: "ask", approver: "admin" }] }, + }); + // The member's own rules allow everything: the team's admin rule still wins. + await member.call("/api/policy", { + method: "PUT", + json: { + defaults: { read: "allow", write: "allow", send: "allow", destructive: "allow" }, + rules: [{ tool: "*", decision: "allow" }], + }, + }); + + seen.length = 0; + resolved.length = 0; + script([ + { toolCalls: [{ name: "memory_save", input: { note: "=HYPERLINK(1)" }, id: "t1" }] }, + { text: "Saved." }, + ]); + const { json } = await member.call("/api/chats", { + method: "POST", + json: { content: '+remember, "quoted"' }, + }); + const runId = json.runId as string; + await worker.processNow(runId); + + const [row] = await services.database.db + .select() + .from(schema.toolCalls) + .where(and(eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.id, "t1"))); + expect(row).toMatchObject({ + status: "awaiting_approval", + approver: "admin", + decisionReason: "Your team requires an admin to approve this.", + }); + + // Notification channels hear about it for the owner and admin, not the member. + expect(seen).toHaveLength(1); + expect(seen[0]!.userId).toBe(member.id); + expect(seen[0]!.recipients.sort()).toEqual([owner.id, admin.id].sort()); + expect(seen[0]!.url).toBe(`${ORIGIN}/inbox`); + + // The member sees it waiting; they can't decide it. + const mine = (await member.call("/api/approvals")).json.approvals; + expect(mine).toEqual([expect.objectContaining({ toolCallId: "t1", approver: "admin" })]); + const path = `/api/runs/${runId}/tool-calls/t1/decision`; + const self = await member.call(path, { method: "POST", json: { approved: true } }); + expect(self.status).toBe(403); + expect( + ( + await member.call(`/api/runs/${runId}/tool-calls/decisions`, { + method: "POST", + json: { decisions: [{ toolCallId: "t1", approved: true }] }, + }) + ).status, + ).toBe(403); + // Someone outside the team can't either, and learns nothing. + expect((await outsider.call(path, { method: "POST", json: { approved: true } })).status).toBe( + 404, + ); + + // Admins see it in the team inbox, with who asked; members can't open that inbox. + expect((await member.call("/api/workspace/approvals")).status).toBe(403); + const inbox = (await admin.call("/api/workspace/approvals")).json.approvals; + expect(inbox).toEqual([ + expect.objectContaining({ + runId, + toolCallId: "t1", + requester: expect.objectContaining({ id: member.id, email: "dev@team.com" }), + }), + ]); + + // An admin can't edit it into something the member's rules or the team block. + await owner.call("/api/workspace/rules", { + method: "PUT", + json: { + rules: [ + { tool: "memory_save", decision: "ask", approver: "admin" }, + { + tool: "memory_save", + decision: "block", + when: [{ path: "note", op: "equals", value: "secret" }], + }, + ], + }, + }); + const edited = await admin.call(path, { + method: "POST", + json: { approved: true, input: { note: "secret" } }, + }); + expect(edited.status).toBe(422); + + // The admin decides; the run resumes. + const ok = await admin.call(path, { method: "POST", json: { approved: true } }); + expect(ok.status).toBe(200); + expect((await admin.call(path, { method: "POST", json: { approved: true } })).status).toBe(409); + expect(resolved).toEqual([ + expect.objectContaining({ toolCallId: "t1", userId: member.id, decidedBy: admin.id }), + ]); + await worker.processNow(runId); + const detail = await member.call(`/api/runs/${runId}`); + expect(detail.json.run.status).toBe("completed"); + expect(detail.json.toolCalls[0]).toMatchObject({ + status: "succeeded", + decidedBy: admin.id, + approver: "admin", + }); + expect((await admin.call("/api/workspace/approvals")).json.approvals).toEqual([]); + + // Admins still can't decide a member's ordinary calls. + await owner.call("/api/workspace/rules", { method: "PUT", json: { rules: [] } }); + await member.call("/api/policy", { + method: "PUT", + json: { + defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" }, + rules: [{ tool: "memory_save", decision: "ask" }], + }, + }); + script([ + { toolCalls: [{ name: "memory_save", input: { note: "x" }, id: "t2" }] }, + { text: "ok" }, + ]); + const second = await member.call("/api/chats", { method: "POST", json: { content: "again" } }); + await worker.processNow(second.json.runId); + const p2 = `/api/runs/${second.json.runId}/tool-calls/t2/decision`; + expect((await admin.call(p2, { method: "POST", json: { approved: true } })).status).toBe(404); + expect((await member.call(p2, { method: "POST", json: { approved: false } })).status).toBe(200); + + // Audit export: admins only, every member's calls, CSV-safe. + expect((await member.call("/api/workspace/audit.csv")).status).toBe(403); + const csv = await admin.call("/api/workspace/audit.csv"); + expect(csv.status).toBe(200); + expect(csv.headers.get("content-type")).toContain("text/csv"); + expect(csv.headers.get("content-disposition")).toContain("attachment"); + const lines = csv.text.split("\r\n"); + expect(lines[0]).toBe( + "time,member,task,tool,effect,decision,status,decided_by,decided_via,reason", + ); + const t1 = lines.find((l) => l.includes("memory_save") && l.includes("lead@team.com"))!; + expect(t1).toContain("dev@team.com"); + // A task title starting with + is neutralised and quoted (it has a comma and quotes). + expect(t1).toContain(`"'+remember, ""quoted"""`); + expect(t1).toContain(",web,Your team requires an admin to approve this."); + expect(lines.filter((l) => l.includes("dev@team.com"))).toHaveLength(2); + expect(csv.text).not.toContain("x@other.com"); + expect((await admin.call("/api/workspace/audit.csv?from=2020-01-01&to=2020-01-02")).text).toBe( + "time,member,task,tool,effect,decision,status,decided_by,decided_via,reason\r\n", + ); + expect((await admin.call("/api/workspace/audit.csv?from=nope")).status).toBe(422); + }); + + test("an admin decides their own admin-required calls", async () => { + const owner = await signUp("solo@own.com"); + await owner.call("/api/workspace", { method: "POST", json: { name: "Solo" } }); + await owner.call("/api/workspace/rules", { + method: "PUT", + json: { rules: [{ tool: "memory_save", decision: "ask", approver: "admin" }] }, + }); + script([ + { toolCalls: [{ name: "memory_save", input: { note: "n" }, id: "s1" }] }, + { text: "done" }, + ]); + const { json } = await owner.call("/api/chats", { method: "POST", json: { content: "go" } }); + await worker.processNow(json.runId); + const approval = seen.find((a) => a.toolCallId === "s1")!; + expect(approval.recipients).toEqual([owner.id]); + expect( + ( + await owner.call(`/api/runs/${json.runId}/tool-calls/s1/decision`, { + method: "POST", + json: { approved: true }, + }) + ).status, + ).toBe(200); + }); + + test("after leaving the team, a member decides their own waiting call", async () => { + const owner = await signUp("o@left.com"); + const member = await signUp("m@left.com"); + await owner.call("/api/workspace", { method: "POST", json: { name: "Left" } }); + await invite(owner, member); + await owner.call("/api/workspace/rules", { + method: "PUT", + json: { rules: [{ tool: "memory_save", decision: "ask", approver: "admin" }] }, + }); + script([ + { toolCalls: [{ name: "memory_save", input: { note: "n" }, id: "l1" }] }, + { text: "done" }, + ]); + const { json } = await member.call("/api/chats", { method: "POST", json: { content: "go" } }); + await worker.processNow(json.runId); + const path = `/api/runs/${json.runId}/tool-calls/l1/decision`; + expect((await member.call(path, { method: "POST", json: { approved: true } })).status).toBe( + 403, + ); + expect( + (await member.call(`/api/workspace/members/${member.id}`, { method: "DELETE" })).status, + ).toBe(204); + // The team's admins can no longer decide it; the member can. + expect((await owner.call(path, { method: "POST", json: { approved: true } })).status).toBe(404); + expect((await member.call(path, { method: "POST", json: { approved: true } })).status).toBe( + 200, + ); + }); +}); + +test("CSV cells are RFC 4180 quoted and formula-safe", () => { + expect( + toCsv( + ["a", "b"], + [ + ["=1+1", "x,y"], + ['say "hi"', null], + ["-2", "@me"], + ["ok", "a\nb"], + ], + ), + ).toBe('a,b\r\n\'=1+1,"x,y"\r\n"say ""hi""",\r\n\'-2,\'@me\r\nok,"a\nb"\r\n'); +}); + +test("audit ranges: dates are inclusive, defaults to 30 days", () => { + const r = auditRange("2026-01-01", "2026-01-31"); + expect(r.from.toISOString()).toBe("2026-01-01T00:00:00.000Z"); + expect(r.to.toISOString()).toBe("2026-02-01T00:00:00.000Z"); + const d = auditRange(); + expect(d.to.getTime() - d.from.getTime()).toBe(30 * 24 * 3600_000); +}); diff --git a/apps/web/app/(app)/inbox/page.tsx b/apps/web/app/(app)/inbox/page.tsx index eda2f8a..f0d4eb1 100644 --- a/apps/web/app/(app)/inbox/page.tsx +++ b/apps/web/app/(app)/inbox/page.tsx @@ -14,7 +14,7 @@ import { ApprovalBatch, PLAN_TOOL } from "@/components/approval/checklist"; import { LearnPrompt, SuggestionStrip } from "@/components/approval/learned-rules"; import { UndoCountdown, type UndoTarget, useTimeLeft } from "@/components/approval/undo-window"; import { Markdown } from "@/components/markdown"; -import { EffectPill, Kbd, Monogram, Skeleton, StatusDot } from "@/components/ui"; +import { EffectPill, Kbd, Monogram, Pill, Skeleton, StatusDot } from "@/components/ui"; import { type Approval, api } from "@/lib/api"; import { cx, formatDateTime, formatRelative, splitToolName } from "@/lib/format"; import { useApi } from "@/lib/use-api"; @@ -79,7 +79,13 @@ function isTyping(e: KeyboardEvent) { } export default function InboxPage() { - const { approvals, tasks, reload } = useWorkspace(); + const { approvals, teamApprovals, waitingForAdmin, tasks, reload } = useWorkspace(); + // Team workspaces: other members' calls an admin must decide (admins only), and your own + // calls waiting on an admin (shown, not signable). + const waitingIds = useMemo( + () => new Set(waitingForAdmin.map((a) => a.toolCallId)), + [waitingForAdmin], + ); const [kept, setKept] = useState>({}); const [decided, setDecided] = useState>({}); const [selected, setSelected] = useState(null); @@ -91,13 +97,22 @@ export default function InboxPage() { const items = useMemo(() => { const map = new Map(); for (const a of Object.values(kept)) map.set(a.toolCallId, a); - for (const a of approvals ?? []) map.set(a.toolCallId, a); + for (const a of [...(approvals ?? []), ...teamApprovals, ...waitingForAdmin]) + map.set(a.toolCallId, a); return Array.from(map.values()).sort((a, b) => b.createdAt.localeCompare(a.createdAt)); - }, [approvals, kept]); + }, [approvals, teamApprovals, waitingForAdmin, kept]); + // Members' calls (they carry a requester) form one "Needs an admin" group, first. const groups = useMemo(() => { - const g = new Map(); + const g = new Map< + string, + { chatId: string; title: string; items: Approval[]; team?: boolean } + >(); + const team = items.filter((a) => a.requester); + if (team.length) + g.set("team", { chatId: "team", title: "Needs an admin", items: team, team: true }); for (const a of items) { + if (a.requester) continue; const cur = g.get(a.chatId) ?? { chatId: a.chatId, title: a.chatTitle, items: [] }; cur.items.push(a); g.set(a.chatId, cur); @@ -105,7 +120,7 @@ export default function InboxPage() { return Array.from(g.values()); }, [items]); const ordered = useMemo(() => groups.flatMap((g) => g.items), [groups]); - const pending = ordered.filter((a) => !decided[a.toolCallId]); + const pending = ordered.filter((a) => !decided[a.toolCallId] && !waitingIds.has(a.toolCallId)); // Initial selection: ?id= or the first pending item. useEffect(() => { @@ -119,10 +134,16 @@ export default function InboxPage() { 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 []; + if ( + !current || + decided[current.toolCallId] || + current.name === PLAN_TOOL || + waitingIds.has(current.toolCallId) + ) + 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]); + }, [current, decided, pending, waitingIds]); const tainted = (chatId: string) => tasks?.find((t) => t.id === chatId)?.tainted ?? false; const move = useCallback( @@ -165,7 +186,8 @@ export default function InboxPage() { function onDecided(a: Approval, d: Decided) { setKept((k) => ({ ...k, [a.toolCallId]: a })); - setDecided((m) => ({ ...m, [a.toolCallId]: d })); + // Undo stays with the member who owns the task, not the admin who signed it. + setDecided((m) => ({ ...m, [a.toolCallId]: a.requester ? { ...d, executeAfter: null } : d })); const next = pending.find((x) => x.toolCallId !== a.toolCallId); if (next && desktop) setSelected(next.toolCallId); void reload(); @@ -235,14 +257,25 @@ export default function InboxPage() {
!decided[a.toolCallId]) ? "needs" : "done"} + status={ + g.items.some((a) => !decided[a.toolCallId] && !waitingIds.has(a.toolCallId)) + ? "needs" + : g.items.some((a) => waitingIds.has(a.toolCallId)) + ? "idle" + : "done" + } /> - - {g.title || "Untitled task"} - + {g.team ? ( + // Members' tasks stay theirs: admins see the call, not the task. + {g.title} + ) : ( + + {g.title || "Untitled task"} + + )}
    {g.items.map((a) => { @@ -287,9 +320,16 @@ export default function InboxPage() { {d.undone ? "Undone" : d.approved ? "Approved" : "Denied"} + ) : waitingIds.has(a.toolCallId) ? ( + Waiting for an admin ) : ( )} + {a.requester ? ( + + {a.requester.name} + + ) : null} @@ -371,7 +411,9 @@ export default function InboxPage() { onUndone={() => markUndone(current.toolCallId)} phase="continuing" /> - {decided[current.toolCallId]!.approved && !decided[current.toolCallId]!.edited ? ( + {decided[current.toolCallId]!.approved && + !decided[current.toolCallId]!.edited && + !current.requester ? ( ) : null} {pending.length === 0 ? ( @@ -407,11 +449,31 @@ export default function InboxPage() { reason={current.reason} preview={current.preview} tainted={tainted(current.chatId)} + waitingForAdmin={waitingIds.has(current.toolCallId)} + requester={current.requester ?? null} onDecided={(approved, info) => onDecided(current, { approved, ...info })} onConflict={() => void reload()} /> )} - + {current.requester ? ( +
    +

    Asked by

    +
    +

    + {current.requester.name} +

    +

    + {current.requester.email} · in “{current.chatTitle || "Untitled task"}” +

    +

    + Your team requires an admin to approve this. The task stays theirs; your + decision lets it continue. +

    +
    +
    + ) : ( + + )}
) : null} diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index d3327a1..5d6557e 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -12,6 +12,7 @@ import { ShieldCheck, Sun, User, + Users, Wallet, X, } from "lucide-react"; @@ -33,8 +34,9 @@ import { useApi } from "@/lib/use-api"; import { useWorkspace } from "@/lib/workspace"; import { MAX_CHAIN, ModelPicker, modelFromRef, priceLabel } from "./model-picker"; import { PolicyEditor } from "./policy-editor"; +import { TeamSettings } from "./team"; -type Section = "general" | "models" | "budgets" | "rules" | "appearance"; +type Section = "general" | "models" | "budgets" | "rules" | "team" | "appearance"; const SECTIONS: { id: Section; label: string; icon: ReactNode; blurb: string }[] = [ { @@ -61,6 +63,12 @@ const SECTIONS: { id: Section; label: string; icon: ReactNode; blurb: string }[] icon: , blurb: "What the agent may do on its own, and what waits for you.", }, + { + id: "team", + label: "Team", + icon: , + blurb: "Shared rules, admin sign-off and an audit log for everyone in your team.", + }, { id: "appearance", label: "Appearance", @@ -170,11 +178,16 @@ export default function SettingsPage() {

{meta.blurb}

- {settings.error && section !== "rules" && section !== "appearance" ? ( + {settings.error && + section !== "rules" && + section !== "team" && + section !== "appearance" ? ( {errorMessage(settings.error)} ) : null} {section === "rules" ? ( + ) : section === "team" ? ( + ) : section === "appearance" ? ( ) : !s ? ( diff --git a/apps/web/app/(app)/settings/policy-editor.tsx b/apps/web/app/(app)/settings/policy-editor.tsx index 9a93472..fc24554 100644 --- a/apps/web/app/(app)/settings/policy-editor.tsx +++ b/apps/web/app/(app)/settings/policy-editor.tsx @@ -1,11 +1,11 @@ "use client"; -import type { ArgMatcher, Decision, Effect, PolicyDefaults, PolicyRule } from "@synapse/core"; +import type { ArgMatcher, Decision, Effect, PolicyDefaults } from "@synapse/core"; import { GripVertical, Plus, ShieldAlert, X } from "lucide-react"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { type ReactNode, useCallback, useEffect, useRef, useState } from "react"; import { useToast } from "@/components/toast"; import { EffectPill, ErrorNote, Pill, Segmented, Skeleton } from "@/components/ui"; -import { api, errorMessage, type Policy } from "@/lib/api"; +import { api, errorMessage, type TeamRule } from "@/lib/api"; import { cx, humanToolName } from "@/lib/format"; import { useApi } from "@/lib/use-api"; @@ -38,6 +38,8 @@ interface DraftRule { when: DraftMatcher[]; note: string; fresh?: boolean; + /** Team rules only: an Ask that a team admin, not the member, must decide. */ + approver?: boolean; } const newKey = () => @@ -45,11 +47,12 @@ const newKey = () => ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`; -function toDraft(rule: PolicyRule): DraftRule { +function toDraft(rule: TeamRule): DraftRule { return { id: rule.id, tool: rule.tool, decision: rule.decision, + approver: rule.approver === "admin", note: rule.note ?? "", when: (rule.when ?? []).map((m) => ({ key: newKey(), @@ -121,17 +124,91 @@ function toMatcher(m: DraftMatcher, where: string): ArgMatcher { } } -function fromDraft(rules: DraftRule[]): PolicyRule[] { +function fromDraft(rules: DraftRule[]): TeamRule[] { return rules.map((r, i) => { const where = `Rule ${i + 1}`; if (!r.tool.trim()) throw new Error(`${where}: which tool does it apply to?`); - const rule: PolicyRule = { id: r.id, tool: r.tool.trim(), decision: r.decision }; + const rule: TeamRule = { id: r.id, tool: r.tool.trim(), decision: r.decision }; if (r.when.length) rule.when = r.when.map((m) => toMatcher(m, where)); if (r.note.trim()) rule.note = r.note.trim(); + if (r.decision === "ask" && r.approver) rule.approver = "admin"; return rule; }); } +/** Draft rules as compared for "unsaved changes". */ +const comparable = (rules: DraftRule[]) => + rules.map(({ when, fresh: _f, approver, ...r }) => ({ + ...r, + approver: r.decision === "ask" && !!approver, + when: when.map(({ key: _k, ...m }) => m), + })); + +/** Rules as loaded by either scope: personal (with defaults) or the team's. */ +interface Loaded { + defaults: PolicyDefaults | null; + rules: TeamRule[]; + canEdit: boolean; +} + +function matcherText(m: ArgMatcher): string { + const label = OPS.find((o) => o.op === m.op)?.label ?? m.op; + const value = Array.isArray(m.value) + ? m.value.map((v) => (typeof v === "string" ? v : JSON.stringify(v))).join(", ") + : typeof m.value === "string" + ? m.value + : JSON.stringify(m.value); + return m.op === "emailsEndWith" ? `${label} ${value}` : `${m.path} ${label} ${value}`; +} + +/** + * Team rules as sentences, for people who can't change them: members in the Team section, + * and everyone above their own rules. + */ +export function TeamRulesReadOnly({ rules, intro }: { rules: TeamRule[]; intro?: ReactNode }) { + return ( +
+
+

Team rules

+ Set by your team +
+ {intro ?

{intro}

: null} + {rules.length === 0 ? ( +

+ Your team hasn't set any rules yet. +

+ ) : ( +
    + {rules.map((r) => ( +
  1. + When + + {r.tool} + + {(r.when ?? []).map((m) => ( + + and {matcherText(m)} + + ))} + + + {DECISION_OPTIONS.find((o) => o.value === r.decision)?.label} + {r.approver === "admin" ? " · an admin decides" : ""} + + {r.note ? {r.note} : null} +
  2. + ))} +
+ )} +
+ ); +} + function move(list: T[], from: number, to: number): T[] { if (to < 0 || to >= list.length || from === to) return list; const next = [...list]; @@ -173,9 +250,29 @@ function Token({ ); } -export function PolicyEditor({ prefillTool }: { prefillTool?: string | null }) { +/** + * Approval rules editor. `scope="personal"` (default) edits your defaults and rules and + * shows your team's rules above them, read-only. `scope="team"` edits the team's rules + * (admins), with "an admin decides" on Ask rules; members see them read-only. + */ +export function PolicyEditor({ + prefillTool, + scope = "personal", +}: { + prefillTool?: string | null; + scope?: "personal" | "team"; +}) { + const team = scope === "team"; const toast = useToast(); - const policy = useApi(() => api.policy()); + const policy = useApi(() => + team + ? api.teamRules().then((r) => ({ defaults: null, rules: r.rules, canEdit: r.canEdit })) + : api.policy().then((p) => ({ ...p, canEdit: true })), + ); + // Personal scope: the team's rules, shown above yours (404 when not in a team). + const teamAbove = useApi(() => + team ? Promise.resolve(null) : api.teamRules().catch(() => null), + ); const [defaults, setDefaults] = useState(null); const [rules, setRules] = useState([]); const [saving, setSaving] = useState(false); @@ -184,7 +281,7 @@ export function PolicyEditor({ prefillTool }: { prefillTool?: string | null }) { const [over, setOver] = useState(null); const prefilled = useRef(false); - const load = useCallback((p: Policy) => { + const load = useCallback((p: Loaded) => { setDefaults(p.defaults); setRules(p.rules.map(toDraft)); }, []); @@ -202,26 +299,15 @@ export function PolicyEditor({ prefillTool }: { prefillTool?: string | null }) { }, [policy.data, load, prefillTool]); const saved = policy.data - ? JSON.stringify({ - d: policy.data.defaults, - r: policy.data.rules - .map(toDraft) - .map(({ when, ...r }) => ({ ...r, when: when.map(({ key: _k, ...m }) => m) })), - }) + ? JSON.stringify({ d: policy.data.defaults, r: comparable(policy.data.rules.map(toDraft)) }) : ""; - const current = JSON.stringify({ - d: defaults, - r: rules.map(({ when, fresh: _f, ...r }) => ({ - ...r, - when: when.map(({ key: _k, ...m }) => m), - })), - }); + const current = JSON.stringify({ d: defaults, r: comparable(rules) }); const dirty = policy.data !== undefined && saved !== current; async function save() { - if (!defaults) return; + if (!team && !defaults) return; setError(null); - let parsed: PolicyRule[]; + let parsed: TeamRule[]; try { parsed = fromDraft(rules); } catch (err) { @@ -230,10 +316,14 @@ export function PolicyEditor({ prefillTool }: { prefillTool?: string | null }) { } setSaving(true); try { - const next = await api.savePolicy({ defaults, rules: parsed }); + const next: Loaded = team + ? await api.saveTeamRules(parsed).then((r) => ({ defaults: null, ...r })) + : await api + .savePolicy({ defaults: defaults!, rules: parsed }) + .then((p) => ({ ...p, canEdit: true })); policy.setData(next); load(next); - toast("Approval rules saved", "success"); + toast(team ? "Team rules saved" : "Approval rules saved", "success"); } catch (err) { setError(errorMessage(err)); } finally { @@ -251,52 +341,73 @@ export function PolicyEditor({ prefillTool }: { prefillTool?: string | null }) { ); if (policy.error) return {errorMessage(policy.error)}; - if (!defaults) + if (!policy.data || (!team && !defaults)) return (
); + // Members see their team's rules; only owners and admins change them. + if (team && !policy.data.canEdit) + return ( + + ); return (
-
-

By default

-

What happens when no rule below matches.

-
    - {EFFECTS.map((effect) => ( -
  • - - - tools - - - label={`Default for ${effect} tools`} - value={defaults[effect]} - onChange={(d) => setDefaults({ ...defaults, [effect]: d })} - options={DECISION_OPTIONS} - /> -
  • - ))} -
-

- - Once a task reads outside content — an email, a web page, a document — anything that - writes, sends or deletes asks you first, whatever these settings say. -

-
+ {teamAbove.data ? ( + + ) : null} + {defaults ? ( +
+

By default

+

+ What happens when no rule below matches. +

+
    + {EFFECTS.map((effect) => ( +
  • + + + tools + + + label={`Default for ${effect} tools`} + value={defaults[effect]} + onChange={(d) => setDefaults({ ...defaults, [effect]: d })} + options={DECISION_OPTIONS} + /> +
  • + ))} +
+

+ + Once a task reads outside content — an email, a web page, a document — anything that + writes, sends or deletes asks you first, whatever these settings say. +

+
+ ) : null}
-

Rules

+

+ {team ? "Team rules" : teamAbove.data ? "Your rules" : "Rules"} +

- Checked top to bottom; the first match wins. A matching Block always wins. Drag to - reorder. + {team + ? "Apply to everyone in the team, on top of their own rules; the strictest answer wins and a team Block can't be overridden. An Ask can need an admin to decide." + : "Checked top to bottom; the first match wins. A matching Block always wins. Drag to reorder."}

{r.note.startsWith("Learned:") ? ( diff --git a/apps/web/app/(app)/settings/team.tsx b/apps/web/app/(app)/settings/team.tsx new file mode 100644 index 0000000..7ec2c32 --- /dev/null +++ b/apps/web/app/(app)/settings/team.tsx @@ -0,0 +1,446 @@ +"use client"; + +import { Check, Copy, Download, Link2, LogOut, X } from "lucide-react"; +import { useState } from "react"; +import { useToast } from "@/components/toast"; +import { ErrorNote, Field, Pill, Segmented, Skeleton } from "@/components/ui"; +import { + api, + errorMessage, + isTeamAdmin, + type WorkspaceInfo, + type WorkspaceInvite, + type WorkspaceRole, +} from "@/lib/api"; +import { formatDateTime, formatRelative } from "@/lib/format"; +import { useApi } from "@/lib/use-api"; +import { useWorkspace } from "@/lib/workspace"; +import { PolicyEditor } from "./policy-editor"; + +const ROLE_LABEL: Record = { + owner: "Owner", + admin: "Admin", + member: "Member", +}; + +/** + * Settings → Team: one workspace whose rules apply to everyone in it, admins who sign off + * on risky actions, and an audit export. Tasks, connections and memory stay personal. + */ +export function TeamSettings() { + const info = useApi(() => api.workspace()); + const { reload } = useWorkspace(); + + if (info.error) return {errorMessage(info.error)}; + if (!info.data) + return ( +
+ + +
+ ); + const changed = (next: WorkspaceInfo) => { + info.setData(next); + void reload(); + }; + if (!info.data.workspace) return ; + const admin = isTeamAdmin(info.data.role); + + return ( +
+ + { + void info.reload(); + void reload(); + }} + /> + {admin ? : null} + + {admin ? : null} +
+ ); +} + +function CreateTeam({ onCreated }: { onCreated: (info: WorkspaceInfo) => void }) { + const toast = useToast(); + const [name, setName] = useState(""); + const [busy, setBusy] = useState(false); + return ( +
+
+

Work as a team

+

+ A team workspace has one set of rules that applies to everyone in it, can send risky + actions to an admin for sign-off, and keeps an exportable audit log. Tasks, connections + and memory stay personal. Got an invite link? Open it to join. +

+
+
{ + e.preventDefault(); + setBusy(true); + try { + onCreated(await api.createWorkspace(name.trim())); + toast("Team created. You're its owner.", "success"); + } catch (err) { + toast(errorMessage(err), "error"); + } finally { + setBusy(false); + } + }} + > + + setName(e.target.value)} + /> + + +
+
+ ); +} + +function TeamName({ + info, + onChanged, +}: { + info: WorkspaceInfo; + onChanged: (info: WorkspaceInfo) => void; +}) { + const toast = useToast(); + const [name, setName] = useState(info.workspace?.name ?? ""); + const [busy, setBusy] = useState(false); + const admin = isTeamAdmin(info.role); + const dirty = name.trim() !== "" && name.trim() !== info.workspace?.name; + return ( +
+
+

{info.workspace?.name}

+ {info.role ? You're {ROLE_LABEL[info.role].toLowerCase()} : null} +
+ {admin ? ( +
{ + e.preventDefault(); + setBusy(true); + try { + onChanged(await api.renameWorkspace(name.trim())); + toast("Team renamed", "success"); + } catch (err) { + toast(errorMessage(err), "error"); + } finally { + setBusy(false); + } + }} + > + + setName(e.target.value)} + /> + + {dirty ? ( + + ) : null} +
+ ) : null} +
+ ); +} + +function Members({ + info, + onChanged, + onReload, +}: { + info: WorkspaceInfo; + onChanged: (info: WorkspaceInfo) => void; + onReload: () => void; +}) { + const toast = useToast(); + const { user } = useWorkspace(); + const [busy, setBusy] = useState(null); + const admin = isTeamAdmin(info.role); + const owner = info.role === "owner"; + + async function setRole(userId: string, role: WorkspaceRole) { + setBusy(userId); + try { + onChanged(await api.setMemberRole(userId, role)); + } catch (err) { + toast(errorMessage(err), "error"); + } finally { + setBusy(null); + } + } + + async function remove(userId: string, self: boolean) { + const ok = window.confirm( + self + ? "Leave this team? Its rules stop applying to you, and you'll need a new invite to come back." + : "Remove this person from the team? Their tasks stay theirs.", + ); + if (!ok) return; + setBusy(userId); + try { + await api.removeMember(userId); + toast(self ? "You left the team" : "Removed from the team", "success"); + onReload(); + } catch (err) { + toast(errorMessage(err), "error"); + } finally { + setBusy(null); + } + } + + return ( +
+

Members

+

+ Owners and admins manage the team and its rules, and sign off on actions the team says need + an admin. Only owners make owners; a team always keeps at least one. +

+
    + {info.members.map((m) => { + const self = m.userId === user?.id; + // Admins manage members and admins; only owners touch owners. + const canChange = admin && (owner || m.role !== "owner"); + return ( +
  • +
    +

    + {m.name} + {self ? · you : null} +

    +

    + {m.email} ·{" "} + + joined {formatRelative(m.joinedAt)} + +

    +
    + {canChange ? ( + + label={`Role for ${m.name}`} + size="sm" + value={m.role} + onChange={(role) => void setRole(m.userId, role)} + options={(owner + ? (["owner", "admin", "member"] as const) + : (["admin", "member"] as const) + ).map((r) => ({ value: r, label: ROLE_LABEL[r] }))} + /> + ) : ( + {ROLE_LABEL[m.role]} + )} + {self ? ( + + ) : canChange ? ( + + ) : null} +
  • + ); + })} +
+
+ ); +} + +const INVITE_TONE: Record = { + active: "ok", + used: "neutral", + revoked: "danger", + expired: "outline", +}; + +function Invites() { + const toast = useToast(); + const invites = useApi(() => api.invites()); + const [role, setRole] = useState<"admin" | "member">("member"); + const [link, setLink] = useState(null); + const [copied, setCopied] = useState(false); + const [busy, setBusy] = useState(false); + + async function create() { + setBusy(true); + try { + const res = await api.createInvite(role); + setLink(res.link); + setCopied(false); + void invites.reload(); + } catch (err) { + toast(errorMessage(err), "error"); + } finally { + setBusy(false); + } + } + + async function copy() { + if (!link) return; + try { + await navigator.clipboard.writeText(link); + setCopied(true); + } catch { + toast("Couldn't copy. Select the link and copy it yourself.", "error"); + } + } + + async function revoke(id: string) { + try { + await api.revokeInvite(id); + void invites.reload(); + } catch (err) { + toast(errorMessage(err), "error"); + } + } + + return ( +
+

Invite people

+

+ Each link works once and expires in 7 days. Send it however you like; whoever opens it while + signed in joins the team. +

+
+ + label="Invite as" + value={role} + onChange={setRole} + options={[ + { value: "member", label: "Member" }, + { value: "admin", label: "Admin" }, + ]} + /> + +
+ {link ? ( +
+

Shown once. Copy it now.

+
+ e.target.select()} + /> + +
+
+ ) : null} + {invites.data && invites.data.invites.length > 0 ? ( +
    + {invites.data.invites.map((i) => ( +
  • + {i.status} + {ROLE_LABEL[i.role]} + + {i.status === "used" + ? `Joined by ${i.usedByEmail ?? "someone"}` + : i.status === "active" + ? `Expires ${formatRelative(i.expiresAt)}` + : `Created ${formatRelative(i.createdAt)}`} + + {i.status === "active" ? ( + + ) : null} +
  • + ))} +
+ ) : null} +
+ ); +} + +const day = (d: Date) => d.toISOString().slice(0, 10); + +function AuditExport() { + const [from, setFrom] = useState(() => day(new Date(Date.now() - 30 * 24 * 3600_000))); + const [to, setTo] = useState(() => day(new Date())); + const valid = from !== "" && to !== "" && from <= to; + return ( +
+

Audit log

+

+ Every action members' tasks proposed while in the team: when, who, which task and tool, what + the rules said, and who decided. A CSV for your spreadsheet or compliance folder. +

+
+ + setFrom(e.target.value)} + /> + + + setTo(e.target.value)} + /> + + + + Download CSV + +
+
+ ); +} diff --git a/apps/web/app/(auth)/auth-form.tsx b/apps/web/app/(auth)/auth-form.tsx index 07d8e96..28826fa 100644 --- a/apps/web/app/(auth)/auth-form.tsx +++ b/apps/web/app/(auth)/auth-form.tsx @@ -22,8 +22,12 @@ export function AuthForm({ mode }: { mode: "sign-in" | "sign-up" }) { const [password, setPassword] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); + // Switching between sign in and sign up keeps where to go after (e.g. an invite link). + const [carry, setCarry] = useState(""); useEffect(() => { + const next = nextPath(); + setCarry(next === "/" ? "" : `?next=${encodeURIComponent(next)}`); api .config() .then(setConfig) @@ -208,7 +212,10 @@ export function AuthForm({ mode }: { mode: "sign-in" | "sign-up" }) { signupEnabled ? ( <> New here?{" "} - + Create an account @@ -216,7 +223,7 @@ export function AuthForm({ mode }: { mode: "sign-in" | "sign-up" }) { ) : ( <> Already have an account?{" "} - + Sign in diff --git a/apps/web/app/join/[token]/join-team.tsx b/apps/web/app/join/[token]/join-team.tsx new file mode 100644 index 0000000..28d0dd7 --- /dev/null +++ b/apps/web/app/join/[token]/join-team.tsx @@ -0,0 +1,107 @@ +"use client"; + +import { ArrowRight, LoaderCircle } from "lucide-react"; +import Link from "next/link"; +import { useEffect, useState } from "react"; +import { Brand } from "@/components/ui"; +import { api, errorMessage, type SessionUser, type WorkspaceInfo } from "@/lib/api"; + +/** + * Accepting an invite link. Signed out: sign in (or up) first, then come back here. + * Joining is a deliberate click, never automatic: it puts you under the team's rules. + */ +export function JoinTeam({ token }: { token: string }) { + const [user, setUser] = useState(undefined); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [joined, setJoined] = useState(null); + + useEffect(() => { + api + .session() + .then((s) => { + if (s) return setUser(s.user); + setUser(null); + const next = encodeURIComponent(`/join/${token}`); + window.location.replace(`/sign-in?next=${next}`); + }) + .catch(() => setUser(null)); + }, [token]); + + async function join() { + setBusy(true); + setError(null); + try { + setJoined(await api.joinWorkspace(token)); + } catch (err) { + setError(errorMessage(err)); + } finally { + setBusy(false); + } + } + + return ( +
+
+
+ +
+
+

Team invite

+ {joined ? ( + <> +

+ You're in {joined.workspace?.name}. +

+

+ Your team's rules now apply to your tasks. When one needs an admin to sign off, + you'll see it waiting in your inbox. +

+
+ + See your team + + + + Home + +
+ + ) : ( + <> +

+ Join a team on Synapse +

+
    +
  • The team's approval rules apply to every task you run, on top of yours.
  • +
  • Some actions may need a team admin to sign off before they run.
  • +
  • Admins can export an audit log of the actions your tasks take.
  • +
  • Your tasks, connections and memory stay yours.
  • +
+ {user ?

Joining as {user.email}

: null} + {error ? ( +

+ {error} +

+ ) : null} +
+ + + Not now + +
+ + )} +
+
+
+ ); +} diff --git a/apps/web/app/join/[token]/page.tsx b/apps/web/app/join/[token]/page.tsx new file mode 100644 index 0000000..6f3f19b --- /dev/null +++ b/apps/web/app/join/[token]/page.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next"; +import { JoinTeam } from "./join-team"; + +export const metadata: Metadata = { title: "Join a team" }; + +export default async function JoinPage({ params }: { params: Promise<{ token: string }> }) { + const { token } = await params; + return ; +} diff --git a/apps/web/components/approval/approval-card.tsx b/apps/web/components/approval/approval-card.tsx index 291df48..c9296ba 100644 --- a/apps/web/components/approval/approval-card.tsx +++ b/apps/web/components/approval/approval-card.tsx @@ -54,6 +54,13 @@ export interface ApprovalCardProps { onConflict: () => void; handle?: Ref; className?: string; + /** + * The person's team requires an admin to decide this, and they aren't one: the slip is + * shown for information, with no way to sign it. + */ + waitingForAdmin?: boolean; + /** A team admin is deciding a member's call: whose task asked. */ + requester?: { name: string; email: string } | null; } /** How long the stamp sits on the slip before the card resolves into a receipt. */ @@ -167,7 +174,7 @@ export function ApprovalCard(props: ApprovalCardProps) { ); async function decide(approved: boolean) { - if (busy || stamped) return; + if (busy || stamped || props.waitingForAdmin) return; setError(null); const body: { approved: boolean; reason?: string; input?: unknown } = { approved }; const invalid = "error" in current ? String(current.error) : null; @@ -203,7 +210,7 @@ export function ApprovalCard(props: ApprovalCardProps) { } function openDeny() { - if (stamped) return; + if (stamped || props.waitingForAdmin) return; setDenying(true); setTimeout(() => denyInput.current?.focus(), 0); } @@ -211,7 +218,8 @@ export function ApprovalCard(props: ApprovalCardProps) { useImperativeHandle(props.handle, () => ({ approve: () => void decide(true), deny: openDeny, - edit: () => (mode === "edit" || stamped || plan ? undefined : startEdit()), + edit: () => + mode === "edit" || stamped || plan || props.waitingForAdmin ? undefined : startEdit(), })); const title = approvalTitle(preview, name); @@ -239,13 +247,22 @@ export function ApprovalCard(props: ApprovalCardProps) { {/* The slip's header: what kind of paper this is and where it goes. */}
- -
- {/* The signature line: the buttons sit on it like a pen on paper. */} -
-
- - {denying || plan ? null : mode === "edit" ? ( - - ) : ( - - )} - {denying ? ( - <> -
+
+ ) : ( + /* The signature line: the buttons sit on it like a pen on paper. */ +
+
+ + {denying || plan ? null : mode === "edit" ? ( + + ) : ( + + )} + {denying ? ( + <> + + + + ) : ( - - ) : ( - - )} -
-
- - {stamped === "approved" - ? "Signed off by you" - : stamped === "denied" - ? "Declined by you" - : "Your signature"} - - - Always allow… - +
+
+ + {stamped === "approved" + ? "Signed off by you" + : stamped === "denied" + ? "Declined by you" + : props.requester + ? "Your signature, as a team admin" + : "Your signature"} + + + Always allow… + +
+ {stamped ? ( + + {stamped === "approved" ? "Approved" : "Denied"} + + ) : null}
- {stamped ? ( - - {stamped === "approved" ? "Approved" : "Denied"} - - ) : null} -
+ )}
); } diff --git a/apps/web/components/shell/mobile.tsx b/apps/web/components/shell/mobile.tsx index 9c6d604..1675694 100644 --- a/apps/web/components/shell/mobile.tsx +++ b/apps/web/components/shell/mobile.tsx @@ -100,11 +100,11 @@ export function MobileTopBar() { export function BottomTabs() { const pathname = usePathname(); - const { approvals } = useWorkspace(); + const { approvals, teamApprovals } = useWorkspace(); const [more, setMore] = useState(false); // biome-ignore lint/correctness/useExhaustiveDependencies: close on navigation useEffect(() => setMore(false), [pathname]); - const count = approvals?.length ?? 0; + const count = (approvals?.length ?? 0) + teamApprovals.length; const tab = "flex flex-1 flex-col items-center justify-center gap-0.5 text-[11px] font-medium"; const moreLinks = [...PRIMARY_NAV.slice(2), ...SECONDARY_NAV]; const moreActive = moreLinks.some((l) => isActivePath(pathname, l.href)); diff --git a/apps/web/components/shell/rail.tsx b/apps/web/components/shell/rail.tsx index 8b6d551..04379ae 100644 --- a/apps/web/components/shell/rail.tsx +++ b/apps/web/components/shell/rail.tsx @@ -24,10 +24,10 @@ export async function signOut() { export function Rail({ onNavigate }: { onNavigate?: () => void }) { const pathname = usePathname(); const router = useRouter(); - const { tasks, approvals } = useWorkspace(); + const { tasks, approvals, teamApprovals } = useWorkspace(); const palette = usePalette(); const [query, setQuery] = useState(""); - const inboxCount = approvals?.length ?? 0; + const inboxCount = (approvals?.length ?? 0) + teamApprovals.length; const filtered = useMemo(() => { const q = query.trim().toLowerCase(); diff --git a/apps/web/components/task/task-view.tsx b/apps/web/components/task/task-view.tsx index b835d22..d084174 100644 --- a/apps/web/components/task/task-view.tsx +++ b/apps/web/components/task/task-view.tsx @@ -12,7 +12,7 @@ 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"; -import { ApiError, api, errorMessage, type TaskRun } from "@/lib/api"; +import { ApiError, api, errorMessage, isTeamAdmin, type TaskRun } from "@/lib/api"; import { cx, formatCost } from "@/lib/format"; import { denialReason, isUndone, receiptPhase, type ToolPart } from "@/lib/steps"; import { useMedia } from "@/lib/use-media"; @@ -39,7 +39,10 @@ const PANEL_KEY = "synapse-run-panel"; export function TaskView({ taskId }: { taskId: string }) { const router = useRouter(); const toast = useToast(); - const { reload: reloadWorkspace, tasks } = useWorkspace(); + const { reload: reloadWorkspace, tasks, teamRole } = useWorkspace(); + // A call the team reserves for an admin: members only watch it; admins sign it here. + const waitsForAdmin = (p: ToolPart) => + p.approver === "admin" && teamRole !== null && !isTeamAdmin(teamRole); const [title, setTitle] = useState(""); const [state, setState] = useState(null); const [loadError, setLoadError] = useState(null); @@ -174,7 +177,11 @@ export function TaskView({ taskId }: { taskId: string }) { ); const hasAwaiting = state?.messages.some((m) => m.parts.some( - (p) => p.type === "tool" && p.status === "awaiting_approval" && !decided[p.toolCallId], + (p) => + p.type === "tool" && + p.status === "awaiting_approval" && + !decided[p.toolCallId] && + !waitsForAdmin(p), ), ); const status = hasAwaiting ? "needs" : taskStatus(run?.status); @@ -262,7 +269,8 @@ export function TaskView({ taskId }: { taskId: string }) { p.type === "tool" && p.status === "awaiting_approval" && p.name !== PLAN_TOOL && - !decided[p.toolCallId], + !decided[p.toolCallId] && + !waitsForAdmin(p), ) : []; if (runId && group.length >= 2 && group.some((p) => p.toolCallId === part.toolCallId)) { @@ -316,6 +324,7 @@ export function TaskView({ taskId }: { taskId: string }) { preview={part.preview} tainted={tainted} glow={initialAwaiting !== null && !initialAwaiting.has(part.toolCallId)} + waitingForAdmin={waitsForAdmin(part)} onDecided={(approved, info) => { setDecided((m) => ({ ...m, [part.toolCallId]: { approved, ...info } })); follow(runId); diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts index c071c64..3f81189 100644 --- a/apps/web/lib/api.ts +++ b/apps/web/lib/api.ts @@ -183,8 +183,47 @@ export interface Approval { /** One-line human summary from the tool. */ preview: string | null; createdAt: string; + /** "admin": the person's team requires a team admin to decide it. */ + approver?: "admin" | null; + /** Team inbox only: the member whose task asked. */ + requester?: { id: string; name: string; email: string }; } +// ---------- Team workspaces ---------- + +export type WorkspaceRole = "owner" | "admin" | "member"; + +export interface WorkspaceMember { + userId: string; + name: string; + email: string; + role: WorkspaceRole; + joinedAt: string; +} + +export interface WorkspaceInfo { + workspace: { id: string; name: string; createdAt: string } | null; + role: WorkspaceRole | null; + members: WorkspaceMember[]; +} + +export interface WorkspaceInvite { + id: string; + role: Exclude; + expiresAt: string; + createdAt: string; + usedAt?: string | null; + revokedAt?: string | null; + usedByEmail?: string | null; + status: "active" | "used" | "revoked" | "expired"; +} + +/** A team rule: a policy rule, plus who must decide an Ask. */ +export type TeamRule = PolicyRule & { approver?: "admin" | null }; + +export const isTeamAdmin = (role: WorkspaceRole | null | undefined) => + role === "owner" || role === "admin"; + export interface ConnectionTool { name: string; title: string | null; @@ -434,4 +473,24 @@ export const api = { models: () => get<{ models: ModelInfo[]; updatedAt: string | null }>("/api/models"), saveSettings: (body: SettingsUpdate) => put("/api/settings", body), usage: (days = 30) => get<{ days: UsageDay[] }>(`/api/usage?days=${days}`), + + workspace: () => get("/api/workspace"), + createWorkspace: (name: string) => post("/api/workspace", { name }), + renameWorkspace: (name: string) => patch("/api/workspace", { name }), + /** The link holds the token and is only returned here, once. */ + createInvite: (role: "admin" | "member") => + post<{ invite: WorkspaceInvite; link: string }>("/api/workspace/invites", { role }), + invites: () => get<{ invites: WorkspaceInvite[] }>("/api/workspace/invites"), + revokeInvite: (id: string) => del(`/api/workspace/invites/${enc(id)}`), + joinWorkspace: (token: string) => post("/api/workspace/join", { token }), + setMemberRole: (userId: string, role: WorkspaceRole) => + patch(`/api/workspace/members/${enc(userId)}`, { role }), + removeMember: (userId: string) => del(`/api/workspace/members/${enc(userId)}`), + teamRules: () => get<{ rules: TeamRule[]; canEdit: boolean }>("/api/workspace/rules"), + saveTeamRules: (rules: TeamRule[]) => + put<{ rules: TeamRule[]; canEdit: boolean }>("/api/workspace/rules", { rules }), + /** Team members' calls waiting for an admin (owners and admins only). */ + teamApprovals: () => get<{ approvals: Approval[] }>("/api/workspace/approvals"), + auditCsvUrl: (from: string, to: string) => + `/api/workspace/audit.csv?from=${enc(from)}&to=${enc(to)}`, }; diff --git a/apps/web/lib/workspace.tsx b/apps/web/lib/workspace.tsx index 872c587..2a59250 100644 --- a/apps/web/lib/workspace.tsx +++ b/apps/web/lib/workspace.tsx @@ -10,11 +10,25 @@ import { useMemo, useState, } from "react"; -import { type Approval, api, type ChatSummary, type SessionUser } from "@/lib/api"; +import { + type Approval, + api, + type ChatSummary, + isTeamAdmin, + type SessionUser, + type WorkspaceRole, +} from "@/lib/api"; interface WorkspaceValue { tasks: ChatSummary[] | null; + /** Calls in your own tasks that you can decide. */ approvals: Approval[] | null; + /** Team admins only: other members' calls their team says an admin must decide. */ + teamApprovals: Approval[]; + /** Your calls that wait for a team admin; you can't decide them. */ + waitingForAdmin: Approval[]; + /** Your role in your team workspace, or null when you're not in one. */ + teamRole: WorkspaceRole | null; user: SessionUser | null; todaySpend: number | null; /** Refetch tasks + approvals (cheap; called after anything that changes them). */ @@ -25,6 +39,9 @@ interface WorkspaceValue { const WorkspaceContext = createContext({ tasks: null, approvals: null, + teamApprovals: [], + waitingForAdmin: [], + teamRole: null, user: null, todaySpend: null, reload: async () => {}, @@ -45,14 +62,41 @@ function todayKey() { export function WorkspaceProvider({ children }: { children: ReactNode }) { const [tasks, setTasks] = useState(null); const [approvals, setApprovals] = useState(null); + const [teamApprovals, setTeamApprovals] = useState([]); + const [waitingForAdmin, setWaitingForAdmin] = useState([]); + const [teamRole, setTeamRole] = useState(null); const [user, setUser] = useState(null); const [todaySpend, setTodaySpend] = useState(null); const pathname = usePathname(); const reload = useCallback(async () => { - const [t, a, u] = await Promise.allSettled([api.chats(), api.approvals(), api.usage(1)]); + const [t, a, u, w] = await Promise.allSettled([ + api.chats(), + api.approvals(), + api.usage(1), + api.workspace(), + ]); if (t.status === "fulfilled") setTasks(t.value.chats); - if (a.status === "fulfilled") setApprovals(a.value.approvals); + const role = w.status === "fulfilled" ? w.value.role : null; + setTeamRole(role); + // Team admins also decide members' calls that need an admin, their own included. + const team = isTeamAdmin(role) + ? await api.teamApprovals().then( + (r) => r.approvals, + () => [], + ) + : []; + const teamIds = new Set(team.map((x) => x.toolCallId)); + if (a.status === "fulfilled") { + const own = a.value.approvals; + const ownIds = new Set(own.map((x) => x.toolCallId)); + // Out of the team (left since): its rules no longer govern you, so it's yours to decide. + const waits = (x: Approval) => + x.approver === "admin" && role !== null && !teamIds.has(x.toolCallId); + setApprovals(own.filter((x) => !waits(x))); + setWaitingForAdmin(own.filter(waits)); + setTeamApprovals(team.filter((x) => !ownIds.has(x.toolCallId))); + } if (u.status === "fulfilled") { const day = u.value.days.find((d) => d.date === todayKey()); setTodaySpend(day?.costUsd ?? 0); @@ -110,8 +154,28 @@ export function WorkspaceProvider({ children }: { children: ReactNode }) { }, [reload]); const value = useMemo( - () => ({ tasks, approvals, user, todaySpend, reload, setUser: updateUser }), - [tasks, approvals, user, todaySpend, reload, updateUser], + () => ({ + tasks, + approvals, + teamApprovals, + waitingForAdmin, + teamRole, + user, + todaySpend, + reload, + setUser: updateUser, + }), + [ + tasks, + approvals, + teamApprovals, + waitingForAdmin, + teamRole, + user, + todaySpend, + reload, + updateUser, + ], ); return {children}; } diff --git a/docs/api.md b/docs/api.md index c7a03cd..f99a5e2 100644 --- a/docs/api.md +++ b/docs/api.md @@ -4,7 +4,7 @@ All endpoints live under `/api`, return JSON, and require a session cookie (Bett mounted at `/api/auth/*`) unless noted. Every query is scoped to the signed-in user; ids belonging to someone else return `404`. -Errors: `{ "error": { "code": string, "message": string } }` with status 400/401/404/409/422/500. +Errors: `{ "error": { "code": string, "message": string } }` with status 400/401/403/404/409/422/500. Types referenced below (`UiMessage`, `UiPart`, `SeqEvent`, `RunStatus`, `Effect`, `ToolOutput`, `PolicyRule`, `PolicyDefaults`) are exported from `@synapse/core` and @@ -45,7 +45,12 @@ agent reads it at its next step; if the run is waiting on approvals, those are d | 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, executeAfter, createdAt }[] }` (audit view) | -| GET | `/api/approvals` | | `{ approvals: { runId, chatId, chatTitle, toolCallId, name, effect, input, reason, preview, createdAt }[] }` — `preview` is a one-line human summary from the tool, `reason` explains why approval is needed — everything awaiting the user | +| GET | `/api/approvals` | | `{ approvals: { runId, chatId, chatTitle, toolCallId, name, effect, input, reason, preview, approver, createdAt }[] }` — `preview` is a one-line human summary from the tool, `reason` explains why approval is needed — everything awaiting the user. `approver: "admin"` means the user's team requires a team admin to decide it: unless the user is an owner or admin of their team, they can only wait (deciding returns `403`) | + +Tool calls carry `approver: "admin" | null` (in `GET /api/runs/:id`, in `UiPart`s and on the +`approval.requested` event). A team owner or admin decides such a call of a team member with +the same decision routes above; `decidedBy` records the admin. They can't decide a member's +other calls (`404`), and can't undo for them. ### Event stream @@ -109,6 +114,35 @@ condition; a single `repo`/`project`/`channel`/`team` becomes `equals`. Sending destructive tools are only suggested with a condition. Learned rules are ordinary rules; a task that read outside content still asks. +## Team workspace + +See [teams.md](teams.md) for how team rules combine with yours. One workspace per person. +`Role` is `"owner" | "admin" | "member"`; "admin+" means owner or admin (`403` otherwise); +endpoints other than create and join return `404 no_workspace` when you're not in one. + +| Method | Path | Body | Response | +|---|---|---|---| +| GET | `/api/workspace` | | `{ workspace: { id, name, createdAt } \| null, role: Role \| null, members: { userId, name, email, role, joinedAt }[] }` | +| POST | `/api/workspace` | `{ name }` | `201`, same shape; you are the owner. `409 already_member` if you're in one | +| PATCH | `/api/workspace` | `{ name }` | same shape (admin+) | +| POST | `/api/workspace/invites` | `{ role?: "member" \| "admin", expiresInDays?: 1–30 }` (default member, 7) | `201 { invite: { id, role, expiresAt, createdAt, status }, link }` — `link` is `${PUBLIC_URL}/join/`, returned only here; only a SHA-256 of the token is stored (admin+) | +| GET | `/api/workspace/invites` | | `{ invites: { id, role, expiresAt, createdAt, usedAt, revokedAt, usedByEmail, status: "active" \| "used" \| "revoked" \| "expired" }[] }` (admin+) | +| DELETE | `/api/workspace/invites/:id` | | `204` — revokes an unused invite (admin+) | +| POST | `/api/workspace/join` | `{ token }` | same shape as GET. Single use. `404 invite_not_found`; `409 invite_used` / `invite_revoked` / `invite_expired` / `already_member` / `already_joined` | +| PATCH | `/api/workspace/members/:userId` | `{ role: Role }` | same shape as GET (admin+). Only owners make or change owners; `409 last_owner` when it would leave no owner | +| DELETE | `/api/workspace/members/:userId` | | `204`. Anyone may remove themselves (leave); admin+ remove others, only owners remove owners. `409 last_owner` for the last owner while others remain; the last person to leave deletes the workspace | +| GET | `/api/workspace/rules` | | `{ rules: TeamRule[], canEdit: boolean }` — `TeamRule` is a `PolicyRule` plus `approver?: "admin"` | +| PUT | `/api/workspace/rules` | `{ rules: TeamRule[] }` (priority order) | same (admin+). Validated like personal rules, incl. `422 invalid_pattern`. `approver` is kept only on `ask` rules | +| GET | `/api/workspace/approvals` | | `{ approvals: { …same as /api/approvals, requester: { id, name, email } }[] }` — team members' calls (yours included) awaiting an admin (admin+) | +| GET | `/api/workspace/audit.csv?from&to` | | `text/csv` attachment (admin+). `from`/`to` are `YYYY-MM-DD` (inclusive) or ISO times; default the last 30 days, at most a year, at most 50,000 rows (`422 too_many_rows`) | + +The audit CSV has a header row `time,member,task,tool,effect,decision,status,decided_by,decided_via,reason`: +every tool call proposed in members' tasks while they were in the team, oldest first. `decision` +is what the policy said (`allow`/`ask`/`block`), `decided_by` the email of the person who +decided (empty when policy decided). Quoting follows RFC 4180 (CRLF lines); a cell starting +with `=`, `+`, `-`, `@`, tab or CR is prefixed with `'` so spreadsheets don't run it as a +formula. + ## Memory | Method | Path | Body | Response | diff --git a/docs/teams.md b/docs/teams.md new file mode 100644 index 0000000..3a21ba7 --- /dev/null +++ b/docs/teams.md @@ -0,0 +1,114 @@ +# Team workspaces + +A team workspace lets a company put its people under one set of approval rules, send risky +actions to an admin for sign-off, and export an audit log. It is deliberately small: + +- **Shared:** the team's rules, its members and roles, invite links, the audit log. +- **Personal, always:** tasks and their history, connections and integrations, memory, + knowledge, models, keys and budgets. Admins never open a member's task; they see the one + action that needs them. + +One person belongs to at most one workspace. Create one in **Settings → Team** (you become +its owner), then invite people with a link. + +## How team rules combine with yours + +Every proposed tool call is checked against your own policy (your rules, then your defaults) +and against your team's rules, separately. The **strictest** answer wins: + +``` +block > ask, an admin decides > ask > allow +``` + +| Team says | You say | Result | +|---|---|---| +| block | anything | **block**. A team block can never be overridden | +| ask, an admin decides | allow / ask | **ask, and a team admin decides** (not you) | +| ask | allow | ask (you decide) | +| allow | ask (rule or default) | ask: a team allow never loosens your own policy | +| no matching rule | anything | your policy decides | +| anything | block | block | + +Details: + +- Team rules have no defaults. A team rule that doesn't match has no opinion, so with no + matching team rule your policy decides exactly as it would without a team. +- Within the team's rules, a matching `block` wins outright, otherwise the first matching + rule, just like personal rules. +- **Outside content** still escalates: once a task has read an email, a web page or a + document, a combined `allow` of anything but a read becomes an ordinary `ask`. A stricter + answer (block, or an admin's ask) stays as it is. +- **Approved plans** (`propose_plan`): a step you approved runs without asking again when + the call matches it exactly. That stands in for *your* approval, so it satisfies an + ordinary ask (yours or the team's), but never a block and never an ask that needs an + admin. +- **Edits:** when you (or an admin) approve with edited input, the edit is checked again. An + edit the rules would block is refused, and so is one that would turn an ordinary ask into + one that needs an admin. + +The composition is `evaluateComposedPolicy` in `packages/core/src/policy.ts`; with no team +rules it returns exactly what `evaluatePolicy` does. + +## When an admin must decide + +A team rule `{ "tool": "gmail_send_*", "decision": "ask", "approver": "admin" }` means a +team owner or admin signs off, not the member whose task asked: + +- The member sees the action as **Waiting for an admin**, with no Approve or Deny. Sending + a new message to the task still withdraws it, as with any pending approval. +- Owners and admins see it in their inbox under **Needs an admin**, with the member's name. + Approving or denying works like any approval; the member's task then continues, and + `decided_by` records the admin. +- If the member is an owner or admin themselves, they may decide their own. +- Notification channels (push, email, Slack) deliver it to the team's owners and admins + instead of the member. +- If the member leaves the team while it waits, the team's rules no longer govern them and + they decide it themselves. + +## Roles + +| | Owner | Admin | Member | +|---|:-:|:-:|:-:| +| See the team, its members and rules | ✓ | ✓ | ✓ | +| Leave | ✓ (not the last owner) | ✓ | ✓ | +| Decide team members' "an admin decides" actions | ✓ | ✓ | | +| Rename the team | ✓ | ✓ | | +| Create and revoke invite links | ✓ | ✓ | | +| Change members' and admins' roles, remove them | ✓ | ✓ | | +| Make someone an owner, change or remove an owner | ✓ | | | +| Edit team rules | ✓ | ✓ | | +| Export the audit log | ✓ | ✓ | | + +A team always keeps at least one owner: the last owner can't step down or leave while +others remain (make someone else owner first). The last person to leave deletes the team. + +## Invites + +An invite is a link, `https:///join/`, shown once when it's created. +Send it however you like. It works once, expires after 7 days, and can be revoked. Only a +SHA-256 of the token is stored. Whoever opens it signs in (or signs up), sees what joining +means, and clicks **Join team**. Invites can make members or admins, never owners. + +## Audit export + +Owners and admins can download a CSV (**Settings → Team → Audit log**, or +`GET /api/workspace/audit.csv?from=YYYY-MM-DD&to=YYYY-MM-DD`) of every action proposed in +members' tasks while they were in the team: + +| Column | | +|---|---| +| `time` | When the agent proposed it (ISO 8601, UTC) | +| `member` | The member's email | +| `task` | The task's title | +| `tool` | Tool name | +| `effect` | read, write, send or destructive | +| `decision` | What the rules said: allow, ask or block | +| `status` | What happened: succeeded, failed, denied, awaiting_approval… | +| `decided_by` | Email of the person who approved or denied (empty when the rules decided) | +| `decided_via` | Where they decided: web, push, slack, email | +| `reason` | Why the rules said so | + +The file is RFC 4180 CSV. Task titles and reasons can contain text that came from outside +(an email subject, say), so any cell starting with `=`, `+`, `-` or `@` is prefixed with `'` +to stop spreadsheets from running it as a formula. Ranges are capped at a year and 50,000 +rows per export. diff --git a/packages/core/src/memory-store.ts b/packages/core/src/memory-store.ts index d345c41..8689c3e 100644 --- a/packages/core/src/memory-store.ts +++ b/packages/core/src/memory-store.ts @@ -1,4 +1,4 @@ -import type { PolicyDefaults, PolicyRule } from "./policy"; +import type { PolicyDefaults, PolicyRule, TeamPolicyRule } from "./policy"; import { SAFE_DEFAULTS } from "./policy"; import { UNDO_DENIAL } from "./runtime"; import type { EventSink, RunStore } from "./store"; @@ -12,6 +12,8 @@ export class MemoryStore implements RunStore { pendingInputs: { chatId: string; text: string }[] = []; rules: PolicyRule[] = []; defaults: PolicyDefaults = SAFE_DEFAULTS; + /** Rules of the user's team workspace, applied on top of `rules`. */ + teamRules: TeamPolicyRule[] = []; private seq = 0; createRun(init: { chatId: string; userId: string; text?: string }): RunRecord { @@ -123,7 +125,7 @@ export class MemoryStore implements RunStore { } async getPolicy() { - return { rules: this.rules, defaults: this.defaults }; + return { rules: this.rules, defaults: this.defaults, teamRules: this.teamRules }; } /** diff --git a/packages/core/src/policy.test.ts b/packages/core/src/policy.test.ts index 834bab6..1ac5110 100644 --- a/packages/core/src/policy.test.ts +++ b/packages/core/src/policy.test.ts @@ -1,5 +1,13 @@ import { describe, expect, test } from "bun:test"; -import { evaluatePolicy, globMatch, type PolicyRule } from "./policy"; +import { + ADMIN_APPROVAL_REASON, + evaluateComposedPolicy, + evaluatePolicy, + globMatch, + type PolicyRule, + planGrantMaySatisfy, + type TeamPolicyRule, +} from "./policy"; const send = { tool: "gmail_send_email", effect: "send" as const, tainted: false }; @@ -95,3 +103,131 @@ test("patterns prone to catastrophic backtracking are refused and never match", ); expect(performance.now() - started).toBeLessThan(50); }); + +describe("evaluateComposedPolicy (team rules)", () => { + const sendCall = { ...send, input: { to: "bob@acme.com" } }; + + test("with no team rules it is exactly evaluatePolicy", () => { + const rules: PolicyRule[] = [ + { id: "a", tool: "gmail_*", decision: "allow" }, + { id: "b", tool: "github_delete_*", decision: "block" }, + ]; + const calls = [ + sendCall, + { ...sendCall, tainted: true }, + { tool: "github_delete_repo", effect: "destructive" as const, input: {}, tainted: false }, + { tool: "web_search", effect: "read" as const, input: {}, tainted: true }, + ]; + for (const call of calls) { + expect(evaluateComposedPolicy(call, { rules })).toEqual({ + ...evaluatePolicy(call, rules), + approver: null, + source: "personal", + }); + expect(evaluateComposedPolicy(call, { rules }, [])).toEqual( + evaluateComposedPolicy(call, { rules }), + ); + } + }); + + test("a team block beats a personal allow", () => { + const r = evaluateComposedPolicy( + sendCall, + { rules: [{ id: "mine", tool: "*", decision: "allow" }] }, + [{ id: "team", tool: "gmail_*", decision: "block" }], + ); + expect(r).toMatchObject({ decision: "block", ruleId: "team", source: "team" }); + expect(r.reason).toContain("team"); + }); + + test("a team block can't be overridden by an earlier team allow either", () => { + const r = evaluateComposedPolicy(sendCall, { rules: [] }, [ + { id: "ok", tool: "*", decision: "allow" }, + { id: "no", tool: "gmail_send_*", decision: "block" }, + ]); + expect(r).toMatchObject({ decision: "block", ruleId: "no" }); + }); + + test("a personal ask beats a team allow; a personal block beats a team ask", () => { + expect( + evaluateComposedPolicy( + sendCall, + { rules: [{ id: "mine", tool: "gmail_*", decision: "ask" }] }, + [{ id: "team", tool: "*", decision: "allow" }], + ), + ).toMatchObject({ decision: "ask", ruleId: "mine", approver: null, source: "personal" }); + // Personal defaults count too: a team allow doesn't loosen "sending asks". + expect( + evaluateComposedPolicy(sendCall, { rules: [] }, [ + { id: "team", tool: "*", decision: "allow" }, + ]).decision, + ).toBe("ask"); + expect( + evaluateComposedPolicy( + sendCall, + { rules: [{ id: "mine", tool: "gmail_*", decision: "block" }] }, + [{ id: "team", tool: "*", decision: "ask", approver: "admin" }], + ), + ).toMatchObject({ decision: "block", ruleId: "mine", approver: null }); + }); + + test("a team admin-ask beats a personal allow and taint", () => { + const team: TeamPolicyRule[] = [ + { id: "t", tool: "gmail_*", decision: "ask", approver: "admin" }, + ]; + const personal = { rules: [{ id: "mine", tool: "*", decision: "allow" as const }] }; + for (const tainted of [false, true]) { + expect(evaluateComposedPolicy({ ...sendCall, tainted }, personal, team)).toEqual({ + decision: "ask", + approver: "admin", + reason: ADMIN_APPROVAL_REASON, + ruleId: "t", + source: "team", + }); + } + // An ordinary team ask has no approver: the member decides. + expect( + evaluateComposedPolicy(sendCall, personal, [{ id: "t", tool: "gmail_*", decision: "ask" }]), + ).toMatchObject({ decision: "ask", approver: null, source: "team" }); + // An approver on a non-ask rule means nothing. + expect( + evaluateComposedPolicy({ ...sendCall, effect: "read" }, personal, [ + { id: "t", tool: "gmail_*", decision: "allow", approver: "admin" }, + ]), + ).toMatchObject({ decision: "allow", approver: null }); + }); + + test("taint still turns a combined allow into an ordinary ask", () => { + const r = evaluateComposedPolicy( + { ...sendCall, tainted: true }, + { rules: [{ id: "mine", tool: "*", decision: "allow" }] }, + [{ id: "team", tool: "*", decision: "allow" }], + ); + expect(r).toMatchObject({ decision: "ask", approver: null }); + expect(r.reason).toContain("outside content"); + }); + + test("team rules only apply where their matchers hold", () => { + const team: TeamPolicyRule[] = [ + { + id: "outside", + tool: "gmail_*", + decision: "ask", + approver: "admin", + when: [{ path: "to", op: "allEndWith", value: ["@acme.com"] }], + }, + ]; + const personal = { rules: [{ id: "mine", tool: "*", decision: "allow" as const }] }; + expect(evaluateComposedPolicy(sendCall, personal, team).approver).toBe("admin"); + expect( + evaluateComposedPolicy({ ...sendCall, input: { to: "x@evil.com" } }, personal, team), + ).toMatchObject({ decision: "allow", approver: null }); + }); + + test("plan grants satisfy ordinary asks only, never a block or an admin ask", () => { + expect(planGrantMaySatisfy({ decision: "ask", approver: null })).toBe(true); + expect(planGrantMaySatisfy({ decision: "allow", approver: null })).toBe(true); + expect(planGrantMaySatisfy({ decision: "ask", approver: "admin" })).toBe(false); + expect(planGrantMaySatisfy({ decision: "block", approver: null })).toBe(false); + }); +}); diff --git a/packages/core/src/policy.ts b/packages/core/src/policy.ts index 299950a..fdd1fb9 100644 --- a/packages/core/src/policy.ts +++ b/packages/core/src/policy.ts @@ -247,3 +247,106 @@ export function getPath(value: JSONValue, path: string): JSONValue | undefined { function deepEqual(a: JSONValue | undefined, b: JSONValue | undefined): boolean { return JSON.stringify(a) === JSON.stringify(b); } + +// ── Team policy composition ───────────────────────────────────────────────── + +/** Who must decide an `ask`: `"admin"` means a workspace owner or admin, not the requester. */ +export type Approver = "admin"; + +/** A rule set by a team workspace. Applies to every member, on top of their own rules. */ +export interface TeamPolicyRule extends PolicyRule { + /** Only meaningful on `ask` rules: a workspace admin must sign off, not the member. */ + approver?: Approver | null; +} + +export interface ComposedPolicyResult extends PolicyResult { + /** Set when a workspace admin (not the requester) must decide. */ + approver: Approver | null; + /** Which rule set decided: the team's or the person's own (rules or defaults). */ + source: "team" | "personal"; +} + +export const ADMIN_APPROVAL_REASON = "Your team requires an admin to approve this."; + +const TAINT_REASON = + "This task has read outside content (an email, web page or document), so anything that changes or sends data needs your approval."; + +/** Strictness order used to combine team and personal verdicts. */ +function strictness(v: { decision: Decision; approver: Approver | null }): number { + if (v.decision === "block") return 3; + if (v.decision === "ask") return v.approver === "admin" ? 2 : 1; + return 0; +} + +/** + * Evaluates a call against a person's own policy and their team's rules, and takes the + * strictest: block > ask (an admin must decide) > ask > allow. + * + * - Team rules have no defaults: a team rule that doesn't match has no opinion, and the + * personal policy (rules, then defaults) decides. So a team `allow` never loosens a + * personal `ask`, and a personal `allow` never loosens a team `ask` or `block`. + * - Among team rules, the first matching `block` wins, else the first matching rule. + * - Taint applies to the combined result: an `allow` of a non-read call in a tainted run + * becomes an ordinary `ask`. Stricter results (block, admin ask) are left as they are. + * - With no team rules this is exactly `evaluatePolicy`, plus `approver: null`. + */ +export function evaluateComposedPolicy( + call: PolicyInput, + personal: { rules: PolicyRule[]; defaults?: PolicyDefaults }, + teamRules: TeamPolicyRule[] = [], +): ComposedPolicyResult { + if (teamRules.length === 0) { + return { + ...evaluatePolicy(call, personal.rules, personal.defaults), + approver: null, + source: "personal", + }; + } + + const own: ComposedPolicyResult = { + ...evaluatePolicy({ ...call, tainted: false }, personal.rules, personal.defaults), + approver: null, + source: "personal", + }; + const team = evaluateTeamRules(call, teamRules); + // Ties go to the personal verdict; only the team can be stricter than it. + const result = team && strictness(team) > strictness(own) ? team : own; + + if (result.decision === "allow" && call.tainted && call.effect !== "read") { + return { ...result, decision: "ask", reason: TAINT_REASON, approver: null }; + } + return result; +} + +function evaluateTeamRules( + call: PolicyInput, + rules: TeamPolicyRule[], +): ComposedPolicyResult | null { + const matching = rules.filter( + (r) => globMatch(r.tool, call.tool) && matchesAll(r.when, call.input), + ); + const rule = matching.find((r) => r.decision === "block") ?? matching[0]; + if (!rule) return null; + const approver = rule.decision === "ask" && rule.approver === "admin" ? "admin" : null; + let reason: string; + if (rule.decision === "block") + reason = rule.note ?? `Blocked by your team's rule for “${rule.tool}”.`; + else if (approver) + reason = rule.note ? `${ADMIN_APPROVAL_REASON} ${rule.note}` : ADMIN_APPROVAL_REASON; + else if (rule.decision === "ask") + reason = rule.note ?? `Your team asks for approval on “${rule.tool}”.`; + else reason = rule.note ?? `Allowed by your team's rule for “${rule.tool}”.`; + return { decision: rule.decision, reason, ruleId: rule.id, approver, source: "team" }; +} + +/** + * Whether an exact-input plan grant may turn this verdict into an allow. A grant stands in + * for the requester's own approval, so it satisfies an ordinary ask (theirs or their + * team's) but never a block, nor an ask that an admin must decide. + */ +export function planGrantMaySatisfy(verdict: { + decision: Decision; + approver: Approver | null; +}): boolean { + return verdict.decision !== "block" && verdict.approver !== "admin"; +} diff --git a/packages/core/src/runtime.test.ts b/packages/core/src/runtime.test.ts index a381aeb..34c9471 100644 --- a/packages/core/src/runtime.test.ts +++ b/packages/core/src/runtime.test.ts @@ -519,6 +519,52 @@ describe("plan grants", () => { expect(executed).toEqual([]); }); + test("a grant can't stand in for a team admin's sign-off or beat a team block", async () => { + const { store, run, opts, events } = setup([ + { + toolCalls: [ + { name: "send_email", input: email, id: "g1" }, + { name: "send_email", input: { ...email, to: "x@y.com" }, id: "g2" }, + ], + }, + ]); + store.rules = [{ id: "mine", tool: "*", decision: "allow" }]; + store.teamRules = [ + { id: "admin", tool: "send_*", decision: "ask", approver: "admin" }, + { + id: "no-y", + tool: "send_*", + decision: "block", + when: [{ path: "to", op: "equals", value: "x@y.com" }], + }, + ]; + await grant(store, run.id, "send_email", email); + await grant(store, run.id, "send_email", { ...email, to: "x@y.com" }); + expect(await runAgent(opts)).toBe("waiting"); + expect(store.toolCalls.get("g1")).toMatchObject({ + status: "awaiting_approval", + approver: "admin", + decisionReason: "Your team requires an admin to approve this.", + }); + expect(store.toolCalls.get("g2")).toMatchObject({ status: "denied", decision: "block" }); + expect(events.events).toContainEqual( + expect.objectContaining({ type: "approval.requested", toolCallId: "g1", approver: "admin" }), + ); + expect((await store.getRun(run.id)).planGrants.every((g) => !g.usedBy)).toBe(true); + expect(executed).toEqual([]); + }); + + test("a grant still satisfies an ordinary team ask", async () => { + const { store, run, opts } = setup([ + { toolCalls: [{ name: "send_email", input: email, id: "g1" }] }, + { text: "sent" }, + ]); + store.teamRules = [{ id: "ask", tool: "send_*", decision: "ask" }]; + await grant(store, run.id, "send_email", email); + expect(await runAgent(opts)).toBe("completed"); + expect(store.toolCalls.get("g1")).toMatchObject({ status: "succeeded", approver: null }); + }); + 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: {} }] }, diff --git a/packages/core/src/runtime.ts b/packages/core/src/runtime.ts index d6232cc..a159bcd 100644 --- a/packages/core/src/runtime.ts +++ b/packages/core/src/runtime.ts @@ -22,7 +22,7 @@ import { } from "./context"; import { costUsd, isRetryable, type ModelSpec } from "./models"; import { hashInput, PLAN_GRANT_REASON } from "./plan"; -import { evaluatePolicy } from "./policy"; +import { evaluateComposedPolicy, planGrantMaySatisfy } from "./policy"; import type { EventSink, RunStore } from "./store"; import type { ToolDefinition, ToolRegistry } from "./tools"; import type { @@ -591,7 +591,8 @@ async function streamOneStep( }); continue; } - let verdict = evaluatePolicy( + // The person's own policy plus their team's rules; the strictest verdict wins. + let verdict = evaluateComposedPolicy( { tool: def.name, effect: def.effect, @@ -599,18 +600,25 @@ async function streamOneStep( tainted: run.tainted, ...(def.defaultDecision ? { defaultDecision: def.defaultDecision } : {}), }, - policy.rules, - policy.defaults, + policy, + policy.teamRules, ); // 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)) { + // user: it runs without asking again, even in a tainted run. Block rules still win, and + // so does a team rule that needs an admin: the user's own sign-off can't stand in for it. + if (planGrantMaySatisfy(verdict) && 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 }; + verdict = { + decision: "allow", + reason: PLAN_GRANT_REASON, + ruleId: null, + approver: null, + source: "personal", + }; } } const status: ToolCallStatus = @@ -625,6 +633,7 @@ async function streamOneStep( status, decision: verdict.decision, decisionReason: verdict.reason, + approver: status === "awaiting_approval" ? verdict.approver : null, output: status === "denied" ? { type: "denied", reason: `Blocked by policy: ${verdict.reason}` } @@ -670,6 +679,7 @@ async function streamOneStep( effect: call.effect, reason: call.decisionReason ?? "", preview: call.preview, + ...(call.approver ? { approver: call.approver } : {}), }); } if (call.output) diff --git a/packages/core/src/store.ts b/packages/core/src/store.ts index 08efb7a..2383b7b 100644 --- a/packages/core/src/store.ts +++ b/packages/core/src/store.ts @@ -1,5 +1,5 @@ import type { AssistantModelMessage, ModelMessage } from "ai"; -import type { PolicyDefaults, PolicyRule } from "./policy"; +import type { PolicyDefaults, PolicyRule, TeamPolicyRule } from "./policy"; import type { RunEvent, RunRecord, @@ -68,7 +68,10 @@ export interface RunStore { /** Moves user messages that arrived while the run was busy into the chat, in order. */ drainPendingInputs(chatId: string, runId: string): Promise; - getPolicy(userId: string): Promise<{ rules: PolicyRule[]; defaults: PolicyDefaults }>; + /** The person's own rules and defaults, plus their team workspace's rules (if any). */ + getPolicy( + userId: string, + ): Promise<{ rules: PolicyRule[]; defaults: PolicyDefaults; teamRules?: TeamPolicyRule[] }>; } export interface EventSink { diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index f788a9f..2016325 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -41,6 +41,11 @@ export interface ToolCallRecord { /** Output as given back to the model (already size-capped). */ output: ToolOutput | null; decidedBy: string | null; + /** + * "admin" when a team rule says a workspace admin (not the requester) must decide. + * Null or absent: the requester decides. + */ + approver?: "admin" | null; /** * Undo window (ISO time): an approved call does not run before this. Set when a person * approves a send or destructive action; null or absent means it may run now. @@ -130,6 +135,8 @@ export type RunEvent = effect: Effect; reason: string; preview: string | null; + /** "admin": a workspace admin must decide; the requester sees it as waiting. */ + approver?: "admin" | null; } | { type: "usage"; inputTokens: number; outputTokens: number; costUsd: number } | { type: "compacted"; messageId: string } diff --git a/packages/core/src/ui.ts b/packages/core/src/ui.ts index eb799ea..fc5651f 100644 --- a/packages/core/src/ui.ts +++ b/packages/core/src/ui.ts @@ -30,6 +30,8 @@ export type UiPart = preview: string | null; /** Undo window: an approved call waits until this time (ISO) before it runs. */ executeAfter?: string | null; + /** "admin": the person's team requires an admin to decide; they only wait. */ + approver?: "admin" | null; }; export interface UiMessage { @@ -102,6 +104,7 @@ export function toUiMessages(rows: StoredMessage[], calls: ToolCallRecord[]): Ui output: rec?.output ?? null, preview: rec?.preview ?? null, ...(rec?.executeAfter ? { executeAfter: rec.executeAfter } : {}), + ...(rec?.approver ? { approver: rec.approver } : {}), }); } } @@ -246,6 +249,7 @@ export function applyEvent(state: ChatState, e: SeqEvent): ChatState { status: "awaiting_approval", reason: e.reason, preview: e.preview, + ...(e.approver ? { approver: e.approver } : {}), }); case "tool.result": return updateTool(next, e.toolCallId, { output: e.output }); diff --git a/packages/db/drizzle/0006_teams.sql b/packages/db/drizzle/0006_teams.sql new file mode 100644 index 0000000..45f0ce9 --- /dev/null +++ b/packages/db/drizzle/0006_teams.sql @@ -0,0 +1,53 @@ +CREATE TABLE "workspace_invites" ( + "id" text PRIMARY KEY NOT NULL, + "workspace_id" text NOT NULL, + "token_hash" text NOT NULL, + "role" text DEFAULT 'member' NOT NULL, + "expires_at" timestamp with time zone NOT NULL, + "created_by" text, + "used_by" text, + "used_at" timestamp with time zone, + "revoked_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "workspace_invites_token_hash_unique" UNIQUE("token_hash") +); +--> statement-breakpoint +CREATE TABLE "workspace_members" ( + "workspace_id" text NOT NULL, + "user_id" text NOT NULL, + "role" text DEFAULT 'member' NOT NULL, + "joined_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "workspace_members_workspace_id_user_id_pk" PRIMARY KEY("workspace_id","user_id"), + CONSTRAINT "workspace_members_user_id_unique" UNIQUE("user_id") +); +--> statement-breakpoint +CREATE TABLE "workspace_rules" ( + "id" text PRIMARY KEY NOT NULL, + "workspace_id" text NOT NULL, + "position" integer DEFAULT 0 NOT NULL, + "tool" text NOT NULL, + "decision" text NOT NULL, + "when" jsonb, + "note" text, + "approver" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "workspaces" ( + "id" text PRIMARY KEY NOT NULL, + "name" text NOT NULL, + "created_by" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "tool_calls" ADD COLUMN "approver" text;--> statement-breakpoint +ALTER TABLE "workspace_invites" ADD CONSTRAINT "workspace_invites_workspace_id_workspaces_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspaces"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "workspace_invites" ADD CONSTRAINT "workspace_invites_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "workspace_invites" ADD CONSTRAINT "workspace_invites_used_by_user_id_fk" FOREIGN KEY ("used_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "workspace_members" ADD CONSTRAINT "workspace_members_workspace_id_workspaces_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspaces"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "workspace_members" ADD CONSTRAINT "workspace_members_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "workspace_rules" ADD CONSTRAINT "workspace_rules_workspace_id_workspaces_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspaces"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "workspaces" ADD CONSTRAINT "workspaces_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "workspace_invites_workspace_idx" ON "workspace_invites" USING btree ("workspace_id","created_at");--> statement-breakpoint +CREATE INDEX "workspace_members_role_idx" ON "workspace_members" USING btree ("workspace_id","role");--> statement-breakpoint +CREATE INDEX "workspace_rules_workspace_idx" ON "workspace_rules" USING btree ("workspace_id","position"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0006_snapshot.json b/packages/db/drizzle/meta/0006_snapshot.json new file mode 100644 index 0000000..ffa500a --- /dev/null +++ b/packages/db/drizzle/meta/0006_snapshot.json @@ -0,0 +1,2447 @@ +{ + "id": "acc70c8a-5ea0-46dd-b70e-a70d2096a6dd", + "prevId": "a1782b93-d749-4af8-8532-db47b083aa61", + "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 + }, + "approver": { + "name": "approver", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_at": { + "name": "decided_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "decided_via": { + "name": "decided_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notified_at": { + "name": "notified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "execute_after": { + "name": "execute_after", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "full_output": { + "name": "full_output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_calls_user_decided_idx": { + "name": "tool_calls_user_decided_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "decided_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "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": "'{}'" + }, + "undo_seconds": { + "name": "undo_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_settings_user_id_user_id_fk": { + "name": "user_settings_user_id_user_id_fk", + "tableFrom": "user_settings", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_invites": { + "name": "workspace_invites", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "used_by": { + "name": "used_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_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()" + } + }, + "indexes": { + "workspace_invites_workspace_idx": { + "name": "workspace_invites_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_invites_workspace_id_workspaces_id_fk": { + "name": "workspace_invites_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_invites", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_invites_created_by_user_id_fk": { + "name": "workspace_invites_created_by_user_id_fk", + "tableFrom": "workspace_invites", + "tableTo": "user", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspace_invites_used_by_user_id_fk": { + "name": "workspace_invites_used_by_user_id_fk", + "tableFrom": "workspace_invites", + "tableTo": "user", + "columnsFrom": [ + "used_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "workspace_invites_token_hash_unique": { + "name": "workspace_invites_token_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "token_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_members": { + "name": "workspace_members", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "joined_at": { + "name": "joined_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_members_role_idx": { + "name": "workspace_members_role_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_members_workspace_id_workspaces_id_fk": { + "name": "workspace_members_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_members", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_members_user_id_user_id_fk": { + "name": "workspace_members_user_id_user_id_fk", + "tableFrom": "workspace_members", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_members_workspace_id_user_id_pk": { + "name": "workspace_members_workspace_id_user_id_pk", + "columns": [ + "workspace_id", + "user_id" + ] + } + }, + "uniqueConstraints": { + "workspace_members_user_id_unique": { + "name": "workspace_members_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_rules": { + "name": "workspace_rules", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_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 + }, + "approver": { + "name": "approver", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_rules_workspace_idx": { + "name": "workspace_rules_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_rules_workspace_id_workspaces_id_fk": { + "name": "workspace_rules_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_rules", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspaces": { + "name": "workspaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "workspaces_created_by_user_id_fk": { + "name": "workspaces_created_by_user_id_fk", + "tableFrom": "workspaces", + "tableTo": "user", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "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 207d5be..6578cc6 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1792891462021, "tag": "0005_approval_channels", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1792891841920, + "tag": "0006_teams", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 7b1c261..767180c 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -5,3 +5,4 @@ export * from "./events"; export * from "./runs"; export * as schema from "./schema"; export * from "./store"; +export * from "./workspaces"; diff --git a/packages/db/src/runs.ts b/packages/db/src/runs.ts index 203b6bd..9136a4c 100644 --- a/packages/db/src/runs.ts +++ b/packages/db/src/runs.ts @@ -2,7 +2,15 @@ import { type Effect, type PlanGrant, UNDO_DENIAL } from "@synapse/core"; import type { JSONValue } from "ai"; import { and, asc, eq, inArray, isNull, lt, or, sql } from "drizzle-orm"; import type { Db } from "./client"; -import { chats, messages, pendingInputs, runs, toolCalls, userSettings } from "./schema"; +import { + chats, + messages, + pendingInputs, + runs, + toolCalls, + userSettings, + workspaceMembers, +} from "./schema"; export class NotFoundError extends Error {} @@ -216,6 +224,62 @@ export interface DecisionOutcome { requeued: boolean; /** ...and no worker may take it before this time (null: now). */ runnableAt: Date | null; + /** Whose run it is (differs from the decider when a team admin decided). */ + ownerId: string; +} + +/** The person may not decide this (e.g. a team rule says an admin must). */ +export class ForbiddenError extends Error {} + +/** + * Who may decide which call. The requester decides their own calls, except those a team + * rule reserves for an admin (`approver = 'admin'`): only an owner or admin of the + * requester's current workspace may decide those, which includes a requester who is an + * admin themselves. If the requester has since left the workspace, its rules no longer + * govern them and they decide it themselves. Anyone else gets "not found", as before. + */ +export async function assertMayDecide( + tx: Db, + run: { id: string; userId: string }, + args: { userId: string; decisions: ToolCallDecision[] }, +): Promise { + const ids = args.decisions.map((d) => d.toolCallId); + const calls = ids.length + ? await tx + .select({ id: toolCalls.id, approver: toolCalls.approver }) + .from(toolCalls) + .where(and(eq(toolCalls.runId, run.id), inArray(toolCalls.id, ids))) + : []; + const own = run.userId === args.userId; + const needsAdmin = calls.some((c) => c.approver === "admin"); + if (!own && !needsAdmin) throw new NotFoundError("run not found"); + if (!needsAdmin) return; + + const [requester, decider] = await Promise.all([ + tx + .select({ workspaceId: workspaceMembers.workspaceId }) + .from(workspaceMembers) + .where(eq(workspaceMembers.userId, run.userId)), + tx + .select({ workspaceId: workspaceMembers.workspaceId, role: workspaceMembers.role }) + .from(workspaceMembers) + .where(eq(workspaceMembers.userId, args.userId)), + ]); + const team = requester[0]?.workspaceId; + const deciderIsAdmin = + team !== undefined && + decider[0]?.workspaceId === team && + (decider[0].role === "owner" || decider[0].role === "admin"); + + if (!own) { + if (!deciderIsAdmin) throw new NotFoundError("run not found"); + // An admin decides only the calls reserved for an admin, never the member's own. + if (calls.length !== ids.length || calls.some((c) => c.approver !== "admin")) + throw new NotFoundError("action not found"); + return; + } + if (team !== undefined && !deciderIsAdmin) + throw new ForbiddenError("Your team requires an admin to approve this."); } /** @@ -255,16 +319,18 @@ export async function decideToolCalls( ): Promise { return db.transaction(async (tx) => { const [run] = await tx - .select({ id: runs.id, status: runs.status }) + .select({ id: runs.id, status: runs.status, userId: runs.userId }) .from(runs) - .where(and(eq(runs.id, args.runId), eq(runs.userId, args.userId))) + .where(eq(runs.id, args.runId)) .for("update"); if (!run) throw new NotFoundError("run not found"); + await assertMayDecide(tx as unknown as Db, run, args); + // The requester's undo window applies, whoever approves. const [settings] = await tx .select({ undoSeconds: userSettings.undoSeconds }) .from(userSettings) - .where(eq(userSettings.userId, args.userId)); + .where(eq(userSettings.userId, run.userId)); const executeAfter: Record = {}; for (const d of args.decisions) { @@ -293,7 +359,7 @@ export async function decideToolCalls( and( eq(toolCalls.runId, run.id), eq(toolCalls.id, d.toolCallId), - eq(toolCalls.userId, args.userId), + eq(toolCalls.userId, run.userId), eq(toolCalls.status, "awaiting_approval"), ), ) @@ -317,9 +383,9 @@ export async function decideToolCalls( .update(runs) .set({ status: "queued", leaseExpiresAt: at }) .where(eq(runs.id, run.id)); - return { executeAfter, requeued: true, runnableAt: at }; + return { executeAfter, requeued: true, runnableAt: at, ownerId: run.userId }; } - return { executeAfter, requeued: false, runnableAt: null }; + return { executeAfter, requeued: false, runnableAt: null, ownerId: run.userId }; }); } diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index a7f1252..5bd6b8b 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -138,6 +138,81 @@ export const policyRules = pgTable( (t) => [index("policy_rules_user_idx").on(t.userId, t.position)], ); +// ── Team workspaces ──────────────────────────────────────────────────────── + +export type WorkspaceRole = "owner" | "admin" | "member"; + +/** + * A team. Its rules apply to every member on top of their own; tasks, connections and + * memory stay personal. + */ +export const workspaces = pgTable("workspaces", { + id: id(), + name: text("name").notNull(), + createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }), + createdAt: createdAt(), +}); + +export const workspaceMembers = pgTable( + "workspace_members", + { + workspaceId: text("workspace_id") + .notNull() + .references(() => workspaces.id, { onDelete: "cascade" }), + /** One workspace per person for now. */ + userId: text("user_id") + .notNull() + .unique() + .references(() => user.id, { onDelete: "cascade" }), + role: text("role").$type().notNull().default("member"), + joinedAt: timestamp("joined_at", { withTimezone: true }).notNull().defaultNow(), + }, + (t) => [ + primaryKey({ columns: [t.workspaceId, t.userId] }), + index("workspace_members_role_idx").on(t.workspaceId, t.role), + ], +); + +/** Invite links. Only a SHA-256 of the token is stored; the link is shown once. */ +export const workspaceInvites = pgTable( + "workspace_invites", + { + id: id(), + workspaceId: text("workspace_id") + .notNull() + .references(() => workspaces.id, { onDelete: "cascade" }), + tokenHash: text("token_hash").notNull().unique(), + role: text("role").$type>().notNull().default("member"), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }), + usedBy: text("used_by").references(() => user.id, { onDelete: "set null" }), + usedAt: timestamp("used_at", { withTimezone: true }), + revokedAt: timestamp("revoked_at", { withTimezone: true }), + createdAt: createdAt(), + }, + (t) => [index("workspace_invites_workspace_idx").on(t.workspaceId, t.createdAt)], +); + +/** Team policy rules: like `policy_rules`, plus who must decide an `ask`. */ +export const workspaceRules = pgTable( + "workspace_rules", + { + id: id(), + workspaceId: text("workspace_id") + .notNull() + .references(() => workspaces.id, { onDelete: "cascade" }), + position: integer("position").notNull().default(0), + tool: text("tool").notNull(), + decision: text("decision").$type().notNull(), + when: jsonb("when").$type(), + note: text("note"), + /** "admin": a workspace owner or admin must approve, not the member. */ + approver: text("approver").$type<"admin">(), + createdAt: createdAt(), + }, + (t) => [index("workspace_rules_workspace_idx").on(t.workspaceId, t.position)], +); + // ── Chats, runs, messages ───────────────────────────────────────────────── export const chats = pgTable( @@ -239,6 +314,8 @@ export const toolCalls = pgTable( decisionReason: text("decision_reason"), preview: text("preview"), decidedBy: text("decided_by"), + /** "admin" when a team rule says a workspace admin, not the requester, must decide. */ + approver: text("approver").$type<"admin">(), decidedAt: timestamp("decided_at", { withTimezone: true }), /** Where the person decided: web, push, slack, email. */ decidedVia: text("decided_via"), diff --git a/packages/db/src/store.ts b/packages/db/src/store.ts index d4ba3aa..29b9c73 100644 --- a/packages/db/src/store.ts +++ b/packages/db/src/store.ts @@ -17,6 +17,7 @@ import { toolCalls, userSettings, } from "./schema"; +import { teamRulesFor } from "./workspaces"; type MessageRow = typeof messages.$inferSelect; type ToolCallRow = typeof toolCalls.$inferSelect; @@ -48,6 +49,7 @@ function toRecord(r: ToolCallRow): ToolCallRecord { decisionReason: r.decisionReason, output: r.output, decidedBy: r.decidedBy, + approver: r.approver ?? null, preview: r.preview, executeAfter: r.executeAfter?.toISOString() ?? null, }; @@ -243,6 +245,8 @@ export class PgRunStore implements RunStore { .from(userSettings) .where(eq(userSettings.userId, userId)); return { + // Rules of the person's team workspace, composed with theirs by the runtime. + teamRules: await teamRulesFor(this.db, userId), rules: rules.map( (r): PolicyRule => ({ id: r.id, diff --git a/packages/db/src/workspaces.ts b/packages/db/src/workspaces.ts new file mode 100644 index 0000000..9aa4f8e --- /dev/null +++ b/packages/db/src/workspaces.ts @@ -0,0 +1,63 @@ +import type { TeamPolicyRule } from "@synapse/core"; +import { and, asc, eq, inArray } from "drizzle-orm"; +import type { Db } from "./client"; +import { type WorkspaceRole, workspaceMembers, workspaceRules } from "./schema"; + +/** Roles that may decide calls a team rule reserves for an admin, and manage the team. */ +export const ADMIN_ROLES: WorkspaceRole[] = ["owner", "admin"]; + +export function isAdminRole(role: WorkspaceRole | null | undefined): boolean { + return role === "owner" || role === "admin"; +} + +/** The person's workspace and role, or null when they are not in one. */ +export async function membershipOf( + db: Db, + userId: string, +): Promise<{ workspaceId: string; role: WorkspaceRole } | null> { + const [row] = await db + .select({ workspaceId: workspaceMembers.workspaceId, role: workspaceMembers.role }) + .from(workspaceMembers) + .where(eq(workspaceMembers.userId, userId)); + return row ?? null; +} + +/** User ids of a workspace's owners and admins. */ +export async function workspaceAdminIds(db: Db, workspaceId: string): Promise { + const rows = await db + .select({ userId: workspaceMembers.userId }) + .from(workspaceMembers) + .where( + and( + eq(workspaceMembers.workspaceId, workspaceId), + inArray(workspaceMembers.role, ADMIN_ROLES), + ), + ) + .orderBy(asc(workspaceMembers.joinedAt)); + return rows.map((r) => r.userId); +} + +/** A workspace's rules, in order, in the shape the policy engine takes. */ +export async function loadTeamRules(db: Db, workspaceId: string): Promise { + const rows = await db + .select() + .from(workspaceRules) + .where(eq(workspaceRules.workspaceId, workspaceId)) + .orderBy(asc(workspaceRules.position), asc(workspaceRules.createdAt)); + return rows.map( + (r): TeamPolicyRule => ({ + id: r.id, + tool: r.tool, + decision: r.decision, + ...(r.when ? { when: r.when } : {}), + ...(r.note ? { note: r.note } : {}), + ...(r.approver ? { approver: r.approver } : {}), + }), + ); +} + +/** The team rules that apply to a person (empty when they are not in a workspace). */ +export async function teamRulesFor(db: Db, userId: string): Promise { + const membership = await membershipOf(db, userId); + return membership ? loadTeamRules(db, membership.workspaceId) : []; +} From b1c571a116c737241caf5d1e2800739e544de346 Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:18:54 +0530 Subject: [PATCH 06/10] Teams across channels: leaving withdraws admin-only requests; admins approve from Slack - A member who leaves (or is removed) can't approve, alone, what needed an admin: their pending admin-only calls are denied and the run re-queued so the agent can respond - Test: a member's admin-only request reaches the admin's Slack, and the admin approves it there (decided_by = admin, decided_via = slack) --- apps/server/src/notify/slack.ts | 4 ++- apps/server/src/routes/workspace.ts | 52 ++++++++++++++++++++++++++++- apps/server/src/slack.test.ts | 38 +++++++++++++++++++++ apps/server/src/teams.test.ts | 11 ++++-- 4 files changed, 100 insertions(+), 5 deletions(-) diff --git a/apps/server/src/notify/slack.ts b/apps/server/src/notify/slack.ts index ee9e6af..9b115e2 100644 --- a/apps/server/src/notify/slack.ts +++ b/apps/server/src/notify/slack.ts @@ -1,5 +1,5 @@ import type { Effect } from "@synapse/core"; -import { ConflictError, NotFoundError, schema } from "@synapse/db"; +import { ConflictError, ForbiddenError, NotFoundError, schema } from "@synapse/db"; import type { JSONValue } from "ai"; import { and, eq, inArray } from "drizzle-orm"; import { DecisionInputError, decide } from "../decisions"; @@ -235,6 +235,8 @@ export class SlackChannel implements NotificationChannel { // e.g. sent to someone who may see it but not decide it here (not the task's owner). if (error instanceof NotFoundError) return refuse("This one can't be decided from Slack. Open it in Synapse."); + if (error instanceof ForbiddenError) + return refuse("Your team needs an admin to decide this one."); if (error instanceof DecisionInputError) return refuse(error.message); throw error; } diff --git a/apps/server/src/routes/workspace.ts b/apps/server/src/routes/workspace.ts index fe10713..dde6805 100644 --- a/apps/server/src/routes/workspace.ts +++ b/apps/server/src/routes/workspace.ts @@ -1,4 +1,4 @@ -import { isAdminRole, loadTeamRules, membershipOf, schema } from "@synapse/db"; +import { type Db, isAdminRole, loadTeamRules, membershipOf, schema } from "@synapse/db"; import { and, asc, count, desc, eq, gt, gte, isNull, lt, sql } from "drizzle-orm"; import { alias } from "drizzle-orm/pg-core"; import { Hono } from "hono"; @@ -285,6 +285,7 @@ export const workspace = new Hono() if (!self && !isAdminRole(m.role)) apiError(403, "forbidden", "Only team owners and admins can remove people."); const { db } = c.var.services.database; + let withdrawn: string[] = []; await db.transaction(async (tx) => { const members = await tx .select({ userId: schema.workspaceMembers.userId, role: schema.workspaceMembers.role }) @@ -314,7 +315,9 @@ export const workspace = new Hono() eq(schema.workspaceMembers.userId, targetId), ), ); + withdrawn = await withdrawAdminRequests(tx as unknown as Db, targetId); }); + for (const runId of withdrawn) await c.var.services.wake(runId); return c.body(null, 204); }) @@ -509,3 +512,50 @@ export function toCsv(header: string[], rows: (string | null | undefined)[][]): }; return `${[header, ...rows].map((r) => r.map(cell).join(",")).join("\r\n")}\r\n`; } + +/** + * Someone leaving (or being removed from) a team must not be able to approve, on their own, + * an action the team said needs an admin. Their pending admin-required calls are denied, and + * runs left with nothing to wait for are re-queued so the agent can respond. Returns them. + */ +async function withdrawAdminRequests(tx: Db, userId: string): Promise { + const denied = await tx + .update(schema.toolCalls) + .set({ + status: "denied", + decidedAt: new Date(), + decisionReason: "Left the team before an admin decided.", + output: { + type: "denied", + reason: + "This needed a team admin's approval, and the user left the team before an admin decided. Don't retry it; ask the user what they want to do instead.", + }, + }) + .where( + and( + eq(schema.toolCalls.userId, userId), + eq(schema.toolCalls.approver, "admin"), + eq(schema.toolCalls.status, "awaiting_approval"), + ), + ) + .returning({ runId: schema.toolCalls.runId }); + const runIds = [...new Set(denied.map((d) => d.runId))]; + const requeued: string[] = []; + for (const runId of runIds) { + const [left] = await tx + .select({ id: schema.toolCalls.id }) + .from(schema.toolCalls) + .where( + and(eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.status, "awaiting_approval")), + ) + .limit(1); + if (left) continue; + const updated = await tx + .update(schema.runs) + .set({ status: "queued", leaseExpiresAt: null }) + .where(and(eq(schema.runs.id, runId), eq(schema.runs.status, "waiting"))) + .returning({ id: schema.runs.id }); + if (updated.length) requeued.push(runId); + } + return requeued; +} diff --git a/apps/server/src/slack.test.ts b/apps/server/src/slack.test.ts index c2c875e..cfa3b85 100644 --- a/apps/server/src/slack.test.ts +++ b/apps/server/src/slack.test.ts @@ -308,3 +308,41 @@ test("rendering: email inputs, key fields, outcome lines, signatures", () => { ); expect(verifySlackSignature("s", { timestamp: undefined, signature: "x", body: "" })).toBe(false); }); + +test("a team admin gets the member's admin-only request in Slack and approves it there", async () => { + const admin = await signUp("boss@team.com"); + const member = await signUp("dev@team.com"); + await connectSlack(admin, "U-boss"); + await admin("/api/workspace", { method: "POST", json: { name: "Team" } }); + const { json: inv } = await admin("/api/workspace/invites", { + method: "POST", + json: { role: "member" }, + }); + const token = new URL(inv.link).pathname.split("/").pop(); + expect((await member("/api/workspace/join", { method: "POST", json: { token } })).status).toBe( + 200, + ); + await admin("/api/workspace/rules", { + method: "PUT", + json: { rules: [{ tool: "memory_save", decision: "ask", approver: "admin" }] }, + }); + script([ + { toolCalls: [{ name: "memory_save", input: { note: "x" }, id: "n1" }] }, + { text: "ok" }, + ]); + const { json } = await member("/api/chats", { method: "POST", json: { content: "remember x" } }); + const runId = json.runId as string; + await worker.processNow(runId); + await services.slack!.settled(); + + const [msg] = slack.dms("U-boss"); + expect(msg).toBeTruthy(); + const res = await click(slack.click(msg!, "approve", { signingSecret: SIGNING, user: "U-boss" })); + expect(res.status).toBe(200); + const decided = await call(runId); + const [boss] = await services.database.db + .select({ id: schema.user.id }) + .from(schema.user) + .where(eq(schema.user.email, "boss@team.com")); + expect(decided).toMatchObject({ status: "approved", decidedVia: "slack", decidedBy: boss!.id }); +}); diff --git a/apps/server/src/teams.test.ts b/apps/server/src/teams.test.ts index efe0fa8..2d64019 100644 --- a/apps/server/src/teams.test.ts +++ b/apps/server/src/teams.test.ts @@ -501,7 +501,7 @@ describe("workspaces", () => { ).toBe(200); }); - test("after leaving the team, a member decides their own waiting call", async () => { + test("leaving the team withdraws calls that were waiting for an admin", async () => { const owner = await signUp("o@left.com"); const member = await signUp("m@left.com"); await owner.call("/api/workspace", { method: "POST", json: { name: "Left" } }); @@ -523,11 +523,16 @@ describe("workspaces", () => { expect( (await member.call(`/api/workspace/members/${member.id}`, { method: "DELETE" })).status, ).toBe(204); - // The team's admins can no longer decide it; the member can. + // Leaving is not a way around the admin: the call is withdrawn, and nobody can approve it. expect((await owner.call(path, { method: "POST", json: { approved: true } })).status).toBe(404); expect((await member.call(path, { method: "POST", json: { approved: true } })).status).toBe( - 200, + 409, ); + const detail = await member.call(`/api/runs/${json.runId}`); + expect(detail.json.toolCalls[0]).toMatchObject({ id: "l1", status: "denied" }); + // The run was re-queued so the agent can tell the member what happened. + await worker.processNow(json.runId); + expect((await member.call(`/api/runs/${json.runId}`)).json.run.status).toBe("completed"); }); }); From 737d636a828ff5b5b7e287a31598acb3674d5722 Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:21:11 +0530 Subject: [PATCH 07/10] Inbox header counts calls waiting for an admin separately --- apps/web/app/(app)/inbox/page.tsx | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/apps/web/app/(app)/inbox/page.tsx b/apps/web/app/(app)/inbox/page.tsx index f0d4eb1..7c946be 100644 --- a/apps/web/app/(app)/inbox/page.tsx +++ b/apps/web/app/(app)/inbox/page.tsx @@ -212,7 +212,12 @@ export default function InboxPage() { const loading = approvals === null; const empty = !loading && ordered.length === 0; - const signed = ordered.length - pending.length; + // Calls waiting for a team admin are in the list but are neither yours to sign nor signed. + const withAdmin = ordered.filter((a) => waitingIds.has(a.toolCallId)).length; + const signed = ordered.length - pending.length - withAdmin; + const adminNote = withAdmin + ? ` · ${withAdmin === 1 ? "one" : withAdmin} waiting for an admin` + : ""; return (
@@ -234,10 +239,12 @@ export default function InboxPage() { {loading ? "Loading…" : pending.length - ? `${pending.length === 1 ? "One thing" : `${pending.length} things`} waiting for your signature${signed ? ` · ${signed} signed` : ""}` + ? `${pending.length === 1 ? "One thing" : `${pending.length} things`} waiting for your signature${signed ? ` · ${signed} signed` : ""}${adminNote}` : signed - ? `All signed · ${signed} this visit` - : "Nothing waiting on you"} + ? `All signed · ${signed} this visit${adminNote}` + : withAdmin + ? `Nothing for you to sign${adminNote}` + : "Nothing waiting on you"}

From 4c9a9459310da7196a16baa95ba536512f18cbbf Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:21:24 +0530 Subject: [PATCH 08/10] Lint ignores local .data folders (dev secrets and keys) --- biome.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/biome.json b/biome.json index d99fd3e..287a061 100644 --- a/biome.json +++ b/biome.json @@ -1,7 +1,7 @@ { "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json", "files": { - "includes": ["**", "!**/node_modules", "!**/.next", "!**/drizzle/meta", "!bun.lock", "!.claude"] + "includes": ["**", "!**/node_modules", "!**/.next", "!**/drizzle/meta", "!bun.lock", "!.claude", "!**/.data"] }, "formatter": { "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 }, "linter": { "rules": { "preset": "recommended", "style": { "noNonNullAssertion": "off" } } }, From 238b0924463b4edc71e6ed3819743f2b0f983b1d Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:21:34 +0530 Subject: [PATCH 09/10] Format biome.json --- biome.json | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/biome.json b/biome.json index 287a061..ccbb13b 100644 --- a/biome.json +++ b/biome.json @@ -1,7 +1,15 @@ { "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json", "files": { - "includes": ["**", "!**/node_modules", "!**/.next", "!**/drizzle/meta", "!bun.lock", "!.claude", "!**/.data"] + "includes": [ + "**", + "!**/node_modules", + "!**/.next", + "!**/drizzle/meta", + "!bun.lock", + "!.claude", + "!**/.data" + ] }, "formatter": { "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 }, "linter": { "rules": { "preset": "recommended", "style": { "noNonNullAssertion": "off" } } }, From a1c82ea562aab86c83793aed500817205996aa58 Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:22:17 +0530 Subject: [PATCH 10/10] README: phone approvals --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3a5b227..4acfdac 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Agent products that act in your tools share three problems: approvals that live - Approve a plan, not every step: the agent proposes the exact actions it will take, you untick what you don't want, and the kept actions run without asking again (even after the task read outside content, because you saw each one) - Several pending actions from one step can be ticked and signed off together - Approvals that learn: after you approve the same kind of action unchanged a few times, Synapse offers a visible, removable rule ("emails where every address is @acme.com"). Tasks that read outside content still ask +- Approve from your phone: install Synapse as an app and get push notifications with Approve and Deny buttons (the undo window still applies), or opt in to email alerts ([setup](docs/notifications.md)) - Approve from Slack: approvals arrive as a DM with Approve and Deny buttons, and the message updates wherever you decide ([setup](docs/slack.md)) - Undo window: approved sends and deletes wait a few seconds (default 10, configurable) with an Undo button - Team workspaces: one set of rules for everyone in the team (the strictest answer wins, a team block can't be overridden), risky actions routed to an admin for sign-off, invite links, and a CSV audit export. Tasks, connections and memory stay personal ([how it works](docs/teams.md))