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

Viewing files at commit 578449aaa53eCommit detailsView latest

apps/api/src/app.ts 1181 lines · 60.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
  AssuranceProbeResponseSchema,
8
  DelegationCredentialSchema,
9
  FeedbackSchema,
10
  InteractionContractSchema,
11
  InteractionEventSchema,
12
  ReceiptSchema,
13
  FederatedInteractionSchema,
14
  LiveSessionEventSchema,
15
  InteractionCompletionReportSchema,
16
  InteractionFeedbackSchema,
17
  ConnectorAgentProfileSchema,
18
  type PublicAgentCard,
19
} from '../../../packages/protocol/src/index.js';
20
import {
21
  MemoryAuditStore,
22
  TrustEngine,
23
  UnavailableFactCheckProvider,
24
} from '../../../packages/core/src/index.js';
25
import { buildPublicAgentCard } from '../../../packages/persistence/src/index.js';
26
import type { AgentProfile, HostedRepository } from '../../../packages/persistence/src/index.js';
27
import { toA2AAgentCard } from '../../../packages/sidecar/src/index.js';
28
import {
29
  approveAgentSetup,
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
      | 'recordSessionAssuranceResponse'
65
      | 'listAssuranceProbePlans'
66
      | 'submitAssuranceProbeResponse'
67
      | 'listAssuranceComparisons'
68
      | 'getAssuranceBrief'
69
      | 'decideAssuranceSafeguard'
70
      | 'listFeedbackRequests'
71
      | 'recordLiveSessionEvent'
72
      | 'touchAgentPresence'
73
      | 'getRuntimeVerificationKey'
74
      | 'registerAgentRuntime'
75
      | 'listAgentRuntimes'
76
      | 'disableAgentRuntime'
77
      | 'deleteAgent'
78
      | 'issueAgentAccessToken'
79
      | 'listAgentAccessTokens'
80
      | 'revokeAgentAccessToken'
81
      | 'createConnectorClaim'
82
      | 'getConnectorClaim'
83
      | 'pollConnectorClaim'
84
      | 'approveConnectorClaim'
85
      | 'rejectConnectorClaim'
86
      | 'createProviderConnection'
87
      | 'getProviderConnection'
88
      | 'completeBotpressConnection'
89
    >
90
  > & {
91
    listContextualIntelligence?: (
92
      operatorId: string,
93
      input?: { agentId?: string; taskCategory?: string },
94
    ) => Promise<any[]>;
95
    searchPersonalizedMarketplace?: (
96
      operatorId: string,
97
      input?: { agentId?: string; taskCategory?: string; query?: string; limit?: number },
98
    ) => Promise<any[]>;
99
  };
100
101
export function buildApi(
102
  engine = new TrustEngine(),
103
  factChecker = new UnavailableFactCheckProvider(),
104
  repository?: DashboardRepository,
105
  security: { internalAuthSecret?: string } = {},
106
) {
107
  const app = Fastify({
108
    bodyLimit: 256 * 1024,
109
    requestTimeout: 30_000,
110
    logger: {
111
      redact: [
112
        'req.headers.authorization',
113
        'req.headers.cookie',
114
        'req.headers.x-openclasp-internal-auth',
115
        'req.headers.x-openclasp-pairing-code',
116
        'req.body.rawMessage',
117
        'req.body.privateKey',
118
      ],
119
    },
120
  });
121
  const engines = new Map<string, Promise<TrustEngine>>();
122
  const limiter = new FixedWindowRateLimiter();
123
  const allowedOrigin = process.env.OPENCLASP_PUBLIC_URL
124
    ? new URL(process.env.OPENCLASP_PUBLIC_URL).origin
125
    : undefined;
126
  void app.register(cors, {
127
    credentials: Boolean(repository),
128
    origin(origin, callback) {
129
      callback(null, !origin || !allowedOrigin || origin === allowedOrigin);
130
    },
131
  });
132
  void app.register(swagger, { openapi: { info: { title: 'OpenClasp API', version: '0.1.0' } } });
133
134
  app.addHook('onRequest', async (request, reply) => {
135
    const method = request.method.toUpperCase();
136
    if (['GET', 'HEAD', 'OPTIONS'].includes(method)) return;
137
    const operator = request.headers['x-openclasp-operator'];
138
    const bucket = typeof operator === 'string' ? `operator:${operator}` : `ip:${request.ip}`;
139
    const externalSession = request.url.startsWith('/sessions/') || request.url.startsWith('/a2a/');
140
    const result = limiter.consume(bucket, externalSession ? 300 : 120, 60_000);
141
    reply.header('x-ratelimit-remaining', result.remaining);
142
    if (!result.allowed)
143
      return reply
144
        .status(429)
145
        .header('retry-after', result.retryAfterSeconds)
146
        .send({ error: 'rate_limit_exceeded' });
147
  });
148
149
  app.addHook('onSend', async (_request, reply, payload) => {
150
    reply.header('x-content-type-options', 'nosniff');
151
    reply.header('referrer-policy', 'no-referrer');
152
    reply.header('permissions-policy', 'camera=(), microphone=(), geolocation=()');
153
    return payload;
154
  });
155
156
  app.setErrorHandler((error, _request, reply) =>
157
    reply
158
      .status(
159
        error instanceof Error && 'statusCode' in error && typeof error.statusCode === 'number'
160
          ? error.statusCode
161
          : 400,
162
      )
163
      .send({ error: error instanceof Error ? error.message : 'Unknown error' }),
164
  );
165
  void app.register(async (router) => {
166
    const operatorId = (request: { headers: Record<string, unknown> }) => {
167
      const value = request.headers['x-openclasp-operator'];
168
      if (
169
        repository &&
170
        security.internalAuthSecret &&
171
        request.headers['x-openclasp-internal-auth'] !== security.internalAuthSecret
172
      ) {
173
        const error = new Error('Trusted authentication boundary required');
174
        Object.assign(error, { statusCode: 401 });
175
        throw error;
176
      }
177
      if (repository && typeof value !== 'string') {
178
        const error = new Error('Authentication required');
179
        Object.assign(error, { statusCode: 401 });
180
        throw error;
181
      }
182
      return typeof value === 'string' ? value : undefined;
183
    };
184
    const boundAgentId = (request: { headers: Record<string, unknown> }) => {
185
      const value = request.headers['x-openclasp-bound-agent'];
186
      if (typeof value !== 'string' || !value) {
187
        const error = new Error('Agent-bound authentication required');
188
        Object.assign(error, { statusCode: 401 });
189
        throw error;
190
      }
191
      return value;
192
    };
193
    const enforceBoundAgent = (
194
      request: { headers: Record<string, unknown> },
195
      requestedAgentId: string,
196
    ) => {
197
      const value = request.headers['x-openclasp-bound-agent'];
198
      if (typeof value === 'string' && value !== requestedAgentId) {
199
        const error = new Error('Agent credential cannot access another agent');
200
        Object.assign(error, { statusCode: 403 });
201
        throw error;
202
      }
203
    };
204
    const scopedEngine = async (request: { headers: Record<string, unknown> }) => {
205
      const owner = operatorId(request);
206
      if (!repository || !owner) return engine;
207
      let pending = engines.get(owner);
208
      if (!pending) {
209
        pending = repository.list(owner).then((rows) => {
210
          const store = new MemoryAuditStore();
211
          for (const row of rows) {
212
            if (row.kind !== 'interaction') store.append(row.kind, row.recordId, row.payload);
213
          }
214
          return new TrustEngine(store);
215
        });
216
        engines.set(owner, pending);
217
      }
218
      return pending;
219
    };
220
    const persist = async (
221
      request: { headers: Record<string, unknown> },
222
      kind: Parameters<HostedRepository['upsert']>[1],
223
      id: string,
224
      value: unknown,
225
    ) => {
226
      const owner = operatorId(request);
227
      if (repository && owner) await repository.upsert(owner, kind, id, value);
228
    };
229
    const publicBaseUrl = (request: { headers: Record<string, unknown> }) => {
230
      const forwardedHost = request.headers['x-forwarded-host'];
231
      const host = typeof forwardedHost === 'string' ? forwardedHost : request.headers.host;
232
      const forwardedProtocol = request.headers['x-forwarded-proto'];
233
      const protocol = typeof forwardedProtocol === 'string' ? forwardedProtocol : 'https';
234
      return process.env.OPENCLASP_PUBLIC_URL ?? `${protocol}://${String(host ?? 'localhost')}`;
235
    };
236
    const publicPublication = (card: PublicAgentCard) => ({
237
      agentId: card.agentId,
238
      published: true,
239
      profileUrl: card.profileUrl,
240
      cardUrl: card.cardUrl,
241
      a2aAgentCardUrl: card.a2aAgentCardUrl,
242
      verification: card.verification,
243
      updatedAt: card.updatedAt,
244
    });
245
    const escapeHtml = (value: string) =>
246
      value.replace(/[&<>"']/g, (character) => {
247
        const entities: Record<string, string> = {
248
          '&': '&amp;',
249
          '<': '&lt;',
250
          '>': '&gt;',
251
          '"': '&quot;',
252
          "'": '&#39;',
253
        };
254
        return entities[character]!;
255
      });
256
    router.get('/health', async () => ({ status: 'ok' }));
257
    router.get('/ready', async () => ({ status: 'ready' }));
258
    router.get('/openapi.json', async () => app.swagger());
259
    router.get('/.well-known/openclasp-session-key', async () => {
260
      if (!repository?.getRuntimeVerificationKey)
261
        throw new Error('Runtime verification is not configured');
262
      return repository.getRuntimeVerificationKey();
263
    });
264
    router.get('/extensions/trust/v0.1', async () => ({
265
      uri: 'https://openclasp.vercel.app/extensions/trust/v0.1',
266
      name: 'OpenClasp A2A assurance extension',
267
      version: '0.1',
268
      required: false,
269
      transportsMessages: false,
270
      documentation: 'https://github.com/aryaamin/OpenClasp/blob/main/docs/A2A_EXTENSION.md',
271
    }));
272
    router.post('/sessions/:id/events', async (request, reply) => {
273
      if (!repository?.recordLiveSessionEvent)
274
        throw new Error('Live-session reporting is not configured');
275
      const authorization = request.headers.authorization;
276
      if (!authorization?.startsWith('Bearer ')) {
277
        reply.status(401);
278
        return { error: 'session_credential_required' };
279
      }
280
      const event = LiveSessionEventSchema.parse(request.body);
281
      if (event.interactionId !== (request.params as { id: string }).id)
282
        throw new Error('Interaction path does not match the event');
283
      return repository.recordLiveSessionEvent(authorization.slice(7), event);
284
    });
285
    router.post('/sessions/:id/completion-reports', async (request, reply) => {
286
      if (!repository?.recordSessionCompletionReport)
287
        throw new Error('Live-session completion reporting is not configured');
288
      const authorization = request.headers.authorization;
289
      if (!authorization?.startsWith('Bearer ')) {
290
        reply.status(401);
291
        return { error: 'session_credential_required' };
292
      }
293
      const report = InteractionCompletionReportSchema.parse(request.body);
294
      if (report.interactionId !== (request.params as { id: string }).id)
295
        throw new Error('Interaction path does not match the completion report');
296
      return repository.recordSessionCompletionReport(authorization.slice(7), report);
297
    });
298
    router.post('/sessions/:id/feedback', async (request, reply) => {
299
      if (!repository?.recordSessionFeedback)
300
        throw new Error('Live-session feedback is not configured');
301
      const authorization = request.headers.authorization;
302
      if (!authorization?.startsWith('Bearer ')) {
303
        reply.status(401);
304
        return { error: 'session_credential_required' };
305
      }
306
      const feedback = InteractionFeedbackSchema.parse(request.body);
307
      if (feedback.interactionId !== (request.params as { id: string }).id)
308
        throw new Error('Interaction path does not match the feedback');
309
      return repository.recordSessionFeedback(authorization.slice(7), feedback);
310
    });
311
    router.post('/sessions/:id/assurance-responses', async (request, reply) => {
312
      if (!repository?.recordSessionAssuranceResponse)
313
        throw new Error('Assurance response reporting is not configured');
314
      const authorization = request.headers.authorization;
315
      if (!authorization?.startsWith('Bearer ')) {
316
        reply.status(401);
317
        return { error: 'session_credential_required' };
318
      }
319
      const response = AssuranceProbeResponseSchema.parse(request.body);
320
      if (response.interactionId !== (request.params as { id: string }).id)
321
        throw new Error('Interaction path does not match the assurance response');
322
      return repository.recordSessionAssuranceResponse(authorization.slice(7), response);
323
    });
324
    router.get('/agents/:id/card.json', async (request) => {
325
      if (!repository) throw new Error('Hosted persistence is not configured');
326
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
327
      if (!card) throw new Error('Published agent not found');
328
      return card;
329
    });
330
    router.get('/agents/:id/.well-known/openclasp-agent.json', async (request) => {
331
      if (!repository) throw new Error('Hosted persistence is not configured');
332
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
333
      if (!card) throw new Error('Published agent not found');
334
      return card;
335
    });
336
    router.get('/agents/:id/a2a-agent-card.json', async (request) => {
337
      if (!repository) throw new Error('Hosted persistence is not configured');
338
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
339
      if (!card) throw new Error('Published agent not found');
340
      if (!card.transports.length) throw new Error('Agent has not published an A2A endpoint');
341
      return toA2AAgentCard(card);
342
    });
343
    router.get('/agents/:id/og.png', async (request, reply) => {
344
      if (!repository) throw new Error('Hosted persistence is not configured');
345
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
346
      if (!card) throw new Error('Published agent not found');
347
      return reply
348
        .type('image/png')
349
        .header('Cache-Control', 'public, max-age=0, s-maxage=86400, stale-while-revalidate=604800')
350
        .send(await renderAgentCardImage(card));
351
    });
352
    router.get('/directory/resolve', async (request) => {
353
      if (!repository) throw new Error('Hosted persistence is not configured');
354
      const { reference } = z
355
        .object({ reference: z.string().min(1).max(2048) })
356
        .parse(request.query);
357
      const result = await repository.resolveAgentReference(reference);
358
      if (!result) throw new Error('Published agent not found');
359
      return result;
360
    });
361
    router.get('/directory/search', async (request) => {
362
      if (!repository) throw new Error('Hosted persistence is not configured');
363
      const input = z
364
        .object({
365
          query: z.string().trim().max(100).optional(),
366
          capability: z.string().trim().max(100).optional(),
367
          limit: z.coerce.number().int().min(1).max(50).optional(),
368
        })
369
        .parse(request.query);
370
      return repository.searchPublishedAgents(input);
371
    });
372
    router.get('/a/:reference', async (request, reply) => {
373
      if (!repository) throw new Error('Hosted persistence is not configured');
374
      const result = await repository.resolveAgentReference(
375
        (request.params as { reference: string }).reference,
376
      );
377
      if (!result) throw new Error('Published agent not found');
378
      const { card } = result;
379
      const socialImageUrl = `${publicBaseUrl(request)}/agents/${encodeURIComponent(card.agentId)}/og.png`;
380
      const capabilities = card.capabilities
381
        .map((capability) => `<li>${escapeHtml(capability)}</li>`)
382
        .join('');
383
      const limitations = card.limitations
384
        .map((limitation) => `<li>${escapeHtml(limitation)}</li>`)
385
        .join('');
386
      const runtimeLabel = 'Agent-owned cloud runtime';
387
      const presence = card.presence?.status ?? 'offline';
388
      const structured = JSON.stringify({
389
        '@context': 'https://schema.org',
390
        '@type': 'SoftwareApplication',
391
        name: card.name,
392
        description: card.description,
393
        url: card.profileUrl,
394
      }).replace(/</g, '\\u003c');
395
      return reply.type('text/html; charset=utf-8').send(`<!doctype html>
396
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
397
<title>${escapeHtml(card.name)} · OpenClasp</title><meta name="description" content="${escapeHtml(card.description)}">
398
<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)}">
399
<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`)}">
400
<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)}">
401
<meta name="theme-color" content="#100b0a"><meta property="og:site_name" content="OpenClasp">
402
<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>
403
<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>
404
<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>
405
<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>
406
<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>
407
<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>`);
408
    });
409
    router.get('/v0.1/dashboard', async (request) => {
410
      const owner = operatorId(request);
411
      if (repository && owner) return repository.dashboard(owner);
412
      return {
413
        agents: [...engine.agents.values()],
414
        projects: [],
415
        installations: [],
416
        setupRequests: [],
417
        publications: [],
418
        interactions: [],
419
        federatedInteractions: [],
420
        liveSessions: [],
421
        events: [...engine.events.values()],
422
        conflicts: [...engine.conflicts.values()],
423
        receipts: [...engine.receipts.values()],
424
        profiles: [...engine.profiles.values()],
425
        counterpartyBriefs: [],
426
        completionReports: [],
427
        feedbackRequests: [],
428
        interactionFeedback: [],
429
        interactionConclusions: [],
430
        learningEligibility: [],
431
        profileDeltas: [],
432
        intelligenceSummaries: [],
433
        runtimes: [],
434
      };
435
    });
436
    router.get('/v0.1/intelligence', async (request) => {
437
      const owner = operatorId(request);
438
      if (!repository?.listContextualIntelligence || !owner)
439
        throw new Error('Contextual intelligence is not configured');
440
      const input = z
441
        .object({
442
          agentId: z.string().min(1).optional(),
443
          taskCategory: z.string().trim().min(1).max(100).optional(),
444
        })
445
        .parse(request.query);
446
      return repository.listContextualIntelligence(owner, {
447
        ...(input.agentId ? { agentId: input.agentId } : {}),
448
        ...(input.taskCategory ? { taskCategory: input.taskCategory } : {}),
449
      });
450
    });
451
    router.get('/v0.1/marketplace', async (request) => {
452
      const owner = operatorId(request);
453
      if (!repository?.searchPersonalizedMarketplace || !owner)
454
        throw new Error('Personalized marketplace is not configured');
455
      const input = z
456
        .object({
457
          agentId: z.string().min(1).optional(),
458
          taskCategory: z.string().trim().min(1).max(100).optional(),
459
          query: z.string().trim().max(100).optional(),
460
          limit: z.coerce.number().int().min(1).max(50).default(30),
461
        })
462
        .parse(request.query);
463
      const results = await repository.searchPersonalizedMarketplace(owner, {
464
        ...(input.agentId ? { agentId: input.agentId } : {}),
465
        ...(input.taskCategory ? { taskCategory: input.taskCategory } : {}),
466
        ...(input.query ? { query: input.query } : {}),
467
        limit: input.limit,
468
      });
469
      return results.filter(
470
        (result) =>
471
          result.card.agentMode === 'persistent_runtime' &&
472
          result.card.transports.some(
473
            (transport: { managedBy?: string }) => transport.managedBy === 'agent',
474
          ),
475
      );
476
    });
477
    router.get('/v0.1/account', async (request) => {
478
      const owner = operatorId(request);
479
      return {
480
        operatorId: owner,
481
        email: decodeURIComponent(String(request.headers['x-openclasp-email'] ?? '')),
482
        name: decodeURIComponent(String(request.headers['x-openclasp-name'] ?? '')),
483
      };
484
    });
485
    router.get('/v0.1/settings', async (request) => {
486
      const owner = operatorId(request);
487
      if (!repository || !owner)
488
        return {
489
          displayName: '',
490
          contributionEnabled: false,
491
          rawConversationsStored: false,
492
        };
493
      return repository.getSettings(owner);
494
    });
495
    router.get('/v0.1/onboarding', async (request) => {
496
      const owner = operatorId(request);
497
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
498
      return getOnboardingState(repository, owner);
499
    });
500
    router.post('/v0.1/connector-claims', async (request) => {
501
      if (!repository?.createConnectorClaim)
502
        throw new Error('Runtime connector claims are not configured');
503
      const value = z
504
        .object({
505
          runtimeEndpoint: z.string().url().max(2048),
506
          credentialPublicKey: z.string().min(1).max(8192),
507
          profile: ConnectorAgentProfileSchema,
508
        })
509
        .strict()
510
        .parse(request.body);
511
      const claim = await repository.createConnectorClaim(value);
512
      return {
513
        ...claim,
514
        confirmationUrl: `${publicBaseUrl(request)}/connect?claim=${encodeURIComponent(claim.claimId)}`,
515
        pollIntervalSeconds: 3,
516
      };
517
    });
518
    router.get('/v0.1/connector-claims/:id', async (request) => {
519
      if (!repository?.getConnectorClaim)
520
        throw new Error('Runtime connector claims are not configured');
521
      return repository.getConnectorClaim((request.params as { id: string }).id);
522
    });
523
    router.post('/v0.1/connector-claims/:id/poll', async (request) => {
524
      if (!repository?.pollConnectorClaim)
525
        throw new Error('Runtime connector claims are not configured');
526
      const claimSecret = request.headers['x-openclasp-claim-secret'];
527
      if (typeof claimSecret !== 'string') {
528
        const error = new Error('Connector claim secret required');
529
        Object.assign(error, { statusCode: 401 });
530
        throw error;
531
      }
532
      return repository.pollConnectorClaim((request.params as { id: string }).id, claimSecret);
533
    });
534
    router.post('/v0.1/connector-claims/:id/approve', async (request) => {
535
      const owner = operatorId(request);
536
      if (!repository?.approveConnectorClaim || !owner)
537
        throw new Error('Runtime connector claims are not configured');
538
      const { name } = z
539
        .object({ name: z.string().trim().min(1).max(100) })
540
        .strict()
541
        .parse(request.body);
542
      return repository.approveConnectorClaim(owner, (request.params as { id: string }).id, name);
543
    });
544
    router.post('/v0.1/connector-claims/:id/reject', async (request) => {
545
      const owner = operatorId(request);
546
      if (!repository?.rejectConnectorClaim || !owner)
547
        throw new Error('Runtime connector claims are not configured');
548
      return repository.rejectConnectorClaim(owner, (request.params as { id: string }).id);
549
    });
550
    router.post('/v0.1/provider-connections/botpress', async (request) => {
551
      const owner = operatorId(request);
552
      if (!repository?.createProviderConnection || !owner)
553
        throw new Error('Botpress connections are not configured');
554
      const { agentName } = z
555
        .object({ agentName: z.string().trim().min(1).max(100) })
556
        .strict()
557
        .parse(request.body);
558
      return repository.createProviderConnection(owner, 'botpress', agentName);
559
    });
560
    router.get('/v0.1/provider-connections/:id', async (request) => {
561
      const owner = operatorId(request);
562
      if (!repository?.getProviderConnection || !owner)
563
        throw new Error('Provider connections are not configured');
564
      return repository.getProviderConnection(owner, (request.params as { id: string }).id);
565
    });
566
    router.post('/v0.1/provider-connections/botpress/complete', async (request) => {
567
      if (!repository?.completeBotpressConnection)
568
        throw new Error('Botpress connections are not configured');
569
      const code = request.headers['x-openclasp-pairing-code'];
570
      if (typeof code !== 'string' || code.length > 100 || !code.startsWith('oc_bp_')) {
571
        const error = new Error('Botpress pairing code required');
572
        Object.assign(error, { statusCode: 401 });
573
        throw error;
574
      }
575
      const value = z
576
        .object({
577
          runtimeEndpoint: z.string().url().max(2048),
578
          credentialPublicKey: z.string().min(1).max(8192),
579
          profile: ConnectorAgentProfileSchema,
580
        })
581
        .strict()
582
        .parse(request.body);
583
      return repository.completeBotpressConnection(code, value);
584
    });
585
    router.get('/v0.1/runtime/bootstrap', async (request) => {
586
      const owner = operatorId(request);
587
      const agentId = boundAgentId(request);
588
      const rows = owner && repository ? await repository.list(owner) : [];
589
      const profile = rows.find((row) => row.kind === 'agent_profile' && row.recordId === agentId)
590
        ?.payload as AgentProfile | undefined;
591
      return {
592
        agentId,
593
        agentVersion: profile?.agentVersion ?? '1.0.0',
594
        capabilities: profile?.capabilities ?? [],
595
        limitations: profile?.limitations ?? [],
596
        openClaspUrl: publicBaseUrl(request),
597
        runtimeRegistrationEndpoint: `${publicBaseUrl(request)}/v0.1/runtime`,
598
        protocol: 'A2A/1.0',
599
        controlProtocol: 'OpenClasp/0.1',
600
      };
601
    });
602
    router.put('/v0.1/runtime', async (request) => {
603
      const owner = operatorId(request);
604
      if (!repository?.registerAgentRuntime || !owner)
605
        throw new Error('Hosted runtime delivery is not configured');
606
      const endpoint = z
607
        .object({ endpoint: z.string().url().max(2048) })
608
        .parse(request.body).endpoint;
609
      return repository.registerAgentRuntime(owner, boundAgentId(request), endpoint);
610
    });
611
    router.delete('/v0.1/runtime', async (request) => {
612
      const owner = operatorId(request);
613
      if (!repository?.disableAgentRuntime || !owner)
614
        throw new Error('Hosted runtime delivery is not configured');
615
      return repository.disableAgentRuntime(owner, boundAgentId(request));
616
    });
617
    router.post('/v0.1/runtime/heartbeat', async (request) => {
618
      const owner = operatorId(request);
619
      if (!repository?.touchAgentPresence || !owner)
620
        throw new Error('Agent presence is not configured');
621
      return repository.touchAgentPresence(owner, boundAgentId(request));
622
    });
623
    router.put('/v0.1/runtime/profile', async (request) => {
624
      const owner = operatorId(request);
625
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
626
      const agentId = boundAgentId(request);
627
      const value = z
628
        .object({
629
          description: z.string().trim().max(500).optional(),
630
          capabilities: z.array(z.string().trim().min(1).max(100)).min(1).max(100),
631
          limitations: z.array(z.string().trim().min(1).max(300)).max(100).default([]),
632
        })
633
        .strict()
634
        .parse(request.body);
635
      const rows = await repository.list(owner);
636
      const current = rows.find((row) => row.kind === 'agent_profile' && row.recordId === agentId)
637
        ?.payload as AgentProfile | undefined;
638
      if (!current || current.status !== 'active') throw new Error('Active owned agent not found');
639
      const profile: AgentProfile = {
640
        ...current,
641
        ...(value.description !== undefined ? { description: value.description } : {}),
642
        capabilities: [...new Set(value.capabilities)],
643
        limitations: [...new Set(value.limitations)],
644
        updatedAt: new Date().toISOString(),
645
      };
646
      await repository.upsert(owner, 'agent_profile', agentId, profile);
647
      const publication = rows.find((row) => row.kind === 'publication' && row.recordId === agentId)
648
        ?.payload as { published?: boolean } | undefined;
649
      if (profile.autoPublish || publication?.published) {
650
        const previous = await repository.getPublishedAgent(agentId);
651
        const card = await repository.publishAgent(
652
          owner,
653
          buildPublicAgentCard(profile, publicBaseUrl(request), previous),
654
        );
655
        await repository.upsert(owner, 'publication', agentId, publicPublication(card));
656
        return { profile, card };
657
      }
658
      return { profile };
659
    });
660
    router.post('/v0.1/onboarding/:id/approve', async (request) => {
661
      const owner = operatorId(request);
662
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
663
      const requestId = (request.params as { id: string }).id;
664
      const state = await getOnboardingState(repository, owner);
665
      const setup = state.setupRequests.find((item) => item.requestId === requestId);
666
      const result = await approveAgentSetup(repository, owner, requestId);
667
      if (result.status === 'connected' && setup?.autoPublish) {
668
        const previous = await repository.getPublishedAgent(result.agent.agentId);
669
        const card = await repository.publishAgent(
670
          owner,
671
          buildPublicAgentCard(result.agent, publicBaseUrl(request), previous),
672
        );
673
        await repository.upsert(
674
          owner,
675
          'publication',
676
          result.agent.agentId,
677
          publicPublication(card),
678
        );
679
      }
680
      return result;
681
    });
682
    router.post('/v0.1/onboarding/:id/reject', async (request) => {
683
      const owner = operatorId(request);
684
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
685
      return rejectAgentSetup(repository, owner, (request.params as { id: string }).id);
686
    });
687
    router.put('/v0.1/settings', async (request) => {
688
      const owner = operatorId(request);
689
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
690
      const value = z
691
        .object({
692
          displayName: z.string().trim().max(100),
693
          contributionEnabled: z.boolean(),
694
        })
695
        .parse(request.body);
696
      return repository.saveSettings(owner, value);
697
    });
698
    router.post('/v0.1/agents', async (request) => {
699
      const owner = operatorId(request);
700
      const current = await scopedEngine(request);
701
      const identity = AgentIdentitySchema.parse(request.body);
702
      if (owner && identity.operatorRef !== `auth0:${owner}`)
703
        throw new Error('Agent identity is not owned by the authenticated operator');
704
      const registered = current.registerAgent(identity);
705
      await persist(request, 'agent', identity.agentId, registered);
706
      return registered;
707
    });
708
    router.get('/v0.1/agents/:id', async (request) => {
709
      const { id } = request.params as { id: string };
710
      const value = (await scopedEngine(request)).agents.get(id);
711
      if (!value) throw new Error('Agent not found');
712
      return value;
713
    });
714
    router.post('/v0.1/agents/:id/publication', async (request) => {
715
      const owner = operatorId(request);
716
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
717
      const { id } = request.params as { id: string };
718
      const { published } = z.object({ published: z.boolean() }).parse(request.body);
719
      const rows = await repository.list(owner);
720
      const agent = rows.find((row) => row.kind === 'agent_profile' && row.recordId === id)
721
        ?.payload as AgentProfile | undefined;
722
      if (!agent) throw new Error('Owned agent not found');
723
      if (agent.status !== 'active') throw new Error('Revoked agents cannot be published');
724
      if (!published) {
725
        await repository.unpublishAgent(owner, id);
726
        const publication = { agentId: id, published: false, updatedAt: new Date().toISOString() };
727
        await repository.upsert(owner, 'publication', id, publication);
728
        return publication;
729
      }
730
      if (repository.listAgentRuntimes) {
731
        const runtime = (await repository.listAgentRuntimes(owner)).find(
732
          (candidate) => candidate.agentId === id && candidate.status === 'verified',
733
        );
734
        if (!runtime) throw new Error('Verify the agent runtime before publishing');
735
      }
736
      const previous = await repository.getPublishedAgent(id);
737
      const card = await repository.publishAgent(
738
        owner,
739
        buildPublicAgentCard(agent, publicBaseUrl(request), previous),
740
      );
741
      const publication = publicPublication(card);
742
      await repository.upsert(owner, 'publication', id, publication);
743
      return { ...publication, card };
744
    });
745
    router.put('/v0.1/agents/:id/automation', async (request) => {
746
      const owner = operatorId(request);
747
      if (!repository || !owner) throw new Error('Hosted persistence is not configured');
748
      const { id } = request.params as { id: string };
749
      const value = z
750
        .object({
751
          autoPublish: z.boolean(),
752
          autoAcceptPolicy: z.enum(['off', 'safe_matching']),
753
          autoAcceptTaskCategories: z.array(z.string().trim().min(1).max(100)).max(100),
754
        })
755
        .parse(request.body);
756
      const rows = await repository.list(owner);
757
      const current = rows.find((row) => row.kind === 'agent_profile' && row.recordId === id)
758
        ?.payload as AgentProfile | undefined;
759
      if (!current) throw new Error('Owned agent not found');
760
      const agent: AgentProfile = {
761
        ...current,
762
        transport: 'direct_a2a',
763
        description: current.description ?? '',
764
        agentVersion: current.agentVersion ?? '1.0.0',
765
        autoPublish: value.autoPublish,
766
        autoAcceptPolicy: value.autoAcceptPolicy,
767
        autoAcceptTaskCategories: [...new Set(value.autoAcceptTaskCategories)],
768
        updatedAt: new Date().toISOString(),
769
      };
770
      await repository.upsert(owner, 'agent_profile', id, agent);
771
      if (value.autoPublish) {
772
        if (repository.listAgentRuntimes) {
773
          const runtime = (await repository.listAgentRuntimes(owner)).find(
774
            (candidate) => candidate.agentId === id && candidate.status === 'verified',
775
          );
776
          if (!runtime) throw new Error('Verify the agent runtime before publishing');
777
        }
778
        const previous = await repository.getPublishedAgent(id);
779
        const card = await repository.publishAgent(
780
          owner,
781
          buildPublicAgentCard(agent, publicBaseUrl(request), previous),
782
        );
783
        await repository.upsert(owner, 'publication', id, publicPublication(card));
784
      } else {
785
        await repository.unpublishAgent(owner, id);
786
        await repository.upsert(owner, 'publication', id, {
787
          agentId: id,
788
          published: false,
789
          updatedAt: new Date().toISOString(),
790
        });
791
      }
792
      return agent;
793
    });
794
    router.delete('/v0.1/agents/:id/runtime', async (request) => {
795
      const owner = operatorId(request);
796
      if (!repository?.disableAgentRuntime || !owner)
797
        throw new Error('Hosted runtime delivery is not configured');
798
      return repository.disableAgentRuntime(owner, (request.params as { id: string }).id);
799
    });
800
    router.get('/v0.1/agents/:id/access-tokens', async (request) => {
801
      const owner = operatorId(request);
802
      if (!repository?.listAgentAccessTokens || !owner)
803
        throw new Error('Agent access tokens are not configured');
804
      return repository.listAgentAccessTokens(owner, (request.params as { id: string }).id);
805
    });
806
    router.delete('/v0.1/agents/:id/access-tokens/:tokenId', async (request) => {
807
      const owner = operatorId(request);
808
      if (!repository?.revokeAgentAccessToken || !owner)
809
        throw new Error('Agent access tokens are not configured');
810
      const params = request.params as { id: string; tokenId: string };
811
      return repository.revokeAgentAccessToken(owner, params.id, params.tokenId);
812
    });
813
    router.delete('/v0.1/agents/:id', async (request) => {
814
      const owner = operatorId(request);
815
      if (!repository?.deleteAgent || !owner)
816
        throw new Error('Hosted agent deletion is not configured');
817
      const result = await repository.deleteAgent(owner, (request.params as { id: string }).id);
818
      engines.delete(owner);
819
      return result;
820
    });
821
    router.get('/v0.1/directory', async (request) => {
822
      operatorId(request);
823
      if (!repository) throw new Error('Hosted persistence is not configured');
824
      const query = z
825
        .object({
826
          query: z.string().trim().max(100).optional(),
827
          capability: z.string().trim().max(100).optional(),
828
          limit: z.coerce.number().int().min(1).max(50).optional(),
829
        })
830
        .parse(request.query);
831
      return repository.searchPublishedAgents(query);
832
    });
833
    router.get('/v0.1/directory/:id', async (request) => {
834
      operatorId(request);
835
      if (!repository) throw new Error('Hosted persistence is not configured');
836
      const card = await repository.getPublishedAgent((request.params as { id: string }).id);
837
      if (!card) throw new Error('Published agent not found');
838
      return card;
839
    });
840
    router.get('/v0.1/federated-interactions', async (request) => {
841
      const owner = operatorId(request);
842
      if (!repository?.listFederatedInteractions || !owner)
843
        throw new Error('Federated interactions are not configured');
844
      return repository.listFederatedInteractions(owner);
845
    });
846
    router.get('/v0.1/federated-interactions/:id', async (request) => {
847
      const owner = operatorId(request);
848
      if (!repository?.getFederatedInteraction || !owner)
849
        throw new Error('Federated interactions are not configured');
850
      const interaction = await repository.getFederatedInteraction(
851
        owner,
852
        (request.params as { id: string }).id,
853
      );
854
      if (!interaction) throw new Error('Interaction not found');
855
      return interaction;
856
    });
857
    router.get('/v0.1/federated-interactions/:id/session', async (request) => {
858
      const owner = operatorId(request);
859
      if (!repository?.getLiveSession || !owner)
860
        throw new Error('Live sessions are not configured');
861
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
862
      enforceBoundAgent(request, value.agentId);
863
      return repository.getLiveSession(owner, (request.params as { id: string }).id, value.agentId);
864
    });
865
    router.get('/v0.1/federated-interactions/:id/brief', async (request) => {
866
      const owner = operatorId(request);
867
      if (!repository?.getCounterpartyBrief || !owner)
868
        throw new Error('Counterparty briefs are not configured');
869
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
870
      enforceBoundAgent(request, value.agentId);
871
      return repository.getCounterpartyBrief(
872
        owner,
873
        (request.params as { id: string }).id,
874
        value.agentId,
875
      );
876
    });
877
    router.get('/v0.1/federated-interactions/:id/assurance-probes', async (request) => {
878
      const owner = operatorId(request);
879
      if (!repository?.listAssuranceProbePlans || !owner)
880
        throw new Error('Assurance probes are not configured');
881
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
882
      enforceBoundAgent(request, value.agentId);
883
      return repository.listAssuranceProbePlans(
884
        owner,
885
        (request.params as { id: string }).id,
886
        value.agentId,
887
      );
888
    });
889
    router.post('/v0.1/federated-interactions/:id/assurance-responses', async (request) => {
890
      const owner = operatorId(request);
891
      if (!repository?.submitAssuranceProbeResponse || !owner)
892
        throw new Error('Assurance responses are not configured');
893
      const response = AssuranceProbeResponseSchema.parse(request.body);
894
      if (response.interactionId !== (request.params as { id: string }).id)
895
        throw new Error('Interaction path does not match the assurance response');
896
      return repository.submitAssuranceProbeResponse(owner, boundAgentId(request), response);
897
    });
898
    router.get('/v0.1/federated-interactions/:id/assurance-comparisons', async (request) => {
899
      const owner = operatorId(request);
900
      if (!repository?.listAssuranceComparisons || !owner)
901
        throw new Error('Assurance comparisons are not configured');
902
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
903
      enforceBoundAgent(request, value.agentId);
904
      return repository.listAssuranceComparisons(
905
        owner,
906
        (request.params as { id: string }).id,
907
        value.agentId,
908
      );
909
    });
910
    router.get('/v0.1/federated-interactions/:id/assurance-brief', async (request) => {
911
      const owner = operatorId(request);
912
      if (!repository?.getAssuranceBrief || !owner)
913
        throw new Error('Assurance decision briefs are not configured');
914
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
915
      enforceBoundAgent(request, value.agentId);
916
      return repository.getAssuranceBrief(
917
        owner,
918
        (request.params as { id: string }).id,
919
        value.agentId,
920
      );
921
    });
922
    router.post(
923
      '/v0.1/federated-interactions/:id/assurance-safeguards/:safeguardId/decision',
924
      async (request) => {
925
        const owner = operatorId(request);
926
        if (!repository?.decideAssuranceSafeguard || !owner)
927
          throw new Error('Assurance safeguard decisions are not configured');
928
        const value = z
929
          .object({
930
            agentId: z.string().min(1).optional(),
931
            status: z.enum(['accepted', 'rejected', 'modified']),
932
            decisionReason: z.string().trim().max(500).optional(),
933
          })
934
          .strict()
935
          .parse(request.body);
936
        const params = request.params as { id: string; safeguardId: string };
937
        const agentId = value.agentId ?? boundAgentId(request);
938
        if (value.agentId) enforceBoundAgent(request, value.agentId);
939
        return repository.decideAssuranceSafeguard(
940
          owner,
941
          params.id,
942
          agentId,
943
          params.safeguardId,
944
          value.status,
945
          value.decisionReason,
946
        );
947
      },
948
    );
949
    router.post('/v0.1/federated-interactions/:id/completion-reports', async (request) => {
950
      const owner = operatorId(request);
951
      if (!repository?.submitCompletionReport || !owner)
952
        throw new Error('Completion reports are not configured');
953
      const report = InteractionCompletionReportSchema.parse(request.body);
954
      if (report.interactionId !== (request.params as { id: string }).id)
955
        throw new Error('Interaction path does not match the completion report');
956
      return repository.submitCompletionReport(
957
        owner,
958
        boundAgentId(request),
959
        report,
960
        request.headers['x-openclasp-credential-type'] === 'agent_access_token'
961
          ? 'agent_access_token'
962
          : 'oauth_installation',
963
      );
964
    });
965
    router.post('/v0.1/federated-interactions/:id/feedback', async (request) => {
966
      const owner = operatorId(request);
967
      if (!repository?.submitInteractionFeedback || !owner)
968
        throw new Error('Interaction feedback is not configured');
969
      const feedback = InteractionFeedbackSchema.parse(request.body);
970
      if (feedback.interactionId !== (request.params as { id: string }).id)
971
        throw new Error('Interaction path does not match the feedback');
972
      return repository.submitInteractionFeedback(
973
        owner,
974
        boundAgentId(request),
975
        feedback,
976
        request.headers['x-openclasp-credential-type'] === 'agent_access_token'
977
          ? 'agent_access_token'
978
          : 'oauth_installation',
979
      );
980
    });
981
    router.get('/v0.1/feedback-requests', async (request) => {
982
      const owner = operatorId(request);
983
      if (!repository?.listFeedbackRequests || !owner)
984
        throw new Error('Interaction feedback is not configured');
985
      const value = z.object({ agentId: z.string().min(1) }).parse(request.query);
986
      enforceBoundAgent(request, value.agentId);
987
      return repository.listFeedbackRequests(owner, value.agentId);
988
    });
989
    router.post('/v0.1/federated-interactions', async (request) => {
990
      const owner = operatorId(request);
991
      if (!repository?.createFederatedInteraction || !owner)
992
        throw new Error('Federated interactions are not configured');
993
      const interaction = FederatedInteractionSchema.parse(request.body);
994
      const acceptance = interaction.acceptances[interaction.initiatorAgentId];
995
      if (!acceptance) throw new Error('Initiator acceptance is required');
996
      return repository.createFederatedInteraction(owner, {
997
        ...interaction,
998
        acceptances: {
999
          [interaction.initiatorAgentId]: { ...acceptance, method: 'oauth_account' },
1000
        },
1001
      });
1002
    });
1003
    router.post('/v0.1/federated-interactions/:id/respond', async (request) => {
1004
      const owner = operatorId(request);
1005
      if (!repository?.respondToFederatedInteraction || !owner)
1006
        throw new Error('Federated interactions are not configured');
1007
      const value = z
1008
        .object({ agentId: z.string().min(1), decision: z.enum(['accept', 'reject']) })
1009
        .parse(request.body);
1010
      return repository.respondToFederatedInteraction(
1011
        owner,
1012
        (request.params as { id: string }).id,
1013
        value.agentId,
1014
        value.decision,
1015
        'oauth_account',
1016
      );
1017
    });
1018
    router.post('/v0.1/federated-interactions/:id/contract-proposals', async (request) => {
1019
      const owner = operatorId(request);
1020
      if (!repository?.proposeContractRevision || !owner)
1021
        throw new Error('Contract negotiation is not configured');
1022
      const value = z
1023
        .object({
1024
          agentId: z.string().min(1),
1025
          expectedTermsHash: z.string().min(1).optional(),
1026
          contract: InteractionContractSchema,
1027
        })
1028
        .parse(request.body);
1029
      enforceBoundAgent(request, value.agentId);
1030
      return repository.proposeContractRevision(
1031
        owner,
1032
        (request.params as { id: string }).id,
1033
        value.agentId,
1034
        value.contract,
1035
        value.expectedTermsHash,
1036
        request.headers['x-openclasp-credential-type'] === 'agent_access_token'
1037
          ? 'oauth_installation'
1038
          : 'oauth_account',
1039
      );
1040
    });
1041
    router.post(
1042
      '/v0.1/federated-interactions/:id/contract-proposals/:revisionId/respond',
1043
      async (request) => {
1044
        const owner = operatorId(request);
1045
        if (!repository?.respondToContractRevision || !owner)
1046
          throw new Error('Contract negotiation is not configured');
1047
        const value = z
1048
          .object({ agentId: z.string().min(1), decision: z.enum(['accept', 'reject']) })
1049
          .parse(request.body);
1050
        enforceBoundAgent(request, value.agentId);
1051
        const params = request.params as { id: string; revisionId: string };
1052
        return repository.respondToContractRevision(
1053
          owner,
1054
          params.id,
1055
          value.agentId,
1056
          params.revisionId,
1057
          value.decision,
1058
          request.headers['x-openclasp-credential-type'] === 'agent_access_token'
1059
            ? 'oauth_installation'
1060
            : 'oauth_account',
1061
        );
1062
      },
1063
    );
1064
    router.post('/v0.1/delegations', async (request) => {
1065
      const value = DelegationCredentialSchema.parse(request.body);
1066
      const current = await scopedEngine(request);
1067
      current.delegations.set(value.delegationId, value);
1068
      await persist(request, 'delegation', value.delegationId, value);
1069
      return { valid: current.verifyDelegation(value.delegationId) };
1070
    });
1071
    router.post('/v0.1/delegations/:id/verify', async (request) => ({
1072
      valid: (await scopedEngine(request)).verifyDelegation((request.params as { id: string }).id),
1073
    }));
1074
    router.post('/v0.1/interactions/contracts', async (request) => {
1075
      const contract = (await scopedEngine(request)).saveContract(
1076
        InteractionContractSchema.parse(request.body),
1077
      );
1078
      await persist(request, 'contract', contract.interactionId, contract);
1079
      return contract;
1080
    });
1081
    router.post('/v0.1/events', async (request) => {
1082
      const event = (await scopedEngine(request)).recordEvent(
1083
        InteractionEventSchema.parse(request.body),
1084
      );
1085
      await persist(request, 'event', event.eventId, event);
1086
      return event;
1087
    });
1088
    router.post('/v0.1/risk/assess', async (request) =>
1089
      (await scopedEngine(request)).assess(request.body as any),
1090
    );
1091
    router.get('/v0.1/profiles/:id', async (request) => {
1092
      const { id } = request.params as { id: string };
1093
      const query = request.query as { version?: string; taskCategory?: string };
1094
      return (await scopedEngine(request)).getRisk(
1095
        id,
1096
        query.version ?? '1.0.0',
1097
        query.taskCategory ?? 'general',
1098
      );
1099
    });
1100
    router.post('/v0.1/claims/check', async (request) =>
1101
      ((value) => factChecker.check(value.claim, value.permission))(
1102
        z.object({ claim: z.string(), permission: z.boolean().optional() }).parse(request.body),
1103
      ),
1104
    );
1105
    router.post('/v0.1/receipts', async (request) => {
1106
      const receipt = (await scopedEngine(request)).submitReceipt(
1107
        ReceiptSchema.parse(request.body),
1108
      );
1109
      await persist(request, 'receipt', receipt.receiptId, receipt);
1110
      return receipt;
1111
    });
1112
    router.post('/v0.1/receipts/verify', async (request) => {
1113
      try {
1114
        (await scopedEngine(request)).verifyReceipt(ReceiptSchema.parse(request.body));
1115
        return { valid: true };
1116
      } catch {
1117
        return { valid: false };
1118
      }
1119
    });
1120
    router.post('/v0.1/feedback', async (request) => {
1121
      const feedback = FeedbackSchema.parse(request.body);
1122
      const current = await scopedEngine(request);
1123
      const result = current.submitFeedback(feedback);
1124
      await persist(request, 'feedback', feedback.feedbackId, feedback);
1125
      for (const profile of current.profiles.values())
1126
        await persist(
1127
          request,
1128
          'profile',
1129
          `${profile.agentId}|${profile.agentVersion}|${profile.taskCategory}`,
1130
          profile,
1131
        );
1132
      return result;
1133
    });
1134
    router.post('/v0.1/conflicts', async (request) => {
1135
      const conflict = (await scopedEngine(request)).createConflict(request.body as any);
1136
      await persist(request, 'conflict', conflict.conflictId, conflict);
1137
      return conflict;
1138
    });
1139
    router.post('/v0.1/conflicts/:id/permit', async (request) => {
1140
      const conflict = (await scopedEngine(request)).permitMediation(
1141
        (request.params as { id: string }).id,
1142
        (request.body as { agentId: string }).agentId,
1143
      );
1144
      await persist(request, 'conflict', conflict.conflictId, conflict);
1145
      return conflict;
1146
    });
1147
    router.post('/v0.1/conflicts/:id/resolve', async (request) => {
1148
      const conflict = (await scopedEngine(request)).resolveConflict(
1149
        (request.params as { id: string }).id,
1150
        (request.body as { resolution: string }).resolution,
1151
      );
1152
      await persist(request, 'conflict', conflict.conflictId, conflict);
1153
      return conflict;
1154
    });
1155
    router.post('/v0.1/revocations/agents/:id', async (request) => {
1156
      const id = (request.params as { id: string }).id;
1157
      const current = await scopedEngine(request);
1158
      current.revokeAgent(id);
1159
      await persist(request, 'agent', id, current.agents.get(id));
1160
      return { revoked: true };
1161
    });
1162
    router.post('/v0.1/revocations/delegations/:id', async (request) => {
1163
      const id = (request.params as { id: string }).id;
1164
      const current = await scopedEngine(request);
1165
      current.revokeDelegation(id);
1166
      await persist(request, 'delegation', id, current.delegations.get(id));
1167
      return { revoked: true };
1168
    });
1169
    router.post('/v0.1/contributions/consent', async (request) => {
1170
      const value = z.object({ agentId: z.string(), enabled: z.boolean() }).parse(request.body);
1171
      const current = await scopedEngine(request);
1172
      current.setContributionConsent(value.agentId, value.enabled);
1173
      await persist(request, 'consent', value.agentId, {
1174
        agentId: value.agentId,
1175
        ...current.contributionConsent.get(value.agentId),
1176
      });
1177
      return value;
1178
    });
1179
  });
1180
  return app;
1181
}