An open-source, faster Devin alternative
TypeScript
Package default database migrations (#757)
Mohamed Habibec942e96a23d
diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex bd24d212..38ddcacb 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.7.6",+ "version": "0.7.7","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.7.6",+ "version": "0.7.7","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",diff --git a/cli/package.json b/cli/package.jsonindex 69d14e7f..caa56102 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.7.6",+ "version": "0.7.7","description": "Build, test, deploy, and share OpenComputer agents as code.","type": "module","bin": {diff --git a/cli/src/api.test.ts b/cli/src/api.test.tsindex a91dbbfe..8f8f8841 100644--- a/cli/src/api.test.ts+++ b/cli/src/api.test.ts@@ -133,3 +133,32 @@ test("memory precondition failures surface the API's code", async (context) => {error.message === "The document changed.",);});++test("database queries use the project read endpoint with positional parameters", async (context) => {+ let request: Request | undefined;+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {+ request = new Request(input, init);+ return Response.json({+ environment: "production",+ result: { columns: ["id"], rows: [{ id: 7 }], rowsAffected: 0, truncated: false },+ });+ });+ const client = new OpenComputerClient({ apiUrl: "https://app.opencomputer.dev", apiKey: "test" });++ const result = await client.databaseQuery({+ projectId: "prj_1",+ environment: "production",+ sql: "SELECT id FROM records WHERE name = ? LIMIT ?",+ parameters: ["pricing", 20],+ });++ assert.deepEqual(result.rows, [{ id: 7 }]);+ assert.ok(request);+ assert.equal(request.url, "https://app.opencomputer.dev/api/managed-agents/projects/prj_1/database/query");+ assert.equal(request.method, "POST");+ assert.deepEqual(await request.json(), {+ environment: "production",+ sql: "SELECT id FROM records WHERE name = ? LIMIT ?",+ parameters: ["pricing", 20],+ });+});diff --git a/cli/src/api.ts b/cli/src/api.tsindex 13b8e62e..1f86b22c 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -35,6 +35,15 @@ export interface ManagedProject {updatedAt: string;}+export type DatabaseValue = string | number | null;++export interface DatabaseResult {+ columns: string[];+ rows: Array<Record<string, DatabaseValue>>;+ rowsAffected: number;+ truncated: boolean;+}+export interface ManagedAgentDeployment {id: string;agentId: string;@@ -936,6 +945,26 @@ export class OpenComputerClient {>(`/api/managed-agents/deployments/${encodeURIComponent(deploymentId)}`);}+ async databaseQuery(input: {+ projectId: string;+ environment: "development" | "production";+ sql: string;+ parameters?: Array<string | number | boolean | null>;+ }): Promise<DatabaseResult> {+ const response = await this.request<{+ environment: "development" | "production";+ result: DatabaseResult;+ }>(`/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/database/query`, {+ method: "POST",+ body: JSON.stringify({+ environment: input.environment,+ sql: input.sql,+ parameters: input.parameters ?? [],+ }),+ });+ return response.result;+ }+// Project memory (docs/agents/document-memory.mdx, "Management API").// Every mutation is conditional: the caller sends back the ETag it read.diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 2412be97..d08c8a7e 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -123,6 +123,38 @@ function environmentOption(throw new Error("--environment must be development or production");}+function databaseParameter(value: string): string | number | boolean | null {+ try {+ const parsed: unknown = JSON.parse(value);+ if (parsed === null || typeof parsed === "string" || typeof parsed === "boolean" ||+ (typeof parsed === "number" && Number.isFinite(parsed))) return parsed;+ } catch {+ // The error below explains the accepted CLI form.+ }+ throw new Error(+ `--parameter expects a JSON string, finite number, boolean, or null; received ${JSON.stringify(value)}`,+ );+}++function printDatabaseResult(result: {+ columns: string[];+ rows: Array<Record<string, string | number | null>>;+ truncated: boolean;+}): void {+ if (!result.columns.length) {+ process.stdout.write("Query completed without returning columns.\n");+ return;+ }+ process.stdout.write(`${result.columns.join("\t")}\n`);+ for (const row of result.rows) {+ process.stdout.write(`${result.columns.map((column) => {+ const value = row[column];+ return value === null || value === undefined ? "NULL" : String(value).replace(/[\t\r\n]+/g, " ");+ }).join("\t")}\n`);+ }+ if (result.truncated) process.stdout.write("Result truncated; add LIMIT and paginate the query.\n");+}+function consumeModelAccessProvider(args: string[]): "claude" | "codex" {if (args[0] === "claude" || args[0] === "codex") {return args.shift() as "claude" | "codex";@@ -1835,6 +1867,27 @@ function serviceOfConnection(connection: {);}+ if (command === "database") {+ const action = args.shift();+ const projectReference = option(args, "--project");+ const environment = environmentOption(option(args, "--environment"));+ const parameters = options(args, "--parameter").map(databaseParameter);+ const sql = args.shift();+ if (action !== "query" || !sql || args.length) {+ throw new Error("Use `opencomputer database query <sql> [--environment development|production] [--parameter <json>]... [--project <id|slug>]`.");+ }+ const project = await selectedProject(client, config, projectReference);+ const result = await client.databaseQuery({+ projectId: project.projectId,+ environment,+ sql,+ parameters,+ });+ if (globals.json) printJSON(result);+ else printDatabaseResult(result);+ return;+ }+if (command === "memory") {const action = args.shift();const projectReference = option(args, "--project");diff --git a/cli/src/dev.test.ts b/cli/src/dev.test.tsindex de5ef4f5..4d62ddfa 100644--- a/cli/src/dev.test.ts+++ b/cli/src/dev.test.ts@@ -147,6 +147,94 @@ test("development publish synchronizes every configured project agent", async ()}});+test("project publish includes ordered default database migrations in deployment identity", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-dev-database-"));+ try {+ const initialized = await initializeAgentProject(resolve(parent, "app"));+ const migrations = resolve(+ initialized.root,+ "opencomputer",+ "database",+ "migrations",+ );+ await mkdir(migrations, { recursive: true });+ await writeFile(resolve(migrations, "002_notes.sql"), "ALTER TABLE notes ADD COLUMN body TEXT;\n");+ await writeFile(resolve(migrations, "001_initial.sql"), "CREATE TABLE notes (id TEXT PRIMARY KEY);\n");+ const published: Array<+ NonNullable<+ Parameters<+ Parameters<typeof publishDevelopment>[0]["registerDeployment"]+ >[0]["projectDeployment"]+ >+ > = [];+ const client = {+ async registerDeployment(+ value: Parameters<+ Parameters<typeof publishDevelopment>[0]["registerDeployment"]+ >[0],+ ) {+ if (value.projectDeployment) published.push(value.projectDeployment);+ return {+ id: `${value.agentId}:${value.source.digest}`,+ agentId: value.agentId,+ alias: value.alias,+ createdAt: new Date(0).toISOString(),+ };+ },+ };+ const binding = {+ version: 1 as const,+ apiUrl: "https://app.opencomputer.dev",+ projectId: "prj_test",+ projectName: "Test",+ agentId: "test-agent",+ };+ await publishProjectDevelopment(client, initialized.root, binding);+ assert.deepEqual(+ published[0]?.resources.database?.migrations.map((migration) => migration.name),+ ["001_initial.sql", "002_notes.sql"],+ );+ assert.match(+ published[0]?.resources.database?.migrations[0]?.checksum ?? "",+ /^[a-f0-9]{64}$/,+ );++ const firstDigest = published[0]?.digest;+ published.length = 0;+ await writeFile(resolve(migrations, "002_notes.sql"), "ALTER TABLE notes ADD COLUMN text TEXT;\n");+ await publishProjectDevelopment(client, initialized.root, binding);+ assert.notEqual(published[0]?.digest, firstDigest);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("project publish rejects invalid default database migration files", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-dev-database-invalid-"));+ try {+ const initialized = await initializeAgentProject(resolve(parent, "app"));+ const migrations = resolve(initialized.root, "opencomputer", "database", "migrations");+ await mkdir(migrations, { recursive: true });+ await writeFile(resolve(migrations, "notes.sql"), "CREATE TABLE notes (id TEXT);\n");+ await assert.rejects(+ publishProjectDevelopment(+ { registerDeployment: async () => { throw new Error("must not register"); } },+ initialized.root,+ {+ version: 1,+ apiUrl: "https://app.opencomputer.dev",+ projectId: "prj_test",+ projectName: "Test",+ agentId: "test-agent",+ },+ ),+ /must be a migration file named like 001_initial\.sql/,+ );+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});+const WORKSHOP_MEMORY = (maxBytes: string) => `import { defineMemory, documentMemory } from "@opencomputer/agent";export const requirements = defineMemory({diff --git a/cli/src/index.ts b/cli/src/index.tsindex fad54cbd..beab7b41 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -95,6 +95,7 @@ Usage:opencomputer memory unfreeze <resource> <id> [--environment development|production]opencomputer memory export --out <dir> [--resource <id>] [--environment development|production]opencomputer memory remove <resource> <id> [--environment development|production]+ opencomputer database query <sql> [--environment development|production] [--parameter <json>]... [--project <id|slug>]opencomputer logs [--agent <agent>] [--session <session-id>] [--environment development|production] [--follow]opencomputer channels status [--agent <agent>] [--environment development|production]opencomputer sessions tail <session-id> [--after <cursor>] [--no-follow]diff --git a/cli/src/project.ts b/cli/src/project.tsindex e91ab2ba..72025705 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -153,6 +153,12 @@ export interface GatedToolManifest {toolId: string;}+export interface DatabaseMigrationManifest {+ name: string;+ checksum: string;+ sql: string;+}+export interface ProjectResourceManifest {version: 1;channels: ChannelDefinitionManifest[];@@ -160,6 +166,8 @@ export interface ProjectResourceManifest {outboxes: OutboxDefinitionManifest[];outboxRegistrations: OutboxRegistrationManifest[];schedules: ScheduleDefinitionManifest[];+ /** Ordered schema migrations for the environment's default database. */+ database?: { migrations: DatabaseMigrationManifest[] };/*** Which tools wait for a human. Declared here as well as in the agent's own* manifest because the platform authorizes a proposal before any agent code@@ -2224,10 +2232,51 @@ async function typescriptFiles(directory: string): Promise<string[]> {.sort();}+const DATABASE_MIGRATION_NAME = /^\d{3,}_[a-z0-9]+(?:[a-z0-9_-]*[a-z0-9])?\.sql$/;+const MAX_DATABASE_MIGRATION_BYTES = 256 * 1024;+const MAX_DATABASE_MIGRATIONS_BYTES = 1024 * 1024;++async function databaseMigrations(+ opencomputer: string,+): Promise<DatabaseMigrationManifest[]> {+ const directory = resolve(opencomputer, "database", "migrations");+ if (!(await exists(directory))) return [];+ const entries = (await readdir(directory, { withFileTypes: true })).sort(+ (left, right) => left.name.localeCompare(right.name),+ );+ const migrations: DatabaseMigrationManifest[] = [];+ let totalBytes = 0;+ for (const entry of entries) {+ const path = resolve(directory, entry.name);+ if (!entry.isFile() || !DATABASE_MIGRATION_NAME.test(entry.name)) {+ throw new Error(+ `${path} must be a migration file named like 001_initial.sql`,+ );+ }+ const sql = await readFile(path, "utf8");+ const bytes = Buffer.byteLength(sql);+ if (!sql.trim()) throw new Error(`${path} must not be empty`);+ if (bytes > MAX_DATABASE_MIGRATION_BYTES) {+ throw new Error(`${path} cannot exceed 256 KiB`);+ }+ totalBytes += bytes;+ if (totalBytes > MAX_DATABASE_MIGRATIONS_BYTES) {+ throw new Error("Database migrations cannot exceed 1 MiB in total");+ }+ migrations.push({+ name: entry.name,+ checksum: createHash("sha256").update(sql).digest("hex"),+ sql,+ });+ }+ return migrations;+}+export async function readProjectResources(projectRoot: string,): Promise<BuiltProjectResources> {const opencomputer = resolve(projectRoot, "opencomputer");+ const migrations = await databaseMigrations(opencomputer);const channelDefinitions = await Promise.all((await typescriptFiles(resolve(opencomputer, "channels"))).map(async (path) => channelDefinition(await readFile(path, "utf8"), path),@@ -2319,6 +2368,7 @@ export async function readProjectResources(`${right.agentId}:${right.id}`,),),+ ...(migrations.length ? { database: { migrations } } : {}),gatedTools: gatedTools.sort((left, right) =>`${left.agentId}:${left.toolId}`.localeCompare(`${right.agentId}:${right.toolId}`,diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex b7f890bd..6f20079f 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -839,6 +839,52 @@ describe("managed agents proxy", () => {expect(JSON.stringify(body)).not.toContain("private-account");});+ it("proxies bounded project database queries without exposing backend fields", async () => {+ const fetchSpy = vi.fn(async () => Response.json({+ environment: "development",+ result: {+ columns: ["id", "token"],+ rows: [{ id: 1, token: "application-owned-value", private: "drop" }],+ rowsAffected: 0,+ truncated: false,+ provider: "private",+ },+ }));+ vi.stubGlobal("fetch", fetchSpy);++ const response = await proxyManagedAgents(+ new Request("https://app.opencomputer.dev/api/managed-agents/projects/prj_test/database/query", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ environment: "development",+ sql: "SELECT id, token FROM records",+ parameters: [],+ }),+ }),+ {+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ },+ { orgID: "org_test", userID: "user_test" },+ "/api/managed-agents",+ );++ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({+ environment: "development",+ result: {+ columns: ["id", "token"],+ rows: [{ id: 1, token: "application-owned-value" }],+ rowsAffected: 0,+ truncated: false,+ },+ });+ expect(String(fetchSpy.mock.calls[0]?.[0])).toBe(+ "https://managedagents.test/v1/projects/prj_test/database/query",+ );+ });+it("exposes public template provenance on a project overview", async () => {vi.stubGlobal("fetch",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 43a2bc53..2527fa3d 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -1270,6 +1270,29 @@ function publicSuccessBody(if (method === "POST" && suffix === "/projects") {return publicProject(body);}+ if (method === "POST" && /^\/projects\/[^/]+\/database\/query$/.test(suffix)) {+ const result = record(body.result) ?? {};+ const columns = strings(result.columns);+ return {+ environment: body.environment,+ result: {+ columns,+ rows: Array.isArray(result.rows)+ ? result.rows.map((value) => {+ const row = record(value) ?? {};+ return Object.fromEntries(+ columns.map((column) => {+ const cell = row[column];+ return [column, typeof cell === "string" || typeof cell === "number" ? cell : null];+ }),+ );+ })+ : [],+ rowsAffected: typeof result.rowsAffected === "number" ? result.rowsAffected : 0,+ truncated: result.truncated === true,+ },+ };+ }if (/^\/github(?:\/connect)?$/.test(suffix) ||/^\/projects\/[^/]+\/github(?:\/(?:connect|attach|repositories))?$/.test(suffix)@@ -1808,6 +1831,9 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {if (method === "GET" && suffix === "/github") return true;if (method === "POST" && suffix === "/github/connect") return true;if (method === "GET" && /^\/projects\/[^/]+$/.test(suffix)) return true;+ if (method === "POST" && /^\/projects\/[^/]+\/database\/query$/.test(suffix)) {+ return true;+ }if (method === "GET" && /^\/projects\/[^/]+\/source-archive$/.test(suffix)) {return true;}diff --git a/create-start/package.json b/create-start/package.jsonindex 460b7106..b9f101ea 100644--- a/create-start/package.json+++ b/create-start/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/create-start",- "version": "0.7.6",+ "version": "0.7.7","description": "Create a hello-world OpenComputer agent application.","type": "module","bin": {@@ -18,7 +18,7 @@"node": ">=22.0.0"},"dependencies": {- "@opencomputer/cli": "0.7.6"+ "@opencomputer/cli": "0.7.7"},"publishConfig": {"access": "public"diff --git a/docs/agents/database.mdx b/docs/agents/database.mdxnew file mode 100644index 00000000..ba503d5a--- /dev/null+++ b/docs/agents/database.mdx@@ -0,0 +1,149 @@+---+title: "Database"+description: "A durable SQL database shared by every session in a project environment"+---++Every project environment has one durable SQL database. All agents and+sessions in that environment share it, so an agent can save structured state+in one session and read it in another. Development and Production databases+are isolated.++OpenComputer provisions the database when you deploy. You do not create a+database account, copy credentials, or configure a connection string.++## Define the schema++Add ordered SQL migrations under `opencomputer/database/migrations`:++```text+opencomputer/+└── database/+ └── migrations/+ ├── 001_initial.sql+ └── 002_monitor_runs.sql+```++Migration names begin with at least three digits and use lowercase letters,+numbers, underscores, or hyphens after the prefix. For example:++```sql 001_initial.sql+CREATE TABLE monitors (+ id TEXT PRIMARY KEY,+ url TEXT NOT NULL,+ query TEXT NOT NULL,+ last_checked_at TEXT+);++CREATE TABLE observations (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ monitor_id TEXT NOT NULL REFERENCES monitors(id),+ observed_at TEXT NOT NULL,+ content_hash TEXT NOT NULL,+ matched INTEGER NOT NULL DEFAULT 0,+ summary TEXT+);+```++Deploy normally:++```bash+npx --package @opencomputer/cli opencomputer deploy+```++Before activating the new deployment, OpenComputer applies every pending+migration in filename order. Each migration is transactional and may contain+multiple SQL statements. If a migration fails, the deployment is not+activated.++Applied migrations are immutable. Adding a new migration is safe; editing the+contents of an already-applied filename causes deployment to fail. Use a new+file for each schema change:++```sql 002_monitor_runs.sql+ALTER TABLE monitors ADD COLUMN schedule TEXT;+```++<Note>+ Prefer additive, backward-compatible migrations. Existing sessions stay on the+ deployment they started with and can overlap a newer deployment.+</Note>++## Use the database from an agent++Every project session receives a `database` MCP server automatically. Its+tools run at the OpenComputer edge and do not start or enter a sandbox:++| Tool | Accepted statements | Use |+| ------------------ | -------------------------------------------------------- | --------------------------- |+| `database_query` | One `SELECT`, `WITH`, or `EXPLAIN` statement | Read rows and inspect data. |+| `database_execute` | One `INSERT`, `UPDATE`, `DELETE`, or `REPLACE` statement | Change application data. |++Both tools accept `sql` and an optional `parameters` array. Use placeholders+instead of interpolating model-generated values:++```json+{+ "sql": "INSERT INTO observations (monitor_id, observed_at, content_hash, matched, summary) VALUES (?, ?, ?, ?, ?)",+ "parameters": [+ "pricing",+ "2026-09-17T19:00:00Z",+ "8f7c…",+ 1,+ "Enterprise plan appeared"+ ]+}+```++Schema changes and transaction-control statements are unavailable to tools;+put them in migrations. A call returns columns, rows, rows affected, and a+`truncated` flag. Results are bounded to 200 rows and 256 KiB, so add a `LIMIT`+and paginate large reads.++No hook is required. Describe when the agent should use the database in its+instructions and create the tables it needs with migrations.++## Query from the CLI++Run a read-only query against the linked project's Development database:++```bash+opencomputer database query "SELECT * FROM monitors ORDER BY id"+```++Choose Production explicitly, select another project, or bind parameters:++```bash+opencomputer database query \+ "SELECT * FROM observations WHERE monitor_id = ? LIMIT ?" \+ --parameter '"pricing"' \+ --parameter 20 \+ --environment production \+ --project <project-id-or-slug>+```++Each `--parameter` is a JSON scalar: a quoted JSON string, finite number,+boolean, or `null`. Add `--json` for the complete machine-readable result.++## Inspect data in the dashboard++Open the project and choose **Database**. The page uses the project's global+Development or Production selector and provides:++- application tables, their schema, and paginated row previews;+- applied migration history; and+- a read-only SQL query box.++The dashboard cannot modify rows or schema. Agent sessions write through+`database_execute`; schema remains source-controlled in the migrations folder.++## Limits++- 100 migrations per deployment manifest+- 256 KiB per migration and 1 MiB across all migrations+- 32 KiB per tool SQL statement+- 100 parameters totaling at most 64 KiB+- 200 returned rows and 256 KiB per result++The database belongs to the project environment, not to an individual agent+or session. Include tenant or user identifiers in your schema when application+data must be isolated within a shared environment.diff --git a/docs/agents/projects.mdx b/docs/agents/projects.mdxindex 00e371e8..0f8b7f34 100644--- a/docs/agents/projects.mdx+++ b/docs/agents/projects.mdx@@ -16,6 +16,7 @@ my-agent/│ ├── .env.example│ ├── project.ts│ ├── channels/ # optional project messaging channels+│ ├── database/ # optional default database migrations│ ├── outboxes/ # optional durable notification routes│ └── agents/│ └── hello-world/@@ -32,6 +33,8 @@ my-agent/- `opencomputer/agents/<id>/agent.ts` defines one agent.- `opencomputer/channels/` and `opencomputer/outboxes/` define shared projectresources; registrations under an agent authorize that agent to use them.+- `opencomputer/database/migrations/` holds ordered SQL migrations for the+ project's [default database](/agents/database).- `opencomputer/.env.local` optionally holds ignored development secrets.- `.opencomputer/project.json` records the linked cloud project; the CLI'sbuild output is cached under `node_modules/.cache/opencomputer/` and never@@ -107,6 +110,8 @@ The current project dashboard provides:binding- **Outboxes** for inspecting proactive notification delivery- **Memory** for reading, editing and exporting saved agent notes+- **Database** for inspecting tables, rows and applied migrations, and running+ read-only queries- **Secrets** for write-only project and agent credentialsProject and agent behavior remains code-owned. The dashboard is for selection,diff --git a/docs/docs.json b/docs/docs.jsonindex cc9ada3b..da9dacb2 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -41,6 +41,7 @@"agents/reactive-agents","agents/sessions","agents/memory",+ "agents/database","agents/schedules","agents/webhooks","agents/capabilities",diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex 539558ab..4939ffec 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -5,6 +5,7 @@ import {Boxes,BrainCircuit,CalendarClock,+ Database,FolderKanban,KeySquare,Layers,@@ -90,6 +91,11 @@ export function managedAgentsNav(options: {label: 'Memory',icon: BookOpen,},+ {+ to: `${projectPath}/database`,+ label: 'Database',+ icon: Database,+ },{to: `${projectPath}/secrets`,label: 'Secrets',diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.tsindex a531ccd8..97b434b3 100644--- a/web/src/components/app-shell.test.ts+++ b/web/src/components/app-shell.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { BrainCircuit, KeySquare, Plug } from 'lucide-react'+import { BrainCircuit, Database, KeySquare, Plug } from 'lucide-react'import { managedAgentsNav } from './app-shell-nav'describe('managed agents navigation', () => {@@ -36,6 +36,7 @@ describe('managed agents navigation', () => {'Schedules','Webhooks','Memory',+ 'Database','Secrets','Connections','BYOK',@@ -47,6 +48,9 @@ describe('managed agents navigation', () => {expect(nav[1]?.items.find((item) => item.label === 'Secrets')?.icon).toBe(KeySquare,)+ expect(nav[1]?.items.find((item) => item.label === 'Database')?.icon).toBe(+ Database,+ )expect(nav[1]?.items.find((item) => item.label === 'Connections')?.to).toBe('/projects/project%20one/connections',)diff --git a/web/src/managed-agents/Database.test.ts b/web/src/managed-agents/Database.test.tsnew file mode 100644index 00000000..a459eedf--- /dev/null+++ b/web/src/managed-agents/Database.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest'+import { quoteDatabaseIdentifier } from './Database'++describe('quoteDatabaseIdentifier', () => {+ it('quotes table names', () => {+ expect(quoteDatabaseIdentifier('monitors')).toBe('"monitors"')+ })++ it('escapes embedded quotes', () => {+ expect(quoteDatabaseIdentifier('odd"name')).toBe('"odd""name"')+ })+})diff --git a/web/src/managed-agents/Database.tsx b/web/src/managed-agents/Database.tsxnew file mode 100644index 00000000..ef0ef02e--- /dev/null+++ b/web/src/managed-agents/Database.tsx@@ -0,0 +1,377 @@+import { useState } from 'react'+import { useMutation, useQuery } from '@tanstack/react-query'+import { Database, Loader2, Play, RefreshCw } from 'lucide-react'+import { EmptyState } from '@/components/empty-state'+import { Textarea } from '@/components/form'+import {+ Panel,+ PanelContent,+ PanelDescription,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'+import { Badge } from '@/components/ui/badge'+import { Button } from '@/components/ui/button'+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table'+import { cn } from '@/lib/utils'+import {+ queryManagedProjectDatabase,+ type ManagedDatabaseResult,+ type ManagedDatabaseValue,+} from './api'+import type { ProjectEnvironment } from './project-context'++const PAGE_SIZE = 50+const TABLES_SQL = `SELECT name, sql+FROM sqlite_master+WHERE type = 'table'+ AND name NOT LIKE 'sqlite_%'+ORDER BY name`+const MIGRATIONS_SQL = `SELECT name, checksum, applied_at+FROM _opencomputer_migrations+ORDER BY name`+const DEFAULT_QUERY = `SELECT name, type+FROM sqlite_master+WHERE type IN ('table', 'view')+ORDER BY name`++export function quoteDatabaseIdentifier(value: string) {+ return `"${value.replace(/"/g, '""')}"`+}++function displayValue(value: ManagedDatabaseValue) {+ if (value === null) return <span className="text-muted-foreground">NULL</span>+ const text = String(value)+ return (+ <span className="block max-w-96 truncate font-mono text-xs" title={text}>+ {text}+ </span>+ )+}++function ResultTable({ result }: { result: ManagedDatabaseResult }) {+ if (!result.columns.length) {+ return (+ <p className="text-muted-foreground py-6 text-center text-sm">+ Query completed without returning columns.+ </p>+ )+ }+ return (+ <div className="overflow-x-auto rounded-md border">+ <Table>+ <TableHeader>+ <TableRow className="hover:bg-transparent">+ {result.columns.map((column) => (+ <TableHead key={column} className="whitespace-nowrap">+ {column}+ </TableHead>+ ))}+ </TableRow>+ </TableHeader>+ <TableBody>+ {result.rows.length ? (+ result.rows.map((row, index) => (+ <TableRow key={index}>+ {result.columns.map((column) => (+ <TableCell key={column}>+ {displayValue(row[column] ?? null)}+ </TableCell>+ ))}+ </TableRow>+ ))+ ) : (+ <TableRow className="hover:bg-transparent">+ <TableCell+ colSpan={result.columns.length}+ className="text-muted-foreground py-8 text-center"+ >+ No rows+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </div>+ )+}++export function ManagedProjectDatabase({+ projectId,+ environment,+ deployed,+}: {+ projectId: string+ environment: ProjectEnvironment+ deployed: boolean+}) {+ const [selectedName, setSelectedName] = useState<string>()+ const [offset, setOffset] = useState(0)+ const [sql, setSql] = useState(DEFAULT_QUERY)+ const tables = useQuery({+ queryKey: ['managed-project-database-tables', projectId, environment],+ queryFn: () =>+ queryManagedProjectDatabase({ projectId, environment, sql: TABLES_SQL }),+ enabled: deployed,+ })+ const applicationTables = (tables.data?.rows ?? [])+ .map((row) => ({+ name: typeof row.name === 'string' ? row.name : '',+ schema: typeof row.sql === 'string' ? row.sql : '',+ }))+ .filter((table) => table.name && !table.name.startsWith('_opencomputer_'))+ const selectedTable =+ applicationTables.find((table) => table.name === selectedName) ??+ applicationTables[0]+ const rows = useQuery({+ queryKey: [+ 'managed-project-database-rows',+ projectId,+ environment,+ selectedTable?.name,+ offset,+ ],+ queryFn: () =>+ queryManagedProjectDatabase({+ projectId,+ environment,+ sql: `SELECT * FROM ${quoteDatabaseIdentifier(selectedTable!.name)} LIMIT ${PAGE_SIZE} OFFSET ${offset}`,+ }),+ enabled: deployed && Boolean(selectedTable),+ })+ const migrations = useQuery({+ queryKey: ['managed-project-database-migrations', projectId, environment],+ queryFn: () =>+ queryManagedProjectDatabase({+ projectId,+ environment,+ sql: MIGRATIONS_SQL,+ }),+ enabled: deployed,+ })+ const customQuery = useMutation({+ mutationFn: (query: string) =>+ queryManagedProjectDatabase({ projectId, environment, sql: query }),+ })++ if (!deployed) {+ return (+ <Panel>+ <EmptyState+ icon={Database}+ title={`No ${environment} database yet`}+ description={`Deploy this project to ${environment} to provision its database and apply migrations.`}+ />+ </Panel>+ )+ }++ return (+ <div className="space-y-5">+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Database</PanelTitle>+ <PanelDescription>+ Read-only tables and rows for this project's {environment}{' '}+ environment.+ </PanelDescription>+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ void tables.refetch()+ if (selectedTable) void rows.refetch()+ void migrations.refetch()+ }}+ >+ <RefreshCw+ className={cn(+ (tables.isFetching || rows.isFetching) && 'animate-spin',+ )}+ />+ Refresh+ </Button>+ </PanelHeader>+ {tables.isError ? (+ <PanelContent>+ <Alert variant="destructive">+ <AlertTitle>Couldn't load database tables</AlertTitle>+ <AlertDescription>{tables.error.message}</AlertDescription>+ </Alert>+ </PanelContent>+ ) : (+ <PanelContent className="grid gap-5 lg:grid-cols-[14rem_minmax(0,1fr)]">+ <div>+ <div className="mb-2 flex items-center justify-between">+ <p className="text-xs font-medium">Tables</p>+ <Badge variant="secondary">{applicationTables.length}</Badge>+ </div>+ <div className="space-y-1">+ {tables.isLoading ? (+ <div className="text-muted-foreground flex items-center gap-2 py-2 text-sm">+ <Loader2 className="size-4 animate-spin" /> Loading tables+ </div>+ ) : applicationTables.length ? (+ applicationTables.map((table) => (+ <button+ key={table.name}+ type="button"+ className={cn(+ 'w-full rounded-md px-2.5 py-2 text-left font-mono text-xs transition-colors',+ selectedTable?.name === table.name+ ? 'bg-accent text-accent-foreground'+ : 'text-muted-foreground hover:bg-muted hover:text-foreground',+ )}+ onClick={() => {+ setSelectedName(table.name)+ setOffset(0)+ }}+ >+ {table.name}+ </button>+ ))+ ) : (+ <p className="text-muted-foreground py-2 text-sm">+ No application tables+ </p>+ )}+ </div>+ </div>+ <div className="min-w-0 space-y-4">+ {selectedTable ? (+ <>+ <div>+ <h3 className="font-mono text-sm font-semibold">+ {selectedTable.name}+ </h3>+ <pre className="bg-muted/40 text-muted-foreground mt-2 overflow-x-auto rounded-md border p-3 text-xs leading-5">+ <code>{selectedTable.schema}</code>+ </pre>+ </div>+ {rows.isError ? (+ <Alert variant="destructive">+ <AlertTitle>Couldn't load rows</AlertTitle>+ <AlertDescription>{rows.error.message}</AlertDescription>+ </Alert>+ ) : rows.data ? (+ <>+ <ResultTable result={rows.data} />+ <div className="flex items-center justify-between">+ <p className="text-muted-foreground text-xs">+ {rows.data.rows.length+ ? `Rows ${offset + 1}–${offset + rows.data.rows.length}`+ : 'No rows on this page'}+ </p>+ <div className="flex gap-2">+ <Button+ variant="outline"+ size="sm"+ disabled={offset === 0}+ onClick={() =>+ setOffset(Math.max(0, offset - PAGE_SIZE))+ }+ >+ Previous+ </Button>+ <Button+ variant="outline"+ size="sm"+ disabled={rows.data.rows.length < PAGE_SIZE}+ onClick={() => setOffset(offset + PAGE_SIZE)}+ >+ Next+ </Button>+ </div>+ </div>+ </>+ ) : (+ <div className="text-muted-foreground flex min-h-32 items-center justify-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" /> Loading rows+ </div>+ )}+ </>+ ) : null}+ </div>+ </PanelContent>+ )}+ </Panel>++ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Migrations</PanelTitle>+ <PanelDescription>+ Applied schema migrations for {environment}.+ </PanelDescription>+ </div>+ </PanelHeader>+ <PanelContent>+ {migrations.isError ? (+ <Alert variant="destructive">+ <AlertTitle>Couldn't load migrations</AlertTitle>+ <AlertDescription>{migrations.error.message}</AlertDescription>+ </Alert>+ ) : migrations.data ? (+ <ResultTable result={migrations.data} />+ ) : (+ <div className="text-muted-foreground flex min-h-20 items-center justify-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" /> Loading migrations+ </div>+ )}+ </PanelContent>+ </Panel>++ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Read-only query</PanelTitle>+ <PanelDescription>+ Run one SELECT, WITH, or EXPLAIN statement. Results are bounded to+ 200 rows.+ </PanelDescription>+ </div>+ </PanelHeader>+ <PanelContent className="space-y-4">+ <Textarea+ aria-label="Read-only SQL query"+ className="min-h-28 font-mono text-xs"+ value={sql}+ onChange={(event) => setSql(event.target.value)}+ />+ <div className="flex justify-end">+ <Button+ size="sm"+ disabled={!sql.trim() || customQuery.isPending}+ onClick={() => customQuery.mutate(sql)}+ >+ {customQuery.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <Play />+ )}+ Run query+ </Button>+ </div>+ {customQuery.isError ? (+ <Alert variant="destructive">+ <AlertTitle>Query failed</AlertTitle>+ <AlertDescription>{customQuery.error.message}</AlertDescription>+ </Alert>+ ) : customQuery.data ? (+ <ResultTable result={customQuery.data} />+ ) : null}+ </PanelContent>+ </Panel>+ </div>+ )+}diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex a113108a..f1ab2709 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -79,6 +79,7 @@ import { ManagedAgentOutboxes } from './Outboxes'import { ManagedAgentSchedules } from './Schedules'import { ManagedAgentWebhooks } from './Webhooks'import { ManagedProjectMemory } from './Memory'+import { ManagedProjectDatabase } from './Database'import { ManagedProjectBYOK } from './BYOK'import { ManagedProjectGitHub } from './GitHub'import { AgentMarkdown } from './AgentMarkdown'@@ -96,6 +97,7 @@ type DetailTab =| 'schedules'| 'webhooks'| 'memory'+ | 'database'| 'secrets'| 'connections'| 'github'@@ -110,6 +112,7 @@ export const PROJECT_DETAIL_TABS = new Set<DetailTab>(['schedules','webhooks','memory',+ 'database','secrets','connections','github',@@ -748,6 +751,7 @@ export default function ManagedAgentDetail({...(project ? ([{ id: 'schedules', label: 'Schedules' }] as const) : []),...(project ? ([{ id: 'webhooks', label: 'Webhooks' }] as const) : []),...(project ? ([{ id: 'memory', label: 'Memory' }] as const) : []),+ ...(project ? ([{ id: 'database', label: 'Database' }] as const) : []),...(project ? ([{ id: 'secrets', label: 'Secrets' }] as const) : []),...(project? ([{ id: 'connections', label: 'Connections' }] as const)@@ -1244,6 +1248,15 @@ export default function ManagedAgentDetail({/>) : null}+ {activeTab === 'database' && project ? (+ <ManagedProjectDatabase+ key={`${project.project.id}:${environment}`}+ projectId={project.project.id}+ environment={environment}+ deployed={Boolean(projectEnvironment?.activeDeploymentId)}+ />+ ) : null}+{activeTab === 'secrets' && project ? (<ManagedProjectSecretsprojectId={project.project.id}diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex c14e9eb0..aea709b7 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -103,6 +103,18 @@ const projectSchema = z.object({const projectsResponseSchema = z.object({ projects: z.array(projectSchema) })+const databaseValueSchema = z.union([z.string(), z.number(), z.null()])+const databaseResultSchema = z.object({+ columns: z.array(z.string()),+ rows: z.array(z.record(z.string(), databaseValueSchema)),+ rowsAffected: z.number(),+ truncated: z.boolean(),+})+const databaseQueryResponseSchema = z.object({+ environment: z.enum(['development', 'production']),+ result: databaseResultSchema,+})+const templateInspectionSchema = z.object({id: z.string(),repository: z.object({@@ -809,6 +821,31 @@ export async function getManagedProject(projectId: string) {)}+export type ManagedDatabaseValue = z.infer<typeof databaseValueSchema>+export type ManagedDatabaseResult = z.infer<typeof databaseResultSchema>++export async function queryManagedProjectDatabase(input: {+ projectId: string+ environment: 'development' | 'production'+ sql: string+ parameters?: Array<string | number | boolean | null>+}) {+ return (+ await apiFetch(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/database/query`,+ {+ method: 'POST',+ body: JSON.stringify({+ environment: input.environment,+ sql: input.sql,+ parameters: input.parameters ?? [],+ }),+ },+ databaseQueryResponseSchema,+ )+ ).result+}+export async function getManagedGitHubStatus(projectId: string) {return apiFetch(`/managed-agents/projects/${encodeURIComponent(projectId)}/github`,