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

Viewing files at commit 00864c3cb723Commit detailsView latest

apps/api/src/app.ts 738 lines · 31.3 KB · typescript
1
import Fastify from 'fastify';
2
import cors from '@fastify/cors';
3
import swagger from '@fastify/swagger';
4
import { z } from 'zod';
5
import {
6
  AgentIdentitySchema,
7
  DelegationCredentialSchema,
8
  FeedbackSchema,
9
  InteractionContractSchema,
10
  InteractionEventSchema,
11
  ReceiptSchema,
12
  FederatedInteractionSchema,
13
  LiveSessionEventSchema,
14
} from '../../../packages/protocol/src/index.js';
15
import {
16
  FixtureFactCheckProvider,
17
  MemoryAuditStore,
18
  TrustEngine,
19
} from '../../../packages/core/src/index.js';
20
import { buildPublicAgentCard } from '../../../packages/persistence/src/index.js';
21
import type { AgentProfile, HostedRepository } from '../../../packages/persistence/src/index.js';
22
import { toA2AAgentCard } from '../../../packages/sidecar/src/index.js';
23
import {
24
  approveAgentSetup,
25
  createHostedProviderAgent,
26
  getOnboardingState,
27
  rejectAgentSetup,
28
} from '../../../packages/persistence/src/onboarding.js';
29
30
type DashboardRepository = Pick<
31
  HostedRepository,
32
  | 'dashboard'
33
  | 'getSettings'
34
  | 'saveSettings'
35
  | 'upsert'
36
  | 'list'
37
  | 'publishAgent'
38
  | 'unpublishAgent'
39
  | 'getPublishedAgent'
40
  | 'searchPublishedAgents'
41
> &
42
  Partial<
43
    Pick<
44
      HostedRepository,
45
      | 'createFederatedInteraction'
46
      | 'listFederatedInteractions'
47
      | 'getFederatedInteraction'
48
      | 'respondToFederatedInteraction'
49
      | 'getLiveSession'
50
      | 'recordLiveSessionEvent'
51
      | 'touchAgentPresence'
52
      | 'getRuntimeVerificationKey'
53
      | 'registerAgentRuntime'
54
      | 'disableAgentRuntime'
55
      | 'deleteAgent'
56
      | 'issueAgentAccessToken'
57
      | 'listAgentAccessTokens'
58
      | 'revokeAgentAccessToken'
59
      | 'receiveTemporaryMessage'
60
      | 'sendTemporaryMessage'
61
      | 'listHostedThreads'
62
      | 'getHostedThread'
63
      | 'markHostedThreadRead'
64
      | 'closeHostedThread'
65
    >
66
  >;
67
68
export function buildApi(
69
  engine = new TrustEngine(),
70
  factChecker = new FixtureFactCheckProvider(),
71
  repository?: DashboardRepository,
72
) {
73
  const app = Fastify({
74
    logger: { redact: ['req.headers.authorization', 'req.body.rawMessage', 'req.body.privateKey'] },
75
  });
76
  const engines = new Map<string, Promise<TrustEngine>>();
77
  void app.register(cors, { origin: true });
78
  void app.register(swagger, { openapi: { info: { title: 'OpenClasp API', version: '0.1.0' } } });
79
80
  app.setErrorHandler((error, _request, reply) =>
81
    reply
82
      .status(
83
        error instanceof Error && 'statusCode' in error && typeof error.statusCode === 'number'
84
          ? error.statusCode
85
          : 400,
86
      )
87
      .send({ error: error instanceof Error ? error.message : 'Unknown error' }),
88
  );
89
  void app.register(async (router) => {
90
    const operatorId = (request: { headers: Record<string, unknown> }) => {
91
      const value = request.headers['x-openclasp-operator'];
92
      if (repository && typeof value !== 'string') {
93
        const error = new Error('Authentication required');
94
        Object.assign(error, { statusCode: 401 });
95
        throw error;
96
      }
97
      return typeof value === 'string' ? value : undefined;
98
    };
99
    const boundAgentId = (request: { headers: Record<string, unknown> }) => {
100
      const value = request.headers['x-openclasp-bound-agent'];
101
      if (typeof value !== 'string' || !value) {
102
        const error = new Error('Agent-bound authentication required');
103
        Object.assign(error, { statusCode: 401 });
104
        throw error;
105
      }
106
      return value;
107
    };
108
    const scopedEngine = async (request: { headers: Record<string, unknown> }) => {
109
      const owner = operatorId(request);
110
      if (!repository || !owner) return engine;
111
      let pending = engines.get(owner);
112
      if (!pending) {
113
        pending = repository.list(owner).then((rows) => {
114
          const store = new MemoryAuditStore();
115
          for (const row of rows) {
116
            if (row.kind !== 'interaction') store.append(row.kind, row.recordId, row.payload);
117
          }
118
          return new TrustEngine(store);
119
        });
120
        engines.set(owner, pending);
121
      }
122
      return pending;
123
    };
124
    const persist = async (
125
      request: { headers: Record<string, unknown> },
126
      kind: Parameters<HostedRepository['upsert']>[1],
127
      id: string,
128
      value: unknown,
129
    ) => {
130
      const owner = operatorId(request);
131
      if (repository && owner) await repository.upsert(owner, kind, id, value);
132
    };
133
    const publicBaseUrl = (request: { headers: Record<string, unknown> }) => {
134
      const forwardedHost = request.headers['x-forwarded-host'];
135
      const host = typeof forwardedHost === 'string' ? forwardedHost : request.headers.host;
136
      const forwardedProtocol = request.headers['x-forwarded-proto'];
137
      const protocol = typeof forwardedProtocol === 'string' ? forwardedProtocol : 'https';
138
      return process.env.OPENCLASP_PUBLIC_URL ?? `${protocol}://${String(host ?? 'localhost')}`;
139
    };
140
    router.get('/health', async () => ({ status: 'ok' }));
141
    router.get('/ready', async () => ({ status: 'ready' }));
142
    router.get('/openapi.json', async () => app.swagger());
143
    router.get('/.well-known/openclasp-session-key', async () => {
144
      if (!repository?.getRuntimeVerificationKey)
145
        throw new Error('Runtime verification is not configured');
146
      return repository.getRuntimeVerificationKey();
147
    });
148
    router.get('/extensions/trust/v0.1', async () => ({
149
      uri: 'https://openclasp.vercel.app/extensions/trust/v0.1',
150
      name: 'OpenClasp A2A assurance extension',
151
      version: '0.1',
152
      required: false,
153
      transportsMessages: false,
154
      temporaryChatAdapter: true,
155
      documentation: 'https://github.com/aryaamin/OpenClasp/blob/main/docs/A2A_EXTENSION.md',
156
    }));
157
    router.post('/sessions/:id/events', async (request, reply) => {
158
      if (!repository?.recordLiveSessionEvent)
159
        throw new Error('Live-session reporting is not configured');
160
      const authorization = request.headers.authorization;
161
      if (!authorization?.startsWith('Bearer ')) {
162
        reply.status(401);
163
        return { error: 'session_credential_required' };
164
      }
165
      const event = LiveSessionEventSchema.parse(request.body);
166
      if (event.interactionId !== (request.params as { id: string }).id)
167
        throw new Error('Interaction path does not match the event');
168
      return repository.recordLiveSessionEvent(authorization.slice(7), event);
169
    });
170
    router.post('/a2a/temporary/:id', async (request, reply) => {
171
      if (!repository?.receiveTemporaryMessage)
172
        throw new Error('Temporary chat delivery is not configured');
173
      const authorization = request.headers.authorization;
174
      if (!authorization?.startsWith('Bearer '))
175
        return reply.status(401).send({ error: 'session_credential_required' });
176
      const rpc = z
177
        .object({
178
          jsonrpc: z.literal('2.0'),
179
          id: z.union([z.string().min(1).max(200), z.number()]),
180
          method: z.literal('message/send'),
181
          params: z.object({
182
            message: z.object({
183
              parts: z.array(z.record(z.string(), z.unknown())).min(1).max(100),
184
            }),
185
          }),
186
        })
187
        .parse(request.body);
188
      const content = rpc.params.message.parts
189
        .map((part) => (typeof part.text === 'string' ? part.text : ''))
190
        .filter(Boolean)
191
        .join('\n')
192
        .trim();
193
      if (!content) throw new Error('Temporary chat MVP accepts text parts only');
194
      const recipientAgentId = (request.params as { id: string }).id;
195
      const result = await repository.receiveTemporaryMessage(
196
        authorization.slice(7),
197
        recipientAgentId,
198
        String(rpc.id),
199
        content,
200
      );
201
      return {
202
        jsonrpc: '2.0',
203
        id: rpc.id,
204
        result: {
205
          task: { id: result.message.messageId, state: 'submitted' },
206
          privacyMode: 'openclasp_hosted_temporary',
207
          deduplicated: result.deduplicated,
208
        },
209
      };
210
    });
211
    router.get('/agents/:id/card.json', async (request) => {
212
      if (!repository) throw new Error('Hosted persistence is not configured');
213
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
214
      if (!card) throw new Error('Published agent not found');
215
      return card;
216
    });
217
    router.get('/agents/:id/.well-known/openclasp-agent.json', async (request) => {
218
      if (!repository) throw new Error('Hosted persistence is not configured');
219
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
220
      if (!card) throw new Error('Published agent not found');
221
      return card;
222
    });
223
    router.get('/agents/:id/a2a-agent-card.json', async (request) => {
224
      if (!repository) throw new Error('Hosted persistence is not configured');
225
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
226
      if (!card) throw new Error('Published agent not found');
227
      if (!card.transports.length) throw new Error('Agent has not published an A2A endpoint');
228
      return toA2AAgentCard(card);
229
    });
230
    router.get('/v0.1/dashboard', async (request) => {
231
      const owner = operatorId(request);
232
      if (repository && owner) return repository.dashboard(owner);
233
      return {
234
        agents: [...engine.agents.values()],
235
        projects: [],
236
        installations: [],
237
        setupRequests: [],
238
        publications: [],
239
        interactions: [],
240
        federatedInteractions: [],
241
        liveSessions: [],
242
        hostedThreads: [],
243
        events: [...engine.events.values()],
244
        conflicts: [...engine.conflicts.values()],
245
        receipts: [...engine.receipts.values()],
246
        profiles: [...engine.profiles.values()],
247
        runtimes: [],
248
      };
249
    });
250
    router.get('/v0.1/account', async (request) => {
251
      const owner = operatorId(request);
252
      return {
253
        operatorId: owner,
254
        email: decodeURIComponent(String(request.headers['x-openclasp-email'] ?? '')),
255
        name: decodeURIComponent(String(request.headers['x-openclasp-name'] ?? '')),
256
      };
257
    });
258
    router.get('/v0.1/settings', async (request) => {
259
      const owner = operatorId(request);
260
      if (!repository || !owner)
261
        return {
262
          displayName: '',
263
          contributionEnabled: false,
264
          retentionDays: 30,
265
          evidenceSharing: 'ask',
266
          rawConversationsStored: false,
267
        };
268
      return repository.getSettings(owner);
269
    });
270
    router.get('/v0.1/onboarding', async (request) => {
271
      const owner = operatorId(request);
272
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
273
      return getOnboardingState(repository, owner);
274
    });
275
    router.get('/v0.1/runtime/bootstrap', async (request) => {
276
      operatorId(request);
277
      const agentId = boundAgentId(request);
278
      return {
279
        agentId,
280
        openClaspUrl: publicBaseUrl(request),
281
        runtimeRegistrationEndpoint: `${publicBaseUrl(request)}/v0.1/runtime`,
282
        protocol: 'A2A/1.0',
283
        controlProtocol: 'OpenClasp/0.1',
284
      };
285
    });
286
    router.put('/v0.1/runtime', async (request) => {
287
      const owner = operatorId(request);
288
      if (!repository?.registerAgentRuntime || !owner)
289
        throw new Error('Hosted runtime delivery is not configured');
290
      const endpoint = z
291
        .object({ endpoint: z.string().url().max(2048) })
292
        .parse(request.body).endpoint;
293
      return repository.registerAgentRuntime(owner, boundAgentId(request), endpoint);
294
    });
295
    router.post('/v0.1/runtime/heartbeat', async (request) => {
296
      const owner = operatorId(request);
297
      if (!repository?.touchAgentPresence || !owner)
298
        throw new Error('Agent presence is not configured');
299
      return repository.touchAgentPresence(owner, boundAgentId(request));
300
    });
301
    router.post('/v0.1/onboarding/:id/approve', async (request) => {
302
      const owner = operatorId(request);
303
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
304
      const requestId = (request.params as { id: string }).id;
305
      const state = await getOnboardingState(repository, owner);
306
      const setup = state.setupRequests.find((item) => item.requestId === requestId);
307
      const result = await approveAgentSetup(repository, owner, requestId);
308
      if (result.status === 'connected' && setup?.autoPublish) {
309
        const previous = await repository.getPublishedAgent(result.agent.agentId);
310
        const card = await repository.publishAgent(
311
          owner,
312
          buildPublicAgentCard(result.agent, publicBaseUrl(request), previous),
313
        );
314
        await repository.upsert(owner, 'publication', result.agent.agentId, {
315
          agentId: result.agent.agentId,
316
          published: true,
317
          updatedAt: card.updatedAt,
318
        });
319
      }
320
      return result;
321
    });
322
    router.post('/v0.1/onboarding/:id/reject', async (request) => {
323
      const owner = operatorId(request);
324
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
325
      return rejectAgentSetup(repository, owner, (request.params as { id: string }).id);
326
    });
327
    router.put('/v0.1/settings', async (request) => {
328
      const owner = operatorId(request);
329
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
330
      const value = z
331
        .object({
332
          displayName: z.string().trim().max(100),
333
          contributionEnabled: z.boolean(),
334
          retentionDays: z.number().int().min(0).max(3650),
335
          evidenceSharing: z.enum(['never', 'ask', 'contract_only']),
336
        })
337
        .parse(request.body);
338
      return repository.saveSettings(owner, value);
339
    });
340
    router.post('/v0.1/provider-connections', async (request) => {
341
      const owner = operatorId(request);
342
      if (!repository?.issueAgentAccessToken || !owner)
343
        throw new Error('Hosted provider connections are not configured');
344
      const value = z
345
        .object({
346
          provider: z.enum(['botpress', 'custom']),
347
          agentName: z.string().trim().min(1).max(100),
348
          projectName: z.string().trim().min(1).max(100),
349
          description: z.string().trim().max(500).optional(),
350
          capabilities: z.array(z.string().trim().min(1).max(100)).max(100).default([]),
351
          limitations: z.array(z.string().trim().min(1).max(300)).max(100).default([]),
352
          expiresInDays: z.number().int().min(1).max(365).default(365),
353
        })
354
        .parse(request.body);
355
      const created = await createHostedProviderAgent(repository, owner, value);
356
      try {
357
        const accessToken = await repository.issueAgentAccessToken(owner, created.agent.agentId, {
358
          name: 'Botpress',
359
          expiresInDays: value.expiresInDays,
360
        });
361
        return { ...created, provider: value.provider, accessToken };
362
      } catch (error) {
363
        if (repository.deleteAgent)
364
          await repository.deleteAgent(owner, created.agent.agentId).catch(() => undefined);
365
        throw error;
366
      }
367
    });
368
    router.post('/v0.1/agents', async (request) => {
369
      const owner = operatorId(request);
370
      const current = await scopedEngine(request);
371
      const identity = AgentIdentitySchema.parse(request.body);
372
      if (owner && identity.operatorRef !== `auth0:${owner}`)
373
        throw new Error('Agent identity is not owned by the authenticated operator');
374
      const registered = current.registerAgent(identity);
375
      await persist(request, 'agent', identity.agentId, registered);
376
      return registered;
377
    });
378
    router.get('/v0.1/agents/:id', async (request) => {
379
      const { id } = request.params as { id: string };
380
      const value = (await scopedEngine(request)).agents.get(id);
381
      if (!value) throw new Error('Agent not found');
382
      return value;
383
    });
384
    router.post('/v0.1/agents/:id/publication', async (request) => {
385
      const owner = operatorId(request);
386
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
387
      const { id } = request.params as { id: string };
388
      const { published } = z.object({ published: z.boolean() }).parse(request.body);
389
      const rows = await repository.list(owner);
390
      const agent = rows.find((row) => row.kind === 'agent_profile' && row.recordId === id)
391
        ?.payload as AgentProfile | undefined;
392
      if (!agent) throw new Error('Owned agent not found');
393
      if (agent.status !== 'active') throw new Error('Revoked agents cannot be published');
394
      if (!published) {
395
        await repository.unpublishAgent(owner, id);
396
        const publication = { agentId: id, published: false, updatedAt: new Date().toISOString() };
397
        await repository.upsert(owner, 'publication', id, publication);
398
        return publication;
399
      }
400
      const previous = await repository.getPublishedAgent(id);
401
      const card = await repository.publishAgent(
402
        owner,
403
        buildPublicAgentCard(agent, publicBaseUrl(request), previous),
404
      );
405
      const publication = { agentId: id, published: true, updatedAt: card.updatedAt };
406
      await repository.upsert(owner, 'publication', id, publication);
407
      return { ...publication, card };
408
    });
409
    router.put('/v0.1/agents/:id/automation', async (request) => {
410
      const owner = operatorId(request);
411
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
412
      const { id } = request.params as { id: string };
413
      const value = z
414
        .object({
415
          autoPublish: z.boolean(),
416
          autoAcceptPolicy: z.enum(['off', 'safe_matching']),
417
          autoAcceptTaskCategories: z.array(z.string().trim().min(1).max(100)).max(100),
418
        })
419
        .parse(request.body);
420
      const rows = await repository.list(owner);
421
      const current = rows.find((row) => row.kind === 'agent_profile' && row.recordId === id)
422
        ?.payload as AgentProfile | undefined;
423
      if (!current) throw new Error('Owned agent not found');
424
      const agent: AgentProfile = {
425
        ...current,
426
        transport: 'direct_a2a',
427
        description: current.description ?? '',
428
        agentVersion: current.agentVersion ?? '1.0.0',
429
        autoPublish: value.autoPublish,
430
        autoAcceptPolicy: value.autoAcceptPolicy,
431
        autoAcceptTaskCategories: [...new Set(value.autoAcceptTaskCategories)],
432
        updatedAt: new Date().toISOString(),
433
      };
434
      await repository.upsert(owner, 'agent_profile', id, agent);
435
      if (value.autoPublish) {
436
        const previous = await repository.getPublishedAgent(id);
437
        const card = await repository.publishAgent(
438
          owner,
439
          buildPublicAgentCard(agent, publicBaseUrl(request), previous),
440
        );
441
        await repository.upsert(owner, 'publication', id, {
442
          agentId: id,
443
          published: true,
444
          updatedAt: card.updatedAt,
445
        });
446
      } else {
447
        await repository.unpublishAgent(owner, id);
448
        await repository.upsert(owner, 'publication', id, {
449
          agentId: id,
450
          published: false,
451
          updatedAt: new Date().toISOString(),
452
        });
453
      }
454
      return agent;
455
    });
456
    router.put('/v0.1/agents/:id/runtime', async (request) => {
457
      const owner = operatorId(request);
458
      if (!repository?.registerAgentRuntime || !owner)
459
        throw new Error('Hosted runtime delivery is not configured');
460
      const endpoint = z
461
        .object({ endpoint: z.string().url().max(2048) })
462
        .parse(request.body).endpoint;
463
      return repository.registerAgentRuntime(
464
        owner,
465
        (request.params as { id: string }).id,
466
        endpoint,
467
      );
468
    });
469
    router.delete('/v0.1/agents/:id/runtime', async (request) => {
470
      const owner = operatorId(request);
471
      if (!repository?.disableAgentRuntime || !owner)
472
        throw new Error('Hosted runtime delivery is not configured');
473
      return repository.disableAgentRuntime(owner, (request.params as { id: string }).id);
474
    });
475
    router.get('/v0.1/agents/:id/access-tokens', async (request) => {
476
      const owner = operatorId(request);
477
      if (!repository?.listAgentAccessTokens || !owner)
478
        throw new Error('Agent access tokens are not configured');
479
      return repository.listAgentAccessTokens(owner, (request.params as { id: string }).id);
480
    });
481
    router.post('/v0.1/agents/:id/access-tokens', async (request) => {
482
      const owner = operatorId(request);
483
      if (!repository?.issueAgentAccessToken || !owner)
484
        throw new Error('Agent access tokens are not configured');
485
      const value = z
486
        .object({
487
          name: z.string().trim().min(1).max(100),
488
          expiresInDays: z.number().int().min(1).max(365).default(365),
489
        })
490
        .parse(request.body);
491
      return repository.issueAgentAccessToken(owner, (request.params as { id: string }).id, value);
492
    });
493
    router.delete('/v0.1/agents/:id/access-tokens/:tokenId', async (request) => {
494
      const owner = operatorId(request);
495
      if (!repository?.revokeAgentAccessToken || !owner)
496
        throw new Error('Agent access tokens are not configured');
497
      const params = request.params as { id: string; tokenId: string };
498
      return repository.revokeAgentAccessToken(owner, params.id, params.tokenId);
499
    });
500
    router.delete('/v0.1/agents/:id', async (request) => {
501
      const owner = operatorId(request);
502
      if (!repository?.deleteAgent || !owner)
503
        throw new Error('Hosted agent deletion is not configured');
504
      const result = await repository.deleteAgent(owner, (request.params as { id: string }).id);
505
      engines.delete(owner);
506
      return result;
507
    });
508
    router.get('/v0.1/agents/:id/threads', async (request) => {
509
      const owner = operatorId(request);
510
      if (!repository?.listHostedThreads || !owner)
511
        throw new Error('Temporary chat history is not configured');
512
      return repository.listHostedThreads(owner, (request.params as { id: string }).id);
513
    });
514
    router.get('/v0.1/agents/:id/threads/:threadId', async (request) => {
515
      const owner = operatorId(request);
516
      if (!repository?.getHostedThread || !owner)
517
        throw new Error('Temporary chat history is not configured');
518
      const params = request.params as { id: string; threadId: string };
519
      return repository.getHostedThread(owner, params.id, params.threadId);
520
    });
521
    router.post('/v0.1/agents/:id/messages', async (request) => {
522
      const owner = operatorId(request);
523
      if (!repository?.sendTemporaryMessage || !owner)
524
        throw new Error('Temporary chat delivery is not configured');
525
      const value = z
526
        .object({ interactionId: z.string().uuid(), content: z.string().trim().min(1).max(20_000) })
527
        .parse(request.body);
528
      return repository.sendTemporaryMessage(
529
        owner,
530
        (request.params as { id: string }).id,
531
        value.interactionId,
532
        value.content,
533
      );
534
    });
535
    router.post('/v0.1/agents/:id/threads/:threadId/read', async (request) => {
536
      const owner = operatorId(request);
537
      if (!repository?.markHostedThreadRead || !owner)
538
        throw new Error('Temporary chat history is not configured');
539
      const params = request.params as { id: string; threadId: string };
540
      return repository.markHostedThreadRead(owner, params.id, params.threadId);
541
    });
542
    router.post('/v0.1/agents/:id/threads/:threadId/close', async (request) => {
543
      const owner = operatorId(request);
544
      if (!repository?.closeHostedThread || !owner)
545
        throw new Error('Temporary chat history is not configured');
546
      const params = request.params as { id: string; threadId: string };
547
      return repository.closeHostedThread(owner, params.id, params.threadId);
548
    });
549
    router.get('/v0.1/directory', async (request) => {
550
      operatorId(request);
551
      if (!repository) throw new Error('Hosted persistence is not configured');
552
      const query = z
553
        .object({
554
          query: z.string().trim().max(100).optional(),
555
          capability: z.string().trim().max(100).optional(),
556
          limit: z.coerce.number().int().min(1).max(50).optional(),
557
        })
558
        .parse(request.query);
559
      return repository.searchPublishedAgents(query);
560
    });
561
    router.get('/v0.1/directory/:id', async (request) => {
562
      operatorId(request);
563
      if (!repository) throw new Error('Hosted persistence is not configured');
564
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
565
      if (!card) throw new Error('Published agent not found');
566
      return card;
567
    });
568
    router.get('/v0.1/federated-interactions', async (request) => {
569
      const owner = operatorId(request);
570
      if (!repository?.listFederatedInteractions || !owner)
571
        throw new Error('Federated interactions are not configured');
572
      return repository.listFederatedInteractions(owner);
573
    });
574
    router.get('/v0.1/federated-interactions/:id', async (request) => {
575
      const owner = operatorId(request);
576
      if (!repository?.getFederatedInteraction || !owner)
577
        throw new Error('Federated interactions are not configured');
578
      const interaction = await repository.getFederatedInteraction(
579
        owner,
580
        (request.params as { id: string }).id,
581
      );
582
      if (!interaction) throw new Error('Interaction not found');
583
      return interaction;
584
    });
585
    router.get('/v0.1/federated-interactions/:id/session', async (request) => {
586
      const owner = operatorId(request);
587
      if (!repository?.getLiveSession || !owner)
588
        throw new Error('Live sessions are not configured');
589
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
590
      return repository.getLiveSession(owner, (request.params as { id: string }).id, value.agentId);
591
    });
592
    router.post('/v0.1/federated-interactions', async (request) => {
593
      const owner = operatorId(request);
594
      if (!repository?.createFederatedInteraction || !owner)
595
        throw new Error('Federated interactions are not configured');
596
      const interaction = FederatedInteractionSchema.parse(request.body);
597
      const acceptance = interaction.acceptances[interaction.initiatorAgentId];
598
      if (!acceptance) throw new Error('Initiator acceptance is required');
599
      return repository.createFederatedInteraction(owner, {
600
        ...interaction,
601
        acceptances: {
602
          [interaction.initiatorAgentId]: { ...acceptance, method: 'oauth_account' },
603
        },
604
      });
605
    });
606
    router.post('/v0.1/federated-interactions/:id/respond', async (request) => {
607
      const owner = operatorId(request);
608
      if (!repository?.respondToFederatedInteraction || !owner)
609
        throw new Error('Federated interactions are not configured');
610
      const value = z
611
        .object({ agentId: z.string().min(1), decision: z.enum(['accept', 'reject']) })
612
        .parse(request.body);
613
      return repository.respondToFederatedInteraction(
614
        owner,
615
        (request.params as { id: string }).id,
616
        value.agentId,
617
        value.decision,
618
        'oauth_account',
619
      );
620
    });
621
    router.post('/v0.1/delegations', async (request) => {
622
      const value = DelegationCredentialSchema.parse(request.body);
623
      const current = await scopedEngine(request);
624
      current.delegations.set(value.delegationId, value);
625
      await persist(request, 'delegation', value.delegationId, value);
626
      return { valid: current.verifyDelegation(value.delegationId) };
627
    });
628
    router.post('/v0.1/delegations/:id/verify', async (request) => ({
629
      valid: (await scopedEngine(request)).verifyDelegation((request.params as { id: string }).id),
630
    }));
631
    router.post('/v0.1/interactions/contracts', async (request) => {
632
      const contract = (await scopedEngine(request)).saveContract(
633
        InteractionContractSchema.parse(request.body),
634
      );
635
      await persist(request, 'contract', contract.interactionId, contract);
636
      return contract;
637
    });
638
    router.post('/v0.1/events', async (request) => {
639
      const event = (await scopedEngine(request)).recordEvent(
640
        InteractionEventSchema.parse(request.body),
641
      );
642
      await persist(request, 'event', event.eventId, event);
643
      return event;
644
    });
645
    router.post('/v0.1/risk/assess', async (request) =>
646
      (await scopedEngine(request)).assess(request.body as any),
647
    );
648
    router.get('/v0.1/profiles/:id', async (request) => {
649
      const { id } = request.params as { id: string };
650
      const query = request.query as { version?: string; taskCategory?: string };
651
      return (await scopedEngine(request)).getRisk(
652
        id,
653
        query.version ?? '1.0.0',
654
        query.taskCategory ?? 'general',
655
      );
656
    });
657
    router.post('/v0.1/claims/check', async (request) =>
658
      ((value) => factChecker.check(value.claim, value.permission))(
659
        z.object({ claim: z.string(), permission: z.boolean().optional() }).parse(request.body),
660
      ),
661
    );
662
    router.post('/v0.1/receipts', async (request) => {
663
      const receipt = (await scopedEngine(request)).submitReceipt(
664
        ReceiptSchema.parse(request.body),
665
      );
666
      await persist(request, 'receipt', receipt.receiptId, receipt);
667
      return receipt;
668
    });
669
    router.post('/v0.1/receipts/verify', async (request) => {
670
      try {
671
        (await scopedEngine(request)).verifyReceipt(ReceiptSchema.parse(request.body));
672
        return { valid: true };
673
      } catch {
674
        return { valid: false };
675
      }
676
    });
677
    router.post('/v0.1/feedback', async (request) => {
678
      const feedback = FeedbackSchema.parse(request.body);
679
      const current = await scopedEngine(request);
680
      const result = current.submitFeedback(feedback);
681
      await persist(request, 'feedback', feedback.feedbackId, feedback);
682
      for (const profile of current.profiles.values())
683
        await persist(
684
          request,
685
          'profile',
686
          `${profile.agentId}|${profile.agentVersion}|${profile.taskCategory}`,
687
          profile,
688
        );
689
      return result;
690
    });
691
    router.post('/v0.1/conflicts', async (request) => {
692
      const conflict = (await scopedEngine(request)).createConflict(request.body as any);
693
      await persist(request, 'conflict', conflict.conflictId, conflict);
694
      return conflict;
695
    });
696
    router.post('/v0.1/conflicts/:id/permit', async (request) => {
697
      const conflict = (await scopedEngine(request)).permitMediation(
698
        (request.params as { id: string }).id,
699
        (request.body as { agentId: string }).agentId,
700
      );
701
      await persist(request, 'conflict', conflict.conflictId, conflict);
702
      return conflict;
703
    });
704
    router.post('/v0.1/conflicts/:id/resolve', async (request) => {
705
      const conflict = (await scopedEngine(request)).resolveConflict(
706
        (request.params as { id: string }).id,
707
        (request.body as { resolution: string }).resolution,
708
      );
709
      await persist(request, 'conflict', conflict.conflictId, conflict);
710
      return conflict;
711
    });
712
    router.post('/v0.1/revocations/agents/:id', async (request) => {
713
      const id = (request.params as { id: string }).id;
714
      const current = await scopedEngine(request);
715
      current.revokeAgent(id);
716
      await persist(request, 'agent', id, current.agents.get(id));
717
      return { revoked: true };
718
    });
719
    router.post('/v0.1/revocations/delegations/:id', async (request) => {
720
      const id = (request.params as { id: string }).id;
721
      const current = await scopedEngine(request);
722
      current.revokeDelegation(id);
723
      await persist(request, 'delegation', id, current.delegations.get(id));
724
      return { revoked: true };
725
    });
726
    router.post('/v0.1/contributions/consent', async (request) => {
727
      const value = z.object({ agentId: z.string(), enabled: z.boolean() }).parse(request.body);
728
      const current = await scopedEngine(request);
729
      current.setContributionConsent(value.agentId, value.enabled);
730
      await persist(request, 'consent', value.agentId, {
731
        agentId: value.agentId,
732
        ...current.contributionConsent.get(value.agentId),
733
      });
734
      return value;
735
    });
736
  });
737
  return app;
738
}