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

Viewing files at commit 3f140fdd2001Commit detailsView latest

apps/dashboard/src/preview.ts 795 lines · 24.5 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
  intelligenceSummaries: Record<string, any>[];
33
  runtimes: Record<string, any>[];
34
  accessTokens: Record<string, any>[];
35
};
36
37
export type Settings = {
38
  displayName: string;
39
  contributionEnabled: boolean;
40
  retentionDays: number;
41
  evidenceSharing: 'never' | 'ask' | 'contract_only';
42
  rawConversationsStored: false;
43
};
44
45
export const defaultPreviewSettings: Settings = {
46
  displayName: 'Local operator',
47
  contributionEnabled: false,
48
  retentionDays: 30,
49
  evidenceSharing: 'ask',
50
  rawConversationsStored: false,
51
};
52
53
const ago = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString();
54
const ahead = (minutes: number) => new Date(Date.now() + minutes * 60_000).toISOString();
55
56
export function createPreviewData(): DashboardData {
57
  return {
58
    projects: [
59
      { projectId: 'proj_ops', name: 'Operations', createdAt: ago(21 * 24 * 60) },
60
      { projectId: 'proj_research', name: 'Research', createdAt: ago(12 * 24 * 60) },
61
    ],
62
    agents: [
63
      {
64
        agentId: 'agent_atlas',
65
        projectId: 'proj_research',
66
        name: 'Atlas Research',
67
        description: 'Literature review and planning',
68
        framework: 'Claude',
69
        agentVersion: '1.4.2',
70
        agentMode: 'persistent_runtime',
71
        a2aEndpoint: 'https://atlas.example.com/a2a',
72
        autoPublish: true,
73
        autoAcceptPolicy: 'safe_matching',
74
        autoAcceptTaskCategories: ['research', 'planning'],
75
        capabilities: ['research', 'planning', 'summarization'],
76
        limitations: ['no payments'],
77
        identityMode: 'oauth_installation',
78
        status: 'active',
79
        createdAt: ago(12 * 24 * 60),
80
        updatedAt: ago(8),
81
        presence: { status: 'online', lastSeenAt: ago(1) },
82
      },
83
      {
84
        agentId: 'agent_harbor',
85
        projectId: 'proj_ops',
86
        name: 'Harbor Ops',
87
        description: 'Incident triage and runbooks',
88
        framework: 'GPT',
89
        agentVersion: '2.1.0',
90
        agentMode: 'temporary_chat',
91
        autoPublish: false,
92
        autoAcceptPolicy: 'off',
93
        autoAcceptTaskCategories: [],
94
        capabilities: ['ops', 'triage'],
95
        limitations: ['no production writes'],
96
        identityMode: 'oauth_installation',
97
        status: 'active',
98
        createdAt: ago(21 * 24 * 60),
99
        updatedAt: ago(180),
100
        presence: { status: 'offline', lastSeenAt: ago(180) },
101
      },
102
    ],
103
    installations: [
104
      {
105
        installationId: 'inst_atlas',
106
        clientId: 'mcp_atlas',
107
        agentId: 'agent_atlas',
108
        projectId: 'proj_research',
109
        connectedAt: ago(12 * 24 * 60),
110
        updatedAt: ago(8),
111
      },
112
    ],
113
    setupRequests: [
114
      {
115
        requestId: 'setup_lumen',
116
        clientId: 'mcp_lumen',
117
        action: 'connect',
118
        status: 'pending',
119
        agentName: 'Lumen Writer',
120
        projectName: 'Content',
121
        framework: 'Claude',
122
        agentVersion: '0.9.0',
123
        autoPublish: true,
124
        autoAcceptPolicy: 'safe_matching',
125
        autoAcceptTaskCategories: ['writing', 'editing'],
126
        capabilities: ['writing', 'editing', 'research'],
127
        limitations: ['no outbound email'],
128
        requestedAt: ago(18),
129
      },
130
    ],
131
    publications: [{ agentId: 'agent_atlas', published: true, updatedAt: ago(40) }],
132
    interactions: [
133
      {
134
        interactionId: 'ix_local_brief',
135
        agentId: 'agent_atlas',
136
        status: 'completed',
137
        contract: {
138
          purpose: 'Produce a source-backed research brief',
139
          taskCategory: 'research',
140
        },
141
        createdAt: ago(240),
142
        completedAt: ago(220),
143
      },
144
    ],
145
    federatedInteractions: [
146
      {
147
        interactionId: 'ix_shared_review',
148
        initiatorAgentId: 'agent_peer_nova',
149
        responderAgentId: 'agent_atlas',
150
        status: 'pending',
151
        termsHash: '7f3c91a0b2e84d11c6aa09f1d3e8b470',
152
        contractRevision: 1,
153
        createdAt: ago(26),
154
        contract: {
155
          purpose: 'Review a research brief for scope and sources',
156
          taskCategory: 'research',
157
          parties: ['agent_peer_nova', 'agent_atlas'],
158
        },
159
        contractRevisions: [
160
          {
161
            revisionId: '17c3a10b-2e84-4d11-86aa-09f1d3e8b470',
162
            revision: 1,
163
            termsHash: '7f3c91a0b2e84d11c6aa09f1d3e8b470',
164
            proposedByAgentId: 'agent_peer_nova',
165
            status: 'proposed',
166
            acceptances: { agent_peer_nova: { method: 'oauth_installation' } },
167
          },
168
        ],
169
      },
170
      {
171
        interactionId: 'ix_shared_ops',
172
        initiatorAgentId: 'agent_atlas',
173
        responderAgentId: 'agent_peer_keel',
174
        status: 'active',
175
        termsHash: '12ab44c0e91f77d0aa3310bc44ee9012',
176
        contractRevision: 1,
177
        createdAt: ago(90),
178
        contract: {
179
          purpose: 'Share a sanitized incident timeline',
180
          taskCategory: 'coordination',
181
          parties: ['agent_atlas', 'agent_peer_keel'],
182
        },
183
        acceptances: {
184
          agent_peer_keel: { method: 'policy_auto_accept' },
185
        },
186
        contractRevisions: [
187
          {
188
            revisionId: '22ab44c0-e91f-47d0-aa33-10bc44ee9012',
189
            revision: 1,
190
            termsHash: '12ab44c0e91f77d0aa3310bc44ee9012',
191
            proposedByAgentId: 'agent_atlas',
192
            status: 'accepted',
193
            acceptances: {
194
              agent_atlas: { method: 'oauth_installation' },
195
              agent_peer_keel: { method: 'policy_auto_accept' },
196
            },
197
          },
198
        ],
199
      },
200
    ],
201
    liveSessions: [
202
      {
203
        interactionId: 'ix_shared_ops',
204
        initiatorAgentId: 'agent_atlas',
205
        responderAgentId: 'agent_peer_keel',
206
        status: 'active',
207
        createdAt: ago(88),
208
        activatedAt: ago(87),
209
        expiresAt: ahead(12),
210
      },
211
    ],
212
    hostedThreads: [],
213
    events: [
214
      {
215
        eventId: 'evt_1',
216
        eventType: 'interaction_started',
217
        agentId: 'agent_atlas',
218
        interactionId: 'ix_shared_ops',
219
        timestamp: ago(88),
220
        visibility: 'participants',
221
      },
222
      {
223
        eventId: 'evt_2',
224
        eventType: 'policy_warning',
225
        agentId: 'agent_harbor',
226
        interactionId: 'ix_local_brief',
227
        timestamp: ago(200),
228
        visibility: 'owner',
229
      },
230
      {
231
        eventId: 'evt_3',
232
        eventType: 'claim_checked',
233
        agentId: 'agent_atlas',
234
        interactionId: 'ix_local_brief',
235
        timestamp: ago(230),
236
        visibility: 'participants',
237
      },
238
      {
239
        eventId: 'evt_4',
240
        eventType: 'session_activated',
241
        agentId: 'agent_atlas',
242
        interactionId: 'ix_shared_ops',
243
        timestamp: ago(87),
244
        visibility: 'participants',
245
      },
246
    ],
247
    conflicts: [
248
      {
249
        conflictId: 'dsp_1',
250
        interactionId: 'ix_local_brief',
251
        status: 'open',
252
        createdAt: ago(190),
253
      },
254
    ],
255
    receipts: [
256
      {
257
        receiptId: 'rcpt_1',
258
        interactionId: 'ix_local_brief',
259
        agentId: 'agent_atlas',
260
        outcome: 'success',
261
        completedAt: ago(220),
262
      },
263
      {
264
        receiptId: 'rcpt_ops_provisional',
265
        interactionId: 'ix_shared_ops',
266
        outcome: 'partial',
267
        unilateral: true,
268
        provisional: true,
269
        confidence: 0.42,
270
        completedAt: ago(12),
271
      },
272
    ],
273
    counterpartyBriefs: [
274
      {
275
        briefId: 'brief_1',
276
        interactionId: 'ix_local_brief',
277
        recipientAgentId: 'agent_atlas',
278
        subjectAgentId: 'agent_peer_nova',
279
        decision: 'CHALLENGE',
280
        relevantSampleSize: 3,
281
        historyConfidence: 0.38,
282
        requirements: [
283
          { requirement: 'Provide source evidence', status: 'partial', confidence: 0.7 },
284
        ],
285
        generatedAt: ago(241),
286
      },
287
    ],
288
    completionReports: [
289
      {
290
        reportId: 'report_1',
291
        interactionId: 'ix_local_brief',
292
        reportingAgentId: 'agent_atlas',
293
        counterpartyAgentId: 'agent_peer_nova',
294
        outcome: 'success',
295
        summary: 'Research brief delivered with sources and scope notes.',
296
        criteria: [{ criterion: 'Brief delivered', status: 'met' }],
297
        completedAt: ago(222),
298
      },
299
      {
300
        reportId: 'report_2',
301
        interactionId: 'ix_local_brief',
302
        reportingAgentId: 'agent_peer_nova',
303
        counterpartyAgentId: 'agent_atlas',
304
        outcome: 'success',
305
        summary: 'Received and accepted the requested brief.',
306
        criteria: [{ criterion: 'Brief delivered', status: 'met' }],
307
        completedAt: ago(221),
308
      },
309
      {
310
        reportId: 'report_ops_1',
311
        interactionId: 'ix_shared_ops',
312
        reportingAgentId: 'agent_atlas',
313
        counterpartyAgentId: 'agent_peer_keel',
314
        outcome: 'partial',
315
        summary:
316
          'The requester ended after the peer stopped responding before the task was complete.',
317
        criteria: [{ criterion: 'Timeline shared', status: 'partially_met' }],
318
        confidence: 0.7,
319
        completedAt: ago(12),
320
      },
321
    ],
322
    feedbackRequests: [
323
      {
324
        requestId: 'feedback_request_1',
325
        interactionId: 'ix_local_brief',
326
        reviewerAgentId: 'agent_atlas',
327
        subjectAgentId: 'agent_peer_nova',
328
        status: 'submitted',
329
        requestedAt: ago(221),
330
        dueAt: ago(197),
331
      },
332
      {
333
        requestId: 'feedback_request_ops_1',
334
        interactionId: 'ix_shared_ops',
335
        reviewerAgentId: 'agent_atlas',
336
        subjectAgentId: 'agent_peer_keel',
337
        status: 'pending',
338
        requestedAt: ago(12),
339
        dueAt: ahead(24 * 60 - 12),
340
      },
341
      {
342
        requestId: 'feedback_request_ops_2',
343
        interactionId: 'ix_shared_ops',
344
        reviewerAgentId: 'agent_peer_keel',
345
        subjectAgentId: 'agent_atlas',
346
        status: 'pending',
347
        requestedAt: ago(12),
348
        dueAt: ahead(24 * 60 - 12),
349
      },
350
      {
351
        requestId: 'feedback_request_2',
352
        interactionId: 'ix_local_brief',
353
        reviewerAgentId: 'agent_peer_nova',
354
        subjectAgentId: 'agent_atlas',
355
        status: 'submitted',
356
        requestedAt: ago(221),
357
        dueAt: ago(197),
358
      },
359
    ],
360
    interactionFeedback: [
361
      {
362
        feedbackId: 'feedback_1',
363
        interactionId: 'ix_local_brief',
364
        reviewerAgentId: 'agent_atlas',
365
        subjectAgentId: 'agent_peer_nova',
366
        ratings: { outcome_satisfaction: 0.9, communication: 0.8, reliability: 0.9 },
367
        wouldWorkAgain: 'yes',
368
        submittedAt: ago(219),
369
      },
370
    ],
371
    interactionConclusions: [
372
      {
373
        conclusionId: 'conclusion_1',
374
        interactionId: 'ix_local_brief',
375
        outcome: 'success',
376
        consensus: 'bilateral_agreement',
377
        summary: 'Both agents reported successful delivery and acceptance.',
378
        criteria: [{ criterion: 'Brief delivered', status: 'met' }],
379
        averageRatings: { outcome_satisfaction: 0.88, communication: 0.82, reliability: 0.9 },
380
        generatedAt: ago(218),
381
      },
382
      {
383
        conclusionId: 'conclusion_ops_provisional',
384
        interactionId: 'ix_shared_ops',
385
        outcome: 'partial',
386
        consensus: 'unilateral',
387
        lifecycle: 'provisional',
388
        confidence: 0.42,
389
        missingReportAgentIds: ['agent_peer_keel'],
390
        pendingFeedbackAgentIds: ['agent_atlas', 'agent_peer_keel'],
391
        peerReportStatus: 'awaiting',
392
        summary:
393
          'Provisional one-sided outcome: the requester ended after the peer stopped responding before the task was complete.',
394
        criteria: [{ criterion: 'Timeline shared', status: 'partially_met' }],
395
        reportIds: ['report_ops_1'],
396
        averageRatings: {},
397
        generatedAt: ago(11),
398
      },
399
    ],
400
    learningEligibility: [
401
      {
402
        decisionId: 'eligibility_1',
403
        interactionId: 'ix_local_brief',
404
        eligible: true,
405
        sampleWeight: 0.87,
406
        contributionMode: 'local_only',
407
        structuredDataOnly: true,
408
        reasons: ['Bilateral reports provide outcome corroboration'],
409
        decidedAt: ago(218),
410
      },
411
    ],
412
    profileDeltas: [
413
      {
414
        deltaId: 'delta_1',
415
        interactionId: 'ix_local_brief',
416
        agentId: 'agent_atlas',
417
        agentVersion: '1.4.2',
418
        taskCategory: 'research',
419
        sampleWeight: 0.87,
420
        dimensionDeltas: { completion: 0.02, evidence: 0.03, communication: -0.01 },
421
        appliedAt: ago(218),
422
      },
423
    ],
424
    profiles: [
425
      {
426
        agentId: 'agent_atlas',
427
        taskCategory: 'research',
428
        agentVersion: '1.4.2',
429
        sampleSize: 14,
430
        effectiveSampleSize: 10.8,
431
        dimensionSampleSizes: {
432
          completion: 10.8,
433
          acceptance: 8.9,
434
          specification: 10.1,
435
          deadline: 9.4,
436
          communication: 10.8,
437
          evidence: 9.7,
438
          scope: 10.2,
439
          correction: 5.1,
440
          limitations: 4.4,
441
          disputes: 10.8,
442
        },
443
        updatedAt: ago(218),
444
        completion: 0.92,
445
        acceptance: 0.87,
446
        specification: 0.86,
447
        scope: 0.84,
448
        evidence: 0.88,
449
        communication: 0.79,
450
        deadline: 0.9,
451
        correction: 0.82,
452
        limitations: 0.77,
453
        disputes: 0.08,
454
      },
455
      {
456
        agentId: 'agent_harbor',
457
        taskCategory: 'ops',
458
        agentVersion: '2.1.0',
459
        sampleSize: 6,
460
        effectiveSampleSize: 4.1,
461
        dimensionSampleSizes: {
462
          completion: 4.1,
463
          acceptance: 3.2,
464
          specification: 3.8,
465
          deadline: 3.5,
466
          communication: 4.1,
467
          evidence: 3.9,
468
          scope: 3.7,
469
          correction: 1.8,
470
          limitations: 1.2,
471
          disputes: 4.1,
472
        },
473
        updatedAt: ago(3 * 24 * 60),
474
        completion: 0.71,
475
        acceptance: 0.68,
476
        specification: 0.63,
477
        scope: 0.66,
478
        evidence: 0.58,
479
        communication: 0.74,
480
        deadline: 0.62,
481
        correction: 0.69,
482
        limitations: 0.54,
483
        disputes: 0.22,
484
      },
485
    ],
486
    intelligenceSummaries: [
487
      {
488
        agentId: 'agent_atlas',
489
        agentVersion: '1.4.2',
490
        taskCategory: 'research',
491
        score: 0.86,
492
        confidence: {
493
          level: 'high',
494
          value: 0.72,
495
          evidenceCount: 14,
496
          effectiveSampleSize: 10.8,
497
        },
498
        trend: { direction: 'improving', delta: 0.018 },
499
        strengths: [
500
          { dimension: 'completion', score: 0.92 },
501
          { dimension: 'deadline', score: 0.9 },
502
          { dimension: 'evidence', score: 0.88 },
503
        ],
504
        risks: [],
505
        versionStatus: {
506
          currentVersion: '1.4.2',
507
          evidenceVersion: '1.4.2',
508
          status: 'current',
509
        },
510
        source: 'private_verified_history',
511
        updatedAt: ago(218),
512
      },
513
      {
514
        agentId: 'agent_harbor',
515
        agentVersion: '2.1.0',
516
        taskCategory: 'ops',
517
        score: 0.66,
518
        confidence: {
519
          level: 'medium',
520
          value: 0.49,
521
          evidenceCount: 6,
522
          effectiveSampleSize: 4.1,
523
        },
524
        trend: { direction: 'declining', delta: -0.022 },
525
        strengths: [{ dimension: 'communication', score: 0.74 }],
526
        risks: [
527
          {
528
            dimension: 'evidence',
529
            score: 0.58,
530
            reason: 'Claims are not consistently supported by evidence.',
531
          },
532
        ],
533
        versionStatus: {
534
          currentVersion: '2.1.0',
535
          evidenceVersion: '2.1.0',
536
          status: 'current',
537
        },
538
        source: 'private_verified_history',
539
        updatedAt: ago(3 * 24 * 60),
540
      },
541
    ],
542
    runtimes: [
543
      {
544
        agentId: 'agent_atlas',
545
        endpoint: 'https://atlas.example.com/openclasp',
546
        a2aEndpoint: 'https://atlas.example.com/a2a',
547
        status: 'verified',
548
        verifiedAt: ago(40),
549
      },
550
    ],
551
    accessTokens: [],
552
  };
553
}
554
555
export function applyPreviewRequest(
556
  data: DashboardData,
557
  settings: Settings,
558
  path: string,
559
  init?: RequestInit,
560
): { data: DashboardData; settings: Settings; result: unknown } {
561
  const method = (init?.method ?? 'GET').toUpperCase();
562
  const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};
563
564
  if (path === '/v0.1/dashboard' && method === 'GET') return { data, settings, result: data };
565
  if (path === '/v0.1/settings' && method === 'GET') return { data, settings, result: settings };
566
  if (path === '/v0.1/settings' && method === 'PUT') {
567
    const next = {
568
      ...settings,
569
      ...body,
570
      rawConversationsStored: false as const,
571
    } as Settings;
572
    return { data, settings: next, result: next };
573
  }
574
575
  if (path === '/v0.1/provider-connections' && method === 'POST') {
576
    const suffix = crypto.randomUUID();
577
    const projectName = String(body.projectName ?? 'Hosted agents');
578
    const existingProject = data.projects.find(
579
      (project) => String(project.name).toLowerCase() === projectName.toLowerCase(),
580
    );
581
    const project = existingProject ?? {
582
      projectId: `project_${suffix}`,
583
      name: projectName,
584
      createdAt: new Date().toISOString(),
585
    };
586
    const agentId = `agent_${suffix}`;
587
    const createdAt = new Date();
588
    const tokenId = suffix.replaceAll('-', '').slice(0, 16);
589
    const provider = body.provider === 'custom' ? 'custom' : 'botpress';
590
    const agent = {
591
      agentId,
592
      projectId: project.projectId,
593
      name: String(body.agentName ?? 'Botpress agent'),
594
      description: String(body.description ?? ''),
595
      framework: provider === 'botpress' ? 'Botpress' : 'Custom runtime',
596
      agentVersion: '1.0.0',
597
      agentMode: 'persistent_runtime',
598
      transport: 'direct_a2a',
599
      autoPublish: false,
600
      autoAcceptPolicy: 'off',
601
      autoAcceptTaskCategories: [],
602
      capabilities: body.capabilities ?? [],
603
      limitations: body.limitations ?? [],
604
      identityMode: 'owner_managed',
605
      status: 'active',
606
      createdAt: createdAt.toISOString(),
607
      updatedAt: createdAt.toISOString(),
608
      presence: { status: 'offline' },
609
    };
610
    const accessToken = {
611
      tokenId,
612
      token: `oc_at_${tokenId}.preview_agent_access_token_secret_not_for_production`,
613
      agentId,
614
      name: provider === 'botpress' ? 'Botpress' : 'Custom runtime',
615
      scopes: ['mcp:access', 'runtime:connect'],
616
      createdAt: createdAt.toISOString(),
617
      expiresAt: new Date(
618
        createdAt.getTime() + Number(body.expiresInDays ?? 365) * 86_400_000,
619
      ).toISOString(),
620
    };
621
    return {
622
      data: {
623
        ...data,
624
        projects: existingProject ? data.projects : [...data.projects, project],
625
        agents: [...data.agents, agent],
626
        accessTokens: [accessToken, ...data.accessTokens],
627
      },
628
      settings,
629
      result: { agent, project, provider, accessToken },
630
    };
631
  }
632
633
  const automation = path.match(/^\/v0\.1\/agents\/([^/]+)\/automation$/);
634
  if (automation && method === 'PUT') {
635
    const agentId = decodeURIComponent(automation[1] ?? '');
636
    const next = {
637
      ...data,
638
      agents: data.agents.map((agent) =>
639
        agent.agentId === agentId
640
          ? {
641
              ...agent,
642
              autoPublish: Boolean(body.autoPublish),
643
              autoAcceptPolicy: body.autoAcceptPolicy,
644
              autoAcceptTaskCategories: body.autoAcceptTaskCategories,
645
            }
646
          : agent,
647
      ),
648
      publications: body.autoPublish
649
        ? [
650
            ...data.publications.filter((item) => item.agentId !== agentId),
651
            { agentId, published: true, updatedAt: new Date().toISOString() },
652
          ]
653
        : data.publications.filter((item) => item.agentId !== agentId),
654
    };
655
    return { data: next, settings, result: { ok: true } };
656
  }
657
658
  const runtime = path.match(/^\/v0\.1\/agents\/([^/]+)\/runtime$/);
659
  if (runtime && method === 'PUT') {
660
    const agentId = decodeURIComponent(runtime[1] ?? '');
661
    const endpoint = String(body.endpoint ?? '');
662
    const record = {
663
      agentId,
664
      endpoint,
665
      a2aEndpoint: endpoint,
666
      status: 'verified',
667
      verifiedAt: new Date().toISOString(),
668
    };
669
    return {
670
      data: {
671
        ...data,
672
        runtimes: [...data.runtimes.filter((item) => item.agentId !== agentId), record],
673
      },
674
      settings,
675
      result: record,
676
    };
677
  }
678
  const tokenCollection = path.match(/^\/v0\.1\/agents\/([^/]+)\/access-tokens$/);
679
  if (tokenCollection && method === 'POST') {
680
    const agentId = decodeURIComponent(tokenCollection[1] ?? '');
681
    const tokenId = crypto.randomUUID().replaceAll('-', '').slice(0, 16);
682
    const createdAt = new Date();
683
    const expiresInDays = Number(body.expiresInDays ?? 365);
684
    const record = {
685
      tokenId,
686
      agentId,
687
      name: String(body.name ?? 'Hosted provider'),
688
      scopes: ['mcp:access', 'runtime:connect'],
689
      createdAt: createdAt.toISOString(),
690
      expiresAt: new Date(createdAt.getTime() + expiresInDays * 86_400_000).toISOString(),
691
    };
692
    return {
693
      data: { ...data, accessTokens: [record, ...data.accessTokens] },
694
      settings,
695
      result: {
696
        ...record,
697
        token: `oc_at_${tokenId}.preview_agent_access_token_secret_not_for_production`,
698
      },
699
    };
700
  }
701
  const tokenItem = path.match(/^\/v0\.1\/agents\/([^/]+)\/access-tokens\/([^/]+)$/);
702
  if (tokenItem && method === 'DELETE') {
703
    const tokenId = decodeURIComponent(tokenItem[2] ?? '');
704
    return {
705
      data: {
706
        ...data,
707
        accessTokens: data.accessTokens.map((token) =>
708
          token.tokenId === tokenId ? { ...token, revokedAt: new Date().toISOString() } : token,
709
        ),
710
      },
711
      settings,
712
      result: { tokenId, revokedAt: new Date().toISOString() },
713
    };
714
  }
715
  const agentDelete = path.match(/^\/v0\.1\/agents\/([^/]+)$/);
716
  if (agentDelete && method === 'DELETE') {
717
    const agentId = decodeURIComponent(agentDelete[1] ?? '');
718
    return {
719
      data: {
720
        ...data,
721
        agents: data.agents.filter((item) => item.agentId !== agentId),
722
        publications: data.publications.filter((item) => item.agentId !== agentId),
723
        runtimes: data.runtimes.filter((item) => item.agentId !== agentId),
724
        installations: data.installations.filter((item) => item.agentId !== agentId),
725
        accessTokens: data.accessTokens.filter((item) => item.agentId !== agentId),
726
      },
727
      settings,
728
      result: { agentId, deleted: true },
729
    };
730
  }
731
732
  if (runtime && method === 'DELETE') {
733
    const agentId = decodeURIComponent(runtime[1] ?? '');
734
    return {
735
      data: {
736
        ...data,
737
        runtimes: data.runtimes.filter((item) => item.agentId !== agentId),
738
      },
739
      settings,
740
      result: { agentId, status: 'disabled' },
741
    };
742
  }
743
744
  const federated = path.match(/^\/v0\.1\/federated-interactions\/([^/]+)\/respond$/);
745
  if (federated && method === 'POST') {
746
    const interactionId = decodeURIComponent(federated[1] ?? '');
747
    const decision = body.decision === 'accept' ? 'active' : 'rejected';
748
    return {
749
      data: {
750
        ...data,
751
        federatedInteractions: data.federatedInteractions.map((item) =>
752
          item.interactionId === interactionId ? { ...item, status: decision } : item,
753
        ),
754
      },
755
      settings,
756
      result: { ok: true },
757
    };
758
  }
759
760
  const onboarding = path.match(/^\/v0\.1\/onboarding\/([^/]+)\/(approve|reject)$/);
761
  if (onboarding && method === 'POST') {
762
    const requestId = decodeURIComponent(onboarding[1] ?? '');
763
    const decision = onboarding[2] === 'approve' ? 'approved' : 'rejected';
764
    return {
765
      data: {
766
        ...data,
767
        setupRequests: data.setupRequests.map((item) =>
768
          item.requestId === requestId
769
            ? { ...item, status: decision, decidedAt: new Date().toISOString() }
770
            : item,
771
        ),
772
      },
773
      settings,
774
      result: { ok: true },
775
    };
776
  }
777
778
  throw new Error('Preview cannot perform this action');
779
}
780
781
export function isPreviewActive() {
782
  return (
783
    import.meta.env.DEV &&
784
    (sessionStorage.getItem(previewKey) === '1' ||
785
      new URLSearchParams(location.search).get('preview') === '1')
786
  );
787
}
788
789
export function enablePreview() {
790
  sessionStorage.setItem(previewKey, '1');
791
}
792
793
export function disablePreview() {
794
  sessionStorage.removeItem(previewKey);
795
}