Unified · Split
| @@ -17,6 +17,14 @@ CONVEX_SITE_URL=https://your-deployment.convex.site · 16 unmodified lines | ||
| 17 | 17 | # When enabled, local Bun execution is allowed. |
| 18 | 18 | # Leave unset in production to default to Cloudflare runtime. |
| 19 | 19 | # DANGEROUSLY_ALLOW_LOCAL_VM=1 |
| 20 | +# Secret encryption key for v2 Convex credential storage (required when using v2 Convex control plane) | |
| 21 | +# CREDENTIAL_ENCRYPTION_KEY=change-me-to-a-long-random-string | |
| 22 | +# Cloudflare worker loader runtime (required for v2 Convex code execution) | |
| 23 | +# CLOUDFLARE_SANDBOX_RUN_URL=http://127.0.0.1:8789/v1/runs | |
| 24 | +# CLOUDFLARE_SANDBOX_AUTH_TOKEN=sandbox-token | |
| 25 | +# CLOUDFLARE_SANDBOX_CALLBACK_URL=http://127.0.0.1:8788/v1/runtime/tool-call | |
| 26 | +# Optional callback signature secret: | |
| 27 | +# CLOUDFLARE_SANDBOX_CALLBACK_SECRET=change-me | |
| 20 | 28 | |
| 21 | 29 | # ── Agent storage backend (optional) ── |
| 22 | 30 | # Default: agentfs-local |
| @@ -38,6 +46,13 @@ CONVEX_SITE_URL=https://your-deployment.convex.site · 15 unmodified lines | ||
| 38 | 46 | # WORKOS_COOKIE_PASSWORD=<32+ char random string, e.g. openssl rand -base64 32> |
| 39 | 47 | # WORKOS_WEBHOOK_SECRET=... |
| 40 | 48 | # WORKOS_FORCE_ENABLED=1 |
| 49 | +# WorkOS Vault script helpers (optional): | |
| 50 | +# WORKOS_VAULT_OBJECT_ID=secret_... | |
| 51 | +# WORKOS_VAULT_CONTEXT_JSON={"workspace_id":"local"} | |
| 52 | +# WORKOS_VAULT_ITERATIONS=10 | |
| 53 | +# WORKOS_VAULT_WARMUP_ITERATIONS=1 | |
| 54 | +# WORKOS_VAULT_VALUE_BYTES=256 | |
| 55 | +# WORKOS_VAULT_DELETE_AFTER=1 | |
| 41 | 56 | |
| 42 | 57 | # ── Anonymous JWT Auth (optional — enables anonymous bearer auth via Convex Auth) ── |
| 43 | 58 | # Generate an ES256 key pair (PKCS8 private + SPKI public), then set both PEM values. |
| @@ -0,0 +1,146 @@ | ||
| 1 | +#!/usr/bin/env bun | |
| 2 | + | |
| 3 | +import { | |
| 4 | + buildObjectName, | |
| 5 | + buildRandomValue, | |
| 6 | + formatMs, | |
| 7 | + getArg, | |
| 8 | + hasFlag, | |
| 9 | + measureLatency, | |
| 10 | + printStats, | |
| 11 | + readBoolean, | |
| 12 | + readEnv, | |
| 13 | + readInt, | |
| 14 | + resolveContext, | |
| 15 | + resolveWorkosClient, | |
| 16 | +} from "./shared"; | |
| 17 | + | |
| 18 | +function printHelp(): void { | |
| 19 | + console.log("Measure WorkOS Vault write and read latency."); | |
| 20 | + console.log(""); | |
| 21 | + console.log("Usage:"); | |
| 22 | + console.log(" bun run executor/scripts/workos-vault/latency.ts [--iterations <n>] [--warmup <n>] [--object-id <id>] [--value-bytes <n>] [--no-delete]"); | |
| 23 | + console.log(""); | |
| 24 | + console.log("Env:"); | |
| 25 | + console.log(" WORKOS_API_KEY Required"); | |
| 26 | + console.log(" WORKOS_VAULT_OBJECT_ID Optional existing object id"); | |
| 27 | + console.log(" WORKOS_VAULT_CONTEXT_JSON Optional JSON object for create context"); | |
| 28 | + console.log(" WORKOS_VAULT_ITERATIONS Optional, default 10"); | |
| 29 | + console.log(" WORKOS_VAULT_WARMUP_ITERATIONS Optional, default 1"); | |
| 30 | + console.log(" WORKOS_VAULT_VALUE_BYTES Optional, default 256"); | |
| 31 | + console.log(" WORKOS_VAULT_DELETE_AFTER Optional, default true"); | |
| 32 | +} | |
| 33 | + | |
| 34 | +async function main(): Promise<void> { | |
| 35 | + if (hasFlag("help")) { | |
| 36 | + printHelp(); | |
| 37 | + return; | |
| 38 | + } | |
| 39 | + | |
| 40 | + const workos = resolveWorkosClient(); | |
| 41 | + | |
| 42 | + const iterations = Math.max( | |
| 43 | + 1, | |
| 44 | + readInt(getArg("iterations") ?? readEnv("WORKOS_VAULT_ITERATIONS"), 10), | |
| 45 | + ); | |
| 46 | + const warmupIterations = Math.max( | |
| 47 | + 0, | |
| 48 | + readInt(getArg("warmup") ?? readEnv("WORKOS_VAULT_WARMUP_ITERATIONS"), 1), | |
| 49 | + ); | |
| 50 | + const valueBytes = Math.max( | |
| 51 | + 16, | |
| 52 | + readInt(getArg("value-bytes") ?? readEnv("WORKOS_VAULT_VALUE_BYTES"), 256), | |
| 53 | + ); | |
| 54 | + const context = resolveContext(readEnv("WORKOS_VAULT_CONTEXT_JSON")); | |
| 55 | + | |
| 56 | + const shouldDeleteAfter = hasFlag("no-delete") | |
| 57 | + ? false | |
| 58 | + : readBoolean(readEnv("WORKOS_VAULT_DELETE_AFTER"), true); | |
| 59 | + | |
| 60 | + const providedObjectId = getArg("object-id") ?? readEnv("WORKOS_VAULT_OBJECT_ID"); | |
| 61 | + | |
| 62 | + let objectId = providedObjectId; | |
| 63 | + let createdObject = false; | |
| 64 | + | |
| 65 | + if (!objectId) { | |
| 66 | + const initialValue = buildRandomValue(valueBytes); | |
| 67 | + const objectName = buildObjectName("executor-vault-latency"); | |
| 68 | + const created = await workos.vault.createObject({ | |
| 69 | + name: objectName, | |
| 70 | + value: initialValue, | |
| 71 | + context, | |
| 72 | + }); | |
| 73 | + objectId = created.id; | |
| 74 | + createdObject = true; | |
| 75 | + } | |
| 76 | + | |
| 77 | + if (!objectId) { | |
| 78 | + throw new Error("Failed to resolve a WorkOS Vault object id"); | |
| 79 | + } | |
| 80 | + | |
| 81 | + const writeLatencies: number[] = []; | |
| 82 | + const readLatencies: number[] = []; | |
| 83 | + const roundtripLatencies: number[] = []; | |
| 84 | + | |
| 85 | + for (let i = 0; i < warmupIterations; i += 1) { | |
| 86 | + const value = buildRandomValue(valueBytes); | |
| 87 | + await workos.vault.updateObject({ | |
| 88 | + id: objectId, | |
| 89 | + value, | |
| 90 | + }); | |
| 91 | + await workos.vault.readObject({ | |
| 92 | + id: objectId, | |
| 93 | + }); | |
| 94 | + } | |
| 95 | + | |
| 96 | + for (let i = 0; i < iterations; i += 1) { | |
| 97 | + const value = buildRandomValue(valueBytes); | |
| 98 | + const roundtripStartedAt = performance.now(); | |
| 99 | + | |
| 100 | + const writeResult = await measureLatency(() => | |
| 101 | + workos.vault.updateObject({ | |
| 102 | + id: objectId, | |
| 103 | + value, | |
| 104 | + }) | |
| 105 | + ); | |
| 106 | + const readResult = await measureLatency(() => | |
| 107 | + workos.vault.readObject({ | |
| 108 | + id: objectId, | |
| 109 | + }) | |
| 110 | + ); | |
| 111 | + | |
| 112 | + const readValue = typeof readResult.value.value === "string" ? readResult.value.value : ""; | |
| 113 | + if (readValue !== value) { | |
| 114 | + throw new Error(`Read-back mismatch on iteration ${i + 1}`); | |
| 115 | + } | |
| 116 | + | |
| 117 | + writeLatencies.push(writeResult.durationMs); | |
| 118 | + readLatencies.push(readResult.durationMs); | |
| 119 | + roundtripLatencies.push(performance.now() - roundtripStartedAt); | |
| 120 | + } | |
| 121 | + | |
| 122 | + let cleanupLatencyMs: number | null = null; | |
| 123 | + if (createdObject && shouldDeleteAfter) { | |
| 124 | + const cleanup = await measureLatency(() => | |
| 125 | + workos.vault.deleteObject({ | |
| 126 | + id: objectId, | |
| 127 | + }) | |
| 128 | + ); | |
| 129 | + cleanupLatencyMs = cleanup.durationMs; | |
| 130 | + } | |
| 131 | + | |
| 132 | + console.log("workos vault latency benchmark complete"); | |
| 133 | + console.log(`objectId: ${objectId}${createdObject ? " (created by script)" : " (provided)"}`); | |
| 134 | + console.log(`iterations: ${iterations}`); | |
| 135 | + console.log(`warmupIterations: ${warmupIterations}`); | |
| 136 | + console.log(`valueBytes: ${valueBytes}`); | |
| 137 | + console.log(`cleanup: ${createdObject ? (shouldDeleteAfter ? "deleted" : "kept") : "not-applicable"}`); | |
| 138 | + if (cleanupLatencyMs !== null) { | |
| 139 | + console.log(`cleanupLatency: ${formatMs(cleanupLatencyMs)}`); | |
| 140 | + } | |
| 141 | + printStats("write", writeLatencies); | |
| 142 | + printStats("read", readLatencies); | |
| 143 | + printStats("roundtrip", roundtripLatencies); | |
| 144 | +} | |
| 145 | + | |
| 146 | +await main(); | |
| @@ -0,0 +1,55 @@ | ||
| 1 | +#!/usr/bin/env bun | |
| 2 | + | |
| 3 | +import { | |
| 4 | + formatMs, | |
| 5 | + getArg, | |
| 6 | + hasFlag, | |
| 7 | + measureLatency, | |
| 8 | + readEnv, | |
| 9 | + resolveWorkosClient, | |
| 10 | +} from "./shared"; | |
| 11 | + | |
| 12 | +function printHelp(): void { | |
| 13 | + console.log("Read one object from WorkOS Vault and print latency."); | |
| 14 | + console.log(""); | |
| 15 | + console.log("Usage:"); | |
| 16 | + console.log(" bun run executor/scripts/workos-vault/read.ts --object-id <id> [--show-value]"); | |
| 17 | + console.log(""); | |
| 18 | + console.log("Env:"); | |
| 19 | + console.log(" WORKOS_API_KEY Required"); | |
| 20 | + console.log(" WORKOS_VAULT_OBJECT_ID Required when --object-id is not provided"); | |
| 21 | +} | |
| 22 | + | |
| 23 | +async function main(): Promise<void> { | |
| 24 | + if (hasFlag("help")) { | |
| 25 | + printHelp(); | |
| 26 | + return; | |
| 27 | + } | |
| 28 | + | |
| 29 | + const workos = resolveWorkosClient(); | |
| 30 | + const objectId = getArg("object-id") ?? readEnv("WORKOS_VAULT_OBJECT_ID"); | |
| 31 | + if (!objectId) { | |
| 32 | + throw new Error("Missing object id. Pass --object-id <id> or set WORKOS_VAULT_OBJECT_ID."); | |
| 33 | + } | |
| 34 | + | |
| 35 | + const { value: object, durationMs } = await measureLatency(() => | |
| 36 | + workos.vault.readObject({ | |
| 37 | + id: objectId, | |
| 38 | + }) | |
| 39 | + ); | |
| 40 | + | |
| 41 | + const value = typeof object.value === "string" ? object.value : ""; | |
| 42 | + const showValue = hasFlag("show-value"); | |
| 43 | + | |
| 44 | + console.log("workos vault read complete"); | |
| 45 | + console.log(`objectId: ${object.id}`); | |
| 46 | + console.log(`name: ${object.name}`); | |
| 47 | + console.log(`valueLength: ${value.length}`); | |
| 48 | + console.log(`latency: ${formatMs(durationMs)}`); | |
| 49 | + | |
| 50 | + if (showValue) { | |
| 51 | + console.log(`value: ${value}`); | |
| 52 | + } | |
| 53 | +} | |
| 54 | + | |
| 55 | +await main(); | |
| @@ -0,0 +1,172 @@ | ||
| 1 | +import { WorkOS } from "@workos-inc/node"; | |
| 2 | + | |
| 3 | +export interface LatencyStats { | |
| 4 | + minMs: number; | |
| 5 | + p50Ms: number; | |
| 6 | + p95Ms: number; | |
| 7 | + maxMs: number; | |
| 8 | + avgMs: number; | |
| 9 | +} | |
| 10 | + | |
| 11 | +export function getArg(name: string): string | undefined { | |
| 12 | + const prefixed = `--${name}=`; | |
| 13 | + for (const arg of process.argv.slice(2)) { | |
| 14 | + if (arg.startsWith(prefixed)) { | |
| 15 | + return arg.slice(prefixed.length); | |
| 16 | + } | |
| 17 | + } | |
| 18 | + | |
| 19 | + const exact = `--${name}`; | |
| 20 | + const index = process.argv.indexOf(exact); | |
| 21 | + if (index === -1) { | |
| 22 | + return undefined; | |
| 23 | + } | |
| 24 | + | |
| 25 | + const next = process.argv[index + 1]; | |
| 26 | + if (!next || next.startsWith("--")) { | |
| 27 | + return undefined; | |
| 28 | + } | |
| 29 | + | |
| 30 | + return next; | |
| 31 | +} | |
| 32 | + | |
| 33 | +export function hasFlag(name: string): boolean { | |
| 34 | + const exact = `--${name}`; | |
| 35 | + return process.argv.includes(exact); | |
| 36 | +} | |
| 37 | + | |
| 38 | +export function readEnv(name: string): string | undefined { | |
| 39 | + const value = process.env[name]; | |
| 40 | + if (!value) { | |
| 41 | + return undefined; | |
| 42 | + } | |
| 43 | + | |
| 44 | + const trimmed = value.trim(); | |
| 45 | + return trimmed.length > 0 ? trimmed : undefined; | |
| 46 | +} | |
| 47 | + | |
| 48 | +export function readRequiredEnv(name: string): string { | |
| 49 | + const value = readEnv(name); | |
| 50 | + if (!value) { | |
| 51 | + throw new Error(`Missing required env var: ${name}`); | |
| 52 | + } | |
| 53 | + return value; | |
| 54 | +} | |
| 55 | + | |
| 56 | +export function readInt(value: string | undefined, fallback: number): number { | |
| 57 | + if (!value) { | |
| 58 | + return fallback; | |
| 59 | + } | |
| 60 | + | |
| 61 | + const parsed = Number.parseInt(value, 10); | |
| 62 | + if (!Number.isFinite(parsed)) { | |
| 63 | + return fallback; | |
| 64 | + } | |
| 65 | + | |
| 66 | + return parsed; | |
| 67 | +} | |
| 68 | + | |
| 69 | +export function readBoolean(value: string | undefined, fallback: boolean): boolean { | |
| 70 | + if (!value) { | |
| 71 | + return fallback; | |
| 72 | + } | |
| 73 | + | |
| 74 | + const normalized = value.trim().toLowerCase(); | |
| 75 | + if (["1", "true", "yes", "on"].includes(normalized)) { | |
| 76 | + return true; | |
| 77 | + } | |
| 78 | + | |
| 79 | + if (["0", "false", "no", "off"].includes(normalized)) { | |
| 80 | + return false; | |
| 81 | + } | |
| 82 | + | |
| 83 | + return fallback; | |
| 84 | +} | |
| 85 | + | |
| 86 | +export function resolveContext(raw: string | undefined): Record<string, unknown> { | |
| 87 | + if (!raw) { | |
| 88 | + return { workspace_id: "local" }; | |
| 89 | + } | |
| 90 | + | |
| 91 | + let parsed: unknown; | |
| 92 | + try { | |
| 93 | + parsed = JSON.parse(raw); | |
| 94 | + } catch (error) { | |
| 95 | + throw new Error(`Failed to parse context JSON: ${error instanceof Error ? error.message : String(error)}`); | |
| 96 | + } | |
| 97 | + | |
| 98 | + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { | |
| 99 | + throw new Error("WORKOS_VAULT_CONTEXT_JSON must be a JSON object"); | |
| 100 | + } | |
| 101 | + | |
| 102 | + return parsed as Record<string, unknown>; | |
| 103 | +} | |
| 104 | + | |
| 105 | +export function resolveWorkosClient(): WorkOS { | |
| 106 | + const apiKey = readRequiredEnv("WORKOS_API_KEY"); | |
| 107 | + return new WorkOS(apiKey); | |
| 108 | +} | |
| 109 | + | |
| 110 | +export async function measureLatency<T>(operation: () => Promise<T>): Promise<{ value: T; durationMs: number }> { | |
| 111 | + const startedAt = performance.now(); | |
| 112 | + const value = await operation(); | |
| 113 | + const durationMs = performance.now() - startedAt; | |
| 114 | + return { value, durationMs }; | |
| 115 | +} | |
| 116 | + | |
| 117 | +function percentile(sortedValues: readonly number[], quantile: number): number { | |
| 118 | + if (sortedValues.length === 0) { | |
| 119 | + return 0; | |
| 120 | + } | |
| 121 | + | |
| 122 | + const normalized = Math.min(1, Math.max(0, quantile)); | |
| 123 | + const index = Math.ceil(sortedValues.length * normalized) - 1; | |
| 124 | + const clampedIndex = Math.min(sortedValues.length - 1, Math.max(0, index)); | |
| 125 | + return sortedValues[clampedIndex] ?? 0; | |
| 126 | +} | |
| 127 | + | |
| 128 | +export function computeStats(samples: readonly number[]): LatencyStats { | |
| 129 | + if (samples.length === 0) { | |
| 130 | + return { | |
| 131 | + minMs: 0, | |
| 132 | + p50Ms: 0, | |
| 133 | + p95Ms: 0, | |
| 134 | + maxMs: 0, | |
| 135 | + avgMs: 0, | |
| 136 | + }; | |
| 137 | + } | |
| 138 | + | |
| 139 | + const sorted = [...samples].sort((a, b) => a - b); | |
| 140 | + const sum = sorted.reduce((total, value) => total + value, 0); | |
| 141 | + | |
| 142 | + return { | |
| 143 | + minMs: sorted[0] ?? 0, | |
| 144 | + p50Ms: percentile(sorted, 0.5), | |
| 145 | + p95Ms: percentile(sorted, 0.95), | |
| 146 | + maxMs: sorted[sorted.length - 1] ?? 0, | |
| 147 | + avgMs: sum / sorted.length, | |
| 148 | + }; | |
| 149 | +} | |
| 150 | + | |
| 151 | +export function formatMs(value: number): string { | |
| 152 | + return `${value.toFixed(2)}ms`; | |
| 153 | +} | |
| 154 | + | |
| 155 | +export function buildObjectName(prefix: string): string { | |
| 156 | + return `${prefix}-${Date.now()}-${crypto.randomUUID().slice(0, 8)}`; | |
| 157 | +} | |
| 158 | + | |
| 159 | +export function buildRandomValue(byteLength: number): string { | |
| 160 | + const target = Math.max(16, byteLength); | |
| 161 | + const suffix = crypto.randomUUID(); | |
| 162 | + const head = `bench-${Date.now()}-${suffix}-`; | |
| 163 | + const fillerLength = Math.max(0, target - head.length); | |
| 164 | + return `${head}${"x".repeat(fillerLength)}`; | |
| 165 | +} | |
| 166 | + | |
| 167 | +export function printStats(label: string, samples: readonly number[]): void { | |
| 168 | + const stats = computeStats(samples); | |
| 169 | + console.log( | |
| 170 | + `${label}: min=${formatMs(stats.minMs)} p50=${formatMs(stats.p50Ms)} p95=${formatMs(stats.p95Ms)} max=${formatMs(stats.maxMs)} avg=${formatMs(stats.avgMs)}`, | |
| 171 | + ); | |
| 172 | +} | |
| @@ -0,0 +1,60 @@ | ||
| 1 | +#!/usr/bin/env bun | |
| 2 | + | |
| 3 | +import { | |
| 4 | + buildObjectName, | |
| 5 | + buildRandomValue, | |
| 6 | + formatMs, | |
| 7 | + getArg, | |
| 8 | + hasFlag, | |
| 9 | + measureLatency, | |
| 10 | + readEnv, | |
| 11 | + resolveContext, | |
| 12 | + resolveWorkosClient, | |
| 13 | +} from "./shared"; | |
| 14 | + | |
| 15 | +function printHelp(): void { | |
| 16 | + console.log("Write one object to WorkOS Vault and print latency."); | |
| 17 | + console.log(""); | |
| 18 | + console.log("Usage:"); | |
| 19 | + console.log(" bun run executor/scripts/workos-vault/write.ts [--name <name>] [--value <secret>] [--context-json <json>]"); | |
| 20 | + console.log(""); | |
| 21 | + console.log("Env:"); | |
| 22 | + console.log(" WORKOS_API_KEY Required"); | |
| 23 | + console.log(" WORKOS_VAULT_OBJECT_NAME Optional object name"); | |
| 24 | + console.log(" WORKOS_VAULT_SECRET_VALUE Optional secret value"); | |
| 25 | + console.log(" WORKOS_VAULT_CONTEXT_JSON Optional JSON object (default: {\"workspace_id\":\"local\"})"); | |
| 26 | +} | |
| 27 | + | |
| 28 | +async function main(): Promise<void> { | |
| 29 | + if (hasFlag("help")) { | |
| 30 | + printHelp(); | |
| 31 | + return; | |
| 32 | + } | |
| 33 | + | |
| 34 | + const workos = resolveWorkosClient(); | |
| 35 | + | |
| 36 | + const name = getArg("name") | |
| 37 | + ?? readEnv("WORKOS_VAULT_OBJECT_NAME") | |
| 38 | + ?? buildObjectName("executor-vault-write"); | |
| 39 | + const value = getArg("value") | |
| 40 | + ?? readEnv("WORKOS_VAULT_SECRET_VALUE") | |
| 41 | + ?? buildRandomValue(256); | |
| 42 | + const contextRaw = getArg("context-json") ?? readEnv("WORKOS_VAULT_CONTEXT_JSON"); | |
| 43 | + const context = resolveContext(contextRaw); | |
| 44 | + | |
| 45 | + const { value: created, durationMs } = await measureLatency(() => | |
| 46 | + workos.vault.createObject({ | |
| 47 | + name, | |
| 48 | + value, | |
| 49 | + context, | |
| 50 | + }) | |
| 51 | + ); | |
| 52 | + | |
| 53 | + console.log("workos vault write complete"); | |
| 54 | + console.log(`objectId: ${created.id}`); | |
| 55 | + console.log(`name: ${name}`); | |
| 56 | + console.log(`valueLength: ${value.length}`); | |
| 57 | + console.log(`latency: ${formatMs(durationMs)}`); | |
| 58 | +} | |
| 59 | + | |
| 60 | +await main(); | |
| @@ -12,6 +12,9 @@ · 11 unmodified lines | ||
| 12 | 12 | "scripts": { |
| 13 | 13 | "with-env": "bun run --env-file=.env --", |
| 14 | 14 | "dev": "bun run dev.ts", |
| 15 | + "workos:vault:write": "bun run with-env bun run executor/scripts/workos-vault/write.ts", | |
| 16 | + "workos:vault:read": "bun run with-env bun run executor/scripts/workos-vault/read.ts", | |
| 17 | + "workos:vault:latency": "bun run with-env bun run executor/scripts/workos-vault/latency.ts", | |
| 15 | 18 | "test": "bun run test:executor && bun run test:assistant", |
| 16 | 19 | "test:executor": "bun run --cwd executor test", |
| 17 | 20 | "test:executor:integration": "bun run --cwd executor test:integration", |
| @@ -23,6 +23,7 @@ import type * as control_plane_storage from "../control_plane/storage.js"; · 22 unmodified lines | ||
| 23 | 23 | import type * as control_plane_tool_registry from "../control_plane/tool_registry.js"; |
| 24 | 24 | import type * as control_plane_tools from "../control_plane/tools.js"; |
| 25 | 25 | import type * as control_plane_workspaces from "../control_plane/workspaces.js"; |
| 26 | +import type * as credential_crypto from "../credential_crypto.js"; | |
| 26 | 27 | import type * as credential_resolver from "../credential_resolver.js"; |
| 27 | 28 | import type * as executor from "../executor.js"; |
| 28 | 29 | import type * as http from "../http.js"; |
| @@ -58,6 +59,7 @@ declare const fullApi: ApiFromModules<{ · 29 unmodified lines | ||
| 58 | 59 | "control_plane/tool_registry": typeof control_plane_tool_registry; |
| 59 | 60 | "control_plane/tools": typeof control_plane_tools; |
| 60 | 61 | "control_plane/workspaces": typeof control_plane_workspaces; |
| 62 | + credential_crypto: typeof credential_crypto; | |
| 61 | 63 | credential_resolver: typeof credential_resolver; |
| 62 | 64 | executor: typeof executor; |
| 63 | 65 | http: typeof http; |
| @@ -33,6 +33,17 @@ const stripConvexSystemFields = ( · 32 unmodified lines | ||
| 33 | 33 | return rest; |
| 34 | 34 | }; |
| 35 | 35 | |
| 36 | +const toOrganizationSlug = (accountId: string): string => { | |
| 37 | + const slug = accountId | |
| 38 | + .trim() | |
| 39 | + .toLowerCase() | |
| 40 | + .replace(/[^a-z0-9]+/g, "-") | |
| 41 | + .replace(/^-+/, "") | |
| 42 | + .replace(/-+$/, ""); | |
| 43 | + | |
| 44 | + return slug.length > 0 ? `acct-${slug}` : `acct-${crypto.randomUUID().slice(0, 8)}`; | |
| 45 | +}; | |
| 46 | + | |
| 36 | 47 | export const getWorkspaceForActor = internalQuery({ |
| 37 | 48 | args: { |
| 38 | 49 | workspaceId: v.string(), |
| @@ -107,6 +118,49 @@ export const ensureWorkspaceForActor = internalMutation({ · 68 unmodified lines | ||
| 107 | 118 | handler: async (ctx, args): Promise<Workspace> => { |
| 108 | 119 | const now = Date.now(); |
| 109 | 120 | |
| 121 | + const ensureOrganizationMembership = async (organizationId: string) => { | |
| 122 | + const existingOrganization = await ctx.db | |
| 123 | + .query("organizations") | |
| 124 | + .withIndex("by_domainId", (q) => q.eq("id", organizationId)) | |
| 125 | + .first(); | |
| 126 | + | |
| 127 | + if (existingOrganization === null) { | |
| 128 | + await ctx.db.insert("organizations", { | |
| 129 | + id: organizationId, | |
| 130 | + slug: toOrganizationSlug(args.accountId), | |
| 131 | + name: `${args.accountId} Organization`, | |
| 132 | + status: "active", | |
| 133 | + createdByAccountId: args.accountId, | |
| 134 | + createdAt: now, | |
| 135 | + updatedAt: now, | |
| 136 | + }); | |
| 137 | + } | |
| 138 | + | |
| 139 | + const existingMembership = await ctx.db | |
| 140 | + .query("organizationMemberships") | |
| 141 | + .withIndex("by_organizationId_accountId", (q) => | |
| 142 | + q.eq("organizationId", organizationId).eq("accountId", args.accountId) | |
| 143 | + ) | |
| 144 | + .first(); | |
| 145 | + | |
| 146 | + if (existingMembership !== null) { | |
| 147 | + return; | |
| 148 | + } | |
| 149 | + | |
| 150 | + await ctx.db.insert("organizationMemberships", { | |
| 151 | + id: `org_member_${crypto.randomUUID()}`, | |
| 152 | + organizationId, | |
| 153 | + accountId: args.accountId, | |
| 154 | + role: "owner", | |
| 155 | + status: "active", | |
| 156 | + billable: false, | |
| 157 | + invitedByAccountId: null, | |
| 158 | + joinedAt: now, | |
| 159 | + createdAt: now, | |
| 160 | + updatedAt: now, | |
| 161 | + }); | |
| 162 | + }; | |
| 163 | + | |
| 110 | 164 | const existing = await ctx.db |
| 111 | 165 | .query("workspaces") |
| 112 | 166 | .withIndex("by_domainId", (q) => q.eq("id", args.workspaceId)) |
| @@ -117,6 +171,8 @@ export const ensureWorkspaceForActor = internalMutation({ · 4 unmodified lines | ||
| 117 | 171 | stripConvexSystemFields(existing as unknown as Record<string, unknown>), |
| 118 | 172 | ); |
| 119 | 173 | |
| 174 | + await ensureOrganizationMembership(existingWorkspace.organizationId); | |
| 175 | + | |
| 120 | 176 | if (existingWorkspace.createdByAccountId !== null) { |
| 121 | 177 | return existingWorkspace; |
| 122 | 178 | } |
| @@ -133,9 +189,12 @@ export const ensureWorkspaceForActor = internalMutation({ · 10 unmodified lines | ||
| 133 | 189 | }); |
| 134 | 190 | } |
| 135 | 191 | |
| 192 | + const organizationId = `org_${args.accountId}`; | |
| 193 | + await ensureOrganizationMembership(organizationId); | |
| 194 | + | |
| 136 | 195 | await ctx.db.insert("workspaces", { |
| 137 | 196 | id: args.workspaceId, |
| 138 | − organizationId: null, | |
| 197 | + organizationId, | |
| 139 | 198 | name: args.workspaceId, |
| 140 | 199 | createdByAccountId: args.accountId, |
| 141 | 200 | createdAt: now, |
| @@ -144,7 +203,7 @@ export const ensureWorkspaceForActor = internalMutation({ · 2 unmodified lines | ||
| 144 | 203 | |
| 145 | 204 | return decodeWorkspace({ |
| 146 | 205 | id: args.workspaceId, |
| 147 | − organizationId: null, | |
| 206 | + organizationId, | |
| 148 | 207 | name: args.workspaceId, |
| 149 | 208 | createdByAccountId: args.accountId, |
| 150 | 209 | createdAt: now, |
| @@ -12,7 +12,12 @@ import { · 11 unmodified lines | ||
| 12 | 12 | import { v } from "convex/values"; |
| 13 | 13 | import * as Schema from "effect/Schema"; |
| 14 | 14 | |
| 15 | +import { internal } from "../_generated/api"; | |
| 16 | +import { decryptSecretValue, encryptSecretValue } from "../credential_crypto"; | |
| 15 | 17 | import { |
| 18 | + action, | |
| 19 | + internalAction, | |
| 20 | + internalMutation, | |
| 16 | 21 | internalQuery, |
| 17 | 22 | mutation, |
| 18 | 23 | query, |
| @@ -20,6 +25,8 @@ import { · 1 unmodified line | ||
| 20 | 25 | type QueryCtx, |
| 21 | 26 | } from "../_generated/server"; |
| 22 | 27 | |
| 28 | +const runtimeInternal = internal as any; | |
| 29 | + | |
| 23 | 30 | const decodeSourceCredentialBinding = Schema.decodeUnknownSync( |
| 24 | 31 | SourceCredentialBindingSchema, |
| 25 | 32 | ); |
| @@ -44,12 +51,27 @@ const credentialProviderValidator = v.union( · 18 unmodified lines | ||
| 44 | 51 | v.literal("custom"), |
| 45 | 52 | ); |
| 46 | 53 | |
| 54 | +const credentialSecretProviderValidator = v.literal("local"); | |
| 55 | + | |
| 47 | 56 | const credentialScopeTypeValidator = v.union( |
| 48 | 57 | v.literal("workspace"), |
| 49 | 58 | v.literal("organization"), |
| 50 | 59 | v.literal("account"), |
| 51 | 60 | ); |
| 52 | 61 | |
| 62 | +const sourceCredentialBindingPayloadValidator = v.object({ | |
| 63 | + id: v.optional(v.string()), | |
| 64 | + credentialId: v.string(), | |
| 65 | + scopeType: credentialScopeTypeValidator, | |
| 66 | + sourceKey: v.string(), | |
| 67 | + provider: credentialProviderValidator, | |
| 68 | + secretProvider: v.optional(credentialSecretProviderValidator), | |
| 69 | + secretRef: v.string(), | |
| 70 | + accountId: v.optional(v.union(v.string(), v.null())), | |
| 71 | + additionalHeadersJson: v.optional(v.union(v.string(), v.null())), | |
| 72 | + boundAuthFingerprint: v.optional(v.union(v.string(), v.null())), | |
| 73 | +}); | |
| 74 | + | |
| 53 | 75 | const sortSourceCredentialBindings = ( |
| 54 | 76 | bindings: ReadonlyArray<SourceCredentialBinding>, |
| 55 | 77 | ): Array<SourceCredentialBinding> => |
| @@ -73,11 +95,11 @@ const resolveWorkspaceOrganizationId = async ( · 17 unmodified lines | ||
| 73 | 95 | .withIndex("by_domainId", (q) => q.eq("id", workspaceId)) |
| 74 | 96 | .unique(); |
| 75 | 97 | |
| 76 | − if (workspace?.organizationId !== null && workspace?.organizationId !== undefined) { | |
| 77 | − return workspace.organizationId; | |
| 98 | + if (!workspace) { | |
| 99 | + throw new Error(`Workspace not found: ${workspaceId}`); | |
| 78 | 100 | } |
| 79 | 101 | |
| 80 | − return `org_${workspaceId}`; | |
| 102 | + return workspace.organizationId; | |
| 81 | 103 | }; |
| 82 | 104 | |
| 83 | 105 | const canAccessSourceCredentialBinding = ( |
| @@ -197,83 +219,162 @@ const selectBestIngestBinding = ( · 113 unmodified lines | ||
| 197 | 219 | return ranked[0]?.binding ?? null; |
| 198 | 220 | }; |
| 199 | 221 | |
| 200 | −export const resolveSourceCredentialHeadersForIngest = internalQuery({ | |
| 222 | +const requireLocalSecretProvider = ( | |
| 223 | + secretProvider: SourceCredentialBinding["secretProvider"], | |
| 224 | +): "local" => { | |
| 225 | + if (secretProvider !== "local") { | |
| 226 | + throw new Error("Convex credentials require secretProvider 'local'"); | |
| 227 | + } | |
| 228 | + | |
| 229 | + return "local"; | |
| 230 | +}; | |
| 231 | + | |
| 232 | +const defaultSecretProvider = (): "local" => "local"; | |
| 233 | + | |
| 234 | +const resolveSecretRefForHeaders = async ( | |
| 235 | + binding: SourceCredentialBinding, | |
| 236 | +): Promise<string> => { | |
| 237 | + requireLocalSecretProvider(binding.secretProvider); | |
| 238 | + return await decryptSecretValue(binding.secretRef); | |
| 239 | +}; | |
| 240 | + | |
| 241 | +const resolveIngestSelection = async ( | |
| 242 | + ctx: QueryCtx, | |
| 201 | 243 | args: { |
| 202 | − workspaceId: v.string(), | |
| 203 | − sourceId: v.string(), | |
| 204 | − sourceName: v.string(), | |
| 205 | − sourceEndpoint: v.string(), | |
| 244 | + workspaceId: string; | |
| 245 | + sourceId: string; | |
| 246 | + sourceName: string; | |
| 247 | + sourceEndpoint: string; | |
| 206 | 248 | }, |
| 207 | − handler: async (ctx, args): Promise<{ | |
| 208 | − headers: Record<string, string>; | |
| 209 | − }> => { | |
| 210 | − const organizationId = await resolveWorkspaceOrganizationId(ctx, args.workspaceId); | |
| 211 | − const sourceKeys = sourceKeyCandidatesForIngest({ | |
| 212 | − sourceId: args.sourceId, | |
| 213 | − sourceName: args.sourceName, | |
| 214 | − sourceEndpoint: args.sourceEndpoint, | |
| 215 | − }); | |
| 216 | − | |
| 217 | − const candidateRows = await Promise.all( | |
| 218 | − sourceKeys.map((sourceKey) => | |
| 219 | − ctx.db | |
| 220 | − .query("sourceCredentialBindings") | |
| 221 | − .withIndex("by_sourceKey", (q) => q.eq("sourceKey", sourceKey)) | |
| 222 | − .collect() | |
| 223 | − .then((rows) => | |
| 224 | − rows.map((row) => ({ | |
| 225 | − binding: toSourceCredentialBinding(row as unknown as Record<string, unknown>), | |
| 226 | − sourceKey, | |
| 227 | − })), | |
| 228 | − ), | |
| 229 | − ), | |
| 230 | − ); | |
| 249 | +): Promise<{ | |
| 250 | + binding: SourceCredentialBinding | null; | |
| 251 | + oauthAccessToken: string | null; | |
| 252 | +}> => { | |
| 253 | + const organizationId = await resolveWorkspaceOrganizationId(ctx, args.workspaceId); | |
| 254 | + const sourceKeys = sourceKeyCandidatesForIngest({ | |
| 255 | + sourceId: args.sourceId, | |
| 256 | + sourceName: args.sourceName, | |
| 257 | + sourceEndpoint: args.sourceEndpoint, | |
| 258 | + }); | |
| 231 | 259 | |
| 232 | − const flattened = candidateRows.flat(); | |
| 233 | − const dedupedById = new Map<string, { binding: SourceCredentialBinding; sourceKey: string }>(); | |
| 234 | − for (const candidate of flattened) { | |
| 235 | − if (!dedupedById.has(candidate.binding.id)) { | |
| 236 | − dedupedById.set(candidate.binding.id, candidate); | |
| 237 | − } | |
| 260 | + const candidateRows = await Promise.all( | |
| 261 | + sourceKeys.map((sourceKey) => | |
| 262 | + ctx.db | |
| 263 | + .query("sourceCredentialBindings") | |
| 264 | + .withIndex("by_sourceKey", (q) => q.eq("sourceKey", sourceKey)) | |
| 265 | + .collect() | |
| 266 | + .then((rows) => | |
| 267 | + rows.map((row) => ({ | |
| 268 | + binding: toSourceCredentialBinding(row as unknown as Record<string, unknown>), | |
| 269 | + sourceKey, | |
| 270 | + })), | |
| 271 | + ), | |
| 272 | + ), | |
| 273 | + ); | |
| 274 | + | |
| 275 | + const flattened = candidateRows.flat(); | |
| 276 | + const dedupedById = new Map<string, { binding: SourceCredentialBinding; sourceKey: string }>(); | |
| 277 | + for (const candidate of flattened) { | |
| 278 | + if (!dedupedById.has(candidate.binding.id)) { | |
| 279 | + dedupedById.set(candidate.binding.id, candidate); | |
| 238 | 280 | } |
| 281 | + } | |
| 239 | 282 | |
| 240 | − const sourceKeyRankByKey = new Map<string, number>(); | |
| 241 | − sourceKeys.forEach((sourceKey, index) => { | |
| 242 | − sourceKeyRankByKey.set(sourceKey, sourceKeys.length - index); | |
| 243 | − }); | |
| 283 | + const sourceKeyRankByKey = new Map<string, number>(); | |
| 284 | + sourceKeys.forEach((sourceKey, index) => { | |
| 285 | + sourceKeyRankByKey.set(sourceKey, sourceKeys.length - index); | |
| 286 | + }); | |
| 244 | 287 | |
| 245 | − const binding = selectBestIngestBinding( | |
| 246 | − [...dedupedById.values()].map((candidate) => ({ | |
| 247 | − binding: candidate.binding, | |
| 248 | − sourceKeyRank: sourceKeyRankByKey.get(candidate.sourceKey) ?? 0, | |
| 249 | − })), | |
| 250 | − { | |
| 288 | + const binding = selectBestIngestBinding( | |
| 289 | + [...dedupedById.values()].map((candidate) => ({ | |
| 290 | + binding: candidate.binding, | |
| 291 | + sourceKeyRank: sourceKeyRankByKey.get(candidate.sourceKey) ?? 0, | |
| 292 | + })), | |
| 293 | + { | |
| 294 | + workspaceId: args.workspaceId, | |
| 295 | + organizationId, | |
| 296 | + }, | |
| 297 | + ); | |
| 298 | + | |
| 299 | + if (!binding || !canAccessSourceCredentialBinding(binding, { workspaceId: args.workspaceId, organizationId })) { | |
| 300 | + return { | |
| 301 | + binding: null, | |
| 302 | + oauthAccessToken: null, | |
| 303 | + }; | |
| 304 | + } | |
| 305 | + | |
| 306 | + const oauthTokens = binding.provider === "oauth2" | |
| 307 | + ? (await ctx.db | |
| 308 | + .query("oauthTokens") | |
| 309 | + .withIndex("by_sourceId", (q) => q.eq("sourceId", args.sourceId)) | |
| 310 | + .collect()).map((row) => toOAuthToken(row as unknown as Record<string, unknown>)) | |
| 311 | + : []; | |
| 312 | + | |
| 313 | + const oauthAccessToken = binding.provider === "oauth2" | |
| 314 | + ? selectOAuthAccessToken(oauthTokens, { | |
| 251 | 315 | workspaceId: args.workspaceId, |
| 252 | 316 | organizationId, |
| 253 | − }, | |
| 254 | − ); | |
| 317 | + accountId: null, | |
| 318 | + sourceKey: binding.sourceKey, | |
| 319 | + }, args.sourceId) | |
| 320 | + : null; | |
| 321 | + | |
| 322 | + return { | |
| 323 | + binding, | |
| 324 | + oauthAccessToken, | |
| 325 | + }; | |
| 326 | +}; | |
| 255 | 327 | |
| 256 | − if (!binding || !canAccessSourceCredentialBinding(binding, { workspaceId: args.workspaceId, organizationId })) { | |
| 257 | − return { headers: {} }; | |
| 258 | − } | |
| 328 | +const withDecryptedSecret = async ( | |
| 329 | + binding: SourceCredentialBinding, | |
| 330 | +): Promise<SourceCredentialBinding> => { | |
| 331 | + const secretRef = await resolveSecretRefForHeaders(binding); | |
| 332 | + return { | |
| 333 | + ...binding, | |
| 334 | + secretProvider: "local", | |
| 335 | + secretRef, | |
| 336 | + }; | |
| 337 | +}; | |
| 259 | 338 | |
| 260 | − const oauthTokens = binding.provider === "oauth2" | |
| 261 | − ? (await ctx.db | |
| 262 | − .query("oauthTokens") | |
| 263 | − .withIndex("by_sourceId", (q) => q.eq("sourceId", args.sourceId)) | |
| 264 | − .collect()).map((row) => toOAuthToken(row as unknown as Record<string, unknown>)) | |
| 265 | − : []; | |
| 339 | +export const resolveSourceCredentialSelectionForIngest = internalQuery({ | |
| 340 | + args: { | |
| 341 | + workspaceId: v.string(), | |
| 342 | + sourceId: v.string(), | |
| 343 | + sourceName: v.string(), | |
| 344 | + sourceEndpoint: v.string(), | |
| 345 | + }, | |
| 346 | + handler: async (ctx, args) => resolveIngestSelection(ctx, args), | |
| 347 | +}); | |
| 266 | 348 | |
| 267 | − const oauthAccessToken = binding.provider === "oauth2" | |
| 268 | − ? selectOAuthAccessToken(oauthTokens, { | |
| 269 | − workspaceId: args.workspaceId, | |
| 270 | − organizationId, | |
| 271 | − accountId: null, | |
| 272 | − sourceKey: binding.sourceKey, | |
| 273 | − }, args.sourceId) | |
| 274 | − : null; | |
| 349 | +export const resolveSourceCredentialHeadersForIngest = internalAction({ | |
| 350 | + args: { | |
| 351 | + workspaceId: v.string(), | |
| 352 | + sourceId: v.string(), | |
| 353 | + sourceName: v.string(), | |
| 354 | + sourceEndpoint: v.string(), | |
| 355 | + }, | |
| 356 | + handler: async (ctx, args): Promise<{ | |
| 357 | + headers: Record<string, string>; | |
| 358 | + }> => { | |
| 359 | + const selected = await ctx.runQuery( | |
| 360 | + runtimeInternal.control_plane.credentials.resolveSourceCredentialSelectionForIngest, | |
| 361 | + args, | |
| 362 | + ) as { | |
| 363 | + binding: SourceCredentialBinding | null; | |
| 364 | + oauthAccessToken: string | null; | |
| 365 | + }; | |
| 366 | + | |
| 367 | + if (!selected.binding) { | |
| 368 | + return { | |
| 369 | + headers: {}, | |
| 370 | + }; | |
| 371 | + } | |
| 275 | 372 | |
| 276 | − const headers = buildCredentialHeaders(binding, { oauthAccessToken }); | |
| 373 | + const decrypted = await withDecryptedSecret(selected.binding); | |
| 374 | + | |
| 375 | + const headers = buildCredentialHeaders(decrypted, { | |
| 376 | + oauthAccessToken: selected.oauthAccessToken, | |
| 377 | + }); | |
| 277 | 378 | |
| 278 | 379 | return { headers }; |
| 279 | 380 | }, |
| @@ -311,24 +412,18 @@ export const listCredentialBindings = query({ · 31 unmodified lines | ||
| 311 | 412 | new Map(bindings.map((binding) => [binding.id, binding])).values(), |
| 312 | 413 | ); |
| 313 | 414 | |
| 314 | − return sortSourceCredentialBindings(uniqueBindings); | |
| 415 | + const decryptedBindings = await Promise.all( | |
| 416 | + uniqueBindings.map((binding) => withDecryptedSecret(binding)), | |
| 417 | + ); | |
| 418 | + | |
| 419 | + return sortSourceCredentialBindings(decryptedBindings); | |
| 315 | 420 | }, |
| 316 | 421 | }); |
| 317 | 422 | |
| 318 | −export const upsertCredentialBinding = mutation({ | |
| 423 | +export const upsertCredentialBindingRecord = internalMutation({ | |
| 319 | 424 | args: { |
| 320 | 425 | workspaceId: v.string(), |
| 321 | − payload: v.object({ | |
| 322 | − id: v.optional(v.string()), | |
| 323 | − credentialId: v.string(), | |
| 324 | − scopeType: credentialScopeTypeValidator, | |
| 325 | − sourceKey: v.string(), | |
| 326 | − provider: credentialProviderValidator, | |
| 327 | − secretRef: v.string(), | |
| 328 | − accountId: v.optional(v.union(v.string(), v.null())), | |
| 329 | − additionalHeadersJson: v.optional(v.union(v.string(), v.null())), | |
| 330 | − boundAuthFingerprint: v.optional(v.union(v.string(), v.null())), | |
| 331 | − }), | |
| 426 | + payload: sourceCredentialBindingPayloadValidator, | |
| 332 | 427 | }, |
| 333 | 428 | handler: async (ctx, args): Promise<SourceCredentialBinding> => { |
| 334 | 429 | const payload = args.payload as UpsertCredentialBindingPayload; |
| @@ -360,6 +455,12 @@ export const upsertCredentialBinding = mutation({ · 25 unmodified lines | ||
| 360 | 455 | throw new Error(`Credential binding not found: ${bindingId}`); |
| 361 | 456 | } |
| 362 | 457 | |
| 458 | + const secretProvider = requireLocalSecretProvider( | |
| 459 | + payload.secretProvider | |
| 460 | + ?? existingBinding?.secretProvider | |
| 461 | + ?? defaultSecretProvider(), | |
| 462 | + ); | |
| 463 | + | |
| 363 | 464 | const nextBinding = decodeSourceCredentialBinding({ |
| 364 | 465 | id: bindingId, |
| 365 | 466 | credentialId: payload.credentialId, |
| @@ -369,6 +470,7 @@ export const upsertCredentialBinding = mutation({ · 3 unmodified lines | ||
| 369 | 470 | scopeType: payload.scopeType, |
| 370 | 471 | sourceKey: payload.sourceKey, |
| 371 | 472 | provider: payload.provider, |
| 473 | + secretProvider, | |
| 372 | 474 | secretRef: payload.secretRef, |
| 373 | 475 | additionalHeadersJson: payload.additionalHeadersJson ?? null, |
| 374 | 476 | boundAuthFingerprint: payload.boundAuthFingerprint ?? null, |
| @@ -386,6 +488,40 @@ export const upsertCredentialBinding = mutation({ · 11 unmodified lines | ||
| 386 | 488 | }, |
| 387 | 489 | }); |
| 388 | 490 | |
| 491 | +export const upsertCredentialBinding = action({ | |
| 492 | + args: { | |
| 493 | + workspaceId: v.string(), | |
| 494 | + payload: sourceCredentialBindingPayloadValidator, | |
| 495 | + }, | |
| 496 | + handler: async (ctx, args): Promise<SourceCredentialBinding> => { | |
| 497 | + const payload = args.payload as UpsertCredentialBindingPayload; | |
| 498 | + const requestedSecretRef = payload.secretRef.trim(); | |
| 499 | + if (requestedSecretRef.length === 0) { | |
| 500 | + throw new Error("Credential secret is required"); | |
| 501 | + } | |
| 502 | + | |
| 503 | + const encryptedSecretRef = await encryptSecretValue(requestedSecretRef); | |
| 504 | + | |
| 505 | + const written = await ctx.runMutation( | |
| 506 | + runtimeInternal.control_plane.credentials.upsertCredentialBindingRecord, | |
| 507 | + { | |
| 508 | + workspaceId: args.workspaceId, | |
| 509 | + payload: { | |
| 510 | + ...payload, | |
| 511 | + secretProvider: "local", | |
| 512 | + secretRef: encryptedSecretRef, | |
| 513 | + }, | |
| 514 | + }, | |
| 515 | + ) as SourceCredentialBinding; | |
| 516 | + | |
| 517 | + return { | |
| 518 | + ...written, | |
| 519 | + secretProvider: "local", | |
| 520 | + secretRef: requestedSecretRef, | |
| 521 | + }; | |
| 522 | + }, | |
| 523 | +}); | |
| 524 | + | |
| 389 | 525 | export const removeCredentialBinding = mutation({ |
| 390 | 526 | args: { |
| 391 | 527 | workspaceId: v.string(), |
| @@ -1049,7 +1049,7 @@ const ingestGraphqlSource = ( · 1048 unmodified lines | ||
| 1049 | 1049 | headers: Record<string, string>; |
| 1050 | 1050 | }>( |
| 1051 | 1051 | () => |
| 1052 | − ctx.runQuery(runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, { | |
| 1052 | + ctx.runAction(runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, { | |
| 1053 | 1053 | workspaceId: source.workspaceId, |
| 1054 | 1054 | sourceId: source.id, |
| 1055 | 1055 | sourceName: source.name, |
| @@ -1206,7 +1206,7 @@ const ingestMcpSource = ( · 150 unmodified lines | ||
| 1206 | 1206 | headers: Record<string, string>; |
| 1207 | 1207 | }>( |
| 1208 | 1208 | () => |
| 1209 | − ctx.runQuery(runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, { | |
| 1209 | + ctx.runAction(runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, { | |
| 1210 | 1210 | workspaceId: source.workspaceId, |
| 1211 | 1211 | sourceId: source.id, |
| 1212 | 1212 | sourceName: source.name, |
| @@ -1,5 +1,9 @@ | ||
| 1 | 1 | import { type UpsertOrganizationPayload } from "@executor-v2/management-api"; |
| 2 | −import { OrganizationSchema, type Organization } from "@executor-v2/schema"; | |
| 2 | +import { | |
| 3 | + OrganizationSchema, | |
| 4 | + type Organization, | |
| 5 | + type OrganizationMembership, | |
| 6 | +} from "@executor-v2/schema"; | |
| 3 | 7 | import { v } from "convex/values"; |
| 4 | 8 | import * as Schema from "effect/Schema"; |
| 5 | 9 | |
| @@ -55,6 +59,7 @@ export const upsertOrganization = mutation({ · 49 unmodified lines | ||
| 55 | 59 | slug: v.string(), |
| 56 | 60 | name: v.string(), |
| 57 | 61 | status: v.optional(organizationStatusValidator), |
| 62 | + createdByAccountId: v.optional(v.union(v.string(), v.null())), | |
| 58 | 63 | }), |
| 59 | 64 | }, |
| 60 | 65 | handler: async (ctx, args): Promise<Organization> => { |
| @@ -72,7 +77,10 @@ export const upsertOrganization = mutation({ · 11 unmodified lines | ||
| 72 | 77 | slug: payload.slug, |
| 73 | 78 | name: payload.name, |
| 74 | 79 | status: payload.status ?? existing?.status ?? "active", |
| 75 | − createdByAccountId: existing?.createdByAccountId ?? null, | |
| 80 | + createdByAccountId: | |
| 81 | + existing?.createdByAccountId | |
| 82 | + ?? payload.createdByAccountId | |
| 83 | + ?? null, | |
| 76 | 84 | createdAt: existing?.createdAt ?? now, |
| 77 | 85 | updatedAt: now, |
| 78 | 86 | }); |
| @@ -81,6 +89,34 @@ export const upsertOrganization = mutation({ · 2 unmodified lines | ||
| 81 | 89 | await ctx.db.patch(existing._id, nextOrganization); |
| 82 | 90 | } else { |
| 83 | 91 | await ctx.db.insert("organizations", nextOrganization); |
| 92 | + | |
| 93 | + if (nextOrganization.createdByAccountId !== null) { | |
| 94 | + const existingMembership = await ctx.db | |
| 95 | + .query("organizationMemberships") | |
| 96 | + .withIndex("by_organizationId_accountId", (q) => | |
| 97 | + q | |
| 98 | + .eq("organizationId", nextOrganization.id) | |
| 99 | + .eq("accountId", nextOrganization.createdByAccountId as string) | |
| 100 | + ) | |
| 101 | + .first(); | |
| 102 | + | |
| 103 | + if (!existingMembership) { | |
| 104 | + const membership: OrganizationMembership = { | |
| 105 | + id: `org_member_${crypto.randomUUID()}` as OrganizationMembership["id"], | |
| 106 | + organizationId: nextOrganization.id, | |
| 107 | + accountId: nextOrganization.createdByAccountId, | |
| 108 | + role: "owner", | |
| 109 | + status: "active", | |
| 110 | + billable: false, | |
| 111 | + invitedByAccountId: null, | |
| 112 | + joinedAt: now, | |
| 113 | + createdAt: now, | |
| 114 | + updatedAt: now, | |
| 115 | + }; | |
| 116 | + | |
| 117 | + await ctx.db.insert("organizationMemberships", membership); | |
| 118 | + } | |
| 119 | + } | |
| 84 | 120 | } |
| 85 | 121 | |
| 86 | 122 | return nextOrganization; |
| @@ -50,7 +50,7 @@ export const makeConvexControlPlaneService = ( · 49 unmodified lines | ||
| 50 | 50 | upsertCredentialBinding: (input) => |
| 51 | 51 | Effect.tryPromise({ |
| 52 | 52 | try: () => |
| 53 | − ctx.runMutation(api.controlPlane.upsertCredentialBinding, { | |
| 53 | + ctx.runAction(api.controlPlane.upsertCredentialBinding, { | |
| 54 | 54 | workspaceId: input.workspaceId, |
| 55 | 55 | payload: input.payload, |
| 56 | 56 | }), |
| @@ -119,11 +119,11 @@ const resolveWorkspaceOrganizationId = async ( · 118 unmodified lines | ||
| 119 | 119 | .withIndex("by_domainId", (q) => q.eq("id", workspaceId)) |
| 120 | 120 | .unique(); |
| 121 | 121 | |
| 122 | − if (workspace?.organizationId !== null && workspace?.organizationId !== undefined) { | |
| 123 | − return workspace.organizationId; | |
| 122 | + if (!workspace) { | |
| 123 | + throw new Error(`Workspace not found: ${workspaceId}`); | |
| 124 | 124 | } |
| 125 | 125 | |
| 126 | − return `org_${workspaceId}`; | |
| 126 | + return workspace.organizationId; | |
| 127 | 127 | }; |
| 128 | 128 | |
| 129 | 129 | const canAccessStorageInstance = ( |
| @@ -44,7 +44,7 @@ export const upsertWorkspace = mutation({ · 43 unmodified lines | ||
| 44 | 44 | args: { |
| 45 | 45 | payload: v.object({ |
| 46 | 46 | id: v.optional(v.string()), |
| 47 | − organizationId: v.optional(v.union(v.string(), v.null())), | |
| 47 | + organizationId: v.string(), | |
| 48 | 48 | name: v.string(), |
| 49 | 49 | }), |
| 50 | 50 | }, |
| @@ -60,10 +60,7 @@ export const upsertWorkspace = mutation({ · 9 unmodified lines | ||
| 60 | 60 | |
| 61 | 61 | const nextWorkspace = decodeWorkspace({ |
| 62 | 62 | id: workspaceId, |
| 63 | − organizationId: | |
| 64 | − payload.organizationId !== undefined | |
| 65 | − ? payload.organizationId | |
| 66 | − : existing?.organizationId ?? null, | |
| 63 | + organizationId: payload.organizationId, | |
| 67 | 64 | name: payload.name, |
| 68 | 65 | createdByAccountId: existing?.createdByAccountId ?? null, |
| 69 | 66 | createdAt: existing?.createdAt ?? now, |
| @@ -0,0 +1,102 @@ | ||
| 1 | +const encryptedPrefix = "enc:v1:"; | |
| 2 | + | |
| 3 | +const encoder = new TextEncoder(); | |
| 4 | +const decoder = new TextDecoder(); | |
| 5 | + | |
| 6 | +const bytesToBase64 = (bytes: Uint8Array): string => { | |
| 7 | + let binary = ""; | |
| 8 | + for (const byte of bytes) { | |
| 9 | + binary += String.fromCharCode(byte); | |
| 10 | + } | |
| 11 | + return btoa(binary); | |
| 12 | +}; | |
| 13 | + | |
| 14 | +const base64ToBytes = (base64: string): Uint8Array => { | |
| 15 | + const binary = atob(base64); | |
| 16 | + const bytes = new Uint8Array(binary.length); | |
| 17 | + for (let i = 0; i < binary.length; i += 1) { | |
| 18 | + bytes[i] = binary.charCodeAt(i); | |
| 19 | + } | |
| 20 | + return bytes; | |
| 21 | +}; | |
| 22 | + | |
| 23 | +const resolveEncryptionPassphrase = (): string => { | |
| 24 | + const passphrase = process.env.CREDENTIAL_ENCRYPTION_KEY?.trim() ?? ""; | |
| 25 | + if (passphrase.length === 0) { | |
| 26 | + throw new Error("Encrypted credential storage requires CREDENTIAL_ENCRYPTION_KEY"); | |
| 27 | + } | |
| 28 | + | |
| 29 | + return passphrase; | |
| 30 | +}; | |
| 31 | + | |
| 32 | +const deriveAesKey = async (): Promise<CryptoKey> => { | |
| 33 | + const passphraseBytes = encoder.encode(resolveEncryptionPassphrase()); | |
| 34 | + const hashBuffer = await crypto.subtle.digest("SHA-256", passphraseBytes); | |
| 35 | + return await crypto.subtle.importKey( | |
| 36 | + "raw", | |
| 37 | + hashBuffer, | |
| 38 | + { | |
| 39 | + name: "AES-GCM", | |
| 40 | + }, | |
| 41 | + false, | |
| 42 | + ["encrypt", "decrypt"], | |
| 43 | + ); | |
| 44 | +}; | |
| 45 | + | |
| 46 | +const parseEncryptedValue = (value: string): { iv: Uint8Array; cipher: Uint8Array } | null => { | |
| 47 | + if (!value.startsWith(encryptedPrefix)) { | |
| 48 | + return null; | |
| 49 | + } | |
| 50 | + | |
| 51 | + const payload = value.slice(encryptedPrefix.length); | |
| 52 | + const parts = payload.split(":"); | |
| 53 | + if (parts.length !== 2) { | |
| 54 | + return null; | |
| 55 | + } | |
| 56 | + | |
| 57 | + try { | |
| 58 | + return { | |
| 59 | + iv: base64ToBytes(parts[0] ?? ""), | |
| 60 | + cipher: base64ToBytes(parts[1] ?? ""), | |
| 61 | + }; | |
| 62 | + } catch { | |
| 63 | + return null; | |
| 64 | + } | |
| 65 | +}; | |
| 66 | + | |
| 67 | +export const isEncryptedSecret = (value: string): boolean => | |
| 68 | + value.startsWith(encryptedPrefix); | |
| 69 | + | |
| 70 | +export const encryptSecretValue = async (plainText: string): Promise<string> => { | |
| 71 | + const key = await deriveAesKey(); | |
| 72 | + const iv = crypto.getRandomValues(new Uint8Array(12)); | |
| 73 | + const encrypted = await crypto.subtle.encrypt( | |
| 74 | + { | |
| 75 | + name: "AES-GCM", | |
| 76 | + iv, | |
| 77 | + }, | |
| 78 | + key, | |
| 79 | + encoder.encode(plainText), | |
| 80 | + ); | |
| 81 | + | |
| 82 | + return `${encryptedPrefix}${bytesToBase64(iv)}:${bytesToBase64(new Uint8Array(encrypted))}`; | |
| 83 | +}; | |
| 84 | + | |
| 85 | +export const decryptSecretValue = async (storedValue: string): Promise<string> => { | |
| 86 | + const parsed = parseEncryptedValue(storedValue); | |
| 87 | + if (parsed === null) { | |
| 88 | + throw new Error("Credential secret is not encrypted"); | |
| 89 | + } | |
| 90 | + | |
| 91 | + const key = await deriveAesKey(); | |
| 92 | + const decrypted = await crypto.subtle.decrypt( | |
| 93 | + { | |
| 94 | + name: "AES-GCM", | |
| 95 | + iv: parsed.iv as unknown as BufferSource, | |
| 96 | + }, | |
| 97 | + key, | |
| 98 | + parsed.cipher as unknown as BufferSource, | |
| 99 | + ); | |
| 100 | + | |
| 101 | + return decoder.decode(decrypted); | |
| 102 | +}; | |
| @@ -20,6 +20,7 @@ import * as Schema from "effect/Schema"; · 19 unmodified lines | ||
| 20 | 20 | |
| 21 | 21 | import { api } from "./_generated/api"; |
| 22 | 22 | import { query, type ActionCtx } from "./_generated/server"; |
| 23 | +import { decryptSecretValue } from "./credential_crypto"; | |
| 23 | 24 | |
| 24 | 25 | const decodeSourceCredentialBinding = Schema.decodeUnknownSync( |
| 25 | 26 | SourceCredentialBindingSchema, |
| @@ -114,6 +115,16 @@ const runQueryEffect = <T>( · 88 unmodified lines | ||
| 114 | 115 | ), |
| 115 | 116 | }); |
| 116 | 117 | |
| 118 | +const requireLocalSecretProvider = ( | |
| 119 | + secretProvider: SourceCredentialBinding["secretProvider"], | |
| 120 | +): "local" => { | |
| 121 | + if (secretProvider !== "local") { | |
| 122 | + throw new Error("Convex credentials require secretProvider 'local'"); | |
| 123 | + } | |
| 124 | + | |
| 125 | + return "local"; | |
| 126 | +}; | |
| 127 | + | |
| 117 | 128 | export const createConvexResolveToolCredentials = ( |
| 118 | 129 | ctx: ActionCtx, |
| 119 | 130 | ): ResolveToolCredentials => |
| @@ -160,10 +171,28 @@ export const createConvexResolveToolCredentials = ( · 40 unmodified lines | ||
| 160 | 171 | ) |
| 161 | 172 | : null; |
| 162 | 173 | |
| 174 | + requireLocalSecretProvider(binding.secretProvider); | |
| 175 | + | |
| 176 | + const secretRef = yield* Effect.tryPromise({ | |
| 177 | + try: () => decryptSecretValue(binding.secretRef), | |
| 178 | + catch: (cause) => | |
| 179 | + toCredentialResolverError( | |
| 180 | + "decrypt_credential_secret", | |
| 181 | + "Convex credential decryption failed", | |
| 182 | + String(cause), | |
| 183 | + ), | |
| 184 | + }); | |
| 185 | + | |
| 163 | 186 | return { |
| 164 | − headers: buildCredentialHeaders(binding, { | |
| 165 | − oauthAccessToken, | |
| 166 | − }), | |
| 187 | + headers: buildCredentialHeaders( | |
| 188 | + { | |
| 189 | + ...binding, | |
| 190 | + secretRef, | |
| 191 | + }, | |
| 192 | + { | |
| 193 | + oauthAccessToken, | |
| 194 | + }, | |
| 195 | + ), | |
| 167 | 196 | }; |
| 168 | 197 | }), |
| 169 | 198 | ); |
| @@ -27,15 +27,91 @@ const setup = () => · 26 unmodified lines | ||
| 27 | 27 | "./_generated/api.js": () => import("./_generated/api.js"), |
| 28 | 28 | }); |
| 29 | 29 | |
| 30 | +const ensureWorkspace = async ( | |
| 31 | + t: ReturnType<typeof setup>, | |
| 32 | + workspaceId: string, | |
| 33 | + organizationId: string, | |
| 34 | +): Promise<void> => { | |
| 35 | + await t.mutation(api.controlPlane.upsertWorkspace, { | |
| 36 | + payload: { | |
| 37 | + id: workspaceId, | |
| 38 | + organizationId, | |
| 39 | + name: workspaceId, | |
| 40 | + }, | |
| 41 | + }); | |
| 42 | +}; | |
| 43 | + | |
| 30 | 44 | describe("Convex executor and control-plane", () => { |
| 31 | 45 | it.effect("executes code via executeRunImpl", () => |
| 32 | 46 | Effect.gen(function* () { |
| 33 | − const result = yield* executeRunImpl({ | |
| 34 | − code: "return 6 * 7;", | |
| 35 | − }); | |
| 47 | + const originalEnv = { | |
| 48 | + runUrl: process.env.CLOUDFLARE_SANDBOX_RUN_URL, | |
| 49 | + authToken: process.env.CLOUDFLARE_SANDBOX_AUTH_TOKEN, | |
| 50 | + callbackUrl: process.env.CLOUDFLARE_SANDBOX_CALLBACK_URL, | |
| 51 | + }; | |
| 52 | + const originalFetch = globalThis.fetch; | |
| 36 | 53 | |
| 37 | − expect(result.status).toBe("completed"); | |
| 38 | − expect(result.result).toBe(42); | |
| 54 | + try { | |
| 55 | + process.env.CLOUDFLARE_SANDBOX_RUN_URL = "https://sandbox.local/run"; | |
| 56 | + process.env.CLOUDFLARE_SANDBOX_AUTH_TOKEN = "sandbox-token"; | |
| 57 | + process.env.CLOUDFLARE_SANDBOX_CALLBACK_URL = "https://convex.local/callback"; | |
| 58 | + | |
| 59 | + globalThis.fetch = (async ( | |
| 60 | + input: RequestInfo | URL, | |
| 61 | + init?: RequestInit, | |
| 62 | + ) => { | |
| 63 | + const url = typeof input === "string" ? input : input.toString(); | |
| 64 | + if (url !== "https://sandbox.local/run") { | |
| 65 | + throw new Error(`Unexpected URL: ${url}`); | |
| 66 | + } | |
| 67 | + | |
| 68 | + expect(init?.method).toBe("POST"); | |
| 69 | + const headers = new Headers(init?.headers as HeadersInit | undefined); | |
| 70 | + expect(headers.get("authorization")).toBe( | |
| 71 | + "Bearer sandbox-token", | |
| 72 | + ); | |
| 73 | + | |
| 74 | + return new Response( | |
| 75 | + JSON.stringify({ | |
| 76 | + status: "completed", | |
| 77 | + result: 42, | |
| 78 | + }), | |
| 79 | + { | |
| 80 | + status: 200, | |
| 81 | + headers: { | |
| 82 | + "content-type": "application/json", | |
| 83 | + }, | |
| 84 | + }, | |
| 85 | + ); | |
| 86 | + }) as unknown as typeof fetch; | |
| 87 | + | |
| 88 | + const result = yield* executeRunImpl({ | |
| 89 | + code: "return 6 * 7;", | |
| 90 | + }); | |
| 91 | + | |
| 92 | + expect(result.status).toBe("completed"); | |
| 93 | + expect(result.result).toBe(42); | |
| 94 | + } finally { | |
| 95 | + globalThis.fetch = originalFetch; | |
| 96 | + | |
| 97 | + if (originalEnv.runUrl === undefined) { | |
| 98 | + delete process.env.CLOUDFLARE_SANDBOX_RUN_URL; | |
| 99 | + } else { | |
| 100 | + process.env.CLOUDFLARE_SANDBOX_RUN_URL = originalEnv.runUrl; | |
| 101 | + } | |
| 102 | + | |
| 103 | + if (originalEnv.authToken === undefined) { | |
| 104 | + delete process.env.CLOUDFLARE_SANDBOX_AUTH_TOKEN; | |
| 105 | + } else { | |
| 106 | + process.env.CLOUDFLARE_SANDBOX_AUTH_TOKEN = originalEnv.authToken; | |
| 107 | + } | |
| 108 | + | |
| 109 | + if (originalEnv.callbackUrl === undefined) { | |
| 110 | + delete process.env.CLOUDFLARE_SANDBOX_CALLBACK_URL; | |
| 111 | + } else { | |
| 112 | + process.env.CLOUDFLARE_SANDBOX_CALLBACK_URL = originalEnv.callbackUrl; | |
| 113 | + } | |
| 114 | + } | |
| 39 | 115 | }), |
| 40 | 116 | ); |
| 41 | 117 | |
| @@ -44,7 +120,7 @@ describe("Convex executor and control-plane", () => { · 2 unmodified lines | ||
| 44 | 120 | const t = setup(); |
| 45 | 121 | |
| 46 | 122 | const added = (yield* Effect.tryPromise(() => |
| 47 | − t.action(api.controlPlane.upsertSource, { | |
| 123 | + t.action(api.controlPlane.upsertSource as any, { | |
| 48 | 124 | workspaceId: "ws_1", |
| 49 | 125 | payload: { |
| 50 | 126 | id: "src_1", |
| @@ -106,8 +182,10 @@ describe("Convex executor and control-plane", () => { · 55 unmodified lines | ||
| 106 | 182 | Effect.gen(function* () { |
| 107 | 183 | const t = setup(); |
| 108 | 184 | |
| 185 | + yield* Effect.tryPromise(() => ensureWorkspace(t, "ws_1", "org_1")); | |
| 186 | + | |
| 109 | 187 | const addedCredential = (yield* Effect.tryPromise(() => |
| 110 | − t.mutation(api.controlPlane.upsertCredentialBinding, { | |
| 188 | + t.action(api.controlPlane.upsertCredentialBinding, { | |
| 111 | 189 | workspaceId: "ws_1", |
| 112 | 190 | payload: { |
| 113 | 191 | id: "credential_binding_1", |
| @@ -448,7 +526,7 @@ describe("Convex executor and control-plane", () => { · 334 unmodified lines | ||
| 448 | 526 | }), |
| 449 | 527 | )) as { |
| 450 | 528 | id: string; |
| 451 | − organizationId: string | null; | |
| 529 | + organizationId: string; | |
| 452 | 530 | }; |
| 453 | 531 | |
| 454 | 532 | expect(workspace.id).toBe("ws_1"); |
| @@ -559,6 +637,7 @@ describe("Convex executor and control-plane", () => { · 104 unmodified lines | ||
| 559 | 637 | rows: manifest.tools.map((tool) => ({ |
| 560 | 638 | toolId: tool.toolId, |
| 561 | 639 | protocol: "openapi", |
| 640 | + method: tool.method, | |
| 562 | 641 | path: `weather_api_src_1.${tool.toolId}`, |
| 563 | 642 | name: tool.name, |
| 564 | 643 | description: tool.description, |
| @@ -683,6 +762,7 @@ describe("Convex executor and control-plane", () => { · 118 unmodified lines | ||
| 683 | 762 | { |
| 684 | 763 | toolId: "linear.graphql", |
| 685 | 764 | protocol: "graphql", |
| 765 | + method: "post", | |
| 686 | 766 | path: "linear_api_phql_1.linear.graphql", |
| 687 | 767 | name: "Linear GraphQL", |
| 688 | 768 | description: "Run raw GraphQL queries against Linear", |
| @@ -694,6 +774,7 @@ describe("Convex executor and control-plane", () => { · 5 unmodified lines | ||
| 694 | 774 | { |
| 695 | 775 | toolId: "linear.query.viewer", |
| 696 | 776 | protocol: "graphql", |
| 777 | + method: "post", | |
| 697 | 778 | path: "linear_api_phql_1.linear.query.viewer", |
| 698 | 779 | name: "viewer", |
| 699 | 780 | description: "Current viewer", |
| @@ -811,6 +892,7 @@ describe("Convex executor and control-plane", () => { · 111 unmodified lines | ||
| 811 | 892 | { |
| 812 | 893 | toolId: "deepwiki.mcp.search_docs", |
| 813 | 894 | protocol: "mcp", |
| 895 | + method: "post", | |
| 814 | 896 | path: "deepwiki_mcp_1.deepwiki.mcp.search_docs", |
| 815 | 897 | name: "search_docs", |
| 816 | 898 | description: "Search docs", |
| @@ -863,6 +945,8 @@ describe("Convex executor and control-plane", () => { · 46 unmodified lines | ||
| 863 | 945 | const t = setup(); |
| 864 | 946 | const originalFetch = globalThis.fetch; |
| 865 | 947 | |
| 948 | + yield* Effect.tryPromise(() => ensureWorkspace(t, "ws_auth", "org_auth")); | |
| 949 | + | |
| 866 | 950 | globalThis.fetch = (async () => |
| 867 | 951 | new Response( |
| 868 | 952 | JSON.stringify({ |
| @@ -932,6 +1016,8 @@ describe("Convex executor and control-plane", () => { · 63 unmodified lines | ||
| 932 | 1016 | const t = setup(); |
| 933 | 1017 | const originalFetch = globalThis.fetch; |
| 934 | 1018 | |
| 1019 | + yield* Effect.tryPromise(() => ensureWorkspace(t, "ws_cred", "org_cred")); | |
| 1020 | + | |
| 935 | 1021 | globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { |
| 936 | 1022 | const authHeader = new Headers(init?.headers).get("authorization"); |
| 937 | 1023 | if (authHeader !== "Bearer linear_token") { |
| @@ -1026,7 +1112,7 @@ describe("Convex executor and control-plane", () => { · 88 unmodified lines | ||
| 1026 | 1112 | const now = Date.now(); |
| 1027 | 1113 | |
| 1028 | 1114 | yield* Effect.tryPromise(() => |
| 1029 | − t.mutation(api.controlPlane.upsertCredentialBinding, { | |
| 1115 | + t.action(api.controlPlane.upsertCredentialBinding, { | |
| 1030 | 1116 | workspaceId: "ws_cred", |
| 1031 | 1117 | payload: { |
| 1032 | 1118 | id: "credential_binding_linear", |
| @@ -1102,6 +1188,10 @@ describe("Convex executor and control-plane", () => { · 69 unmodified lines | ||
| 1102 | 1188 | const t = setup(); |
| 1103 | 1189 | const originalFetch = globalThis.fetch; |
| 1104 | 1190 | |
| 1191 | + yield* Effect.tryPromise(() => | |
| 1192 | + ensureWorkspace(t, "ws_mcp_ingest", "org_mcp_ingest") | |
| 1193 | + ); | |
| 1194 | + | |
| 1105 | 1195 | globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { |
| 1106 | 1196 | const authHeader = new Headers(init?.headers).get("authorization"); |
| 1107 | 1197 | if (authHeader !== "Bearer mcp_token") { |
| @@ -1215,7 +1305,7 @@ describe("Convex executor and control-plane", () => { · 107 unmodified lines | ||
| 1215 | 1305 | const now = Date.now(); |
| 1216 | 1306 | |
| 1217 | 1307 | yield* Effect.tryPromise(() => |
| 1218 | − t.mutation(api.controlPlane.upsertCredentialBinding, { | |
| 1308 | + t.action(api.controlPlane.upsertCredentialBinding, { | |
| 1219 | 1309 | workspaceId: "ws_mcp_ingest", |
| 1220 | 1310 | payload: { |
| 1221 | 1311 | id: "credential_binding_mcp", |
| @@ -71,7 +71,7 @@ const hasWorkspaceAccess = async ( · 70 unmodified lines | ||
| 71 | 71 | runtimeInternal.control_plane.actor.getWorkspaceForActor, |
| 72 | 72 | { workspaceId }, |
| 73 | 73 | )) as { |
| 74 | − organizationId: string | null; | |
| 74 | + organizationId: string; | |
| 75 | 75 | createdByAccountId: string | null; |
| 76 | 76 | } | null; |
| 77 | 77 | |
| @@ -83,10 +83,6 @@ const hasWorkspaceAccess = async ( · 5 unmodified lines | ||
| 83 | 83 | return true; |
| 84 | 84 | } |
| 85 | 85 | |
| 86 | − if (!workspace.organizationId) { | |
| 87 | − return false; | |
| 88 | − } | |
| 89 | − | |
| 90 | 86 | const memberships = (await ctx.runQuery( |
| 91 | 87 | runtimeInternal.control_plane.actor.listOrganizationMembershipsForActor, |
| 92 | 88 | { accountId }, |
| @@ -3,8 +3,8 @@ import { · 2 unmodified lines | ||
| 3 | 3 | type RuntimeExecuteError, |
| 4 | 4 | type RuntimeExecuteInput, |
| 5 | 5 | } from "@executor-v2/engine"; |
| 6 | −import { makeLocalInProcessRuntimeAdapter } from "@executor-v2/runtime-local-inproc"; | |
| 6 | +import { makeCloudflareWorkerLoaderRuntimeAdapter } from "@executor-v2/runtime-cloudflare-worker-loader"; | |
| 7 | 7 | |
| 8 | 8 | export type { RuntimeAdapter, RuntimeExecuteError, RuntimeExecuteInput }; |
| 9 | 9 | |
| 10 | −export { makeLocalInProcessRuntimeAdapter }; | |
| 10 | +export { makeCloudflareWorkerLoaderRuntimeAdapter }; | |
| @@ -8,13 +8,9 @@ import { · 7 unmodified lines | ||
| 8 | 8 | makeRuntimeAdapterRegistry, |
| 9 | 9 | type RuntimeExecuteError, |
| 10 | 10 | } from "@executor-v2/engine"; |
| 11 | −import { makeLocalInProcessRuntimeAdapter } from "@executor-v2/runtime-local-inproc"; | |
| 11 | +import { makeCloudflareWorkerLoaderRuntimeAdapter } from "@executor-v2/runtime-cloudflare-worker-loader"; | |
| 12 | 12 | import * as Effect from "effect/Effect"; |
| 13 | 13 | |
| 14 | −const convexRuntimeAdapter = makeLocalInProcessRuntimeAdapter(); | |
| 15 | − | |
| 16 | −const runtimeAdapters = makeRuntimeAdapterRegistry([convexRuntimeAdapter]); | |
| 17 | − | |
| 18 | 14 | export type ConvexRuntimeExecutionPortOptions = { |
| 19 | 15 | toolRegistry?: ToolRegistry; |
| 20 | 16 | }; |
| @@ -22,6 +18,9 @@ export type ConvexRuntimeExecutionPortOptions = { · 1 unmodified line | ||
| 22 | 18 | export const createExecuteRuntimeRunInConvex = ( |
| 23 | 19 | options: ConvexRuntimeExecutionPortOptions = {}, |
| 24 | 20 | ): ExecuteRuntimeRun => { |
| 21 | + const convexRuntimeAdapter = makeCloudflareWorkerLoaderRuntimeAdapter(); | |
| 22 | + const runtimeAdapters = makeRuntimeAdapterRegistry([convexRuntimeAdapter]); | |
| 23 | + | |
| 25 | 24 | const toolRegistry = |
| 26 | 25 | options.toolRegistry ?? |
| 27 | 26 | createStaticToolRegistry({ |
| @@ -46,8 +45,9 @@ export const createExecuteRuntimeRunInConvex = ( · 18 unmodified lines | ||
| 46 | 45 | if (!isAvailable) { |
| 47 | 46 | return yield* new RuntimeExecutionPortError({ |
| 48 | 47 | operation: "runtime_available", |
| 49 | − message: `Runtime '${convexRuntimeAdapter.kind}' is not available in this convex process.`, | |
| 50 | − details: null, | |
| 48 | + message: `Runtime '${convexRuntimeAdapter.kind}' is not configured in this convex process.`, | |
| 49 | + details: | |
| 50 | + "Set CLOUDFLARE_SANDBOX_RUN_URL, CLOUDFLARE_SANDBOX_AUTH_TOKEN, and CLOUDFLARE_SANDBOX_CALLBACK_URL.", | |
| 51 | 51 | }); |
| 52 | 52 | } |
| 53 | 53 | |
| @@ -268,7 +268,7 @@ const resolveSourceCredentialHeadersForInvocation = async ( · 267 unmodified lines | ||
| 268 | 268 | source: Source, |
| 269 | 269 | ): Promise<Record<string, string>> => { |
| 270 | 270 | try { |
| 271 | − const resolved = (await ctx.runQuery( | |
| 271 | + const resolved = (await ctx.runAction( | |
| 272 | 272 | runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, |
| 273 | 273 | { |
| 274 | 274 | workspaceId: source.workspaceId, |
| @@ -3,8 +3,8 @@ · 2 unmodified lines | ||
| 3 | 3 | "private": true, |
| 4 | 4 | "type": "module", |
| 5 | 5 | "scripts": { |
| 6 | − "dev": "bunx convex dev", | |
| 7 | − "test": "bunx vitest run --no-watch convex/*.test.ts", | |
| 6 | + "dev": "CREDENTIAL_ENCRYPTION_KEY=dev-credential-encryption-key bunx convex dev", | |
| 7 | + "test": "CREDENTIAL_ENCRYPTION_KEY=test-credential-encryption-key bunx vitest run --no-watch convex/*.test.ts", | |
| 8 | 8 | "typecheck": "bunx tsc --noEmit -p tsconfig.json", |
| 9 | 9 | "convex:codegen": "bunx convex codegen" |
| 10 | 10 | }, |
| @@ -16,7 +16,7 @@ · 5 unmodified lines | ||
| 16 | 16 | "@executor-v2/management-api": "workspace:*", |
| 17 | 17 | "@executor-v2/mcp-gateway": "workspace:*", |
| 18 | 18 | "@executor-v2/persistence-ports": "workspace:*", |
| 19 | − "@executor-v2/runtime-local-inproc": "workspace:*", | |
| 19 | + "@executor-v2/runtime-cloudflare-worker-loader": "workspace:*", | |
| 20 | 20 | "@executor-v2/schema": "workspace:*", |
| 21 | 21 | "@executor-v2/sdk": "workspace:*", |
| 22 | 22 | "convex": "catalog:", |
| @@ -41,13 +41,12 @@ const resolveWorkspaceOrganizationId = ( · 40 unmodified lines | ||
| 41 | 41 | workspaceId: WorkspaceId, |
| 42 | 42 | ): OrganizationId => { |
| 43 | 43 | const workspace = snapshot.workspaces.find((item) => item.id === workspaceId); |
| 44 | − const organizationId = workspace?.organizationId; | |
| 45 | 44 | |
| 46 | − if (organizationId !== null && organizationId !== undefined) { | |
| 47 | − return organizationId; | |
| 45 | + if (!workspace) { | |
| 46 | + throw new Error(`Workspace not found: ${workspaceId}`); | |
| 48 | 47 | } |
| 49 | 48 | |
| 50 | − return (`org_${workspaceId}`) as OrganizationId; | |
| 49 | + return workspace.organizationId; | |
| 51 | 50 | }; |
| 52 | 51 | |
| 53 | 52 | const sortCredentialBindings = ( |
| @@ -200,6 +199,10 @@ export const createPmCredentialsService = ( · 146 unmodified lines | ||
| 200 | 199 | scopeType: input.payload.scopeType, |
| 201 | 200 | sourceKey: input.payload.sourceKey, |
| 202 | 201 | provider: input.payload.provider, |
| 202 | + secretProvider: | |
| 203 | + input.payload.secretProvider | |
| 204 | + ?? existing?.secretProvider | |
| 205 | + ?? "local", | |
| 203 | 206 | secretRef: input.payload.secretRef, |
| 204 | 207 | additionalHeadersJson: input.payload.additionalHeadersJson ?? null, |
| 205 | 208 | boundAuthFingerprint: input.payload.boundAuthFingerprint ?? null, |
| @@ -10,6 +10,8 @@ import { · 9 unmodified lines | ||
| 10 | 10 | } from "@executor-v2/management-api"; |
| 11 | 11 | import { |
| 12 | 12 | RuntimeAdapterError, |
| 13 | + makeGraphqlToolProvider, | |
| 14 | + makeMcpToolProvider, | |
| 13 | 15 | createRunExecutor, |
| 14 | 16 | createSourceToolRegistry, |
| 15 | 17 | defaultExecuteToolExposureMode, |
| @@ -175,7 +177,11 @@ const controlPlaneWebHandler = makeControlPlaneWebHandler( · 159 unmodified lines | ||
| 175 | 177 | PmActorLive(localStateStore), |
| 176 | 178 | ); |
| 177 | 179 | |
| 178 | −const toolProviderRegistry = makeToolProviderRegistry([makeOpenApiToolProvider()]); | |
| 180 | +const toolProviderRegistry = makeToolProviderRegistry([ | |
| 181 | + makeOpenApiToolProvider(), | |
| 182 | + makeMcpToolProvider(), | |
| 183 | + makeGraphqlToolProvider(), | |
| 184 | +]); | |
| 179 | 185 | const persistentApprovalPolicy = createPmPersistentToolApprovalPolicy(localStateStore, { |
| 180 | 186 | requireApprovals: requireToolApprovals, |
| 181 | 187 | }); |
| @@ -8,7 +8,10 @@ import { · 7 unmodified lines | ||
| 8 | 8 | type LocalStateStore, |
| 9 | 9 | type LocalStateStoreError, |
| 10 | 10 | } from "@executor-v2/persistence-local"; |
| 11 | −import { type Organization } from "@executor-v2/schema"; | |
| 11 | +import { | |
| 12 | + type Organization, | |
| 13 | + type OrganizationMembership, | |
| 14 | +} from "@executor-v2/schema"; | |
| 12 | 15 | import * as Effect from "effect/Effect"; |
| 13 | 16 | import * as Option from "effect/Option"; |
| 14 | 17 | |
| @@ -70,6 +73,15 @@ const appendOrganization = ( · 55 unmodified lines | ||
| 70 | 73 | organizations: [...snapshot.organizations, organization], |
| 71 | 74 | }); |
| 72 | 75 | |
| 76 | +const appendOrganizationMembership = ( | |
| 77 | + snapshot: LocalStateSnapshot, | |
| 78 | + membership: OrganizationMembership, | |
| 79 | +): LocalStateSnapshot => ({ | |
| 80 | + ...snapshot, | |
| 81 | + generatedAt: Date.now(), | |
| 82 | + organizationMemberships: [...snapshot.organizationMemberships, membership], | |
| 83 | +}); | |
| 84 | + | |
| 73 | 85 | export const createPmOrganizationsService = ( |
| 74 | 86 | localStateStore: LocalStateStore, |
| 75 | 87 | ): ControlPlaneOrganizationsServiceShape => |
| @@ -122,15 +134,41 @@ export const createPmOrganizationsService = ( · 46 unmodified lines | ||
| 122 | 134 | slug: input.payload.slug, |
| 123 | 135 | name: input.payload.name, |
| 124 | 136 | status: input.payload.status ?? existing?.status ?? "active", |
| 125 | − createdByAccountId: existing?.createdByAccountId ?? null, | |
| 137 | + createdByAccountId: | |
| 138 | + existing?.createdByAccountId | |
| 139 | + ?? input.payload.createdByAccountId | |
| 140 | + ?? null, | |
| 126 | 141 | createdAt: existing?.createdAt ?? now, |
| 127 | 142 | updatedAt: now, |
| 128 | 143 | }; |
| 129 | 144 | |
| 130 | − const nextSnapshot = existingIndex >= 0 | |
| 145 | + let nextSnapshot = existingIndex >= 0 | |
| 131 | 146 | ? replaceOrganizationAt(snapshot, existingIndex, nextOrganization) |
| 132 | 147 | : appendOrganization(snapshot, nextOrganization); |
| 133 | 148 | |
| 149 | + if (existing === null && nextOrganization.createdByAccountId !== null) { | |
| 150 | + const existingMembership = nextSnapshot.organizationMemberships.find( | |
| 151 | + (membership) => | |
| 152 | + membership.organizationId === nextOrganization.id | |
| 153 | + && membership.accountId === nextOrganization.createdByAccountId, | |
| 154 | + ); | |
| 155 | + | |
| 156 | + if (!existingMembership) { | |
| 157 | + nextSnapshot = appendOrganizationMembership(nextSnapshot, { | |
| 158 | + id: `org_member_${crypto.randomUUID()}` as OrganizationMembership["id"], | |
| 159 | + organizationId: nextOrganization.id, | |
| 160 | + accountId: nextOrganization.createdByAccountId, | |
| 161 | + role: "owner", | |
| 162 | + status: "active", | |
| 163 | + billable: false, | |
| 164 | + invitedByAccountId: null, | |
| 165 | + joinedAt: now, | |
| 166 | + createdAt: now, | |
| 167 | + updatedAt: now, | |
| 168 | + }); | |
| 169 | + } | |
| 170 | + } | |
| 171 | + | |
| 134 | 172 | yield* localStateStore.writeSnapshot(nextSnapshot).pipe( |
| 135 | 173 | Effect.mapError((error) => |
| 136 | 174 | toSourceStoreErrorFromLocalState("organizations.upsert_write", error), |
| @@ -29,7 +29,7 @@ const createTestSnapshot = (): LocalStateSnapshot => · 28 unmodified lines | ||
| 29 | 29 | workspaces: [ |
| 30 | 30 | { |
| 31 | 31 | id: "ws_local", |
| 32 | − organizationId: null, | |
| 32 | + organizationId: "org_local", | |
| 33 | 33 | name: "Local Workspace", |
| 34 | 34 | createdByAccountId: null, |
| 35 | 35 | createdAt: Date.now(), |
| @@ -97,13 +97,12 @@ const resolveWorkspaceOrganizationId = ( · 96 unmodified lines | ||
| 97 | 97 | workspaceId: WorkspaceId, |
| 98 | 98 | ): OrganizationId => { |
| 99 | 99 | const workspace = snapshot.workspaces.find((item) => item.id === workspaceId); |
| 100 | − const organizationId = workspace?.organizationId; | |
| 101 | 100 | |
| 102 | − if (organizationId !== null && organizationId !== undefined) { | |
| 103 | − return organizationId; | |
| 101 | + if (!workspace) { | |
| 102 | + throw new Error(`Workspace not found: ${workspaceId}`); | |
| 104 | 103 | } |
| 105 | 104 | |
| 106 | − return (`org_${workspaceId}`) as OrganizationId; | |
| 105 | + return workspace.organizationId; | |
| 107 | 106 | }; |
| 108 | 107 | |
| 109 | 108 | const canAccessStorageInstance = ( |
| @@ -113,10 +113,7 @@ export const createPmWorkspacesService = ( · 112 unmodified lines | ||
| 113 | 113 | |
| 114 | 114 | const nextWorkspace: Workspace = { |
| 115 | 115 | id: existing?.id ?? (input.payload.id ?? (`ws_${crypto.randomUUID()}` as Workspace["id"])), |
| 116 | − organizationId: | |
| 117 | − input.payload.organizationId !== undefined | |
| 118 | − ? input.payload.organizationId | |
| 119 | − : existing?.organizationId ?? null, | |
| 116 | + organizationId: input.payload.organizationId, | |
| 120 | 117 | name: input.payload.name, |
| 121 | 118 | createdByAccountId: existing?.createdByAccountId ?? null, |
| 122 | 119 | createdAt: existing?.createdAt ?? now, |
| @@ -4,15 +4,20 @@ Basic Next.js frontend for Executor v2 control plane. · 3 unmodified lines | ||
| 4 | 4 | |
| 5 | 5 | - Uses `@executor-v2/control-plane` Effect HttpApi client |
| 6 | 6 | - Uses Effect Atom (`@effect-atom/atom`, `@effect-atom/atom-react`) for query state |
| 7 | −- Proxies backend calls through `/api/control-plane/*` via `next.config.ts` rewrites | |
| 8 | 7 | |
| 9 | 8 | Run: |
| 10 | 9 | |
| 11 | 10 | - `bun run --cwd apps/web dev` |
| 12 | 11 | - Open `http://127.0.0.1:3000` |
| 13 | 12 | |
| 14 | −By default, control-plane proxy target is `http://127.0.0.1:8788`. | |
| 15 | −Override with `CONTROL_PLANE_UPSTREAM_URL`. | |
| 13 | +By default, control-plane API calls go directly to `http://127.0.0.1:8788`. | |
| 14 | +Override with `NEXT_PUBLIC_CONTROL_PLANE_BASE_URL` (and optionally `CONTROL_PLANE_SERVER_BASE_URL` for SSR). | |
| 15 | + | |
| 16 | +MCP install URL generation: | |
| 17 | + | |
| 18 | +- Derives from existing control-plane/frontend config. | |
| 19 | +- Prioritizes server-side `CONTROL_PLANE_UPSTREAM_URL` (or server/base control-plane URL) when available. | |
| 20 | +- In local dev, defaults to direct Convex MCP URL: `http://127.0.0.1:8788/v1/mcp?...` | |
| 16 | 21 | |
| 17 | 22 | WorkOS auth setup (optional but recommended): |
| 18 | 23 | |
| @@ -1,5 +1,28 @@ | ||
| 1 | 1 | import { ToolsView } from "../../../components/tools/tools-view"; |
| 2 | 2 | |
| 3 | −const ToolsPage = () => <ToolsView />; | |
| 3 | +const resolveMcpBaseUrl = (): string | null => { | |
| 4 | + const candidates = [ | |
| 5 | + process.env.CONTROL_PLANE_UPSTREAM_URL, | |
| 6 | + process.env.CONTROL_PLANE_SERVER_BASE_URL, | |
| 7 | + process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL, | |
| 8 | + ]; | |
| 9 | + | |
| 10 | + for (const candidate of candidates) { | |
| 11 | + const value = candidate?.trim(); | |
| 12 | + if (!value) { | |
| 13 | + continue; | |
| 14 | + } | |
| 15 | + | |
| 16 | + try { | |
| 17 | + return new URL(value).origin; | |
| 18 | + } catch { | |
| 19 | + // ignore invalid URL and continue | |
| 20 | + } | |
| 21 | + } | |
| 22 | + | |
| 23 | + return null; | |
| 24 | +}; | |
| 25 | + | |
| 26 | +const ToolsPage = () => <ToolsView mcpBaseUrl={resolveMcpBaseUrl()} />; | |
| 4 | 27 | |
| 5 | 28 | export default ToolsPage; |
| @@ -1,314 +0,0 @@ | ||
| 1 | −import { ControlPlaneAuthHeaders } from "@executor-v2/management-api"; | |
| 2 | −import { withAuth } from "@workos-inc/authkit-nextjs"; | |
| 3 | −import { type NextRequest } from "next/server"; | |
| 4 | − | |
| 5 | −import { isLocalControlPlaneUpstream, isWorkosEnabled } from "../../../../lib/workos"; | |
| 6 | − | |
| 7 | −const controlPlaneUpstream = | |
| 8 | − process.env.CONTROL_PLANE_UPSTREAM_URL ?? "http://127.0.0.1:8788"; | |
| 9 | − | |
| 10 | −type TaggedControlPlaneError = { | |
| 11 | − _tag: | |
| 12 | − | "ControlPlaneBadRequestError" | |
| 13 | − | "ControlPlaneUnauthorizedError" | |
| 14 | − | "ControlPlaneForbiddenError" | |
| 15 | − | "ControlPlaneStorageError"; | |
| 16 | − operation: string; | |
| 17 | − message: string; | |
| 18 | − details: string; | |
| 19 | −}; | |
| 20 | − | |
| 21 | −const readOptionalHeader = (headers: Headers, name: string): string | null => { | |
| 22 | − const value = headers.get(name); | |
| 23 | − if (value === null) { | |
| 24 | − return null; | |
| 25 | − } | |
| 26 | − | |
| 27 | − const trimmed = value.trim(); | |
| 28 | − return trimmed.length > 0 ? trimmed : null; | |
| 29 | −}; | |
| 30 | − | |
| 31 | −const isRecord = (value: unknown): value is Record<string, unknown> => | |
| 32 | − typeof value === "object" && value !== null; | |
| 33 | − | |
| 34 | −const readOptionalString = (record: Record<string, unknown>, key: string): string | null => { | |
| 35 | − const value = record[key]; | |
| 36 | − return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; | |
| 37 | −}; | |
| 38 | − | |
| 39 | −const tagForStatus = (status: number): TaggedControlPlaneError["_tag"] => { | |
| 40 | − switch (status) { | |
| 41 | − case 400: | |
| 42 | − return "ControlPlaneBadRequestError"; | |
| 43 | − case 401: | |
| 44 | − return "ControlPlaneUnauthorizedError"; | |
| 45 | − case 403: | |
| 46 | − return "ControlPlaneForbiddenError"; | |
| 47 | − default: | |
| 48 | − return "ControlPlaneStorageError"; | |
| 49 | − } | |
| 50 | −}; | |
| 51 | − | |
| 52 | −const responseStatusForTag = (status: number): number => { | |
| 53 | − switch (status) { | |
| 54 | − case 400: | |
| 55 | − case 401: | |
| 56 | − case 403: | |
| 57 | − return status; | |
| 58 | − default: | |
| 59 | − return 500; | |
| 60 | − } | |
| 61 | −}; | |
| 62 | − | |
| 63 | −const toTaggedErrorPayload = (input: { | |
| 64 | − status: number; | |
| 65 | − operation: string; | |
| 66 | − message: string; | |
| 67 | − details: string; | |
| 68 | −}): TaggedControlPlaneError => ({ | |
| 69 | − _tag: tagForStatus(input.status), | |
| 70 | − operation: input.operation, | |
| 71 | − message: input.message, | |
| 72 | − details: input.details, | |
| 73 | −}); | |
| 74 | − | |
| 75 | −const unauthorizedResponse = (): Response => | |
| 76 | − Response.json( | |
| 77 | − toTaggedErrorPayload({ | |
| 78 | − status: 401, | |
| 79 | − operation: "control-plane.proxy", | |
| 80 | − message: "Authentication required", | |
| 81 | − details: "Sign in with WorkOS before calling control-plane APIs", | |
| 82 | − }), | |
| 83 | − { status: 401 }, | |
| 84 | − ); | |
| 85 | − | |
| 86 | −const internalErrorResponse = (operation: string, cause: unknown): Response => | |
| 87 | − Response.json( | |
| 88 | − toTaggedErrorPayload({ | |
| 89 | − status: 500, | |
| 90 | − operation, | |
| 91 | − message: "Control plane proxy failed", | |
| 92 | − details: cause instanceof Error ? cause.message : String(cause), | |
| 93 | − }), | |
| 94 | − { status: 500 }, | |
| 95 | − ); | |
| 96 | − | |
| 97 | −const toProxyUrl = (request: NextRequest, path: ReadonlyArray<string>): URL => { | |
| 98 | − const joinedPath = path.join("/"); | |
| 99 | − const suffix = joinedPath.length > 0 ? `/${joinedPath}` : ""; | |
| 100 | − return new URL(`${controlPlaneUpstream}${suffix}${request.nextUrl.search}`); | |
| 101 | −}; | |
| 102 | − | |
| 103 | −const buildProxyHeaders = (request: NextRequest): Headers => { | |
| 104 | − const headers = new Headers(); | |
| 105 | − | |
| 106 | − const contentType = readOptionalHeader(request.headers, "content-type"); | |
| 107 | − if (contentType !== null) { | |
| 108 | − headers.set("content-type", contentType); | |
| 109 | − } | |
| 110 | − | |
| 111 | − const accept = readOptionalHeader(request.headers, "accept"); | |
| 112 | − if (accept !== null) { | |
| 113 | − headers.set("accept", accept); | |
| 114 | − } | |
| 115 | − | |
| 116 | − const acceptEncoding = readOptionalHeader(request.headers, "accept-encoding"); | |
| 117 | − if (acceptEncoding !== null) { | |
| 118 | − headers.set("accept-encoding", acceptEncoding); | |
| 119 | − } | |
| 120 | − | |
| 121 | − return headers; | |
| 122 | −}; | |
| 123 | − | |
| 124 | −const toDisplayName = (user: { | |
| 125 | − firstName?: string | null; | |
| 126 | − lastName?: string | null; | |
| 127 | −}): string | null => { | |
| 128 | − const first = user.firstName?.trim() ?? ""; | |
| 129 | − const last = user.lastName?.trim() ?? ""; | |
| 130 | − const fullName = `${first} ${last}`.trim(); | |
| 131 | − return fullName.length > 0 ? fullName : null; | |
| 132 | −}; | |
| 133 | − | |
| 134 | −const resolvePrincipalAccountId = ( | |
| 135 | − request: NextRequest, | |
| 136 | − userId: string | null, | |
| 137 | −): string | null => { | |
| 138 | − if (userId !== null) { | |
| 139 | − return userId; | |
| 140 | − } | |
| 141 | − | |
| 142 | − return readOptionalHeader(request.headers, ControlPlaneAuthHeaders.accountId); | |
| 143 | −}; | |
| 144 | − | |
| 145 | −const normalizeControlPlaneErrorResponse = async ( | |
| 146 | − upstreamResponse: Response, | |
| 147 | −): Promise<Response> => { | |
| 148 | − const contentType = upstreamResponse.headers.get("content-type")?.toLowerCase() ?? ""; | |
| 149 | − const isJson = contentType.includes("application/json"); | |
| 150 | − | |
| 151 | − const payload = isJson | |
| 152 | − ? await upstreamResponse | |
| 153 | − .json() | |
| 154 | − .catch(() => null) | |
| 155 | − : null; | |
| 156 | − | |
| 157 | − if (isRecord(payload)) { | |
| 158 | − const tagged = readOptionalString(payload, "_tag"); | |
| 159 | − const operation = readOptionalString(payload, "operation"); | |
| 160 | − const message = readOptionalString(payload, "message"); | |
| 161 | − const details = readOptionalString(payload, "details"); | |
| 162 | − | |
| 163 | − if ( | |
| 164 | − tagged !== null | |
| 165 | − && operation !== null | |
| 166 | − && message !== null | |
| 167 | − && details !== null | |
| 168 | − && ( | |
| 169 | − tagged === "ControlPlaneBadRequestError" | |
| 170 | − || tagged === "ControlPlaneUnauthorizedError" | |
| 171 | − || tagged === "ControlPlaneForbiddenError" | |
| 172 | − || tagged === "ControlPlaneStorageError" | |
| 173 | − ) | |
| 174 | − ) { | |
| 175 | − return Response.json( | |
| 176 | − { | |
| 177 | − _tag: tagged, | |
| 178 | − operation, | |
| 179 | − message, | |
| 180 | − details, | |
| 181 | − } satisfies TaggedControlPlaneError, | |
| 182 | − { status: upstreamResponse.status }, | |
| 183 | − ); | |
| 184 | − } | |
| 185 | − | |
| 186 | − if (isRecord(payload.error)) { | |
| 187 | − const operationFromCode = readOptionalString(payload.error, "code"); | |
| 188 | − const messageFromError = readOptionalString(payload.error, "message"); | |
| 189 | − const detailsFromError = readOptionalString(payload.error, "details"); | |
| 190 | − | |
| 191 | − return Response.json( | |
| 192 | − toTaggedErrorPayload({ | |
| 193 | − status: upstreamResponse.status, | |
| 194 | − operation: operationFromCode ?? "control-plane.proxy", | |
| 195 | − message: messageFromError ?? "Control plane request failed", | |
| 196 | − details: detailsFromError ?? (upstreamResponse.statusText || "Request failed"), | |
| 197 | − }), | |
| 198 | − { status: responseStatusForTag(upstreamResponse.status) }, | |
| 199 | − ); | |
| 200 | − } | |
| 201 | − } | |
| 202 | − | |
| 203 | − const textBody = await upstreamResponse | |
| 204 | − .text() | |
| 205 | − .catch(() => ""); | |
| 206 | − | |
| 207 | − return Response.json( | |
| 208 | − toTaggedErrorPayload({ | |
| 209 | − status: upstreamResponse.status, | |
| 210 | − operation: "control-plane.proxy", | |
| 211 | − message: "Control plane request failed", | |
| 212 | − details: | |
| 213 | − textBody.trim().length > 0 | |
| 214 | − ? textBody.trim() | |
| 215 | − : upstreamResponse.statusText || "Request failed", | |
| 216 | − }), | |
| 217 | − { status: responseStatusForTag(upstreamResponse.status) }, | |
| 218 | − ); | |
| 219 | −}; | |
| 220 | − | |
| 221 | −const normalizeSuccessResponse = ( | |
| 222 | − upstreamResponse: Response, | |
| 223 | −): Response => { | |
| 224 | − const contentType = upstreamResponse.headers.get("content-type")?.toLowerCase() ?? ""; | |
| 225 | − | |
| 226 | − const headers = new Headers(); | |
| 227 | − if (contentType.length > 0) { | |
| 228 | − headers.set("content-type", contentType); | |
| 229 | − } | |
| 230 | − | |
| 231 | − return new Response(upstreamResponse.body, { | |
| 232 | − status: upstreamResponse.status, | |
| 233 | − headers, | |
| 234 | − }); | |
| 235 | −}; | |
| 236 | − | |
| 237 | −const proxyControlPlaneRequest = async ( | |
| 238 | − request: NextRequest, | |
| 239 | − path: ReadonlyArray<string>, | |
| 240 | −): Promise<Response> => { | |
| 241 | − try { | |
| 242 | − const workosEnabled = isWorkosEnabled(); | |
| 243 | − const user = workosEnabled ? (await withAuth()).user : null; | |
| 244 | − | |
| 245 | − let principalAccountId = resolvePrincipalAccountId(request, user?.id ?? null); | |
| 246 | − | |
| 247 | − if (workosEnabled && user === null) { | |
| 248 | − return unauthorizedResponse(); | |
| 249 | − } | |
| 250 | − | |
| 251 | − if (principalAccountId === null && !workosEnabled && isLocalControlPlaneUpstream()) { | |
| 252 | − const localAccountId = process.env.CONTROL_PLANE_LOCAL_ACCOUNT_ID?.trim(); | |
| 253 | − principalAccountId = localAccountId && localAccountId.length > 0 | |
| 254 | − ? localAccountId | |
| 255 | − : "local-dev"; | |
| 256 | − } | |
| 257 | − | |
| 258 | − if (principalAccountId === null) { | |
| 259 | − return unauthorizedResponse(); | |
| 260 | − } | |
| 261 | − | |
| 262 | − const headers = buildProxyHeaders(request); | |
| 263 | − | |
| 264 | − headers.set(ControlPlaneAuthHeaders.accountId, principalAccountId); | |
| 265 | − headers.set(ControlPlaneAuthHeaders.principalProvider, user ? "workos" : "local"); | |
| 266 | − headers.set( | |
| 267 | − ControlPlaneAuthHeaders.principalSubject, | |
| 268 | − user ? `workos:${user.id}` : `local:${principalAccountId}`, | |
| 269 | − ); | |
| 270 | − | |
| 271 | − const email = user?.email?.trim(); | |
| 272 | − if (email) { | |
| 273 | − headers.set(ControlPlaneAuthHeaders.principalEmail, email); | |
| 274 | − } | |
| 275 | − | |
| 276 | − const displayName = user ? toDisplayName(user) : null; | |
| 277 | − if (displayName) { | |
| 278 | − headers.set(ControlPlaneAuthHeaders.principalDisplayName, displayName); | |
| 279 | − } | |
| 280 | − | |
| 281 | − const body = | |
| 282 | − request.method === "GET" || request.method === "HEAD" | |
| 283 | − ? undefined | |
| 284 | − : await request.arrayBuffer(); | |
| 285 | − | |
| 286 | − const upstreamResponse = await fetch(toProxyUrl(request, path), { | |
| 287 | − method: request.method, | |
| 288 | − headers, | |
| 289 | − body, | |
| 290 | − cache: "no-store", | |
| 291 | − }); | |
| 292 | − | |
| 293 | − if (!upstreamResponse.ok) { | |
| 294 | − return normalizeControlPlaneErrorResponse(upstreamResponse); | |
| 295 | − } | |
| 296 | − | |
| 297 | − return normalizeSuccessResponse(upstreamResponse); | |
| 298 | − } catch (cause) { | |
| 299 | − return internalErrorResponse("control-plane.proxy", cause); | |
| 300 | − } | |
| 301 | −}; | |
| 302 | − | |
| 303 | −type RouteParams = { | |
| 304 | − params: Promise<{ path: Array<string> }>; | |
| 305 | −}; | |
| 306 | − | |
| 307 | −export const GET = async (request: NextRequest, context: RouteParams) => | |
| 308 | − proxyControlPlaneRequest(request, (await context.params).path); | |
| 309 | − | |
| 310 | −export const POST = async (request: NextRequest, context: RouteParams) => | |
| 311 | − proxyControlPlaneRequest(request, (await context.params).path); | |
| 312 | − | |
| 313 | −export const DELETE = async (request: NextRequest, context: RouteParams) => | |
| 314 | − proxyControlPlaneRequest(request, (await context.params).path); | |
| @@ -60,6 +60,17 @@ const defaultWorkspaceForm = (): WorkspaceForm => ({ · 59 unmodified lines | ||
| 60 | 60 | organizationId: "", |
| 61 | 61 | }); |
| 62 | 62 | |
| 63 | +const createOrganizationId = (): Organization["id"] => | |
| 64 | + `org_${crypto.randomUUID()}` as Organization["id"]; | |
| 65 | + | |
| 66 | +const createWorkspaceId = (): Workspace["id"] => | |
| 67 | + `ws_${crypto.randomUUID()}` as Workspace["id"]; | |
| 68 | + | |
| 69 | +const errorMessage = (cause: unknown, fallback: string): string => | |
| 70 | + cause instanceof Error && cause.message.trim().length > 0 | |
| 71 | + ? cause.message | |
| 72 | + : fallback; | |
| 73 | + | |
| 63 | 74 | const organizationStatusVariant = ( |
| 64 | 75 | status: Organization["status"], |
| 65 | 76 | ): "approved" | "pending" | "denied" | "outline" => { |
| @@ -106,7 +117,7 @@ export default function SettingsView() { · 40 unmodified lines | ||
| 106 | 117 | ...current, |
| 107 | 118 | id: currentWorkspace.id, |
| 108 | 119 | name: currentWorkspace.name, |
| 109 | − organizationId: currentWorkspace.organizationId ?? "", | |
| 120 | + organizationId: currentWorkspace.organizationId, | |
| 110 | 121 | })); |
| 111 | 122 | }, [workspaceId, workspaceForm.name, workspaces.items]); |
| 112 | 123 | |
| @@ -116,7 +127,7 @@ export default function SettingsView() { · 3 unmodified lines | ||
| 116 | 127 | } |
| 117 | 128 | |
| 118 | 129 | const currentWorkspace = workspaces.items.find((workspace) => workspace.id === workspaceId); |
| 119 | − if (!currentWorkspace?.organizationId) { | |
| 130 | + if (!currentWorkspace) { | |
| 120 | 131 | return; |
| 121 | 132 | } |
| 122 | 133 | |
| @@ -141,6 +152,9 @@ export default function SettingsView() { · 18 unmodified lines | ||
| 141 | 152 | const slug = organizationForm.slug.trim(); |
| 142 | 153 | const name = organizationForm.name.trim(); |
| 143 | 154 | const inputId = organizationForm.id.trim(); |
| 155 | + const organizationId = inputId.length > 0 | |
| 156 | + ? (inputId as Organization["id"]) | |
| 157 | + : createOrganizationId(); | |
| 144 | 158 | |
| 145 | 159 | if (slug.length === 0 || name.length === 0) { |
| 146 | 160 | setOrganizationStatusText("Organization slug and name are required."); |
| @@ -148,7 +162,7 @@ export default function SettingsView() { · 1 unmodified line | ||
| 148 | 162 | } |
| 149 | 163 | |
| 150 | 164 | const payload = toOrganizationUpsertPayload({ |
| 151 | − id: inputId.length > 0 ? (inputId as Organization["id"]) : undefined, | |
| 165 | + id: organizationId, | |
| 152 | 166 | slug, |
| 153 | 167 | name, |
| 154 | 168 | status: organizationForm.status, |
| @@ -164,8 +178,8 @@ export default function SettingsView() { · 9 unmodified lines | ||
| 164 | 178 | status: organization.status, |
| 165 | 179 | }); |
| 166 | 180 | }) |
| 167 | − .catch(() => { | |
| 168 | − setOrganizationStatusText("Organization save failed."); | |
| 181 | + .catch((cause) => { | |
| 182 | + setOrganizationStatusText(errorMessage(cause, "Organization save failed.")); | |
| 169 | 183 | }); |
| 170 | 184 | }; |
| 171 | 185 | |
| @@ -175,16 +189,24 @@ export default function SettingsView() { · 3 unmodified lines | ||
| 175 | 189 | const name = workspaceForm.name.trim(); |
| 176 | 190 | const inputId = workspaceForm.id.trim(); |
| 177 | 191 | const organizationId = workspaceForm.organizationId.trim(); |
| 192 | + const workspaceId = inputId.length > 0 | |
| 193 | + ? (inputId as Workspace["id"]) | |
| 194 | + : createWorkspaceId(); | |
| 178 | 195 | |
| 179 | 196 | if (name.length === 0) { |
| 180 | 197 | setWorkspaceStatusText("Workspace name is required."); |
| 181 | 198 | return; |
| 182 | 199 | } |
| 183 | 200 | |
| 201 | + if (organizationId.length === 0) { | |
| 202 | + setWorkspaceStatusText("Workspace organization is required."); | |
| 203 | + return; | |
| 204 | + } | |
| 205 | + | |
| 184 | 206 | const payload = toWorkspaceUpsertPayload({ |
| 185 | − id: inputId.length > 0 ? (inputId as Workspace["id"]) : undefined, | |
| 207 | + id: workspaceId, | |
| 186 | 208 | name, |
| 187 | − organizationId: organizationId.length > 0 ? (organizationId as Workspace["organizationId"]) : null, | |
| 209 | + organizationId: organizationId as Workspace["organizationId"], | |
| 188 | 210 | }); |
| 189 | 211 | |
| 190 | 212 | void runUpsertWorkspace({ payload }) |
| @@ -193,12 +215,12 @@ export default function SettingsView() { · 2 unmodified lines | ||
| 193 | 215 | setWorkspaceForm({ |
| 194 | 216 | id: workspace.id, |
| 195 | 217 | name: workspace.name, |
| 196 | − organizationId: workspace.organizationId ?? "", | |
| 218 | + organizationId: workspace.organizationId, | |
| 197 | 219 | }); |
| 198 | 220 | setWorkspaceId(workspace.id); |
| 199 | 221 | }) |
| 200 | − .catch(() => { | |
| 201 | − setWorkspaceStatusText("Workspace save failed."); | |
| 222 | + .catch((cause) => { | |
| 223 | + setWorkspaceStatusText(errorMessage(cause, "Workspace save failed.")); | |
| 202 | 224 | }); |
| 203 | 225 | }; |
| 204 | 226 | |
| @@ -216,7 +238,7 @@ export default function SettingsView() { · 11 unmodified lines | ||
| 216 | 238 | setWorkspaceForm({ |
| 217 | 239 | id: workspace.id, |
| 218 | 240 | name: workspace.name, |
| 219 | − organizationId: workspace.organizationId ?? "", | |
| 241 | + organizationId: workspace.organizationId, | |
| 220 | 242 | }); |
| 221 | 243 | setWorkspaceId(workspace.id); |
| 222 | 244 | setWorkspaceStatusText(`Loaded workspace ${workspace.id}.`); |
| @@ -376,7 +398,7 @@ export default function SettingsView() { · 153 unmodified lines | ||
| 376 | 398 | <CardHeader className="pb-3"> |
| 377 | 399 | <CardTitle>Workspace Profile</CardTitle> |
| 378 | 400 | <CardDescription> |
| 379 | − Create or update workspace records and their optional organization id. | |
| 401 | + Create or update workspace records scoped to an organization. | |
| 380 | 402 | </CardDescription> |
| 381 | 403 | </CardHeader> |
| 382 | 404 | |
| @@ -413,9 +435,9 @@ export default function SettingsView() { · 30 unmodified lines | ||
| 413 | 435 | </div> |
| 414 | 436 | <div className="grid gap-1.5"> |
| 415 | 437 | <label className="text-xs text-muted-foreground" htmlFor="workspace-organization-id"> |
| 416 | − Organization ID | |
| 438 | + Organization | |
| 417 | 439 | </label> |
| 418 | − <Input | |
| 440 | + <Select | |
| 419 | 441 | id="workspace-organization-id" |
| 420 | 442 | value={workspaceForm.organizationId} |
| 421 | 443 | onChange={(event) => |
| @@ -424,9 +446,15 @@ export default function SettingsView() { · 2 unmodified lines | ||
| 424 | 446 | organizationId: event.target.value, |
| 425 | 447 | })) |
| 426 | 448 | } |
| 427 | − placeholder="org_local (optional)" | |
| 428 | 449 | disabled={workspacesLoading} |
| 429 | − /> | |
| 450 | + > | |
| 451 | + <option value="">Select organization</option> | |
| 452 | + {organizations.items.map((organization) => ( | |
| 453 | + <option key={organization.id} value={organization.id}> | |
| 454 | + {organization.name} | |
| 455 | + </option> | |
| 456 | + ))} | |
| 457 | + </Select> | |
| 430 | 458 | </div> |
| 431 | 459 | |
| 432 | 460 | <div className="flex gap-2"> |
| @@ -466,7 +494,7 @@ export default function SettingsView() { · 33 unmodified lines | ||
| 466 | 494 | <p className="truncate text-sm font-medium">{workspace.name}</p> |
| 467 | 495 | <div className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground"> |
| 468 | 496 | <span className="break-all">{workspace.id}</span> |
| 469 | − <span className="break-all">org {workspace.organizationId ?? "-"}</span> | |
| 497 | + <span className="break-all">org {workspace.organizationId}</span> | |
| 470 | 498 | </div> |
| 471 | 499 | </div> |
| 472 | 500 | <Button |
| @@ -128,18 +128,10 @@ export function AppShell({ · 127 unmodified lines | ||
| 128 | 128 | {/* ---- Sidebar ---- */} |
| 129 | 129 | <aside className="flex w-[220px] shrink-0 flex-col border-r border-sidebar-border bg-sidebar"> |
| 130 | 130 | {/* Logo / brand */} |
| 131 | − <div className="flex h-12 items-center gap-2 border-b border-sidebar-border px-4"> | |
| 132 | − <div className="flex size-6 items-center justify-center rounded bg-primary/90 text-[10px] font-bold text-primary-foreground"> | |
| 133 | − Ex | |
| 131 | + <div className="border-b border-sidebar-border px-3 py-2"> | |
| 132 | + <div className="min-w-0"> | |
| 133 | + <WorkspaceSelector /> | |
| 134 | 134 | </div> |
| 135 | − <span className="text-[13px] font-semibold tracking-tight text-sidebar-foreground"> | |
| 136 | − Executor v2 | |
| 137 | − </span> | |
| 138 | − </div> | |
| 139 | − | |
| 140 | − {/* Workspace selector */} | |
| 141 | − <div className="border-b border-sidebar-border px-3 py-2.5"> | |
| 142 | − <WorkspaceSelector /> | |
| 143 | 135 | </div> |
| 144 | 136 | |
| 145 | 137 | {/* Nav items */} |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | "use client"; |
| 2 | 2 | |
| 3 | −import { useEffect, useMemo, useState, type FormEvent } from "react"; | |
| 3 | +import { useEffect, useMemo, useRef, useState, type FormEvent } from "react"; | |
| 4 | 4 | import { useAtomSet, useAtomValue } from "@effect-atom/atom-react"; |
| 5 | 5 | import type { Organization, Workspace } from "@executor-v2/schema"; |
| 6 | 6 | |
| @@ -13,23 +13,34 @@ import { · 6 unmodified lines | ||
| 13 | 13 | workspacesState, |
| 14 | 14 | } from "../../lib/control-plane/atoms"; |
| 15 | 15 | import { useWorkspace } from "../../lib/hooks/use-workspace"; |
| 16 | +import { cn } from "../../lib/utils"; | |
| 16 | 17 | import { Button } from "../ui/button"; |
| 17 | 18 | import { Input } from "../ui/input"; |
| 18 | −import { Select } from "../ui/select"; | |
| 19 | 19 | |
| 20 | 20 | type StatusState = { |
| 21 | 21 | message: string | null; |
| 22 | 22 | variant: "info" | "error"; |
| 23 | 23 | }; |
| 24 | 24 | |
| 25 | −type WorkspaceGroup = { | |
| 26 | − key: string; | |
| 25 | +type OrganizationGroup = { | |
| 26 | + organizationId: Organization["id"]; | |
| 27 | 27 | label: string; |
| 28 | 28 | workspaces: Array<Workspace>; |
| 29 | 29 | }; |
| 30 | 30 | |
| 31 | 31 | const defaultStatus = (): StatusState => ({ message: null, variant: "info" }); |
| 32 | 32 | |
| 33 | +const createWorkspaceId = (): Workspace["id"] => | |
| 34 | + `ws_${crypto.randomUUID()}` as Workspace["id"]; | |
| 35 | + | |
| 36 | +const createOrganizationId = (): Organization["id"] => | |
| 37 | + `org_${crypto.randomUUID()}` as Organization["id"]; | |
| 38 | + | |
| 39 | +const errorMessage = (cause: unknown, fallback: string): string => | |
| 40 | + cause instanceof Error && cause.message.trim().length > 0 | |
| 41 | + ? cause.message | |
| 42 | + : fallback; | |
| 43 | + | |
| 33 | 44 | const slugify = (value: string): string => |
| 34 | 45 | value |
| 35 | 46 | .trim() |
| @@ -39,14 +50,34 @@ const slugify = (value: string): string => · 3 unmodified lines | ||
| 39 | 50 | .replace(/-+$/, "") |
| 40 | 51 | .replace(/-{2,}/g, "-"); |
| 41 | 52 | |
| 53 | +const CheckIcon = ({ className }: { className?: string }) => ( | |
| 54 | + <svg viewBox="0 0 16 16" fill="none" className={className}> | |
| 55 | + <path d="M3.5 8.5l3 3 6-7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> | |
| 56 | + </svg> | |
| 57 | +); | |
| 58 | + | |
| 59 | +const PlusIcon = ({ className }: { className?: string }) => ( | |
| 60 | + <svg viewBox="0 0 16 16" fill="none" className={className}> | |
| 61 | + <path d="M8 3v10M3 8h10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" /> | |
| 62 | + </svg> | |
| 63 | +); | |
| 64 | + | |
| 65 | +const ChevronsIcon = ({ className }: { className?: string }) => ( | |
| 66 | + <svg viewBox="0 0 16 16" fill="none" className={className}> | |
| 67 | + <path d="M5 6l3-3 3 3M11 10l-3 3-3-3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" /> | |
| 68 | + </svg> | |
| 69 | +); | |
| 70 | + | |
| 42 | 71 | export function WorkspaceSelector() { |
| 43 | 72 | const { workspaceId, setWorkspaceId } = useWorkspace(); |
| 44 | 73 | const organizations = useAtomValue(organizationsState); |
| 45 | 74 | const workspaces = useAtomValue(workspacesState); |
| 46 | 75 | const runUpsertOrganization = useAtomSet(upsertOrganization, { mode: "promise" }); |
| 47 | 76 | const runUpsertWorkspace = useAtomSet(upsertWorkspace, { mode: "promise" }); |
| 77 | + const containerRef = useRef<HTMLDivElement | null>(null); | |
| 48 | 78 | |
| 49 | 79 | const [activeForm, setActiveForm] = useState<"workspace" | "organization" | null>(null); |
| 80 | + const [menuOpen, setMenuOpen] = useState(false); | |
| 50 | 81 | const [workspaceName, setWorkspaceName] = useState(""); |
| 51 | 82 | const [workspaceOrganizationId, setWorkspaceOrganizationId] = useState(""); |
| 52 | 83 | const [organizationName, setOrganizationName] = useState(""); |
| @@ -68,44 +99,53 @@ export function WorkspaceSelector() { · 15 unmodified lines | ||
| 68 | 99 | [workspaces.items, workspaceId], |
| 69 | 100 | ); |
| 70 | 101 | |
| 71 | − const currentOrganizationLabel = useMemo(() => { | |
| 72 | − if (!currentWorkspace?.organizationId) { | |
| 73 | − return "No organization"; | |
| 74 | − } | |
| 102 | + const currentWorkspaceLabel = currentWorkspace?.name ?? "Select workspace"; | |
| 103 | + const hasOrganizations = organizations.items.length > 0; | |
| 75 | 104 | |
| 76 | − return organizationNameById.get(currentWorkspace.organizationId) | |
| 77 | − ?? currentWorkspace.organizationId; | |
| 78 | − }, [currentWorkspace, organizationNameById]); | |
| 105 | + const currentOrganizationLabel = useMemo( | |
| 106 | + () => | |
| 107 | + currentWorkspace | |
| 108 | + ? organizationNameById.get(currentWorkspace.organizationId) ?? currentWorkspace.organizationId | |
| 109 | + : null, | |
| 110 | + [currentWorkspace, organizationNameById], | |
| 111 | + ); | |
| 79 | 112 | |
| 80 | − const workspaceGroups = useMemo((): Array<WorkspaceGroup> => { | |
| 81 | − const byGroup = new Map<string, WorkspaceGroup>(); | |
| 113 | + const organizationGroups = useMemo((): Array<OrganizationGroup> => { | |
| 114 | + const workspacesByOrganization = new Map<string, Array<Workspace>>(); | |
| 82 | 115 | |
| 83 | 116 | for (const workspace of workspaces.items) { |
| 84 | − const key = workspace.organizationId ?? "__none__"; | |
| 85 | − const label = | |
| 86 | − workspace.organizationId === null | |
| 87 | − ? "No organization" | |
| 88 | − : organizationNameById.get(workspace.organizationId) ?? workspace.organizationId; | |
| 89 | − | |
| 90 | − const existing = byGroup.get(key); | |
| 117 | + const existing = workspacesByOrganization.get(workspace.organizationId); | |
| 91 | 118 | if (existing) { |
| 92 | − existing.workspaces.push(workspace); | |
| 119 | + existing.push(workspace); | |
| 120 | + } else { | |
| 121 | + workspacesByOrganization.set(workspace.organizationId, [workspace]); | |
| 122 | + } | |
| 123 | + } | |
| 124 | + | |
| 125 | + const groups = organizations.items | |
| 126 | + .map((organization) => ({ | |
| 127 | + organizationId: organization.id, | |
| 128 | + label: organization.name, | |
| 129 | + workspaces: [...(workspacesByOrganization.get(organization.id) ?? [])].sort((a, b) => | |
| 130 | + a.name.localeCompare(b.name), | |
| 131 | + ), | |
| 132 | + })) | |
| 133 | + .sort((left, right) => left.label.localeCompare(right.label)); | |
| 134 | + | |
| 135 | + for (const [organizationId, groupedWorkspaces] of workspacesByOrganization.entries()) { | |
| 136 | + if (organizationNameById.has(organizationId)) { | |
| 93 | 137 | continue; |
| 94 | 138 | } |
| 95 | 139 | |
| 96 | − byGroup.set(key, { | |
| 97 | − key, | |
| 98 | − label, | |
| 99 | − workspaces: [workspace], | |
| 140 | + groups.push({ | |
| 141 | + organizationId: organizationId as Organization["id"], | |
| 142 | + label: organizationId, | |
| 143 | + workspaces: [...groupedWorkspaces].sort((a, b) => a.name.localeCompare(b.name)), | |
| 100 | 144 | }); |
| 101 | 145 | } |
| 102 | 146 | |
| 103 | − return [...byGroup.values()].sort((left, right) => { | |
| 104 | − if (left.key === "__none__") return -1; | |
| 105 | − if (right.key === "__none__") return 1; | |
| 106 | − return left.label.localeCompare(right.label); | |
| 107 | − }); | |
| 108 | − }, [organizationNameById, workspaces.items]); | |
| 147 | + return groups; | |
| 148 | + }, [organizationNameById, organizations.items, workspaces.items]); | |
| 109 | 149 | |
| 110 | 150 | useEffect(() => { |
| 111 | 151 | if (workspaces.state !== "ready") { |
| @@ -125,9 +165,49 @@ export function WorkspaceSelector() { · 13 unmodified lines | ||
| 125 | 165 | } |
| 126 | 166 | }, [setWorkspaceId, workspaceId, workspaces.items, workspaces.state]); |
| 127 | 167 | |
| 128 | − const openWorkspaceForm = () => { | |
| 168 | + useEffect(() => { | |
| 169 | + if (!menuOpen) { | |
| 170 | + return; | |
| 171 | + } | |
| 172 | + | |
| 173 | + const onPointerDown = (event: MouseEvent | TouchEvent) => { | |
| 174 | + if (!containerRef.current?.contains(event.target as Node)) { | |
| 175 | + setMenuOpen(false); | |
| 176 | + } | |
| 177 | + }; | |
| 178 | + | |
| 179 | + const onKeyDown = (event: KeyboardEvent) => { | |
| 180 | + if (event.key === "Escape") { | |
| 181 | + setMenuOpen(false); | |
| 182 | + } | |
| 183 | + }; | |
| 184 | + | |
| 185 | + document.addEventListener("mousedown", onPointerDown); | |
| 186 | + document.addEventListener("touchstart", onPointerDown); | |
| 187 | + document.addEventListener("keydown", onKeyDown); | |
| 188 | + | |
| 189 | + return () => { | |
| 190 | + document.removeEventListener("mousedown", onPointerDown); | |
| 191 | + document.removeEventListener("touchstart", onPointerDown); | |
| 192 | + document.removeEventListener("keydown", onKeyDown); | |
| 193 | + }; | |
| 194 | + }, [menuOpen]); | |
| 195 | + | |
| 196 | + const selectWorkspace = (nextWorkspaceId: Workspace["id"]) => { | |
| 197 | + setWorkspaceId(nextWorkspaceId); | |
| 129 | 198 | setStatus(defaultStatus()); |
| 130 | − if (activeForm === "workspace") { | |
| 199 | + setActiveForm(null); | |
| 200 | + setMenuOpen(false); | |
| 201 | + }; | |
| 202 | + | |
| 203 | + const openWorkspaceForm = (organizationId?: Organization["id"]) => { | |
| 204 | + setStatus(defaultStatus()); | |
| 205 | + | |
| 206 | + if (!menuOpen) { | |
| 207 | + setMenuOpen(true); | |
| 208 | + } | |
| 209 | + | |
| 210 | + if (activeForm === "workspace" && organizationId === workspaceOrganizationId) { | |
| 131 | 211 | setActiveForm(null); |
| 132 | 212 | return; |
| 133 | 213 | } |
| @@ -135,7 +215,21 @@ export function WorkspaceSelector() { · 1 unmodified line | ||
| 135 | 215 | setActiveForm("workspace"); |
| 136 | 216 | setWorkspaceName(""); |
| 137 | 217 | |
| 138 | − if (currentWorkspace?.organizationId) { | |
| 218 | + if (organizations.items.length === 0) { | |
| 219 | + setWorkspaceOrganizationId(""); | |
| 220 | + setStatus({ | |
| 221 | + message: "Create an organization first.", | |
| 222 | + variant: "error", | |
| 223 | + }); | |
| 224 | + return; | |
| 225 | + } | |
| 226 | + | |
| 227 | + if (organizationId) { | |
| 228 | + setWorkspaceOrganizationId(organizationId); | |
| 229 | + return; | |
| 230 | + } | |
| 231 | + | |
| 232 | + if (currentWorkspace) { | |
| 139 | 233 | setWorkspaceOrganizationId(currentWorkspace.organizationId); |
| 140 | 234 | return; |
| 141 | 235 | } |
| @@ -145,6 +239,11 @@ export function WorkspaceSelector() { · 3 unmodified lines | ||
| 145 | 239 | |
| 146 | 240 | const openOrganizationForm = () => { |
| 147 | 241 | setStatus(defaultStatus()); |
| 242 | + | |
| 243 | + if (!menuOpen) { | |
| 244 | + setMenuOpen(true); | |
| 245 | + } | |
| 246 | + | |
| 148 | 247 | if (activeForm === "organization") { |
| 149 | 248 | setActiveForm(null); |
| 150 | 249 | return; |
| @@ -169,28 +268,36 @@ export function WorkspaceSelector() { · 18 unmodified lines | ||
| 169 | 268 | return; |
| 170 | 269 | } |
| 171 | 270 | |
| 271 | + if (organizationId.length === 0) { | |
| 272 | + setStatus({ | |
| 273 | + message: "Select an organization first.", | |
| 274 | + variant: "error", | |
| 275 | + }); | |
| 276 | + return; | |
| 277 | + } | |
| 278 | + | |
| 172 | 279 | setCreatingWorkspace(true); |
| 173 | 280 | |
| 174 | 281 | void runUpsertWorkspace({ |
| 175 | 282 | payload: toWorkspaceUpsertPayload({ |
| 283 | + id: createWorkspaceId(), | |
| 176 | 284 | name, |
| 177 | − organizationId: organizationId.length > 0 | |
| 178 | − ? (organizationId as Workspace["organizationId"]) | |
| 179 | − : null, | |
| 285 | + organizationId: organizationId as Workspace["organizationId"], | |
| 180 | 286 | }), |
| 181 | 287 | }) |
| 182 | 288 | .then((workspace) => { |
| 183 | 289 | setWorkspaceId(workspace.id); |
| 184 | 290 | setWorkspaceName(""); |
| 185 | 291 | setActiveForm(null); |
| 292 | + setMenuOpen(false); | |
| 186 | 293 | setStatus({ |
| 187 | 294 | message: `Created workspace ${workspace.name}.`, |
| 188 | 295 | variant: "info", |
| 189 | 296 | }); |
| 190 | 297 | }) |
| 191 | − .catch(() => { | |
| 298 | + .catch((cause) => { | |
| 192 | 299 | setStatus({ |
| 193 | − message: "Workspace creation failed.", | |
| 300 | + message: errorMessage(cause, "Workspace creation failed."), | |
| 194 | 301 | variant: "error", |
| 195 | 302 | }); |
| 196 | 303 | }) |
| @@ -225,34 +332,48 @@ export function WorkspaceSelector() { · 28 unmodified lines | ||
| 225 | 332 | |
| 226 | 333 | setCreatingOrganization(true); |
| 227 | 334 | |
| 335 | + const organizationId = createOrganizationId(); | |
| 336 | + | |
| 228 | 337 | void runUpsertOrganization({ |
| 229 | 338 | payload: toOrganizationUpsertPayload({ |
| 339 | + id: organizationId, | |
| 230 | 340 | name, |
| 231 | 341 | slug, |
| 232 | 342 | status: "active", |
| 233 | 343 | }), |
| 234 | 344 | }) |
| 235 | 345 | .then(async (organization) => { |
| 236 | − const workspace = await runUpsertWorkspace({ | |
| 237 | − payload: toWorkspaceUpsertPayload({ | |
| 238 | − name, | |
| 239 | − organizationId: organization.id as Workspace["organizationId"], | |
| 240 | − }), | |
| 241 | − }); | |
| 242 | − | |
| 243 | − setWorkspaceId(workspace.id); | |
| 244 | − setWorkspaceOrganizationId(organization.id); | |
| 245 | − setOrganizationName(""); | |
| 246 | − setOrganizationSlug(""); | |
| 247 | − setActiveForm(null); | |
| 248 | − setStatus({ | |
| 249 | − message: `Created organization ${organization.name} with workspace ${workspace.name}.`, | |
| 250 | − variant: "info", | |
| 251 | − }); | |
| 346 | + try { | |
| 347 | + const workspace = await runUpsertWorkspace({ | |
| 348 | + payload: toWorkspaceUpsertPayload({ | |
| 349 | + id: createWorkspaceId(), | |
| 350 | + name, | |
| 351 | + organizationId: organization.id as Workspace["organizationId"], | |
| 352 | + }), | |
| 353 | + }); | |
| 354 | + | |
| 355 | + setWorkspaceId(workspace.id); | |
| 356 | + setWorkspaceOrganizationId(organization.id); | |
| 357 | + setOrganizationName(""); | |
| 358 | + setOrganizationSlug(""); | |
| 359 | + setActiveForm(null); | |
| 360 | + setMenuOpen(false); | |
| 361 | + setStatus({ | |
| 362 | + message: `Created organization ${organization.name} with workspace ${workspace.name}.`, | |
| 363 | + variant: "info", | |
| 364 | + }); | |
| 365 | + } catch { | |
| 366 | + setWorkspaceOrganizationId(organization.id); | |
| 367 | + setActiveForm("workspace"); | |
| 368 | + setStatus({ | |
| 369 | + message: `Created organization ${organization.name}, but workspace creation failed.`, | |
| 370 | + variant: "error", | |
| 371 | + }); | |
| 372 | + } | |
| 252 | 373 | }) |
| 253 | − .catch(() => { | |
| 374 | + .catch((cause) => { | |
| 254 | 375 | setStatus({ |
| 255 | − message: "Organization creation failed.", | |
| 376 | + message: errorMessage(cause, "Organization creation failed."), | |
| 256 | 377 | variant: "error", |
| 257 | 378 | }); |
| 258 | 379 | }) |
| @@ -261,137 +382,175 @@ export function WorkspaceSelector() { · 2 unmodified lines | ||
| 261 | 382 | }); |
| 262 | 383 | }; |
| 263 | 384 | |
| 264 | − const selectorDisabled = workspaces.state === "loading" || workspaces.items.length === 0; | |
| 385 | + const workspaceCreationDisabled = creatingWorkspace || !hasOrganizations; | |
| 386 | + const showEmptyState = workspaces.state !== "loading" && organizationGroups.length === 0; | |
| 387 | + const selectedOrganizationLabel = | |
| 388 | + workspaceOrganizationId.length > 0 | |
| 389 | + ? organizationNameById.get(workspaceOrganizationId) ?? workspaceOrganizationId | |
| 390 | + : null; | |
| 265 | 391 | |
| 266 | 392 | return ( |
| 267 | − <div className="space-y-2"> | |
| 268 | − <div> | |
| 269 | − <label className="block text-[10px] uppercase tracking-widest text-sidebar-foreground/50"> | |
| 270 | − Workspace | |
| 271 | − </label> | |
| 272 | − <p className="mt-0.5 truncate text-[10px] text-sidebar-foreground/50"> | |
| 273 | − {currentWorkspace ? currentOrganizationLabel : "Create your first workspace"} | |
| 274 | − </p> | |
| 275 | − </div> | |
| 276 | − | |
| 277 | − <Select | |
| 278 | − value={workspaceId} | |
| 279 | − onChange={(event) => { | |
| 280 | − setWorkspaceId(event.target.value); | |
| 393 | + <div ref={containerRef} className="relative"> | |
| 394 | + <button | |
| 395 | + type="button" | |
| 396 | + className="flex h-10 w-full items-center justify-between rounded-lg border border-sidebar-border bg-sidebar-active/55 px-2.5 text-left text-sidebar-foreground transition-colors hover:bg-sidebar-active/75" | |
| 397 | + onClick={() => { | |
| 281 | 398 | setStatus(defaultStatus()); |
| 399 | + setMenuOpen((open) => !open); | |
| 282 | 400 | }} |
| 283 | − disabled={selectorDisabled} | |
| 284 | − className="h-8 border-sidebar-border bg-sidebar-active/50 px-2 text-[12px] text-sidebar-foreground" | |
| 285 | 401 | > |
| 286 | − {workspaces.state === "loading" ? ( | |
| 287 | − <option value="">Loading workspaces...</option> | |
| 288 | − ) : null} | |
| 289 | − | |
| 290 | − {workspaces.state !== "loading" && workspaces.items.length === 0 ? ( | |
| 291 | − <option value="">No workspaces available</option> | |
| 292 | − ) : null} | |
| 293 | − | |
| 294 | − {workspaceGroups.map((group) => ( | |
| 295 | − <optgroup key={group.key} label={group.label}> | |
| 296 | − {group.workspaces.map((workspace) => ( | |
| 297 | − <option key={workspace.id} value={workspace.id}> | |
| 298 | − {workspace.name} | |
| 299 | − </option> | |
| 402 | + <span className="flex min-w-0 items-center gap-2"> | |
| 403 | + <span className="flex size-6 shrink-0 items-center justify-center rounded bg-sidebar-active text-[10px] font-semibold text-sidebar-foreground/80"> | |
| 404 | + {(currentWorkspaceLabel[0] ?? "W").toUpperCase()} | |
| 405 | + </span> | |
| 406 | + <span className="min-w-0"> | |
| 407 | + <span className="block truncate text-[10px] text-sidebar-foreground/55"> | |
| 408 | + {currentOrganizationLabel ?? "Create your first organization"} | |
| 409 | + </span> | |
| 410 | + <span className="block truncate text-[12px] font-medium"> | |
| 411 | + {currentWorkspaceLabel} | |
| 412 | + </span> | |
| 413 | + </span> | |
| 414 | + </span> | |
| 415 | + <ChevronsIcon className="ml-2 size-3.5 shrink-0 text-sidebar-foreground/60" /> | |
| 416 | + </button> | |
| 417 | + | |
| 418 | + {menuOpen ? ( | |
| 419 | + <div className="absolute left-0 top-[calc(100%+6px)] z-50 w-[300px] max-w-[calc(100vw-24px)] rounded-lg border border-sidebar-border bg-sidebar p-2 shadow-lg"> | |
| 420 | + <div className="max-h-56 space-y-2 overflow-y-auto"> | |
| 421 | + {workspaces.state === "loading" ? ( | |
| 422 | + <p className="px-1 text-[11px] text-sidebar-foreground/60">Loading workspaces...</p> | |
| 423 | + ) : null} | |
| 424 | + | |
| 425 | + {showEmptyState ? ( | |
| 426 | + <p className="px-1 text-[11px] text-sidebar-foreground/60">No workspaces yet.</p> | |
| 427 | + ) : null} | |
| 428 | + | |
| 429 | + {organizationGroups.map((group) => ( | |
| 430 | + <div key={group.organizationId} className="space-y-1 rounded-md border border-sidebar-border/70 p-1.5"> | |
| 431 | + <div className="flex items-center justify-between gap-2 px-1"> | |
| 432 | + <p className="truncate text-[10px] uppercase tracking-wider text-sidebar-foreground/45"> | |
| 433 | + {group.label} | |
| 434 | + </p> | |
| 435 | + <button | |
| 436 | + type="button" | |
| 437 | + className="inline-flex h-5 items-center gap-1 rounded border border-sidebar-border px-1.5 text-[10px] text-sidebar-foreground/70 transition-colors hover:bg-sidebar-active hover:text-sidebar-foreground" | |
| 438 | + onClick={() => openWorkspaceForm(group.organizationId)} | |
| 439 | + > | |
| 440 | + <PlusIcon className="size-2.5" /> | |
| 441 | + Workspace | |
| 442 | + </button> | |
| 443 | + </div> | |
| 444 | + | |
| 445 | + {group.workspaces.length === 0 ? ( | |
| 446 | + <p className="px-2 py-1 text-[11px] text-sidebar-foreground/55">No workspaces yet.</p> | |
| 447 | + ) : null} | |
| 448 | + | |
| 449 | + {group.workspaces.map((workspace) => ( | |
| 450 | + <button | |
| 451 | + key={workspace.id} | |
| 452 | + type="button" | |
| 453 | + className={cn( | |
| 454 | + "flex h-7 w-full items-center gap-1.5 rounded px-2 text-[12px] text-sidebar-foreground transition-colors", | |
| 455 | + workspace.id === workspaceId | |
| 456 | + ? "bg-sidebar-active" | |
| 457 | + : "hover:bg-sidebar-active/65", | |
| 458 | + )} | |
| 459 | + onClick={() => selectWorkspace(workspace.id)} | |
| 460 | + > | |
| 461 | + <CheckIcon | |
| 462 | + className={cn( | |
| 463 | + "size-3.5 shrink-0", | |
| 464 | + workspace.id === workspaceId ? "opacity-100" : "opacity-0", | |
| 465 | + )} | |
| 466 | + /> | |
| 467 | + <span className="truncate">{workspace.name}</span> | |
| 468 | + </button> | |
| 469 | + ))} | |
| 470 | + </div> | |
| 300 | 471 | ))} |
| 301 | − </optgroup> | |
| 302 | − ))} | |
| 303 | − </Select> | |
| 304 | − | |
| 305 | − <div className="flex gap-1"> | |
| 306 | − <Button | |
| 307 | − type="button" | |
| 308 | − size="sm" | |
| 309 | − variant={activeForm === "workspace" ? "secondary" : "ghost"} | |
| 310 | − className="h-7 flex-1 px-2 text-[11px]" | |
| 311 | − onClick={openWorkspaceForm} | |
| 312 | − > | |
| 313 | − + Workspace | |
| 314 | − </Button> | |
| 315 | − <Button | |
| 316 | − type="button" | |
| 317 | − size="sm" | |
| 318 | − variant={activeForm === "organization" ? "secondary" : "ghost"} | |
| 319 | − className="h-7 flex-1 px-2 text-[11px]" | |
| 320 | − onClick={openOrganizationForm} | |
| 321 | − > | |
| 322 | − + Org | |
| 323 | − </Button> | |
| 324 | − </div> | |
| 325 | − | |
| 326 | − {activeForm === "workspace" ? ( | |
| 327 | − <form className="space-y-1.5 rounded-md border border-sidebar-border p-2" onSubmit={handleCreateWorkspace}> | |
| 328 | − <Input | |
| 329 | − value={workspaceName} | |
| 330 | − onChange={(event) => setWorkspaceName(event.target.value)} | |
| 331 | − placeholder="Workspace name" | |
| 332 | − className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]" | |
| 333 | − maxLength={64} | |
| 334 | − /> | |
| 335 | − <Select | |
| 336 | − value={workspaceOrganizationId} | |
| 337 | − onChange={(event) => setWorkspaceOrganizationId(event.target.value)} | |
| 338 | − className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]" | |
| 339 | − > | |
| 340 | − <option value="">No organization</option> | |
| 341 | − {organizations.items.map((organization) => ( | |
| 342 | − <option key={organization.id} value={organization.id}> | |
| 343 | − {organization.name} | |
| 344 | − </option> | |
| 345 | − ))} | |
| 346 | − </Select> | |
| 347 | − <Button | |
| 348 | − type="submit" | |
| 349 | − size="sm" | |
| 350 | − className="h-7 w-full text-[11px]" | |
| 351 | − disabled={creatingWorkspace} | |
| 352 | − > | |
| 353 | − {creatingWorkspace ? "Creating..." : "Create workspace"} | |
| 354 | − </Button> | |
| 355 | − </form> | |
| 356 | − ) : null} | |
| 357 | − | |
| 358 | − {activeForm === "organization" ? ( | |
| 359 | − <form className="space-y-1.5 rounded-md border border-sidebar-border p-2" onSubmit={handleCreateOrganization}> | |
| 360 | − <Input | |
| 361 | − value={organizationName} | |
| 362 | − onChange={(event) => setOrganizationName(event.target.value)} | |
| 363 | − placeholder="Organization name" | |
| 364 | − className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]" | |
| 365 | − maxLength={64} | |
| 366 | − /> | |
| 367 | − <Input | |
| 368 | − value={organizationSlug} | |
| 369 | − onChange={(event) => setOrganizationSlug(event.target.value)} | |
| 370 | − placeholder="Slug (optional)" | |
| 371 | − className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]" | |
| 372 | − maxLength={64} | |
| 373 | − /> | |
| 374 | − <Button | |
| 375 | − type="submit" | |
| 376 | − size="sm" | |
| 377 | − className="h-7 w-full text-[11px]" | |
| 378 | − disabled={creatingOrganization} | |
| 379 | − > | |
| 380 | − {creatingOrganization ? "Creating..." : "Create organization"} | |
| 381 | − </Button> | |
| 382 | − </form> | |
| 383 | − ) : null} | |
| 384 | − | |
| 385 | − {workspaces.state === "error" ? ( | |
| 386 | − <p className="text-[11px] text-destructive">{workspaces.message}</p> | |
| 387 | − ) : null} | |
| 388 | − {organizations.state === "error" ? ( | |
| 389 | − <p className="text-[11px] text-destructive">{organizations.message}</p> | |
| 390 | − ) : null} | |
| 391 | − {status.message ? ( | |
| 392 | − <p className={status.variant === "error" ? "text-[11px] text-destructive" : "text-[11px] text-sidebar-foreground/70"}> | |
| 393 | − {status.message} | |
| 394 | − </p> | |
| 472 | + </div> | |
| 473 | + | |
| 474 | + <div className="mt-2 space-y-1 border-t border-sidebar-border pt-2"> | |
| 475 | + <Button | |
| 476 | + type="button" | |
| 477 | + size="sm" | |
| 478 | + variant={activeForm === "organization" ? "secondary" : "ghost"} | |
| 479 | + className="h-7 w-full px-2 text-[11px]" | |
| 480 | + onClick={openOrganizationForm} | |
| 481 | + > | |
| 482 | + <PlusIcon className="mr-1 size-3" /> | |
| 483 | + New organization | |
| 484 | + </Button> | |
| 485 | + | |
| 486 | + {activeForm === "workspace" ? ( | |
| 487 | + <form className="space-y-1.5 rounded-md border border-sidebar-border p-2" onSubmit={handleCreateWorkspace}> | |
| 488 | + <p className="truncate text-[10px] uppercase tracking-wider text-sidebar-foreground/45"> | |
| 489 | + {selectedOrganizationLabel ? `Create in ${selectedOrganizationLabel}` : "Select organization"} | |
| 490 | + </p> | |
| 491 | + <Input | |
| 492 | + value={workspaceName} | |
| 493 | + onChange={(event) => setWorkspaceName(event.target.value)} | |
| 494 | + placeholder="Workspace name" | |
| 495 | + className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]" | |
| 496 | + maxLength={64} | |
| 497 | + /> | |
| 498 | + <Button | |
| 499 | + type="submit" | |
| 500 | + size="sm" | |
| 501 | + className="h-7 w-full text-[11px]" | |
| 502 | + disabled={workspaceCreationDisabled} | |
| 503 | + > | |
| 504 | + {creatingWorkspace ? "Creating..." : "Create workspace"} | |
| 505 | + </Button> | |
| 506 | + </form> | |
| 507 | + ) : null} | |
| 508 | + | |
| 509 | + {activeForm === "organization" ? ( | |
| 510 | + <form className="space-y-1.5 rounded-md border border-sidebar-border p-2" onSubmit={handleCreateOrganization}> | |
| 511 | + <Input | |
| 512 | + value={organizationName} | |
| 513 | + onChange={(event) => setOrganizationName(event.target.value)} | |
| 514 | + placeholder="Organization name" | |
| 515 | + className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]" | |
| 516 | + maxLength={64} | |
| 517 | + /> | |
| 518 | + <Input | |
| 519 | + value={organizationSlug} | |
| 520 | + onChange={(event) => setOrganizationSlug(event.target.value)} | |
| 521 | + placeholder="Slug (optional)" | |
| 522 | + className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]" | |
| 523 | + maxLength={64} | |
| 524 | + /> | |
| 525 | + <Button | |
| 526 | + type="submit" | |
| 527 | + size="sm" | |
| 528 | + className="h-7 w-full text-[11px]" | |
| 529 | + disabled={creatingOrganization} | |
| 530 | + > | |
| 531 | + {creatingOrganization ? "Creating..." : "Create organization"} | |
| 532 | + </Button> | |
| 533 | + </form> | |
| 534 | + ) : null} | |
| 535 | + </div> | |
| 536 | + | |
| 537 | + {workspaces.state === "error" ? ( | |
| 538 | + <p className="mt-2 text-[11px] text-destructive">{workspaces.message}</p> | |
| 539 | + ) : null} | |
| 540 | + {organizations.state === "error" ? ( | |
| 541 | + <p className="mt-2 text-[11px] text-destructive">{organizations.message}</p> | |
| 542 | + ) : null} | |
| 543 | + {status.message ? ( | |
| 544 | + <p className={cn( | |
| 545 | + "mt-2 text-[11px]", | |
| 546 | + status.variant === "error" | |
| 547 | + ? "text-destructive" | |
| 548 | + : "text-sidebar-foreground/70", | |
| 549 | + )}> | |
| 550 | + {status.message} | |
| 551 | + </p> | |
| 552 | + ) : null} | |
| 553 | + </div> | |
| 395 | 554 | ) : null} |
| 396 | 555 | </div> |
| 397 | 556 | ); |
| @@ -65,6 +65,9 @@ type SourceGroup = { · 64 unmodified lines | ||
| 65 | 65 | toolCount: number; |
| 66 | 66 | }; |
| 67 | 67 | |
| 68 | +const configuredControlPlaneBaseUrl = | |
| 69 | + process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL?.trim() ?? ""; | |
| 70 | + | |
| 68 | 71 | // --------------------------------------------------------------------------- |
| 69 | 72 | // Search helpers (ported from old executor explorer-derived.ts) |
| 70 | 73 | // --------------------------------------------------------------------------- |
| @@ -317,7 +320,9 @@ const TOOL_DESCRIPTION_CLASSES = [ · 246 unmodified lines | ||
| 317 | 320 | // ToolsView (main export) |
| 318 | 321 | // --------------------------------------------------------------------------- |
| 319 | 322 | |
| 320 | −export function ToolsView() { | |
| 323 | +export function ToolsView(props: { | |
| 324 | + mcpBaseUrl: string | null; | |
| 325 | +}) { | |
| 321 | 326 | const { workspaceId } = useWorkspace(); |
| 322 | 327 | |
| 323 | 328 | // --- Data --- |
| @@ -366,14 +371,28 @@ export function ToolsView() { · 42 unmodified lines | ||
| 366 | 371 | const totalToolCount = workspaceTools.items.length; |
| 367 | 372 | |
| 368 | 373 | const mcpUrl = useMemo(() => { |
| 374 | + if (props.mcpBaseUrl) { | |
| 375 | + const configured = new URL(props.mcpBaseUrl); | |
| 376 | + configured.pathname = "/v1/mcp"; | |
| 377 | + configured.searchParams.set("workspaceId", workspaceId); | |
| 378 | + return configured.toString(); | |
| 379 | + } | |
| 380 | + | |
| 381 | + if (configuredControlPlaneBaseUrl.length > 0 && /^https?:\/\//i.test(configuredControlPlaneBaseUrl)) { | |
| 382 | + const configured = new URL(configuredControlPlaneBaseUrl); | |
| 383 | + configured.pathname = "/v1/mcp"; | |
| 384 | + configured.searchParams.set("workspaceId", workspaceId); | |
| 385 | + return configured.toString(); | |
| 386 | + } | |
| 387 | + | |
| 369 | 388 | if (typeof window === "undefined") { |
| 370 | − return `/v1/mcp?workspaceId=${encodeURIComponent(workspaceId)}`; | |
| 389 | + return `http://127.0.0.1:8788/v1/mcp?workspaceId=${encodeURIComponent(workspaceId)}`; | |
| 371 | 390 | } |
| 372 | 391 | |
| 373 | − const url = new URL("/v1/mcp", window.location.origin); | |
| 392 | + const url = new URL("/v1/mcp", "http://127.0.0.1:8788"); | |
| 374 | 393 | url.searchParams.set("workspaceId", workspaceId); |
| 375 | 394 | return url.toString(); |
| 376 | − }, [workspaceId]); | |
| 395 | + }, [props.mcpBaseUrl, workspaceId]); | |
| 377 | 396 | |
| 378 | 397 | const installConfig = useMemo( |
| 379 | 398 | () => getAddMcpInstallConfig(mcpUrl, inferServerName(workspaceId)), |
| @@ -66,11 +66,11 @@ export const upsertWorkspace = controlPlaneClient.mutation("workspaces", "upsert · 65 unmodified lines | ||
| 66 | 66 | |
| 67 | 67 | export const toWorkspaceUpsertPayload = (input: { |
| 68 | 68 | id?: Workspace["id"]; |
| 69 | − organizationId?: Workspace["organizationId"]; | |
| 69 | + organizationId: Workspace["organizationId"]; | |
| 70 | 70 | name: string; |
| 71 | 71 | }): UpsertWorkspacePayload => ({ |
| 72 | 72 | ...(input.id ? { id: input.id } : {}), |
| 73 | − ...(input.organizationId !== undefined ? { organizationId: input.organizationId } : {}), | |
| 73 | + organizationId: input.organizationId, | |
| 74 | 74 | name: input.name, |
| 75 | 75 | }); |
| 76 | 76 | |
| @@ -1,12 +1,21 @@ | ||
| 1 | 1 | import { createControlPlaneAtomClient } from "@executor-v2/management-api/client"; |
| 2 | 2 | import { ControlPlaneAuthHeaders } from "@executor-v2/management-api/auth/principal"; |
| 3 | 3 | |
| 4 | +const trim = (value: string | undefined): string | undefined => { | |
| 5 | + const candidate = value?.trim(); | |
| 6 | + return candidate && candidate.length > 0 ? candidate : undefined; | |
| 7 | +}; | |
| 8 | + | |
| 9 | +const defaultControlPlaneBaseUrl = "http://127.0.0.1:8788"; | |
| 10 | + | |
| 4 | 11 | const controlPlaneBaseUrl = |
| 5 | 12 | typeof window === "undefined" |
| 6 | − ? process.env.CONTROL_PLANE_SERVER_BASE_URL ?? | |
| 7 | − process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL ?? | |
| 8 | − "http://127.0.0.1:4312/api/control-plane" | |
| 9 | − : process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL ?? "/api/control-plane"; | |
| 13 | + ? trim(process.env.CONTROL_PLANE_SERVER_BASE_URL) | |
| 14 | + ?? trim(process.env.CONTROL_PLANE_UPSTREAM_URL) | |
| 15 | + ?? trim(process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL) | |
| 16 | + ?? defaultControlPlaneBaseUrl | |
| 17 | + : trim(process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL) | |
| 18 | + ?? defaultControlPlaneBaseUrl; | |
| 10 | 19 | |
| 11 | 20 | const controlPlaneAccountId = process.env.NEXT_PUBLIC_CONTROL_PLANE_ACCOUNT_ID; |
| 12 | 21 | |
| @@ -42,7 +42,7 @@ · 41 unmodified lines | ||
| 42 | 42 | "@executor-v2/management-api": "workspace:*", |
| 43 | 43 | "@executor-v2/mcp-gateway": "workspace:*", |
| 44 | 44 | "@executor-v2/persistence-ports": "workspace:*", |
| 45 | − "@executor-v2/runtime-local-inproc": "workspace:*", | |
| 45 | + "@executor-v2/runtime-cloudflare-worker-loader": "workspace:*", | |
| 46 | 46 | "@executor-v2/schema": "workspace:*", |
| 47 | 47 | "@executor-v2/sdk": "workspace:*", |
| 48 | 48 | "convex": "catalog:", |
| @@ -183,6 +183,7 @@ · 134 unmodified lines | ||
| 183 | 183 | "@executor-v2/persistence-ports": "workspace:*", |
| 184 | 184 | "@executor-v2/schema": "workspace:*", |
| 185 | 185 | "@executor-v2/sdk": "workspace:*", |
| 186 | + "@modelcontextprotocol/sdk": "^1.26.0", | |
| 186 | 187 | "effect": "catalog:", |
| 187 | 188 | }, |
| 188 | 189 | "devDependencies": { |
| @@ -14,6 +14,7 @@ · 13 unmodified lines | ||
| 14 | 14 | "@executor-v2/persistence-ports": "workspace:*", |
| 15 | 15 | "@executor-v2/schema": "workspace:*", |
| 16 | 16 | "@executor-v2/sdk": "workspace:*", |
| 17 | + "@modelcontextprotocol/sdk": "^1.26.0", | |
| 17 | 18 | "effect": "catalog:" |
| 18 | 19 | }, |
| 19 | 20 | "devDependencies": { |
| @@ -0,0 +1,210 @@ | ||
| 1 | +import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; | |
| 2 | + | |
| 3 | +import { describe, expect, it } from "@effect/vitest"; | |
| 4 | +import { SourceSchema } from "@executor-v2/schema"; | |
| 5 | +import * as Data from "effect/Data"; | |
| 6 | +import * as Effect from "effect/Effect"; | |
| 7 | +import * as Schema from "effect/Schema"; | |
| 8 | + | |
| 9 | +import { makeGraphqlToolProvider } from "./graphql-provider"; | |
| 10 | + | |
| 11 | +const decodeSource = Schema.decodeUnknownSync(SourceSchema); | |
| 12 | + | |
| 13 | +type TestServer = { | |
| 14 | + endpoint: string; | |
| 15 | + requests: Array<{ | |
| 16 | + headers: Record<string, string>; | |
| 17 | + body: Record<string, unknown>; | |
| 18 | + }>; | |
| 19 | + close: () => Promise<void>; | |
| 20 | +}; | |
| 21 | + | |
| 22 | +class GraphqlProviderTestServerReleaseError extends Data.TaggedError( | |
| 23 | + "GraphqlProviderTestServerReleaseError", | |
| 24 | +)<{ | |
| 25 | + message: string; | |
| 26 | +}> {} | |
| 27 | + | |
| 28 | +const getHeader = (request: IncomingMessage, key: string): string | null => { | |
| 29 | + const value = request.headers[key]; | |
| 30 | + if (typeof value === "string") { | |
| 31 | + return value; | |
| 32 | + } | |
| 33 | + | |
| 34 | + if (Array.isArray(value)) { | |
| 35 | + return value[0] ?? null; | |
| 36 | + } | |
| 37 | + | |
| 38 | + return null; | |
| 39 | +}; | |
| 40 | + | |
| 41 | +const json = (response: ServerResponse, body: unknown): void => { | |
| 42 | + response.statusCode = 200; | |
| 43 | + response.setHeader("content-type", "application/json"); | |
| 44 | + response.end(JSON.stringify(body)); | |
| 45 | +}; | |
| 46 | + | |
| 47 | +const makeGraphqlTestServer = Effect.acquireRelease( | |
| 48 | + Effect.promise<TestServer>( | |
| 49 | + () => | |
| 50 | + new Promise<TestServer>((resolve, reject) => { | |
| 51 | + const requests: TestServer["requests"] = []; | |
| 52 | + | |
| 53 | + const server = createServer(async (request, response) => { | |
| 54 | + if (request.method !== "POST") { | |
| 55 | + response.statusCode = 405; | |
| 56 | + response.end(); | |
| 57 | + return; | |
| 58 | + } | |
| 59 | + | |
| 60 | + const chunks: Array<Buffer> = []; | |
| 61 | + for await (const chunk of request) { | |
| 62 | + chunks.push(Buffer.from(chunk)); | |
| 63 | + } | |
| 64 | + | |
| 65 | + const rawBody = Buffer.concat(chunks).toString("utf8"); | |
| 66 | + const parsedBody = JSON.parse(rawBody) as Record<string, unknown>; | |
| 67 | + requests.push({ | |
| 68 | + headers: { | |
| 69 | + "x-api-key": getHeader(request, "x-api-key") ?? "", | |
| 70 | + "x-extra": getHeader(request, "x-extra") ?? "", | |
| 71 | + }, | |
| 72 | + body: parsedBody, | |
| 73 | + }); | |
| 74 | + | |
| 75 | + const query = typeof parsedBody.query === "string" ? parsedBody.query : ""; | |
| 76 | + if (query.includes("errorCase")) { | |
| 77 | + json(response, { | |
| 78 | + errors: [{ message: "boom" }], | |
| 79 | + }); | |
| 80 | + return; | |
| 81 | + } | |
| 82 | + | |
| 83 | + json(response, { | |
| 84 | + data: { | |
| 85 | + ok: true, | |
| 86 | + }, | |
| 87 | + }); | |
| 88 | + }); | |
| 89 | + | |
| 90 | + server.once("error", (error) => reject(error)); | |
| 91 | + server.listen(0, "127.0.0.1", () => { | |
| 92 | + const address = server.address(); | |
| 93 | + if (!address || typeof address === "string") { | |
| 94 | + reject(new Error("Failed to resolve GraphQL test server address")); | |
| 95 | + return; | |
| 96 | + } | |
| 97 | + | |
| 98 | + resolve({ | |
| 99 | + endpoint: `http://127.0.0.1:${address.port}/graphql`, | |
| 100 | + requests, | |
| 101 | + close: () => | |
| 102 | + new Promise<void>((closeResolve, closeReject) => { | |
| 103 | + server.close((error) => { | |
| 104 | + if (error) { | |
| 105 | + closeReject(error); | |
| 106 | + return; | |
| 107 | + } | |
| 108 | + closeResolve(); | |
| 109 | + }); | |
| 110 | + }), | |
| 111 | + }); | |
| 112 | + }); | |
| 113 | + }), | |
| 114 | + ), | |
| 115 | + (server) => | |
| 116 | + Effect.tryPromise({ | |
| 117 | + try: () => server.close(), | |
| 118 | + catch: (cause) => | |
| 119 | + new GraphqlProviderTestServerReleaseError({ | |
| 120 | + message: cause instanceof Error ? cause.message : String(cause), | |
| 121 | + }), | |
| 122 | + }).pipe(Effect.orDie), | |
| 123 | +); | |
| 124 | + | |
| 125 | +describe("makeGraphqlToolProvider", () => { | |
| 126 | + it.scoped("discovers a request tool and invokes GraphQL operations", () => | |
| 127 | + Effect.gen(function* () { | |
| 128 | + const testServer = yield* makeGraphqlTestServer; | |
| 129 | + const provider = makeGraphqlToolProvider(); | |
| 130 | + | |
| 131 | + const source = decodeSource({ | |
| 132 | + id: "src_graphql", | |
| 133 | + workspaceId: "ws_local", | |
| 134 | + name: "GraphQL Source", | |
| 135 | + kind: "graphql", | |
| 136 | + endpoint: "https://fallback.example/graphql", | |
| 137 | + status: "connected", | |
| 138 | + enabled: true, | |
| 139 | + configJson: JSON.stringify({ | |
| 140 | + endpoint: testServer.endpoint, | |
| 141 | + headers: { | |
| 142 | + "x-api-key": "secret", | |
| 143 | + }, | |
| 144 | + }), | |
| 145 | + sourceHash: "source_hash", | |
| 146 | + lastError: null, | |
| 147 | + createdAt: Date.now(), | |
| 148 | + updatedAt: Date.now(), | |
| 149 | + }); | |
| 150 | + | |
| 151 | + const discovered = yield* provider.discoverFromSource!(source); | |
| 152 | + expect(discovered.sourceHash).toBe("source_hash"); | |
| 153 | + expect(discovered.tools).toHaveLength(1); | |
| 154 | + expect(discovered.tools[0]?.toolId).toBe("request"); | |
| 155 | + | |
| 156 | + const tool = discovered.tools[0]!; | |
| 157 | + const success = yield* provider.invoke({ | |
| 158 | + source, | |
| 159 | + tool, | |
| 160 | + args: { | |
| 161 | + query: "query viewer { viewer { id } }", | |
| 162 | + variables: { | |
| 163 | + includePrivate: false, | |
| 164 | + }, | |
| 165 | + operationName: "viewer", | |
| 166 | + headers: { | |
| 167 | + "x-extra": "extra", | |
| 168 | + }, | |
| 169 | + }, | |
| 170 | + }); | |
| 171 | + | |
| 172 | + expect(success.isError).toBe(false); | |
| 173 | + expect(success.output).toMatchObject({ | |
| 174 | + status: 200, | |
| 175 | + body: { | |
| 176 | + data: { | |
| 177 | + ok: true, | |
| 178 | + }, | |
| 179 | + }, | |
| 180 | + }); | |
| 181 | + | |
| 182 | + const failing = yield* provider.invoke({ | |
| 183 | + source, | |
| 184 | + tool, | |
| 185 | + args: { | |
| 186 | + query: "query errorCase { viewer { id } }", | |
| 187 | + }, | |
| 188 | + }); | |
| 189 | + | |
| 190 | + expect(failing.isError).toBe(true); | |
| 191 | + expect(failing.output).toMatchObject({ | |
| 192 | + status: 200, | |
| 193 | + body: { | |
| 194 | + errors: [{ message: "boom" }], | |
| 195 | + }, | |
| 196 | + }); | |
| 197 | + | |
| 198 | + expect(testServer.requests).toHaveLength(2); | |
| 199 | + expect(testServer.requests[0]?.headers["x-api-key"]).toBe("secret"); | |
| 200 | + expect(testServer.requests[0]?.headers["x-extra"]).toBe("extra"); | |
| 201 | + expect(testServer.requests[0]?.body).toMatchObject({ | |
| 202 | + query: "query viewer { viewer { id } }", | |
| 203 | + variables: { | |
| 204 | + includePrivate: false, | |
| 205 | + }, | |
| 206 | + operationName: "viewer", | |
| 207 | + }); | |
| 208 | + }), | |
| 209 | + ); | |
| 210 | +}); | |
| @@ -0,0 +1,195 @@ | ||
| 1 | +import type { | |
| 2 | + CanonicalToolDescriptor, | |
| 3 | + Source, | |
| 4 | +} from "@executor-v2/schema"; | |
| 5 | +import * as Effect from "effect/Effect"; | |
| 6 | +import * as ParseResult from "effect/ParseResult"; | |
| 7 | +import * as Schema from "effect/Schema"; | |
| 8 | + | |
| 9 | +import { | |
| 10 | + collectSourceHeaders, | |
| 11 | + parseSourceConfig, | |
| 12 | + readStringRecord, | |
| 13 | + resolveSourceEndpoint, | |
| 14 | +} from "./source-config"; | |
| 15 | +import { ToolProviderError, type ToolProvider } from "./tool-providers"; | |
| 16 | + | |
| 17 | +const GraphqlInvocationPayloadSchema = Schema.Struct({ | |
| 18 | + kind: Schema.Literal("graphql_request"), | |
| 19 | +}); | |
| 20 | + | |
| 21 | +const GraphqlInvokeArgsSchema = Schema.Struct({ | |
| 22 | + query: Schema.String, | |
| 23 | + variables: Schema.optional( | |
| 24 | + Schema.Record({ | |
| 25 | + key: Schema.String, | |
| 26 | + value: Schema.Unknown, | |
| 27 | + }), | |
| 28 | + ), | |
| 29 | + operationName: Schema.optional(Schema.String), | |
| 30 | + headers: Schema.optional( | |
| 31 | + Schema.Record({ | |
| 32 | + key: Schema.String, | |
| 33 | + value: Schema.String, | |
| 34 | + }), | |
| 35 | + ), | |
| 36 | +}); | |
| 37 | + | |
| 38 | +const decodeGraphqlInvocationPayload = Schema.decodeUnknown(GraphqlInvocationPayloadSchema); | |
| 39 | +const decodeGraphqlInvokeArgs = Schema.decodeUnknown(GraphqlInvokeArgsSchema); | |
| 40 | + | |
| 41 | +const toGraphqlProviderError = ( | |
| 42 | + operation: string, | |
| 43 | + message: string, | |
| 44 | + cause: unknown, | |
| 45 | +): ToolProviderError => | |
| 46 | + new ToolProviderError({ | |
| 47 | + operation, | |
| 48 | + providerKind: "graphql", | |
| 49 | + message, | |
| 50 | + details: ParseResult.isParseError(cause) | |
| 51 | + ? ParseResult.TreeFormatter.formatErrorSync(cause) | |
| 52 | + : String(cause), | |
| 53 | + }); | |
| 54 | + | |
| 55 | +const parseGraphqlResponseBody = ( | |
| 56 | + response: Response, | |
| 57 | +): Effect.Effect<unknown, ToolProviderError> => | |
| 58 | + Effect.tryPromise({ | |
| 59 | + try: async () => { | |
| 60 | + const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""; | |
| 61 | + if (contentType.includes("application/json")) { | |
| 62 | + return await response.json(); | |
| 63 | + } | |
| 64 | + | |
| 65 | + return await response.text(); | |
| 66 | + }, | |
| 67 | + catch: (cause) => | |
| 68 | + toGraphqlProviderError( | |
| 69 | + "invoke.decode_response", | |
| 70 | + "Failed to decode GraphQL response body", | |
| 71 | + cause, | |
| 72 | + ), | |
| 73 | + }); | |
| 74 | + | |
| 75 | +const hasGraphqlErrors = (value: unknown): boolean => { | |
| 76 | + if (!value || typeof value !== "object" || Array.isArray(value)) { | |
| 77 | + return false; | |
| 78 | + } | |
| 79 | + | |
| 80 | + return Array.isArray((value as { errors?: unknown }).errors); | |
| 81 | +}; | |
| 82 | + | |
| 83 | +const descriptorForSource = (source: Source): CanonicalToolDescriptor => ({ | |
| 84 | + providerKind: "graphql", | |
| 85 | + sourceId: source.id, | |
| 86 | + workspaceId: source.workspaceId, | |
| 87 | + toolId: "request", | |
| 88 | + name: "GraphQL request", | |
| 89 | + description: "Execute a GraphQL operation with args.query, args.variables, and args.operationName.", | |
| 90 | + invocationMode: "graphql", | |
| 91 | + availability: "remote_capable", | |
| 92 | + providerPayload: { | |
| 93 | + kind: "graphql_request", | |
| 94 | + }, | |
| 95 | +}); | |
| 96 | + | |
| 97 | +export const makeGraphqlToolProvider = (): ToolProvider => ({ | |
| 98 | + kind: "graphql", | |
| 99 | + | |
| 100 | + discoverFromSource: (source) => | |
| 101 | + Effect.succeed({ | |
| 102 | + sourceHash: source.sourceHash, | |
| 103 | + tools: [descriptorForSource(source)], | |
| 104 | + }), | |
| 105 | + | |
| 106 | + invoke: (input) => | |
| 107 | + Effect.gen(function* () { | |
| 108 | + if (!input.source) { | |
| 109 | + return yield* new ToolProviderError({ | |
| 110 | + operation: "invoke.validate_source", | |
| 111 | + providerKind: "graphql", | |
| 112 | + message: "GraphQL provider requires a source", | |
| 113 | + details: null, | |
| 114 | + }); | |
| 115 | + } | |
| 116 | + const source = input.source; | |
| 117 | + | |
| 118 | + yield* decodeGraphqlInvocationPayload(input.tool.providerPayload).pipe( | |
| 119 | + Effect.mapError((cause) => | |
| 120 | + toGraphqlProviderError( | |
| 121 | + "invoke.decode_payload", | |
| 122 | + `Invalid GraphQL invocation payload for tool: ${input.tool.toolId}`, | |
| 123 | + cause, | |
| 124 | + ), | |
| 125 | + ), | |
| 126 | + ); | |
| 127 | + | |
| 128 | + const args = yield* decodeGraphqlInvokeArgs(input.args).pipe( | |
| 129 | + Effect.mapError((cause) => | |
| 130 | + toGraphqlProviderError( | |
| 131 | + "invoke.decode_args", | |
| 132 | + `Invalid GraphQL args for tool: ${input.tool.toolId}`, | |
| 133 | + cause, | |
| 134 | + ), | |
| 135 | + ), | |
| 136 | + ); | |
| 137 | + | |
| 138 | + const query = args.query.trim(); | |
| 139 | + if (query.length === 0) { | |
| 140 | + return yield* new ToolProviderError({ | |
| 141 | + operation: "invoke.validate_args", | |
| 142 | + providerKind: "graphql", | |
| 143 | + message: "GraphQL query must be non-empty", | |
| 144 | + details: input.tool.toolId, | |
| 145 | + }); | |
| 146 | + } | |
| 147 | + | |
| 148 | + const config = parseSourceConfig(source); | |
| 149 | + const endpoint = resolveSourceEndpoint(source, config, ["endpoint", "url"]); | |
| 150 | + if (endpoint.trim().length === 0) { | |
| 151 | + return yield* new ToolProviderError({ | |
| 152 | + operation: "invoke.validate_source", | |
| 153 | + providerKind: "graphql", | |
| 154 | + message: "GraphQL source endpoint is required", | |
| 155 | + details: source.id, | |
| 156 | + }); | |
| 157 | + } | |
| 158 | + | |
| 159 | + const headers = new Headers({ | |
| 160 | + "content-type": "application/json", | |
| 161 | + ...collectSourceHeaders(config), | |
| 162 | + ...readStringRecord(args.headers), | |
| 163 | + }); | |
| 164 | + | |
| 165 | + const response = yield* Effect.tryPromise({ | |
| 166 | + try: () => | |
| 167 | + fetch(endpoint, { | |
| 168 | + method: "POST", | |
| 169 | + headers, | |
| 170 | + body: JSON.stringify({ | |
| 171 | + query, | |
| 172 | + variables: args.variables, | |
| 173 | + operationName: args.operationName, | |
| 174 | + }), | |
| 175 | + }), | |
| 176 | + catch: (cause) => | |
| 177 | + toGraphqlProviderError( | |
| 178 | + "invoke.http_request", | |
| 179 | + `GraphQL request failed for source: ${source.name}`, | |
| 180 | + cause, | |
| 181 | + ), | |
| 182 | + }); | |
| 183 | + | |
| 184 | + const body = yield* parseGraphqlResponseBody(response); | |
| 185 | + | |
| 186 | + return { | |
| 187 | + output: { | |
| 188 | + status: response.status, | |
| 189 | + headers: Object.fromEntries(response.headers.entries()), | |
| 190 | + body, | |
| 191 | + }, | |
| 192 | + isError: response.status >= 400 || hasGraphqlErrors(body), | |
| 193 | + }; | |
| 194 | + }), | |
| 195 | +}); | |
| @@ -66,6 +66,8 @@ export { · 65 unmodified lines | ||
| 66 | 66 | makeOpenApiToolProvider, |
| 67 | 67 | openApiToolDescriptorsFromManifest, |
| 68 | 68 | } from "./openapi-provider"; |
| 69 | +export { makeMcpToolProvider, type MakeMcpToolProviderOptions } from "./mcp-provider"; | |
| 70 | +export { makeGraphqlToolProvider } from "./graphql-provider"; | |
| 69 | 71 | |
| 70 | 72 | export { |
| 71 | 73 | ToolProviderRegistryLive, |
| @@ -0,0 +1,143 @@ | ||
| 1 | +import { describe, expect, it } from "@effect/vitest"; | |
| 2 | +import { SourceSchema, type CanonicalToolDescriptor } from "@executor-v2/schema"; | |
| 3 | +import * as Effect from "effect/Effect"; | |
| 4 | +import * as Schema from "effect/Schema"; | |
| 5 | + | |
| 6 | +import { makeMcpToolProvider } from "./mcp-provider"; | |
| 7 | + | |
| 8 | +const decodeSource = Schema.decodeUnknownSync(SourceSchema); | |
| 9 | + | |
| 10 | +describe("makeMcpToolProvider", () => { | |
| 11 | + it.effect("discovers MCP tools and produces stable unique tool ids", () => | |
| 12 | + Effect.gen(function* () { | |
| 13 | + let closeCalls = 0; | |
| 14 | + | |
| 15 | + const provider = makeMcpToolProvider({ | |
| 16 | + connector: async (input) => { | |
| 17 | + expect(input.endpoint).toBe("https://mcp.example/mcp"); | |
| 18 | + expect(input.transport).toBe("streamable-http"); | |
| 19 | + expect(input.queryParams).toEqual({ | |
| 20 | + workspace: "ws_local", | |
| 21 | + }); | |
| 22 | + | |
| 23 | + return { | |
| 24 | + client: { | |
| 25 | + listTools: async () => ({ | |
| 26 | + tools: [ | |
| 27 | + { name: "Read File", description: "Reads a file" }, | |
| 28 | + { name: "Read.File", description: "Also reads a file" }, | |
| 29 | + { name: "List Users", description: null }, | |
| 30 | + ], | |
| 31 | + }), | |
| 32 | + callTool: async () => ({ | |
| 33 | + content: [{ type: "text", text: "ok" }], | |
| 34 | + isError: false, | |
| 35 | + }), | |
| 36 | + }, | |
| 37 | + close: async () => { | |
| 38 | + closeCalls += 1; | |
| 39 | + }, | |
| 40 | + }; | |
| 41 | + }, | |
| 42 | + }); | |
| 43 | + | |
| 44 | + const source = decodeSource({ | |
| 45 | + id: "src_mcp", | |
| 46 | + workspaceId: "ws_local", | |
| 47 | + name: "MCP Source", | |
| 48 | + kind: "mcp", | |
| 49 | + endpoint: "https://fallback.example/mcp", | |
| 50 | + status: "connected", | |
| 51 | + enabled: true, | |
| 52 | + configJson: JSON.stringify({ | |
| 53 | + url: "https://mcp.example/mcp", | |
| 54 | + transport: "streamable-http", | |
| 55 | + queryParams: { | |
| 56 | + workspace: "ws_local", | |
| 57 | + }, | |
| 58 | + }), | |
| 59 | + sourceHash: "hash_1", | |
| 60 | + lastError: null, | |
| 61 | + createdAt: Date.now(), | |
| 62 | + updatedAt: Date.now(), | |
| 63 | + }); | |
| 64 | + | |
| 65 | + const discovered = yield* provider.discoverFromSource!(source); | |
| 66 | + expect(discovered.sourceHash).toBe("hash_1"); | |
| 67 | + expect(discovered.tools.map((tool) => tool.toolId)).toEqual([ | |
| 68 | + "read_file", | |
| 69 | + "read_file_2", | |
| 70 | + "list_users", | |
| 71 | + ]); | |
| 72 | + expect(closeCalls).toBe(1); | |
| 73 | + }), | |
| 74 | + ); | |
| 75 | + | |
| 76 | + it.effect("invokes MCP tool and propagates isError from MCP result payload", () => | |
| 77 | + Effect.gen(function* () { | |
| 78 | + const provider = makeMcpToolProvider({ | |
| 79 | + connector: async () => ({ | |
| 80 | + client: { | |
| 81 | + listTools: async () => ({ tools: [] }), | |
| 82 | + callTool: async (input) => { | |
| 83 | + expect(input.name).toBe("echo"); | |
| 84 | + expect(input.arguments).toEqual({ | |
| 85 | + value: "hello", | |
| 86 | + }); | |
| 87 | + | |
| 88 | + return { | |
| 89 | + isError: true, | |
| 90 | + content: [{ type: "text", text: "denied" }], | |
| 91 | + }; | |
| 92 | + }, | |
| 93 | + }, | |
| 94 | + close: async () => undefined, | |
| 95 | + }), | |
| 96 | + }); | |
| 97 | + | |
| 98 | + const source = decodeSource({ | |
| 99 | + id: "src_mcp", | |
| 100 | + workspaceId: "ws_local", | |
| 101 | + name: "MCP Source", | |
| 102 | + kind: "mcp", | |
| 103 | + endpoint: "https://mcp.example/mcp", | |
| 104 | + status: "connected", | |
| 105 | + enabled: true, | |
| 106 | + configJson: "{}", | |
| 107 | + sourceHash: null, | |
| 108 | + lastError: null, | |
| 109 | + createdAt: Date.now(), | |
| 110 | + updatedAt: Date.now(), | |
| 111 | + }); | |
| 112 | + | |
| 113 | + const tool: CanonicalToolDescriptor = { | |
| 114 | + providerKind: "mcp", | |
| 115 | + sourceId: source.id, | |
| 116 | + workspaceId: source.workspaceId, | |
| 117 | + toolId: "echo", | |
| 118 | + name: "Echo", | |
| 119 | + description: null, | |
| 120 | + invocationMode: "mcp", | |
| 121 | + availability: "remote_capable", | |
| 122 | + providerPayload: { | |
| 123 | + kind: "mcp_tool", | |
| 124 | + toolName: "echo", | |
| 125 | + }, | |
| 126 | + }; | |
| 127 | + | |
| 128 | + const result = yield* provider.invoke({ | |
| 129 | + source, | |
| 130 | + tool, | |
| 131 | + args: { | |
| 132 | + value: "hello", | |
| 133 | + }, | |
| 134 | + }); | |
| 135 | + | |
| 136 | + expect(result.isError).toBe(true); | |
| 137 | + expect(result.output).toEqual({ | |
| 138 | + isError: true, | |
| 139 | + content: [{ type: "text", text: "denied" }], | |
| 140 | + }); | |
| 141 | + }), | |
| 142 | + ); | |
| 143 | +}); | |
| @@ -0,0 +1,389 @@ | ||
| 1 | +import { | |
| 2 | + type CanonicalToolDescriptor, | |
| 3 | + type Source, | |
| 4 | +} from "@executor-v2/schema"; | |
| 5 | +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; | |
| 6 | +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; | |
| 7 | +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; | |
| 8 | +import * as Effect from "effect/Effect"; | |
| 9 | +import * as ParseResult from "effect/ParseResult"; | |
| 10 | +import * as Schema from "effect/Schema"; | |
| 11 | + | |
| 12 | +import { | |
| 13 | + collectSourceHeaders, | |
| 14 | + parseSourceConfig, | |
| 15 | + readMcpTransportFromConfig, | |
| 16 | + readQueryParamsFromConfig, | |
| 17 | + resolveSourceEndpoint, | |
| 18 | + type McpTransportPreference, | |
| 19 | +} from "./source-config"; | |
| 20 | +import { ToolProviderError, type ToolProvider } from "./tool-providers"; | |
| 21 | + | |
| 22 | +type McpClientLike = { | |
| 23 | + listTools: () => Promise<unknown>; | |
| 24 | + callTool: (input: { name: string; arguments: Record<string, unknown> }) => Promise<unknown>; | |
| 25 | +}; | |
| 26 | + | |
| 27 | +type McpConnection = { | |
| 28 | + client: McpClientLike; | |
| 29 | + close: () => Promise<void>; | |
| 30 | +}; | |
| 31 | + | |
| 32 | +type McpConnectorInput = { | |
| 33 | + endpoint: string; | |
| 34 | + transport: McpTransportPreference; | |
| 35 | + queryParams: Record<string, string>; | |
| 36 | + headers: Record<string, string>; | |
| 37 | +}; | |
| 38 | + | |
| 39 | +export type McpConnector = (input: McpConnectorInput) => Promise<McpConnection>; | |
| 40 | + | |
| 41 | +type McpToolSummary = { | |
| 42 | + name: string; | |
| 43 | + description: string | null; | |
| 44 | +}; | |
| 45 | + | |
| 46 | +const McpInvocationPayloadSchema = Schema.Struct({ | |
| 47 | + kind: Schema.Literal("mcp_tool"), | |
| 48 | + toolName: Schema.String, | |
| 49 | +}); | |
| 50 | + | |
| 51 | +const McpInvokeArgsSchema = Schema.Record({ | |
| 52 | + key: Schema.String, | |
| 53 | + value: Schema.Unknown, | |
| 54 | +}); | |
| 55 | + | |
| 56 | +const decodeMcpInvocationPayload = Schema.decodeUnknown(McpInvocationPayloadSchema); | |
| 57 | +const decodeMcpInvokeArgs = Schema.decodeUnknown(McpInvokeArgsSchema); | |
| 58 | + | |
| 59 | +const toMcpProviderError = ( | |
| 60 | + operation: string, | |
| 61 | + message: string, | |
| 62 | + cause: unknown, | |
| 63 | +): ToolProviderError => | |
| 64 | + new ToolProviderError({ | |
| 65 | + operation, | |
| 66 | + providerKind: "mcp", | |
| 67 | + message, | |
| 68 | + details: ParseResult.isParseError(cause) | |
| 69 | + ? ParseResult.TreeFormatter.formatErrorSync(cause) | |
| 70 | + : String(cause), | |
| 71 | + }); | |
| 72 | + | |
| 73 | +const mergeHeadersForFetch = ( | |
| 74 | + input: RequestInfo | URL, | |
| 75 | + init: RequestInit | undefined, | |
| 76 | + headers: Record<string, string>, | |
| 77 | +): Promise<Response> => { | |
| 78 | + const mergedHeaders = new Headers(init?.headers ?? {}); | |
| 79 | + | |
| 80 | + for (const [key, value] of Object.entries(headers)) { | |
| 81 | + mergedHeaders.set(key, value); | |
| 82 | + } | |
| 83 | + | |
| 84 | + return fetch(input, { | |
| 85 | + ...init, | |
| 86 | + headers: mergedHeaders, | |
| 87 | + }); | |
| 88 | +}; | |
| 89 | + | |
| 90 | +const createEndpoint = ( | |
| 91 | + endpoint: string, | |
| 92 | + queryParams: Record<string, string>, | |
| 93 | +): URL => { | |
| 94 | + const url = new URL(endpoint); | |
| 95 | + | |
| 96 | + for (const [key, value] of Object.entries(queryParams)) { | |
| 97 | + url.searchParams.set(key, value); | |
| 98 | + } | |
| 99 | + | |
| 100 | + return url; | |
| 101 | +}; | |
| 102 | + | |
| 103 | +const connectMcpWithSdk: McpConnector = async (input) => { | |
| 104 | + const endpoint = createEndpoint(input.endpoint, input.queryParams); | |
| 105 | + const requestInit = Object.keys(input.headers).length > 0 | |
| 106 | + ? { headers: input.headers } | |
| 107 | + : undefined; | |
| 108 | + | |
| 109 | + const client = new Client( | |
| 110 | + { | |
| 111 | + name: "executor-v2-engine", | |
| 112 | + version: "0.1.0", | |
| 113 | + }, | |
| 114 | + { capabilities: {} }, | |
| 115 | + ); | |
| 116 | + | |
| 117 | + if (input.transport === "sse") { | |
| 118 | + await client.connect(new SSEClientTransport(endpoint, { | |
| 119 | + requestInit, | |
| 120 | + eventSourceInit: requestInit | |
| 121 | + ? { | |
| 122 | + fetch: (requestInput, requestOptions) => | |
| 123 | + mergeHeadersForFetch(requestInput, requestOptions, input.headers), | |
| 124 | + } | |
| 125 | + : undefined, | |
| 126 | + })); | |
| 127 | + | |
| 128 | + return { | |
| 129 | + client, | |
| 130 | + close: () => client.close(), | |
| 131 | + }; | |
| 132 | + } | |
| 133 | + | |
| 134 | + if (input.transport === "streamable-http") { | |
| 135 | + await client.connect(new StreamableHTTPClientTransport(endpoint, { | |
| 136 | + requestInit, | |
| 137 | + })); | |
| 138 | + | |
| 139 | + return { | |
| 140 | + client, | |
| 141 | + close: () => client.close(), | |
| 142 | + }; | |
| 143 | + } | |
| 144 | + | |
| 145 | + try { | |
| 146 | + await client.connect(new StreamableHTTPClientTransport(endpoint, { | |
| 147 | + requestInit, | |
| 148 | + })); | |
| 149 | + | |
| 150 | + return { | |
| 151 | + client, | |
| 152 | + close: () => client.close(), | |
| 153 | + }; | |
| 154 | + } catch { | |
| 155 | + await client.connect(new SSEClientTransport(endpoint, { | |
| 156 | + requestInit, | |
| 157 | + eventSourceInit: requestInit | |
| 158 | + ? { | |
| 159 | + fetch: (requestInput, requestOptions) => | |
| 160 | + mergeHeadersForFetch(requestInput, requestOptions, input.headers), | |
| 161 | + } | |
| 162 | + : undefined, | |
| 163 | + })); | |
| 164 | + | |
| 165 | + return { | |
| 166 | + client, | |
| 167 | + close: () => client.close(), | |
| 168 | + }; | |
| 169 | + } | |
| 170 | +}; | |
| 171 | + | |
| 172 | +const extractMcpTools = (value: unknown): Array<McpToolSummary> => { | |
| 173 | + if (!value || typeof value !== "object" || Array.isArray(value)) { | |
| 174 | + return []; | |
| 175 | + } | |
| 176 | + | |
| 177 | + const tools = (value as { tools?: unknown }).tools; | |
| 178 | + if (!Array.isArray(tools)) { | |
| 179 | + return []; | |
| 180 | + } | |
| 181 | + | |
| 182 | + return tools | |
| 183 | + .map((tool): McpToolSummary | null => { | |
| 184 | + if (!tool || typeof tool !== "object" || Array.isArray(tool)) { | |
| 185 | + return null; | |
| 186 | + } | |
| 187 | + | |
| 188 | + const toolRecord = tool as Record<string, unknown>; | |
| 189 | + const name = typeof toolRecord.name === "string" ? toolRecord.name.trim() : ""; | |
| 190 | + if (name.length === 0) { | |
| 191 | + return null; | |
| 192 | + } | |
| 193 | + | |
| 194 | + const description = typeof toolRecord.description === "string" | |
| 195 | + ? toolRecord.description | |
| 196 | + : null; | |
| 197 | + | |
| 198 | + return { | |
| 199 | + name, | |
| 200 | + description, | |
| 201 | + }; | |
| 202 | + }) | |
| 203 | + .filter((tool): tool is McpToolSummary => tool !== null); | |
| 204 | +}; | |
| 205 | + | |
| 206 | +const sanitizeToolId = (value: string): string => { | |
| 207 | + const normalized = value | |
| 208 | + .trim() | |
| 209 | + .toLowerCase() | |
| 210 | + .replace(/[^a-z0-9]+/g, "_") | |
| 211 | + .replace(/^_+|_+$/g, ""); | |
| 212 | + | |
| 213 | + return normalized.length > 0 ? normalized : "tool"; | |
| 214 | +}; | |
| 215 | + | |
| 216 | +const uniqueToolId = (value: string, byBase: Map<string, number>): string => { | |
| 217 | + const base = sanitizeToolId(value); | |
| 218 | + const count = (byBase.get(base) ?? 0) + 1; | |
| 219 | + byBase.set(base, count); | |
| 220 | + | |
| 221 | + return count === 1 ? base : `${base}_${count}`; | |
| 222 | +}; | |
| 223 | + | |
| 224 | +const withMcpConnection = <A>( | |
| 225 | + source: Source, | |
| 226 | + connector: McpConnector, | |
| 227 | + operation: string, | |
| 228 | + run: (connection: McpConnection) => Effect.Effect<A, ToolProviderError>, | |
| 229 | +): Effect.Effect<A, ToolProviderError> => | |
| 230 | + Effect.scoped( | |
| 231 | + Effect.gen(function* () { | |
| 232 | + const config = parseSourceConfig(source); | |
| 233 | + const endpoint = resolveSourceEndpoint(source, config, ["url", "endpoint"]); | |
| 234 | + if (endpoint.trim().length === 0) { | |
| 235 | + return yield* new ToolProviderError({ | |
| 236 | + operation, | |
| 237 | + providerKind: "mcp", | |
| 238 | + message: "MCP source endpoint is required", | |
| 239 | + details: source.id, | |
| 240 | + }); | |
| 241 | + } | |
| 242 | + | |
| 243 | + const connection = yield* Effect.acquireRelease( | |
| 244 | + Effect.tryPromise({ | |
| 245 | + try: () => | |
| 246 | + connector({ | |
| 247 | + endpoint, | |
| 248 | + transport: readMcpTransportFromConfig(config), | |
| 249 | + queryParams: readQueryParamsFromConfig(config), | |
| 250 | + headers: collectSourceHeaders(config), | |
| 251 | + }), | |
| 252 | + catch: (cause) => | |
| 253 | + toMcpProviderError( | |
| 254 | + operation, | |
| 255 | + `Failed to connect to MCP source: ${source.name}`, | |
| 256 | + cause, | |
| 257 | + ), | |
| 258 | + }), | |
| 259 | + (connected) => | |
| 260 | + Effect.tryPromise({ | |
| 261 | + try: () => connected.close(), | |
| 262 | + catch: () => undefined, | |
| 263 | + }).pipe(Effect.orDie), | |
| 264 | + ); | |
| 265 | + | |
| 266 | + return yield* run(connection); | |
| 267 | + }), | |
| 268 | + ); | |
| 269 | + | |
| 270 | +export type MakeMcpToolProviderOptions = { | |
| 271 | + connector?: McpConnector; | |
| 272 | +}; | |
| 273 | + | |
| 274 | +export const makeMcpToolProvider = ( | |
| 275 | + options: MakeMcpToolProviderOptions = {}, | |
| 276 | +): ToolProvider => { | |
| 277 | + const connector = options.connector ?? connectMcpWithSdk; | |
| 278 | + | |
| 279 | + return { | |
| 280 | + kind: "mcp", | |
| 281 | + | |
| 282 | + discoverFromSource: (source) => | |
| 283 | + withMcpConnection( | |
| 284 | + source, | |
| 285 | + connector, | |
| 286 | + "discover.connect", | |
| 287 | + (connection) => | |
| 288 | + Effect.gen(function* () { | |
| 289 | + const listed = yield* Effect.tryPromise({ | |
| 290 | + try: () => connection.client.listTools(), | |
| 291 | + catch: (cause) => | |
| 292 | + toMcpProviderError( | |
| 293 | + "discover.list_tools", | |
| 294 | + `Failed to list MCP tools for source: ${source.name}`, | |
| 295 | + cause, | |
| 296 | + ), | |
| 297 | + }); | |
| 298 | + | |
| 299 | + const discoveredTools = extractMcpTools(listed); | |
| 300 | + const usedToolIds = new Map<string, number>(); | |
| 301 | + | |
| 302 | + const tools: ReadonlyArray<CanonicalToolDescriptor> = discoveredTools.map((tool) => ({ | |
| 303 | + providerKind: "mcp", | |
| 304 | + sourceId: source.id, | |
| 305 | + workspaceId: source.workspaceId, | |
| 306 | + toolId: uniqueToolId(tool.name, usedToolIds), | |
| 307 | + name: tool.name, | |
| 308 | + description: tool.description, | |
| 309 | + invocationMode: "mcp", | |
| 310 | + availability: "remote_capable", | |
| 311 | + providerPayload: { | |
| 312 | + kind: "mcp_tool", | |
| 313 | + toolName: tool.name, | |
| 314 | + }, | |
| 315 | + })); | |
| 316 | + | |
| 317 | + return { | |
| 318 | + sourceHash: source.sourceHash, | |
| 319 | + tools, | |
| 320 | + }; | |
| 321 | + }), | |
| 322 | + ), | |
| 323 | + | |
| 324 | + invoke: (input) => | |
| 325 | + Effect.gen(function* () { | |
| 326 | + if (!input.source) { | |
| 327 | + return yield* new ToolProviderError({ | |
| 328 | + operation: "invoke.validate_source", | |
| 329 | + providerKind: "mcp", | |
| 330 | + message: "MCP provider requires a source", | |
| 331 | + details: null, | |
| 332 | + }); | |
| 333 | + } | |
| 334 | + | |
| 335 | + const payload = yield* decodeMcpInvocationPayload(input.tool.providerPayload).pipe( | |
| 336 | + Effect.mapError((cause) => | |
| 337 | + toMcpProviderError( | |
| 338 | + "invoke.decode_payload", | |
| 339 | + `Invalid MCP invocation payload for tool: ${input.tool.toolId}`, | |
| 340 | + cause, | |
| 341 | + ), | |
| 342 | + ), | |
| 343 | + ); | |
| 344 | + | |
| 345 | + const args = yield* decodeMcpInvokeArgs(input.args).pipe( | |
| 346 | + Effect.mapError((cause) => | |
| 347 | + toMcpProviderError( | |
| 348 | + "invoke.decode_args", | |
| 349 | + `Invalid MCP tool args for tool: ${input.tool.toolId}`, | |
| 350 | + cause, | |
| 351 | + ), | |
| 352 | + ), | |
| 353 | + ); | |
| 354 | + | |
| 355 | + return yield* withMcpConnection( | |
| 356 | + input.source, | |
| 357 | + connector, | |
| 358 | + "invoke.connect", | |
| 359 | + (connection) => | |
| 360 | + Effect.gen(function* () { | |
| 361 | + const result = yield* Effect.tryPromise({ | |
| 362 | + try: () => | |
| 363 | + connection.client.callTool({ | |
| 364 | + name: payload.toolName, | |
| 365 | + arguments: args, | |
| 366 | + }), | |
| 367 | + catch: (cause) => | |
| 368 | + toMcpProviderError( | |
| 369 | + "invoke.call_tool", | |
| 370 | + `Failed MCP tool invocation: ${payload.toolName}`, | |
| 371 | + cause, | |
| 372 | + ), | |
| 373 | + }); | |
| 374 | + | |
| 375 | + const isError = Boolean( | |
| 376 | + result && | |
| 377 | + typeof result === "object" && | |
| 378 | + (result as { isError?: unknown }).isError === true, | |
| 379 | + ); | |
| 380 | + | |
| 381 | + return { | |
| 382 | + output: result, | |
| 383 | + isError, | |
| 384 | + }; | |
| 385 | + }), | |
| 386 | + ); | |
| 387 | + }), | |
| 388 | + }; | |
| 389 | +}; | |
| @@ -0,0 +1,143 @@ | ||
| 1 | +import type { Source } from "@executor-v2/schema"; | |
| 2 | + | |
| 3 | +export type SourceConfig = Record<string, unknown>; | |
| 4 | + | |
| 5 | +export type McpTransportPreference = "auto" | "streamable-http" | "sse"; | |
| 6 | + | |
| 7 | +const normalizeString = (value: unknown): string | null => { | |
| 8 | + if (typeof value !== "string") { | |
| 9 | + return null; | |
| 10 | + } | |
| 11 | + | |
| 12 | + const trimmed = value.trim(); | |
| 13 | + return trimmed.length > 0 ? trimmed : null; | |
| 14 | +}; | |
| 15 | + | |
| 16 | +const asRecord = (value: unknown): Record<string, unknown> => { | |
| 17 | + if (!value || typeof value !== "object" || Array.isArray(value)) { | |
| 18 | + return {}; | |
| 19 | + } | |
| 20 | + | |
| 21 | + return value as Record<string, unknown>; | |
| 22 | +}; | |
| 23 | + | |
| 24 | +const parseJson = (value: string): unknown | null => { | |
| 25 | + try { | |
| 26 | + return JSON.parse(value); | |
| 27 | + } catch { | |
| 28 | + return null; | |
| 29 | + } | |
| 30 | +}; | |
| 31 | + | |
| 32 | +export const parseSourceConfig = (source: Source): SourceConfig => | |
| 33 | + asRecord(parseJson(source.configJson)); | |
| 34 | + | |
| 35 | +export const resolveSourceEndpoint = ( | |
| 36 | + source: Source, | |
| 37 | + config: SourceConfig, | |
| 38 | + candidates: ReadonlyArray<string>, | |
| 39 | +): string => { | |
| 40 | + for (const candidate of candidates) { | |
| 41 | + const value = normalizeString(config[candidate]); | |
| 42 | + if (value) { | |
| 43 | + return value; | |
| 44 | + } | |
| 45 | + } | |
| 46 | + | |
| 47 | + return source.endpoint; | |
| 48 | +}; | |
| 49 | + | |
| 50 | +export const readStringRecord = ( | |
| 51 | + value: unknown, | |
| 52 | +): Record<string, string> => { | |
| 53 | + const record = asRecord(value); | |
| 54 | + const normalized: Record<string, string> = {}; | |
| 55 | + | |
| 56 | + for (const [rawKey, rawValue] of Object.entries(record)) { | |
| 57 | + const key = normalizeString(rawKey); | |
| 58 | + const resolvedValue = normalizeString(rawValue); | |
| 59 | + if (!key || !resolvedValue) { | |
| 60 | + continue; | |
| 61 | + } | |
| 62 | + | |
| 63 | + normalized[key] = resolvedValue; | |
| 64 | + } | |
| 65 | + | |
| 66 | + return normalized; | |
| 67 | +}; | |
| 68 | + | |
| 69 | +export const readQueryParamsFromConfig = ( | |
| 70 | + config: SourceConfig, | |
| 71 | +): Record<string, string> => { | |
| 72 | + const queryParams = asRecord(config.queryParams); | |
| 73 | + const normalized: Record<string, string> = {}; | |
| 74 | + | |
| 75 | + for (const [key, value] of Object.entries(queryParams)) { | |
| 76 | + const normalizedKey = normalizeString(key); | |
| 77 | + if (!normalizedKey) { | |
| 78 | + continue; | |
| 79 | + } | |
| 80 | + | |
| 81 | + if ( | |
| 82 | + typeof value === "string" || | |
| 83 | + typeof value === "number" || | |
| 84 | + typeof value === "boolean" || | |
| 85 | + typeof value === "bigint" | |
| 86 | + ) { | |
| 87 | + normalized[normalizedKey] = String(value); | |
| 88 | + } | |
| 89 | + } | |
| 90 | + | |
| 91 | + return normalized; | |
| 92 | +}; | |
| 93 | + | |
| 94 | +export const readMcpTransportFromConfig = ( | |
| 95 | + config: SourceConfig, | |
| 96 | +): McpTransportPreference => { | |
| 97 | + const value = normalizeString(config.transport)?.toLowerCase(); | |
| 98 | + if (value === "streamable-http" || value === "sse") { | |
| 99 | + return value; | |
| 100 | + } | |
| 101 | + | |
| 102 | + return "auto"; | |
| 103 | +}; | |
| 104 | + | |
| 105 | +export const collectSourceHeaders = ( | |
| 106 | + config: SourceConfig, | |
| 107 | +): Record<string, string> => { | |
| 108 | + const configuredHeaders = readStringRecord(config.headers); | |
| 109 | + const auth = asRecord(config.auth); | |
| 110 | + const authType = normalizeString(auth.type)?.toLowerCase(); | |
| 111 | + const authHeaders: Record<string, string> = {}; | |
| 112 | + | |
| 113 | + if (authType === "bearer") { | |
| 114 | + const token = normalizeString(auth.token) ?? normalizeString(auth.value); | |
| 115 | + if (token) { | |
| 116 | + authHeaders.Authorization = `Bearer ${token}`; | |
| 117 | + } | |
| 118 | + } | |
| 119 | + | |
| 120 | + if (authType === "apikey" || authType === "api_key" || authType === "apiKey") { | |
| 121 | + const headerName = normalizeString(auth.header) ?? "Authorization"; | |
| 122 | + const apiKey = normalizeString(auth.value); | |
| 123 | + if (apiKey) { | |
| 124 | + authHeaders[headerName] = apiKey; | |
| 125 | + } | |
| 126 | + } | |
| 127 | + | |
| 128 | + if (authType === "basic") { | |
| 129 | + const username = normalizeString(auth.username); | |
| 130 | + const password = normalizeString(auth.password); | |
| 131 | + if (username && password) { | |
| 132 | + authHeaders.Authorization = `Basic ${Buffer.from( | |
| 133 | + `${username}:${password}`, | |
| 134 | + "utf8", | |
| 135 | + ).toString("base64")}`; | |
| 136 | + } | |
| 137 | + } | |
| 138 | + | |
| 139 | + return { | |
| 140 | + ...configuredHeaders, | |
| 141 | + ...authHeaders, | |
| 142 | + }; | |
| 143 | +}; | |
| @@ -65,23 +65,21 @@ export const deriveWorkspaceMembershipsForPrincipal = (input: { · 64 unmodified lines | ||
| 65 | 65 | }); |
| 66 | 66 | } |
| 67 | 67 | |
| 68 | − if (input.workspace.organizationId !== null) { | |
| 69 | − for (const membership of input.organizationMemberships) { | |
| 70 | − if (membership.accountId !== input.principalAccountId) { | |
| 71 | − continue; | |
| 72 | − } | |
| 73 | − | |
| 74 | − if (membership.organizationId !== input.workspace.organizationId) { | |
| 75 | − continue; | |
| 76 | − } | |
| 68 | + for (const membership of input.organizationMemberships) { | |
| 69 | + if (membership.accountId !== input.principalAccountId) { | |
| 70 | + continue; | |
| 71 | + } | |
| 77 | 72 | |
| 78 | − candidates.push({ | |
| 79 | − role: membership.role, | |
| 80 | − status: toWorkspaceMembershipStatus(membership.status), | |
| 81 | − grantedAt: membership.joinedAt ?? membership.createdAt, | |
| 82 | − updatedAt: membership.updatedAt, | |
| 83 | − }); | |
| 73 | + if (membership.organizationId !== input.workspace.organizationId) { | |
| 74 | + continue; | |
| 84 | 75 | } |
| 76 | + | |
| 77 | + candidates.push({ | |
| 78 | + role: membership.role, | |
| 79 | + status: toWorkspaceMembershipStatus(membership.status), | |
| 80 | + grantedAt: membership.joinedAt ?? membership.createdAt, | |
| 81 | + updatedAt: membership.updatedAt, | |
| 82 | + }); | |
| 85 | 83 | } |
| 86 | 84 | |
| 87 | 85 | const activeCandidates = candidates.filter( |
| @@ -18,7 +18,13 @@ const RequiredUpsertCredentialBindingPayloadSchema = SourceCredentialBindingSche · 17 unmodified lines | ||
| 18 | 18 | ); |
| 19 | 19 | |
| 20 | 20 | const OptionalUpsertCredentialBindingPayloadSchema = SourceCredentialBindingSchema.pipe( |
| 21 | − Schema.pick("id", "accountId", "additionalHeadersJson", "boundAuthFingerprint"), | |
| 21 | + Schema.pick( | |
| 22 | + "id", | |
| 23 | + "accountId", | |
| 24 | + "secretProvider", | |
| 25 | + "additionalHeadersJson", | |
| 26 | + "boundAuthFingerprint", | |
| 27 | + ), | |
| 22 | 28 | Schema.partialWith({ exact: true }), |
| 23 | 29 | ); |
| 24 | 30 | |
| @@ -14,7 +14,7 @@ const RequiredUpsertOrganizationPayloadSchema = OrganizationSchema.pipe( · 13 unmodified lines | ||
| 14 | 14 | ); |
| 15 | 15 | |
| 16 | 16 | const OptionalUpsertOrganizationPayloadSchema = OrganizationSchema.pipe( |
| 17 | − Schema.pick("id", "status"), | |
| 17 | + Schema.pick("id", "status", "createdByAccountId"), | |
| 18 | 18 | Schema.partialWith({ exact: true }), |
| 19 | 19 | ); |
| 20 | 20 | |
| @@ -124,8 +124,22 @@ export const ControlPlaneOrganizationsLive = HttpApiBuilder.group( · 123 unmodified lines | ||
| 124 | 124 | }); |
| 125 | 125 | } |
| 126 | 126 | |
| 127 | + const payloadWithCreator = { | |
| 128 | + ...payload, | |
| 129 | + createdByAccountId: actor.principal.accountId, | |
| 130 | + }; | |
| 131 | + | |
| 132 | + const existingOrganizations = yield* service.listOrganizations(); | |
| 133 | + const organizationExists = existingOrganizations.some( | |
| 134 | + (organization) => organization.id === payload.id, | |
| 135 | + ); | |
| 136 | + | |
| 137 | + if (!organizationExists) { | |
| 138 | + return yield* service.upsertOrganization({ payload: payloadWithCreator }); | |
| 139 | + } | |
| 140 | + | |
| 127 | 141 | return yield* withPolicy(requireManageOrganization(payload.id))( |
| 128 | − service.upsertOrganization({ payload }), | |
| 142 | + service.upsertOrganization({ payload: payloadWithCreator }), | |
| 129 | 143 | ).pipe(Effect.provideService(Actor, actor)); |
| 130 | 144 | }).pipe( |
| 131 | 145 | Effect.catchTag("ActorUnauthenticatedError", (cause) => |
| @@ -10,11 +10,11 @@ import { · 9 unmodified lines | ||
| 10 | 10 | } from "../errors"; |
| 11 | 11 | |
| 12 | 12 | const RequiredUpsertWorkspacePayloadSchema = WorkspaceSchema.pipe( |
| 13 | − Schema.pick("name"), | |
| 13 | + Schema.pick("name", "organizationId"), | |
| 14 | 14 | ); |
| 15 | 15 | |
| 16 | 16 | const OptionalUpsertWorkspacePayloadSchema = WorkspaceSchema.pipe( |
| 17 | − Schema.pick("id", "organizationId"), | |
| 17 | + Schema.pick("id"), | |
| 18 | 18 | Schema.partialWith({ exact: true }), |
| 19 | 19 | ); |
| 20 | 20 | |
| @@ -17,7 +17,6 @@ import { · 16 unmodified lines | ||
| 17 | 17 | import * as Effect from "effect/Effect"; |
| 18 | 18 | |
| 19 | 19 | import { |
| 20 | − ControlPlaneBadRequestError, | |
| 21 | 20 | ControlPlaneForbiddenError, |
| 22 | 21 | ControlPlaneStorageError, |
| 23 | 22 | ControlPlaneUnauthorizedError, |
| @@ -102,13 +101,10 @@ const filterVisibleWorkspaces = ( · 78 unmodified lines | ||
| 102 | 101 | permission: "workspace:read", |
| 103 | 102 | workspaceId: workspace.id, |
| 104 | 103 | }) |
| 105 | − || ( | |
| 106 | − workspace.organizationId !== null | |
| 107 | − && actor.hasPermission({ | |
| 108 | − permission: "workspace:read", | |
| 109 | − organizationId: workspace.organizationId, | |
| 110 | − }) | |
| 111 | − ) | |
| 104 | + || actor.hasPermission({ | |
| 105 | + permission: "workspace:read", | |
| 106 | + organizationId: workspace.organizationId, | |
| 107 | + }) | |
| 112 | 108 | ); |
| 113 | 109 | |
| 114 | 110 | export const ControlPlaneWorkspacesLive = HttpApiBuilder.group( |
| @@ -143,32 +139,12 @@ export const ControlPlaneWorkspacesLive = HttpApiBuilder.group( · 28 unmodified lines | ||
| 143 | 139 | const service = yield* ControlPlaneService; |
| 144 | 140 | const actor = yield* resolveActor; |
| 145 | 141 | |
| 146 | − const workspacePolicy = (() => { | |
| 147 | − if (payload.id && payload.organizationId !== null && payload.organizationId !== undefined) { | |
| 148 | − return any([ | |
| 142 | + const workspacePolicy = payload.id | |
| 143 | + ? any([ | |
| 149 | 144 | requireManageWorkspace(payload.id), |
| 150 | 145 | requireManageWorkspaceInOrganization(payload.organizationId), |
| 151 | − ]); | |
| 152 | − } | |
| 153 | − | |
| 154 | − if (payload.id) { | |
| 155 | − return requireManageWorkspace(payload.id); | |
| 156 | − } | |
| 157 | − | |
| 158 | − if (payload.organizationId !== null && payload.organizationId !== undefined) { | |
| 159 | − return requireManageWorkspaceInOrganization(payload.organizationId); | |
| 160 | − } | |
| 161 | − | |
| 162 | − return null; | |
| 163 | − })(); | |
| 164 | − | |
| 165 | − if (!workspacePolicy) { | |
| 166 | − return yield* new ControlPlaneBadRequestError({ | |
| 167 | − operation: "workspaces.upsert", | |
| 168 | − message: "workspace id or organizationId is required", | |
| 169 | − details: "payload.id or payload.organizationId must be provided for scoped authorization", | |
| 170 | − }); | |
| 171 | − } | |
| 146 | + ]) | |
| 147 | + : requireManageWorkspaceInOrganization(payload.organizationId); | |
| 172 | 148 | |
| 173 | 149 | return yield* withPolicy(workspacePolicy)( |
| 174 | 150 | service.upsertWorkspace({ payload }), |
| @@ -127,7 +127,7 @@ const resolveConfig = ( · 126 unmodified lines | ||
| 127 | 127 | const callbackInternalSecret = |
| 128 | 128 | options.callbackInternalSecret ?? |
| 129 | 129 | normalizeString( |
| 130 | − env.CLOUDFLARE_SANDBOX_CALLBACK_INTERNAL_SECRET ?? | |
| 130 | + env.CLOUDFLARE_SANDBOX_CALLBACK_SECRET ?? | |
| 131 | 131 | env.EXECUTOR_INTERNAL_TOKEN, |
| 132 | 132 | ) ?? |
| 133 | 133 | null; |
| @@ -13,6 +13,9 @@ export const CredentialProviderSchema = Schema.Literal( · 12 unmodified lines | ||
| 13 | 13 | "oauth2", |
| 14 | 14 | "custom", |
| 15 | 15 | ); |
| 16 | +export const CredentialSecretProviderSchema = Schema.Literal( | |
| 17 | + "local", | |
| 18 | +); | |
| 16 | 19 | export const CredentialScopeTypeSchema = Schema.Literal( |
| 17 | 20 | "workspace", |
| 18 | 21 | "organization", |
| @@ -44,6 +47,7 @@ export type ApprovalStatus = typeof ApprovalStatusSchema.Type; · 25 unmodified lines | ||
| 44 | 47 | export type TaskRunStatus = typeof TaskRunStatusSchema.Type; |
| 45 | 48 | export type CredentialMode = typeof CredentialModeSchema.Type; |
| 46 | 49 | export type CredentialProvider = typeof CredentialProviderSchema.Type; |
| 50 | +export type CredentialSecretProvider = typeof CredentialSecretProviderSchema.Type; | |
| 47 | 51 | export type CredentialScopeType = typeof CredentialScopeTypeSchema.Type; |
| 48 | 52 | export type StorageScopeType = typeof StorageScopeTypeSchema.Type; |
| 49 | 53 | export type StorageDurability = typeof StorageDurabilitySchema.Type; |
| @@ -1,7 +1,11 @@ | ||
| 1 | 1 | import { Schema } from "effect"; |
| 2 | 2 | |
| 3 | 3 | import { TimestampMsSchema } from "../common"; |
| 4 | −import { CredentialProviderSchema, CredentialScopeTypeSchema } from "../enums"; | |
| 4 | +import { | |
| 5 | + CredentialProviderSchema, | |
| 6 | + CredentialScopeTypeSchema, | |
| 7 | + CredentialSecretProviderSchema, | |
| 8 | +} from "../enums"; | |
| 5 | 9 | import { |
| 6 | 10 | AccountIdSchema, |
| 7 | 11 | CredentialBindingIdSchema, |
| @@ -19,6 +23,7 @@ export const SourceCredentialBindingSchema = Schema.Struct({ · 11 unmodified lines | ||
| 19 | 23 | scopeType: CredentialScopeTypeSchema, |
| 20 | 24 | sourceKey: Schema.String, |
| 21 | 25 | provider: CredentialProviderSchema, |
| 26 | + secretProvider: Schema.optional(CredentialSecretProviderSchema), | |
| 22 | 27 | secretRef: Schema.String, |
| 23 | 28 | additionalHeadersJson: Schema.NullOr(Schema.String), |
| 24 | 29 | boundAuthFingerprint: Schema.NullOr(Schema.String), |
| @@ -5,7 +5,7 @@ import { AccountIdSchema, OrganizationIdSchema, WorkspaceIdSchema } from "../ids · 4 unmodified lines | ||
| 5 | 5 | |
| 6 | 6 | export const WorkspaceSchema = Schema.Struct({ |
| 7 | 7 | id: WorkspaceIdSchema, |
| 8 | − organizationId: Schema.NullOr(OrganizationIdSchema), | |
| 8 | + organizationId: OrganizationIdSchema, | |
| 9 | 9 | name: Schema.String, |
| 10 | 10 | createdByAccountId: Schema.NullOr(AccountIdSchema), |
| 11 | 11 | createdAt: TimestampMsSchema, |
| @@ -60,7 +60,7 @@ describe("makeLocalStateStore", () => { · 59 unmodified lines | ||
| 60 | 60 | workspaces: [ |
| 61 | 61 | { |
| 62 | 62 | id: "ws_local", |
| 63 | − organizationId: null, | |
| 63 | + organizationId: "org_local", | |
| 64 | 64 | name: "Local Workspace", |
| 65 | 65 | createdByAccountId: null, |
| 66 | 66 | createdAt: now, |