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

Viewing files at commit 535fc73a59b4Commit detailsView latest

apps/dashboard/src/preview.ts 623 lines · 19.2 KB · typescript
1
export const previewKey = 'openclasp.preview.v1';
2
3
export const previewSession = {
4
  user: {
5
    sub: 'local-preview',
6
    name: 'Local preview',
7
    email: 'preview@localhost',
8
  },
9
};
10
11
export type DashboardData = {
12
  agents: Record<string, any>[];
13
  projects: Record<string, any>[];
14
  installations: Record<string, any>[];
15
  setupRequests: Record<string, any>[];
16
  publications: Record<string, any>[];
17
  interactions: Record<string, any>[];
18
  federatedInteractions: Record<string, any>[];
19
  liveSessions: Record<string, any>[];
20
  hostedThreads: Record<string, any>[];
21
  events: Record<string, any>[];
22
  conflicts: Record<string, any>[];
23
  receipts: Record<string, any>[];
24
  profiles: Record<string, any>[];
25
  counterpartyBriefs: Record<string, any>[];
26
  completionReports: Record<string, any>[];
27
  feedbackRequests: Record<string, any>[];
28
  interactionFeedback: Record<string, any>[];
29
  interactionConclusions: Record<string, any>[];
30
  learningEligibility: Record<string, any>[];
31
  profileDeltas: Record<string, any>[];
32
  runtimes: Record<string, any>[];
33
  accessTokens: Record<string, any>[];
34
};
35
36
export type Settings = {
37
  displayName: string;
38
  contributionEnabled: boolean;
39
  retentionDays: number;
40
  evidenceSharing: 'never' | 'ask' | 'contract_only';
41
  rawConversationsStored: false;
42
};
43
44
export const defaultPreviewSettings: Settings = {
45
  displayName: 'Local operator',
46
  contributionEnabled: false,
47
  retentionDays: 30,
48
  evidenceSharing: 'ask',
49
  rawConversationsStored: false,
50
};
51
52
const ago = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString();
53
const ahead = (minutes: number) => new Date(Date.now() + minutes * 60_000).toISOString();
54
55
export function createPreviewData(): DashboardData {
56
  return {
57
    projects: [
58
      { projectId: 'proj_ops', name: 'Operations', createdAt: ago(21 * 24 * 60) },
59
      { projectId: 'proj_research', name: 'Research', createdAt: ago(12 * 24 * 60) },
60
    ],
61
    agents: [
62
      {
63
        agentId: 'agent_atlas',
64
        projectId: 'proj_research',
65
        name: 'Atlas Research',
66
        description: 'Literature review and planning',
67
        framework: 'Claude',
68
        agentVersion: '1.4.2',
69
        agentMode: 'persistent_runtime',
70
        a2aEndpoint: 'https://atlas.example.com/a2a',
71
        autoPublish: true,
72
        autoAcceptPolicy: 'safe_matching',
73
        autoAcceptTaskCategories: ['research', 'planning'],
74
        capabilities: ['research', 'planning', 'summarization'],
75
        limitations: ['no payments'],
76
        identityMode: 'oauth_installation',
77
        status: 'active',
78
        createdAt: ago(12 * 24 * 60),
79
        updatedAt: ago(8),
80
        presence: { status: 'online', lastSeenAt: ago(1) },
81
      },
82
      {
83
        agentId: 'agent_harbor',
84
        projectId: 'proj_ops',
85
        name: 'Harbor Ops',
86
        description: 'Incident triage and runbooks',
87
        framework: 'GPT',
88
        agentVersion: '2.1.0',
89
        agentMode: 'temporary_chat',
90
        autoPublish: false,
91
        autoAcceptPolicy: 'off',
92
        autoAcceptTaskCategories: [],
93
        capabilities: ['ops', 'triage'],
94
        limitations: ['no production writes'],
95
        identityMode: 'oauth_installation',
96
        status: 'active',
97
        createdAt: ago(21 * 24 * 60),
98
        updatedAt: ago(180),
99
        presence: { status: 'offline', lastSeenAt: ago(180) },
100
      },
101
    ],
102
    installations: [
103
      {
104
        installationId: 'inst_atlas',
105
        clientId: 'mcp_atlas',
106
        agentId: 'agent_atlas',
107
        projectId: 'proj_research',
108
        connectedAt: ago(12 * 24 * 60),
109
        updatedAt: ago(8),
110
      },
111
    ],
112
    setupRequests: [
113
      {
114
        requestId: 'setup_lumen',
115
        clientId: 'mcp_lumen',
116
        action: 'connect',
117
        status: 'pending',
118
        agentName: 'Lumen Writer',
119
        projectName: 'Content',
120
        framework: 'Claude',
121
        agentVersion: '0.9.0',
122
        autoPublish: true,
123
        autoAcceptPolicy: 'safe_matching',
124
        autoAcceptTaskCategories: ['writing', 'editing'],
125
        capabilities: ['writing', 'editing', 'research'],
126
        limitations: ['no outbound email'],
127
        requestedAt: ago(18),
128
      },
129
    ],
130
    publications: [{ agentId: 'agent_atlas', published: true, updatedAt: ago(40) }],
131
    interactions: [
132
      {
133
        interactionId: 'ix_local_brief',
134
        agentId: 'agent_atlas',
135
        status: 'completed',
136
        contract: {
137
          purpose: 'Produce a source-backed research brief',
138
          taskCategory: 'research',
139
        },
140
        createdAt: ago(240),
141
        completedAt: ago(220),
142
      },
143
    ],
144
    federatedInteractions: [
145
      {
146
        interactionId: 'ix_shared_review',
147
        initiatorAgentId: 'agent_peer_nova',
148
        responderAgentId: 'agent_atlas',
149
        status: 'pending',
150
        termsHash: '7f3c91a0b2e84d11c6aa09f1d3e8b470',
151
        createdAt: ago(26),
152
        contract: {
153
          purpose: 'Review a research brief for scope and sources',
154
          taskCategory: 'research',
155
        },
156
      },
157
      {
158
        interactionId: 'ix_shared_ops',
159
        initiatorAgentId: 'agent_atlas',
160
        responderAgentId: 'agent_peer_keel',
161
        status: 'active',
162
        termsHash: '12ab44c0e91f77d0aa3310bc44ee9012',
163
        createdAt: ago(90),
164
        contract: {
165
          purpose: 'Share a sanitized incident timeline',
166
          taskCategory: 'coordination',
167
        },
168
        acceptances: {
169
          agent_peer_keel: { method: 'policy_auto_accept' },
170
        },
171
      },
172
    ],
173
    liveSessions: [
174
      {
175
        interactionId: 'ix_shared_ops',
176
        initiatorAgentId: 'agent_atlas',
177
        responderAgentId: 'agent_peer_keel',
178
        status: 'active',
179
        createdAt: ago(88),
180
        activatedAt: ago(87),
181
        expiresAt: ahead(12),
182
      },
183
    ],
184
    hostedThreads: [],
185
    events: [
186
      {
187
        eventId: 'evt_1',
188
        eventType: 'interaction_started',
189
        agentId: 'agent_atlas',
190
        interactionId: 'ix_shared_ops',
191
        timestamp: ago(88),
192
        visibility: 'participants',
193
      },
194
      {
195
        eventId: 'evt_2',
196
        eventType: 'policy_warning',
197
        agentId: 'agent_harbor',
198
        interactionId: 'ix_local_brief',
199
        timestamp: ago(200),
200
        visibility: 'owner',
201
      },
202
      {
203
        eventId: 'evt_3',
204
        eventType: 'claim_checked',
205
        agentId: 'agent_atlas',
206
        interactionId: 'ix_local_brief',
207
        timestamp: ago(230),
208
        visibility: 'participants',
209
      },
210
      {
211
        eventId: 'evt_4',
212
        eventType: 'session_activated',
213
        agentId: 'agent_atlas',
214
        interactionId: 'ix_shared_ops',
215
        timestamp: ago(87),
216
        visibility: 'participants',
217
      },
218
    ],
219
    conflicts: [
220
      {
221
        conflictId: 'dsp_1',
222
        interactionId: 'ix_local_brief',
223
        status: 'open',
224
        createdAt: ago(190),
225
      },
226
    ],
227
    receipts: [
228
      {
229
        receiptId: 'rcpt_1',
230
        interactionId: 'ix_local_brief',
231
        agentId: 'agent_atlas',
232
        outcome: 'success',
233
        completedAt: ago(220),
234
      },
235
    ],
236
    counterpartyBriefs: [
237
      {
238
        briefId: 'brief_1',
239
        interactionId: 'ix_local_brief',
240
        recipientAgentId: 'agent_atlas',
241
        subjectAgentId: 'agent_peer_nova',
242
        decision: 'CHALLENGE',
243
        relevantSampleSize: 3,
244
        historyConfidence: 0.38,
245
        requirements: [
246
          { requirement: 'Provide source evidence', status: 'partial', confidence: 0.7 },
247
        ],
248
        generatedAt: ago(241),
249
      },
250
    ],
251
    completionReports: [
252
      {
253
        reportId: 'report_1',
254
        interactionId: 'ix_local_brief',
255
        reportingAgentId: 'agent_atlas',
256
        counterpartyAgentId: 'agent_peer_nova',
257
        outcome: 'success',
258
        summary: 'Research brief delivered with sources and scope notes.',
259
        criteria: [{ criterion: 'Brief delivered', status: 'met' }],
260
        completedAt: ago(222),
261
      },
262
      {
263
        reportId: 'report_2',
264
        interactionId: 'ix_local_brief',
265
        reportingAgentId: 'agent_peer_nova',
266
        counterpartyAgentId: 'agent_atlas',
267
        outcome: 'success',
268
        summary: 'Received and accepted the requested brief.',
269
        criteria: [{ criterion: 'Brief delivered', status: 'met' }],
270
        completedAt: ago(221),
271
      },
272
    ],
273
    feedbackRequests: [
274
      {
275
        requestId: 'feedback_request_1',
276
        interactionId: 'ix_local_brief',
277
        reviewerAgentId: 'agent_atlas',
278
        subjectAgentId: 'agent_peer_nova',
279
        status: 'submitted',
280
        requestedAt: ago(221),
281
        dueAt: ago(197),
282
      },
283
      {
284
        requestId: 'feedback_request_2',
285
        interactionId: 'ix_local_brief',
286
        reviewerAgentId: 'agent_peer_nova',
287
        subjectAgentId: 'agent_atlas',
288
        status: 'submitted',
289
        requestedAt: ago(221),
290
        dueAt: ago(197),
291
      },
292
    ],
293
    interactionFeedback: [
294
      {
295
        feedbackId: 'feedback_1',
296
        interactionId: 'ix_local_brief',
297
        reviewerAgentId: 'agent_atlas',
298
        subjectAgentId: 'agent_peer_nova',
299
        ratings: { outcome_satisfaction: 0.9, communication: 0.8, reliability: 0.9 },
300
        wouldWorkAgain: 'yes',
301
        submittedAt: ago(219),
302
      },
303
    ],
304
    interactionConclusions: [
305
      {
306
        conclusionId: 'conclusion_1',
307
        interactionId: 'ix_local_brief',
308
        outcome: 'success',
309
        consensus: 'bilateral_agreement',
310
        summary: 'Both agents reported successful delivery and acceptance.',
311
        criteria: [{ criterion: 'Brief delivered', status: 'met' }],
312
        averageRatings: { outcome_satisfaction: 0.88, communication: 0.82, reliability: 0.9 },
313
        generatedAt: ago(218),
314
      },
315
    ],
316
    learningEligibility: [
317
      {
318
        decisionId: 'eligibility_1',
319
        interactionId: 'ix_local_brief',
320
        eligible: true,
321
        sampleWeight: 0.87,
322
        contributionMode: 'local_only',
323
        structuredDataOnly: true,
324
        reasons: ['Bilateral reports provide outcome corroboration'],
325
        decidedAt: ago(218),
326
      },
327
    ],
328
    profileDeltas: [
329
      {
330
        deltaId: 'delta_1',
331
        interactionId: 'ix_local_brief',
332
        agentId: 'agent_atlas',
333
        agentVersion: '1.4.2',
334
        taskCategory: 'research',
335
        sampleWeight: 0.87,
336
        dimensionDeltas: { completion: 0.02, evidence: 0.03, communication: -0.01 },
337
        appliedAt: ago(218),
338
      },
339
    ],
340
    profiles: [
341
      {
342
        agentId: 'agent_atlas',
343
        taskCategory: 'research',
344
        agentVersion: '1.4.2',
345
        sampleSize: 14,
346
        effectiveSampleSize: 10.8,
347
        updatedAt: ago(218),
348
        completion: 0.92,
349
        acceptance: 0.87,
350
        specification: 0.86,
351
        scope: 0.84,
352
        evidence: 0.88,
353
        communication: 0.79,
354
        deadline: 0.9,
355
        disputes: 0.08,
356
      },
357
      {
358
        agentId: 'agent_harbor',
359
        taskCategory: 'ops',
360
        agentVersion: '2.1.0',
361
        sampleSize: 6,
362
        effectiveSampleSize: 4.1,
363
        updatedAt: ago(3 * 24 * 60),
364
        completion: 0.71,
365
        acceptance: 0.68,
366
        specification: 0.63,
367
        scope: 0.66,
368
        evidence: 0.58,
369
        communication: 0.74,
370
        deadline: 0.62,
371
        disputes: 0.22,
372
      },
373
    ],
374
    runtimes: [
375
      {
376
        agentId: 'agent_atlas',
377
        endpoint: 'https://atlas.example.com/openclasp',
378
        a2aEndpoint: 'https://atlas.example.com/a2a',
379
        status: 'verified',
380
        verifiedAt: ago(40),
381
      },
382
    ],
383
    accessTokens: [],
384
  };
385
}
386
387
export function applyPreviewRequest(
388
  data: DashboardData,
389
  settings: Settings,
390
  path: string,
391
  init?: RequestInit,
392
): { data: DashboardData; settings: Settings; result: unknown } {
393
  const method = (init?.method ?? 'GET').toUpperCase();
394
  const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};
395
396
  if (path === '/v0.1/dashboard' && method === 'GET') return { data, settings, result: data };
397
  if (path === '/v0.1/settings' && method === 'GET') return { data, settings, result: settings };
398
  if (path === '/v0.1/settings' && method === 'PUT') {
399
    const next = {
400
      ...settings,
401
      ...body,
402
      rawConversationsStored: false as const,
403
    } as Settings;
404
    return { data, settings: next, result: next };
405
  }
406
407
  if (path === '/v0.1/provider-connections' && method === 'POST') {
408
    const suffix = crypto.randomUUID();
409
    const projectName = String(body.projectName ?? 'Hosted agents');
410
    const existingProject = data.projects.find(
411
      (project) => String(project.name).toLowerCase() === projectName.toLowerCase(),
412
    );
413
    const project = existingProject ?? {
414
      projectId: `project_${suffix}`,
415
      name: projectName,
416
      createdAt: new Date().toISOString(),
417
    };
418
    const agentId = `agent_${suffix}`;
419
    const createdAt = new Date();
420
    const tokenId = suffix.replaceAll('-', '').slice(0, 16);
421
    const provider = body.provider === 'custom' ? 'custom' : 'botpress';
422
    const agent = {
423
      agentId,
424
      projectId: project.projectId,
425
      name: String(body.agentName ?? 'Botpress agent'),
426
      description: String(body.description ?? ''),
427
      framework: provider === 'botpress' ? 'Botpress' : 'Custom runtime',
428
      agentVersion: '1.0.0',
429
      agentMode: 'persistent_runtime',
430
      transport: 'direct_a2a',
431
      autoPublish: false,
432
      autoAcceptPolicy: 'off',
433
      autoAcceptTaskCategories: [],
434
      capabilities: body.capabilities ?? [],
435
      limitations: body.limitations ?? [],
436
      identityMode: 'owner_managed',
437
      status: 'active',
438
      createdAt: createdAt.toISOString(),
439
      updatedAt: createdAt.toISOString(),
440
      presence: { status: 'offline' },
441
    };
442
    const accessToken = {
443
      tokenId,
444
      token: `oc_at_${tokenId}.preview_agent_access_token_secret_not_for_production`,
445
      agentId,
446
      name: provider === 'botpress' ? 'Botpress' : 'Custom runtime',
447
      scopes: ['mcp:access', 'runtime:connect'],
448
      createdAt: createdAt.toISOString(),
449
      expiresAt: new Date(
450
        createdAt.getTime() + Number(body.expiresInDays ?? 365) * 86_400_000,
451
      ).toISOString(),
452
    };
453
    return {
454
      data: {
455
        ...data,
456
        projects: existingProject ? data.projects : [...data.projects, project],
457
        agents: [...data.agents, agent],
458
        accessTokens: [accessToken, ...data.accessTokens],
459
      },
460
      settings,
461
      result: { agent, project, provider, accessToken },
462
    };
463
  }
464
465
  const automation = path.match(/^\/v0\.1\/agents\/([^/]+)\/automation$/);
466
  if (automation && method === 'PUT') {
467
    const agentId = decodeURIComponent(automation[1] ?? '');
468
    const next = {
469
      ...data,
470
      agents: data.agents.map((agent) =>
471
        agent.agentId === agentId
472
          ? {
473
              ...agent,
474
              autoPublish: Boolean(body.autoPublish),
475
              autoAcceptPolicy: body.autoAcceptPolicy,
476
              autoAcceptTaskCategories: body.autoAcceptTaskCategories,
477
            }
478
          : agent,
479
      ),
480
      publications: body.autoPublish
481
        ? [
482
            ...data.publications.filter((item) => item.agentId !== agentId),
483
            { agentId, published: true, updatedAt: new Date().toISOString() },
484
          ]
485
        : data.publications.filter((item) => item.agentId !== agentId),
486
    };
487
    return { data: next, settings, result: { ok: true } };
488
  }
489
490
  const runtime = path.match(/^\/v0\.1\/agents\/([^/]+)\/runtime$/);
491
  if (runtime && method === 'PUT') {
492
    const agentId = decodeURIComponent(runtime[1] ?? '');
493
    const endpoint = String(body.endpoint ?? '');
494
    const record = {
495
      agentId,
496
      endpoint,
497
      a2aEndpoint: endpoint,
498
      status: 'verified',
499
      verifiedAt: new Date().toISOString(),
500
    };
501
    return {
502
      data: {
503
        ...data,
504
        runtimes: [...data.runtimes.filter((item) => item.agentId !== agentId), record],
505
      },
506
      settings,
507
      result: record,
508
    };
509
  }
510
  const tokenCollection = path.match(/^\/v0\.1\/agents\/([^/]+)\/access-tokens$/);
511
  if (tokenCollection && method === 'POST') {
512
    const agentId = decodeURIComponent(tokenCollection[1] ?? '');
513
    const tokenId = crypto.randomUUID().replaceAll('-', '').slice(0, 16);
514
    const createdAt = new Date();
515
    const expiresInDays = Number(body.expiresInDays ?? 365);
516
    const record = {
517
      tokenId,
518
      agentId,
519
      name: String(body.name ?? 'Hosted provider'),
520
      scopes: ['mcp:access', 'runtime:connect'],
521
      createdAt: createdAt.toISOString(),
522
      expiresAt: new Date(createdAt.getTime() + expiresInDays * 86_400_000).toISOString(),
523
    };
524
    return {
525
      data: { ...data, accessTokens: [record, ...data.accessTokens] },
526
      settings,
527
      result: {
528
        ...record,
529
        token: `oc_at_${tokenId}.preview_agent_access_token_secret_not_for_production`,
530
      },
531
    };
532
  }
533
  const tokenItem = path.match(/^\/v0\.1\/agents\/([^/]+)\/access-tokens\/([^/]+)$/);
534
  if (tokenItem && method === 'DELETE') {
535
    const tokenId = decodeURIComponent(tokenItem[2] ?? '');
536
    return {
537
      data: {
538
        ...data,
539
        accessTokens: data.accessTokens.map((token) =>
540
          token.tokenId === tokenId ? { ...token, revokedAt: new Date().toISOString() } : token,
541
        ),
542
      },
543
      settings,
544
      result: { tokenId, revokedAt: new Date().toISOString() },
545
    };
546
  }
547
  const agentDelete = path.match(/^\/v0\.1\/agents\/([^/]+)$/);
548
  if (agentDelete && method === 'DELETE') {
549
    const agentId = decodeURIComponent(agentDelete[1] ?? '');
550
    return {
551
      data: {
552
        ...data,
553
        agents: data.agents.filter((item) => item.agentId !== agentId),
554
        publications: data.publications.filter((item) => item.agentId !== agentId),
555
        runtimes: data.runtimes.filter((item) => item.agentId !== agentId),
556
        installations: data.installations.filter((item) => item.agentId !== agentId),
557
        accessTokens: data.accessTokens.filter((item) => item.agentId !== agentId),
558
      },
559
      settings,
560
      result: { agentId, deleted: true },
561
    };
562
  }
563
564
  if (runtime && method === 'DELETE') {
565
    const agentId = decodeURIComponent(runtime[1] ?? '');
566
    return {
567
      data: {
568
        ...data,
569
        runtimes: data.runtimes.filter((item) => item.agentId !== agentId),
570
      },
571
      settings,
572
      result: { agentId, status: 'disabled' },
573
    };
574
  }
575
576
  const federated = path.match(/^\/v0\.1\/federated-interactions\/([^/]+)\/respond$/);
577
  if (federated && method === 'POST') {
578
    const interactionId = decodeURIComponent(federated[1] ?? '');
579
    const decision = body.decision === 'accept' ? 'active' : 'rejected';
580
    return {
581
      data: {
582
        ...data,
583
        federatedInteractions: data.federatedInteractions.map((item) =>
584
          item.interactionId === interactionId ? { ...item, status: decision } : item,
585
        ),
586
      },
587
      settings,
588
      result: { ok: true },
589
    };
590
  }
591
592
  const onboarding = path.match(/^\/v0\.1\/onboarding\/([^/]+)\/(approve|reject)$/);
593
  if (onboarding && method === 'POST') {
594
    const requestId = decodeURIComponent(onboarding[1] ?? '');
595
    const decision = onboarding[2] === 'approve' ? 'approved' : 'rejected';
596
    return {
597
      data: {
598
        ...data,
599
        setupRequests: data.setupRequests.map((item) =>
600
          item.requestId === requestId
601
            ? { ...item, status: decision, decidedAt: new Date().toISOString() }
602
            : item,
603
        ),
604
      },
605
      settings,
606
      result: { ok: true },
607
    };
608
  }
609
610
  throw new Error('Preview cannot perform this action');
611
}
612
613
export function isPreviewActive() {
614
  return import.meta.env.DEV && sessionStorage.getItem(previewKey) === '1';
615
}
616
617
export function enablePreview() {
618
  sessionStorage.setItem(previewKey, '1');
619
}
620
621
export function disablePreview() {
622
  sessionStorage.removeItem(previewKey);
623
}