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

Viewing files at commit 20744dd65349Commit detailsView latest

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