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

Viewing files at commit eaaa2f905f1dCommit detailsView latest

apps/api/src/app.ts 1050 lines · 46.5 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
  InteractionCompletionReportSchema,
15
  InteractionFeedbackSchema,
16
} from '../../../packages/protocol/src/index.js';
17
import {
18
  FixtureFactCheckProvider,
19
  MemoryAuditStore,
20
  TrustEngine,
21
} from '../../../packages/core/src/index.js';
22
import { buildPublicAgentCard } from '../../../packages/persistence/src/index.js';
23
import type { AgentProfile, HostedRepository } from '../../../packages/persistence/src/index.js';
24
import { toA2AAgentCard } from '../../../packages/sidecar/src/index.js';
25
import {
26
  approveAgentSetup,
27
  createHostedProviderAgent,
28
  getOnboardingState,
29
  rejectAgentSetup,
30
} from '../../../packages/persistence/src/onboarding.js';
31
32
type DashboardRepository = Pick<
33
  HostedRepository,
34
  | 'getSettings'
35
  | 'saveSettings'
36
  | 'upsert'
37
  | 'list'
38
  | 'publishAgent'
39
  | 'unpublishAgent'
40
  | 'getPublishedAgent'
41
  | 'resolveAgentReference'
42
  | 'searchPublishedAgents'
43
> & {
44
  dashboard(operatorId: string): Promise<Record<string, unknown>>;
45
} & Partial<
46
    Pick<
47
      HostedRepository,
48
      | 'createFederatedInteraction'
49
      | 'listFederatedInteractions'
50
      | 'getFederatedInteraction'
51
      | 'respondToFederatedInteraction'
52
      | 'proposeContractRevision'
53
      | 'respondToContractRevision'
54
      | 'getLiveSession'
55
      | 'getCounterpartyBrief'
56
      | 'submitCompletionReport'
57
      | 'recordSessionCompletionReport'
58
      | 'submitInteractionFeedback'
59
      | 'recordSessionFeedback'
60
      | 'listFeedbackRequests'
61
      | 'recordLiveSessionEvent'
62
      | 'touchAgentPresence'
63
      | 'getRuntimeVerificationKey'
64
      | 'registerAgentRuntime'
65
      | 'disableAgentRuntime'
66
      | 'deleteAgent'
67
      | 'issueAgentAccessToken'
68
      | 'listAgentAccessTokens'
69
      | 'revokeAgentAccessToken'
70
      | 'receiveTemporaryMessage'
71
      | 'sendTemporaryMessage'
72
      | 'listHostedThreads'
73
      | 'getHostedThread'
74
      | 'markHostedThreadRead'
75
      | 'closeHostedThread'
76
    >
77
  > & {
78
    listContextualIntelligence?: (
79
      operatorId: string,
80
      input?: { agentId?: string; taskCategory?: string },
81
    ) => Promise<any[]>;
82
    searchPersonalizedMarketplace?: (
83
      operatorId: string,
84
      input?: { agentId?: string; taskCategory?: string; query?: string; limit?: number },
85
    ) => Promise<any[]>;
86
  };
87
88
export function buildApi(
89
  engine = new TrustEngine(),
90
  factChecker = new FixtureFactCheckProvider(),
91
  repository?: DashboardRepository,
92
) {
93
  const app = Fastify({
94
    logger: { redact: ['req.headers.authorization', 'req.body.rawMessage', 'req.body.privateKey'] },
95
  });
96
  const engines = new Map<string, Promise<TrustEngine>>();
97
  void app.register(cors, { origin: true });
98
  void app.register(swagger, { openapi: { info: { title: 'OpenClasp API', version: '0.1.0' } } });
99
100
  app.setErrorHandler((error, _request, reply) =>
101
    reply
102
      .status(
103
        error instanceof Error && 'statusCode' in error && typeof error.statusCode === 'number'
104
          ? error.statusCode
105
          : 400,
106
      )
107
      .send({ error: error instanceof Error ? error.message : 'Unknown error' }),
108
  );
109
  void app.register(async (router) => {
110
    const operatorId = (request: { headers: Record<string, unknown> }) => {
111
      const value = request.headers['x-openclasp-operator'];
112
      if (repository && typeof value !== 'string') {
113
        const error = new Error('Authentication required');
114
        Object.assign(error, { statusCode: 401 });
115
        throw error;
116
      }
117
      return typeof value === 'string' ? value : undefined;
118
    };
119
    const boundAgentId = (request: { headers: Record<string, unknown> }) => {
120
      const value = request.headers['x-openclasp-bound-agent'];
121
      if (typeof value !== 'string' || !value) {
122
        const error = new Error('Agent-bound authentication required');
123
        Object.assign(error, { statusCode: 401 });
124
        throw error;
125
      }
126
      return value;
127
    };
128
    const enforceBoundAgent = (
129
      request: { headers: Record<string, unknown> },
130
      requestedAgentId: string,
131
    ) => {
132
      const value = request.headers['x-openclasp-bound-agent'];
133
      if (typeof value === 'string' && value !== requestedAgentId) {
134
        const error = new Error('Agent credential cannot access another agent');
135
        Object.assign(error, { statusCode: 403 });
136
        throw error;
137
      }
138
    };
139
    const scopedEngine = async (request: { headers: Record<string, unknown> }) => {
140
      const owner = operatorId(request);
141
      if (!repository || !owner) return engine;
142
      let pending = engines.get(owner);
143
      if (!pending) {
144
        pending = repository.list(owner).then((rows) => {
145
          const store = new MemoryAuditStore();
146
          for (const row of rows) {
147
            if (row.kind !== 'interaction') store.append(row.kind, row.recordId, row.payload);
148
          }
149
          return new TrustEngine(store);
150
        });
151
        engines.set(owner, pending);
152
      }
153
      return pending;
154
    };
155
    const persist = async (
156
      request: { headers: Record<string, unknown> },
157
      kind: Parameters<HostedRepository['upsert']>[1],
158
      id: string,
159
      value: unknown,
160
    ) => {
161
      const owner = operatorId(request);
162
      if (repository && owner) await repository.upsert(owner, kind, id, value);
163
    };
164
    const publicBaseUrl = (request: { headers: Record<string, unknown> }) => {
165
      const forwardedHost = request.headers['x-forwarded-host'];
166
      const host = typeof forwardedHost === 'string' ? forwardedHost : request.headers.host;
167
      const forwardedProtocol = request.headers['x-forwarded-proto'];
168
      const protocol = typeof forwardedProtocol === 'string' ? forwardedProtocol : 'https';
169
      return process.env.OPENCLASP_PUBLIC_URL ?? `${protocol}://${String(host ?? 'localhost')}`;
170
    };
171
    const escapeHtml = (value: string) =>
172
      value.replace(/[&<>"']/g, (character) => {
173
        const entities: Record<string, string> = {
174
          '&': '&amp;',
175
          '<': '&lt;',
176
          '>': '&gt;',
177
          '"': '&quot;',
178
          "'": '&#39;',
179
        };
180
        return entities[character]!;
181
      });
182
    router.get('/health', async () => ({ status: 'ok' }));
183
    router.get('/ready', async () => ({ status: 'ready' }));
184
    router.get('/openapi.json', async () => app.swagger());
185
    router.get('/.well-known/openclasp-session-key', async () => {
186
      if (!repository?.getRuntimeVerificationKey)
187
        throw new Error('Runtime verification is not configured');
188
      return repository.getRuntimeVerificationKey();
189
    });
190
    router.get('/extensions/trust/v0.1', async () => ({
191
      uri: 'https://openclasp.vercel.app/extensions/trust/v0.1',
192
      name: 'OpenClasp A2A assurance extension',
193
      version: '0.1',
194
      required: false,
195
      transportsMessages: false,
196
      temporaryChatAdapter: true,
197
      documentation: 'https://github.com/aryaamin/OpenClasp/blob/main/docs/A2A_EXTENSION.md',
198
    }));
199
    router.post('/sessions/:id/events', async (request, reply) => {
200
      if (!repository?.recordLiveSessionEvent)
201
        throw new Error('Live-session reporting is not configured');
202
      const authorization = request.headers.authorization;
203
      if (!authorization?.startsWith('Bearer ')) {
204
        reply.status(401);
205
        return { error: 'session_credential_required' };
206
      }
207
      const event = LiveSessionEventSchema.parse(request.body);
208
      if (event.interactionId !== (request.params as { id: string }).id)
209
        throw new Error('Interaction path does not match the event');
210
      return repository.recordLiveSessionEvent(authorization.slice(7), event);
211
    });
212
    router.post('/sessions/:id/completion-reports', async (request, reply) => {
213
      if (!repository?.recordSessionCompletionReport)
214
        throw new Error('Live-session completion reporting is not configured');
215
      const authorization = request.headers.authorization;
216
      if (!authorization?.startsWith('Bearer ')) {
217
        reply.status(401);
218
        return { error: 'session_credential_required' };
219
      }
220
      const report = InteractionCompletionReportSchema.parse(request.body);
221
      if (report.interactionId !== (request.params as { id: string }).id)
222
        throw new Error('Interaction path does not match the completion report');
223
      return repository.recordSessionCompletionReport(authorization.slice(7), report);
224
    });
225
    router.post('/sessions/:id/feedback', async (request, reply) => {
226
      if (!repository?.recordSessionFeedback)
227
        throw new Error('Live-session feedback is not configured');
228
      const authorization = request.headers.authorization;
229
      if (!authorization?.startsWith('Bearer ')) {
230
        reply.status(401);
231
        return { error: 'session_credential_required' };
232
      }
233
      const feedback = InteractionFeedbackSchema.parse(request.body);
234
      if (feedback.interactionId !== (request.params as { id: string }).id)
235
        throw new Error('Interaction path does not match the feedback');
236
      return repository.recordSessionFeedback(authorization.slice(7), feedback);
237
    });
238
    router.post('/a2a/temporary/:id', async (request, reply) => {
239
      if (!repository?.receiveTemporaryMessage)
240
        throw new Error('Temporary chat delivery is not configured');
241
      const authorization = request.headers.authorization;
242
      if (!authorization?.startsWith('Bearer '))
243
        return reply.status(401).send({ error: 'session_credential_required' });
244
      const rpc = z
245
        .object({
246
          jsonrpc: z.literal('2.0'),
247
          id: z.union([z.string().min(1).max(200), z.number()]),
248
          method: z.literal('message/send'),
249
          params: z.object({
250
            message: z.object({
251
              parts: z.array(z.record(z.string(), z.unknown())).min(1).max(100),
252
            }),
253
          }),
254
        })
255
        .parse(request.body);
256
      const content = rpc.params.message.parts
257
        .map((part) => (typeof part.text === 'string' ? part.text : ''))
258
        .filter(Boolean)
259
        .join('\n')
260
        .trim();
261
      if (!content) throw new Error('Temporary chat MVP accepts text parts only');
262
      const recipientAgentId = (request.params as { id: string }).id;
263
      const result = await repository.receiveTemporaryMessage(
264
        authorization.slice(7),
265
        recipientAgentId,
266
        String(rpc.id),
267
        content,
268
      );
269
      return {
270
        jsonrpc: '2.0',
271
        id: rpc.id,
272
        result: {
273
          task: { id: result.message.messageId, state: 'submitted' },
274
          privacyMode: 'openclasp_hosted_temporary',
275
          deduplicated: result.deduplicated,
276
        },
277
      };
278
    });
279
    router.get('/agents/:id/card.json', async (request) => {
280
      if (!repository) throw new Error('Hosted persistence is not configured');
281
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
282
      if (!card) throw new Error('Published agent not found');
283
      return card;
284
    });
285
    router.get('/agents/:id/.well-known/openclasp-agent.json', async (request) => {
286
      if (!repository) throw new Error('Hosted persistence is not configured');
287
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
288
      if (!card) throw new Error('Published agent not found');
289
      return card;
290
    });
291
    router.get('/agents/:id/a2a-agent-card.json', async (request) => {
292
      if (!repository) throw new Error('Hosted persistence is not configured');
293
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
294
      if (!card) throw new Error('Published agent not found');
295
      if (!card.transports.length) throw new Error('Agent has not published an A2A endpoint');
296
      return toA2AAgentCard(card);
297
    });
298
    router.get('/directory/resolve', async (request) => {
299
      if (!repository) throw new Error('Hosted persistence is not configured');
300
      const { reference } = z
301
        .object({ reference: z.string().min(1).max(2048) })
302
        .parse(request.query);
303
      const result = await repository.resolveAgentReference(reference);
304
      if (!result) throw new Error('Published agent not found');
305
      return result;
306
    });
307
    router.get('/directory/search', async (request) => {
308
      if (!repository) throw new Error('Hosted persistence is not configured');
309
      const input = z
310
        .object({
311
          query: z.string().trim().max(100).optional(),
312
          capability: z.string().trim().max(100).optional(),
313
          limit: z.coerce.number().int().min(1).max(50).optional(),
314
        })
315
        .parse(request.query);
316
      return repository.searchPublishedAgents(input);
317
    });
318
    router.get('/a/:reference', async (request, reply) => {
319
      if (!repository) throw new Error('Hosted persistence is not configured');
320
      const result = await repository.resolveAgentReference(
321
        (request.params as { reference: string }).reference,
322
      );
323
      if (!result) throw new Error('Published agent not found');
324
      const { card } = result;
325
      const capabilities = card.capabilities
326
        .map((capability) => `<li>${escapeHtml(capability)}</li>`)
327
        .join('');
328
      const limitations = card.limitations
329
        .map((limitation) => `<li>${escapeHtml(limitation)}</li>`)
330
        .join('');
331
      const structured = JSON.stringify({
332
        '@context': 'https://schema.org',
333
        '@type': 'SoftwareApplication',
334
        name: card.name,
335
        description: card.description,
336
        url: card.profileUrl,
337
      }).replace(/</g, '\\u003c');
338
      return reply.type('text/html; charset=utf-8').send(`<!doctype html>
339
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
340
<title>${escapeHtml(card.name)} · OpenClasp</title><meta name="description" content="${escapeHtml(card.description)}">
341
<meta property="og:title" content="${escapeHtml(card.name)} · OpenClasp verified agent"><meta property="og:description" content="${escapeHtml(card.description)}">
342
<style>color-scheme:dark;*{box-sizing:border-box}body{margin:0;background:#0c0a0a;color:#f6f1ee;font:15px/1.55 Inter,system-ui,sans-serif}main{max-width:760px;margin:0 auto;padding:64px 24px}.brand{color:#f04b2d;font-weight:700}.verified{display:inline-block;margin:24px 0 8px;padding:5px 9px;border:1px solid #2fbf71;color:#2fbf71;border-radius:999px;font-size:12px}h1{font-size:42px;line-height:1.05;margin:8px 0 12px}p{color:#a39a94}.grid{display:grid;grid-template-columns:1fr 1fr;gap:32px;margin:36px 0}h2{font-size:13px;text-transform:uppercase;letter-spacing:.08em;color:#a39a94}a{color:#f04b2d;overflow-wrap:anywhere}.links{padding-top:24px;border-top:1px solid #2b2523}.status{color:${card.presence?.status === 'online' ? '#2fbf71' : '#a39a94'}}@media(max-width:600px){.grid{grid-template-columns:1fr}h1{font-size:34px}}</style>
343
<script type="application/ld+json">${structured}</script></head><body><main><div class="brand">OpenClasp</div><div class="verified">✓ Account and agent ownership verified</div>
344
<h1>${escapeHtml(card.name)}</h1><p>${escapeHtml(card.description || 'No description provided.')}</p><p class="status">${escapeHtml(card.presence?.status ?? 'offline')} · ${escapeHtml(card.agentMode.replace('_', ' '))}</p>
345
<div class="grid"><section><h2>Capabilities</h2><ul>${capabilities || '<li>None published</li>'}</ul></section><section><h2>Limitations</h2><ul>${limitations || '<li>None published</li>'}</ul></section></div>
346
<div class="links"><p><strong>Agent ID</strong><br>${escapeHtml(card.agentId)}</p><p><a href="${escapeHtml(card.cardUrl)}">OpenClasp card</a> · <a href="${escapeHtml(card.a2aAgentCardUrl)}">A2A Agent Card</a></p></div></main></body></html>`);
347
    });
348
    router.get('/v0.1/dashboard', async (request) => {
349
      const owner = operatorId(request);
350
      if (repository && owner) return repository.dashboard(owner);
351
      return {
352
        agents: [...engine.agents.values()],
353
        projects: [],
354
        installations: [],
355
        setupRequests: [],
356
        publications: [],
357
        interactions: [],
358
        federatedInteractions: [],
359
        liveSessions: [],
360
        hostedThreads: [],
361
        events: [...engine.events.values()],
362
        conflicts: [...engine.conflicts.values()],
363
        receipts: [...engine.receipts.values()],
364
        profiles: [...engine.profiles.values()],
365
        counterpartyBriefs: [],
366
        completionReports: [],
367
        feedbackRequests: [],
368
        interactionFeedback: [],
369
        interactionConclusions: [],
370
        learningEligibility: [],
371
        profileDeltas: [],
372
        intelligenceSummaries: [],
373
        runtimes: [],
374
      };
375
    });
376
    router.get('/v0.1/intelligence', async (request) => {
377
      const owner = operatorId(request);
378
      if (!repository?.listContextualIntelligence || !owner)
379
        throw new Error('Contextual intelligence is not configured');
380
      const input = z
381
        .object({
382
          agentId: z.string().min(1).optional(),
383
          taskCategory: z.string().trim().min(1).max(100).optional(),
384
        })
385
        .parse(request.query);
386
      return repository.listContextualIntelligence(owner, {
387
        ...(input.agentId ? { agentId: input.agentId } : {}),
388
        ...(input.taskCategory ? { taskCategory: input.taskCategory } : {}),
389
      });
390
    });
391
    router.get('/v0.1/marketplace', async (request) => {
392
      const owner = operatorId(request);
393
      if (!repository?.searchPersonalizedMarketplace || !owner)
394
        throw new Error('Personalized marketplace is not configured');
395
      const input = z
396
        .object({
397
          agentId: z.string().min(1).optional(),
398
          taskCategory: z.string().trim().min(1).max(100).optional(),
399
          query: z.string().trim().max(100).optional(),
400
          limit: z.coerce.number().int().min(1).max(50).default(30),
401
        })
402
        .parse(request.query);
403
      return repository.searchPersonalizedMarketplace(owner, {
404
        ...(input.agentId ? { agentId: input.agentId } : {}),
405
        ...(input.taskCategory ? { taskCategory: input.taskCategory } : {}),
406
        ...(input.query ? { query: input.query } : {}),
407
        limit: input.limit,
408
      });
409
    });
410
    router.get('/v0.1/account', async (request) => {
411
      const owner = operatorId(request);
412
      return {
413
        operatorId: owner,
414
        email: decodeURIComponent(String(request.headers['x-openclasp-email'] ?? '')),
415
        name: decodeURIComponent(String(request.headers['x-openclasp-name'] ?? '')),
416
      };
417
    });
418
    router.get('/v0.1/settings', async (request) => {
419
      const owner = operatorId(request);
420
      if (!repository || !owner)
421
        return {
422
          displayName: '',
423
          contributionEnabled: false,
424
          retentionDays: 30,
425
          evidenceSharing: 'ask',
426
          rawConversationsStored: false,
427
        };
428
      return repository.getSettings(owner);
429
    });
430
    router.get('/v0.1/onboarding', async (request) => {
431
      const owner = operatorId(request);
432
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
433
      return getOnboardingState(repository, owner);
434
    });
435
    router.get('/v0.1/runtime/bootstrap', async (request) => {
436
      const owner = operatorId(request);
437
      const agentId = boundAgentId(request);
438
      const rows = owner && repository ? await repository.list(owner) : [];
439
      const profile = rows.find((row) => row.kind === 'agent_profile' && row.recordId === agentId)
440
        ?.payload as AgentProfile | undefined;
441
      return {
442
        agentId,
443
        agentVersion: profile?.agentVersion ?? '1.0.0',
444
        capabilities: profile?.capabilities ?? [],
445
        limitations: profile?.limitations ?? [],
446
        openClaspUrl: publicBaseUrl(request),
447
        runtimeRegistrationEndpoint: `${publicBaseUrl(request)}/v0.1/runtime`,
448
        protocol: 'A2A/1.0',
449
        controlProtocol: 'OpenClasp/0.1',
450
      };
451
    });
452
    router.put('/v0.1/runtime', async (request) => {
453
      const owner = operatorId(request);
454
      if (!repository?.registerAgentRuntime || !owner)
455
        throw new Error('Hosted runtime delivery is not configured');
456
      const endpoint = z
457
        .object({ endpoint: z.string().url().max(2048) })
458
        .parse(request.body).endpoint;
459
      return repository.registerAgentRuntime(owner, boundAgentId(request), endpoint);
460
    });
461
    router.delete('/v0.1/runtime', async (request) => {
462
      const owner = operatorId(request);
463
      if (!repository?.disableAgentRuntime || !owner)
464
        throw new Error('Hosted runtime delivery is not configured');
465
      return repository.disableAgentRuntime(owner, boundAgentId(request));
466
    });
467
    router.post('/v0.1/runtime/heartbeat', async (request) => {
468
      const owner = operatorId(request);
469
      if (!repository?.touchAgentPresence || !owner)
470
        throw new Error('Agent presence is not configured');
471
      return repository.touchAgentPresence(owner, boundAgentId(request));
472
    });
473
    router.put('/v0.1/runtime/profile', async (request) => {
474
      const owner = operatorId(request);
475
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
476
      const agentId = boundAgentId(request);
477
      const value = z
478
        .object({
479
          description: z.string().trim().max(500).optional(),
480
          capabilities: z.array(z.string().trim().min(1).max(100)).min(1).max(100),
481
          limitations: z.array(z.string().trim().min(1).max(300)).max(100).default([]),
482
        })
483
        .strict()
484
        .parse(request.body);
485
      const rows = await repository.list(owner);
486
      const current = rows.find((row) => row.kind === 'agent_profile' && row.recordId === agentId)
487
        ?.payload as AgentProfile | undefined;
488
      if (!current || current.status !== 'active') throw new Error('Active owned agent not found');
489
      const profile: AgentProfile = {
490
        ...current,
491
        ...(value.description !== undefined ? { description: value.description } : {}),
492
        capabilities: [...new Set(value.capabilities)],
493
        limitations: [...new Set(value.limitations)],
494
        updatedAt: new Date().toISOString(),
495
      };
496
      await repository.upsert(owner, 'agent_profile', agentId, profile);
497
      const publication = rows.find((row) => row.kind === 'publication' && row.recordId === agentId)
498
        ?.payload as { published?: boolean } | undefined;
499
      if (profile.autoPublish || publication?.published) {
500
        const previous = await repository.getPublishedAgent(agentId);
501
        const card = await repository.publishAgent(
502
          owner,
503
          buildPublicAgentCard(profile, publicBaseUrl(request), previous),
504
        );
505
        await repository.upsert(owner, 'publication', agentId, {
506
          agentId,
507
          published: true,
508
          updatedAt: card.updatedAt,
509
        });
510
        return { profile, card };
511
      }
512
      return { profile };
513
    });
514
    router.post('/v0.1/onboarding/:id/approve', async (request) => {
515
      const owner = operatorId(request);
516
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
517
      const requestId = (request.params as { id: string }).id;
518
      const state = await getOnboardingState(repository, owner);
519
      const setup = state.setupRequests.find((item) => item.requestId === requestId);
520
      const result = await approveAgentSetup(repository, owner, requestId);
521
      if (result.status === 'connected' && setup?.autoPublish) {
522
        const previous = await repository.getPublishedAgent(result.agent.agentId);
523
        const card = await repository.publishAgent(
524
          owner,
525
          buildPublicAgentCard(result.agent, publicBaseUrl(request), previous),
526
        );
527
        await repository.upsert(owner, 'publication', result.agent.agentId, {
528
          agentId: result.agent.agentId,
529
          published: true,
530
          updatedAt: card.updatedAt,
531
        });
532
      }
533
      return result;
534
    });
535
    router.post('/v0.1/onboarding/:id/reject', async (request) => {
536
      const owner = operatorId(request);
537
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
538
      return rejectAgentSetup(repository, owner, (request.params as { id: string }).id);
539
    });
540
    router.put('/v0.1/settings', async (request) => {
541
      const owner = operatorId(request);
542
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
543
      const value = z
544
        .object({
545
          displayName: z.string().trim().max(100),
546
          contributionEnabled: z.boolean(),
547
          retentionDays: z.number().int().min(0).max(3650),
548
          evidenceSharing: z.enum(['never', 'ask', 'contract_only']),
549
        })
550
        .parse(request.body);
551
      return repository.saveSettings(owner, value);
552
    });
553
    router.post('/v0.1/provider-connections', async (request) => {
554
      const owner = operatorId(request);
555
      if (!repository?.issueAgentAccessToken || !owner)
556
        throw new Error('Hosted provider connections are not configured');
557
      const value = z
558
        .object({
559
          provider: z.enum(['botpress', 'custom']),
560
          agentName: z.string().trim().min(1).max(100),
561
          projectName: z.string().trim().min(1).max(100),
562
          description: z.string().trim().min(1).max(500),
563
          capabilities: z.array(z.string().trim().min(1).max(100)).min(1).max(100),
564
          limitations: z.array(z.string().trim().min(1).max(300)).max(100).default([]),
565
          expiresInDays: z.number().int().min(1).max(365).default(365),
566
        })
567
        .parse(request.body);
568
      const created = await createHostedProviderAgent(repository, owner, value);
569
      try {
570
        const accessToken = await repository.issueAgentAccessToken(owner, created.agent.agentId, {
571
          name: 'Botpress',
572
          expiresInDays: value.expiresInDays,
573
        });
574
        return { ...created, provider: value.provider, accessToken };
575
      } catch (error) {
576
        if (repository.deleteAgent)
577
          await repository.deleteAgent(owner, created.agent.agentId).catch(() => undefined);
578
        throw error;
579
      }
580
    });
581
    router.post('/v0.1/agents', async (request) => {
582
      const owner = operatorId(request);
583
      const current = await scopedEngine(request);
584
      const identity = AgentIdentitySchema.parse(request.body);
585
      if (owner && identity.operatorRef !== `auth0:${owner}`)
586
        throw new Error('Agent identity is not owned by the authenticated operator');
587
      const registered = current.registerAgent(identity);
588
      await persist(request, 'agent', identity.agentId, registered);
589
      return registered;
590
    });
591
    router.get('/v0.1/agents/:id', async (request) => {
592
      const { id } = request.params as { id: string };
593
      const value = (await scopedEngine(request)).agents.get(id);
594
      if (!value) throw new Error('Agent not found');
595
      return value;
596
    });
597
    router.post('/v0.1/agents/:id/publication', async (request) => {
598
      const owner = operatorId(request);
599
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
600
      const { id } = request.params as { id: string };
601
      const { published } = z.object({ published: z.boolean() }).parse(request.body);
602
      const rows = await repository.list(owner);
603
      const agent = rows.find((row) => row.kind === 'agent_profile' && row.recordId === id)
604
        ?.payload as AgentProfile | undefined;
605
      if (!agent) throw new Error('Owned agent not found');
606
      if (agent.status !== 'active') throw new Error('Revoked agents cannot be published');
607
      if (!published) {
608
        await repository.unpublishAgent(owner, id);
609
        const publication = { agentId: id, published: false, updatedAt: new Date().toISOString() };
610
        await repository.upsert(owner, 'publication', id, publication);
611
        return publication;
612
      }
613
      const previous = await repository.getPublishedAgent(id);
614
      const card = await repository.publishAgent(
615
        owner,
616
        buildPublicAgentCard(agent, publicBaseUrl(request), previous),
617
      );
618
      const publication = { agentId: id, published: true, updatedAt: card.updatedAt };
619
      await repository.upsert(owner, 'publication', id, publication);
620
      return { ...publication, card };
621
    });
622
    router.put('/v0.1/agents/:id/automation', async (request) => {
623
      const owner = operatorId(request);
624
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
625
      const { id } = request.params as { id: string };
626
      const value = z
627
        .object({
628
          autoPublish: z.boolean(),
629
          autoAcceptPolicy: z.enum(['off', 'safe_matching']),
630
          autoAcceptTaskCategories: z.array(z.string().trim().min(1).max(100)).max(100),
631
        })
632
        .parse(request.body);
633
      const rows = await repository.list(owner);
634
      const current = rows.find((row) => row.kind === 'agent_profile' && row.recordId === id)
635
        ?.payload as AgentProfile | undefined;
636
      if (!current) throw new Error('Owned agent not found');
637
      const agent: AgentProfile = {
638
        ...current,
639
        transport: 'direct_a2a',
640
        description: current.description ?? '',
641
        agentVersion: current.agentVersion ?? '1.0.0',
642
        autoPublish: value.autoPublish,
643
        autoAcceptPolicy: value.autoAcceptPolicy,
644
        autoAcceptTaskCategories: [...new Set(value.autoAcceptTaskCategories)],
645
        updatedAt: new Date().toISOString(),
646
      };
647
      await repository.upsert(owner, 'agent_profile', id, agent);
648
      if (value.autoPublish) {
649
        const previous = await repository.getPublishedAgent(id);
650
        const card = await repository.publishAgent(
651
          owner,
652
          buildPublicAgentCard(agent, publicBaseUrl(request), previous),
653
        );
654
        await repository.upsert(owner, 'publication', id, {
655
          agentId: id,
656
          published: true,
657
          updatedAt: card.updatedAt,
658
        });
659
      } else {
660
        await repository.unpublishAgent(owner, id);
661
        await repository.upsert(owner, 'publication', id, {
662
          agentId: id,
663
          published: false,
664
          updatedAt: new Date().toISOString(),
665
        });
666
      }
667
      return agent;
668
    });
669
    router.put('/v0.1/agents/:id/runtime', async (request) => {
670
      const owner = operatorId(request);
671
      if (!repository?.registerAgentRuntime || !owner)
672
        throw new Error('Hosted runtime delivery is not configured');
673
      const endpoint = z
674
        .object({ endpoint: z.string().url().max(2048) })
675
        .parse(request.body).endpoint;
676
      return repository.registerAgentRuntime(
677
        owner,
678
        (request.params as { id: string }).id,
679
        endpoint,
680
      );
681
    });
682
    router.delete('/v0.1/agents/:id/runtime', async (request) => {
683
      const owner = operatorId(request);
684
      if (!repository?.disableAgentRuntime || !owner)
685
        throw new Error('Hosted runtime delivery is not configured');
686
      return repository.disableAgentRuntime(owner, (request.params as { id: string }).id);
687
    });
688
    router.get('/v0.1/agents/:id/access-tokens', async (request) => {
689
      const owner = operatorId(request);
690
      if (!repository?.listAgentAccessTokens || !owner)
691
        throw new Error('Agent access tokens are not configured');
692
      return repository.listAgentAccessTokens(owner, (request.params as { id: string }).id);
693
    });
694
    router.post('/v0.1/agents/:id/access-tokens', async (request) => {
695
      const owner = operatorId(request);
696
      if (!repository?.issueAgentAccessToken || !owner)
697
        throw new Error('Agent access tokens are not configured');
698
      const value = z
699
        .object({
700
          name: z.string().trim().min(1).max(100),
701
          expiresInDays: z.number().int().min(1).max(365).default(365),
702
        })
703
        .parse(request.body);
704
      return repository.issueAgentAccessToken(owner, (request.params as { id: string }).id, value);
705
    });
706
    router.delete('/v0.1/agents/:id/access-tokens/:tokenId', async (request) => {
707
      const owner = operatorId(request);
708
      if (!repository?.revokeAgentAccessToken || !owner)
709
        throw new Error('Agent access tokens are not configured');
710
      const params = request.params as { id: string; tokenId: string };
711
      return repository.revokeAgentAccessToken(owner, params.id, params.tokenId);
712
    });
713
    router.delete('/v0.1/agents/:id', async (request) => {
714
      const owner = operatorId(request);
715
      if (!repository?.deleteAgent || !owner)
716
        throw new Error('Hosted agent deletion is not configured');
717
      const result = await repository.deleteAgent(owner, (request.params as { id: string }).id);
718
      engines.delete(owner);
719
      return result;
720
    });
721
    router.get('/v0.1/agents/:id/threads', async (request) => {
722
      const owner = operatorId(request);
723
      if (!repository?.listHostedThreads || !owner)
724
        throw new Error('Temporary chat history is not configured');
725
      return repository.listHostedThreads(owner, (request.params as { id: string }).id);
726
    });
727
    router.get('/v0.1/agents/:id/threads/:threadId', async (request) => {
728
      const owner = operatorId(request);
729
      if (!repository?.getHostedThread || !owner)
730
        throw new Error('Temporary chat history is not configured');
731
      const params = request.params as { id: string; threadId: string };
732
      return repository.getHostedThread(owner, params.id, params.threadId);
733
    });
734
    router.post('/v0.1/agents/:id/messages', async (request) => {
735
      const owner = operatorId(request);
736
      if (!repository?.sendTemporaryMessage || !owner)
737
        throw new Error('Temporary chat delivery is not configured');
738
      const value = z
739
        .object({ interactionId: z.string().uuid(), content: z.string().trim().min(1).max(20_000) })
740
        .parse(request.body);
741
      return repository.sendTemporaryMessage(
742
        owner,
743
        (request.params as { id: string }).id,
744
        value.interactionId,
745
        value.content,
746
      );
747
    });
748
    router.post('/v0.1/agents/:id/threads/:threadId/read', async (request) => {
749
      const owner = operatorId(request);
750
      if (!repository?.markHostedThreadRead || !owner)
751
        throw new Error('Temporary chat history is not configured');
752
      const params = request.params as { id: string; threadId: string };
753
      return repository.markHostedThreadRead(owner, params.id, params.threadId);
754
    });
755
    router.post('/v0.1/agents/:id/threads/:threadId/close', async (request) => {
756
      const owner = operatorId(request);
757
      if (!repository?.closeHostedThread || !owner)
758
        throw new Error('Temporary chat history is not configured');
759
      const params = request.params as { id: string; threadId: string };
760
      return repository.closeHostedThread(owner, params.id, params.threadId);
761
    });
762
    router.get('/v0.1/directory', async (request) => {
763
      operatorId(request);
764
      if (!repository) throw new Error('Hosted persistence is not configured');
765
      const query = z
766
        .object({
767
          query: z.string().trim().max(100).optional(),
768
          capability: z.string().trim().max(100).optional(),
769
          limit: z.coerce.number().int().min(1).max(50).optional(),
770
        })
771
        .parse(request.query);
772
      return repository.searchPublishedAgents(query);
773
    });
774
    router.get('/v0.1/directory/:id', async (request) => {
775
      operatorId(request);
776
      if (!repository) throw new Error('Hosted persistence is not configured');
777
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
778
      if (!card) throw new Error('Published agent not found');
779
      return card;
780
    });
781
    router.get('/v0.1/federated-interactions', async (request) => {
782
      const owner = operatorId(request);
783
      if (!repository?.listFederatedInteractions || !owner)
784
        throw new Error('Federated interactions are not configured');
785
      return repository.listFederatedInteractions(owner);
786
    });
787
    router.get('/v0.1/federated-interactions/:id', async (request) => {
788
      const owner = operatorId(request);
789
      if (!repository?.getFederatedInteraction || !owner)
790
        throw new Error('Federated interactions are not configured');
791
      const interaction = await repository.getFederatedInteraction(
792
        owner,
793
        (request.params as { id: string }).id,
794
      );
795
      if (!interaction) throw new Error('Interaction not found');
796
      return interaction;
797
    });
798
    router.get('/v0.1/federated-interactions/:id/session', async (request) => {
799
      const owner = operatorId(request);
800
      if (!repository?.getLiveSession || !owner)
801
        throw new Error('Live sessions are not configured');
802
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
803
      enforceBoundAgent(request, value.agentId);
804
      return repository.getLiveSession(owner, (request.params as { id: string }).id, value.agentId);
805
    });
806
    router.get('/v0.1/federated-interactions/:id/brief', async (request) => {
807
      const owner = operatorId(request);
808
      if (!repository?.getCounterpartyBrief || !owner)
809
        throw new Error('Counterparty briefs are not configured');
810
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
811
      enforceBoundAgent(request, value.agentId);
812
      return repository.getCounterpartyBrief(
813
        owner,
814
        (request.params as { id: string }).id,
815
        value.agentId,
816
      );
817
    });
818
    router.post('/v0.1/federated-interactions/:id/completion-reports', async (request) => {
819
      const owner = operatorId(request);
820
      if (!repository?.submitCompletionReport || !owner)
821
        throw new Error('Completion reports are not configured');
822
      const report = InteractionCompletionReportSchema.parse(request.body);
823
      if (report.interactionId !== (request.params as { id: string }).id)
824
        throw new Error('Interaction path does not match the completion report');
825
      return repository.submitCompletionReport(
826
        owner,
827
        boundAgentId(request),
828
        report,
829
        request.headers['x-openclasp-credential-type'] === 'agent_access_token'
830
          ? 'agent_access_token'
831
          : 'oauth_installation',
832
      );
833
    });
834
    router.post('/v0.1/federated-interactions/:id/feedback', async (request) => {
835
      const owner = operatorId(request);
836
      if (!repository?.submitInteractionFeedback || !owner)
837
        throw new Error('Interaction feedback is not configured');
838
      const feedback = InteractionFeedbackSchema.parse(request.body);
839
      if (feedback.interactionId !== (request.params as { id: string }).id)
840
        throw new Error('Interaction path does not match the feedback');
841
      return repository.submitInteractionFeedback(
842
        owner,
843
        boundAgentId(request),
844
        feedback,
845
        request.headers['x-openclasp-credential-type'] === 'agent_access_token'
846
          ? 'agent_access_token'
847
          : 'oauth_installation',
848
      );
849
    });
850
    router.get('/v0.1/feedback-requests', async (request) => {
851
      const owner = operatorId(request);
852
      if (!repository?.listFeedbackRequests || !owner)
853
        throw new Error('Interaction feedback is not configured');
854
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
855
      enforceBoundAgent(request, value.agentId);
856
      return repository.listFeedbackRequests(owner, value.agentId);
857
    });
858
    router.post('/v0.1/federated-interactions', async (request) => {
859
      const owner = operatorId(request);
860
      if (!repository?.createFederatedInteraction || !owner)
861
        throw new Error('Federated interactions are not configured');
862
      const interaction = FederatedInteractionSchema.parse(request.body);
863
      const acceptance = interaction.acceptances[interaction.initiatorAgentId];
864
      if (!acceptance) throw new Error('Initiator acceptance is required');
865
      return repository.createFederatedInteraction(owner, {
866
        ...interaction,
867
        acceptances: {
868
          [interaction.initiatorAgentId]: { ...acceptance, method: 'oauth_account' },
869
        },
870
      });
871
    });
872
    router.post('/v0.1/federated-interactions/:id/respond', async (request) => {
873
      const owner = operatorId(request);
874
      if (!repository?.respondToFederatedInteraction || !owner)
875
        throw new Error('Federated interactions are not configured');
876
      const value = z
877
        .object({ agentId: z.string().min(1), decision: z.enum(['accept', 'reject']) })
878
        .parse(request.body);
879
      return repository.respondToFederatedInteraction(
880
        owner,
881
        (request.params as { id: string }).id,
882
        value.agentId,
883
        value.decision,
884
        'oauth_account',
885
      );
886
    });
887
    router.post('/v0.1/federated-interactions/:id/contract-proposals', async (request) => {
888
      const owner = operatorId(request);
889
      if (!repository?.proposeContractRevision || !owner)
890
        throw new Error('Contract negotiation is not configured');
891
      const value = z
892
        .object({
893
          agentId: z.string().min(1),
894
          expectedTermsHash: z.string().min(1).optional(),
895
          contract: InteractionContractSchema,
896
        })
897
        .parse(request.body);
898
      enforceBoundAgent(request, value.agentId);
899
      return repository.proposeContractRevision(
900
        owner,
901
        (request.params as { id: string }).id,
902
        value.agentId,
903
        value.contract,
904
        value.expectedTermsHash,
905
        request.headers['x-openclasp-credential-type'] === 'agent_access_token'
906
          ? 'oauth_installation'
907
          : 'oauth_account',
908
      );
909
    });
910
    router.post(
911
      '/v0.1/federated-interactions/:id/contract-proposals/:revisionId/respond',
912
      async (request) => {
913
        const owner = operatorId(request);
914
        if (!repository?.respondToContractRevision || !owner)
915
          throw new Error('Contract negotiation is not configured');
916
        const value = z
917
          .object({ agentId: z.string().min(1), decision: z.enum(['accept', 'reject']) })
918
          .parse(request.body);
919
        enforceBoundAgent(request, value.agentId);
920
        const params = request.params as { id: string; revisionId: string };
921
        return repository.respondToContractRevision(
922
          owner,
923
          params.id,
924
          value.agentId,
925
          params.revisionId,
926
          value.decision,
927
          request.headers['x-openclasp-credential-type'] === 'agent_access_token'
928
            ? 'oauth_installation'
929
            : 'oauth_account',
930
        );
931
      },
932
    );
933
    router.post('/v0.1/delegations', async (request) => {
934
      const value = DelegationCredentialSchema.parse(request.body);
935
      const current = await scopedEngine(request);
936
      current.delegations.set(value.delegationId, value);
937
      await persist(request, 'delegation', value.delegationId, value);
938
      return { valid: current.verifyDelegation(value.delegationId) };
939
    });
940
    router.post('/v0.1/delegations/:id/verify', async (request) => ({
941
      valid: (await scopedEngine(request)).verifyDelegation((request.params as { id: string }).id),
942
    }));
943
    router.post('/v0.1/interactions/contracts', async (request) => {
944
      const contract = (await scopedEngine(request)).saveContract(
945
        InteractionContractSchema.parse(request.body),
946
      );
947
      await persist(request, 'contract', contract.interactionId, contract);
948
      return contract;
949
    });
950
    router.post('/v0.1/events', async (request) => {
951
      const event = (await scopedEngine(request)).recordEvent(
952
        InteractionEventSchema.parse(request.body),
953
      );
954
      await persist(request, 'event', event.eventId, event);
955
      return event;
956
    });
957
    router.post('/v0.1/risk/assess', async (request) =>
958
      (await scopedEngine(request)).assess(request.body as any),
959
    );
960
    router.get('/v0.1/profiles/:id', async (request) => {
961
      const { id } = request.params as { id: string };
962
      const query = request.query as { version?: string; taskCategory?: string };
963
      return (await scopedEngine(request)).getRisk(
964
        id,
965
        query.version ?? '1.0.0',
966
        query.taskCategory ?? 'general',
967
      );
968
    });
969
    router.post('/v0.1/claims/check', async (request) =>
970
      ((value) => factChecker.check(value.claim, value.permission))(
971
        z.object({ claim: z.string(), permission: z.boolean().optional() }).parse(request.body),
972
      ),
973
    );
974
    router.post('/v0.1/receipts', async (request) => {
975
      const receipt = (await scopedEngine(request)).submitReceipt(
976
        ReceiptSchema.parse(request.body),
977
      );
978
      await persist(request, 'receipt', receipt.receiptId, receipt);
979
      return receipt;
980
    });
981
    router.post('/v0.1/receipts/verify', async (request) => {
982
      try {
983
        (await scopedEngine(request)).verifyReceipt(ReceiptSchema.parse(request.body));
984
        return { valid: true };
985
      } catch {
986
        return { valid: false };
987
      }
988
    });
989
    router.post('/v0.1/feedback', async (request) => {
990
      const feedback = FeedbackSchema.parse(request.body);
991
      const current = await scopedEngine(request);
992
      const result = current.submitFeedback(feedback);
993
      await persist(request, 'feedback', feedback.feedbackId, feedback);
994
      for (const profile of current.profiles.values())
995
        await persist(
996
          request,
997
          'profile',
998
          `${profile.agentId}|${profile.agentVersion}|${profile.taskCategory}`,
999
          profile,
1000
        );
1001
      return result;
1002
    });
1003
    router.post('/v0.1/conflicts', async (request) => {
1004
      const conflict = (await scopedEngine(request)).createConflict(request.body as any);
1005
      await persist(request, 'conflict', conflict.conflictId, conflict);
1006
      return conflict;
1007
    });
1008
    router.post('/v0.1/conflicts/:id/permit', async (request) => {
1009
      const conflict = (await scopedEngine(request)).permitMediation(
1010
        (request.params as { id: string }).id,
1011
        (request.body as { agentId: string }).agentId,
1012
      );
1013
      await persist(request, 'conflict', conflict.conflictId, conflict);
1014
      return conflict;
1015
    });
1016
    router.post('/v0.1/conflicts/:id/resolve', async (request) => {
1017
      const conflict = (await scopedEngine(request)).resolveConflict(
1018
        (request.params as { id: string }).id,
1019
        (request.body as { resolution: string }).resolution,
1020
      );
1021
      await persist(request, 'conflict', conflict.conflictId, conflict);
1022
      return conflict;
1023
    });
1024
    router.post('/v0.1/revocations/agents/:id', async (request) => {
1025
      const id = (request.params as { id: string }).id;
1026
      const current = await scopedEngine(request);
1027
      current.revokeAgent(id);
1028
      await persist(request, 'agent', id, current.agents.get(id));
1029
      return { revoked: true };
1030
    });
1031
    router.post('/v0.1/revocations/delegations/:id', async (request) => {
1032
      const id = (request.params as { id: string }).id;
1033
      const current = await scopedEngine(request);
1034
      current.revokeDelegation(id);
1035
      await persist(request, 'delegation', id, current.delegations.get(id));
1036
      return { revoked: true };
1037
    });
1038
    router.post('/v0.1/contributions/consent', async (request) => {
1039
      const value = z.object({ agentId: z.string(), enabled: z.boolean() }).parse(request.body);
1040
      const current = await scopedEngine(request);
1041
      current.setContributionConsent(value.agentId, value.enabled);
1042
      await persist(request, 'consent', value.agentId, {
1043
        agentId: value.agentId,
1044
        ...current.contributionConsent.get(value.agentId),
1045
      });
1046
      return value;
1047
    });
1048
  });
1049
  return app;
1050
}