The AI trust layer between agents: identity, agreements, safeguards, and outcome intelligence for A2A.

Viewing files at commit c6b86fb80ff9Commit detailsView latest

packages/persistence/src/onboarding.ts 372 lines · 13.2 KB · typescript
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 requestAgentSetup(
174
  store: OnboardingStore,
175
  operatorId: string,
176
  input: {
177
    clientId: string;
178
    action?: 'connect' | 'switch' | undefined;
179
    agentName?: string | undefined;
180
    projectName?: string | undefined;
181
    projectId?: string | undefined;
182
    existingAgentId?: string | undefined;
183
    framework?: string | undefined;
184
    description?: string | undefined;
185
    agentVersion?: string | undefined;
186
    agentMode?: 'persistent_runtime' | 'temporary_chat' | undefined;
187
    a2aEndpoint?: string | undefined;
188
    autoPublish?: boolean | undefined;
189
    autoAcceptPolicy?: 'off' | 'safe_matching' | undefined;
190
    autoAcceptTaskCategories?: string[] | undefined;
191
    capabilities?: string[] | undefined;
192
    limitations?: string[] | undefined;
193
  },
194
): Promise<SetupRequest> {
195
  const state = await getOnboardingState(store, operatorId);
196
  const pending = state.setupRequests.find(
197
    (item) => item.clientId === input.clientId && item.status === 'pending',
198
  );
199
  if (pending) return pending;
200
  if (
201
    !input.existingAgentId &&
202
    (!input.agentName?.trim() || (!input.projectId && !input.projectName?.trim()))
203
  )
204
    throw new Error('agentName and either projectName or projectId are required for a new agent');
205
  if (
206
    input.existingAgentId &&
207
    !state.agentProfiles.some((agent) => agent.agentId === input.existingAgentId)
208
  )
209
    throw new Error('Existing agent not found');
210
  if (input.projectId && !state.projects.some((project) => project.projectId === input.projectId))
211
    throw new Error('Project not found');
212
213
  const request: SetupRequest = {
214
    requestId: randomUUID(),
215
    clientId: input.clientId,
216
    action: input.action ?? (input.existingAgentId ? 'switch' : 'connect'),
217
    status: 'pending',
218
    ...(input.agentName?.trim() ? { agentName: input.agentName.trim() } : {}),
219
    ...(input.projectName?.trim() ? { projectName: input.projectName.trim() } : {}),
220
    ...(input.projectId ? { projectId: input.projectId } : {}),
221
    ...(input.existingAgentId ? { existingAgentId: input.existingAgentId } : {}),
222
    framework: input.framework?.trim() || 'unknown',
223
    description: input.description?.trim() || '',
224
    agentVersion: input.agentVersion?.trim() || '1.0.0',
225
    agentMode: input.agentMode ?? 'temporary_chat',
226
    ...(input.a2aEndpoint?.trim() ? { a2aEndpoint: input.a2aEndpoint.trim() } : {}),
227
    autoPublish: input.autoPublish ?? true,
228
    autoAcceptPolicy: input.autoAcceptPolicy ?? 'safe_matching',
229
    autoAcceptTaskCategories: [
230
      ...new Set(input.autoAcceptTaskCategories ?? input.capabilities ?? []),
231
    ],
232
    capabilities: [...new Set(input.capabilities ?? [])],
233
    limitations: [...new Set(input.limitations ?? [])],
234
    requestedAt: new Date().toISOString(),
235
  };
236
  await store.upsert(operatorId, 'setup_request', request.requestId, request);
237
  return request;
238
}
239
240
export async function approveAgentSetup(
241
  store: OnboardingStore,
242
  operatorId: string,
243
  requestId: string,
244
) {
245
  const state = await getOnboardingState(store, operatorId);
246
  const request = state.setupRequests.find((item) => item.requestId === requestId);
247
  if (!request) throw new Error('Setup request not found');
248
  if (request.status === 'rejected') throw new Error('Setup request was rejected');
249
  if (request.status === 'approved')
250
    return resolveInstallation(store, operatorId, request.clientId);
251
252
  const now = new Date().toISOString();
253
  let agent = request.existingAgentId
254
    ? state.agentProfiles.find((item) => item.agentId === request.existingAgentId)
255
    : undefined;
256
  let project = agent
257
    ? state.projects.find((item) => item.projectId === agent!.projectId)
258
    : request.projectId
259
      ? state.projects.find((item) => item.projectId === request.projectId)
260
      : undefined;
261
262
  if (!project) {
263
    project = {
264
      projectId: `project_${randomUUID()}`,
265
      name: request.projectName!,
266
      createdAt: now,
267
    };
268
    await store.upsert(operatorId, 'project', project.projectId, project);
269
  }
270
  if (!agent) {
271
    agent = {
272
      agentId: `agent_${randomUUID()}`,
273
      projectId: project.projectId,
274
      name: request.agentName!,
275
      description: request.description ?? '',
276
      framework: request.framework,
277
      agentVersion: request.agentVersion,
278
      agentMode: request.agentMode ?? 'temporary_chat',
279
      transport: 'direct_a2a',
280
      autoPublish: request.autoPublish ?? false,
281
      autoAcceptPolicy: request.autoAcceptPolicy ?? 'off',
282
      autoAcceptTaskCategories: request.autoAcceptTaskCategories ?? [],
283
      capabilities: request.capabilities,
284
      limitations: request.limitations,
285
      identityMode: 'oauth_installation',
286
      status: 'active',
287
      createdAt: now,
288
      updatedAt: now,
289
    };
290
    await store.upsert(operatorId, 'agent_profile', agent.agentId, agent);
291
  }
292
293
  const previous = state.installations.find((item) => item.clientId === request.clientId);
294
  const installation: AgentInstallation = {
295
    installationId: previous?.installationId ?? `install_${randomUUID()}`,
296
    clientId: request.clientId,
297
    agentId: agent.agentId,
298
    projectId: project.projectId,
299
    connectedAt: previous?.connectedAt ?? now,
300
    updatedAt: now,
301
  };
302
  await store.upsert(operatorId, 'installation', request.clientId, installation);
303
  await store.upsert(operatorId, 'setup_request', request.requestId, {
304
    ...request,
305
    status: 'approved',
306
    decidedAt: now,
307
    installationId: installation.installationId,
308
  } satisfies SetupRequest);
309
  return { status: 'connected' as const, installation, agent, project };
310
}
311
312
export async function rejectAgentSetup(
313
  store: OnboardingStore,
314
  operatorId: string,
315
  requestId: string,
316
) {
317
  const state = await getOnboardingState(store, operatorId);
318
  const request = state.setupRequests.find((item) => item.requestId === requestId);
319
  if (!request) throw new Error('Setup request not found');
320
  if (request.status !== 'pending') throw new Error('Setup request is no longer pending');
321
  const rejected: SetupRequest = {
322
    ...request,
323
    status: 'rejected',
324
    decidedAt: new Date().toISOString(),
325
  };
326
  await store.upsert(operatorId, 'setup_request', requestId, rejected);
327
  return rejected;
328
}
329
330
export async function updateAgentProfile(
331
  store: OnboardingStore,
332
  operatorId: string,
333
  clientId: string,
334
  patch: {
335
    name?: string | undefined;
336
    description?: string | undefined;
337
    framework?: string | undefined;
338
    agentVersion?: string | undefined;
339
    agentMode?: 'persistent_runtime' | 'temporary_chat' | undefined;
340
    a2aEndpoint?: string | undefined;
341
    autoPublish?: boolean | undefined;
342
    autoAcceptPolicy?: 'off' | 'safe_matching' | undefined;
343
    autoAcceptTaskCategories?: string[] | undefined;
344
    capabilities?: string[] | undefined;
345
    limitations?: string[] | undefined;
346
  },
347
) {
348
  const binding = await resolveInstallation(store, operatorId, clientId);
349
  if (binding.status !== 'connected') throw new Error('This MCP installation is not connected');
350
  const agent: AgentProfile = {
351
    ...binding.agent,
352
    transport: 'direct_a2a',
353
    agentMode:
354
      patch.agentMode ??
355
      binding.agent.agentMode ??
356
      (binding.agent.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat'),
357
    ...(patch.name?.trim() ? { name: patch.name.trim() } : {}),
358
    ...(patch.description !== undefined ? { description: patch.description.trim() } : {}),
359
    ...(patch.framework?.trim() ? { framework: patch.framework.trim() } : {}),
360
    ...(patch.agentVersion?.trim() ? { agentVersion: patch.agentVersion.trim() } : {}),
361
    ...(patch.autoPublish !== undefined ? { autoPublish: patch.autoPublish } : {}),
362
    ...(patch.autoAcceptPolicy ? { autoAcceptPolicy: patch.autoAcceptPolicy } : {}),
363
    ...(patch.autoAcceptTaskCategories
364
      ? { autoAcceptTaskCategories: [...new Set(patch.autoAcceptTaskCategories)] }
365
      : {}),
366
    ...(patch.capabilities ? { capabilities: [...new Set(patch.capabilities)] } : {}),
367
    ...(patch.limitations ? { limitations: [...new Set(patch.limitations)] } : {}),
368
    updatedAt: new Date().toISOString(),
369
  };
370
  await store.upsert(operatorId, 'agent_profile', agent.agentId, agent);
371
  return agent;
372
}