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

Viewing files at commit 32cfcb5542e9Commit detailsView latest

packages/persistence/src/onboarding.ts 325 lines · 11.5 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';
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 requestAgentSetup(
127
  store: OnboardingStore,
128
  operatorId: string,
129
  input: {
130
    clientId: string;
131
    action?: 'connect' | 'switch' | undefined;
132
    agentName?: string | undefined;
133
    projectName?: string | undefined;
134
    projectId?: string | undefined;
135
    existingAgentId?: string | undefined;
136
    framework?: string | undefined;
137
    description?: string | undefined;
138
    agentVersion?: string | undefined;
139
    agentMode?: 'persistent_runtime' | 'temporary_chat' | undefined;
140
    a2aEndpoint?: string | undefined;
141
    autoPublish?: boolean | undefined;
142
    autoAcceptPolicy?: 'off' | 'safe_matching' | undefined;
143
    autoAcceptTaskCategories?: string[] | undefined;
144
    capabilities?: string[] | undefined;
145
    limitations?: string[] | undefined;
146
  },
147
): Promise<SetupRequest> {
148
  const state = await getOnboardingState(store, operatorId);
149
  const pending = state.setupRequests.find(
150
    (item) => item.clientId === input.clientId && item.status === 'pending',
151
  );
152
  if (pending) return pending;
153
  if (
154
    !input.existingAgentId &&
155
    (!input.agentName?.trim() || (!input.projectId && !input.projectName?.trim()))
156
  )
157
    throw new Error('agentName and either projectName or projectId are required for a new agent');
158
  if (
159
    input.existingAgentId &&
160
    !state.agentProfiles.some((agent) => agent.agentId === input.existingAgentId)
161
  )
162
    throw new Error('Existing agent not found');
163
  if (input.projectId && !state.projects.some((project) => project.projectId === input.projectId))
164
    throw new Error('Project not found');
165
166
  const request: SetupRequest = {
167
    requestId: randomUUID(),
168
    clientId: input.clientId,
169
    action: input.action ?? (input.existingAgentId ? 'switch' : 'connect'),
170
    status: 'pending',
171
    ...(input.agentName?.trim() ? { agentName: input.agentName.trim() } : {}),
172
    ...(input.projectName?.trim() ? { projectName: input.projectName.trim() } : {}),
173
    ...(input.projectId ? { projectId: input.projectId } : {}),
174
    ...(input.existingAgentId ? { existingAgentId: input.existingAgentId } : {}),
175
    framework: input.framework?.trim() || 'unknown',
176
    description: input.description?.trim() || '',
177
    agentVersion: input.agentVersion?.trim() || '1.0.0',
178
    agentMode: input.agentMode ?? 'temporary_chat',
179
    ...(input.a2aEndpoint?.trim() ? { a2aEndpoint: input.a2aEndpoint.trim() } : {}),
180
    autoPublish: input.autoPublish ?? true,
181
    autoAcceptPolicy: input.autoAcceptPolicy ?? 'safe_matching',
182
    autoAcceptTaskCategories: [
183
      ...new Set(input.autoAcceptTaskCategories ?? input.capabilities ?? []),
184
    ],
185
    capabilities: [...new Set(input.capabilities ?? [])],
186
    limitations: [...new Set(input.limitations ?? [])],
187
    requestedAt: new Date().toISOString(),
188
  };
189
  await store.upsert(operatorId, 'setup_request', request.requestId, request);
190
  return request;
191
}
192
193
export async function approveAgentSetup(
194
  store: OnboardingStore,
195
  operatorId: string,
196
  requestId: string,
197
) {
198
  const state = await getOnboardingState(store, operatorId);
199
  const request = state.setupRequests.find((item) => item.requestId === requestId);
200
  if (!request) throw new Error('Setup request not found');
201
  if (request.status === 'rejected') throw new Error('Setup request was rejected');
202
  if (request.status === 'approved')
203
    return resolveInstallation(store, operatorId, request.clientId);
204
205
  const now = new Date().toISOString();
206
  let agent = request.existingAgentId
207
    ? state.agentProfiles.find((item) => item.agentId === request.existingAgentId)
208
    : undefined;
209
  let project = agent
210
    ? state.projects.find((item) => item.projectId === agent!.projectId)
211
    : request.projectId
212
      ? state.projects.find((item) => item.projectId === request.projectId)
213
      : undefined;
214
215
  if (!project) {
216
    project = {
217
      projectId: `project_${randomUUID()}`,
218
      name: request.projectName!,
219
      createdAt: now,
220
    };
221
    await store.upsert(operatorId, 'project', project.projectId, project);
222
  }
223
  if (!agent) {
224
    agent = {
225
      agentId: `agent_${randomUUID()}`,
226
      projectId: project.projectId,
227
      name: request.agentName!,
228
      description: request.description ?? '',
229
      framework: request.framework,
230
      agentVersion: request.agentVersion,
231
      agentMode: request.agentMode ?? 'temporary_chat',
232
      transport: 'direct_a2a',
233
      autoPublish: request.autoPublish ?? false,
234
      autoAcceptPolicy: request.autoAcceptPolicy ?? 'off',
235
      autoAcceptTaskCategories: request.autoAcceptTaskCategories ?? [],
236
      capabilities: request.capabilities,
237
      limitations: request.limitations,
238
      identityMode: 'oauth_installation',
239
      status: 'active',
240
      createdAt: now,
241
      updatedAt: now,
242
    };
243
    await store.upsert(operatorId, 'agent_profile', agent.agentId, agent);
244
  }
245
246
  const previous = state.installations.find((item) => item.clientId === request.clientId);
247
  const installation: AgentInstallation = {
248
    installationId: previous?.installationId ?? `install_${randomUUID()}`,
249
    clientId: request.clientId,
250
    agentId: agent.agentId,
251
    projectId: project.projectId,
252
    connectedAt: previous?.connectedAt ?? now,
253
    updatedAt: now,
254
  };
255
  await store.upsert(operatorId, 'installation', request.clientId, installation);
256
  await store.upsert(operatorId, 'setup_request', request.requestId, {
257
    ...request,
258
    status: 'approved',
259
    decidedAt: now,
260
    installationId: installation.installationId,
261
  } satisfies SetupRequest);
262
  return { status: 'connected' as const, installation, agent, project };
263
}
264
265
export async function rejectAgentSetup(
266
  store: OnboardingStore,
267
  operatorId: string,
268
  requestId: string,
269
) {
270
  const state = await getOnboardingState(store, operatorId);
271
  const request = state.setupRequests.find((item) => item.requestId === requestId);
272
  if (!request) throw new Error('Setup request not found');
273
  if (request.status !== 'pending') throw new Error('Setup request is no longer pending');
274
  const rejected: SetupRequest = {
275
    ...request,
276
    status: 'rejected',
277
    decidedAt: new Date().toISOString(),
278
  };
279
  await store.upsert(operatorId, 'setup_request', requestId, rejected);
280
  return rejected;
281
}
282
283
export async function updateAgentProfile(
284
  store: OnboardingStore,
285
  operatorId: string,
286
  clientId: string,
287
  patch: {
288
    name?: string | undefined;
289
    description?: string | undefined;
290
    framework?: string | undefined;
291
    agentVersion?: string | undefined;
292
    agentMode?: 'persistent_runtime' | 'temporary_chat' | undefined;
293
    a2aEndpoint?: string | undefined;
294
    autoPublish?: boolean | undefined;
295
    autoAcceptPolicy?: 'off' | 'safe_matching' | undefined;
296
    autoAcceptTaskCategories?: string[] | undefined;
297
    capabilities?: string[] | undefined;
298
    limitations?: string[] | undefined;
299
  },
300
) {
301
  const binding = await resolveInstallation(store, operatorId, clientId);
302
  if (binding.status !== 'connected') throw new Error('This MCP installation is not connected');
303
  const agent: AgentProfile = {
304
    ...binding.agent,
305
    transport: 'direct_a2a',
306
    agentMode:
307
      patch.agentMode ??
308
      binding.agent.agentMode ??
309
      (binding.agent.a2aEndpoint ? 'persistent_runtime' : 'temporary_chat'),
310
    ...(patch.name?.trim() ? { name: patch.name.trim() } : {}),
311
    ...(patch.description !== undefined ? { description: patch.description.trim() } : {}),
312
    ...(patch.framework?.trim() ? { framework: patch.framework.trim() } : {}),
313
    ...(patch.agentVersion?.trim() ? { agentVersion: patch.agentVersion.trim() } : {}),
314
    ...(patch.autoPublish !== undefined ? { autoPublish: patch.autoPublish } : {}),
315
    ...(patch.autoAcceptPolicy ? { autoAcceptPolicy: patch.autoAcceptPolicy } : {}),
316
    ...(patch.autoAcceptTaskCategories
317
      ? { autoAcceptTaskCategories: [...new Set(patch.autoAcceptTaskCategories)] }
318
      : {}),
319
    ...(patch.capabilities ? { capabilities: [...new Set(patch.capabilities)] } : {}),
320
    ...(patch.limitations ? { limitations: [...new Set(patch.limitations)] } : {}),
321
    updatedAt: new Date().toISOString(),
322
  };
323
  await store.upsert(operatorId, 'agent_profile', agent.agentId, agent);
324
  return agent;
325
}