| 1 | import { randomUUID } from 'node:crypto';
|
| 2 |
|
| 3 | export type Project = {
|
| 4 | projectId: string;
|
| 5 | name: string;
|
| 6 | createdAt: string;
|
| 7 | };
|
| 8 |
|
| 9 | export type AgentProfile = {
|
| 10 | agentId: string;
|
| 11 | projectId: string;
|
| 12 | name: string;
|
| 13 | description: string;
|
| 14 | framework: string;
|
| 15 | agentVersion: string;
|
| 16 | agentMode?: 'persistent_runtime' | 'temporary_chat';
|
| 17 | a2aEndpoint?: string;
|
| 18 | transport?: 'direct_a2a' | 'openclasp_gateway';
|
| 19 | autoPublish: boolean;
|
| 20 | autoAcceptPolicy: 'off' | 'safe_matching';
|
| 21 | autoAcceptTaskCategories: string[];
|
| 22 | capabilities: string[];
|
| 23 | limitations: string[];
|
| 24 | identityMode: 'oauth_installation' | 'owner_managed';
|
| 25 | status: 'active' | 'revoked';
|
| 26 | createdAt: string;
|
| 27 | updatedAt: string;
|
| 28 | };
|
| 29 |
|
| 30 | export type AgentInstallation = {
|
| 31 | installationId: string;
|
| 32 | clientId: string;
|
| 33 | agentId: string;
|
| 34 | projectId: string;
|
| 35 | connectedAt: string;
|
| 36 | updatedAt: string;
|
| 37 | };
|
| 38 |
|
| 39 | export type SetupRequest = {
|
| 40 | requestId: string;
|
| 41 | clientId: string;
|
| 42 | action: 'connect' | 'switch';
|
| 43 | status: 'pending' | 'approved' | 'rejected';
|
| 44 | agentName?: string;
|
| 45 | description?: string;
|
| 46 | projectName?: string;
|
| 47 | projectId?: string;
|
| 48 | existingAgentId?: string;
|
| 49 | framework: string;
|
| 50 | agentVersion: string;
|
| 51 | agentMode: 'persistent_runtime' | 'temporary_chat';
|
| 52 | a2aEndpoint?: string;
|
| 53 | autoPublish: boolean;
|
| 54 | autoAcceptPolicy: 'off' | 'safe_matching';
|
| 55 | autoAcceptTaskCategories: string[];
|
| 56 | capabilities: string[];
|
| 57 | limitations: string[];
|
| 58 | requestedAt: string;
|
| 59 | decidedAt?: string;
|
| 60 | installationId?: string;
|
| 61 | };
|
| 62 |
|
| 63 | export type OnboardingKind = 'project' | 'agent_profile' | 'installation' | 'setup_request';
|
| 64 |
|
| 65 | export type OnboardingRow = {
|
| 66 | kind: string;
|
| 67 | recordId: string;
|
| 68 | payload: any;
|
| 69 | };
|
| 70 |
|
| 71 | export interface OnboardingStore {
|
| 72 | list(operatorId: string): Promise<OnboardingRow[]>;
|
| 73 | upsert(
|
| 74 | operatorId: string,
|
| 75 | kind: OnboardingKind,
|
| 76 | recordId: string,
|
| 77 | payload: unknown,
|
| 78 | ): Promise<void>;
|
| 79 | }
|
| 80 |
|
| 81 | export type OnboardingState = {
|
| 82 | projects: Project[];
|
| 83 | agentProfiles: AgentProfile[];
|
| 84 | installations: AgentInstallation[];
|
| 85 | setupRequests: SetupRequest[];
|
| 86 | };
|
| 87 |
|
| 88 | export async function getOnboardingState(
|
| 89 | store: OnboardingStore,
|
| 90 | operatorId: string,
|
| 91 | ): Promise<OnboardingState> {
|
| 92 | const rows = await store.list(operatorId);
|
| 93 | const values = <T>(kind: OnboardingKind) =>
|
| 94 | rows.filter((row) => row.kind === kind).map((row) => row.payload as T);
|
| 95 | return {
|
| 96 | projects: values<Project>('project'),
|
| 97 | agentProfiles: values<AgentProfile>('agent_profile').map((agent) => ({
|
| 98 | ...agent,
|
| 99 | agentMode: agent.agentMode ?? (agent.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat'),
|
| 100 | transport: agent.a2aEndpoint ? 'direct_a2a' : (agent.transport ?? 'direct_a2a'),
|
| 101 | description: agent.description ?? '',
|
| 102 | agentVersion: agent.agentVersion ?? '1.0.0',
|
| 103 | autoPublish: agent.autoPublish ?? false,
|
| 104 | autoAcceptPolicy: agent.autoAcceptPolicy ?? 'off',
|
| 105 | autoAcceptTaskCategories: agent.autoAcceptTaskCategories ?? [],
|
| 106 | })),
|
| 107 | installations: values<AgentInstallation>('installation'),
|
| 108 | setupRequests: values<SetupRequest>('setup_request'),
|
| 109 | };
|
| 110 | }
|
| 111 |
|
| 112 | export async function resolveInstallation(
|
| 113 | store: OnboardingStore,
|
| 114 | operatorId: string,
|
| 115 | clientId: string,
|
| 116 | ) {
|
| 117 | const state = await getOnboardingState(store, operatorId);
|
| 118 | const installation = state.installations.find((item) => item.clientId === clientId);
|
| 119 | if (!installation) return { status: 'unbound' as const };
|
| 120 | const agent = state.agentProfiles.find((item) => item.agentId === installation.agentId);
|
| 121 | const project = state.projects.find((item) => item.projectId === installation.projectId);
|
| 122 | if (!agent || !project) return { status: 'invalid_binding' as const, installation };
|
| 123 | return { status: 'connected' as const, installation, agent, project };
|
| 124 | }
|
| 125 |
|
| 126 | export async function createHostedProviderAgent(
|
| 127 | store: OnboardingStore,
|
| 128 | operatorId: string,
|
| 129 | input: {
|
| 130 | provider: 'botpress' | 'custom';
|
| 131 | agentName: string;
|
| 132 | projectName: string;
|
| 133 | description?: string | undefined;
|
| 134 | capabilities?: string[] | undefined;
|
| 135 | limitations?: string[] | undefined;
|
| 136 | },
|
| 137 | ) {
|
| 138 | const state = await getOnboardingState(store, operatorId);
|
| 139 | const projectName = input.projectName.trim();
|
| 140 | const agentName = input.agentName.trim();
|
| 141 | if (!projectName || !agentName) throw new Error('Agent and project names are required');
|
| 142 | const now = new Date().toISOString();
|
| 143 | let project = state.projects.find(
|
| 144 | (candidate) => candidate.name.trim().toLowerCase() === projectName.toLowerCase(),
|
| 145 | );
|
| 146 | if (!project) {
|
| 147 | project = { projectId: `project_${randomUUID()}`, name: projectName, createdAt: now };
|
| 148 | await store.upsert(operatorId, 'project', project.projectId, project);
|
| 149 | }
|
| 150 | const agent: AgentProfile = {
|
| 151 | agentId: `agent_${randomUUID()}`,
|
| 152 | projectId: project.projectId,
|
| 153 | name: agentName,
|
| 154 | description: input.description?.trim() ?? '',
|
| 155 | framework: input.provider === 'botpress' ? 'Botpress' : 'Custom runtime',
|
| 156 | agentVersion: '1.0.0',
|
| 157 | agentMode: 'persistent_runtime',
|
| 158 | transport: 'direct_a2a',
|
| 159 | autoPublish: false,
|
| 160 | autoAcceptPolicy: 'off',
|
| 161 | autoAcceptTaskCategories: [],
|
| 162 | capabilities: [...new Set(input.capabilities ?? [])],
|
| 163 | limitations: [...new Set(input.limitations ?? [])],
|
| 164 | identityMode: 'owner_managed',
|
| 165 | status: 'active',
|
| 166 | createdAt: now,
|
| 167 | updatedAt: now,
|
| 168 | };
|
| 169 | await store.upsert(operatorId, 'agent_profile', agent.agentId, agent);
|
| 170 | return { project, agent };
|
| 171 | }
|
| 172 |
|
| 173 | export async function createDashboardAgent(
|
| 174 | store: OnboardingStore,
|
| 175 | operatorId: string,
|
| 176 | input: {
|
| 177 | agentName: string;
|
| 178 | projectName: string;
|
| 179 | description: string;
|
| 180 | capabilities: string[];
|
| 181 | limitations?: string[] | undefined;
|
| 182 | },
|
| 183 | ) {
|
| 184 | const state = await getOnboardingState(store, operatorId);
|
| 185 | const projectName = input.projectName.trim();
|
| 186 | const agentName = input.agentName.trim();
|
| 187 | if (!projectName || !agentName) throw new Error('Agent and project names are required');
|
| 188 | const capabilities = [
|
| 189 | ...new Set(input.capabilities.map((value) => value.trim()).filter(Boolean)),
|
| 190 | ];
|
| 191 | if (!capabilities.length) throw new Error('At least one capability is required');
|
| 192 | const now = new Date().toISOString();
|
| 193 | let project = state.projects.find(
|
| 194 | (candidate) => candidate.name.trim().toLowerCase() === projectName.toLowerCase(),
|
| 195 | );
|
| 196 | if (!project) {
|
| 197 | project = { projectId: `project_${randomUUID()}`, name: projectName, createdAt: now };
|
| 198 | await store.upsert(operatorId, 'project', project.projectId, project);
|
| 199 | }
|
| 200 | const existing = state.agentProfiles.find(
|
| 201 | (candidate) =>
|
| 202 | candidate.status === 'active' &&
|
| 203 | candidate.projectId === project!.projectId &&
|
| 204 | candidate.name.trim().toLowerCase() === agentName.toLowerCase(),
|
| 205 | );
|
| 206 | if (existing) return { project, agent: existing };
|
| 207 | const agent: AgentProfile = {
|
| 208 | agentId: `agent_${randomUUID()}`,
|
| 209 | projectId: project.projectId,
|
| 210 | name: agentName,
|
| 211 | description: input.description.trim(),
|
| 212 | framework: 'OpenClasp hosted',
|
| 213 | agentVersion: '1.0.0',
|
| 214 | agentMode: 'temporary_chat',
|
| 215 | transport: 'openclasp_gateway',
|
| 216 | autoPublish: true,
|
| 217 | autoAcceptPolicy: 'off',
|
| 218 | autoAcceptTaskCategories: [],
|
| 219 | capabilities,
|
| 220 | limitations: [
|
| 221 | ...new Set((input.limitations ?? []).map((value) => value.trim()).filter(Boolean)),
|
| 222 | ],
|
| 223 | identityMode: 'owner_managed',
|
| 224 | status: 'active',
|
| 225 | createdAt: now,
|
| 226 | updatedAt: now,
|
| 227 | };
|
| 228 | await store.upsert(operatorId, 'agent_profile', agent.agentId, agent);
|
| 229 | return { project, agent };
|
| 230 | }
|
| 231 |
|
| 232 | export async function requestAgentSetup(
|
| 233 | store: OnboardingStore,
|
| 234 | operatorId: string,
|
| 235 | input: {
|
| 236 | clientId: string;
|
| 237 | action?: 'connect' | 'switch' | undefined;
|
| 238 | agentName?: string | undefined;
|
| 239 | projectName?: string | undefined;
|
| 240 | projectId?: string | undefined;
|
| 241 | existingAgentId?: string | undefined;
|
| 242 | framework?: string | undefined;
|
| 243 | description?: string | undefined;
|
| 244 | agentVersion?: string | undefined;
|
| 245 | agentMode?: 'persistent_runtime' | 'temporary_chat' | undefined;
|
| 246 | a2aEndpoint?: string | undefined;
|
| 247 | autoPublish?: boolean | undefined;
|
| 248 | autoAcceptPolicy?: 'off' | 'safe_matching' | undefined;
|
| 249 | autoAcceptTaskCategories?: string[] | undefined;
|
| 250 | capabilities?: string[] | undefined;
|
| 251 | limitations?: string[] | undefined;
|
| 252 | },
|
| 253 | ): Promise<SetupRequest> {
|
| 254 | const state = await getOnboardingState(store, operatorId);
|
| 255 | const pending = state.setupRequests.find(
|
| 256 | (item) => item.clientId === input.clientId && item.status === 'pending',
|
| 257 | );
|
| 258 | if (pending) return pending;
|
| 259 | if (
|
| 260 | !input.existingAgentId &&
|
| 261 | (!input.agentName?.trim() || (!input.projectId && !input.projectName?.trim()))
|
| 262 | )
|
| 263 | throw new Error('agentName and either projectName or projectId are required for a new agent');
|
| 264 | if (
|
| 265 | input.existingAgentId &&
|
| 266 | !state.agentProfiles.some((agent) => agent.agentId === input.existingAgentId)
|
| 267 | )
|
| 268 | throw new Error('Existing agent not found');
|
| 269 | if (input.projectId && !state.projects.some((project) => project.projectId === input.projectId))
|
| 270 | throw new Error('Project not found');
|
| 271 |
|
| 272 | const request: SetupRequest = {
|
| 273 | requestId: randomUUID(),
|
| 274 | clientId: input.clientId,
|
| 275 | action: input.action ?? (input.existingAgentId ? 'switch' : 'connect'),
|
| 276 | status: 'pending',
|
| 277 | ...(input.agentName?.trim() ? { agentName: input.agentName.trim() } : {}),
|
| 278 | ...(input.projectName?.trim() ? { projectName: input.projectName.trim() } : {}),
|
| 279 | ...(input.projectId ? { projectId: input.projectId } : {}),
|
| 280 | ...(input.existingAgentId ? { existingAgentId: input.existingAgentId } : {}),
|
| 281 | framework: input.framework?.trim() || 'unknown',
|
| 282 | description: input.description?.trim() || '',
|
| 283 | agentVersion: input.agentVersion?.trim() || '1.0.0',
|
| 284 | agentMode: input.agentMode ?? 'temporary_chat',
|
| 285 | ...(input.a2aEndpoint?.trim() ? { a2aEndpoint: input.a2aEndpoint.trim() } : {}),
|
| 286 | autoPublish: input.autoPublish ?? true,
|
| 287 | autoAcceptPolicy: input.autoAcceptPolicy ?? 'safe_matching',
|
| 288 | autoAcceptTaskCategories: [
|
| 289 | ...new Set(input.autoAcceptTaskCategories ?? input.capabilities ?? []),
|
| 290 | ],
|
| 291 | capabilities: [...new Set(input.capabilities ?? [])],
|
| 292 | limitations: [...new Set(input.limitations ?? [])],
|
| 293 | requestedAt: new Date().toISOString(),
|
| 294 | };
|
| 295 | await store.upsert(operatorId, 'setup_request', request.requestId, request);
|
| 296 | return request;
|
| 297 | }
|
| 298 |
|
| 299 | export async function approveAgentSetup(
|
| 300 | store: OnboardingStore,
|
| 301 | operatorId: string,
|
| 302 | requestId: string,
|
| 303 | ) {
|
| 304 | const state = await getOnboardingState(store, operatorId);
|
| 305 | const request = state.setupRequests.find((item) => item.requestId === requestId);
|
| 306 | if (!request) throw new Error('Setup request not found');
|
| 307 | if (request.status === 'rejected') throw new Error('Setup request was rejected');
|
| 308 | if (request.status === 'approved')
|
| 309 | return resolveInstallation(store, operatorId, request.clientId);
|
| 310 |
|
| 311 | const now = new Date().toISOString();
|
| 312 | let agent = request.existingAgentId
|
| 313 | ? state.agentProfiles.find((item) => item.agentId === request.existingAgentId)
|
| 314 | : undefined;
|
| 315 | let project = agent
|
| 316 | ? state.projects.find((item) => item.projectId === agent!.projectId)
|
| 317 | : request.projectId
|
| 318 | ? state.projects.find((item) => item.projectId === request.projectId)
|
| 319 | : undefined;
|
| 320 |
|
| 321 | if (!project) {
|
| 322 | project = {
|
| 323 | projectId: `project_${randomUUID()}`,
|
| 324 | name: request.projectName!,
|
| 325 | createdAt: now,
|
| 326 | };
|
| 327 | await store.upsert(operatorId, 'project', project.projectId, project);
|
| 328 | }
|
| 329 | if (!agent) {
|
| 330 | agent = {
|
| 331 | agentId: `agent_${randomUUID()}`,
|
| 332 | projectId: project.projectId,
|
| 333 | name: request.agentName!,
|
| 334 | description: request.description ?? '',
|
| 335 | framework: request.framework,
|
| 336 | agentVersion: request.agentVersion,
|
| 337 | agentMode: request.agentMode ?? 'temporary_chat',
|
| 338 | transport: 'direct_a2a',
|
| 339 | autoPublish: request.autoPublish ?? false,
|
| 340 | autoAcceptPolicy: request.autoAcceptPolicy ?? 'off',
|
| 341 | autoAcceptTaskCategories: request.autoAcceptTaskCategories ?? [],
|
| 342 | capabilities: request.capabilities,
|
| 343 | limitations: request.limitations,
|
| 344 | identityMode: 'oauth_installation',
|
| 345 | status: 'active',
|
| 346 | createdAt: now,
|
| 347 | updatedAt: now,
|
| 348 | };
|
| 349 | await store.upsert(operatorId, 'agent_profile', agent.agentId, agent);
|
| 350 | }
|
| 351 |
|
| 352 | const previous = state.installations.find((item) => item.clientId === request.clientId);
|
| 353 | const installation: AgentInstallation = {
|
| 354 | installationId: previous?.installationId ?? `install_${randomUUID()}`,
|
| 355 | clientId: request.clientId,
|
| 356 | agentId: agent.agentId,
|
| 357 | projectId: project.projectId,
|
| 358 | connectedAt: previous?.connectedAt ?? now,
|
| 359 | updatedAt: now,
|
| 360 | };
|
| 361 | await store.upsert(operatorId, 'installation', request.clientId, installation);
|
| 362 | await store.upsert(operatorId, 'setup_request', request.requestId, {
|
| 363 | ...request,
|
| 364 | status: 'approved',
|
| 365 | decidedAt: now,
|
| 366 | installationId: installation.installationId,
|
| 367 | } satisfies SetupRequest);
|
| 368 | return { status: 'connected' as const, installation, agent, project };
|
| 369 | }
|
| 370 |
|
| 371 | export async function rejectAgentSetup(
|
| 372 | store: OnboardingStore,
|
| 373 | operatorId: string,
|
| 374 | requestId: string,
|
| 375 | ) {
|
| 376 | const state = await getOnboardingState(store, operatorId);
|
| 377 | const request = state.setupRequests.find((item) => item.requestId === requestId);
|
| 378 | if (!request) throw new Error('Setup request not found');
|
| 379 | if (request.status !== 'pending') throw new Error('Setup request is no longer pending');
|
| 380 | const rejected: SetupRequest = {
|
| 381 | ...request,
|
| 382 | status: 'rejected',
|
| 383 | decidedAt: new Date().toISOString(),
|
| 384 | };
|
| 385 | await store.upsert(operatorId, 'setup_request', requestId, rejected);
|
| 386 | return rejected;
|
| 387 | }
|
| 388 |
|
| 389 | export async function updateAgentProfile(
|
| 390 | store: OnboardingStore,
|
| 391 | operatorId: string,
|
| 392 | clientId: string,
|
| 393 | patch: {
|
| 394 | name?: string | undefined;
|
| 395 | description?: string | undefined;
|
| 396 | framework?: string | undefined;
|
| 397 | agentVersion?: string | undefined;
|
| 398 | agentMode?: 'persistent_runtime' | 'temporary_chat' | undefined;
|
| 399 | a2aEndpoint?: string | undefined;
|
| 400 | autoPublish?: boolean | undefined;
|
| 401 | autoAcceptPolicy?: 'off' | 'safe_matching' | undefined;
|
| 402 | autoAcceptTaskCategories?: string[] | undefined;
|
| 403 | capabilities?: string[] | undefined;
|
| 404 | limitations?: string[] | undefined;
|
| 405 | },
|
| 406 | ) {
|
| 407 | const binding = await resolveInstallation(store, operatorId, clientId);
|
| 408 | if (binding.status !== 'connected') throw new Error('This MCP installation is not connected');
|
| 409 | const agent: AgentProfile = {
|
| 410 | ...binding.agent,
|
| 411 | transport: 'direct_a2a',
|
| 412 | agentMode:
|
| 413 | patch.agentMode ??
|
| 414 | binding.agent.agentMode ??
|
| 415 | (binding.agent.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat'),
|
| 416 | ...(patch.name?.trim() ? { name: patch.name.trim() } : {}),
|
| 417 | ...(patch.description !== undefined ? { description: patch.description.trim() } : {}),
|
| 418 | ...(patch.framework?.trim() ? { framework: patch.framework.trim() } : {}),
|
| 419 | ...(patch.agentVersion?.trim() ? { agentVersion: patch.agentVersion.trim() } : {}),
|
| 420 | ...(patch.autoPublish !== undefined ? { autoPublish: patch.autoPublish } : {}),
|
| 421 | ...(patch.autoAcceptPolicy ? { autoAcceptPolicy: patch.autoAcceptPolicy } : {}),
|
| 422 | ...(patch.autoAcceptTaskCategories
|
| 423 | ? { autoAcceptTaskCategories: [...new Set(patch.autoAcceptTaskCategories)] }
|
| 424 | : {}),
|
| 425 | ...(patch.capabilities ? { capabilities: [...new Set(patch.capabilities)] } : {}),
|
| 426 | ...(patch.limitations ? { limitations: [...new Set(patch.limitations)] } : {}),
|
| 427 | updatedAt: new Date().toISOString(),
|
| 428 | };
|
| 429 | await store.upsert(operatorId, 'agent_profile', agent.agentId, agent);
|
| 430 | return agent;
|
| 431 | }
|