From fff487c9977aff586d9b7b6abf5b5caa6edd088c Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:51:08 +0530 Subject: [PATCH 1/3] Gmail attachments and Google Sheets tools - gmail_read_thread lists each message's attachments (id, name, type, size) - gmail_save_attachment (read, untrusted) copies an attachment into the user's files: text and PDFs are extracted and indexed, photos become viewable with file_read, anything can be forwarded with gmail_send. Matches by name when Gmail's per-fetch attachment id changed, sniffs octet-stream types, refuses over 25 MB before downloading - New optional Sheets scope group (spreadsheets) with sheets_read, sheets_append, sheets_update and sheets_create; ids or links accepted, writes check the spreadsheet title the approval card shows - Risk facts: "Overwrites N cells" and "Includes formulas" - Approval card shows sheet writes as a table; Connections lists the tools - Fake Google covers attachments and the Sheets API; tests incl. an invoice-to-sheet run with approval - Docs: google.md, README, api.md --- README.md | 7 +- apps/server/src/google-tools.test.ts | 91 +++++- apps/server/src/routes/integrations.ts | 10 + apps/server/src/worker.ts | 10 +- apps/web/app/(app)/connections/page.tsx | 16 +- apps/web/components/approval/payload.tsx | 107 +++++++ apps/web/lib/api.ts | 2 +- docs/api.md | 4 +- docs/google.md | 59 ++-- packages/core/src/risk.test.ts | 25 ++ packages/core/src/risk.ts | 22 ++ packages/tools/src/google/client.ts | 3 +- packages/tools/src/google/gmail.ts | 149 ++++++++- packages/tools/src/google/google.test.ts | 325 ++++++++++++++++++- packages/tools/src/google/sheets.ts | 389 +++++++++++++++++++++++ packages/tools/src/google/testing.ts | 206 ++++++++++-- packages/tools/src/index.ts | 8 +- 17 files changed, 1363 insertions(+), 70 deletions(-) create mode 100644 packages/tools/src/google/sheets.ts diff --git a/README.md b/README.md index d4c8152..b9f2a4c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **An open-source agent that does real work in your tools — and can't be talked into doing the wrong thing.** -SynapseAI works in the services you already use (Gmail, Google Calendar, Drive, Contacts and Slack built in; GitHub, Linear, Notion, Jira, Sentry, or any [MCP](https://modelcontextprotocol.io) server), takes multi-step actions on your behalf, and asks before anything that writes, sends or deletes. It doesn't wait to be asked: automations start work on a schedule, when an email arrives, or when another app calls a webhook. Approvals are enforced in code, not in the prompt; once the agent has read untrusted content such as an email or a web page, every outward action needs your sign-off. Self-host it with one command, bring your own model keys, and see exactly what it did and what it cost. +SynapseAI works in the services you already use (Gmail, Google Calendar, Drive, Sheets, Contacts and Slack built in; GitHub, Linear, Notion, Jira, Sentry, or any [MCP](https://modelcontextprotocol.io) server), takes multi-step actions on your behalf, and asks before anything that writes, sends or deletes. It doesn't wait to be asked: automations start work on a schedule, when an email arrives, or when another app calls a webhook. Approvals are enforced in code, not in the prompt; once the agent has read untrusted content such as an email or a web page, every outward action needs your sign-off. Self-host it with one command, bring your own model keys, and see exactly what it did and what it cost. ![A task waiting for approval: the agent drafted an email and shows it as an editable card, with the activity timeline on the right](docs/screenshots/task.png) @@ -26,8 +26,9 @@ Agent products that act in your tools share three problems: approvals that live ## Features - Chat with live streaming (reasoning, tool calls, results) that resumes after reconnects -- Built-in Gmail and Google Calendar: search, read threads, draft, reply in-thread, label and archive, find free time, book and move meetings, answer invitations ([setup](docs/google.md)) +- Built-in Gmail and Google Calendar: search, read threads, open attachments (PDFs read, photos seen), draft, reply in-thread, label and archive, find free time, book and move meetings, answer invitations ([setup](docs/google.md)) - Built-in Google Drive and Contacts: search Drive and read Docs, Sheets, Slides and PDFs, create Google Docs (with approval), and look people up by name so "email Sam" just works +- Built-in Google Sheets: read any sheet by link, add rows, update cells and create spreadsheets, each write shown as a table on the approval card ("save the invoice from that email and add its total to my Expenses sheet") - Automations triggered by a cron schedule, new Gmail messages matching a search, or a secret webhook URL - MCP connections over Streamable HTTP with OAuth 2.1 + PKCE, or bearer tokens; presets for GitHub, Linear, Notion, Atlassian, Sentry - Approval inbox, editable approvals, deny-with-reason, cancel now / after this step @@ -96,7 +97,7 @@ The server is stateless apart from Postgres. Run the API and workers separately |---|---| | `packages/core` | Host-agnostic agent runtime: run loop, approval state machine, policy, compaction, model fallback, client event reducer. No database or HTTP. | | `packages/db` | Drizzle schema and migrations, Postgres store for the runtime, run leasing, ordered event log, secret encryption. | -| `packages/tools` | Gmail, Calendar, Drive and Contacts, Slack, MCP client with OAuth, SSRF guard, web search/fetch, knowledge base, memory. | +| `packages/tools` | Gmail, Calendar, Drive, Sheets and Contacts, Slack, MCP client with OAuth, SSRF guard, web search/fetch, knowledge base, memory. | | `packages/evals` | Scenario harness (task + safety) with simulated users; `bun run evals`. | | `apps/server` | HTTP API, auth, SSE, worker. | | `apps/web` | Next.js UI. | diff --git a/apps/server/src/google-tools.test.ts b/apps/server/src/google-tools.test.ts index 574e227..12025de 100644 --- a/apps/server/src/google-tools.test.ts +++ b/apps/server/src/google-tools.test.ts @@ -1,7 +1,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test"; import { type ScriptedStep, scriptedModel } from "@synapse/core/testing"; import { schema } from "@synapse/db"; -import { fakeGoogle, LEGACY_GOOGLE_SCOPE } from "@synapse/tools/testing"; +import { fakeGoogle, LEGACY_GOOGLE_SCOPE, tinyPdf } from "@synapse/tools/testing"; import { and, eq } from "drizzle-orm"; import { createApp } from "./app"; import { loadConfig } from "./config"; @@ -89,7 +89,7 @@ async function run(runId: string) { return row!; } -test("a grant from before Drive and Contacts keeps working and asks for a reconnect", async () => { +test("a grant from before Drive, Contacts and Sheets keeps working and asks for a reconnect", async () => { const ada = await signUp("legacy@gtools.test"); await connectGoogle(ada, LEGACY_GOOGLE_SCOPE); const status = await ada("/api/integrations"); @@ -97,6 +97,7 @@ test("a grant from before Drive and Contacts keeps working and asks for a reconn expect(status.json.google.connection.missing.map((m: { label: string }) => m.label)).toEqual([ "Drive", "Contacts", + "Sheets", ]); expect( status.json.google.tools.find((t: { name: string }) => t.name === "drive_create_doc").group, @@ -111,7 +112,7 @@ test("a grant from before Drive and Contacts keeps working and asks for a reconn await worker.processNow(chat.json.runId); expect((await toolCall(chat.json.runId, "d1")).status).not.toBe("succeeded"); const prompt = JSON.stringify(model.calls[0]?.prompt); - expect(prompt).toContain("Drive and Contacts: not granted yet"); + expect(prompt).toContain("Drive, Contacts and Sheets: not granted yet"); await connectGoogle(ada); expect((await ada("/api/integrations")).json.google.connection.missing).toEqual([]); @@ -171,3 +172,87 @@ test("creating a Doc asks first, then uploads it as a Google Doc", async () => { expect(google.state.createdDocs.map((d) => d.name)).toEqual(["Launch plan"]); expect(google.state.createdDocs[0]!.html).toContain("

Launch

"); }); + +test("“save the invoice PDF and add its total to my sheet”: reads run, the append asks", async () => { + const ada = await signUp("sheets@gtools.test"); + await connectGoogle(ada); + await ada("/api/settings", { method: "PUT", json: { undoSeconds: 0 } }); + const id = "1ExPeNsEs0123456789abcdefghij"; + google.state.spreadsheets.push({ + id, + title: "Expenses", + sheets: [{ sheetId: 0, title: "Sheet1", rows: [["Date", "Vendor", "Total"]] }], + }); + const mail = google.receive({ + from: "billing@acme.example", + subject: "Invoice 4471", + body: "Your invoice is attached.", + attachments: [ + { filename: "invoice-4471.pdf", mimeType: "application/pdf", data: tinyPdf("Total 1234.50") }, + ], + }); + const link = `https://docs.google.com/spreadsheets/d/${id}/edit`; + const chat = await ada("/api/chats", { + method: "POST", + json: { + content: `Save the invoice PDF from Acme's email and add its total to my sheet ${link}`, + }, + }); + const append = { + spreadsheet: link, + spreadsheetTitle: "Expenses", + range: "Sheet1", + rows: [["2026-10-31", "Acme", 1234.5]], + }; + script([ + { toolCalls: [{ name: "gmail_read_thread", id: "r1", input: { threadId: mail.threadId } }] }, + { + toolCalls: [ + { + name: "gmail_save_attachment", + id: "a1", + // An id from an earlier fetch: Gmail's change every time, the name still matches. + input: { messageId: mail.id, attachmentId: "stale", filename: "invoice-4471.pdf" }, + }, + { name: "sheets_read", id: "q1", input: { spreadsheet: link, range: "Sheet1" } }, + ], + }, + { toolCalls: [{ name: "sheets_append", id: "w1", input: append }] }, + { text: "Added Acme's 1,234.50 to Expenses." }, + ]); + await worker.processNow(chat.json.runId); + for (const read of ["r1", "a1", "q1"]) + expect((await toolCall(chat.json.runId, read)).status).toBe("succeeded"); + const saved = (await toolCall(chat.json.runId, "a1")).output as unknown as { + value: { fileId: string; mimeType: string }; + }; + expect(saved.value.mimeType).toBe("application/pdf"); + const [file] = await services.database.db + .select() + .from(schema.files) + .where(eq(schema.files.id, saved.value.fileId)); + expect(file?.text).toContain("Total 1234.50"); + expect((await ada(`/api/files/${saved.value.fileId}`)).status).toBe(200); + expect((await run(chat.json.runId)).tainted).toBe(true); + + const waiting = await toolCall(chat.json.runId, "w1"); + expect(waiting.status).toBe("awaiting_approval"); + expect(waiting.preview).toBe("Add 1 row to “Expenses” › Sheet1"); + expect(google.state.sheetWrites).toHaveLength(0); + const [approval] = (await ada("/api/approvals")).json.approvals; + expect(approval.facts).toEqual(["After reading outside content"]); + + await ada(`/api/runs/${chat.json.runId}/tool-calls/w1/decision`, { + method: "POST", + json: { approved: true }, + }); + await worker.processNow(chat.json.runId); + expect((await toolCall(chat.json.runId, "w1")).status).toBe("succeeded"); + expect(google.state.spreadsheets[0]!.sheets[0]!.rows).toEqual([ + ["Date", "Vendor", "Total"], + ["2026-10-31", "Acme", 1234.5], + ]); + expect(google.state.sheetWrites).toEqual([ + { kind: "append", range: "Sheet1", valueInputOption: "USER_ENTERED" }, + ]); +}); diff --git a/apps/server/src/routes/integrations.ts b/apps/server/src/routes/integrations.ts index bb1e748..03386ee 100644 --- a/apps/server/src/routes/integrations.ts +++ b/apps/server/src/routes/integrations.ts @@ -17,6 +17,12 @@ import { slackStatus } from "./slack"; const GOOGLE_TOOLS = [ { name: "gmail_search", group: "gmail", effect: "read", title: "Search email" }, { name: "gmail_read_thread", group: "gmail", effect: "read", title: "Read a conversation" }, + { + name: "gmail_save_attachment", + group: "gmail", + effect: "read", + title: "Open attachments", + }, { name: "gmail_create_draft", group: "gmail", effect: "write", title: "Save a draft" }, { name: "gmail_organize", group: "gmail", effect: "write", title: "Label, archive, mark read" }, { name: "gmail_send", group: "gmail", effect: "send", title: "Send email" }, @@ -41,6 +47,10 @@ const GOOGLE_TOOLS = [ { name: "drive_read", group: "drive", effect: "read", title: "Read Docs, Sheets, PDFs" }, { name: "drive_create_doc", group: "drive", effect: "write", title: "Create Google Docs" }, { name: "contacts_search", group: "contacts", effect: "read", title: "Look up contacts" }, + { name: "sheets_read", group: "sheets", effect: "read", title: "Read Sheets" }, + { name: "sheets_append", group: "sheets", effect: "write", title: "Add rows to Sheets" }, + { name: "sheets_update", group: "sheets", effect: "write", title: "Change cells" }, + { name: "sheets_create", group: "sheets", effect: "write", title: "Create Sheets" }, ] as const satisfies readonly { name: string; group: GoogleScopeGroup; diff --git a/apps/server/src/worker.ts b/apps/server/src/worker.ts index 23144ed..a12bb60 100644 --- a/apps/server/src/worker.ts +++ b/apps/server/src/worker.ts @@ -238,10 +238,14 @@ export class Worker { ); if (toolset.google) { const { missing } = toolset.google; - const extra = ["Drive", "Contacts"].filter((g) => !missing.includes(g)); + const extra = ["Drive", "Contacts", "Sheets"].filter((g) => !missing.includes(g)); // Withheld groups are named so the agent can tell the user how to get them. - const later = missing.length - ? ` (${missing.join(" and ")}: not granted yet; the user can reconnect Google under Connections)` + const names = + missing.length > 1 + ? `${missing.slice(0, -1).join(", ")} and ${missing.at(-1)}` + : missing[0]; + const later = names + ? ` (${names}: not granted yet; the user can reconnect Google under Connections)` : ""; conns.unshift({ name: `Gmail, Google Calendar${extra.map((g) => `, Google ${g}`).join("")}${later}`, diff --git a/apps/web/app/(app)/connections/page.tsx b/apps/web/app/(app)/connections/page.tsx index 42eabf5..87e93ef 100644 --- a/apps/web/app/(app)/connections/page.tsx +++ b/apps/web/app/(app)/connections/page.tsx @@ -114,7 +114,7 @@ export default function ConnectionsPage() { setAdding(true)}> @@ -630,15 +630,19 @@ function SampleConnections() { ); } +/** "Drive", "Drive and Sheets", "Drive, Contacts and Sheets". */ +const andList = (items: string[]) => + items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}` : (items[0] ?? ""); + const GOOGLE_SETUP = "https://github.com/Taskmaster-1/SynapseAI/blob/main/docs/google.md"; -/** Gmail, Calendar, Drive and Contacts, built in: one OAuth consent, no MCP server to run. */ +/** Gmail, Calendar, Drive, Sheets and Contacts, built in: one OAuth consent, no MCP server to run. */ function GoogleCard({ google, onChange }: { google: GoogleIntegration; onChange: () => void }) { const toast = useToast(); const [busy, setBusy] = useState<"connect" | "disconnect" | null>(null); const conn = google.connection; const connected = conn?.status === "active"; - // A grant from before Drive and Contacts existed: those tools wait for a reconnect. + // A grant from before Drive, Contacts or Sheets existed: those tools wait for a reconnect. const missing = connected ? (conn.missing ?? []) : []; const withheld = new Set(missing.map((m) => m.group)); @@ -656,7 +660,7 @@ function GoogleCard({ google, onChange }: { google: GoogleIntegration; onChange: async function disconnect() { if ( !window.confirm( - "Disconnect Google? The agent loses access to Gmail, Calendar, Drive and Contacts, and email automations stop.", + "Disconnect Google? The agent loses access to Gmail, Calendar, Drive, Sheets and Contacts, and email automations stop.", ) ) return; @@ -685,7 +689,7 @@ function GoogleCard({ google, onChange }: { google: GoogleIntegration; onChange:
{conn ? conn.account - : "Answer email, book meetings, read and write Docs, look up contacts."} + : "Answer email, book meetings, read and write Docs and Sheets, look up contacts."}
@@ -724,7 +728,7 @@ function GoogleCard({ google, onChange }: { google: GoogleIntegration; onChange: {missing.length > 0 && google.available ? (

- Reconnect to let the agent use {missing.map((m) => m.label).join(" and ")}. Gmail and + Reconnect to let the agent use {andList(missing.map((m) => m.label))}. Gmail and Calendar keep working until then.

- - + {a.runAt ? ( + + ) : ( + + )} + {a.kind === "reminder" ? null : ( + + )}
@@ -534,6 +589,42 @@ function splitSchedule(cron: string): [string, string | null] { return at ? [when!, at] : [d, null]; } +function Tag({ children }: { children: string }) { + return ( + + {children} + + ); +} + +/** The stub of a one-off: its date and time, in its own zone. */ +function OnceStub({ automation: a }: { automation: Automation }) { + const at = new Date(a.runAt ?? ""); + const part = (o: Intl.DateTimeFormatOptions) => { + try { + return at.toLocaleString(undefined, { timeZone: a.timezone, ...o }); + } catch { + return at.toLocaleString(undefined, o); + } + }; + return ( + + ); +} + /** The tear-off stub on the left of a schedule ticket. */ function ScheduleStub({ cron, enabled }: { cron: string; enabled: boolean }) { const [when, at] = splitSchedule(cron); @@ -781,6 +872,25 @@ function CopyField({ value }: { value: string }) { function TriggerLine({ automation: a }: { automation: Automation }) { const iconClass = a.enabled ? "text-accent" : "text-fg-faint"; + if (a.trigger.type === "schedule" && a.runAt) + return ( +
+ + {a.kind === "reminder" ? ( + + ) : ( + + )} + {a.kind === "reminder" ? "Reminds you" : "Runs once"} {onceLabel(a.runAt, a.timezone)} ( + {a.timezone}) + + {a.chatId ? ( + + From this conversation + + ) : null} +
+ ); if (a.trigger.type === "schedule") return (
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index ab763f9..a881804 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -318,10 +318,64 @@ function General({ settings, save }: { settings: Settings; save: SaveFn }) { }} /> +
); } +function deviceZone() { + try { + return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + } catch { + return "UTC"; + } +} + +/** Saved on change: reminders and the agent's "today" follow it. */ +function TimeZone({ settings, save }: { settings: Settings; save: SaveFn }) { + const device = deviceZone(); + const zones = useMemo(() => { + let all: string[] = []; + try { + all = Intl.supportedValuesOf("timeZone"); + } catch {} + const current = settings.timezone ?? device; + return all.includes(current) ? all : [current, ...all]; + }, [settings.timezone, device]); + return ( + +
+ + {settings.timezone && settings.timezone !== device ? ( + + ) : null} +
+
+ ); +} + const UNDO_OPTIONS = ["0", "5", "10", "30"] as const; /** Saved on click, like the theme: there's nothing to draft. */ diff --git a/apps/web/components/approval/payload.tsx b/apps/web/components/approval/payload.tsx index 9709c1c..686aeab 100644 --- a/apps/web/components/approval/payload.tsx +++ b/apps/web/components/approval/payload.tsx @@ -276,8 +276,70 @@ function DocView({ obj }: { obj: Obj }) { ); } +const REPEAT_LABELS: Record = { + none: "Once", + daily: "Every day", + weekdays: "Every weekday", + weekly: "Every week", + monthly: "Every month", +}; + +/** When it fires, in the zone given or the offset the agent wrote (else this device's). */ +function scheduledTime(when: unknown, timezone: unknown): string { + const s = typeof when === "string" ? when : ""; + const d = new Date(s); + if (!s || Number.isNaN(d.getTime())) return s || "—"; + const tz = typeof timezone === "string" && timezone ? timezone : undefined; + try { + return d.toLocaleString(undefined, { + timeZone: tz, + weekday: "short", + day: "numeric", + month: "short", + year: "numeric", + hour: "2-digit", + minute: "2-digit", + timeZoneName: "short", + }); + } catch { + return s; + } +} + +/** Scheduling for later: what kind, when, how often, then the instructions as a page. */ +function ScheduleView({ obj }: { obj: Obj }) { + const reminder = obj.kind === "reminder"; + const repeat = typeof obj.repeat === "string" && obj.repeat ? obj.repeat : "none"; + const rows: [string, string][] = [ + ["When", scheduledTime(obj.when, obj.timezone)], + ["Repeats", REPEAT_LABELS[repeat] ?? `Custom (${repeat})`], + ["Then", reminder ? "Notify you" : "The agent carries out the instructions in this chat"], + ]; + const text = typeof obj.instructions === "string" ? obj.instructions.trim() : ""; + return ( +
+

{reminder ? "Reminder" : "Scheduled task"}

+

+ {String(obj.title ?? "") || Untitled} +

+
+ {rows.map(([k, v]) => ( +
+
{k}
+
{v}
+
+ ))} +
+
+ {text || empty} +
+
+ ); +} + /** Tool input rendered as something a person reads, not JSON. `tool` picks a tailored view. */ export function PayloadView({ input, tool }: { input: unknown; tool?: string }) { + if (tool === "schedule_task" && isPlainObject(input)) return ; if (tool === "slack_post_message" && isPlainObject(input)) return ; if (tool === "drive_create_doc" && isPlainObject(input)) return ; if (isEmailLike(input)) return ; diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts index 03ad7f0..38d8f66 100644 --- a/apps/web/lib/api.ts +++ b/apps/web/lib/api.ts @@ -345,6 +345,8 @@ export interface Settings { remindMinutes: number; /** Deny an undecided approval after this many hours; 0 is never. */ expireHours: number; + /** IANA time zone for scheduled tasks and the agent's "today"; null until set. */ + timezone: string | null; } export interface SettingsUpdate { @@ -356,6 +358,7 @@ export interface SettingsUpdate { providerKeys?: Partial>; undoSeconds?: number; emailAlerts?: boolean; + timezone?: string | null; } export interface PushConfig { @@ -412,8 +415,12 @@ export interface Automation { name: string; prompt: string; trigger: AutomationTrigger; - /** Cron; empty for event triggers. */ + /** Cron; empty for event triggers and one-offs. */ schedule: string; + /** One-offs: the single time it fires (then it turns itself off). */ + runAt: string | null; + /** `reminder` only notifies; `task` runs the prompt. */ + kind: "task" | "reminder"; /** Secret URL for webhook triggers. */ webhookUrl: string | null; lastError: string | null; @@ -431,6 +438,8 @@ export interface AutomationInput { schedule?: string; timezone?: string; enabled?: boolean; + runAt?: string | null; + kind?: "task" | "reminder"; rotateWebhook?: boolean; } diff --git a/apps/web/lib/workspace.tsx b/apps/web/lib/workspace.tsx index 51193c1..9be49d0 100644 --- a/apps/web/lib/workspace.tsx +++ b/apps/web/lib/workspace.tsx @@ -132,6 +132,26 @@ export function WorkspaceProvider({ children }: { children: ReactNode }) { .catch(() => {}); }, []); + // Scheduled reminders and the agent's sense of "today" need a time zone: until the user + // picks one in Settings, use this device's. Checked once per device. + useEffect(() => { + if (!user) return; + const key = `synapse-tz:${user.id}`; + try { + if (localStorage.getItem(key)) return; + } catch {} + const zone = Intl.DateTimeFormat().resolvedOptions().timeZone; + api + .settings() + .then(async (s) => { + if (!s.timezone && zone) await api.saveSettings({ timezone: zone }); + try { + localStorage.setItem(key, "1"); + } catch {} + }) + .catch(() => {}); + }, [user]); + const updateUser = useCallback((u: SessionUser) => { setUser(u); try { diff --git a/docs/api.md b/docs/api.md index e8c5644..7b508fb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -195,7 +195,7 @@ other notes. | 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, emailAlerts: boolean, remindMinutes: number, expireHours: number }` — 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; `remindMinutes` (0–1440, default 30, 0 is off) sends one reminder about an undecided approval; `expireHours` (0–336, default 24, 0 is never) denies it as expired | +| GET | `/api/settings` | | `{ instructions: string \| null, models: { chain: string[] }, budgets: { perRunUsd, perDayUsd }, providerKeys: Record<"anthropic"\|"openai"\|"google"\|"gateway", boolean>, undoSeconds: number, emailAlerts: boolean, remindMinutes: number, expireHours: number, timezone: string \| null }` — 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; `remindMinutes` (0–1440, default 30, 0 is off) sends one reminder about an undecided approval; `expireHours` (0–336, default 24, 0 is never) denies it as expired; `timezone` (IANA name or null) is used for scheduled reminders and tasks | | 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 }` | @@ -239,7 +239,7 @@ approvals inbox. | `trigger` | Fires | Where it runs | |---|---|---| -| `{ type: "schedule" }` | On the 5-field cron in `schedule` (≥ 15 min apart), in `timezone` | The automation's own chat | +| `{ type: "schedule" }` | On the 5-field cron in `schedule` (≥ 15 min apart), in `timezone`; or once, at `runAt`, after which it turns itself off | The automation's chat (for ones scheduled from chat, that chat) | | `{ type: "gmail", query }` | For each new Gmail message matching `query` (Gmail search syntax; empty = inbox). Polled every `TRIGGER_POLL_SECONDS` (120). Mail you send and mail that was there before the trigger was created never fire it. | A new task per email | | `{ type: "webhook" }` | On `POST webhookUrl` | A new task per delivery | @@ -248,9 +248,44 @@ so no write, send or destructive call is auto-allowed, whatever your rules say. | Method | Path | Body | Response | |---|---|---|---| -| GET | `/api/automations` | | `{ automations: { id, name, prompt, trigger, schedule, timezone, enabled, chatId, nextRunAt, lastRunAt, lastError, webhookUrl }[] }` | -| POST | `/api/automations` | `{ name, prompt, trigger?, schedule?, timezone?, enabled? }` — `trigger` defaults to schedule | `{ automation }` (`422 invalid_schedule`, `422 google_not_connected`) | +| GET | `/api/automations` | | `{ automations: { id, name, prompt, kind, trigger, schedule, runAt, timezone, enabled, chatId, nextRunAt, lastRunAt, lastError, webhookUrl }[] }` | +| POST | `/api/automations` | `{ name, prompt, kind?, trigger?, schedule?, runAt?, timezone?, enabled? }` — `trigger` defaults to schedule; `runAt` (ISO 8601 with offset, in the future, within a year) makes it a one-off and `schedule` is ignored; `kind` is `task` (default: runs the prompt) or `reminder` (only notifies) | `{ automation }` (`422 invalid_schedule`, `422 google_not_connected`) | | PATCH | `/api/automations/:id` | any of the above, plus `rotateWebhook: true` for a new URL; omitted fields keep their value | `{ automation }` | | DELETE | `/api/automations/:id` | | `204` | -| POST | `/api/automations/:id/run` | | `{ runId, queued, chatId }` — run it now | +| POST | `/api/automations/:id/run` | | `{ runId, queued, chatId }` — run it now (`422 reminder` for reminders) | | GET | `/api/automations/templates` | | `{ categories, googleAvailable, templates: { id, name, outcome, category, trigger, schedule?, prompt, requires, missing }[] }` — the gallery; `requires` is `google`, `github` or `linear` (MCP connections match by name or URL), `missing` what you haven't connected | + +### Scheduled from chat + +The agent schedules reminders and follow-ups with three built-in tools. Each creates or +changes an ordinary schedule automation, so everything above applies, and they show on the +Automations page (one-offs with a "Once" label and their time, cancellable there). + +| Tool | Effect | What it does | +|---|---|---| +| `schedule_task` | write, allowed by default | `{ title, instructions, when, kind, repeat?, timezone? }`. `when` is ISO 8601 with an offset (the model resolves "Friday at 9" itself), in the future and within a year. `repeat` is `none` (default), `daily`, `weekdays`, `weekly` or `monthly`, anchored on the day and wall-clock time of `when` in the user's time zone (so 09:00 stays 09:00 across DST), or a five-field cron (≥ 15 min apart) whose first run is at or after `when`. At most 100 active automations per person. The approval card reads "Remind you Fri 7 Nov, 09:00: Send the report" or "Schedule for Mon 3 Nov, 09:00 (weekly): Plan the week". | +| `list_scheduled` | read | Upcoming schedule automations with id, next time and repeat, plus the current time in the user's zone (how the agent learns what "now" is). | +| `cancel_scheduled` | write, allowed by default | Pauses one by id. Nothing is deleted: it can be turned back on under Automations. | + +**Where it runs.** The automation belongs to the chat it was asked in. A `task` posts +`[Scheduled: title]` and the instructions into that chat as a new turn, so the agent picks up +with the whole conversation (who Sam is, which email) as context. A `reminder` makes no model +call: it adds "Reminder: …" to the chat as the assistant and notifies the person on every +channel they set up (push, Slack DM, and email if email alerts are on). Deleting the chat +deletes its scheduled items. If the chat has a turn in progress, or one waiting on an +approval, when a one-off task is due, it retries every minute until the chat is free; a +reminder is still sent on time, without the chat note. + +**Why scheduling doesn't ask.** It only touches the person's own account, they can see and +cancel everything under Automations, and a fired task is a new run in which every action +goes through policy again (a chat that read outside content stays tainted). The safety rule +that matters is kept: once a run has read untrusted content (an email, web page, document), +`schedule_task` and `cancel_scheduled` ask like any other write, so an email cannot plant a +scheduled instruction or switch off your automations. A rule like +`{ tool: "schedule_task", decision: "ask" }` makes it always ask. + +**Time zone.** `timezone` in `/api/settings` (an IANA name; the web app fills it from the +browser the first time, and Settings → General changes it). It sets the default zone for +scheduled items, how times are shown to the agent and on approval cards, and the date in +the system prompt ("Today is Friday 2026-11-06, time zone Europe/London"). Without one, +UTC is used. diff --git a/docs/notifications.md b/docs/notifications.md index 4791c86..1a4817d 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -10,6 +10,11 @@ When a task stops to ask, Synapse can tell you where you are: Each approval is announced once, when the run starts waiting. Several approvals at once become one summary notification per person. +The same channels (push, Slack DM, and email when email alerts are on) also deliver +reminders you asked the agent for ("remind me Friday at 9 to send the report"): a plain +notification with the reminder and a link to the conversation. See +[scheduled from chat](api.md#scheduled-from-chat). + ## Reminders, escalation and expiry If nobody decides, the same channels hear about it again, once each: diff --git a/packages/db/drizzle/0010_schedule_tasks.sql b/packages/db/drizzle/0010_schedule_tasks.sql new file mode 100644 index 0000000..3aec624 --- /dev/null +++ b/packages/db/drizzle/0010_schedule_tasks.sql @@ -0,0 +1,3 @@ +ALTER TABLE "automations" ADD COLUMN "run_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "automations" ADD COLUMN "kind" text DEFAULT 'task' NOT NULL;--> statement-breakpoint +ALTER TABLE "user_settings" ADD COLUMN "timezone" text; \ No newline at end of file diff --git a/packages/db/drizzle/meta/0010_snapshot.json b/packages/db/drizzle/meta/0010_snapshot.json new file mode 100644 index 0000000..5646d3b --- /dev/null +++ b/packages/db/drizzle/meta/0010_snapshot.json @@ -0,0 +1,3110 @@ +{ + "id": "fdab2485-47b6-40a6-9860-31629e0f2892", + "prevId": "24d5fae9-9ab9-44fc-a1a4-8219f7c61ab9", + "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": "''" + }, + "run_at": { + "name": "run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'task'" + }, + "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.files": { + "name": "files", + "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 + }, + "data": { + "name": "data", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "document_id": { + "name": "document_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "files_user_idx": { + "name": "files_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": { + "files_user_id_user_id_fk": { + "name": "files_user_id_user_id_fk", + "tableFrom": "files", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "files_document_id_documents_id_fk": { + "name": "files_document_id_documents_id_fk", + "tableFrom": "files", + "tableTo": "documents", + "columnsFrom": [ + "document_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "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 + }, + "untrusted": { + "name": "untrusted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "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" + }, + "skills": { + "name": "skills", + "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.skills": { + "name": "skills", + "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 + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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": { + "skills_user_name_idx": { + "name": "skills_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": { + "skills_user_id_user_id_fk": { + "name": "skills_user_id_user_id_fk", + "tableFrom": "skills", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "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": "''" + }, + "user_token": { + "name": "user_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_scopes": { + "name": "user_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 + }, + "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 + }, + "reminded_at": { + "name": "reminded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "escalated_at": { + "name": "escalated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "first_approved_by": { + "name": "first_approved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_approved_at": { + "name": "first_approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "first_approved_via": { + "name": "first_approved_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execute_after": { + "name": "execute_after", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "skills": { + "name": "skills", + "type": "jsonb", + "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 + }, + "disabled_skills": { + "name": "disabled_skills", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "remind_minutes": { + "name": "remind_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 30 + }, + "expire_hours": { + "name": "expire_hours", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 24 + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_settings_user_id_user_id_fk": { + "name": "user_settings_user_id_user_id_fk", + "tableFrom": "user_settings", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "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 + }, + "escalate_minutes": { + "name": "escalate_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 60 + }, + "expire_hours": { + "name": "expire_hours", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "two_person": { + "name": "two_person", + "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 6282a2c..ae919d3 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -71,6 +71,13 @@ "when": 1793443617268, "tag": "0009_slack_user_token", "breakpoints": true + }, + { + "idx": 10, + "version": "7", + "when": 1793445190695, + "tag": "0010_schedule_tasks", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/automations.ts b/packages/db/src/automations.ts index b7b2320..39ad06e 100644 --- a/packages/db/src/automations.ts +++ b/packages/db/src/automations.ts @@ -1,8 +1,8 @@ import { Cron } from "croner"; -import { and, asc, eq, lte, sql } from "drizzle-orm"; +import { and, asc, eq, inArray, lte, sql } from "drizzle-orm"; import type { Db } from "./client"; import { sendMessage } from "./runs"; -import { automations } from "./schema"; +import { automations, chats, messages, runs } from "./schema"; /** Next fire time for a cron expression, or throws on an invalid expression/timezone. */ export function nextRun(schedule: string, timezone: string, after = new Date()): Date | null { @@ -28,10 +28,100 @@ export function validateSchedule( } } +export function isTimeZone(timezone: string): boolean { + try { + new Intl.DateTimeFormat("en-US", { timeZone: timezone }); + return true; + } catch { + return false; + } +} + +/** Wall-clock fields of `at` in `timezone`. */ +export function wallClock(at: Date, timezone: string) { + const parts: Record = {}; + const format = new Intl.DateTimeFormat("en-US", { + timeZone: timezone, + hourCycle: "h23", + day: "numeric", + hour: "numeric", + minute: "numeric", + weekday: "short", + }); + for (const p of format.formatToParts(at)) parts[p.type] = p.value; + return { + minute: Number(parts.minute), + hour: Number(parts.hour), + day: Number(parts.day), + weekday: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(parts.weekday ?? ""), + }; +} + +export const REPEATS = ["none", "daily", "weekdays", "weekly", "monthly"] as const; +export type Repeat = (typeof REPEATS)[number]; + +/** A one-off fire time, or a cron with its first fire time. */ +export type SchedulePlan = + | { runAt: Date; schedule: ""; nextRunAt: Date; timezone: string } + | { runAt: null; schedule: string; nextRunAt: Date; timezone: string }; + +const ISO_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})$/; +const MAX_AHEAD_MS = 366 * 24 * 3600_000; + +/** + * Turns "when, and how often" into automation fields. `when` must be an ISO time with an + * offset (the model resolves "Friday at 9" itself), in the future and within a year. + * `repeat` is a keyword, anchored on `when`'s wall-clock time in `timezone` (so "weekly" + * from a Friday at 09:00 fires Fridays at 09:00, through DST changes), or a five-field cron + * whose first fire is at or after `when`. Returns the plan, or an error for the model. + */ +export function planSchedule( + args: { when: string; repeat?: string | null; timezone: string }, + now = new Date(), +): SchedulePlan | string { + const { timezone } = args; + if (!isTimeZone(timezone)) return `Unknown time zone "${timezone}". Use an IANA name.`; + const when = args.when.trim(); + const at = new Date(when); + if (!ISO_WITH_OFFSET.test(when) || Number.isNaN(at.getTime())) + return `"${args.when}" is not an ISO 8601 time with an offset, like 2026-11-07T09:00:00+01:00.`; + if (at.getTime() <= now.getTime()) + return `${when} is in the past (it is now ${now.toISOString()}).`; + if (at.getTime() - now.getTime() > MAX_AHEAD_MS) return "That is more than a year away."; + const repeat = (args.repeat ?? "none").trim() || "none"; + if (repeat === "none") return { runAt: at, schedule: "", nextRunAt: at, timezone }; + let schedule: string; + if ((REPEATS as readonly string[]).includes(repeat)) { + const w = wallClock(at, timezone); + const hm = `${w.minute} ${w.hour}`; + schedule = + repeat === "daily" + ? `${hm} * * *` + : repeat === "weekdays" + ? `${hm} * * 1-5` + : repeat === "weekly" + ? `${hm} * * ${w.weekday}` + : `${hm} ${w.day} * *`; + } else { + if (repeat.split(/\s+/).length !== 5) + return `repeat must be one of ${REPEATS.join(", ")}, or a five-field cron expression.`; + schedule = repeat; + } + const problem = validateSchedule(schedule, timezone); + if (problem) return problem; + // The first fire is `when` itself for keywords, else the first cron time from then on. + const first = nextRun(schedule, timezone, new Date(at.getTime() - 1000)); + if (!first) return "This schedule never fires."; + return { runAt: null, schedule, nextRunAt: first, timezone }; +} + +/** A one-off whose chat is busy (a run going, or waiting on the user) retries after this. */ +const RETRY_BUSY_MS = 60_000; + /** * Fires every due automation once. Safe with many schedulers: each row is claimed with * SKIP LOCKED and its next fire time is advanced in the same transaction as the message. - * Missed fires (e.g. while down) collapse into one run. + * Missed fires (e.g. while down) collapse into one run. One-offs turn off once they fire. */ export async function fireDueAutomations(db: Db, now = new Date()): Promise { const fired: string[] = []; @@ -44,6 +134,7 @@ export async function fireDueAutomations(db: Db, now = new Date()): Promise>'type' = 'schedule'`, ), ) @@ -51,22 +142,21 @@ export async function fireDueAutomations(db: Db, now = new Date()): Promise { + const fired: FiredReminder[] = []; + for (;;) { + const more = await db.transaction(async (tx) => { + const [due] = await tx + .select() + .from(automations) + .where( + and( + eq(automations.enabled, true), + lte(automations.nextRunAt, now), + eq(automations.kind, "reminder"), + sql`${automations.trigger}->>'type' = 'schedule'`, + ), + ) + .orderBy(asc(automations.nextRunAt)) + .limit(1) + .for("update", { skipLocked: true }); + if (!due) return false; + const [busy] = await tx + .select({ id: runs.id }) + .from(runs) + .where( + and(eq(runs.chatId, due.chatId), inArray(runs.status, ["queued", "running", "waiting"])), + ) + .limit(1); + if (!busy) { + await tx.insert(messages).values({ + chatId: due.chatId, + message: { role: "assistant", content: [{ type: "text", text: reminderText(due) }] }, + }); + await tx.update(chats).set({ updatedAt: now }).where(eq(chats.id, due.chatId)); + } + await advance(tx as unknown as Db, due, now); + fired.push({ + automationId: due.id, + userId: due.userId, + chatId: due.chatId, + title: due.name, + text: due.prompt, + }); + return true; + }); + if (!more) return fired; + } +} + +/** How a fired reminder reads in its chat. */ +export function reminderText(a: { name: string; prompt: string }) { + return a.prompt.trim() === a.name.trim() + ? `Reminder: ${a.name}` + : `Reminder: ${a.name}\n\n${a.prompt}`; +} + /** * Claims the gmail-triggered automations that are due a poll and pushes their next poll * `intervalMs` out, so concurrent schedulers never poll the same automation twice. diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index c55972d..b33ba82 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -130,6 +130,8 @@ export const userSettings = pgTable("user_settings", { remindMinutes: integer("remind_minutes").notNull().default(30), /** Deny an approval nobody decided after this many hours. 0: never expires. */ expireHours: integer("expire_hours").notNull().default(24), + /** IANA time zone, e.g. "Europe/London": scheduled tasks and the date in the prompt use it. */ + timezone: text("timezone"), updatedAt: updatedAt(), }); @@ -636,6 +638,9 @@ export type AutomationTrigger = /** POST to the automation's secret webhook URL. */ | { type: "webhook" }; +/** What a scheduled automation does when it fires: run the agent, or only remind. */ +export type AutomationKind = "task" | "reminder"; + /** Poll state for event triggers. */ export interface TriggerCursor { /** Newest message time seen, in ms. */ @@ -682,8 +687,15 @@ export const automations = pgTable( name: text("name").notNull(), prompt: text("prompt").notNull(), trigger: jsonb("trigger").$type().notNull().default({ type: "schedule" }), - /** Five-field cron expression, evaluated in `timezone`. Empty for event triggers. */ + /** Five-field cron expression, evaluated in `timezone`. Empty for event and one-off triggers. */ schedule: text("schedule").notNull().default(""), + /** One-off schedules: fires once at this time, then turns itself off. */ + runAt: timestamp("run_at", { withTimezone: true }), + /** + * `task` sends the prompt to the agent; `reminder` only notifies the user (in the chat + * and on their channels), without a model call. + */ + kind: text("kind").$type().notNull().default("task"), timezone: text("timezone").notNull().default("UTC"), enabled: boolean("enabled").notNull().default(true), chatId: text("chat_id") diff --git a/packages/tools/src/builtin/schedule.ts b/packages/tools/src/builtin/schedule.ts new file mode 100644 index 0000000..2494d68 --- /dev/null +++ b/packages/tools/src/builtin/schedule.ts @@ -0,0 +1,257 @@ +import type { ToolDefinition } from "@synapse/core"; +import { type Db, isTimeZone, planSchedule, REPEATS, schema } from "@synapse/db"; +import type { JSONValue } from "ai"; +import { and, asc, eq, sql } from "drizzle-orm"; + +/** Active scheduled automations one person may have, so a loop cannot pile them up. */ +export const MAX_SCHEDULED = 100; +const MAX_TITLE = 80; +const MAX_INSTRUCTIONS = 4000; + +interface ScheduleInput { + title: string; + instructions: string; + when: string; + kind: "reminder" | "task"; + repeat?: string; + timezone?: string; +} + +/** + * Formats a time for people, in a time zone: "Fri 7 Nov, 09:00" (the year only when it is + * not this year). Without a zone, uses the offset written in `iso`, which is the zone the + * model resolved the time in. + */ +export function formatWhen(at: Date, timezone: string | null, iso?: string): string { + let zone = timezone && isTimeZone(timezone) ? timezone : "UTC"; + let shown = at; + if (!timezone && iso) { + // A bare offset is no IANA zone: shift the instant and print it as UTC. + const m = /([+-])(\d{2}):(\d{2})$/.exec(iso.trim()); + if (m) { + const minutes = (m[1] === "-" ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])); + shown = new Date(at.getTime() + minutes * 60_000); + zone = "UTC"; + } + } + const sameYear = + new Intl.DateTimeFormat("en-GB", { timeZone: zone, year: "numeric" }).format(shown) === + new Intl.DateTimeFormat("en-GB", { timeZone: zone, year: "numeric" }).format(new Date()); + const day = new Intl.DateTimeFormat("en-GB", { + timeZone: zone, + weekday: "short", + day: "numeric", + month: "short", + ...(sameYear ? {} : { year: "numeric" }), + }) + .format(shown) + .replace(",", ""); + const time = new Intl.DateTimeFormat("en-GB", { + timeZone: zone, + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }).format(shown); + return `${day}, ${time}`; +} + +/** "weekly", "weekdays", or the cron itself; null for a one-off. */ +function repeatLabel(repeat: string | undefined): string | null { + const r = repeat?.trim(); + if (!r || r === "none") return null; + return r; +} + +/** One line for approval cards and the activity log. */ +export function schedulePreview(input: JSONValue, timezone: string | null): string { + const i = input as Partial; + const at = new Date(String(i.when ?? "")); + const when = Number.isNaN(at.getTime()) + ? String(i.when ?? "an invalid time") + : formatWhen(at, i.timezone && isTimeZone(i.timezone) ? i.timezone : timezone, i.when); + const every = repeatLabel(i.repeat); + const head = i.kind === "reminder" ? "Remind you" : "Schedule for"; + return `${head} ${when}${every ? ` (${every})` : ""}: ${i.title ?? i.instructions ?? ""}`; +} + +/** + * Scheduling future work for the user: reminders ("remind me Friday at 9 to send the + * report") and follow-ups the agent does itself ("in 3 days, check whether Sam replied"). + * Each is a one-off or recurring automation on the chat it was asked in, so when it fires + * the agent continues that conversation with its context; a reminder only notifies. + * + * Scheduling and cancelling run without approval by default: they touch only the user's + * own account, and a fired task is a fresh run whose every action goes through policy again. + * Like every non-read tool they ask once the run has read outside content, so an email + * cannot plant a scheduled instruction without the user seeing it. + */ +export function scheduleTools(db: Db, timezone: string | null): ToolDefinition[] { + const zoneNote = timezone + ? `The user's time zone is ${timezone}.` + : "The user has not set a time zone; ask for it if the time of day matters and you cannot tell."; + return [ + { + name: "schedule_task", + description: `Schedule something for later in this conversation. kind "reminder": at that time the user is just notified (push, Slack, email, as they set up) with the title and instructions; no action is taken. kind "task": at that time you continue this conversation and carry out the instructions (e.g. "check whether Sam replied to my email about the report; if not, draft a short nudge"). Write instructions as a complete task prompt that makes sense on its own. Resolve relative times ("Friday at 9", "in 3 days") yourself into an ISO 8601 time with the user's UTC offset; call list_scheduled first if you need the current time. ${zoneNote}`, + inputSchema: { + type: "object", + properties: { + title: { type: "string", maxLength: MAX_TITLE, description: "Short label." }, + instructions: { + type: "string", + maxLength: MAX_INSTRUCTIONS, + description: + "For a reminder, what to tell the user. For a task, what you should do then.", + }, + when: { + type: "string", + description: + "First (or only) time, ISO 8601 with offset, e.g. 2026-11-07T09:00:00+01:00. In the future, within a year.", + }, + kind: { type: "string", enum: ["reminder", "task"] }, + repeat: { + type: "string", + description: `One of ${REPEATS.join(", ")} (anchored on the day and time of \`when\`), or a five-field cron expression. Default none.`, + }, + timezone: { + type: "string", + description: "IANA time zone, only if the user named one other than their own.", + }, + }, + required: ["title", "instructions", "when", "kind"], + additionalProperties: false, + }, + effect: "write", + defaultDecision: "allow", + untrustedOutput: false, + source: "builtin", + preview: (input) => schedulePreview(input, timezone), + execute: async (input, ctx) => { + const i = input as Partial; + const title = String(i.title ?? "") + .trim() + .slice(0, MAX_TITLE); + const instructions = String(i.instructions ?? "") + .trim() + .slice(0, MAX_INSTRUCTIONS); + if (!title || !instructions) + return { type: "error", value: "title and instructions are required." }; + if (i.kind !== "reminder" && i.kind !== "task") + return { type: "error", value: 'kind must be "reminder" or "task".' }; + const zone = i.timezone?.trim() || timezone || "UTC"; + const plan = planSchedule({ when: String(i.when ?? ""), repeat: i.repeat, timezone: zone }); + if (typeof plan === "string") return { type: "error", value: plan }; + const [{ n } = { n: 0 }] = await db + .select({ n: sql`count(*)::int` }) + .from(schema.automations) + .where( + and(eq(schema.automations.userId, ctx.userId), eq(schema.automations.enabled, true)), + ); + if (n >= MAX_SCHEDULED) + return { + type: "error", + value: `The user already has ${MAX_SCHEDULED} active automations. Cancel some first.`, + }; + const [row] = await db + .insert(schema.automations) + .values({ + userId: ctx.userId, + chatId: ctx.chatId, + name: title, + prompt: instructions, + kind: i.kind, + trigger: { type: "schedule" }, + ...plan, + }) + .returning({ id: schema.automations.id }); + const shownZone = i.timezone?.trim() || timezone; + const when = formatWhen(plan.nextRunAt, shownZone, String(i.when)); + const every = plan.schedule ? `, then ${repeatLabel(i.repeat) ?? plan.schedule}` : ""; + return { + type: "text", + value: `Scheduled ${i.kind} "${title}" (id ${row!.id}) for ${when}${shownZone ? ` ${shownZone}` : ""}${every}. ${ + i.kind === "reminder" + ? "The user will be notified then." + : "You will continue this conversation then." + } It is listed under Automations, where the user can cancel it.`, + }; + }, + }, + { + name: "list_scheduled", + description: + "List the user's upcoming scheduled tasks and reminders (and recurring automations) with their next time and id. Also tells you the current time.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + effect: "read", + untrustedOutput: false, + source: "builtin", + execute: async (_input, ctx) => { + const rows = await db + .select({ + id: schema.automations.id, + name: schema.automations.name, + kind: schema.automations.kind, + schedule: schema.automations.schedule, + timezone: schema.automations.timezone, + runAt: schema.automations.runAt, + nextRunAt: schema.automations.nextRunAt, + chatId: schema.automations.chatId, + chatTitle: schema.chats.title, + }) + .from(schema.automations) + .innerJoin(schema.chats, eq(schema.chats.id, schema.automations.chatId)) + .where( + and( + eq(schema.automations.userId, ctx.userId), + eq(schema.automations.enabled, true), + sql`${schema.automations.trigger}->>'type' = 'schedule'`, + ), + ) + .orderBy(asc(schema.automations.nextRunAt)) + .limit(50); + const now = `Now: ${formatWhen(new Date(), timezone)}${timezone ? ` ${timezone}` : " UTC"} (${new Date().toISOString()}).`; + if (rows.length === 0) return { type: "text", value: `${now}\nNothing is scheduled.` }; + const lines = rows.map((r) => { + const next = r.nextRunAt ? formatWhen(r.nextRunAt, timezone ?? r.timezone) : "not set"; + const how = r.runAt ? "once" : `repeats: ${r.schedule} (${r.timezone})`; + const where = + r.chatId === ctx.chatId ? "this chat" : `chat "${r.chatTitle ?? "Untitled"}"`; + return `- ${r.name} [${r.kind}, id ${r.id}]: next ${next}; ${how}; in ${where}`; + }); + return { type: "text", value: [now, ...lines].join("\n") }; + }, + }, + { + name: "cancel_scheduled", + description: + "Cancel one of the user's scheduled tasks, reminders or scheduled automations by id (from list_scheduled). It is paused, not deleted: the user can turn it back on under Automations.", + inputSchema: { + type: "object", + properties: { id: { type: "string" } }, + required: ["id"], + additionalProperties: false, + }, + effect: "write", + defaultDecision: "allow", + untrustedOutput: false, + source: "builtin", + preview: (input) => `Cancel scheduled item ${(input as { id?: string }).id ?? ""}`, + execute: async (input, ctx) => { + const id = String((input as { id?: string }).id ?? "").trim(); + const [row] = await db + .update(schema.automations) + .set({ enabled: false, nextRunAt: null }) + .where( + and( + eq(schema.automations.id, id), + eq(schema.automations.userId, ctx.userId), + sql`${schema.automations.trigger}->>'type' = 'schedule'`, + ), + ) + .returning({ name: schema.automations.name }); + if (!row) return { type: "error", value: `No scheduled item with id ${id}.` }; + return { type: "text", value: `Cancelled "${row.name}".` }; + }, + }, + ]; +} diff --git a/packages/tools/src/index.ts b/packages/tools/src/index.ts index 1d63714..3d26a04 100644 --- a/packages/tools/src/index.ts +++ b/packages/tools/src/index.ts @@ -1,9 +1,11 @@ import { type ToolDefinition, ToolRegistry } from "@synapse/core"; -import type { Db, SecretBox } from "@synapse/db"; +import { type Db, type SecretBox, schema } from "@synapse/db"; +import { eq } from "drizzle-orm"; import { fileReadTool, loadFiles } from "./builtin/files"; import { type Embedder, knowledgeTool } from "./builtin/knowledge"; import { memoryTools } from "./builtin/memory"; import { planTool } from "./builtin/plan"; +import { scheduleTools } from "./builtin/schedule"; import { enabledSkills, skillTools } from "./builtin/skills"; import { type WebSearchConfig, webFetchTool, webSearchTool } from "./builtin/web"; import { calendarTools } from "./google/calendar"; @@ -25,6 +27,7 @@ export * from "./builtin/files"; export * from "./builtin/knowledge"; export { loadMemoryBlock, loadWritingStyle } from "./builtin/memory"; export { PLAN_TOOL } from "./builtin/plan"; +export { formatWhen, MAX_SCHEDULED, schedulePreview } from "./builtin/schedule"; export { BUILTIN_SKILL_FILES, BUILTIN_SKILLS, @@ -70,12 +73,17 @@ export interface ToolsetConfig { export async function buildToolset(cfg: ToolsetConfig, userId: string) { const mcp = new McpSession(cfg.db, cfg.box, cfg.app); const skills = await enabledSkills(cfg.db, userId); + const [settings] = await cfg.db + .select({ timezone: schema.userSettings.timezone }) + .from(schema.userSettings) + .where(eq(schema.userSettings.userId, userId)); const builtin: ToolDefinition[] = [ webFetchTool(), knowledgeTool(cfg.db, cfg.embedder), fileReadTool(cfg.db), ...memoryTools(cfg.db), planTool(cfg.db), + ...scheduleTools(cfg.db, settings?.timezone ?? null), ...skillTools(cfg.db, skills), ...(cfg.webSearch ? [webSearchTool(cfg.webSearch)] : []), ]; From dc3a5357f608e1a9d2773a14950481af6295f571 Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:58:28 +0530 Subject: [PATCH 3/3] Scheduled-task card shows the time in the same zone as its title --- apps/web/components/approval/payload.tsx | 39 +++++++++++++++--------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/apps/web/components/approval/payload.tsx b/apps/web/components/approval/payload.tsx index ce4e951..441005e 100644 --- a/apps/web/components/approval/payload.tsx +++ b/apps/web/components/approval/payload.tsx @@ -387,26 +387,35 @@ const REPEAT_LABELS: Record = { monthly: "Every month", }; -/** When it fires, in the zone given or the offset the agent wrote (else this device's). */ +/** + * When it fires, in the zone given, else at the offset the agent wrote, so it matches the + * card's title (which the server writes in the user's zone). + */ function scheduledTime(when: unknown, timezone: unknown): string { const s = typeof when === "string" ? when : ""; const d = new Date(s); if (!s || Number.isNaN(d.getTime())) return s || "—"; - const tz = typeof timezone === "string" && timezone ? timezone : undefined; - try { - return d.toLocaleString(undefined, { - timeZone: tz, - weekday: "short", - day: "numeric", - month: "short", - year: "numeric", - hour: "2-digit", - minute: "2-digit", - timeZoneName: "short", - }); - } catch { - return s; + const parts = { + weekday: "short", + day: "numeric", + month: "short", + year: "numeric", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + } as const; + if (typeof timezone === "string" && timezone) { + try { + return d.toLocaleString(undefined, { ...parts, timeZone: timezone, timeZoneName: "short" }); + } catch {} } + const m = /([+-])(\d{2}):?(\d{2})$/.exec(s); + const offset = m ? (m[1] === "-" ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])) : 0; + const local = new Date(d.getTime() + offset * 60_000).toLocaleString(undefined, { + ...parts, + timeZone: "UTC", + }); + return `${local} ${offset === 0 ? "UTC" : `UTC${m![1]}${m![2]}:${m![3]}`}`; } /** Scheduling for later: what kind, when, how often, then the instructions as a page. */