Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

64.9 KB
Raw Blame
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Docs · three.ws</title>
		<meta name="description" content="Documentation for three.ws, the open-source platform for 3D AI agents." />
		<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
		<link rel="canonical" href="https://three.ws/docs" />
		<meta property="og:type" content="website" />
		<meta property="og:site_name" content="three.ws" />
		<meta property="og:url" content="https://three.ws/docs" />
		<meta property="og:title" content="Docs · three.ws" />
		<meta property="og:description" content="Full documentation: SDKs, API reference, embedding, agent system, smart contracts." />
		<meta property="og:image" content="https://three.ws/api/page-og?s=learn&amp;t=Docs&amp;d=Full+documentation%3A+SDKs%2C+API+reference%2C+embedding%2C+agent+system%2C+smart+contracts.&amp;p=%2Fdocs" />
		<meta property="og:image:width" content="1200" />
		<meta property="og:image:height" content="630" />
		<meta property="og:image:alt" content="three.ws documentation" />
		<meta name="twitter:card" content="summary_large_image" />
		<meta name="twitter:site" content="@trythreews" />
		<meta name="twitter:title" content="Docs · three.ws" />
		<meta name="twitter:description" content="Full documentation: SDKs, API reference, embedding, agent system, smart contracts." />
		<meta name="twitter:image" content="https://three.ws/api/page-og?s=learn&amp;t=Docs&amp;d=Full+documentation%3A+SDKs%2C+API+reference%2C+embedding%2C+agent+system%2C+smart+contracts.&amp;p=%2Fdocs" />
		<link rel="icon" href="/favicon.ico" />
		<link rel="preload" href="/fonts/inter-latin.woff2" as="font" type="font/woff2" crossorigin />
		<link rel="preload" href="/fonts/space-grotesk-latin.woff2" as="font" type="font/woff2" crossorigin />
		<!-- Both CDNs are on the critical path: cdnjs serves a render-blocking
		     stylesheet a few lines below, and jsdelivr serves marked. Without the
		     handshake started up here the browser only learns it needs a cdnjs
		     connection when the parser reaches that <link>, and pays DNS + TCP +
		     TLS before a single byte of the theme arrives. -->
		<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin />
		<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin />
		<link rel="stylesheet" href="/fonts/fonts.css" />
		<link rel="stylesheet" href="/style.css" />
		<link
			rel="stylesheet"
			href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css"
		/>
		<link rel="stylesheet" href="/docs-live.css" />
		<!-- Cookbook recipes and tutorials both use `figure:` directives, and both
		     render here as well as in the standalone viewers. Without the resolver
		     this shell paints <img src="figure:img:…">, which is a broken image and
		     an ERR_UNKNOWN_URL_SCHEME per figure. Same files the tutorial viewer
		     loads, so a figure looks identical on every surface. -->
		<link rel="stylesheet" href="/tutorial-figures.css" />
		<!-- All four are deferred so they stop blocking the parser; nothing here is
		     needed before the shell's boot, which waits for DOMContentLoaded (fired
		     only after every deferred script has executed). -->
		<script src="/tutorial-figures.js" defer></script>
		<script src="/model-viewer-meshopt.js" defer></script>
		<script src="https://cdn.jsdelivr.net/npm/[email protected]/marked.min.js" defer></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" defer></script>
		<style>
			:root {
				--sidebar-w: 268px;
				--header-h: 52px;
				--docs-accent: #8b5cf6;
				--docs-accent-soft: rgba(139, 92, 246, 0.12);
				--docs-bg: #09090f;
				--sidebar-bg: #0c0c13;
				--border: rgba(255, 255, 255, 0.07);
				/* 0.62 alpha, not 0.5: composited on --docs-bg #09090f that's 6.1:1
				   contrast (axe AA needs 4.5:1; 0.5 measured 4.32 and failed). */
				--text-muted: rgba(224, 224, 224, 0.62);
				--text-body: rgba(224, 224, 224, 0.85);
			}
			*,
			*::before,
			*::after {
				box-sizing: border-box;
			}
			html,
			body {
				margin: 0;
				padding: 0;
				height: auto;
				overflow: visible;
			}
			body {
				background: var(--docs-bg);
				color: #e0e0e0;
				font-family: var(--font-body);
				font-size: var(--text-base);
				line-height: 1.65;
				display: block;
			}

			/* ── Header ─────────────────────────────────── */
			.docs-header {
				position: fixed;
				top: 0;
				left: 0;
				right: 0;
				height: var(--header-h);
				background: rgba(9, 9, 15, 0.88);
				backdrop-filter: blur(16px);
				-webkit-backdrop-filter: blur(16px);
				border-bottom: 1px solid var(--border);
				display: flex;
				align-items: center;
				padding: 0 var(--space-lg);
				gap: var(--space-md);
				z-index: 100;
			}
			.docs-logo {
				font-family: var(--font-display);
				font-size: var(--text-lg);
				font-weight: 600;
				color: #fff;
				text-decoration: none;
				display: flex;
				align-items: center;
				gap: 7px;
				flex-shrink: 0;
			}
			.docs-logo-dot {
				width: 9px;
				height: 9px;
				border-radius: 50%;
				background: linear-gradient(135deg, #a78bfa 0%, #6366f1 100%);
				flex-shrink: 0;
			}
			.docs-logo-mark {
				width: 24px;
				height: 24px;
				flex-shrink: 0;
				filter: grayscale(1) contrast(1.05) brightness(1.08)
					drop-shadow(0 0 5px rgba(139, 92, 246, 0.45))
					drop-shadow(0 0 1px rgba(99, 102, 241, 0.55));
			}
			.docs-header-sep {
				width: 1px;
				height: 18px;
				background: var(--border);
				flex-shrink: 0;
			}
			.docs-header-label {
				font-size: var(--text-sm);
				color: var(--text-muted);
				font-family: var(--font-body);
			}
			.docs-header-right {
				margin-left: auto;
				display: flex;
				align-items: center;
				gap: var(--space-sm);
			}
			.docs-header-right a {
				font-size: var(--text-sm);
				color: var(--text-muted);
				text-decoration: none;
				padding: 4px 10px;
				border-radius: var(--radius-md);
				transition: color 0.15s, background 0.15s;
			}
			.docs-header-right a:hover {
				color: #fff;
				background: rgba(255, 255, 255, 0.05);
			}
			.docs-header-right .btn-primary {
				background: var(--docs-accent-soft);
				color: #c4b5fd;
				border: 1px solid rgba(139, 92, 246, 0.25);
			}
			.docs-header-right .btn-primary:hover {
				background: rgba(139, 92, 246, 0.2);
				color: #ddd6fe;
			}
			.docs-header-right .docs-world-link {
				display: inline-flex;
				align-items: center;
				gap: 5px;
				color: #c4b5fd;
				border: 1px solid rgba(139, 92, 246, 0.3);
				background: linear-gradient(120deg, rgba(139, 92, 246, 0.14), rgba(59, 130, 246, 0.1));
			}
			.docs-header-right .docs-world-link:hover {
				color: #ede9fe;
				border-color: rgba(139, 92, 246, 0.55);
				background: linear-gradient(120deg, rgba(139, 92, 246, 0.24), rgba(59, 130, 246, 0.18));
			}
			.docs-header-right .docs-world-link svg {
				opacity: 0.85;
			}
			@media (max-width: 560px) {
				.docs-header-right .docs-world-link span {
					display: none;
				}
			}
			/* Below ~760px the five site links stop fitting beside the logo. The
			   header is fixed, so the overflow was clipped off the right edge with
			   no scroll and no hint (an Android reader saw "Discover" cut to "D").
			   The secondary links move into the sidebar drawer, which is already
			   the mobile navigation surface, so nothing becomes unreachable. */
			@media (max-width: 760px) {
				.docs-header {
					padding: 0 var(--space-md);
					gap: var(--space-sm);
				}
				.docs-header-right .docs-header-more {
					display: none;
				}
			}
			/* Last resort for the narrowest devices (Fold-class outer screens):
			   drop the "Docs" label rather than let the logo and the nav collide. */
			@media (max-width: 340px) {
				.docs-header-sep,
				.docs-header-label {
					display: none;
				}
			}

			/* ── Shell ───────────────────────────────────── */
			.docs-shell {
				display: flex;
				padding-top: var(--header-h);
				min-height: 100vh;
			}

			/* ── Sidebar ─────────────────────────────────── */
			.docs-sidebar {
				position: fixed;
				top: var(--header-h);
				left: 0;
				bottom: 0;
				width: var(--sidebar-w);
				background: var(--sidebar-bg);
				border-right: 1px solid var(--border);
				overflow-y: auto;
				padding: var(--space-md) 0 var(--space-2xl);
				scrollbar-width: thin;
				scrollbar-color: rgba(255, 255, 255, 0.08) transparent;
			}
			.docs-sidebar::-webkit-scrollbar {
				width: 3px;
			}
			.docs-sidebar::-webkit-scrollbar-thumb {
				background: rgba(255, 255, 255, 0.08);
				border-radius: 2px;
			}

			/* Designed sidebar states: manifest load failed, or a search that
			   matched nothing. Both used to render an unexplained blank column. */
			.sidebar-empty {
				margin: var(--space-sm);
				padding: 14px;
				border: 1px solid var(--border);
				border-radius: var(--radius-md);
				background: rgba(255, 255, 255, 0.02);
			}
			.sidebar-empty p {
				margin: 0 0 8px;
				font-size: var(--text-sm);
				line-height: 1.5;
				color: rgba(255, 255, 255, 0.55);
			}
			.sidebar-empty-title {
				color: #ddd6fe !important;
				font-weight: 600;
			}
			.sidebar-empty-btn {
				display: inline-flex;
				align-items: center;
				margin-top: 2px;
				padding: 6px 12px;
				font: inherit;
				font-size: var(--text-sm);
				color: #c4b5fd;
				background: rgba(139, 92, 246, 0.12);
				border: 1px solid rgba(139, 92, 246, 0.3);
				border-radius: var(--radius-md);
				cursor: pointer;
				transition: background 0.15s, border-color 0.15s, color 0.15s;
			}
			.sidebar-empty-btn:hover:not(:disabled) {
				color: #ede9fe;
				background: rgba(139, 92, 246, 0.22);
				border-color: rgba(139, 92, 246, 0.55);
			}
			.sidebar-empty-btn:focus-visible {
				outline: 2px solid rgba(139, 92, 246, 0.7);
				outline-offset: 2px;
			}
			.sidebar-empty-btn:disabled {
				opacity: 0.6;
				cursor: default;
			}

			.sidebar-search {
				margin: 0 var(--space-sm) var(--space-md);
				position: relative;
			}
			.sidebar-search input {
				width: 100%;
				background: rgba(255, 255, 255, 0.04);
				border: 1px solid var(--border);
				border-radius: var(--radius-md);
				padding: 7px 10px 7px 32px;
				font-size: var(--text-sm);
				color: #ccc;
				outline: none;
				font-family: var(--font-body);
				transition: border-color 0.15s, background 0.15s;
			}
			.sidebar-search input::placeholder {
				color: rgba(255, 255, 255, 0.25);
			}
			.sidebar-search input:focus {
				border-color: rgba(139, 92, 246, 0.5);
				background: rgba(139, 92, 246, 0.05);
			}
			.sidebar-search-icon {
				position: absolute;
				left: 9px;
				top: 50%;
				transform: translateY(-50%);
				pointer-events: none;
				opacity: 0.35;
			}
			.sidebar-search kbd {
				position: absolute;
				right: 8px;
				top: 50%;
				transform: translateY(-50%);
				pointer-events: none;
				font: 600 10px/1 var(--font-mono, ui-monospace, monospace);
				color: rgba(255, 255, 255, 0.28);
				border: 1px solid var(--border);
				border-radius: 4px;
				padding: 3px 5px;
				transition: opacity 0.15s;
			}
			.sidebar-search input:focus ~ kbd,
			.sidebar-search input:not(:placeholder-shown) ~ kbd {
				opacity: 0;
			}

			/* Full-text results from the docs search index. Rendered above the
			   filtered page list because a content match is almost always what
			   someone typing a question is looking for. */
			.sidebar-results {
				margin: 0 var(--space-sm) var(--space-md);
			}
			.sidebar-results[hidden] {
				display: none;
			}
			.sidebar-results-head {
				display: flex;
				align-items: baseline;
				justify-content: space-between;
				gap: 8px;
				font-size: 10px;
				font-weight: 700;
				letter-spacing: 0.1em;
				text-transform: uppercase;
				color: rgba(255, 255, 255, 0.32);
				padding: 0 4px 6px;
			}
			.sidebar-hit {
				display: block;
				padding: 7px 9px;
				border-radius: var(--radius-md);
				text-decoration: none;
				border: 1px solid transparent;
				transition: background 0.12s, border-color 0.12s;
			}
			.sidebar-hit:hover,
			.sidebar-hit:focus-visible,
			.sidebar-hit[aria-selected='true'] {
				background: rgba(139, 92, 246, 0.1);
				border-color: rgba(139, 92, 246, 0.35);
				outline: none;
			}
			.sidebar-hit-title {
				display: block;
				font-size: var(--text-sm);
				color: #e6e6e6;
				line-height: 1.35;
			}
			.sidebar-hit-title mark {
				background: rgba(139, 92, 246, 0.28);
				color: #fff;
				border-radius: 2px;
				padding: 0 1px;
			}
			.sidebar-hit-doc {
				display: block;
				font-size: 11px;
				color: rgba(255, 255, 255, 0.38);
				margin-top: 2px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
			.sidebar-results-note {
				padding: 4px 5px 0;
				font-size: 11px;
				color: rgba(255, 255, 255, 0.34);
				line-height: 1.5;
			}

			.sidebar-section {
				margin-bottom: var(--space-md);
			}
			.sidebar-section-title {
				display: block;
				font-size: 10px;
				font-weight: 700;
				letter-spacing: 0.1em;
				text-transform: uppercase;
				/* 0.55 alpha, not 0.28: on --sidebar-bg #0c0c13 that's 6.3:1 (axe AA
				   needs 4.5:1 even for bold text this small; 0.28 measured 2.43). */
				color: rgba(255, 255, 255, 0.55);
				padding: 0 var(--space-sm) 5px var(--space-md);
			}
			.sidebar-link {
				display: block;
				padding: 5px var(--space-sm) 5px var(--space-md);
				font-size: 13.5px;
				color: rgba(255, 255, 255, 0.52);
				text-decoration: none;
				border-left: 2px solid transparent;
				transition: color 0.12s, background 0.12s, border-color 0.12s;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				line-height: 1.5;
			}
			.sidebar-link:hover {
				color: rgba(255, 255, 255, 0.9);
				background: rgba(255, 255, 255, 0.035);
			}
			.sidebar-link.active {
				color: #c4b5fd;
				border-left-color: var(--docs-accent);
				background: var(--docs-accent-soft);
				font-weight: 500;
			}
			.sidebar-link.external::after {
				content: '↗';
				font-size: 10px;
				margin-left: 4px;
				opacity: 0.5;
			}

			/* The site links the header drops on narrow screens. Hidden wherever
			   the header still shows them. Chips rather than four more rows,
			   because they sit above a list of 200+ doc links and must not push
			   the docs themselves off the first screen. */
			.sidebar-site {
				display: none;
				flex-wrap: wrap;
				gap: 6px;
				margin: 0 var(--space-sm) var(--space-md);
				padding-bottom: var(--space-md);
				border-bottom: 1px solid var(--border);
			}
			.sidebar-site a {
				display: inline-flex;
				align-items: center;
				min-height: 44px;
				padding: 4px 10px;
				font-size: var(--text-sm);
				color: rgba(255, 255, 255, 0.62);
				text-decoration: none;
				border: 1px solid var(--border);
				border-radius: var(--radius-md);
				background: rgba(255, 255, 255, 0.03);
				transition: color 0.15s, background 0.15s, border-color 0.15s;
			}
			.sidebar-site a:hover,
			.sidebar-site a:focus-visible {
				color: #fff;
				background: rgba(255, 255, 255, 0.07);
			}
			@media (max-width: 760px) {
				.sidebar-site {
					display: flex;
				}
			}

			/* ── Main ────────────────────────────────────── */
			.docs-main {
				flex: 1;
				/* A flex item's min-width is auto, so a wide table or code block
				   inside would stretch the column past the viewport and put a
				   horizontal scrollbar on the whole page. */
				min-width: 0;
				margin-left: var(--sidebar-w);
				padding: var(--space-2xl) clamp(var(--space-lg), 5vw, var(--space-2xl)) 100px;
			}
			.docs-content {
				max-width: 728px;
				margin-inline: auto;
			}

			/* Jumping to a section must not park it under the fixed header. */
			.docs-content :is(h2, h3, h4) {
				scroll-margin-top: 88px;
			}

			/* ── Markdown typography ─────────────────────── */
			.docs-content h1 {
				font-family: var(--font-display);
				font-weight: 500;
				font-size: clamp(var(--text-xl), 3vw, var(--text-2xl));
				letter-spacing: -0.03em;
				margin: 0 0 var(--space-sm);
				color: #fff;
				line-height: 1.2;
			}
			.docs-content h2 {
				font-family: var(--font-display);
				font-weight: 500;
				font-size: var(--text-xl);
				letter-spacing: -0.02em;
				margin: var(--space-2xl) 0 var(--space-sm);
				padding-bottom: var(--space-xs);
				border-bottom: 1px solid var(--border);
				color: #fff;
				line-height: 1.3;
			}
			.docs-content h2:first-child {
				margin-top: 0;
			}
			.docs-content h3 {
				font-weight: 600;
				font-size: var(--text-lg);
				margin: var(--space-xl) 0 var(--space-xs);
				color: #f0f0f0;
			}
			.docs-content h4 {
				font-weight: 600;
				font-size: var(--text-base);
				margin: var(--space-lg) 0 var(--space-xs);
				color: #ddd;
			}
			.docs-content p {
				color: var(--text-body);
				margin: 0 0 var(--space-md);
			}
			.docs-content ul,
			.docs-content ol {
				padding-left: var(--space-lg);
				margin: 0 0 var(--space-md);
			}
			.docs-content li {
				color: var(--text-body);
				margin-bottom: 4px;
			}
			.docs-content li > ul,
			.docs-content li > ol {
				margin-top: 4px;
				margin-bottom: 4px;
			}
			.docs-content a {
				color: #a78bfa;
				text-decoration: none;
				border-bottom: 1px solid rgba(167, 139, 250, 0.25);
				transition: color 0.12s, border-color 0.12s;
			}
			.docs-content a:hover {
				color: #c4b5fd;
				border-bottom-color: rgba(196, 181, 253, 0.5);
			}
			.docs-content strong {
				color: #fff;
				font-weight: 600;
			}
			.docs-content em {
				color: rgba(224, 224, 224, 0.75);
			}
			.docs-content code {
				font-family: var(--font-mono);
				font-size: 0.875em;
				background: rgba(139, 92, 246, 0.1);
				border: 1px solid rgba(139, 92, 246, 0.18);
				padding: 1px 5px;
				border-radius: 3px;
				color: #c4b5fd;
			}
			.docs-content pre {
				background: #0d0d18;
				border: 1px solid rgba(255, 255, 255, 0.07);
				border-radius: var(--radius-md);
				padding: var(--space-md);
				overflow-x: auto;
				margin: 0 0 var(--space-md);
				position: relative;
			}
			.docs-content pre code {
				background: transparent;
				border: none;
				padding: 0;
				color: inherit;
				font-size: var(--text-sm);
				line-height: 1.6;
			}
			.docs-content blockquote {
				border-left: 3px solid var(--docs-accent);
				margin: 0 0 var(--space-md);
				padding: var(--space-xs) var(--space-md);
				background: rgba(139, 92, 246, 0.06);
				border-radius: 0 var(--radius-md) var(--radius-md) 0;
			}
			.docs-content blockquote p {
				color: rgba(224, 224, 224, 0.7);
				margin: 0;
			}
			.docs-content table {
				width: 100%;
				border-collapse: collapse;
				margin: 0 0 var(--space-md);
				font-size: 13.5px;
				/* Reference tables are wider than a phone. Scroll the table inside
				   its own box rather than the whole page sideways. */
				display: block;
				overflow-x: auto;
			}
			.docs-content th {
				text-align: left;
				padding: 8px var(--space-sm);
				border-bottom: 1px solid rgba(255, 255, 255, 0.1);
				color: rgba(255, 255, 255, 0.45);
				font-weight: 600;
				font-size: 11px;
				letter-spacing: 0.06em;
				text-transform: uppercase;
			}
			.docs-content td {
				padding: 9px var(--space-sm);
				border-bottom: 1px solid rgba(255, 255, 255, 0.04);
				color: var(--text-body);
				vertical-align: top;
			}
			.docs-content tr:last-child td {
				border-bottom: none;
			}
			.docs-content hr {
				border: none;
				border-top: 1px solid var(--border);
				margin: var(--space-xl) 0;
			}
			.docs-content img {
				max-width: 100%;
				border-radius: var(--radius-md);
				border: 1px solid var(--border);
			}

			/* ── Loading state ───────────────────────────── */
			.docs-loading {
				display: flex;
				align-items: center;
				gap: var(--space-sm);
				color: var(--text-muted);
				font-size: var(--text-sm);
				padding: var(--space-2xl) 0;
			}
			.docs-loading-dot {
				width: 6px;
				height: 6px;
				border-radius: 50%;
				background: var(--docs-accent);
				animation: blink 1s ease-in-out infinite;
			}
			@keyframes blink {
				0%,
				100% {
					opacity: 0.15;
				}
				50% {
					opacity: 1;
				}
			}

			/* ── Missing / unreadable article ─────────────
			   A hash route the reader typed (or an old link) can name a page that
			   no longer exists, and the network can fail mid-fetch. Both used to
			   render one gray line of text with nowhere to go. */
			.docs-notfound {
				max-width: 44rem;
				margin: var(--space-2xl) 0;
				padding: var(--space-lg);
				border: 1px solid var(--border);
				border-radius: var(--radius-lg);
				background: rgba(255, 255, 255, 0.02);
			}
			.docs-notfound h2 {
				margin: 0 0 8px;
				font-size: var(--text-lg);
				font-weight: 600;
				color: #ddd6fe;
				border: none;
				padding: 0;
			}
			.docs-notfound p {
				margin: 0 0 var(--space-md);
				font-size: var(--text-sm);
				line-height: 1.6;
				color: rgba(255, 255, 255, 0.55);
			}
			.docs-notfound code {
				color: rgba(255, 255, 255, 0.8);
				word-break: break-all;
			}
			.docs-notfound-actions {
				display: flex;
				flex-wrap: wrap;
				gap: var(--space-sm);
			}
			.docs-notfound-btn {
				display: inline-flex;
				align-items: center;
				padding: 7px 14px;
				font: inherit;
				font-size: var(--text-sm);
				text-decoration: none;
				color: #c4b5fd;
				background: rgba(139, 92, 246, 0.12);
				border: 1px solid rgba(139, 92, 246, 0.3);
				border-radius: var(--radius-md);
				cursor: pointer;
				transition: background 0.15s, border-color 0.15s, color 0.15s;
			}
			.docs-notfound-btn:hover {
				color: #ede9fe;
				background: rgba(139, 92, 246, 0.22);
				border-color: rgba(139, 92, 246, 0.55);
			}
			.docs-notfound-btn:active {
				background: rgba(139, 92, 246, 0.3);
			}
			.docs-notfound-btn:focus-visible {
				outline: 2px solid rgba(139, 92, 246, 0.7);
				outline-offset: 2px;
			}

			/* ── Prev/Next nav ───────────────────────────── */
			.docs-pager {
				display: grid;
				grid-template-columns: 1fr 1fr;
				gap: var(--space-sm);
				margin-top: var(--space-2xl);
				padding-top: var(--space-xl);
				border-top: 1px solid var(--border);
			}
			.docs-pager-btn {
				display: flex;
				flex-direction: column;
				gap: 3px;
				padding: var(--space-sm) var(--space-md);
				background: rgba(255, 255, 255, 0.025);
				border: 1px solid var(--border);
				border-radius: var(--radius-md);
				text-decoration: none;
				transition: background 0.15s, border-color 0.15s;
				color: inherit;
			}
			.docs-pager-btn:hover {
				background: rgba(255, 255, 255, 0.05);
				border-color: rgba(255, 255, 255, 0.12);
				border-bottom-color: rgba(255, 255, 255, 0.12);
			}
			.docs-pager-btn .pager-dir {
				font-size: 10px;
				text-transform: uppercase;
				letter-spacing: 0.08em;
				color: var(--text-muted);
			}
			.docs-pager-btn .pager-title {
				font-size: var(--text-sm);
				font-weight: 500;
				color: #e0e0e0;
			}
			.docs-pager-btn.next {
				text-align: right;
			}
			.docs-pager-btn.placeholder {
				visibility: hidden;
			}

			/* ── Mobile toggle ───────────────────────────── */
			.sidebar-fab {
				display: none;
				position: fixed;
				bottom: 22px;
				right: 22px;
				z-index: 200;
				background: var(--docs-accent);
				color: #fff;
				border: none;
				border-radius: 50%;
				width: 46px;
				height: 46px;
				cursor: pointer;
				align-items: center;
				justify-content: center;
				box-shadow: 0 4px 24px rgba(139, 92, 246, 0.45);
				transition: transform 0.15s;
			}
			.sidebar-fab:hover {
				transform: scale(1.06);
			}
			.sidebar-overlay {
				display: none;
				position: fixed;
				inset: 0;
				background: rgba(0, 0, 0, 0.6);
				z-index: 140;
			}

			@media (max-width: 860px) {
				.docs-sidebar {
					transform: translateX(-100%);
					transition: transform 0.22s cubic-bezier(0.4, 0, 0.2, 1);
					z-index: 150;
					box-shadow: 4px 0 32px rgba(0, 0, 0, 0.5);
				}
				.docs-sidebar.open {
					transform: translateX(0);
				}
				.docs-main {
					margin-left: 0;
					padding: var(--space-lg) var(--space-md) 80px;
				}
				.sidebar-fab {
					display: flex;
				}
				.sidebar-overlay.visible {
					display: block;
				}
			}

			/* highlight.js override */
			.hljs {
				background: transparent !important;
				padding: 0 !important;
			}
			/* atom-one-dark comments ship as #5c6370, which is 3.13:1 against
			   the code-block background below and fails AA. Comments carry the
			   explanation in most of our samples, so they get a readable tone
			   rather than a decorative one. */
			.hljs-comment,
			.hljs-quote {
				color: #7d8496 !important;
			}

			/* Anchor IDs — offset for fixed header */
			.docs-content h2[id],
			.docs-content h3[id],
			.docs-content h4[id] {
				scroll-margin-top: calc(var(--header-h) + 16px);
			}

			/* ── Copy page control ───────────────────────── */
			.docs-content {
				position: relative;
			}
			.docs-pagetools {
				position: absolute;
				top: 0;
				right: 0;
				z-index: 20;
			}
			/* The freshness banner host sits between the pagetools and the H1.
			   When the banner renders, it takes the clearance and pushes the
			   title below the buttons; when the host stays empty (doc not in
			   the freshness report), the title is effectively adjacent and
			   needs the clearance itself, or it runs under the Copy-page
			   control. */
			.docs-pagetools + h1,
			.docs-pagetools + div:empty + h1 {
				padding-right: 184px;
			}
			.docs-pagetools ~ div .doc-freshness {
				margin-right: 184px;
			}
			.docs-pagetools-group {
				display: inline-flex;
				align-items: stretch;
				border: 1px solid var(--border);
				border-radius: 9px;
				background: rgba(255, 255, 255, 0.025);
				overflow: visible;
				transition: border-color 0.15s ease, background 0.15s ease;
			}
			.docs-pagetools-group:hover {
				border-color: rgba(255, 255, 255, 0.14);
				background: rgba(255, 255, 255, 0.05);
			}
			.docs-pagetools-btn {
				display: inline-flex;
				align-items: center;
				gap: 7px;
				padding: 7px 12px;
				font-family: var(--font-body);
				font-size: var(--text-sm);
				font-weight: 500;
				color: var(--text-body);
				background: none;
				border: none;
				border-radius: 8px 0 0 8px;
				cursor: pointer;
				white-space: nowrap;
				transition: color 0.15s ease, background 0.15s ease;
			}
			.docs-pagetools-btn:hover {
				color: #fff;
				background: rgba(255, 255, 255, 0.04);
			}
			.docs-pagetools-btn svg {
				flex-shrink: 0;
			}
			.docs-pagetools-btn.copied {
				color: #34d399;
			}
			.docs-pagetools-caret {
				padding: 7px 9px;
				border-left: 1px solid var(--border);
				border-radius: 0 8px 8px 0;
			}
			.docs-pagetools-caret svg {
				transition: transform 0.18s ease;
			}
			.docs-pagetools-group.open .docs-pagetools-caret svg {
				transform: rotate(180deg);
			}
			.docs-pagetools-menu {
				position: absolute;
				top: calc(100% + 8px);
				right: 0;
				min-width: 288px;
				padding: 6px;
				background: #14141b;
				border: 1px solid var(--border);
				border-radius: 12px;
				box-shadow: 0 16px 48px rgba(0, 0, 0, 0.55);
				opacity: 0;
				transform: translateY(-6px);
				pointer-events: none;
				transition: opacity 0.16s ease, transform 0.16s ease;
			}
			.docs-pagetools-group.open .docs-pagetools-menu {
				opacity: 1;
				transform: translateY(0);
				pointer-events: auto;
			}
			.docs-pagetools-item {
				display: flex;
				align-items: center;
				gap: 12px;
				width: 100%;
				padding: 9px 10px;
				border-radius: 8px;
				background: none;
				border: none;
				text-align: left;
				text-decoration: none;
				color: inherit;
				cursor: pointer;
				transition: background 0.13s ease;
			}
			.docs-pagetools-item:hover {
				background: rgba(255, 255, 255, 0.05);
			}
			.docs-pagetools-item:focus-visible {
				outline: 2px solid var(--docs-accent);
				outline-offset: -2px;
			}
			.docs-pagetools-icon {
				display: grid;
				place-items: center;
				width: 34px;
				height: 34px;
				flex-shrink: 0;
				border: 1px solid var(--border);
				border-radius: 8px;
				color: var(--text-body);
				background: rgba(255, 255, 255, 0.02);
			}
			.docs-pagetools-text {
				display: flex;
				flex-direction: column;
				gap: 1px;
				min-width: 0;
			}
			.docs-pagetools-title {
				display: flex;
				align-items: center;
				gap: 5px;
				font-size: var(--text-sm);
				font-weight: 600;
				color: #fff;
			}
			.docs-pagetools-title svg {
				opacity: 0.45;
			}
			.docs-pagetools-sub {
				font-size: var(--text-xs);
				color: var(--text-muted);
			}
			@media (max-width: 640px) {
				.docs-pagetools {
					position: static;
					margin-bottom: var(--space-md);
				}
				.docs-pagetools + h1,
				.docs-pagetools + div:empty + h1 {
					padding-right: 0;
				}
				.docs-pagetools ~ div .doc-freshness {
					margin-right: 0;
				}
				.docs-pagetools-menu {
					left: 0;
					right: auto;
					min-width: 0;
					width: 100%;
				}
			}
		</style>
	
	<meta property="og:locale" content="en_US">
	<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Docs","description":"Full documentation: SDKs, API reference, embedding, agent system, smart contracts.","url":"https://three.ws/docs","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=learn&t=Docs&d=Full+documentation%3A+SDKs%2C+API+reference%2C+embedding%2C+agent+system%2C+smart+contracts.&p=%2Fdocs"}]}</script>
</head>
	<body>
		<header class="docs-header">
			<a href="/" class="docs-logo">
				<img src="/three.svg" class="docs-logo-mark" alt="" aria-hidden="true" width="24" height="24" />three.ws
			</a>
			<span class="docs-header-sep"></span>
			<span class="docs-header-label">Docs</span>
			<nav class="docs-header-right">
				<a href="/docs/world" class="docs-world-link" id="world-link" aria-label="3D world" title="Read these docs inside a walkable 3D world">
					<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="9" ry="3.6"/><path d="M12 3v18"/></svg>
					<span>3D world</span>
				</a>
				<a href="/widgets" class="docs-header-more">Widgets</a>
				<a href="/discover" class="docs-header-more">Discover</a>
				<a href="/app" class="docs-header-more">Launch app</a>
				<a href="/studio" class="btn-primary">Studio</a>
			</nav>
		</header>

		<div class="docs-shell">
			<aside class="docs-sidebar" id="sidebar">
				<div class="sidebar-search">
					<svg
						class="sidebar-search-icon"
						width="14"
						height="14"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						stroke-width="2.2"
					>
						<circle cx="11" cy="11" r="8" /><path d="m21 21-4.35-4.35" />
					</svg>
					<input
						type="text"
						id="search-input"
						placeholder="Search the docs…"
						autocomplete="off"
						spellcheck="false"
						role="combobox"
						aria-expanded="false"
						aria-controls="content-results"
						aria-autocomplete="list"
						aria-label="Search the documentation"
					/>
					<kbd>/</kbd>
				</div>
				<div
					class="sidebar-results"
					id="content-results"
					role="listbox"
					aria-label="Documentation content matches"
					hidden
				></div>
				<nav class="sidebar-site" aria-label="three.ws site">
					<a href="/widgets">Widgets</a>
					<a href="/discover">Discover</a>
					<a href="/app">Launch app</a>
				</nav>
				<nav id="sidebar-nav"></nav>
			</aside>

			<main class="docs-main">
				<div class="docs-content" id="docs-content">
					<!-- Static fallback for crawlers and no-JS readers; the runtime
					     markdown render replaces this node's contents wholesale. -->
					<h1>three.ws documentation</h1>
					<p>
						Guides and reference for building on three.ws: SDKs, the HTTP API,
						one-tag avatar embeds, the agent system, and smart contracts. Pick a
						topic from the sidebar, or start with
						<a href="/docs/start-here">Start here</a>.
					</p>
				</div>
			</main>
		</div>

		<div class="sidebar-overlay" id="sidebar-overlay"></div>
		<button class="sidebar-fab" id="sidebar-fab" aria-label="Open navigation">
			<svg
				width="20"
				height="20"
				fill="none"
				viewBox="0 0 24 24"
				stroke="currentColor"
				stroke-width="2"
			>
				<path d="M4 6h16M4 12h10M4 18h16" />
			</svg>
		</button>

		<script>
			// The sidebar manifest lives in /docs/nav.json: one source of truth shared
			// with the immersive 3D docs world at /docs/world. Loaded by the boot at
			// the bottom of this script; until then both stay empty.
			let NAV = [];
			let ALL_PAGES = [];
			// Non-null once a manifest load has failed, so buildSidebar can tell
			// "still loading" (blank, briefly) apart from "load failed" (designed).
			let navError = null;

			// The hash is the doc route, which means a plain "#section" link inside a
			// page would be read as "load the doc named section" and 404 the reader
			// out of the page they were reading. Section links therefore route as
			// "#<doc>@<section>": the doc part navigates, the part after @ scrolls.
			// One exception, for links written by hand and shared: on first load a
			// bare "#section" on a /docs/<doc> URL is that doc's section, not a doc.
			let booted = false;

			function currentRoute() {
				const hash = location.hash.slice(1).replace(/^\//, '');
				// Nested doc paths (docs/<topic>/chapters/<n>) are served by the same
				// shell, so the whole tail after /docs/ is the article path.
				const m = location.pathname.match(/^\/docs\/(.+?)\/?$/);
				const fromUrl = m ? m[1] : '';
				if (hash.includes('@')) {
					const at = hash.indexOf('@');
					return {
						path: hash.slice(0, at) || fromUrl || 'start-here',
						anchor: hash.slice(at + 1),
					};
				}
				if (hash) {
					if (!booted && fromUrl) return { path: fromUrl, anchor: hash };
					return { path: hash, anchor: '' };
				}
				return { path: fromUrl || 'start-here', anchor: '' };
			}

			function currentPath() {
				return currentRoute().path;
			}

			function slugifyHeading(text) {
				return (text || '')
					.trim()
					.toLowerCase()
					.replace(/[^\w\- ]+/g, '')
					.replace(/ /g, '-');
			}

			// Returns whether the anchor actually matched something on the page, so a
			// caller can tell "scrolled to the heading" from "there is no such
			// heading here" and decide what the hash meant instead.
			function scrollToAnchor(anchor) {
				if (!anchor) {
					window.scrollTo({ top: 0 });
					return true;
				}
				let target = document.getElementById(anchor);
				if (!target) {
					// Older docs carry hand-written anchors that punctuate differently
					// from the slug. Match on letters and digits alone before giving up.
					const loose = s => s.toLowerCase().replace(/[^a-z0-9]+/g, '');
					const want = loose(anchor);
					target = [...document.querySelectorAll('#docs-content h2, #docs-content h3, #docs-content h4')].find(
						h => loose(h.id) === want || loose(h.textContent) === want,
					);
				}
				if (target) target.scrollIntoView({ block: 'start' });
				else window.scrollTo({ top: 0 });
				return Boolean(target);
			}

			// Does /docs/<slug>.md exist? Used only to disambiguate a hash that named
			// neither a heading on this page nor a doc the sidebar manifest lists. A
			// HEAD keeps it to headers; a network failure answers "no", which lands
			// the reader exactly where the old code left them.
			const docExistsCache = new Map();
			function docExists(slug) {
				if (!docExistsCache.has(slug)) {
					docExistsCache.set(
						slug,
						fetch('/docs/' + slug + '.md', { method: 'HEAD' })
							.then(res => res.ok)
							.catch(() => false),
					);
				}
				return docExistsCache.get(slug);
			}

			function buildSidebar(filter) {
				const q = (filter || '').toLowerCase();
				const current = currentPath();
				const nav = document.getElementById('sidebar-nav');
				// The manifest is a network fetch, so it has a real failure mode. An
				// empty sidebar reads as "this product has no docs" rather than "one
				// request failed", so say which it is and offer the way out. The
				// article itself still renders: only navigation depends on the manifest.
				if (!NAV.length && navError) {
					nav.innerHTML = '';
					const box = document.createElement('div');
					box.className = 'sidebar-empty';
					box.innerHTML =
						'<p class="sidebar-empty-title">Contents unavailable</p>' +
						'<p>The page list could not be loaded. The page you are reading is unaffected.</p>';
					const retry = document.createElement('button');
					retry.type = 'button';
					retry.className = 'sidebar-empty-btn';
					retry.textContent = 'Retry';
					retry.addEventListener('click', () => {
						retry.disabled = true;
						retry.textContent = 'Retrying…';
						loadNav();
					});
					box.appendChild(retry);
					nav.appendChild(box);
					return;
				}
				const matched = NAV.some(s => s.links.some(l => !q || l.label.toLowerCase().includes(q)));
				if (q && !matched) {
					nav.innerHTML = '';
					const box = document.createElement('div');
					box.className = 'sidebar-empty';
					box.innerHTML = '<p class="sidebar-empty-title">No matches</p>';
					const p = document.createElement('p');
					p.textContent = 'Nothing in the docs matches “' + filter + '”.';
					const clear = document.createElement('button');
					clear.type = 'button';
					clear.className = 'sidebar-empty-btn';
					clear.textContent = 'Clear search';
					clear.addEventListener('click', () => {
						const input = document.getElementById('search-input');
						input.value = '';
						input.focus();
						buildSidebar('');
					});
					box.append(p, clear);
					nav.appendChild(box);
					return;
				}
				nav.innerHTML = NAV.map(section => {
					const links = section.links.filter(
						l => !q || l.label.toLowerCase().includes(q),
					);
					if (!links.length) return '';
					return `<div class="sidebar-section">
						<span class="sidebar-section-title">${section.title}</span>
						${links
							.map(l => {
								const href = l.href || '#' + l.path;
								const active = !l.href && l.path === current ? ' active' : '';
								const external = l.external ? ' external' : '';
								const target = l.href ? ' target="_blank" rel="noopener"' : '';
								return `<a href="${href}" class="sidebar-link${active}${external}"${target}>${l.label}</a>`;
							})
							.join('')}
					</div>`;
				}).join('');
			}

			// Strip a leading YAML frontmatter block. Several docs are article
			// drafts that carry one (title, venue, tags, canonical URL), and marked
			// has no concept of frontmatter: it reads the opening `---` as a
			// thematic break and the closing `---` as a setext underline, so the
			// whole YAML block renders as a giant <h2> above the article. Removing
			// it here fixes the rendered page and the "Copy page" markdown in one
			// place; the raw .md link still serves the file with its frontmatter
			// intact, which is what a reader asking for the source wants.
			const FRONTMATTER = /^?---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
			function stripFrontmatter(md) {
				return md.replace(FRONTMATTER, '');
			}

			// marked/hljs arrive via deferred head scripts, so this must not run at
			// parse time; the boot below calls it once DOMContentLoaded guarantees
			// they have executed.
			function configureMarked() {
				marked.setOptions({
					highlight: (code, lang) => {
						if (lang && hljs.getLanguage(lang)) {
							return hljs.highlight(code, { language: lang }).value;
						}
						return hljs.highlightAuto(code).value;
					},
					gfm: true,
					breaks: false,
				});
			}

			const COPY_ICON =
				'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
			const CHECK_ICON =
				'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>';
			const EXTERNAL_ICON =
				'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17 17 7M9 7h8v8"/></svg>';

			function renderPageTools(path, md) {
				const content = document.getElementById('docs-content');
				const mdUrl = '/docs/' + path + '.md';
				const absMdUrl = 'https://three.ws' + mdUrl;
				const claudePrompt =
					'Read ' +
					absMdUrl +
					' so I can ask questions about this three.ws documentation page.';
				const claudeUrl =
					'https://claude.ai/new?q=' + encodeURIComponent(claudePrompt);

				const wrap = document.createElement('div');
				wrap.className = 'docs-pagetools';
				wrap.innerHTML = `
					<div class="docs-pagetools-group" id="pagetools-group">
						<button type="button" class="docs-pagetools-btn" id="pagetools-copy" title="Copy page as Markdown">
							${COPY_ICON}<span>Copy page</span>
						</button>
						<button type="button" class="docs-pagetools-caret" id="pagetools-caret" aria-label="More options" aria-haspopup="true" aria-expanded="false">
							<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
						</button>
						<div class="docs-pagetools-menu" role="menu">
							<button type="button" class="docs-pagetools-item" id="pagetools-copy-2" role="menuitem">
								<span class="docs-pagetools-icon">${COPY_ICON}</span>
								<span class="docs-pagetools-text">
									<span class="docs-pagetools-title">Copy page</span>
									<span class="docs-pagetools-sub">Copy page as Markdown for LLMs</span>
								</span>
							</button>
							<a class="docs-pagetools-item" href="${mdUrl}" target="_blank" rel="noopener" role="menuitem">
								<span class="docs-pagetools-icon">
									<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="5" width="20" height="14" rx="2.5"/><path d="M6 15V9l3 3 3-3v6" stroke-linecap="round" stroke-linejoin="round"/><path d="M17 9v6m0 0 2-2m-2 2-2-2" stroke-linecap="round" stroke-linejoin="round"/></svg>
								</span>
								<span class="docs-pagetools-text">
									<span class="docs-pagetools-title">View as Markdown ${EXTERNAL_ICON}</span>
									<span class="docs-pagetools-sub">View this page as plain text</span>
								</span>
							</a>
							<a class="docs-pagetools-item" href="${claudeUrl}" target="_blank" rel="noopener" role="menuitem">
								<span class="docs-pagetools-icon">
									<svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.4 13.9 8l5.7.2-4.5 3.5 1.6 5.5L12 14l-4.7 3.2 1.6-5.5L4.4 8.2 10.1 8 12 2.4Z"/></svg>
								</span>
								<span class="docs-pagetools-text">
									<span class="docs-pagetools-title">Open in Claude ${EXTERNAL_ICON}</span>
									<span class="docs-pagetools-sub">Ask questions about this page</span>
								</span>
							</a>
						</div>
					</div>`;
				content.prepend(wrap);

				const group = wrap.querySelector('#pagetools-group');
				const caret = wrap.querySelector('#pagetools-caret');
				const copyBtn = wrap.querySelector('#pagetools-copy');
				const copyBtn2 = wrap.querySelector('#pagetools-copy-2');

				const closeMenu = () => {
					group.classList.remove('open');
					caret.setAttribute('aria-expanded', 'false');
				};
				caret.addEventListener('click', e => {
					e.stopPropagation();
					const open = group.classList.toggle('open');
					caret.setAttribute('aria-expanded', String(open));
				});
				document.addEventListener('click', e => {
					if (!group.contains(e.target)) closeMenu();
				});
				document.addEventListener('keydown', e => {
					if (e.key === 'Escape') closeMenu();
				});

				let resetTimer;
				const label = copyBtn.querySelector('span');
				const doCopy = async () => {
					try {
						await navigator.clipboard.writeText(md);
					} catch {
						const ta = document.createElement('textarea');
						ta.value = md;
						ta.style.position = 'fixed';
						ta.style.opacity = '0';
						document.body.appendChild(ta);
						ta.select();
						document.execCommand('copy');
						document.body.removeChild(ta);
					}
					copyBtn.classList.add('copied');
					copyBtn.innerHTML = CHECK_ICON + '<span>Copied</span>';
					clearTimeout(resetTimer);
					resetTimer = setTimeout(() => {
						copyBtn.classList.remove('copied');
						copyBtn.innerHTML = COPY_ICON + '<span>Copy page</span>';
					}, 1800);
				};
				copyBtn.addEventListener('click', doCopy);
				copyBtn2.addEventListener('click', () => {
					doCopy();
					closeMenu();
				});
			}

			// Carries the HTTP status so the failure state can tell "this page does
			// not exist" apart from "the network dropped", which need different
			// answers: one is a wrong address, the other is worth retrying.
			class DocLoadError extends Error {
				constructor(status) {
					super('doc request failed with ' + status);
					this.status = status;
				}
			}

			function renderLoadFailure(content, path, anchor, err) {
				const missing = err instanceof DocLoadError && err.status === 404;
				const box = document.createElement('div');
				box.className = 'docs-notfound';
				const slug = path.split('/').pop() || path;
				box.innerHTML = missing
					? '<h2>This page does not exist</h2>' +
						'<p>No documentation lives at <code>/docs/' +
						escapeHtml(path) +
						'</code>. It may have been renamed, or the link that sent you here is out of date.</p>'
					: '<h2>This page could not load</h2>' +
						'<p>The request for <code>/docs/' +
						escapeHtml(path) +
						'.md</code> failed. Your connection may have dropped mid-fetch.</p>';

				const actions = document.createElement('div');
				actions.className = 'docs-notfound-actions';

				if (!missing) {
					const retry = document.createElement('button');
					retry.type = 'button';
					retry.className = 'docs-notfound-btn';
					retry.textContent = 'Try again';
					retry.addEventListener('click', () => loadPage(path, anchor));
					actions.appendChild(retry);
				}

				const start = document.createElement('a');
				start.className = 'docs-notfound-btn';
				start.href = '#start-here';
				start.textContent = 'Start here';
				actions.appendChild(start);

				const search = document.createElement('button');
				search.type = 'button';
				search.className = 'docs-notfound-btn';
				search.textContent = 'Search the docs';
				search.addEventListener('click', () => {
					const input = document.getElementById('search-input');
					input.value = slug.replace(/[-_]+/g, ' ');
					input.focus();
					input.dispatchEvent(new Event('input', { bubbles: true }));
				});
				actions.appendChild(search);

				const all = document.createElement('a');
				all.className = 'docs-notfound-btn';
				all.href = '/sitemap?q=' + encodeURIComponent(slug.replace(/[-_]+/g, ' '));
				all.textContent = 'Browse all pages';
				actions.appendChild(all);

				box.appendChild(actions);
				content.innerHTML = '';
				content.appendChild(box);
			}

			async function loadPage(path, anchor) {
				const content = document.getElementById('docs-content');
				content.innerHTML =
					'<div class="docs-loading"><span class="docs-loading-dot"></span> Loading…</div>';

				try {
					const url = '/docs/' + path + '.md';
					const res = await fetch(url);
					if (!res.ok) throw new DocLoadError(res.status);
					const md = stripFrontmatter(await res.text());

					// Turn `figure:` directives into inert slots BEFORE parsing. Left as
					// <img src="figure:…">, the browser fires a request the moment the
					// markup lands and logs ERR_UNKNOWN_URL_SCHEME for every figure.
					const html = marked.parse(
						window.tutorialFigures ? window.tutorialFigures.preprocess(md) : md,
					);
					content.innerHTML = html;

					// Fill those slots with the captured media, the live 3D viewers,
					// and the shared lightbox.
					window.tutorialFigures?.mount(content);

					// Freshness: has anyone checked this page against the code lately?
					// Mounted above the article, before the heavier enhancers, because
					// a reader deciding whether to trust the page should see it first.
					// Fails silently: a missing report must never cost the reader the
					// documentation itself.
					const freshHost = document.createElement('div');
					content.prepend(freshHost);
					import('/doc-freshness.js')
						.then((m) => m.mountBadge(freshHost, m.docPathForSlug(path)))
						.catch(() => freshHost.remove());

					// Markdown images become captioned, zoomable figures sized from
					// the media manifest, so the article never reflows on decode.
					window.DocFigures?.upgrade(content);

					renderPageTools(path, md);

					content.querySelectorAll('pre code').forEach(block => {
						hljs.highlightElement(block);
					});

					// Live Docs: samples that can be run become runnable in place
					// (public/docs-live.js). Loaded lazily on the first rendered
					// page so a reader who never scrolls to a code block never
					// pays for the runner; the module caches after that.
					import('/docs-live.js')
						.then(m => m.enhance(content))
						.catch(() => {
							/* Static samples still read correctly; the copy
							   buttons and highlighting above are unaffected. */
						});

					// Rewrite internal .md links → hash routing. Resolve each href
					// against the current doc's URL so relative links inside nested
					// docs (agent-abilities/chapters/…, tutorials/…) route to the
					// right file instead of being read as /docs-root paths.
					//
					// A link that resolves OUTSIDE /docs/ (e.g. ../../src/foo/README.md,
					// a reference to repo source) can never be fetched by this viewer.
					// Send those to GitHub rather than hash-routing them into a 404.
					const REPO = 'https://github.com/nirholas/three.ws/blob/main';
					// docs/internal, docs/ops and docs/security live in the repo but are
					// deliberately never copied into dist/docs (the copy-static-docs
					// plugin in vite.config.js filters them out): they name GCP projects,
					// service accounts and open security findings. A doc that cites one
					// is citing repo source, so it goes to GitHub like any other source
					// link. Hash-routing it would send the reader to a doc the site does
					// not serve: a 404 that only reproduces in production, because dev
					// serves the whole docs/ tree off disk.
					const REPO_ONLY_DOCS = new Set(['internal', 'ops', 'security']);
					const isRepoOnlyDoc = (abs) => REPO_ONLY_DOCS.has(abs.slice('/docs/'.length).split('/')[0]);
					content.querySelectorAll('a[href]').forEach(a => {
						if (a.closest('.docs-pagetools')) return;
						const h = a.getAttribute('href');
						if (!h || h.startsWith('http') || h.startsWith('mailto:')) return;
						// A section link inside the page: keep it on this doc.
						if (h.startsWith('#')) {
							a.href = '#' + path + '@' + h.slice(1);
							return;
						}
						// "guide.md#section" is one link, not two: split the heading off so a
						// cross-doc link that also targets a section routes to the doc AND
						// scrolls, instead of failing the .md test and rendering unrewritten.
						const hashAt = h.indexOf('#');
						const target = hashAt === -1 ? h : h.slice(0, hashAt);
						const section = hashAt === -1 ? '' : h.slice(hashAt + 1);
						if (target.endsWith('.md')) {
							const abs = new URL(target, location.origin + '/docs/' + path).pathname;
							if (abs.startsWith('/docs/') && !isRepoOnlyDoc(abs)) {
								const doc = abs.slice('/docs/'.length).replace(/\.md$/, '');
								a.href = '#' + doc + (section ? '@' + section : '');
							} else {
								a.href = REPO + abs + (section ? '#' + section : '');
								a.target = '_blank';
								a.rel = 'noopener';
							}
							return;
						}
						// A relative link to repo source (../api/_lib/x402-spec.js,
						// ../../scripts/deploy.mjs). Docs cite code constantly, and the
						// viewer serves docs, not the tree, so these resolve against
						// /docs/ into site paths that do not exist and 404 the reader.
						// Anything landing outside /docs/ goes to the file on GitHub.
						// Site-absolute links (/forge, /docs/img/x.png) are real routes and
						// are left alone.
						if (target.startsWith('.')) {
							const abs = new URL(target, location.origin + '/docs/' + path).pathname;
							if (!abs.startsWith('/docs/') || isRepoOnlyDoc(abs)) {
								a.href = REPO + abs + (section ? '#' + section : '');
								a.target = '_blank';
								a.rel = 'noopener';
							}
						}
					});

					// Add IDs to headings for anchor links. GitHub's slug rules, so a
					// link an author wrote against the file on GitHub resolves here too.
					content.querySelectorAll('h2, h3, h4').forEach(h => {
						if (!h.id) h.id = slugifyHeading(h.textContent);
					});

					// Prev / Next
					const idx = ALL_PAGES.findIndex(p => p.path === path);
					const prev = idx > 0 ? ALL_PAGES[idx - 1] : null;
					const next = idx < ALL_PAGES.length - 1 ? ALL_PAGES[idx + 1] : null;

					const pager = document.createElement('div');
					pager.className = 'docs-pager';
					pager.innerHTML = `
						${prev ? `<a href="#${prev.path}" class="docs-pager-btn prev"><span class="pager-dir">← Previous</span><span class="pager-title">${prev.label}</span></a>` : '<div class="docs-pager-btn placeholder"></div>'}
						${next ? `<a href="#${next.path}" class="docs-pager-btn next"><span class="pager-dir">Next →</span><span class="pager-title">${next.label}</span></a>` : '<div class="docs-pager-btn placeholder"></div>'}
					`;
					content.appendChild(pager);
				} catch (err) {
					renderLoadFailure(content, path, anchor, err);
				}

				// A cold load of /docs/<page>#<hash> is ambiguous. Usually the hash is
				// a heading on that page, which is why currentRoute() reads it that
				// way. But every in-body cross-doc link is rewritten to a doc-path
				// hash, so the URL a reader copies after clicking one (for example
				// /docs/payment-sessions#custody) means "open the custody doc". When
				// the hash matches no heading here but does name a real doc, follow
				// it, and rewrite the address bar to that doc's own path so the link
				// is shareable the next time.
				//
				// The sidebar manifest is NOT the test for "a real doc": it lists the
				// docs worth navigating to, not every doc that exists, and the body of
				// a doc routinely cites one it omits (financial-controls,
				// tutorials/pay-for-x402-service, agent-abilities/wallet/21-access).
				// Judging by the manifest alone stranded the reader on the page they
				// arrived from, with no error, for exactly those links. So fall back to
				// asking the server whether the doc is there. That costs one HEAD, and
				// only on the cold load that would otherwise have gone nowhere.
				const candidate = anchor && anchor !== path ? anchor : '';
				if (candidate && !scrollToAnchor(anchor)) {
					const listed = ALL_PAGES.find(p => p.path === candidate);
					if (listed || (await docExists(candidate))) {
						history.replaceState(null, '', '/docs/' + candidate);
						loadedPath = candidate;
						await loadPage(candidate, '');
						// The served <head> still describes the page in the URL we arrived
						// on, so the tab would name the wrong doc after this redirect.
						const label =
							(listed && listed.label) ||
							(document.querySelector('#docs-content h1') || {}).textContent ||
							candidate;
						document.title = 'Docs: ' + label.trim() + ' · three.ws';
						return;
					}
				}
				if (!candidate) scrollToAnchor(anchor);
				buildSidebar(document.getElementById('search-input').value);
			}

			let loadedPath = '';

			function navigate() {
				const { path, anchor } = currentRoute();
				booted = true;
				// The 3D-world button deep-links to the doc being read, so switching
				// surfaces never loses the reader's place.
				const worldLink = document.getElementById('world-link');
				if (worldLink) worldLink.href = '/docs/world#' + path;
				// Jumping between sections of the doc already on screen must not
				// refetch and rebuild it: that would lose the reader's place.
				if (path === loadedPath) {
					scrollToAnchor(anchor);
					return;
				}
				loadedPath = path;
				loadPage(path, anchor);
			}

			window.addEventListener('hashchange', navigate);

			// ── Full-text search over the docs corpus ────────────────────────────
			//
			// The sidebar filter has always matched page TITLES, which only helps a
			// reader who already knows what the page is called. The engine in
			// /docs-search.js answers the other question: "which page says this?" -
			// against an index of every heading and paragraph under docs/.
			//
			// It is loaded on the first keystroke, never on page load: the index is
			// ~1.4 MB and most readers arrive to read, not to search.
			const searchInput = document.getElementById('search-input');
			const resultsBox = document.getElementById('content-results');
			const MIN_QUERY = 2;
			const SEARCH_DEBOUNCE_MS = 90;
			const MAX_HITS = 8;

			let enginePromise = null;
			let searchTimer = null;
			let activeHit = -1;
			let lastQuery = '';

			function loadEngine() {
				if (enginePromise) return enginePromise;
				enginePromise = new Promise(resolve => {
					if (window.twsDocsSearch) return resolve(window.twsDocsSearch);
					const script = document.createElement('script');
					script.src = '/docs-search.js';
					script.onload = () => resolve(window.twsDocsSearch || null);
					// A missing engine degrades to title filtering, which is exactly
					// what this page did before. Nothing user-facing breaks.
					script.onerror = () => resolve(null);
					document.head.appendChild(script);
				}).then(async engine => {
					if (!engine) return null;
					const ok = await engine.ready();
					return ok ? engine : null;
				});
				return enginePromise;
			}

			function escapeHtml(text) {
				return String(text).replace(
					/[&<>"']/g,
					c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
				);
			}

			// Highlight the terms that actually earned the match, longest first so
			// "wallet" wins over "wall" and the shorter term cannot split the tag it
			// is nested inside.
			function highlight(text, matched) {
				const safe = escapeHtml(text);
				const terms = (matched || [])
					.filter(t => t && t.length >= MIN_QUERY)
					.sort((a, b) => b.length - a.length)
					.slice(0, 8)
					.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
				if (!terms.length) return safe;
				return safe.replace(new RegExp('(' + terms.join('|') + ')', 'gi'), '<mark>$1</mark>');
			}

			function clearResults() {
				resultsBox.hidden = true;
				resultsBox.innerHTML = '';
				searchInput.setAttribute('aria-expanded', 'false');
				searchInput.removeAttribute('aria-activedescendant');
				activeHit = -1;
			}

			function renderNote(message) {
				resultsBox.hidden = false;
				resultsBox.innerHTML = '<p class="sidebar-results-note">' + escapeHtml(message) + '</p>';
				searchInput.setAttribute('aria-expanded', 'false');
			}

			function renderHits(hits, query) {
				if (!hits.length) {
					renderNote('No content matches “' + query + '”. Matching page names are listed below.');
					return;
				}
				const head =
					'<div class="sidebar-results-head"><span>In page content</span><span>' +
					hits.length +
					'</span></div>';
				resultsBox.innerHTML =
					head +
					hits
						.map(
							(hit, i) =>
								'<a class="sidebar-hit" role="option" aria-selected="false" id="docs-hit-' +
								i +
								'" href="' +
								escapeHtml(hit.url) +
								'"><span class="sidebar-hit-title">' +
								highlight(hit.heading || hit.docTitle, hit.matched) +
								'</span><span class="sidebar-hit-doc">' +
								escapeHtml(hit.docTitle) +
								'</span></a>',
						)
						.join('');
				resultsBox.hidden = false;
				searchInput.setAttribute('aria-expanded', 'true');
				activeHit = -1;
				searchInput.removeAttribute('aria-activedescendant');
			}

			function moveActive(delta) {
				const rows = [...resultsBox.querySelectorAll('.sidebar-hit')];
				if (!rows.length) return false;
				if (activeHit >= 0 && rows[activeHit]) rows[activeHit].setAttribute('aria-selected', 'false');
				activeHit = (activeHit + delta + rows.length + 1) % (rows.length + 1);
				// The extra slot is "nothing selected", so ArrowUp from the first row
				// returns focus to the query rather than wrapping to the bottom.
				if (activeHit === rows.length) {
					activeHit = -1;
					searchInput.removeAttribute('aria-activedescendant');
					return true;
				}
				const row = rows[activeHit];
				row.setAttribute('aria-selected', 'true');
				row.scrollIntoView({ block: 'nearest' });
				searchInput.setAttribute('aria-activedescendant', row.id);
				return true;
			}

			async function runSearch(query) {
				const trimmed = query.trim();
				lastQuery = trimmed;
				if (trimmed.length < MIN_QUERY) {
					clearResults();
					return;
				}
				const engine = await loadEngine();
				// The reader kept typing while the index loaded; that keystroke's own
				// search is already on its way.
				if (lastQuery !== trimmed) return;
				if (!engine) {
					renderNote('Content search is unavailable. Page names still filter below.');
					return;
				}
				renderHits(engine.query(trimmed, MAX_HITS), trimmed);
			}

			searchInput.addEventListener('input', e => {
				const value = e.target.value;
				buildSidebar(value);
				clearTimeout(searchTimer);
				searchTimer = setTimeout(() => runSearch(value), SEARCH_DEBOUNCE_MS);
			});

			searchInput.addEventListener('keydown', e => {
				if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
					if (moveActive(e.key === 'ArrowDown' ? 1 : -1)) e.preventDefault();
					return;
				}
				if (e.key === 'Enter') {
					const row = resultsBox.querySelectorAll('.sidebar-hit')[activeHit];
					if (row) {
						e.preventDefault();
						row.click();
					}
					return;
				}
				if (e.key === 'Escape') {
					if (resultsBox.hidden && !searchInput.value) return;
					e.preventDefault();
					searchInput.value = '';
					buildSidebar('');
					clearResults();
				}
			});

			resultsBox.addEventListener('click', () => {
				// Navigation is by hash, so the result list would otherwise stay open
				// over the page the reader just chose.
				clearResults();
				if (window.innerWidth <= 860) {
					document.getElementById('sidebar').classList.remove('open');
					document.getElementById('sidebar-overlay').classList.remove('visible');
				}
			});

			// "/" is the near-universal focus-search shortcut. Ignored while the
			// reader is typing somewhere else, so it never swallows a real slash.
			document.addEventListener('keydown', e => {
				if (e.key !== '/' || e.metaKey || e.ctrlKey || e.altKey) return;
				const tag = (e.target.tagName || '').toLowerCase();
				if (tag === 'input' || tag === 'textarea' || e.target.isContentEditable) return;
				e.preventDefault();
				document.getElementById('sidebar').classList.add('open');
				searchInput.focus();
				searchInput.select();
			});

			// /docs?q=… runs the search on arrival, so a search result is a URL
			// someone can send to a colleague.
			const initialQuery = new URLSearchParams(location.search).get('q');
			if (initialQuery) {
				searchInput.value = initialQuery;
				runSearch(initialQuery);
			}

			const fab = document.getElementById('sidebar-fab');
			const sidebar = document.getElementById('sidebar');
			const overlay = document.getElementById('sidebar-overlay');

			fab.addEventListener('click', () => {
				sidebar.classList.add('open');
				overlay.classList.add('visible');
			});
			overlay.addEventListener('click', () => {
				sidebar.classList.remove('open');
				overlay.classList.remove('visible');
			});
			sidebar.addEventListener('click', e => {
				if (e.target.closest('.sidebar-link') && window.innerWidth <= 860) {
					sidebar.classList.remove('open');
					overlay.classList.remove('visible');
				}
			});

			async function loadNav() {
				try {
					const res = await fetch('/docs/nav.json');
					if (!res.ok) throw new Error(res.status);
					const nav = await res.json();
					NAV = Array.isArray(nav.sections) ? nav.sections : [];
					navError = NAV.length ? null : 'empty manifest';
				} catch (err) {
					// Content still loads without the manifest; only the sidebar and
					// prev/next pager degrade. buildSidebar renders the designed
					// failure state rather than an unexplained blank column.
					NAV = [];
					navError = String(err && err.message ? err.message : err);
				}
				ALL_PAGES = NAV.flatMap(s => s.links.filter(l => l.path));
				buildSidebar(document.getElementById('search-input').value);
				navigate();
			}
			function boot() {
				configureMarked();
				loadNav();
			}
			if (document.readyState === 'loading') {
				document.addEventListener('DOMContentLoaded', boot);
			} else {
				boot();
			}
		</script>

		<div id="footer-container"></div>
		<script src="/footer.js" defer></script>
	</body>
</html>