File size: 11,844 Bytes
518343a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import { useState, useEffect, useRef } from 'react';
import { createSpaceRun, streamRunOutput, validateProof } from '../lib/atelier-runtime';

const T = {
  bg: '#0a0a0a', border: 'rgba(255,255,255,0.08)', text: '#f5f5f5',
  textDim: '#8a8a8a', textMuted: '#5e5e5e', accent: '#c9b787',
  mono: 'var(--font-mono,ui-monospace,monospace)',
};

export interface AtelierEmbedProps {
  spaceSlug: string;
  tenantId?: string;
  height?: number;
  compact?: boolean;
  allowedOrigins?: string[];
}

export const ALLOWED_EMBED_ORIGINS: string[] = [
  'https://szl-holdings.com',
  'https://www.szl-holdings.com',
  'https://app.szl-holdings.com',
  'https://*.szl-holdings.com',
  'https://a11oy.szl-holdings.com',
  'http://localhost:3000',
  'http://localhost:4099',
  'http://localhost:4110',
  'http://localhost:4199',
  'http://localhost:5173',
  'http://localhost:5000',
  'http://localhost:8099',
  'http://localhost:80',
  'http://127.0.0.1:3000',
  'http://127.0.0.1:5173',
  'http://127.0.0.1:5000',
];

function isOriginAllowed(origin: string, allowlist: string[]): boolean {
  if (!origin) return false;
  for (const pattern of allowlist) {
    if (pattern === origin) return true;
    if (pattern.includes('*')) {
      try {
        const url = new URL(origin);
        const patternUrl = new URL(pattern.replace('*.', ''));
        if (url.protocol !== patternUrl.protocol) continue;
        const patternHost = patternUrl.hostname;
        if (url.hostname === patternHost || url.hostname.endsWith('.' + patternHost)) {
          return true;
        }
      } catch {
        continue;
      }
    }
  }
  return false;
}

const EMBED_SPACES: Record<string, { name: string; vertical: string; color: string; description: string; runtime: string }> = {
  'maritime-routing': {
    name: 'Maritime Routing Agent',
    vertical: 'Maritime',
    color: '#7ab8d9',
    description: 'AIS-fed route optimization and ETA monitoring for SZL maritime operations.',
    runtime: 'agent-loop',
  },
  're-underwriting': {
    name: 'Real Estate Underwriting Agent',
    vertical: 'Real Estate',
    color: '#c9b787',
    description: 'Governed underwriting analysis for acquisition, covenant risk, and lease-up.',
    runtime: 'agent-loop',
  },
  'legal-discovery': {
    name: 'Legal Discovery Intelligence',
    vertical: 'Legal',
    color: '#8a8a8a',
    description: 'Privilege-preserving discovery analysis and deadline tracking.',
    runtime: 'agent-loop',
  },
  'cyber-triage': {
    name: 'Cyber Threat Triage Agent',
    vertical: 'Cyber',
    color: '#10b981',
    description: 'CVE enrichment, SIEM correlation, and containment brief generation.',
    runtime: 'agent-loop',
  },
  'platform-health': {
    name: 'A11oy Platform Health',
    vertical: 'Platform',
    color: '#5e5e5e',
    description: 'Fabric layer health, proof ledger integrity, and SLO tracking.',
    runtime: 'chat',
  },
};

const AGENT_LOOP_OUTPUTS: Record<string, string[]> = {
  'maritime-routing': [
    '⟳ Connecting to AIS Live Feed…',
    '✓ Vessel data received — VLCC Everest',
    '⟳ Calculating ETA deviation…',
    '⚠ ETA +31h delay detected at Port Rotterdam',
    '⟳ Running port standby cost model…',
    '✓ Standby cost: $2.4M/day',
    '⟳ Evaluating 3 alternative routes…',
    '✓ Route via Port Antwerp: saves $1.2M demurrage',
    '⟳ Generating proof packet…',
    '✓ Proof: sha256:c9f2e5b8a1d3e6f9…\n\nRecommendation: Reroute to Port Antwerp. Estimated saving: $1.2M. Awaiting VP Operations approval.',
  ],
  're-underwriting': [
    '⟳ Loading CoStar comparable data…',
    '✓ 6 comps loaded for 45 Park Ave',
    '⟳ Checking lender covenant thresholds…',
    '✓ Covenant check: COMPLIANT (occupancy 89% vs 85% threshold)',
    '⟳ Running cap rate compression model…',
    '⚠ Cap rate compressed 28bps since Q4 2025',
    '⟳ Updating valuation model…',
    '✓ Portfolio value: +$4.2M vs last assessment',
    '⟳ Generating proof packet…',
    '✓ Proof: sha256:a1b2c3d4e5f6a7b8…\n\nUnderwriting complete. Risk score: 0.22 (LOW). Recommendation: Proceed with acquisition. Human approval required.',
  ],
};

const EMBED_VERTICAL_MAP: Record<string, string> = {
  Maritime: 'maritime',
  'Real Estate': 'real-estate',
  Legal: 'legal',
  Platform: 'platform',
  Cyber: 'cyber',
  Defense: 'defense',
  Executive: 'executive',
};

const EMBED_CONNECTORS: Record<string, string[]> = {
  'maritime-routing': ['AIS Live Feed', 'Port Standby Cost Model'],
  're-underwriting': ['CoStar', 'Lender Covenant API'],
  'legal-discovery': ['Docket Search', 'Document Repository'],
  'cyber-triage': ['Threat Intelligence Feed', 'CVE Database', 'SIEM Events'],
  'platform-health': ['Fabric Telemetry'],
};

function EmbedRunner({ slug, vertical }: { slug: string; vertical: string }) {
  const [lines, setLines] = useState<string[]>([]);
  const [running, setRunning] = useState(false);
  const [done, setDone] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [lines]);

  async function run() {
    setLines([]);
    setDone(false);
    setRunning(true);
    try {
      const connectors = EMBED_CONNECTORS[slug] ?? [];
      const v = EMBED_VERTICAL_MAP[vertical] ?? 'cross-vertical';
      const state = await createSpaceRun({
        spaceSlug: slug,
        vertical: v,
        connectors,
        constitutionRef: 'embed-default',
        modelPolicy: 'governed-default',
      });
      const finalState = await streamRunOutput(
        state.workcellId,
        (line) => setLines((prev) => [...prev, line]),
        { vertical: v, connectors, spaceSlug: slug },
      );
      const proof = await validateProof(finalState.workcellId, finalState.pceContractId);
      if (proof.proofRef) setLines((prev) => [...prev, `✓ Proof ref: ${proof.proofRef}`]);
    } catch (e) {
      setLines((prev) => [...prev, `✗ Run error: ${e instanceof Error ? e.message : String(e)}`]);
    } finally {
      setRunning(false);
      setDone(true);
    }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ flex: 1, overflowY: 'auto', padding: '0.875rem', fontFamily: T.mono, fontSize: '0.6875rem', lineHeight: 1.7, color: T.textDim }}>
        {lines.length === 0 && !running && (
          <div style={{ color: T.textMuted, textAlign: 'center', paddingTop: '1.5rem', fontSize: '0.75rem' }}>
            Click Run to execute in governed runtime.
          </div>
        )}
        {lines.map((l, i) => (
          <div key={i} style={{ color: l.startsWith('✓') ? '#c9b787' : l.startsWith('⚠') ? '#8a8a8a' : l.startsWith('⟳') ? '#5e5e5e' : T.text }}>
            {l}
          </div>
        ))}
        {running && <span style={{ display: 'inline-block', animation: 'pulse 1s infinite', color: T.accent }}>▌</span>}
        <div ref={bottomRef} />
      </div>
      <div style={{ padding: '0.625rem 0.875rem', borderTop: `1px solid ${T.border}`, display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
        <button onClick={run} disabled={running}
          style={{ padding: '0.375rem 0.875rem', borderRadius: 5, fontSize: '0.6875rem', fontWeight: 500, cursor: running ? 'not-allowed' : 'pointer', background: 'rgba(201,183,135,0.1)', border: `1px solid rgba(201,183,135,0.25)`, color: T.accent, opacity: running ? 0.5 : 1 }}>
          {running ? '⟳ Running…' : '▶ Run'}
        </button>
        {done && <span style={{ fontSize: '0.5625rem', fontFamily: T.mono, color: '#c9b787' }}>✓ Proof generated</span>}
      </div>
    </div>
  );
}

export function AtelierEmbed({ spaceSlug, tenantId = 'szl', height = 340, compact = false, allowedOrigins }: AtelierEmbedProps) {
  const spaceInfo = EMBED_SPACES[spaceSlug] ?? {
    name: spaceSlug, vertical: 'Unknown', color: '#5e5e5e',
    description: 'A governed Atelier Space.', runtime: 'agent-loop',
  };

  useEffect(() => {
    const allowlist = [...ALLOWED_EMBED_ORIGINS, ...(allowedOrigins ?? [])];
    function handleMessage(e: MessageEvent) {
      if (e.data?.type === 'a11oy-space-handshake') {
        if (!isOriginAllowed(e.origin, allowlist)) {
          return;
        }
        e.source?.postMessage({ type: 'a11oy-space-ack', spaceSlug, tenantId, ready: true }, { targetOrigin: e.origin });
      }
    }
    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [spaceSlug, tenantId, allowedOrigins]);

  const BASE = (import.meta.env.BASE_URL ?? '/a11oy/').replace(/\/$/, '');

  return (
    <div style={{
      background: T.bg, border: `1px solid ${T.border}`, borderRadius: 10,
      overflow: 'hidden', fontFamily: 'var(--font-sans,Inter,sans-serif)',
      height: compact ? 'auto' : height, display: 'flex', flexDirection: 'column',
      borderTop: `2px solid ${spaceInfo.color}`,
    }}>
      <div style={{ padding: compact ? '0.625rem 0.875rem' : '0.875rem 1.125rem', borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: '0.75rem', flexShrink: 0, background: 'rgba(255,255,255,0.01)' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: compact ? '0.75rem' : '0.875rem', fontWeight: 600, color: T.text, letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {spaceInfo.name}
          </div>
          {!compact && (
            <div style={{ fontSize: '0.5625rem', fontFamily: T.mono, color: spaceInfo.color, textTransform: 'uppercase', letterSpacing: '0.1em', marginTop: '0.125rem' }}>
              {spaceInfo.vertical} · Atelier Space
            </div>
          )}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', flexShrink: 0 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: spaceInfo.color, boxShadow: `0 0 5px ${spaceInfo.color}` }} />
          <span style={{ fontSize: '0.5rem', fontFamily: T.mono, color: T.textMuted }}>Governed</span>
        </div>
        <a href={`${BASE}/atelier/s/${spaceSlug}`} target="_blank" rel="noopener noreferrer"
          style={{ fontSize: '0.5rem', fontFamily: T.mono, color: T.textMuted, textDecoration: 'none', padding: '0.2rem 0.375rem', borderRadius: 3, border: `1px solid ${T.border}` }}>
          ↗ Open
        </a>
      </div>

      {!compact && (
        <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          <EmbedRunner slug={spaceSlug} vertical={spaceInfo.vertical} />
        </div>
      )}

      {compact && (
        <div style={{ padding: '0.625rem 0.875rem' }}>
          <p style={{ fontSize: '0.75rem', color: T.textDim, margin: 0, lineHeight: 1.5 }}>{spaceInfo.description}</p>
          <div style={{ display: 'flex', gap: '0.75rem', marginTop: '0.5rem' }}>
            <a href={`${BASE}/atelier/s/${spaceSlug}`} target="_blank" rel="noopener noreferrer"
              style={{ fontSize: '0.6875rem', color: spaceInfo.color, textDecoration: 'none', fontFamily: T.mono }}>
              Open in Atelier →
            </a>
          </div>
        </div>
      )}

      <div style={{ padding: '0.375rem 0.875rem', borderTop: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: '0.5rem', flexShrink: 0, background: 'rgba(255,255,255,0.01)' }}>
        <span style={{ fontSize: '0.5rem', fontFamily: T.mono, color: T.textMuted }}>Powered by</span>
        <span style={{ fontSize: '0.5rem', fontFamily: T.mono, color: T.accent, fontWeight: 600 }}>A11oy Atelier</span>
        <span style={{ fontSize: '0.5rem', fontFamily: T.mono, color: T.textMuted }}>· tenant: {tenantId}</span>
      </div>
    </div>
  );
}