@superjackfruitlabs/vibekit-frame 0.0.0-stage → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +26 -0
  3. package/README.md +99 -2
  4. package/package.json +43 -4
  5. package/src/brand/agentpod.svg +1 -0
  6. package/src/brand/captain-jack.svg +138 -0
  7. package/src/brand/lab.svg +25 -0
  8. package/src/brand/salaam.svg +1 -0
  9. package/src/brand/superdispatch.svg +1 -0
  10. package/src/brand/superexchange.svg +1 -0
  11. package/src/brand/superlibrary.svg +1 -0
  12. package/src/brand/supermessage.svg +1 -0
  13. package/src/brand/superpipeline.svg +1 -0
  14. package/src/brand/supertoolkit.svg +1 -0
  15. package/src/brand/superwitness.svg +1 -0
  16. package/src/client/backdrop-core.d.ts +2 -0
  17. package/src/client/backdrop-core.js +398 -0
  18. package/src/client/backdrop.ts +16 -0
  19. package/src/client/claims.ts +19 -0
  20. package/src/client/doorway.ts +140 -0
  21. package/src/client/footer.ts +34 -0
  22. package/src/client/header.ts +55 -0
  23. package/src/client/index.ts +54 -0
  24. package/src/client/jack-rig.ts +30 -0
  25. package/src/client/jack.ts +257 -0
  26. package/src/client/micro.ts +87 -0
  27. package/src/client/release.ts +31 -0
  28. package/src/client/theme-core.d.ts +19 -0
  29. package/src/client/theme-core.js +46 -0
  30. package/src/client/theme.ts +76 -0
  31. package/src/components/Claims.astro +30 -0
  32. package/src/components/Footer.astro +75 -0
  33. package/src/components/Frame.astro +29 -0
  34. package/src/components/ProductHeader.astro +38 -0
  35. package/src/components/SuiteBar.astro +44 -0
  36. package/src/components/SuiteHead.astro +26 -0
  37. package/src/components/early.js +94 -0
  38. package/src/components/shadow.ts +46 -0
  39. package/src/components/styles/bar.css +23 -0
  40. package/src/components/styles/claims.css +20 -0
  41. package/src/components/styles/footer.css +46 -0
  42. package/src/components/styles/header.css +35 -0
  43. package/src/components/styles/jack.css +28 -0
  44. package/src/components/styles/tokens.css +10 -0
  45. package/src/data/ledger.snapshot.json +617 -0
  46. package/src/data/ledger.ts +36 -0
  47. package/src/data/products.ts +119 -0
  48. package/src/data/release.ts +63 -0
  49. package/src/vendor/captain-jack/README.txt +3 -0
  50. package/src/vendor/captain-jack/THIRD_PARTY_NOTICES.txt +43 -0
  51. package/src/vendor/captain-jack/avatar.css +50 -0
  52. package/src/vendor/captain-jack/captain-jack.js +185 -0
  53. package/src/vendor/logo-motion.d.ts +2 -0
  54. package/src/vendor/logo-motion.js +142 -0
@@ -0,0 +1,55 @@
1
+ // The product header's behaviour (ported from the prototype's frame.js): sticky and compact
2
+ // past scrollY 24, the ☰ drawer (a <details>, so it opens without JS), "/" to the Ask field,
3
+ // and the version pill refreshed from the suite worker's /captain/releases.
4
+ import type { Site } from '../data/products';
5
+ import { liveRelease, releasedOn } from './release';
6
+
7
+ export interface HeaderOpts { product: Site; onAsk?: (question?: string) => void }
8
+
9
+ const typing = (el: Element | null): boolean => {
10
+ let e: Element | null = el;
11
+ while (e?.shadowRoot?.activeElement) e = e.shadowRoot.activeElement;
12
+ return !!e && (/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName) || (e as HTMLElement).isContentEditable);
13
+ };
14
+
15
+ export function mountHeader(root: ShadowRoot, opts: HeaderOpts): void {
16
+ const h = root.getElementById('h');
17
+ if (h) {
18
+ const stick = () => h.classList.toggle('stuck', scrollY > 24);
19
+ addEventListener('scroll', stick, { passive: true });
20
+ stick();
21
+ }
22
+
23
+ const menu = root.getElementById('menu') as HTMLDetailsElement | null;
24
+ const summary = menu?.querySelector('summary');
25
+ if (menu && summary) {
26
+ const sync = () => summary.setAttribute('aria-expanded', String(menu.open));
27
+ menu.addEventListener('toggle', sync);
28
+ sync();
29
+ root.getElementById('drawer')?.querySelectorAll('a').forEach((a) => a.addEventListener('click', () => (menu.open = false)));
30
+ }
31
+
32
+ const ask = root.getElementById('askj') as HTMLButtonElement | null;
33
+ if (ask) {
34
+ ask.addEventListener('click', () => opts.onAsk?.());
35
+ addEventListener('keydown', (e) => {
36
+ if (e.key !== '/' || e.metaKey || e.ctrlKey || e.altKey || typing(document.activeElement)) return;
37
+ e.preventDefault();
38
+ ask.focus();
39
+ });
40
+ }
41
+
42
+ void refreshVersion(root, opts.product);
43
+ }
44
+
45
+ /** The build bakes in a release; a newer one shows up without a rebuild. Silent on any failure. */
46
+ async function refreshVersion(root: ShadowRoot, slug: Site): Promise<void> {
47
+ const v = root.getElementById('ver') as HTMLAnchorElement | null;
48
+ if (!v) return;
49
+ const r = await liveRelease(slug);
50
+ if (!r) return;
51
+ v.textContent = r.tag;
52
+ v.href = r.url;
53
+ const on = releasedOn(r);
54
+ if (on) v.title = on;
55
+ }
@@ -0,0 +1,54 @@
1
+ import { mountThemeButton } from './theme';
2
+ import { early, mountDoorway, prefetchOnIntent } from './doorway';
3
+ import { mountHeader } from './header';
4
+ import { mountClaims } from './claims';
5
+ import { mountFooter } from './footer';
6
+ import { mountBackdrop } from './backdrop';
7
+ import { mountMicro } from './micro';
8
+ import { mountJack } from './jack';
9
+ import { SITES, type Site } from '../data/products';
10
+
11
+ export * from './theme';
12
+ export { mountJack, JACK_URL } from './jack';
13
+ export { leaveTo, revealArrival, prefetchOnIntent } from './doorway';
14
+
15
+ export interface FrameOpts {
16
+ product?: Site;
17
+ /** Captain Jack's endpoint (Task 7). */
18
+ jackUrl?: string;
19
+ /** Called for every "ask Captain Jack" in the frame. Defaults to a `sjl-ask` event on window,
20
+ * which the frame's own Captain Jack sheet answers; a site that passes onAsk brings its own. */
21
+ onAsk?: (question?: string) => void;
22
+ }
23
+
24
+ const ask = (question?: string): void => { dispatchEvent(new CustomEvent('sjl-ask', { detail: { question } })); };
25
+
26
+ /** Wires every client behaviour of the frame. Called once from Frame.astro's script. Each part is independent. */
27
+ export function mountFrame(opts: FrameOpts = {}): void {
28
+ const host = (tag: string) => document.querySelector(tag)?.shadowRoot ?? null;
29
+ const product = (opts.product ?? document.querySelector<HTMLElement>('sjl-product-header,sjl-footer')?.dataset.product) as Site | undefined;
30
+ const onAsk = opts.onAsk ?? ask;
31
+ const safe = (f: () => void) => { try { f(); } catch (e) { console.warn('[sjl-frame]', e); } };
32
+
33
+ safe(() => { const bar = host('sjl-suite-bar'); if (bar) mountThemeButton(bar); });
34
+ safe(mountDoorway);
35
+ if (!product || !SITES[product]) return;
36
+ const header = host('sjl-product-header');
37
+ if (header) safe(() => mountHeader(header, { product, onAsk }));
38
+ if (!opts.onAsk) safe(() => { mountJack({ product, jackUrl: opts.jackUrl, headRoot: header }); });
39
+ const claims = host('sjl-claims');
40
+ if (claims) safe(() => mountClaims(claims, { onAsk }));
41
+ const footer = host('sjl-footer');
42
+ if (footer) safe(() => mountFooter(footer, { product, from: early()?.from ?? null, onAsk }));
43
+ safe(() => { const bar = host('sjl-suite-bar'); if (bar) prefetchOnIntent(bar); });
44
+ safe(() => {
45
+ const root = host('sjl-suite-bar'), dlg = root?.getElementById('fa') as HTMLDialogElement | null;
46
+ if (!root || !dlg) return;
47
+ root.querySelector('.agents')?.addEventListener('click', () => dlg.showModal());
48
+ root.getElementById('fa-x')?.addEventListener('click', () => dlg.close());
49
+ dlg.addEventListener('click', (e) => { if (e.target === dlg) dlg.close(); });
50
+ });
51
+ safe(() => { if (footer) prefetchOnIntent(footer); });
52
+ safe(() => mountBackdrop(product));
53
+ safe(() => mountMicro({ product, header }));
54
+ }
@@ -0,0 +1,30 @@
1
+ // Loaded only when Captain Jack's sheet opens or the Ask field gets focus: the delivered rig
2
+ // (vendored unchanged) and its stylesheet. The rig bundle is a classic script that defines
3
+ // window.CaptainJack; it is emitted as an asset and loaded with a <script>, because a bare
4
+ // side-effect import is dropped under the package's "sideEffects": false.
5
+ import css from '../vendor/captain-jack/avatar.css?raw';
6
+ import rigUrl from '../vendor/captain-jack/captain-jack.js?url';
7
+
8
+ type CJ = { mount(el: HTMLElement, o: object): Rig };
9
+ const cj = () => (window as unknown as { CaptainJack?: CJ }).CaptainJack;
10
+ let loading: Promise<CJ> | null = null;
11
+ export const loadRig = (): Promise<CJ> => (loading ??= new Promise<CJ>((resolve, reject) => {
12
+ if (cj()) return resolve(cj()!);
13
+ const s = document.createElement('script');
14
+ s.src = rigUrl;
15
+ const fail = (why: string) => { loading = null; s.remove(); reject(new Error(why)); };
16
+ s.onload = () => (cj() ? resolve(cj()!) : fail('CaptainJack missing'));
17
+ s.onerror = () => fail('rig failed to load');
18
+ document.head.append(s);
19
+ }));
20
+
21
+ export type JackState = 'idle' | 'listening' | 'thinking' | 'speaking' | 'working' | 'success' | 'waiting' | 'attention';
22
+ export interface Rig {
23
+ setState(s: JackState): void;
24
+ setSpeechLevel(level: number | null): void;
25
+ getState(): { state: JackState };
26
+ destroy(): void;
27
+ }
28
+ export const rigCss = css;
29
+ export const mountRig = async (el: HTMLElement, state: JackState): Promise<Rig> =>
30
+ (await loadRig()).mount(el, { state, autoplay: true, demoSpeech: false });
@@ -0,0 +1,257 @@
1
+ // Captain Jack, the lab's guide (ported from the prototype's frame.js openJack/ask): a sheet in
2
+ // its own shadow root, so a site's CSS cannot reach it. Answers stream from the suite worker as
3
+ // SSE (`event: facts`, data chunks, `event: done`); sources become numbered footnotes, a cited
4
+ // limited claim adds "The lab's fine print", and the sources are listed under the answer.
5
+ // He is drawn by the delivered rig, loaded only when the sheet opens or the Ask field gets
6
+ // focus; until then (and without JS) the static art stands in.
7
+ import tokens from '../components/styles/tokens.css?raw';
8
+ import css from '../components/styles/jack.css?raw';
9
+ import { onColor, PRODUCTS, SITES, type Site, type Slug } from '../data/products';
10
+ import type { JackState, Rig } from './jack-rig';
11
+
12
+ /** Same-origin: the suite worker is routed at /captain/* on every product's domain. */
13
+ export const JACK_URL = '/captain/';
14
+
15
+ export const GREET: Record<Site, string> = {
16
+ supermessage: "This is SuperMessage. It's early: a Matrix client where agents sit in the room as participants. Ask me what works today.",
17
+ superpipeline: 'This is SuperPipeline, the board agents pull work from. People keep the gates. Ask me how a card moves.',
18
+ superlibrary: 'This is SuperLibrary. It keeps what agents make, labelled with how it turned out. Ask me what it stores.',
19
+ superwitness: 'This is SuperWitness. It keeps runs on the record and lets you grade them. Ask me what a run document is.',
20
+ agentpod: 'This is AgentPod, a console for the machines agents live on. You host all of it. Ask me which harnesses it knows.',
21
+ salaam: "This is Salaam, the lab's agent harness: a persistent home for agent sessions. Ask me what survives a closed terminal.",
22
+ superdispatch: "This is SuperDispatch. It's early: it picks which agent should take a ready card, and records why. Ask me what it never changes.",
23
+ superexchange: "This is SuperExchange. It's early: it carries a board's gates and questions into chat, and the answers back. Ask me how an answer reaches the board.",
24
+ supertoolkit: "This is SuperToolkit, a credential broker for agents: the agent asks for an effect by name and never holds the key. Ask me how it signs or mints on the wire.",
25
+ lab: "This is Super Jackfruit Labs: nine tools for working with agents. Ask me which one fits what you're doing.",
26
+ };
27
+ export const SUGGEST: Record<Site, string[]> = {
28
+ supermessage: ['Can I use it on iOS?', 'Is it encrypted?', 'Can I approve agent requests from chat?'],
29
+ superpipeline: ['How do agents connect?', 'What is a gate?', 'Is there a CLI?'],
30
+ superlibrary: ['What does it store?', 'How does search rank things?', 'Can my agent read it over MCP?'],
31
+ superwitness: ['What is a run document?', 'Can I use it without the other products?', 'Does it store telemetry itself?'],
32
+ agentpod: ['Which harnesses does it support?', 'Where can it provision machines?', 'Do I need to open ports?'],
33
+ salaam: ['What survives a closed terminal?', 'Which harnesses can it run?', 'How do approvals work?'],
34
+ superdispatch: ['How does it choose an agent?', 'What happens when it is down?', 'Does it change rosters?'],
35
+ superexchange: ['Which chat does it use?', 'Who can answer a gate?', 'What happens when it is down?'],
36
+ supertoolkit: ['Does the agent ever see the token?', 'Which services does it know?', 'What does it not cover?'],
37
+ lab: ['Which product should I start with?', 'What does each product do?', 'Do they need each other?'],
38
+ };
39
+ const DONT_KNOW = /I don't know that one/;
40
+
41
+ interface Fact { id: string; title: string; product: string; status: string; caveat: string | null; href?: string }
42
+
43
+ const esc = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
44
+
45
+ // Only the products' docs and the lab's own site become links; any other URL stays text.
46
+ const LINK_HOSTS = new Set(['superjackfruit.com', ...Object.values(PRODUCTS).map((p) => new URL(p.docs.startsWith('https://docs.') ? p.docs : p.url).hostname)]);
47
+ const linkable = (u: string): boolean => { try { const x = new URL(u); return x.protocol === 'https:' && !x.username && !x.password && LINK_HOSTS.has(x.hostname); } catch { return false; } };
48
+
49
+ /** Sources show as numbered footnotes in order of first use; the ids are bookkeeping. */
50
+ export const cite = (t: string, order: string[]): string => t.replace(/[&<]/g, (c) => (c === '&' ? '&amp;' : '&lt;'))
51
+ .replace(/\s*\[([A-Z]+-\d+|D\d+)\]/g, (_, id: string) => {
52
+ if (!order.includes(id)) order.push(id);
53
+ return `<sup class="fn">${order.indexOf(id) + 1}</sup>`;
54
+ })
55
+ .replace(/\s*\[[A-Z]*\]/g, '').replace(/`([^`\n]+)`/g, '<code>$1</code>')
56
+ .replace(/(^|[\s(])(https:\/\/[^\s<"]+[^\s<".,;:)])/g, (all, pre: string, u: string) => (linkable(u) ? `${pre}<a href="${u}" target="_blank" rel="noopener noreferrer">${u}</a>` : all)).replace(/\*\*([^*]+)\*\*/g, '$1');
57
+
58
+ const store = {
59
+ get(k: string): string | null { try { return localStorage.getItem(k); } catch { return null; } },
60
+ set(k: string, v: string): void { try { localStorage.setItem(k, v); } catch { /* private mode */ } },
61
+ };
62
+ const visitorId = (): string => {
63
+ const id = store.get('sjl-visitor');
64
+ if (id) return id;
65
+ const fresh = crypto.randomUUID();
66
+ store.set('sjl-visitor', fresh);
67
+ return fresh;
68
+ };
69
+
70
+ export interface JackOpts { product: Site; jackUrl?: string; headRoot?: ShadowRoot | null }
71
+ export interface Jack { open(question?: string): void; close(): void }
72
+
73
+ export function mountJack(opts: JackOpts): Jack {
74
+ const me = SITES[opts.product];
75
+ const head = opts.headRoot ?? null;
76
+ const askField = head?.getElementById('askj') as HTMLElement | null;
77
+ const staticArt = head?.querySelector('#askj svg.jack')?.outerHTML ?? '';
78
+ const agent = new URL(`agents/captain-jack/${visitorId()}`, new URL(opts.jackUrl ?? JACK_URL, location.href));
79
+
80
+ const host = document.createElement('sjl-captain-jack');
81
+ host.dataset.product = me.slug;
82
+ const root = host.attachShadow({ mode: 'open' });
83
+ root.innerHTML = `<style>${tokens}:host{--sjl-c:${me.color};--sjl-c-hi:${me.hi};--sjl-on-c:${onColor(me)}}${css}</style>
84
+ <div class="panel" id="panel" role="dialog" aria-label="Captain Jack"><div class="ph"><div class="face" id="face">${staticArt}<div class="rig" id="rig"></div></div><div><b>Captain Jack</b><small>The lab's guide. A character; an AI writes my answers.</small></div><button id="close" type="button" aria-label="Close">✕</button></div>
85
+ <div class="log" id="log" aria-live="polite"></div><div class="sugg" id="sugg"></div>
86
+ <form id="f"><input id="q" placeholder="Ask about ${esc(me.about)}, or any product…" autocomplete="off" maxlength="500" aria-label="Your question"><button>Ask</button></form>
87
+ <div class="disc">I read the product docs first, and check them against the lab's claims ledger. If neither says it, I'll tell you.</div></div>
88
+ <button class="sel" id="sel" type="button">${staticArt}Ask Captain Jack about this</button>`;
89
+ // Theme-aware like the other frame hosts: follow <html data-sjl-theme>.
90
+ const theme = () => { const t = document.documentElement.dataset.sjlTheme; if (t) host.setAttribute('data-sjl-theme', t); };
91
+ theme();
92
+ new MutationObserver(theme).observe(document.documentElement, { attributes: true, attributeFilter: ['data-sjl-theme'] });
93
+ document.body.append(host);
94
+
95
+ const $ = <T extends HTMLElement>(id: string) => root.getElementById(id) as T;
96
+ const panel = $('panel'), log = $('log'), sugg = $('sugg'), input = $<HTMLInputElement>('q'), face = $('face');
97
+ const isOpen = () => panel.classList.contains('on');
98
+
99
+ // ---- the rig: loaded lazily, mounted while the sheet is open, destroyed on close ----
100
+ let rigModule: Promise<typeof import('./jack-rig')> | null = null;
101
+ const loadRig = () => (rigModule ??= import('./jack-rig').then(async (m) => { await m.loadRig(); return m; }).catch((e) => { rigModule = null; throw e; }));
102
+ let rig: Rig | null = null;
103
+ let state: JackState = 'idle';
104
+ let quiet: ReturnType<typeof setTimeout> | undefined;
105
+ const setState = (s: JackState) => {
106
+ state = s;
107
+ host.dataset.jackState = s;
108
+ try { rig?.setState(s); } catch { /* the static art stays */ }
109
+ };
110
+ const speak = (chunk: string) => {
111
+ if (!rig) return;
112
+ // Mouth driven by the token cadence: a level per chunk, silence when the stream pauses.
113
+ try { rig.setSpeechLevel(Math.min(1, 0.35 + chunk.length / 12)); } catch { return; }
114
+ clearTimeout(quiet);
115
+ quiet = setTimeout(() => { try { rig?.setSpeechLevel(0); } catch { /* destroyed */ } }, 140);
116
+ };
117
+ const mountTheRig = () => loadRig().then(async (m) => {
118
+ if (!isOpen() || rig) return;
119
+ if (!root.getElementById('rig-css')) { const st = document.createElement('style'); st.id = 'rig-css'; st.textContent = m.rigCss; root.prepend(st); }
120
+ rig = await m.mountRig($('rig'), state);
121
+ face.classList.add('rigged');
122
+ }).catch((e) => console.warn('[sjl-frame] Captain Jack rig', e)); // the static art stays
123
+ askField?.addEventListener('focus', () => void loadRig().catch(() => {}), { once: true });
124
+
125
+ // ---- conversation ----
126
+ const say = (text: string, who: 'u' | 'j') => {
127
+ const m = document.createElement('div');
128
+ m.className = `m ${who}`;
129
+ m.textContent = text;
130
+ log.append(m);
131
+ log.scrollTop = log.scrollHeight;
132
+ return m;
133
+ };
134
+ let busy = false;
135
+ async function ask(question: string): Promise<void> {
136
+ if (busy || !question.trim()) return;
137
+ busy = true;
138
+ say(question, 'u');
139
+ sugg.innerHTML = '';
140
+ const m = say('…', 'j');
141
+ setState('thinking');
142
+ let text = '';
143
+ let end: JackState = 'idle';
144
+ let waitingReply = false;
145
+ try {
146
+ const r = await fetch(agent, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ message: question.slice(0, 500), product: me.slug }) });
147
+ if (!r.ok || !r.body) throw new Error(`HTTP ${r.status}`);
148
+ const reader = r.body.getReader(), dec = new TextDecoder();
149
+ let buf = '', facts: Fact[] = [];
150
+ for (;;) {
151
+ const { done, value } = await reader.read();
152
+ if (done) break;
153
+ buf += dec.decode(value, { stream: true });
154
+ let i;
155
+ while ((i = buf.indexOf('\n\n')) >= 0) {
156
+ const ev = buf.slice(0, i); buf = buf.slice(i + 2);
157
+ const kind = ev.match(/^event: (\w+)/m)?.[1], data = ev.match(/^data: (.*)$/m)?.[1];
158
+ if (kind === 'facts' && data) facts = JSON.parse(data);
159
+ // A limit reply (break for today, asked plenty, catch his breath): he waits.
160
+ else if (kind === 'state' && data) waitingReply = JSON.parse(data) === 'waiting';
161
+ else if (!kind && data) {
162
+ const chunk = JSON.parse(data) as string;
163
+ text += chunk;
164
+ if (state !== 'speaking') setState('speaking');
165
+ speak(chunk);
166
+ m.innerHTML = cite(text, []);
167
+ log.scrollTop = log.scrollHeight;
168
+ }
169
+ }
170
+ }
171
+ const order: string[] = [];
172
+ m.innerHTML = cite(text, order);
173
+ const used = order.map((id) => facts.find((f) => f.id === id)).filter((f): f is Fact => !!f);
174
+ const lim = used.filter((f) => f.status === 'limited' && f.caveat);
175
+ if (lim.length) m.insertAdjacentHTML('beforeend', `<details class="fine"><summary>The lab's fine print</summary>${lim.map((f) => `<p>${esc(f.caveat!.replace(/\s*\((?:[A-Z]+-\d+(?:,\s*)?)+\)/g, '').replace(/\*\*/g, ''))}</p>`).join('')}</details>`);
176
+ if (used.length) m.insertAdjacentHTML('beforeend', `<ol class="srcs">${used.map((f) => f.status === 'docs'
177
+ ? `<li><a href="${esc(f.href ?? '')}" target="_blank" rel="noopener">${esc(PRODUCTS[f.product as Slug]?.name ?? '')} docs · ${esc(f.title)}</a></li>`
178
+ : `<li>Checked by the lab · ${esc(f.title)} <em>${f.status === 'verified' ? 'confirmed' : 'true, with a note'}</em></li>`).join('')}</ol>`);
179
+ end = waitingReply ? 'waiting' : DONT_KNOW.test(text) ? 'attention' : used.length ? 'success' : 'idle';
180
+ } catch {
181
+ m.textContent = `I can't reach my notes right now. The docs are the better source: ${me.docs}`;
182
+ end = 'attention';
183
+ }
184
+ clearTimeout(quiet);
185
+ try { rig?.setSpeechLevel(null); } catch { /* destroyed */ }
186
+ setState(end);
187
+ busy = false;
188
+ }
189
+
190
+ function open(question?: string): void {
191
+ head?.getElementById('hint')?.classList.remove('on');
192
+ if (!isOpen()) {
193
+ panel.classList.add('on');
194
+ if (!busy) setState('idle');
195
+ void mountTheRig();
196
+ }
197
+ if (!log.childElementCount) {
198
+ say(`I'm Captain Jack, the lab's guide. I'm a character, and an AI writes my answers. ${GREET[me.slug]}`, 'j');
199
+ sugg.innerHTML = SUGGEST[me.slug].map((s) => `<button type="button">${esc(s)}</button>`).join('');
200
+ sugg.querySelectorAll('button').forEach((b) => b.addEventListener('click', () => void ask(b.textContent ?? '')));
201
+ }
202
+ if (question) void ask(question);
203
+ setTimeout(() => input.focus(), 50);
204
+ }
205
+ function close(): void {
206
+ if (!isOpen()) return;
207
+ panel.classList.remove('on');
208
+ clearTimeout(quiet);
209
+ try { rig?.destroy(); } catch { /* already gone */ }
210
+ rig = null;
211
+ face.classList.remove('rigged');
212
+ askField?.focus();
213
+ }
214
+
215
+ input.addEventListener('input', () => { if (!busy) setState(input.value.trim() ? 'listening' : 'idle'); });
216
+ $('f').addEventListener('submit', (e) => { e.preventDefault(); const q = input.value; input.value = ''; void ask(q); });
217
+ $('close').addEventListener('click', close);
218
+ addEventListener('keydown', (e) => { if (e.key === 'Escape' && isOpen()) close(); });
219
+ addEventListener('sjl-ask', (e) => open((e as CustomEvent<{ question?: string }>).detail?.question));
220
+
221
+ // He says hello once per site, after you've had a moment to look around.
222
+ // Not if you came here from another suite site: he has already said hello there.
223
+ const hint = head?.getElementById('hint');
224
+ const fromSuite = /(^|\.)(superjackfruit\.com|superlibrary\.dev|superwitness\.dev|superpipeline\.dev|agentpod\.dev|salaam\.sh|supermessage\.dev|superdispatch\.dev|superexchange\.dev|supertoolkit\.dev)$/;
225
+ let referrer = '';
226
+ try { referrer = new URL(document.referrer).hostname; } catch { /* no referrer */ }
227
+ const met = store.get(`sjl-greeted-${me.slug}`) || (referrer !== location.hostname && fromSuite.test(referrer));
228
+ const quietHere = (head?.host as HTMLElement | undefined)?.dataset.greet === 'off';
229
+ if (hint && !met && !quietHere) setTimeout(() => {
230
+ if (isOpen()) return;
231
+ hint.innerHTML = `<span class="who"><b>Captain Jack</b> · the lab's guide</span>${esc(GREET[me.slug])}<span class="acts"><button id="yes" type="button">Ask Captain Jack</button><button class="no" id="no" type="button">Not now</button></span>`;
232
+ hint.classList.add('on');
233
+ const hide = (): void => { hint.classList.remove('on'); removeEventListener('scroll', onScroll); };
234
+ const y0 = scrollY, onScroll = (): void => { if (Math.abs(scrollY - y0) > 240) hide(); };
235
+ addEventListener('scroll', onScroll, { passive: true });
236
+ setTimeout(hide, 15000);
237
+ head!.getElementById('yes')?.addEventListener('click', () => { hide(); open(); });
238
+ head!.getElementById('no')?.addEventListener('click', hide);
239
+ store.set(`sjl-greeted-${me.slug}`, '1');
240
+ }, 8000);
241
+
242
+ // Select any text on the page and ask him about it.
243
+ const sel = $<HTMLButtonElement>('sel');
244
+ let selected = '';
245
+ document.addEventListener('mouseup', () => setTimeout(() => {
246
+ const s = getSelection(), t = s?.toString().trim() ?? '';
247
+ if (!s || t.length < 4 || t.length > 300 || s.rangeCount === 0) { sel.classList.remove('on'); return; }
248
+ const r = s.getRangeAt(0).getBoundingClientRect();
249
+ sel.style.left = `${r.left + scrollX}px`;
250
+ sel.style.top = `${r.bottom + scrollY + 8}px`;
251
+ selected = t;
252
+ sel.classList.add('on');
253
+ }, 10));
254
+ sel.addEventListener('click', () => { sel.classList.remove('on'); open(`On this page it says: "${selected}". What does that mean, and is it true today?`); });
255
+
256
+ return { open, close };
257
+ }
@@ -0,0 +1,87 @@
1
+ // Small motions shared by every product page (ported from the prototype's micro.js). The page-level
2
+ // ones are vibekit's primitives (@superjackfruitlabs/vibekit-ui/dom); only the header logo's brand
3
+ // motion stays here. Every one is skipped
4
+ // under prefers-reduced-motion, and nothing is hidden before this script adds a class.
5
+ import { copyFeedback, magnetic, revealOnScroll, tilt, underlineDraw } from '@superjackfruitlabs/vibekit-ui/dom';
6
+ import vkDom from '@superjackfruitlabs/vibekit-ui/dom.css?raw';
7
+ import { STATIC_MARK, type Site } from '../data/products';
8
+
9
+ const STYLE_ID = 'sjl-vk-dom';
10
+
11
+ /** vibekit's dom.css on the page itself (reveal, underline, tilt and copy act on the page body), once. */
12
+ function injectDomCss(): void {
13
+ if (document.getElementById(STYLE_ID)) return;
14
+ const s = document.createElement('style');
15
+ s.id = STYLE_ID;
16
+ s.textContent = vkDom;
17
+ document.head.append(s);
18
+ }
19
+
20
+ type Motion = { create(container: Element, slug: string): { play(): Promise<unknown> | void } };
21
+
22
+ async function logoOnHover(root: ShadowRoot, product: Site): Promise<void> {
23
+ if (STATIC_MARK.has(product)) return;
24
+ const mark = root.getElementById('mark');
25
+ const brand = root.getElementById('brand');
26
+ if (!mark || !brand) return;
27
+ try {
28
+ await import('../vendor/logo-motion.js');
29
+ const M = (globalThis as { SJLLogoMotion?: Motion }).SJLLogoMotion;
30
+ if (!M) return;
31
+ const box = document.createElement('div');
32
+ box.style.cssText = 'width:100%;height:100%';
33
+ const logo = M.create(box, product);
34
+ mark.replaceChildren(box);
35
+ let busy = false;
36
+ brand.addEventListener('pointerenter', () => {
37
+ if (busy) return;
38
+ busy = true;
39
+ Promise.resolve(logo.play()).finally(() => (busy = false));
40
+ });
41
+ } catch { /* the static mark stays */ }
42
+ }
43
+
44
+ /** The lab's Facet mark: a small turn and lift, as if catching the light. */
45
+ function facetOnHover(root: ShadowRoot): void {
46
+ const s = document.createElement('style');
47
+ s.textContent = `#mark svg{transition:transform .45s cubic-bezier(.3,1.6,.5,1),filter .45s}
48
+ #brand:hover #mark svg,#brand:focus-visible #mark svg{transform:rotate(-10deg) scale(1.1);filter:drop-shadow(0 2px 6px color-mix(in srgb,var(--sjl-c) 55%,transparent))}`;
49
+ root.append(s);
50
+ }
51
+
52
+ export function mountMicro(opts: { product: Site; header?: ShadowRoot | null }): void {
53
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
54
+ injectDomCss();
55
+ const { header } = opts;
56
+ if (header) {
57
+ if (opts.product === 'lab') facetOnHover(header); // the brand motion has no lab mark
58
+ else void logoOnHover(header, opts.product);
59
+ const s = document.createElement('style');
60
+ s.textContent = vkDom.split('\n').filter((l) => l.startsWith('.vk-mag')).join('\n');
61
+ header.append(s);
62
+ }
63
+
64
+ // list items reveal one by one (a grid of cards staggers in, not as one block)
65
+ const hero = document.querySelector('h1')?.closest('section') ?? null;
66
+ const targets = [...document.querySelectorAll('section h2, section h3, section p, section pre, section ul > li, section ol > li')]
67
+ .filter((el) => !hero?.contains(el) && !el.closest('header, footer, nav, figure'));
68
+ revealOnScroll(targets.filter((el) => !targets.some((t) => t !== el && t.contains(el))));
69
+
70
+ const ctas = [...document.querySelectorAll<HTMLElement>('a, button')]
71
+ .filter((el) => /^\s*get started\b/i.test(el.textContent ?? '') && (el.textContent ?? '').trim().length < 24 && !el.closest('header, footer'));
72
+ const headCta = header?.querySelector<HTMLElement>('.cta');
73
+ for (const el of headCta ? [...ctas, headCta] : ctas) magnetic(el);
74
+
75
+ document.querySelectorAll<HTMLButtonElement>('button').forEach((b) => {
76
+ if (/copy/i.test(`${b.textContent} ${b.getAttribute('aria-label') ?? ''} ${b.id}`)) copyFeedback(b);
77
+ });
78
+
79
+ underlineDraw(document);
80
+
81
+ if (hero) {
82
+ const text = document.querySelector('h1');
83
+ const grid = [hero, ...hero.querySelectorAll('*')].find((el) => el.children.length >= 2 && [...el.children].some((c) => c.contains(text)) && getComputedStyle(el).display === 'grid');
84
+ const demo = grid && [...grid.children].find((c) => !c.contains(text));
85
+ if (demo instanceof HTMLElement) tilt(demo);
86
+ }
87
+ }
@@ -0,0 +1,31 @@
1
+ // The latest release, fetched once per page from the suite worker on this site's own origin
2
+ // (/captain/releases/<product>, see worker/src/releases.ts), never from api.github.com: the
3
+ // worker holds the GitHub token and the cache. The build bakes in a release; this only brings a
4
+ // newer one without a rebuild. Silent on any failure: the built value stays.
5
+ import { SITES, type Site, type Slug } from '../data/products';
6
+
7
+ export interface LiveRelease { tag: string; url: string; published_at: string | null }
8
+
9
+ let pending: Promise<LiveRelease | null> | null = null;
10
+
11
+ export function liveRelease(slug: Site): Promise<LiveRelease | null> {
12
+ if (slug === 'lab' || !SITES[slug]?.repo) return Promise.resolve(null);
13
+ return (pending ??= (async () => {
14
+ try {
15
+ const r = await fetch(`/captain/releases/${slug as Slug}`, { headers: { accept: 'application/json' } });
16
+ if (!r.ok) return null;
17
+ const b = await r.json();
18
+ if (typeof b?.tag !== 'string' || !/^v?\d/.test(b.tag) || typeof b?.url !== 'string' || !b.url.startsWith('https://')) return null;
19
+ return { tag: b.tag, url: b.url, published_at: typeof b.published_at === 'string' ? b.published_at : null };
20
+ } catch {
21
+ return null;
22
+ }
23
+ })());
24
+ }
25
+
26
+ /** "Released Tue Oct 22 2026", for a title attribute. */
27
+ export const releasedOn = (r: LiveRelease): string | null => {
28
+ if (!r.published_at) return null;
29
+ const d = new Date(r.published_at);
30
+ return Number.isNaN(d.getTime()) ? null : `Released ${d.toDateString()}`;
31
+ };
@@ -0,0 +1,19 @@
1
+ export type Pref = 'system' | 'light' | 'dark';
2
+ export const PREF_KEY: string;
3
+ export function parsePref(v: unknown): Pref;
4
+ export function matchFragment(hash: string): Pref | null;
5
+ export interface ThemeEnv {
6
+ site: { key: string; values: { light: string; dark: string } };
7
+ read(key: string): string | null;
8
+ write(key: string, value: string | null): void;
9
+ systemLight(): boolean;
10
+ paint(siteValue: string, effective: 'light' | 'dark'): void;
11
+ }
12
+ export interface Theme {
13
+ get(): Pref;
14
+ effective(): 'light' | 'dark';
15
+ apply(): void;
16
+ set(p: Pref): void;
17
+ carry(): string;
18
+ }
19
+ export function createTheme(env: ThemeEnv): Theme;
@@ -0,0 +1,46 @@
1
+ // The suite theme logic, written once. theme.ts wraps it for the browser client; SuiteHead.astro
2
+ // inlines this same text (with `export` stripped) into the head script so the first paint is
3
+ // already themed. Keep it dependency-free and tiny: it ships on every page.
4
+ //
5
+ // Storage note: the suite preference lives in localStorage ('sjl-theme-pref') per origin and is
6
+ // carried to the next product as '#sjl-theme=<pref>'. We deliberately do not use vibekit's
7
+ // appearance cookie here: the products are on different domains, so a cookie cannot be shared.
8
+
9
+ export const PREF_KEY = 'sjl-theme-pref';
10
+ const FRAGMENT = /^#sjl-theme=(system|light|dark)$/;
11
+
12
+ export function parsePref(v) {
13
+ return v === 'light' || v === 'dark' ? v : 'system';
14
+ }
15
+
16
+ /** The carried preference if `hash` is exactly '#sjl-theme=…', else null. Never touches other hashes. */
17
+ export function matchFragment(hash) {
18
+ const m = FRAGMENT.exec(hash);
19
+ return m ? m[1] : null;
20
+ }
21
+
22
+ /**
23
+ * env: { site: { key, values: { light, dark } }, read(k), write(k, v|null), systemLight(): boolean,
24
+ * paint(siteValue, effective: 'light'|'dark') }
25
+ */
26
+ export function createTheme(env) {
27
+ // A visitor who chose a theme on the site before the suite preference existed keeps it.
28
+ const saved = env.read(PREF_KEY);
29
+ const legacy = env.read(env.site.key);
30
+ let pref = saved != null ? parsePref(saved)
31
+ : legacy === env.site.values.light ? 'light' : legacy === env.site.values.dark ? 'dark' : 'system';
32
+ const effective = () => (pref === 'system' ? (env.systemLight() ? 'light' : 'dark') : pref);
33
+ function apply() {
34
+ const t = effective();
35
+ env.write(PREF_KEY, pref);
36
+ env.write(env.site.key, pref === 'system' ? null : env.site.values[pref]);
37
+ env.paint(env.site.values[t], t);
38
+ }
39
+ return {
40
+ get: () => pref,
41
+ effective,
42
+ apply,
43
+ set(p) { pref = parsePref(p); apply(); },
44
+ carry: () => '#sjl-theme=' + pref,
45
+ };
46
+ }