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

Viewing files at commit 89b58109a0e6Commit detailsView latest

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