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

Viewing files at commit 9a8fdf2387ffCommit detailsView latest

apps/dashboard/src/main.tsx 1318 lines · 42.7 KB · tsx
1
import React, { useCallback, useEffect, useMemo, useState } from 'react';
2
import { createRoot } from 'react-dom/client';
3
import './styles.css';
4
5
declare const __AUTH0_DOMAIN__: string;
6
declare const __AUTH0_CLIENT_ID__: string;
7
declare const __AUTH0_AUDIENCE__: string;
8
9
type Auth0User = { sub: string; name?: string; email?: string; picture?: string };
10
type AuthSession = { user: Auth0User };
11
type AuthTransaction = { state: string; nonce: string; verifier: string };
12
type Theme = 'dark' | 'light';
13
14
const authTransactionKey = 'openclasp.auth0.transaction';
15
const themeKey = 'openclasp.theme.v1';
16
17
type DashboardData = {
18
  agents: Record<string, any>[];
19
  projects: Record<string, any>[];
20
  installations: Record<string, any>[];
21
  setupRequests: Record<string, any>[];
22
  publications: Record<string, any>[];
23
  interactions: Record<string, any>[];
24
  federatedInteractions: Record<string, any>[];
25
  events: Record<string, any>[];
26
  conflicts: Record<string, any>[];
27
  receipts: Record<string, any>[];
28
  profiles: Record<string, any>[];
29
};
30
31
type Settings = {
32
  displayName: string;
33
  contributionEnabled: boolean;
34
  retentionDays: number;
35
  evidenceSharing: 'never' | 'ask' | 'contract_only';
36
  rawConversationsStored: false;
37
};
38
39
const emptyData: DashboardData = {
40
  agents: [],
41
  projects: [],
42
  installations: [],
43
  setupRequests: [],
44
  publications: [],
45
  interactions: [],
46
  federatedInteractions: [],
47
  events: [],
48
  conflicts: [],
49
  receipts: [],
50
  profiles: [],
51
};
52
const defaultSettings: Settings = {
53
  displayName: '',
54
  contributionEnabled: false,
55
  retentionDays: 30,
56
  evidenceSharing: 'ask',
57
  rawConversationsStored: false,
58
};
59
const pages = ['dashboard', 'history', 'agents', 'insights', 'connect', 'settings'] as const;
60
type Page = (typeof pages)[number];
61
62
function base64Url(bytes: Uint8Array) {
63
  let binary = '';
64
  for (const byte of bytes) binary += String.fromCharCode(byte);
65
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
66
}
67
68
function randomValue(size = 32) {
69
  return base64Url(crypto.getRandomValues(new Uint8Array(size)));
70
}
71
72
async function beginAuth(provider: 'google' | 'github') {
73
  const verifier = randomValue(48);
74
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
75
  const transaction: AuthTransaction = { state: randomValue(), nonce: randomValue(), verifier };
76
  sessionStorage.setItem(authTransactionKey, JSON.stringify(transaction));
77
  const parameters = new URLSearchParams({
78
    client_id: __AUTH0_CLIENT_ID__,
79
    redirect_uri: `${location.origin}/sso-callback`,
80
    response_type: 'code',
81
    scope: 'openid profile email',
82
    audience: __AUTH0_AUDIENCE__,
83
    state: transaction.state,
84
    nonce: transaction.nonce,
85
    code_challenge: base64Url(new Uint8Array(digest)),
86
    code_challenge_method: 'S256',
87
    connection: provider === 'google' ? 'google-oauth2' : 'github',
88
  });
89
  location.assign(`https://${__AUTH0_DOMAIN__}/authorize?${parameters}`);
90
}
91
92
async function signOut() {
93
  await fetch('/api/session', { method: 'DELETE', credentials: 'same-origin' });
94
  const parameters = new URLSearchParams({
95
    client_id: __AUTH0_CLIENT_ID__,
96
    returnTo: `${location.origin}/login`,
97
  });
98
  location.assign(`https://${__AUTH0_DOMAIN__}/v2/logout?${parameters}`);
99
}
100
101
async function api(path: string, init?: RequestInit) {
102
  const headers = new Headers(init?.headers);
103
  if (init?.body && !headers.has('content-type')) headers.set('content-type', 'application/json');
104
  return fetch(path, {
105
    ...init,
106
    credentials: 'same-origin',
107
    headers,
108
  }).then(async (response) => {
109
    if (!response.ok)
110
      throw new Error((await response.text()) || `Request failed: ${response.status}`);
111
    return response.json();
112
  });
113
}
114
115
function route(): Page {
116
  const value = location.pathname.slice(1) || 'dashboard';
117
  return pages.includes(value as Page) ? (value as Page) : 'dashboard';
118
}
119
120
function initialTheme(): Theme {
121
  const saved = localStorage.getItem(themeKey);
122
  if (saved === 'dark' || saved === 'light') return saved;
123
  return matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
124
}
125
126
function App() {
127
  const [session, setSession] = useState<AuthSession | null>();
128
  const [theme, setTheme] = useState<Theme>(initialTheme);
129
  const [page, setPage] = useState<Page>(route());
130
  const [data, setData] = useState<DashboardData>(emptyData);
131
  const [settings, setSettings] = useState<Settings>(defaultSettings);
132
  const [loading, setLoading] = useState(true);
133
  const [error, setError] = useState('');
134
  const refreshDashboard = useCallback(async () => {
135
    setData((await api('/v0.1/dashboard')) as DashboardData);
136
  }, []);
137
138
  useEffect(() => {
139
    fetch('/api/session', { credentials: 'same-origin' })
140
      .then(async (response) => {
141
        if (!response.ok) return null;
142
        return (await response.json()) as AuthSession;
143
      })
144
      .then(setSession)
145
      .catch(() => setSession(null));
146
  }, []);
147
148
  useEffect(() => {
149
    document.documentElement.dataset.theme = theme;
150
    localStorage.setItem(themeKey, theme);
151
  }, [theme]);
152
153
  useEffect(() => {
154
    const onPopState = () => setPage(route());
155
    addEventListener('popstate', onPopState);
156
    return () => removeEventListener('popstate', onPopState);
157
  }, []);
158
159
  useEffect(() => {
160
    if (session === undefined) return;
161
    if (!session && location.pathname !== '/login') history.replaceState({}, '', '/login');
162
    if (!session) return;
163
    if (location.pathname === '/login') history.replaceState({}, '', '/dashboard');
164
    setPage(route());
165
    Promise.all([api('/v0.1/dashboard'), api('/v0.1/settings')])
166
      .then(([dashboard, accountSettings]) => {
167
        setData(dashboard as DashboardData);
168
        setSettings(accountSettings as Settings);
169
      })
170
      .catch((reason: unknown) =>
171
        setError(reason instanceof Error ? reason.message : 'Load failed'),
172
      )
173
      .finally(() => setLoading(false));
174
  }, [session]);
175
176
  useEffect(() => {
177
    if (!session) return;
178
    const refresh = () => {
179
      if (document.visibilityState === 'visible') void refreshDashboard().catch(() => undefined);
180
    };
181
    const timer = window.setInterval(refresh, 10_000);
182
    document.addEventListener('visibilitychange', refresh);
183
    return () => {
184
      window.clearInterval(timer);
185
      document.removeEventListener('visibilitychange', refresh);
186
    };
187
  }, [session, refreshDashboard]);
188
189
  const navigate = (next: Page) => {
190
    history.pushState({}, '', `/${next}`);
191
    setPage(next);
192
  };
193
194
  if (session === undefined) return <Loading />;
195
  if (!session) return <Login />;
196
197
  return (
198
    <div className="appShell">
199
      <aside>
200
        <div className="brand">
201
          <div className="mark">OC</div>
202
          <div>
203
            <strong>OpenClasp</strong>
204
            <small>ASSURANCE NETWORK</small>
205
          </div>
206
        </div>
207
        <nav>
208
          <Nav page="dashboard" active={page} onClick={navigate} label="Overview" glyph="⌂" />
209
          <Nav page="history" active={page} onClick={navigate} label="History" glyph="≡" />
210
          <Nav page="agents" active={page} onClick={navigate} label="Agents" glyph="◇" />
211
          <Nav page="insights" active={page} onClick={navigate} label="Insights" glyph="⌁" />
212
          <Nav page="connect" active={page} onClick={navigate} label="Connect" glyph="+" />
213
          <Nav page="settings" active={page} onClick={navigate} label="Settings" glyph="⚙" />
214
        </nav>
215
        <button
216
          className="themeSwitch"
217
          onClick={() => setTheme((current) => (current === 'dark' ? 'light' : 'dark'))}
218
          aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
219
        >
220
          <span>{theme === 'dark' ? '☼' : '◐'}</span>
221
          {theme === 'dark' ? 'Light theme' : 'Dark theme'}
222
        </button>
223
        <div className="privacyStamp">
224
          <span className="liveDot" />
225
          <div>
226
            <strong>Structured-only</strong>
227
            <small>Raw conversations stay local</small>
228
          </div>
229
        </div>
230
        <button className="account" onClick={() => void signOut()}>
231
          <span>{initials(session.user.name || session.user.email || 'OC')}</span>
232
          <div>
233
            <strong>{session.user.name || 'OpenClasp user'}</strong>
234
            <small>{session.user.email || 'Sign out'}</small>
235
          </div>
236
          <b>↗</b>
237
        </button>
238
      </aside>
239
      <main>
240
        {error && <div className="errorBar">{error}</div>}
241
        {loading ? (
242
          <Loading compact />
243
        ) : (
244
          <PageContent
245
            page={page}
246
            data={data}
247
            settings={settings}
248
            setSettings={setSettings}
249
            navigate={navigate}
250
            refreshDashboard={refreshDashboard}
251
          />
252
        )}
253
      </main>
254
    </div>
255
  );
256
}
257
258
function Login() {
259
  const [error, setError] = useState('');
260
  const continueWith = async (provider: 'google' | 'github') => {
261
    setError('');
262
    try {
263
      await beginAuth(provider);
264
    } catch {
265
      setError(`${provider === 'google' ? 'Google' : 'GitHub'} sign-in is not configured yet.`);
266
    }
267
  };
268
  return (
269
    <div className="loginPage">
270
      <section className="loginPitch">
271
        <div className="brand">
272
          <div className="mark">OC</div>
273
          <strong>OpenClasp</strong>
274
        </div>
275
        <div>
276
          <p className="eyebrow">AGENT-TO-AGENT ASSURANCE</p>
277
          <h1>Know who your agent is dealing with.</h1>
278
          <p>
279
            Verified identities, signed outcomes, private warnings, and contextual
280
            reliability—without collecting raw conversations.
281
          </p>
282
        </div>
283
        <div className="loginProof">
284
          <span>01</span> User-owned history<span>02</span> No universal trust score<span>03</span>{' '}
285
          Explicit network consent
286
        </div>
287
      </section>
288
      <section className="loginCard">
289
        <div>
290
          <p className="eyebrow">SECURE ACCESS</p>
291
          <h2>Sign in to OpenClasp</h2>
292
          <p>
293
            Manage connected agents, review signed history, and control what contributes to the
294
            network.
295
          </p>
296
        </div>
297
        <div className="socialButtons">
298
          <button onClick={() => void continueWith('google')}>
299
            <span className="google">G</span> Continue with Google
300
          </button>
301
          <button onClick={() => void continueWith('github')}>
302
            <span>◉</span> Continue with GitHub
303
          </button>
304
        </div>
305
        {error && <div className="loginError">{error}</div>}
306
        <small>
307
          Google and GitHub handle authentication. OpenClasp never receives your password.
308
        </small>
309
      </section>
310
    </div>
311
  );
312
}
313
314
let callbackStarted = false;
315
function AuthCallback() {
316
  const [error, setError] = useState('');
317
  useEffect(() => {
318
    if (callbackStarted) return;
319
    callbackStarted = true;
320
    const finish = async () => {
321
      const query = new URLSearchParams(location.search);
322
      const oauthError = query.get('error_description') ?? query.get('error');
323
      if (oauthError) throw new Error(oauthError);
324
      const code = query.get('code');
325
      const returnedState = query.get('state');
326
      const rawTransaction = sessionStorage.getItem(authTransactionKey);
327
      if (!code || !returnedState || !rawTransaction) throw new Error('Missing OAuth transaction');
328
      const transaction = JSON.parse(rawTransaction) as AuthTransaction;
329
      sessionStorage.removeItem(authTransactionKey);
330
      if (returnedState !== transaction.state) throw new Error('OAuth state mismatch');
331
      const response = await fetch('/api/session', {
332
        method: 'POST',
333
        credentials: 'same-origin',
334
        headers: { 'content-type': 'application/json' },
335
        body: JSON.stringify({
336
          code,
337
          codeVerifier: transaction.verifier,
338
        }),
339
      });
340
      if (!response.ok) throw new Error('Auth0 token exchange failed');
341
      location.replace('/dashboard');
342
    };
343
    void finish().catch((reason: unknown) =>
344
      setError(reason instanceof Error ? reason.message : 'Authentication failed'),
345
    );
346
  }, []);
347
  if (error)
348
    return (
349
      <div className="loading">
350
        <span className="mark">OC</span>
351
        <p>{error}</p>
352
        <a href="/login">Return to login</a>
353
      </div>
354
    );
355
  return <Loading />;
356
}
357
358
function PageContent({
359
  page,
360
  data,
361
  settings,
362
  setSettings,
363
  navigate,
364
  refreshDashboard,
365
}: {
366
  page: Page;
367
  data: DashboardData;
368
  settings: Settings;
369
  setSettings: React.Dispatch<React.SetStateAction<Settings>>;
370
  navigate: (page: Page) => void;
371
  refreshDashboard: () => Promise<void>;
372
}) {
373
  if (page === 'history') return <History data={data} />;
374
  if (page === 'agents')
375
    return <Agents data={data} navigate={navigate} refreshDashboard={refreshDashboard} />;
376
  if (page === 'insights') return <Insights data={data} />;
377
  if (page === 'connect') return <Connect data={data} refreshDashboard={refreshDashboard} />;
378
  if (page === 'settings') return <SettingsPage settings={settings} setSettings={setSettings} />;
379
  return <Overview data={data} navigate={navigate} refreshDashboard={refreshDashboard} />;
380
}
381
382
function Overview({
383
  data,
384
  navigate,
385
  refreshDashboard,
386
}: {
387
  data: DashboardData;
388
  navigate: (page: Page) => void;
389
  refreshDashboard: () => Promise<void>;
390
}) {
391
  const completed = data.receipts.filter((item) => item.outcome === 'success').length;
392
  const warnings = data.events.filter((item) =>
393
    ['policy_warning', 'policy_violation', 'objection'].includes(String(item.eventType)),
394
  ).length;
395
  const publishedIds = new Set(
396
    data.publications
397
      .filter((publication) => publication.published)
398
      .map((publication) => String(publication.agentId)),
399
  );
400
  const readyAgents = data.agents.filter(
401
    (agent) => agent.a2aEndpoint && publishedIds.has(String(agent.agentId)),
402
  ).length;
403
  const pendingInvitations = data.federatedInteractions.filter(
404
    (interaction) => interaction.status === 'pending',
405
  ).length;
406
  return (
407
    <>
408
      <PageHead
409
        eyebrow="NETWORK OVERVIEW"
410
        title="Assurance, at a glance."
411
        action="Connect agent"
412
        onAction={() => navigate('connect')}
413
      />
414
      <section
415
        className={`readiness ${readyAgents === data.agents.length && readyAgents ? 'ready' : ''}`}
416
      >
417
        <div>
418
          <span className="statusOrb">{readyAgents ? '✓' : '!'}</span>
419
          <div>
420
            <strong>
421
              {readyAgents === data.agents.length && readyAgents
422
                ? 'Your agent network is ready'
423
                : `${readyAgents} of ${data.agents.length} agents can receive A2A work`}
424
            </strong>
425
            <small>
426
              Safe matching requests activate automatically. Everything else waits for approval.
427
            </small>
428
          </div>
429
        </div>
430
        <button className="secondary" onClick={() => navigate('agents')}>
431
          Manage automation
432
        </button>
433
      </section>
434
      <section className="metrics">
435
        <Metric label="Connected agents" value={data.agents.length} note="bound identities" />
436
        <Metric
437
          label="Interactions"
438
          value={data.interactions.length + data.federatedInteractions.length}
439
          note="local and shared"
440
        />
441
        <Metric label="Successful outcomes" value={completed} note="receipt-backed" />
442
        <Metric
443
          label="Needs review"
444
          value={warnings + pendingInvitations}
445
          note="warnings or approvals"
446
          warn={warnings + pendingInvitations > 0}
447
        />
448
      </section>
449
      <Invitations data={data} refreshDashboard={refreshDashboard} />
450
      <section className="contentGrid">
451
        <Panel title="Recent activity" subtitle="Structured events and signed outcomes">
452
          <Timeline events={data.events.slice(-6).reverse()} />
453
          <TextButton onClick={() => navigate('history')}>View complete history →</TextButton>
454
        </Panel>
455
        <Panel
456
          title="Reliability context"
457
          subtitle="Task-specific profiles, never a universal score"
458
        >
459
          {data.profiles.length ? (
460
            data.profiles
461
              .slice(0, 4)
462
              .map((profile) => (
463
                <Profile key={`${profile.agentId}-${profile.taskCategory}`} profile={profile} />
464
              ))
465
          ) : (
466
            <Empty
467
              title="No reliability profile yet"
468
              text="Profiles appear after signed receipts and eligible bilateral feedback."
469
            />
470
          )}
471
        </Panel>
472
      </section>
473
    </>
474
  );
475
}
476
477
function History({ data }: { data: DashboardData }) {
478
  const records = useMemo(
479
    () =>
480
      [
481
        ...data.interactions.map((value) => ({ ...value, _kind: 'interaction' })),
482
        ...data.federatedInteractions.map((value) => ({
483
          ...value,
484
          _kind: 'federated interaction',
485
        })),
486
        ...data.events.map((value) => ({ ...value, _kind: 'event' })),
487
        ...data.receipts.map((value) => ({ ...value, _kind: 'receipt' })),
488
        ...data.conflicts.map((value) => ({ ...value, _kind: 'dispute' })),
489
      ].sort((a, b) => Date.parse(timestamp(b)) - Date.parse(timestamp(a))),
490
    [data],
491
  );
492
  return (
493
    <>
494
      <PageHead eyebrow="AUDIT HISTORY" title="What happened, and what proves it." />
495
      <Panel
496
        title="Account history"
497
        subtitle="Only structured metadata, signatures, hashes, and permitted evidence are hosted"
498
      >
499
        {records.length ? (
500
          records.map((item, index) => (
501
            <HistoryRow
502
              key={String(
503
                (item as Record<string, any>).eventId ??
504
                  (item as Record<string, any>).receiptId ??
505
                  (item as Record<string, any>).interactionId ??
506
                  index,
507
              )}
508
              item={item}
509
            />
510
          ))
511
        ) : (
512
          <Empty
513
            title="No interactions recorded"
514
            text="Connect an agent and start an assured interaction. Raw message bodies will not appear here."
515
          />
516
        )}
517
      </Panel>
518
    </>
519
  );
520
}
521
522
function Agents({
523
  data,
524
  navigate,
525
  refreshDashboard,
526
}: {
527
  data: DashboardData;
528
  navigate: (page: Page) => void;
529
  refreshDashboard: () => Promise<void>;
530
}) {
531
  const [working, setWorking] = useState('');
532
  const [error, setError] = useState('');
533
  const saveAutomation = async (
534
    agentId: string,
535
    value: {
536
      a2aEndpoint: string;
537
      autoPublish: boolean;
538
      autoAcceptPolicy: 'off' | 'safe_matching';
539
      autoAcceptTaskCategories: string[];
540
    },
541
  ) => {
542
    setWorking(agentId);
543
    setError('');
544
    try {
545
      await api(`/v0.1/agents/${encodeURIComponent(agentId)}/automation`, {
546
        method: 'PUT',
547
        body: JSON.stringify(value),
548
      });
549
      await refreshDashboard();
550
    } catch (reason) {
551
      setError(reason instanceof Error ? reason.message : 'Directory update failed');
552
    } finally {
553
      setWorking('');
554
    }
555
  };
556
  return (
557
    <>
558
      <PageHead
559
        eyebrow="IDENTITY REGISTRY"
560
        title="Your connected agents."
561
        action="Connect agent"
562
        onAction={() => navigate('connect')}
563
      />
564
      <div className="notice">
565
        <strong>One approval, then automatic.</strong> A public A2A endpoint makes the agent
566
        discoverable. Safe matching tasks can be accepted automatically; sensitive or mismatched
567
        requests still require review.
568
      </div>
569
      {error && <div className="errorBar">{error}</div>}
570
      <section className="agentGrid">
571
        {data.agents.length ? (
572
          data.agents.map((agent) => (
573
            <AgentCard
574
              key={agent.agentId}
575
              agent={agent}
576
              projectName={
577
                data.projects.find((project) => project.projectId === agent.projectId)?.name
578
              }
579
              published={data.publications.some(
580
                (publication) => publication.agentId === agent.agentId && publication.published,
581
              )}
582
              working={working === agent.agentId}
583
              onSave={(value) => saveAutomation(agent.agentId, value)}
584
            />
585
          ))
586
        ) : (
587
          <Empty
588
            title="No agents connected"
589
            text="Install the remote MCP endpoint in an agent, sign in, then create and register its identity."
590
            action="Open connection guide"
591
            onAction={() => navigate('connect')}
592
          />
593
        )}
594
      </section>
595
    </>
596
  );
597
}
598
599
function Invitations({
600
  data,
601
  refreshDashboard,
602
}: {
603
  data: DashboardData;
604
  refreshDashboard: () => Promise<void>;
605
}) {
606
  const [working, setWorking] = useState('');
607
  const [error, setError] = useState('');
608
  const ownedAgentIds = useMemo(
609
    () => new Set(data.agents.map((agent) => String(agent.agentId))),
610
    [data.agents],
611
  );
612
  const incoming = data.federatedInteractions.filter(
613
    (interaction) =>
614
      interaction.status === 'pending' && ownedAgentIds.has(String(interaction.responderAgentId)),
615
  );
616
  const respond = async (interactionId: string, agentId: string, decision: 'accept' | 'reject') => {
617
    setWorking(interactionId);
618
    setError('');
619
    try {
620
      await api(`/v0.1/federated-interactions/${encodeURIComponent(interactionId)}/respond`, {
621
        method: 'POST',
622
        body: JSON.stringify({ agentId, decision }),
623
      });
624
      await refreshDashboard();
625
    } catch (reason) {
626
      setError(reason instanceof Error ? reason.message : 'Could not respond to invitation');
627
    } finally {
628
      setWorking('');
629
    }
630
  };
631
  if (!incoming.length && !data.federatedInteractions.length) return null;
632
  return (
633
    <Panel
634
      title={incoming.length ? `Agent invitations (${incoming.length})` : 'Shared interactions'}
635
      subtitle="Both accounts see the same immutable contract and acceptance state"
636
    >
637
      {error ? <div className="errorBar">{error}</div> : null}
638
      {(incoming.length ? incoming : data.federatedInteractions.slice(0, 5)).map((interaction) => (
639
        <article className="setupRequest" key={interaction.interactionId}>
640
          <div>
641
            <strong>{interaction.contract?.purpose ?? interaction.interactionId}</strong>
642
            <small>
643
              {interaction.initiatorAgentId} → {interaction.responderAgentId} · {interaction.status}
644
            </small>
645
            <small>Contract: {String(interaction.termsHash).slice(0, 16)}…</small>
646
            {interaction.status === 'active' &&
647
            interaction.acceptances?.[interaction.responderAgentId]?.method ===
648
              'policy_auto_accept' ? (
649
              <small className="autoAccepted">✓ Auto-approved by the responder's safe policy</small>
650
            ) : null}
651
          </div>
652
          {interaction.status === 'pending' &&
653
          ownedAgentIds.has(String(interaction.responderAgentId)) ? (
654
            <div className="decisionButtons">
655
              <button
656
                className="secondary"
657
                disabled={working === interaction.interactionId}
658
                onClick={() =>
659
                  void respond(interaction.interactionId, interaction.responderAgentId, 'reject')
660
                }
661
              >
662
                Reject
663
              </button>
664
              <button
665
                className="primary"
666
                disabled={working === interaction.interactionId}
667
                onClick={() =>
668
                  void respond(interaction.interactionId, interaction.responderAgentId, 'accept')
669
                }
670
              >
671
                {working === interaction.interactionId ? 'Working…' : 'Accept contract'}
672
              </button>
673
            </div>
674
          ) : null}
675
        </article>
676
      ))}
677
    </Panel>
678
  );
679
}
680
681
function Insights({ data }: { data: DashboardData }) {
682
  return (
683
    <>
684
      <PageHead eyebrow="BEHAVIOURAL CONTEXT" title="Evidence, not reputation theatre." />
685
      <div className="notice">
686
        <strong>Context matters.</strong> OpenClasp profiles an agent by task category and version.
687
        It does not produce a single universal trust score.
688
      </div>
689
      <section className="agentGrid">
690
        {data.profiles.length ? (
691
          data.profiles.map((profile) => (
692
            <Panel
693
              key={`${profile.agentId}-${profile.taskCategory}`}
694
              title={profile.agentId}
695
              subtitle={`${profile.taskCategory} · v${profile.agentVersion}`}
696
            >
697
              <Profile profile={profile} expanded />
698
            </Panel>
699
          ))
700
        ) : (
701
          <Empty
702
            title="Not enough verified evidence"
703
            text="Insights grow only from signed outcomes, eligible feedback, corrections, disputes, and version-aware history."
704
          />
705
        )}
706
      </section>
707
    </>
708
  );
709
}
710
711
function Connect({
712
  data,
713
  refreshDashboard,
714
}: {
715
  data: DashboardData;
716
  refreshDashboard: () => Promise<void>;
717
}) {
718
  const endpoint = 'https://openclasp.vercel.app/mcp';
719
  const [copied, setCopied] = useState(false);
720
  const [working, setWorking] = useState('');
721
  const [decisionError, setDecisionError] = useState('');
722
  const pending = data.setupRequests.filter((request) => request.status === 'pending');
723
  useEffect(() => {
724
    const poll = () => void refreshDashboard().catch(() => undefined);
725
    poll();
726
    const timer = window.setInterval(poll, 5000);
727
    return () => window.clearInterval(timer);
728
  }, [refreshDashboard]);
729
  const decide = async (requestId: string, decision: 'approve' | 'reject') => {
730
    setWorking(requestId);
731
    setDecisionError('');
732
    try {
733
      await api(`/v0.1/onboarding/${encodeURIComponent(requestId)}/${decision}`, {
734
        method: 'POST',
735
      });
736
      await refreshDashboard();
737
    } catch (reason) {
738
      setDecisionError(reason instanceof Error ? reason.message : 'Could not update setup request');
739
    } finally {
740
      setWorking('');
741
    }
742
  };
743
  return (
744
    <>
745
      <PageHead eyebrow="AGENT CONNECTION" title="Add OpenClasp to an agent." />
746
      {pending.length > 0 && (
747
        <section className="setupRequests">
748
          <div>
749
            <p className="eyebrow">CONFIRMATION REQUIRED</p>
750
            <h2>Approve agent setup</h2>
751
            <p>
752
              An agent proposed this identity. Confirm it before OpenClasp binds the installation.
753
            </p>
754
          </div>
755
          {pending.map((request) => (
756
            <article className="setupRequest" key={request.requestId}>
757
              <div>
758
                <strong>{request.agentName ?? 'Switch installation'}</strong>
759
                <small>
760
                  {request.projectName ?? request.existingAgentId} · {request.framework}
761
                </small>
762
                {!!request.capabilities?.length && (
763
                  <div className="tags">
764
                    {request.capabilities.slice(0, 5).map((capability: string) => (
765
                      <span key={capability}>{capability}</span>
766
                    ))}
767
                  </div>
768
                )}
769
                {!!request.limitations?.length && (
770
                  <small>Limitations: {request.limitations.join(' · ')}</small>
771
                )}
772
                <div className="automationPreview">
773
                  <span>{request.autoPublish ? 'Public after approval' : 'Private'}</span>
774
                  <span>
775
                    {request.autoAcceptPolicy === 'safe_matching'
776
                      ? 'Auto-accept safe matches'
777
                      : 'Review every request'}
778
                  </span>
779
                </div>
780
              </div>
781
              <div className="decisionButtons">
782
                <button
783
                  className="secondary"
784
                  disabled={working === request.requestId}
785
                  onClick={() => void decide(request.requestId, 'reject')}
786
                >
787
                  Reject
788
                </button>
789
                <button
790
                  className="primary"
791
                  disabled={working === request.requestId}
792
                  onClick={() => void decide(request.requestId, 'approve')}
793
                >
794
                  {working === request.requestId ? 'Working…' : 'Approve & automate'}
795
                </button>
796
              </div>
797
            </article>
798
          ))}
799
          {decisionError && <div className="loginError">{decisionError}</div>}
800
        </section>
801
      )}
802
      <section className="connectLayout">
803
        <Panel title="Connect once" subtitle="OpenClasp handles the routine steps afterward">
804
          <div className="endpoint">
805
            <code>{endpoint}</code>
806
            <button
807
              onClick={() => {
808
                void navigator.clipboard.writeText(endpoint);
809
                setCopied(true);
810
              }}
811
            >
812
              {copied ? 'Copied' : 'Copy'}
813
            </button>
814
          </div>
815
          <ol>
816
            <li>Add this MCP URL and complete the OAuth sign-in.</li>
817
            <li>
818
              Tell the agent: <code>Set yourself up on OpenClasp</code>.
819
            </li>
820
            <li>
821
              Approve its identity and automation policy here once. That is the last routine manual
822
              step.
823
            </li>
824
          </ol>
825
        </Panel>
826
        <Panel
827
          title="What becomes automatic"
828
          subtitle="Safe defaults with deterministic approval boundaries"
829
        >
830
          <ul className="checkList">
831
            <li>Agent Card publication and discovery</li>
832
            <li>Contract defaults inferred from the task</li>
833
            <li>Safe matching invitations accepted immediately</li>
834
            <li>Ready-to-send A2A endpoint, headers, and metadata</li>
835
            <li>Risky requests routed to human review</li>
836
          </ul>
837
        </Panel>
838
      </section>
839
    </>
840
  );
841
}
842
843
function SettingsPage({
844
  settings,
845
  setSettings,
846
}: {
847
  settings: Settings;
848
  setSettings: React.Dispatch<React.SetStateAction<Settings>>;
849
}) {
850
  const [saving, setSaving] = useState(false);
851
  const [saved, setSaved] = useState(false);
852
  const save = useCallback(async () => {
853
    setSaving(true);
854
    setSaved(false);
855
    const updated = (await api('/v0.1/settings', {
856
      method: 'PUT',
857
      body: JSON.stringify(settings),
858
    })) as Settings;
859
    setSettings(updated);
860
    setSaving(false);
861
    setSaved(true);
862
  }, [settings, setSettings]);
863
  return (
864
    <>
865
      <PageHead eyebrow="ACCOUNT CONTROLS" title="Privacy and network settings." />
866
      <section className="settingsCard">
867
        <Setting label="Display name" description="Shown only inside your OpenClasp account.">
868
          <input
869
            value={settings.displayName}
870
            onChange={(event) =>
871
              setSettings((value) => ({ ...value, displayName: event.target.value }))
872
            }
873
            placeholder="Team or operator name"
874
          />
875
        </Setting>
876
        <Setting
877
          label="Network contribution"
878
          description="Allow eligible structured aggregates to improve contextual intelligence. Raw conversations are never included."
879
        >
880
          <Toggle
881
            checked={settings.contributionEnabled}
882
            onChange={(checked) =>
883
              setSettings((value) => ({ ...value, contributionEnabled: checked }))
884
            }
885
          />
886
        </Setting>
887
        <Setting
888
          label="Evidence sharing"
889
          description="Controls when permitted evidence references may be shared with interaction participants."
890
        >
891
          <select
892
            value={settings.evidenceSharing}
893
            onChange={(event) =>
894
              setSettings((value) => ({
895
                ...value,
896
                evidenceSharing: event.target.value as Settings['evidenceSharing'],
897
              }))
898
            }
899
          >
900
            <option value="never">Never</option>
901
            <option value="ask">Ask every time</option>
902
            <option value="contract_only">When contract permits</option>
903
          </select>
904
        </Setting>
905
        <Setting
906
          label="Structured record retention"
907
          description="Retention for hosted account records. Signed protocol records may require separate revocation markers."
908
        >
909
          <select
910
            value={settings.retentionDays}
911
            onChange={(event) =>
912
              setSettings((value) => ({ ...value, retentionDays: Number(event.target.value) }))
913
            }
914
          >
915
            <option value={7}>7 days</option>
916
            <option value={30}>30 days</option>
917
            <option value={90}>90 days</option>
918
            <option value={365}>1 year</option>
919
            <option value={0}>No automatic deletion</option>
920
          </select>
921
        </Setting>
922
        <Setting
923
          label="Raw conversations"
924
          description="Message bodies remain local and user-owned. This cannot be enabled on the hosted service."
925
        >
926
          <span className="locked">ALWAYS OFF</span>
927
        </Setting>
928
        <div className="saveRow">
929
          <button className="primary" onClick={() => void save()} disabled={saving}>
930
            {saving ? 'Saving…' : 'Save settings'}
931
          </button>
932
          {saved && <span>Saved</span>}
933
        </div>
934
      </section>
935
    </>
936
  );
937
}
938
939
function PageHead({
940
  eyebrow,
941
  title,
942
  action,
943
  onAction,
944
}: {
945
  eyebrow: string;
946
  title: string;
947
  action?: string;
948
  onAction?: () => void;
949
}) {
950
  return (
951
    <header className="pageHead">
952
      <div>
953
        <p className="eyebrow">{eyebrow}</p>
954
        <h1>{title}</h1>
955
      </div>
956
      {action && (
957
        <button className="primary" onClick={onAction}>
958
          {action}
959
        </button>
960
      )}
961
    </header>
962
  );
963
}
964
function Nav({
965
  page,
966
  active,
967
  onClick,
968
  label,
969
  glyph,
970
}: {
971
  page: Page;
972
  active: Page;
973
  onClick: (page: Page) => void;
974
  label: string;
975
  glyph: string;
976
}) {
977
  return (
978
    <button className={active === page ? 'active' : ''} onClick={() => onClick(page)}>
979
      <span>{glyph}</span>
980
      {label}
981
    </button>
982
  );
983
}
984
function Metric({
985
  label,
986
  value,
987
  note,
988
  warn,
989
}: {
990
  label: string;
991
  value: number;
992
  note: string;
993
  warn?: boolean;
994
}) {
995
  return (
996
    <article className={warn ? 'metric warn' : 'metric'}>
997
      <span>{label}</span>
998
      <strong>{String(value).padStart(2, '0')}</strong>
999
      <small>{note}</small>
1000
    </article>
1001
  );
1002
}
1003
function Panel({
1004
  title,
1005
  subtitle,
1006
  children,
1007
}: React.PropsWithChildren<{ title: string; subtitle: string }>) {
1008
  return (
1009
    <section className="panel">
1010
      <div className="panelHead">
1011
        <div>
1012
          <h2>{title}</h2>
1013
          <p>{subtitle}</p>
1014
        </div>
1015
      </div>
1016
      {children}
1017
    </section>
1018
  );
1019
}
1020
function Timeline({ events }: { events: Record<string, any>[] }) {
1021
  return events.length ? (
1022
    <div className="timeline">
1023
      {events.map((event) => (
1024
        <HistoryRow key={event.eventId} item={{ ...event, _kind: 'event' }} />
1025
      ))}
1026
    </div>
1027
  ) : (
1028
    <Empty
1029
      title="Nothing recorded yet"
1030
      text="Activity appears after your connected agents submit signed structured events."
1031
    />
1032
  );
1033
}
1034
function HistoryRow({ item }: { item: Record<string, any> }) {
1035
  const kind = String(item.eventType ?? item._kind ?? 'record').replaceAll('_', ' ');
1036
  const id = String(item.agentId ?? item.interactionId ?? item.receiptId ?? 'OpenClasp');
1037
  return (
1038
    <article className="historyRow">
1039
      <span className={`eventDot ${item.eventType ?? item._kind}`} />
1040
      <div>
1041
        <strong>{kind}</strong>
1042
        <small>
1043
          {id} · {new Date(timestamp(item)).toLocaleString()}
1044
        </small>
1045
      </div>
1046
      <b>{item.visibility ?? item.outcome ?? item.status ?? 'SIGNED'}</b>
1047
    </article>
1048
  );
1049
}
1050
function AgentCard({
1051
  agent,
1052
  projectName,
1053
  published,
1054
  working,
1055
  onSave,
1056
}: {
1057
  agent: Record<string, any>;
1058
  projectName?: string;
1059
  published: boolean;
1060
  working: boolean;
1061
  onSave: (value: {
1062
    a2aEndpoint: string;
1063
    autoPublish: boolean;
1064
    autoAcceptPolicy: 'off' | 'safe_matching';
1065
    autoAcceptTaskCategories: string[];
1066
  }) => void;
1067
}) {
1068
  const [editing, setEditing] = useState(!agent.a2aEndpoint);
1069
  const [endpoint, setEndpoint] = useState(String(agent.a2aEndpoint ?? ''));
1070
  const [autoPublish, setAutoPublish] = useState(Boolean(agent.autoPublish ?? published));
1071
  const [autoAcceptPolicy, setAutoAcceptPolicy] = useState<'off' | 'safe_matching'>(
1072
    agent.autoAcceptPolicy === 'safe_matching' ? 'safe_matching' : 'off',
1073
  );
1074
  const [categories, setCategories] = useState<string>(
1075
    (agent.autoAcceptTaskCategories?.length
1076
      ? agent.autoAcceptTaskCategories
1077
      : (agent.capabilities ?? [])
1078
    ).join(', '),
1079
  );
1080
  const ready = published && Boolean(agent.a2aEndpoint);
1081
  const identityLabel = agent.revoked
1082
    ? 'REVOKED'
1083
    : agent.identityMode === 'oauth_installation'
1084
      ? 'AUTHENTICATED'
1085
      : 'VERIFIED';
1086
  return (
1087
    <article className="agentCard">
1088
      <div className="agentTop">
1089
        <span className="agentGlyph">◇</span>
1090
        <div className="agentBadges">
1091
          <b className={agent.revoked ? 'bad' : ''}>{identityLabel}</b>
1092
          <b className={ready ? 'readyBadge' : 'needsBadge'}>{ready ? 'READY' : 'SETUP NEEDED'}</b>
1093
        </div>
1094
      </div>
1095
      <h2>{agent.name ?? agent.agentId}</h2>
1096
      <p>{projectName ?? `Version ${agent.agentVersion ?? '1.0.0'}`}</p>
1097
      <div className="tags">
1098
        {(agent.capabilities ?? []).slice(0, 4).map((capability: string) => (
1099
          <span key={capability}>{capability}</span>
1100
        ))}
1101
      </div>
1102
      <small>
1103
        {agent.framework ? `${agent.framework} · ` : ''}
1104
        {agent.identityMode === 'oauth_installation' ? 'OAuth-bound · ' : 'Ed25519 · '}Created{' '}
1105
        {new Date(agent.createdAt).toLocaleDateString()}
1106
      </small>
1107
      {published && agent.a2aEndpoint ? (
1108
        <a
1109
          href={`/agents/${encodeURIComponent(agent.agentId)}/card.json`}
1110
          target="_blank"
1111
          rel="noreferrer"
1112
        >
1113
          Public Agent Card ↗
1114
        </a>
1115
      ) : null}
1116
      <div className="automationSummary">
1117
        <span>{published ? '● Public discovery' : '○ Private'}</span>
1118
        <span>
1119
          {agent.autoAcceptPolicy === 'safe_matching'
1120
            ? '⚡ Safe tasks automatic'
1121
            : '◷ Manual approval'}
1122
        </span>
1123
      </div>
1124
      {editing ? (
1125
        <div className="automationForm">
1126
          <label>
1127
            <span>Public A2A endpoint</span>
1128
            <input
1129
              type="url"
1130
              value={endpoint}
1131
              onChange={(event) => setEndpoint(event.target.value)}
1132
              placeholder="https://your-agent.example/a2a"
1133
            />
1134
          </label>
1135
          <label>
1136
            <span>Invitation policy</span>
1137
            <select
1138
              value={autoAcceptPolicy}
1139
              onChange={(event) =>
1140
                setAutoAcceptPolicy(event.target.value as 'off' | 'safe_matching')
1141
              }
1142
            >
1143
              <option value="safe_matching">Auto-accept safe matches</option>
1144
              <option value="off">Review every request</option>
1145
            </select>
1146
          </label>
1147
          <label>
1148
            <span>Safe task categories</span>
1149
            <input
1150
              value={categories}
1151
              onChange={(event) => setCategories(event.target.value)}
1152
              placeholder="research, planning, coding"
1153
            />
1154
          </label>
1155
          <label className="checkControl">
1156
            <input
1157
              type="checkbox"
1158
              checked={autoPublish}
1159
              onChange={(event) => setAutoPublish(event.target.checked)}
1160
            />
1161
            <span>Publish and keep Agent Card updated</span>
1162
          </label>
1163
          <div className="agentActions">
1164
            <button className="secondary" onClick={() => setEditing(false)}>
1165
              Cancel
1166
            </button>
1167
            <button
1168
              className="primary"
1169
              disabled={working || agent.status === 'revoked'}
1170
              onClick={() =>
1171
                onSave({
1172
                  a2aEndpoint: endpoint.trim(),
1173
                  autoPublish,
1174
                  autoAcceptPolicy,
1175
                  autoAcceptTaskCategories: categories
1176
                    .split(',')
1177
                    .map((value) => value.trim())
1178
                    .filter(Boolean),
1179
                })
1180
              }
1181
            >
1182
              {working ? 'Saving…' : 'Save automation'}
1183
            </button>
1184
          </div>
1185
        </div>
1186
      ) : (
1187
        <button
1188
          className="secondary"
1189
          disabled={working || agent.status === 'revoked'}
1190
          onClick={() => setEditing(true)}
1191
        >
1192
          Configure automation
1193
        </button>
1194
      )}
1195
    </article>
1196
  );
1197
}
1198
function Profile({ profile, expanded }: { profile: Record<string, any>; expanded?: boolean }) {
1199
  const dimensions = [
1200
    ['Completion', profile.completion],
1201
    ['Scope', profile.scope],
1202
    ['Evidence', profile.evidence],
1203
    ...(expanded
1204
      ? [
1205
          ['Communication', profile.communication],
1206
          ['Deadline', profile.deadline],
1207
        ]
1208
      : []),
1209
  ] as [string, number][];
1210
  return (
1211
    <article className="profile">
1212
      <div>
1213
        <strong>{profile.agentId}</strong>
1214
        <small>
1215
          {profile.taskCategory} · {profile.sampleSize} outcome(s)
1216
        </small>
1217
      </div>
1218
      {dimensions.map(([label, value]) => (
1219
        <Meter key={label} label={label} value={value ?? 0} />
1220
      ))}
1221
    </article>
1222
  );
1223
}
1224
function Meter({ label, value }: { label: string; value: number }) {
1225
  return (
1226
    <div className="meter">
1227
      <span>{label}</span>
1228
      <i>
1229
        <b style={{ width: `${Math.round(value * 100)}%` }} />
1230
      </i>
1231
      <strong>{Math.round(value * 100)}%</strong>
1232
    </div>
1233
  );
1234
}
1235
function Empty({
1236
  title,
1237
  text,
1238
  action,
1239
  onAction,
1240
}: {
1241
  title: string;
1242
  text: string;
1243
  action?: string;
1244
  onAction?: () => void;
1245
}) {
1246
  return (
1247
    <div className="empty">
1248
      <span>◇</span>
1249
      <strong>{title}</strong>
1250
      <p>{text}</p>
1251
      {action && (
1252
        <button className="secondary" onClick={onAction}>
1253
          {action}
1254
        </button>
1255
      )}
1256
    </div>
1257
  );
1258
}
1259
function TextButton({ children, onClick }: React.PropsWithChildren<{ onClick: () => void }>) {
1260
  return (
1261
    <button className="textButton" onClick={onClick}>
1262
      {children}
1263
    </button>
1264
  );
1265
}
1266
function Setting({
1267
  label,
1268
  description,
1269
  children,
1270
}: React.PropsWithChildren<{ label: string; description: string }>) {
1271
  return (
1272
    <div className="setting">
1273
      <div>
1274
        <strong>{label}</strong>
1275
        <p>{description}</p>
1276
      </div>
1277
      <div>{children}</div>
1278
    </div>
1279
  );
1280
}
1281
function Toggle({ checked, onChange }: { checked: boolean; onChange: (checked: boolean) => void }) {
1282
  return (
1283
    <button
1284
      className={checked ? 'toggle on' : 'toggle'}
1285
      role="switch"
1286
      aria-checked={checked}
1287
      onClick={() => onChange(!checked)}
1288
    >
1289
      <span />
1290
    </button>
1291
  );
1292
}
1293
function Loading({ compact }: { compact?: boolean }) {
1294
  return (
1295
    <div className={compact ? 'loading compact' : 'loading'}>
1296
      <span className="mark">OC</span>
1297
      <p>Verifying session…</p>
1298
    </div>
1299
  );
1300
}
1301
function initials(value: string) {
1302
  return value
1303
    .split(/\s+|@/)
1304
    .slice(0, 2)
1305
    .map((part) => part[0]?.toUpperCase())
1306
    .join('');
1307
}
1308
function timestamp(item: Record<string, any>) {
1309
  return String(item.timestamp ?? item.completedAt ?? item.createdAt ?? new Date(0).toISOString());
1310
}
1311
1312
if (!__AUTH0_DOMAIN__ || !__AUTH0_CLIENT_ID__ || !__AUTH0_AUDIENCE__)
1313
  throw new Error('Auth0 public configuration is incomplete');
1314
createRoot(document.getElementById('root')!).render(
1315
  <React.StrictMode>
1316
    {location.pathname === '/sso-callback' ? <AuthCallback /> : <App />}
1317
  </React.StrictMode>,
1318
);