// Typed API client surface. Three backends: // 1. phi's own bot endpoints (relative URLs: /api/activity, /api/memory/graph, /health) // 2. phi's PDS records (public, no auth) via bsky.social // 3. external services: bsky public API, hub discovery pool, top chicken market import { parseTrader, parseMarket, parseResults } from './chicken'; import type { ActivityItem, Atlas, BlogDoc, BskyFeedItem, CacheStability, Capability, ContextBudget, ContextPreview, ChickenResultRound, ChickenMarket, ChickenTrader, DiscoveryEntry, Docket, Goal, GraphData, HealthInfo, Skill, UserView, UserViewInteraction } from './types'; export const PHI_DID = 'did:plc:65sucjiel52gefhcdcypynsr'; export const PHI_HANDLE = 'phi.zzstoatzz.io'; export const OWNER_HANDLE = 'zzstoatzz.io'; const BSKY_PUBLIC = 'https://public.api.bsky.app'; const PDS_HOST = 'https://bsky.social'; interface PdsListRecordsResponse { records: { uri: string; cid: string; value: V }[]; cursor?: string; } async function listPdsRecords( repo: string, collection: string, limit = 50 ): Promise<{ uri: string; cid: string; value: V }[]> { const url = `${PDS_HOST}/xrpc/com.atproto.repo.listRecords?repo=${encodeURIComponent(repo)}&collection=${encodeURIComponent(collection)}&limit=${limit}`; const res = await fetch(url); if (!res.ok) throw new Error(`listRecords ${collection}: ${res.status}`); const data: PdsListRecordsResponse = await res.json(); return data.records; } function rkey(uri: string): string { return uri.split('/').pop() ?? ''; } // --- phi state from PDS --- export async function getGoals(): Promise { const records = await listPdsRecords<{ title: string; description: string; progress_signal: string; created_at: string; updated_at: string; }>(PHI_DID, 'io.zzstoatzz.phi.goal', 20); return records.map((r) => ({ rkey: rkey(r.uri), ...r.value })); } export async function getBlogDocs(limit = 50): Promise { const records = await listPdsRecords<{ title: string; content: string; tags?: string[]; publishedAt?: string; path?: string; }>(PHI_DID, 'app.greengale.document', limit); return records .map((r) => ({ rkey: rkey(r.uri), title: r.value.title, content: r.value.content, tags: r.value.tags ?? [], publishedAt: r.value.publishedAt ?? '', url: `https://greengale.app/${PHI_HANDLE}/${rkey(r.uri)}` })) .sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : -1)); } export async function getMentionConsent(): Promise { try { const records = await listPdsRecords<{ handles?: string[] }>( PHI_DID, 'io.zzstoatzz.phi.mentionConsent', 10 ); const set = new Set(); for (const r of records) { for (const h of r.value.handles ?? []) set.add(h); } return [...set].sort(); } catch { return []; } } // --- bot endpoints (relative URLs; same-origin in prod, vite-proxied in dev) --- export async function getActivity(): Promise { const res = await fetch('/api/activity'); if (!res.ok) throw new Error(`activity: ${res.status}`); return await res.json(); } export async function getMemoryGraph(): Promise { const res = await fetch('/api/memory/graph'); if (!res.ok) throw new Error(`memory graph: ${res.status}`); return await res.json(); } export async function getHealth(): Promise { const res = await fetch('/health'); if (!res.ok && res.status !== 503) throw new Error(`health: ${res.status}`); return await res.json(); } export async function getCapabilities(): Promise { const res = await fetch('/api/abilities'); if (!res.ok) throw new Error(`abilities: ${res.status}`); return await res.json(); } export async function getSkills(): Promise { const res = await fetch('/api/skills'); if (!res.ok) throw new Error(`skills: ${res.status}`); return await res.json(); } // phi's daily promotion docket — 5-15 work-item candidates emitted by the // `docket` Prefect flow after each atlas. The bot endpoint caches by PDS // record CID so a hot endpoint reuses the parsed JSON. Returns null when // no docket has been written yet (page renders an empty state). export async function getDocket(): Promise { const res = await fetch('/api/docket'); if (res.status === 404) return null; if (!res.ok) throw new Error(`docket: ${res.status}`); return await res.json(); } export async function getAtlas(): Promise { const res = await fetch('/api/atlas'); if (res.status === 404) return null; if (!res.ok) throw new Error(`atlas: ${res.status}`); return await res.json(); } export async function getUserView(handle: string): Promise { try { const res = await fetch(`/api/users/${encodeURIComponent(handle)}`); if (!res.ok) return null; const view: UserView = await res.json(); view.recent_interactions = parseUserInteractions(view.recent_interactions); return view; } catch { return null; } } function parseUserInteractions(value: unknown): UserViewInteraction[] | null { if (!Array.isArray(value)) return null; const items: unknown[] = value; const interactions: UserViewInteraction[] = []; for (const item of items) { if ( typeof item !== 'object' || item === null || !('id' in item) || typeof item.id !== 'string' || !('content' in item) || typeof item.content !== 'string' || !('created_at' in item) || (item.created_at !== null && typeof item.created_at !== 'string') || !('source_uris' in item) || !Array.isArray(item.source_uris) || !item.source_uris.every((uri: unknown): uri is string => typeof uri === 'string') ) return null; interactions.push({ id: item.id, content: item.content, created_at: item.created_at, source_uris: item.source_uris }); } return interactions; } // --- bsky public API --- export async function getBskyFeed(limit = 20): Promise { const url = `${BSKY_PUBLIC}/xrpc/app.bsky.feed.getAuthorFeed?actor=${PHI_DID}&filter=posts_with_replies&limit=${limit}`; const res = await fetch(url); if (!res.ok) throw new Error(`getAuthorFeed: ${res.status}`); const data: { feed: BskyFeedItem[] } = await res.json(); return data.feed; } // Phi's current profile description — the bio she rewrites at every startup. // Renders in the HudIdentity area as her own voice. export async function getPhiBio(): Promise { try { const url = `${BSKY_PUBLIC}/xrpc/app.bsky.actor.getProfile?actor=${PHI_DID}`; const res = await fetch(url); if (!res.ok) return null; const data: { description?: string } = await res.json(); return data.description ?? null; } catch { return null; } } // --- discovery pool --- // // frontend calls the bot's /api/discovery (NOT hub directly), so the public // page reflects the same filtered list phi sees in her prompt — operator // likes minus handles phi has already exchanged with. single source of // truth lives in bot/core/discovery_pool.py:get_filtered_pool. export async function getDiscoveryPool(): Promise { try { const res = await fetch('/api/discovery'); if (!res.ok) return []; return await res.json(); } catch { return []; } } // --- top chicken market --- // // topchicken.cee.wtf serves no CORS headers, so these reads go through the // bot's /api/chicken/* proxy (60s server-side cache; trader is pinned to // phi's DID there). export async function getChickenTrader(refresh = false): Promise { const res = await fetch(`/api/chicken/trader?refresh=${refresh}`, { cache: 'no-store' }); if (res.status === 404) return null; if (!res.ok) throw new Error(`Wallet unavailable (${res.status})`); return parseTrader(await res.json()); } export async function getChickenMarket(refresh = false): Promise { const res = await fetch(`/api/chicken/market?refresh=${refresh}`, { cache: 'no-store' }); if (!res.ok) throw new Error(`Season unavailable (${res.status})`); return parseMarket(await res.json()); } export async function getChickenResults(refresh = false): Promise { const res = await fetch(`/api/chicken/results?refresh=${refresh}`, { cache: 'no-store' }); if (!res.ok) throw new Error(`Round results unavailable (${res.status})`); return parseResults(await res.json()); } // --- prompt cache stability --- // // per-run cache read/write/uncached token accounting, straight from the // provider's usage numbers. this is the only check that phi's 1h tool + // instruction cache and 5m message cache are doing what agent.py claims. export async function getCacheStability(): Promise { try { const res = await fetch('/api/cache'); if (!res.ok) return null; return await res.json(); } catch { return null; } } // --- next-run context preview --- // // every prompt block rendered as a fresh scheduled run would compose it // right now. stateless on the backend; slow-ish (several blocks hit the // network), so callers should show a loading state. // the server keeps a snapshot; `refresh` asks it to recompose (slow, seconds) export type ContextBudgetReply = { kind: 'ready'; budget: ContextBudget } | { kind: 'computing' } | { kind: 'unavailable' }; export async function getContextBudget(refresh = false): Promise { try { const res = refresh ? await fetch('/api/context/budget/refresh', { method: 'POST' }) : await fetch('/api/context/budget'); if (res.status === 202) return { kind: 'computing' }; if (!res.ok) return { kind: 'unavailable' }; return { kind: 'ready', budget: await res.json() }; } catch { return { kind: 'unavailable' }; } } export async function getContextPreview(): Promise { try { const res = await fetch('/api/diagnostic/context'); if (!res.ok) return null; return await res.json(); } catch { return null; } }