@vercel/geistdocs 1.26.1 → 1.27.0

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.
package/dist/cli/index.js CHANGED
@@ -4,4 +4,4 @@ import{program as F}from"commander";import{access as je,copyFile as Be}from"fs/p
4
4
  `);throw new AggregateError(s,`Mixedbread search sync did not complete:
5
5
  ${a}`)}return r},It=async({client:e,file:t,pollIntervalMs:n,pollTimeoutMs:r,sleep:s})=>{let i=t,o=Date.now()+r;for(;i.status==="pending"||i.status==="in_progress";){if(Date.now()>=o)throw new Error(`Mixedbread timed out while indexing file ${t.id}.`);await s(n),i=await e.retrieveStoreFile(t.id)}if(i.status!=="completed")throw new Error(`Mixedbread failed to index file ${t.id} (${i.status}).`);return i},Mt=async({client:e,desired:t,pollIntervalMs:n,pollTimeoutMs:r,sleep:s})=>{let i=await e.uploadFile({content:t.document.content,filename:`${L(t.document.id).slice(0,32)}.md`}),o;try{o=await e.createStoreFile({externalId:t.externalId,fileId:i,metadata:{...t.metadata,[g.rawFileId]:i}})}catch(a){try{await e.deleteFile(i)}catch(d){throw new AggregateError([a,d],`Mixedbread failed to attach and clean up raw file ${i}.`)}throw a}return It({client:e,file:o,pollIntervalMs:n,pollTimeoutMs:r,sleep:s})},xe=async({client:e,concurrency:t=ht,manifest:n,pollIntervalMs:r=wt,pollTimeoutMs:s=yt,revision:i,revisionAncestors:o=[],revisionTimestamp:a,sleep:d=Tt})=>{let c=we(n);if(c.provider!=="mixedbread")return{deleted:0,skipped:c.documents.length,uploaded:0};let u=c.siteId?.trim();if(!u)throw new Error("Mixedbread retrieval requires a non-empty siteId in geistdocs.tsx.");if(c.documents.length===0)throw new Error("The Geistdocs search export is empty. Refusing to remove indexed documents.");let l=c.documents.map(p=>Et(p,u,i,o,a)),m=new Map(l.map(p=>[p.document.id,p])),h=(await me(e)).flatMap(p=>{let y=K(p.metadata);return y?.siteId===u?[{file:p,metadata:y}]:[]}),x=new Map,v=new Set;for(let p of h){z(p.metadata,i,a)&&v.add(p.metadata.documentId);let y=m.get(p.metadata.documentId);y&&p.metadata.contentHash===y.hash&&p.file.status==="completed"&&!x.has(p.metadata.documentId)&&x.set(p.metadata.documentId,p)}let _=l.filter(p=>!(x.has(p.document.id)||v.has(p.document.id)));await fe(_,t,p=>Mt({client:e,desired:p,pollIntervalMs:r,pollTimeoutMs:s,sleep:d}));let b=(await me(e)).flatMap(p=>{let y=K(p.metadata);return y?.siteId===u?[{file:p,metadata:y}]:[]}),A=new Set(b.filter(({metadata:p})=>z(p,i,a)).map(({metadata:p})=>p.documentId)),se=new Set;for(let p of l){if(A.has(p.document.id))continue;let oe=b.filter(({file:V,metadata:k})=>V.status==="completed"&&k.documentId===p.document.id&&k.contentHash===p.hash).sort((V,k)=>V.file.id.localeCompare(k.file.id))[0];oe&&se.add(oe.file.id)}let ie=b.filter(({file:p,metadata:y})=>p.status!=="pending"&&p.status!=="in_progress"&&!z(y,i,a)&&_t({currentRevision:i,currentRevisionAncestors:o,currentRevisionTimestamp:a,desired:m.get(y.documentId),metadata:y})&&!se.has(p.id));return await fe(ie,t,async({file:p,metadata:y})=>{await e.deleteFile(y.rawFileId??p.id),await e.deleteStoreFile(p.id)}),{deleted:ie.length,skipped:l.length-_.length,uploaded:_.length}};var Rt=50,Pt=e=>`vercel integration add mixedbread --name docs-${e||"your-site-id"} --environment production`,be=(e,t)=>vt("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Dt=e=>{let t=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),n=[];try{n=be(e,["rev-list",`--max-count=${Rt+1}`,t||"HEAD"]).split(`
6
6
  `).filter(Boolean)}catch{n=[]}let r=t||n[0],s;for(let i of Array.from(new Set([r,"HEAD"].filter(Boolean))))try{let o=Number(be(e,["show","-s","--format=%ct",i]));if(Number.isFinite(o)){s=o;break}}catch{}return{revision:r,revisionAncestors:n.filter(i=>i!==r),revisionTimestamp:s}},Se=async({allowNonProduction:e=!1,dir:t=".next"}={})=>{let n=process.cwd();Ft.loadEnvConfig(n,!1);let r=process.env.MXBAI_API_KEY?.trim(),s=process.env.MXBAI_STORE_ID?.trim();if(process.env.VERCEL_ENV!=="production"&&!e){console.log("Geistdocs search sync skipped: this is not a production Vercel build.");return}if(!!r!=!!s)throw new Error("Mixedbread is partially configured. Set both MXBAI_API_KEY and MXBAI_STORE_ID.");let i;try{i=await ye({cwd:n,outputDirectory:t})}catch(a){if(!(r||s)){console.log("Geistdocs search sync skipped: no Mixedbread credentials or static search export were found.");return}throw a}if(i.provider!=="mixedbread"){console.log("Geistdocs search sync skipped: Ask AI uses local retrieval.");return}if(!(r&&s))throw new Error(["Mixedbread retrieval is enabled, but MXBAI_API_KEY or MXBAI_STORE_ID is missing.","From the root of this site's repository, linked to the correct Vercel project, run:",Pt(i.siteId)].join(`
7
- `));let o=await xe({client:pe({apiBaseUrl:process.env.MXBAI_BASE_URL,apiKey:r,storeId:s}),manifest:i,...Dt(n)});console.log(`Geistdocs search sync complete: ${o.uploaded} uploaded, ${o.deleted} deleted, ${o.skipped} unchanged.`)};import{readFileSync as At,writeFileSync as kt}from"fs";import{mkdir as Ct,readFile as Q,writeFile as $t}from"fs/promises";import{dirname as Ot,extname as Nt,relative as Ie,resolve as j}from"path";import{intro as Ut,isCancel as Lt,log as I,multiselect as Gt,outro as G,spinner as jt}from"@clack/prompts";import{glob as Bt}from"glob";import{Node as D,Project as Vt,SyntaxKind as Jt}from"ts-morph";var Ht="geistdocs.tsx",Xt="content/docs/**/*.mdx",Z=".translation-cache.json",W=8,Ee=()=>({version:1,entries:{}}),Yt=async e=>{let t=await Q(e),{createHash:n}=await import("crypto");return n("sha256").update(t).digest("hex")},Kt=e=>{let t=j(process.cwd(),e);return At(t,"utf8")},_e=e=>D.isObjectLiteralExpression(e)?e.getProperties().flatMap(t=>{if(D.isPropertyAssignment(t)){let n=t.getNameNode();if(D.isIdentifier(n)||D.isStringLiteral(n))return[n.getText().replaceAll(/['"]/g,"")]}return[]}).filter(Boolean):[],qt=e=>{try{let t=new Vt({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),n=Kt(e),i=t.createSourceFile(e,n,{overwrite:!0}).getVariableDeclarations().find(a=>a.getName()==="translations")?.getInitializer();if(!i)return[];if(D.isObjectLiteralExpression(i))return _e(i);let o=i.getFirstDescendantByKind(Jt.ObjectLiteralExpression);return o?_e(o):[]}catch(t){let n=t instanceof Error?t.message:`${t}`;return I.warn(`Failed to read locales from ${e}: ${n}`),[]}},zt=async()=>{let e=await Gt({message:"Which locales should be translated?",options:[{value:"cn",label:"Chinese (cn)"},{value:"jp",label:"Japanese (jp)"},{value:"es",label:"Spanish (es)"},{value:"fr",label:"French (fr)"},{value:"de",label:"German (de)"}],required:!0});return Lt(e)&&(G("Translation cancelled"),process.exit(0)),e},Wt=async e=>(await Bt(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),Qt=async()=>{let e=j(process.cwd(),Z);try{let t=await Q(e,"utf8"),n=JSON.parse(t);return n.version!==1||!n.entries?Ee():{version:1,entries:n.entries}}catch{return Ee()}},Te=e=>{let t=j(process.cwd(),Z),n=JSON.stringify(e,null,2);kt(t,n,"utf8")},Zt=async e=>{let t=await Promise.all(e.map(async n=>[n,await Yt(n)]));return Object.fromEntries(t)},en=(e,t)=>{let n=Nt(e);return`${e.slice(0,-n.length)}.${t}${n}`},Me=(e,t)=>`${Ie(process.cwd(),e)}::${t}`,tn=(e,t,n,r,s=!1)=>{let i=[],o=0;for(let a of t){let d=n[a];for(let c of e){let u=en(a,c),l=Me(a,c),m=r.entries[l];if(!s&&m?.hash===d){o+=1;continue}i.push({locale:c,sourceFile:a,sourceHash:d,targetFile:u})}}return{tasks:i,skippedCount:o}},nn=async e=>{await Ct(Ot(e),{recursive:!0})},rn=async(e,t,n)=>{let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,locale:n})});if(!r.ok){let i=await r.text();throw new Error(`API request failed (${r.status}): ${i}`)}let s=await r.json();if(!s.translation)throw new Error("API response did not include a translation");return s.translation},sn=async(e,t,n)=>{let r=await Q(e.sourceFile,"utf8"),s=await rn(t,r,e.locale);await nn(e.targetFile),await $t(e.targetFile,s,"utf8"),n.entries[Me(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},ve=async(e,t)=>{Ut("Translate MDX content");let n=e??Xt,r=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",s=qt(t.config??Ht),i=await Wt(n);i.length===0&&(I.error(`No MDX files found matching pattern: ${n}`),G("Translation cancelled"),process.exit(1)),I.info(`Found ${i.length} MDX file(s) matching pattern`),s.length===0&&(s=await zt());let o=j(process.cwd(),Z),a=await Qt();await Te(a),I.info(`Using cache: ${o}`);let d=await Zt(i),{tasks:c,skippedCount:u}=tn(s,i,d,a,t.force);if(c.length===0){I.success("All translations are up to date!"),G(`Skipped ${u} file(s) (unchanged)`);return}let l=[];for(let h=0;h<c.length;h+=W)l.push(c.slice(h,h+W));I.info(`Processing ${c.length} translation(s) in ${l.length} batch(es) of up to ${W}`),u>0&&I.info(`Skipped ${u} translation(s) (unchanged)`);let m=jt();m.start("Translating content...");let f=0;for(let h of l)await Promise.all(h.map(async x=>{await sn(x,r,a),f+=1,m.message(`Translated ${f}/${c.length}: ${Ie(process.cwd(),x.targetFile)}`)})),await Te(a);m.stop("Translation complete!"),G(`Created/updated ${c.length} file(s)`)};import{access as on,copyFile as an,mkdir as De,rm as ne}from"fs/promises";import{dirname as cn,join as M}from"path";import{intro as dn,log as w,outro as B,spinner as Ae}from"@clack/prompts";import{glob as ln}from"glob";var pn=["**/*"],un=["content/docs/**"],ee=".geistdocs-tmp",gn=async(e,t)=>{let n=M(e,t);await ne(n,{recursive:!0,force:!0}),await De(n,{recursive:!0})},te=async e=>await ne(e,{recursive:!0,force:!0}),Fe=async(e,t,n)=>(await ln(e,{cwd:n,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),mn=async e=>{try{return await on(e),!0}catch{return!1}},fn=async(e,t,n)=>{let r=M(t,e),s=M(n,e);return await mn(r)?(await an(r,s),{success:!0}):{success:!1,error:`Source file not found: ${r}`}},hn=async(e,t)=>{let n=M(t,e);return await ne(n,{force:!0}),{success:!0}},Re=20,Pe=async(e,t,n)=>{let r=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),o=await Promise.all(i.map(t));r.push(...o)}return r},wn=async(e,t,n,r,s)=>{let i={success:[],deleted:[],failed:[]},o=[...new Set(e.map(d=>cn(M(r,d))))];s.message(`Creating ${o.length} directories...`),await Promise.all(o.map(d=>De(d,{recursive:!0}))),s.message(`Updating ${e.length} files...`);let a=await Pe(e,async d=>{let c=await fn(d,n,r);return{file:d,...c}},Re);for(let{file:d,success:c,error:u}of a)c?i.success.push(d):i.failed.push({file:d,error:u??"Unknown error"});if(t.length>0){s.message(`Deleting ${t.length} files...`);let d=await Pe(t,async c=>{try{return await hn(c,r),{file:c,success:!0}}catch(u){let l=u instanceof Error?u.message:`${u}`;return{file:c,success:!1,error:l}}},Re);for(let c of d)c.success?i.deleted.push(c.file):i.failed.push({file:c.file,error:c.error})}return i},yn=e=>{if(e.success.length>0){w.success(`Successfully updated ${e.success.length} files:`);for(let t of e.success)w.info(` \u2713 ${t}`)}if(e.deleted.length>0){w.success(`Deleted ${e.deleted.length} files:`);for(let t of e.deleted)w.info(` \u{1F5D1} ${t}`)}if(e.failed.length>0){w.warn(`Failed to update ${e.failed.length} files:`);for(let{file:t,error:n}of e.failed)w.error(` \u2717 ${t}: ${n}`)}},xn=e=>e.includes("canary")?"canary":"latest",bn=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(E)}`);if(!t.ok)throw new Error(`Failed to resolve ${E}@${e}`);let r=(await t.json())["dist-tags"]?.[e];if(!r)throw new Error(`Could not find dist-tag ${e} for ${E}`);return r},Sn=async e=>{let t=await R(e),n=J(t,E);if(!n)return{currentVersion:n,nextVersion:void 0,updated:!1};let r=xn(n),s=await bn(r);return n===s?{currentVersion:n,nextVersion:s,updateTag:r,updated:!1}:(O(t,E,s),await $(e,t),{currentVersion:n,nextVersion:s,updateTag:r,updated:!0})},En=async(e,t,n)=>{let r=await R(e);if(!de(r,E))return!1;t&&t.length>0&&w.warn("Ignoring file patterns for a package-based site. This update will bump the package version instead."),n?.sync&&w.warn("Ignoring --sync for a package-based site. Runtime updates now come from the package version.");let{currentVersion:s,nextVersion:i,updateTag:o,updated:a}=await Sn(e);if(!a)return w.success(s?`@vercel/geistdocs is already at ${i} (${o}).`:"No package version update was needed."),B("Package-based site is already up to date."),!0;w.info(`Bumping ${E} from ${s} to ${i} (${o})`);let d=Ae();return d.start("Installing updated package version..."),await T("pnpm",["install"],{cwd:e}),d.stop("Package update complete!"),B("Please review and test the upgraded package version."),!0},_n=async(e,t,n,r,s)=>{let i=M(e,ee),o=Ae(),a=s?.sync?i:t;o.start("Preparing template snapshot..."),s?.sync&&(await gn(e,ee),await N(i)),o.message("Scanning for files...");let d=await Fe(n,r,a),c=[];if(s?.sync){o.message("Comparing with local files...");let l=await Fe(n,r,e),m=new Set(d);c=l.filter(f=>!m.has(f))}if(o.stop(`Found ${d.length} files to update`),d.length===0&&c.length===0){w.warn("No files matched the patterns. Nothing to update."),s?.sync&&await te(i),B("Update cancelled.");return}w.info(`Patterns: ${n.length}`),w.info(`Files to update: ${d.length}`),s?.sync&&w.info(`Files to delete: ${c.length}`),o.start("Updating files...");let u=await wn(d,c,a,e,o);s?.sync&&(o.message("Cleaning up..."),await te(i)),o.stop("Update complete!"),yn(u),B("Please review and test the changes carefully.")},ke=async(e,t)=>{let n=process.cwd(),r=H(),s=e&&e.length>0?e:pn,i=e&&e.length>0?[]:un;try{if(dn("Let's update your Geistdocs project!"),await En(n,e,t))return;w.info("Template source: bundled package snapshot"),e&&e.length>0&&w.info(`Updating specific files: ${e.join(", ")}`),t?.sync&&w.info("Sync mode enabled: will delete files removed from template"),await _n(n,r,s,i,t)}catch(o){let a=o instanceof Error?o.message:`${o}`;try{await te(M(n,ee))}catch{}w.error(`Failed to update project: ${a}`),process.exit(1)}};F.name("geistdocs").description("CLI for Geistdocs projects").version("1.26.1","-v, --version","Output the current version");F.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").option("--disable-git","Disable git initialization").action(le);F.command("update [files...]").description("Update a Geistdocs project (optionally specify files/patterns to update)").option("--sync","Delete local files that no longer exist in the template").action(ke);F.command("translate [pattern]").description("Translate MDX file(s) to one or more locales (default: content/docs/**/*.mdx)").option("--config <path>","Path to config file to load locales from (defaults to geistdocs.tsx)").option("--url <url>","Custom translation API URL (defaults to GEISTDOCS_TRANSLATE_URL or https://geistdocs.com/translate)").option("--force","Force re-translation of all files, ignoring cache").action(ve);var Tn=F.command("search").description("Manage the external search index used by Ask AI");Tn.command("sync").description("Sync the latest static docs export to Mixedbread").option("--dir <path>","Next.js output directory",".next").option("--allow-non-production","Run outside a production Vercel build").action(Se);await F.parseAsync(process.argv).catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});
7
+ `));let o=await xe({client:pe({apiBaseUrl:process.env.MXBAI_BASE_URL,apiKey:r,storeId:s}),manifest:i,...Dt(n)});console.log(`Geistdocs search sync complete: ${o.uploaded} uploaded, ${o.deleted} deleted, ${o.skipped} unchanged.`)};import{readFileSync as At,writeFileSync as kt}from"fs";import{mkdir as Ct,readFile as Q,writeFile as $t}from"fs/promises";import{dirname as Ot,extname as Nt,relative as Ie,resolve as j}from"path";import{intro as Ut,isCancel as Lt,log as I,multiselect as Gt,outro as G,spinner as jt}from"@clack/prompts";import{glob as Bt}from"glob";import{Node as D,Project as Vt,SyntaxKind as Jt}from"ts-morph";var Ht="geistdocs.tsx",Xt="content/docs/**/*.mdx",Z=".translation-cache.json",W=8,Ee=()=>({version:1,entries:{}}),Yt=async e=>{let t=await Q(e),{createHash:n}=await import("crypto");return n("sha256").update(t).digest("hex")},Kt=e=>{let t=j(process.cwd(),e);return At(t,"utf8")},_e=e=>D.isObjectLiteralExpression(e)?e.getProperties().flatMap(t=>{if(D.isPropertyAssignment(t)){let n=t.getNameNode();if(D.isIdentifier(n)||D.isStringLiteral(n))return[n.getText().replaceAll(/['"]/g,"")]}return[]}).filter(Boolean):[],qt=e=>{try{let t=new Vt({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),n=Kt(e),i=t.createSourceFile(e,n,{overwrite:!0}).getVariableDeclarations().find(a=>a.getName()==="translations")?.getInitializer();if(!i)return[];if(D.isObjectLiteralExpression(i))return _e(i);let o=i.getFirstDescendantByKind(Jt.ObjectLiteralExpression);return o?_e(o):[]}catch(t){let n=t instanceof Error?t.message:`${t}`;return I.warn(`Failed to read locales from ${e}: ${n}`),[]}},zt=async()=>{let e=await Gt({message:"Which locales should be translated?",options:[{value:"cn",label:"Chinese (cn)"},{value:"jp",label:"Japanese (jp)"},{value:"es",label:"Spanish (es)"},{value:"fr",label:"French (fr)"},{value:"de",label:"German (de)"}],required:!0});return Lt(e)&&(G("Translation cancelled"),process.exit(0)),e},Wt=async e=>(await Bt(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),Qt=async()=>{let e=j(process.cwd(),Z);try{let t=await Q(e,"utf8"),n=JSON.parse(t);return n.version!==1||!n.entries?Ee():{version:1,entries:n.entries}}catch{return Ee()}},Te=e=>{let t=j(process.cwd(),Z),n=JSON.stringify(e,null,2);kt(t,n,"utf8")},Zt=async e=>{let t=await Promise.all(e.map(async n=>[n,await Yt(n)]));return Object.fromEntries(t)},en=(e,t)=>{let n=Nt(e);return`${e.slice(0,-n.length)}.${t}${n}`},Me=(e,t)=>`${Ie(process.cwd(),e)}::${t}`,tn=(e,t,n,r,s=!1)=>{let i=[],o=0;for(let a of t){let d=n[a];for(let c of e){let u=en(a,c),l=Me(a,c),m=r.entries[l];if(!s&&m?.hash===d){o+=1;continue}i.push({locale:c,sourceFile:a,sourceHash:d,targetFile:u})}}return{tasks:i,skippedCount:o}},nn=async e=>{await Ct(Ot(e),{recursive:!0})},rn=async(e,t,n)=>{let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,locale:n})});if(!r.ok){let i=await r.text();throw new Error(`API request failed (${r.status}): ${i}`)}let s=await r.json();if(!s.translation)throw new Error("API response did not include a translation");return s.translation},sn=async(e,t,n)=>{let r=await Q(e.sourceFile,"utf8"),s=await rn(t,r,e.locale);await nn(e.targetFile),await $t(e.targetFile,s,"utf8"),n.entries[Me(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},ve=async(e,t)=>{Ut("Translate MDX content");let n=e??Xt,r=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",s=qt(t.config??Ht),i=await Wt(n);i.length===0&&(I.error(`No MDX files found matching pattern: ${n}`),G("Translation cancelled"),process.exit(1)),I.info(`Found ${i.length} MDX file(s) matching pattern`),s.length===0&&(s=await zt());let o=j(process.cwd(),Z),a=await Qt();await Te(a),I.info(`Using cache: ${o}`);let d=await Zt(i),{tasks:c,skippedCount:u}=tn(s,i,d,a,t.force);if(c.length===0){I.success("All translations are up to date!"),G(`Skipped ${u} file(s) (unchanged)`);return}let l=[];for(let h=0;h<c.length;h+=W)l.push(c.slice(h,h+W));I.info(`Processing ${c.length} translation(s) in ${l.length} batch(es) of up to ${W}`),u>0&&I.info(`Skipped ${u} translation(s) (unchanged)`);let m=jt();m.start("Translating content...");let f=0;for(let h of l)await Promise.all(h.map(async x=>{await sn(x,r,a),f+=1,m.message(`Translated ${f}/${c.length}: ${Ie(process.cwd(),x.targetFile)}`)})),await Te(a);m.stop("Translation complete!"),G(`Created/updated ${c.length} file(s)`)};import{access as on,copyFile as an,mkdir as De,rm as ne}from"fs/promises";import{dirname as cn,join as M}from"path";import{intro as dn,log as w,outro as B,spinner as Ae}from"@clack/prompts";import{glob as ln}from"glob";var pn=["**/*"],un=["content/docs/**"],ee=".geistdocs-tmp",gn=async(e,t)=>{let n=M(e,t);await ne(n,{recursive:!0,force:!0}),await De(n,{recursive:!0})},te=async e=>await ne(e,{recursive:!0,force:!0}),Fe=async(e,t,n)=>(await ln(e,{cwd:n,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),mn=async e=>{try{return await on(e),!0}catch{return!1}},fn=async(e,t,n)=>{let r=M(t,e),s=M(n,e);return await mn(r)?(await an(r,s),{success:!0}):{success:!1,error:`Source file not found: ${r}`}},hn=async(e,t)=>{let n=M(t,e);return await ne(n,{force:!0}),{success:!0}},Re=20,Pe=async(e,t,n)=>{let r=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),o=await Promise.all(i.map(t));r.push(...o)}return r},wn=async(e,t,n,r,s)=>{let i={success:[],deleted:[],failed:[]},o=[...new Set(e.map(d=>cn(M(r,d))))];s.message(`Creating ${o.length} directories...`),await Promise.all(o.map(d=>De(d,{recursive:!0}))),s.message(`Updating ${e.length} files...`);let a=await Pe(e,async d=>{let c=await fn(d,n,r);return{file:d,...c}},Re);for(let{file:d,success:c,error:u}of a)c?i.success.push(d):i.failed.push({file:d,error:u??"Unknown error"});if(t.length>0){s.message(`Deleting ${t.length} files...`);let d=await Pe(t,async c=>{try{return await hn(c,r),{file:c,success:!0}}catch(u){let l=u instanceof Error?u.message:`${u}`;return{file:c,success:!1,error:l}}},Re);for(let c of d)c.success?i.deleted.push(c.file):i.failed.push({file:c.file,error:c.error})}return i},yn=e=>{if(e.success.length>0){w.success(`Successfully updated ${e.success.length} files:`);for(let t of e.success)w.info(` \u2713 ${t}`)}if(e.deleted.length>0){w.success(`Deleted ${e.deleted.length} files:`);for(let t of e.deleted)w.info(` \u{1F5D1} ${t}`)}if(e.failed.length>0){w.warn(`Failed to update ${e.failed.length} files:`);for(let{file:t,error:n}of e.failed)w.error(` \u2717 ${t}: ${n}`)}},xn=e=>e.includes("canary")?"canary":"latest",bn=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(E)}`);if(!t.ok)throw new Error(`Failed to resolve ${E}@${e}`);let r=(await t.json())["dist-tags"]?.[e];if(!r)throw new Error(`Could not find dist-tag ${e} for ${E}`);return r},Sn=async e=>{let t=await R(e),n=J(t,E);if(!n)return{currentVersion:n,nextVersion:void 0,updated:!1};let r=xn(n),s=await bn(r);return n===s?{currentVersion:n,nextVersion:s,updateTag:r,updated:!1}:(O(t,E,s),await $(e,t),{currentVersion:n,nextVersion:s,updateTag:r,updated:!0})},En=async(e,t,n)=>{let r=await R(e);if(!de(r,E))return!1;t&&t.length>0&&w.warn("Ignoring file patterns for a package-based site. This update will bump the package version instead."),n?.sync&&w.warn("Ignoring --sync for a package-based site. Runtime updates now come from the package version.");let{currentVersion:s,nextVersion:i,updateTag:o,updated:a}=await Sn(e);if(!a)return w.success(s?`@vercel/geistdocs is already at ${i} (${o}).`:"No package version update was needed."),B("Package-based site is already up to date."),!0;w.info(`Bumping ${E} from ${s} to ${i} (${o})`);let d=Ae();return d.start("Installing updated package version..."),await T("pnpm",["install"],{cwd:e}),d.stop("Package update complete!"),B("Please review and test the upgraded package version."),!0},_n=async(e,t,n,r,s)=>{let i=M(e,ee),o=Ae(),a=s?.sync?i:t;o.start("Preparing template snapshot..."),s?.sync&&(await gn(e,ee),await N(i)),o.message("Scanning for files...");let d=await Fe(n,r,a),c=[];if(s?.sync){o.message("Comparing with local files...");let l=await Fe(n,r,e),m=new Set(d);c=l.filter(f=>!m.has(f))}if(o.stop(`Found ${d.length} files to update`),d.length===0&&c.length===0){w.warn("No files matched the patterns. Nothing to update."),s?.sync&&await te(i),B("Update cancelled.");return}w.info(`Patterns: ${n.length}`),w.info(`Files to update: ${d.length}`),s?.sync&&w.info(`Files to delete: ${c.length}`),o.start("Updating files...");let u=await wn(d,c,a,e,o);s?.sync&&(o.message("Cleaning up..."),await te(i)),o.stop("Update complete!"),yn(u),B("Please review and test the changes carefully.")},ke=async(e,t)=>{let n=process.cwd(),r=H(),s=e&&e.length>0?e:pn,i=e&&e.length>0?[]:un;try{if(dn("Let's update your Geistdocs project!"),await En(n,e,t))return;w.info("Template source: bundled package snapshot"),e&&e.length>0&&w.info(`Updating specific files: ${e.join(", ")}`),t?.sync&&w.info("Sync mode enabled: will delete files removed from template"),await _n(n,r,s,i,t)}catch(o){let a=o instanceof Error?o.message:`${o}`;try{await te(M(n,ee))}catch{}w.error(`Failed to update project: ${a}`),process.exit(1)}};F.name("geistdocs").description("CLI for Geistdocs projects").version("1.27.0","-v, --version","Output the current version");F.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").option("--disable-git","Disable git initialization").action(le);F.command("update [files...]").description("Update a Geistdocs project (optionally specify files/patterns to update)").option("--sync","Delete local files that no longer exist in the template").action(ke);F.command("translate [pattern]").description("Translate MDX file(s) to one or more locales (default: content/docs/**/*.mdx)").option("--config <path>","Path to config file to load locales from (defaults to geistdocs.tsx)").option("--url <url>","Custom translation API URL (defaults to GEISTDOCS_TRANSLATE_URL or https://geistdocs.com/translate)").option("--force","Force re-translation of all files, ignoring cache").action(ve);var Tn=F.command("search").description("Manage the external search index used by Ask AI");Tn.command("sync").description("Sync the latest static docs export to Mixedbread").option("--dir <path>","Next.js output directory",".next").option("--allow-non-production","Run outside a production Vercel build").action(Se);await F.parseAsync(process.argv).catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});
package/dist/config.d.ts CHANGED
@@ -192,6 +192,7 @@ export interface GeistdocsConfig {
192
192
  title: string;
193
193
  translations?: GeistdocsTranslations;
194
194
  versions?: GeistdocsVersionsConfig;
195
+ webmcp?: GeistdocsFeatureConfig;
195
196
  }
196
197
  export declare const defineConfig: <T extends GeistdocsConfig>(config: T) => T;
197
198
  //# sourceMappingURL=config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MA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AAsB,CAAC;IACtC,iBAAiB,CAAC,EAAE,yBAAyB,EAAE,CAAC;IAChD,aAAa,CAAC,EAAE,KAAK,GAAG,UAAU,CAAC;IACnC,WAAW,CAAC,EAAE,0BAA0B,CAAC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,sBAAsB,CAAC;IAChC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,2EAA2E;IAC3E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,KAAK,CAAC,EAAE,sBAAsB,CAAC;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,CAAC,EAAE,qBAAqB,CAAC;IACrC,QAAQ,CAAC,EAAE,uBAAuB,CAAC;IACnC,MAAM,CAAC,EAAE,sBAAsB,CAAC;CACjC;AAED,eAAO,MAAM,YAAY,GAAI,CAAC,SAAS,eAAe,EAAE,QAAQ,CAAC,KAAG,CAAW,CAAC"}
@@ -30,7 +30,7 @@ export const ChatPromptInput = ({ onChange, onStop, onSubmit, status, textareaRe
30
30
  else if (status === "error") {
31
31
  icon = _jsx(XIcon, { className: "size-4" });
32
32
  }
33
- return (_jsx("form", { onSubmit: onSubmit, children: _jsxs(InputGroup, { children: [_jsx(InputGroupTextarea, { className: cn("field-sizing-content max-h-48 min-h-16"), maxLength: 1000, name: "message", onChange: (event) => onChange(event.currentTarget.value), onCompositionEnd: () => setIsComposing(false), onCompositionStart: () => setIsComposing(true), onKeyDown: handleKeyDown, placeholder: "What would you like to know?", ref: textareaRef, value: value }), _jsxs(InputGroupAddon, { align: "block-end", className: "justify-between gap-1", children: [_jsxs("p", { className: "text-gray-800 text-xs", children: [value.length, " / 1000"] }), _jsx(InputGroupButton, { "aria-label": isGenerating ? "Stop" : "Submit", onClick: isGenerating && onStop
33
+ return (_jsx("form", { onSubmit: onSubmit, children: _jsxs(InputGroup, { children: [_jsx(InputGroupTextarea, { className: cn("field-sizing-content max-h-48 min-h-16"), maxLength: 1000, name: "message", onChange: (event) => onChange(event.currentTarget.value), onCompositionEnd: () => setIsComposing(false), onCompositionStart: () => setIsComposing(true), onKeyDown: handleKeyDown, placeholder: "What would you like to know?", ref: textareaRef, value: value }), _jsxs(InputGroupAddon, { align: "block-end", className: "justify-between gap-1", children: [_jsxs("p", { className: "text-gray-900 text-xs", children: [value.length, " / 1000"] }), _jsx(InputGroupButton, { "aria-label": isGenerating ? "Stop" : "Submit", onClick: isGenerating && onStop
34
34
  ? (event) => {
35
35
  event.preventDefault();
36
36
  onStop();
@@ -1 +1 @@
1
- {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/shell.tsx"],"names":[],"mappings":"AAqXA,eAAO,MAAM,kBAAkB,sDAgE9B,CAAC"}
1
+ {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/shell.tsx"],"names":[],"mappings":"AAsaA,eAAO,MAAM,kBAAkB,sDAkF9B,CAAC"}
@@ -3,7 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
3
3
  import { useChat } from "@ai-sdk/react";
4
4
  import { DefaultChatTransport } from "ai";
5
5
  import { useLiveQuery } from "dexie-react-hooks";
6
- import { ChevronRightIcon, Trash } from "lucide-react";
6
+ import { ChevronRightIcon, Maximize2Icon, Minimize2Icon, Trash, } from "lucide-react";
7
7
  import { catchError } from "next/error";
8
8
  import { usePathname } from "next/navigation";
9
9
  import { Portal } from "radix-ui";
@@ -90,7 +90,7 @@ const useChatPersistence = (title) => {
90
90
  clearMessages,
91
91
  };
92
92
  };
93
- const GeistdocsChatInner = ({ isOpen }) => {
93
+ const GeistdocsChatInner = ({ isExpanded = false, isOpen, onExpandedChange, }) => {
94
94
  const id = useId();
95
95
  const pathname = usePathname();
96
96
  const textareaRef = useRef(null);
@@ -167,22 +167,33 @@ const GeistdocsChatInner = ({ isOpen }) => {
167
167
  if (isLoading) {
168
168
  return (_jsx("div", { className: "flex size-full w-full flex-col items-center justify-center overflow-hidden whitespace-nowrap rounded-xl xl:max-w-md xl:border xl:bg-background-100", children: _jsx(Spinner, {}) }));
169
169
  }
170
- return (_jsxs("aside", { "aria-label": "Ask AI chat", className: "flex size-full w-full flex-col overflow-hidden whitespace-nowrap bg-background-100", children: [_jsxs("div", { className: "flex items-center justify-between px-4 py-2.5", children: [_jsx("h2", { className: "font-semibold text-sm", children: "Chat" }), _jsx("div", { className: "flex items-center gap-3", children: _jsxs(ButtonGroup, { children: [_jsx(CopyChat, { messages: messages }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { "aria-label": "Clear chat", disabled: messages.length === 0, onClick: handleClearChat, size: "icon-sm", variant: "ghost", children: _jsx(Trash, { className: "size-3.5" }) }) }), _jsx(TooltipContent, { children: "Clear chat" })] }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { "aria-label": "Close chat", onClick: () => setIsOpen(false), size: "icon-sm", variant: "ghost", children: _jsx(ChevronRightIcon, { className: "size-3.5" }) }) }), _jsx(TooltipContent, { children: "Close chat" })] })] }) })] }), _jsxs(Conversation, { children: [_jsxs(ConversationContent, { children: [messages.map((message) => (_jsxs(Message, { className: "max-w-[90%]", from: message.role, children: [_jsx(MessageMetadata, { inProgress: status === "submitted" || status === "streaming", parts: message.parts }), message.parts
170
+ return (_jsxs("aside", { "aria-label": "Ask AI chat", className: "flex size-full w-full flex-col overflow-hidden whitespace-nowrap bg-background-100", children: [_jsxs("div", { className: cn("flex items-center justify-between px-4 py-2.5", isExpanded && "mx-auto w-full max-w-5xl px-6"), children: [_jsx("h2", { className: "font-semibold text-sm", children: "Chat" }), _jsx("div", { className: "flex items-center gap-3", children: _jsxs(ButtonGroup, { children: [_jsx(CopyChat, { messages: messages }), onExpandedChange ? (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { "aria-label": isExpanded ? "Collapse chat" : "Expand chat", "aria-pressed": isExpanded, onClick: () => onExpandedChange(!isExpanded), size: "icon-sm", variant: "ghost", children: isExpanded ? (_jsx(Minimize2Icon, { className: "size-3.5" })) : (_jsx(Maximize2Icon, { className: "size-3.5" })) }) }), _jsx(TooltipContent, { children: isExpanded ? "Collapse chat" : "Expand chat" })] })) : null, _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { "aria-label": "Clear chat", disabled: messages.length === 0, onClick: handleClearChat, size: "icon-sm", variant: "ghost", children: _jsx(Trash, { className: "size-3.5" }) }) }), _jsx(TooltipContent, { children: "Clear chat" })] }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { "aria-label": "Close chat", onClick: () => setIsOpen(false), size: "icon-sm", variant: "ghost", children: _jsx(ChevronRightIcon, { className: "size-3.5" }) }) }), _jsx(TooltipContent, { children: "Close chat" })] })] }) })] }), _jsxs(Conversation, { children: [_jsxs(ConversationContent, { className: cn(isExpanded && "mx-auto w-full max-w-5xl px-6"), children: [messages.map((message) => (_jsxs(Message, { className: cn(isExpanded ? "max-w-full" : "max-w-[90%]"), from: message.role, children: [_jsx(MessageMetadata, { inProgress: status === "submitted" || status === "streaming", parts: message.parts }), message.parts
171
171
  .filter((part) => part.type === "text")
172
- .map((part) => (_jsx(MessageContent, { children: _jsx(MessageResponse, { className: "text-wrap", children: part.text }) }, `${message.id}-${part.type}-${part.text}`)))] }, message.id))), status === "submitted" ? (_jsx("div", { className: "size-12 text-gray-800 text-sm", children: _jsx(Spinner, {}) })) : null] }), _jsx(ConversationScrollButton, {})] }), _jsxs("div", { className: "relative grid w-auto shrink-0 gap-4 p-4", children: [messages.length ? null : (_jsxs(_Fragment, { children: [_jsx(Suggestions, { className: "flex-col items-start gap-px", children: suggestions.map((text) => (_jsx(Suggestion, { className: "rounded-none p-0 text-copy-14", onClick: handleSuggestionClick, suggestion: text, variant: "link" }, text))) }), _jsxs("p", { className: "text-gray-800 text-sm", children: ["Tip: You can open and close chat with", " ", _jsxs(KbdGroup, { children: [_jsx(Kbd, { className: "border bg-transparent", children: "\u2318" }), _jsx(Kbd, { className: "border bg-transparent", children: "I" })] })] })] })), _jsx(ChatPromptInput, { onChange: setPrompt, onStop: stop, onSubmit: (event) => {
172
+ .map((part) => (_jsx(MessageContent, { children: _jsx(MessageResponse, { className: "text-wrap", children: part.text }) }, `${message.id}-${part.type}-${part.text}`)))] }, message.id))), status === "submitted" ? (_jsx("div", { className: "size-12 text-gray-800 text-sm", children: _jsx(Spinner, {}) })) : null] }), _jsx(ConversationScrollButton, {})] }), _jsxs("div", { className: cn("relative grid w-auto shrink-0 gap-4 p-4", isExpanded && "mx-auto w-full max-w-5xl px-6"), children: [messages.length ? null : (_jsxs(_Fragment, { children: [_jsx(Suggestions, { className: "flex-col items-start gap-px", children: suggestions.map((text) => (_jsx(Suggestion, { className: "rounded-none p-0 text-copy-14", onClick: handleSuggestionClick, suggestion: text, variant: "link" }, text))) }), _jsxs("p", { className: "text-gray-900 text-sm", children: ["Tip: You can open and close chat with", " ", _jsxs(KbdGroup, { children: [_jsx(Kbd, { className: "border bg-transparent", children: "\u2318" }), _jsx(Kbd, { className: "border bg-transparent", children: "I" })] })] })] })), _jsx(ChatPromptInput, { onChange: setPrompt, onStop: stop, onSubmit: (event) => {
173
173
  event.preventDefault();
174
174
  handleSubmit().catch((error) => {
175
175
  console.error("Failed to submit chat message:", error);
176
176
  });
177
- }, status: status, textareaRef: textareaRef, value: prompt }), footer ? _jsx("div", { className: "text-gray-800 text-sm", children: footer }) : null] })] }));
177
+ }, status: status, textareaRef: textareaRef, value: prompt }), footer ? _jsx("div", { className: "text-gray-900 text-sm", children: footer }) : null] })] }));
178
178
  };
179
179
  const GeistdocsChatErrorFallback = ({ onClose }, { retry }) => (_jsxs("div", { className: "flex size-full flex-col items-start justify-center gap-4 p-6", "data-geistdocs-chat-error": true, role: "alert", children: [_jsx("h2", { className: "font-semibold text-lg", children: "Ask AI couldn't load" }), _jsx("p", { className: "text-gray-900 text-sm", children: "Try loading Ask AI again or close the panel to continue reading." }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { onClick: () => retry(), type: "button", children: "Try again" }), _jsx(Button, { onClick: onClose, type: "button", variant: "outline", children: "Close" })] })] }));
180
180
  const GeistdocsChatErrorBoundary = catchError(GeistdocsChatErrorFallback);
181
181
  export const GeistdocsChatShell = () => {
182
182
  const { enabled, isOpen, setIsOpen } = useGeistdocsChat();
183
183
  const isMobile = useIsMobile();
184
+ const [isExpanded, setIsExpanded] = useState(false);
185
+ useEffect(() => {
186
+ if (!isOpen) {
187
+ setIsExpanded(false);
188
+ }
189
+ }, [isOpen]);
184
190
  useEffect(() => {
185
191
  const handleKeyDown = (event) => {
192
+ if (event.key === "Escape" && isExpanded) {
193
+ event.preventDefault();
194
+ setIsExpanded(false);
195
+ return;
196
+ }
186
197
  if ((event.metaKey || event.ctrlKey) &&
187
198
  !event.altKey &&
188
199
  !event.shiftKey &&
@@ -193,7 +204,7 @@ export const GeistdocsChatShell = () => {
193
204
  };
194
205
  window.addEventListener("keydown", handleKeyDown);
195
206
  return () => window.removeEventListener("keydown", handleKeyDown);
196
- }, [setIsOpen]);
207
+ }, [isExpanded, setIsOpen]);
197
208
  if (!enabled) {
198
209
  return null;
199
210
  }
@@ -202,5 +213,5 @@ export const GeistdocsChatShell = () => {
202
213
  // modal surfaces like the search command menu, dialogs, and
203
214
  // dropdowns (z-50), so opening the command menu paints over an
204
215
  // open chat panel.
205
- "fixed inset-y-0 right-0 z-45 flex h-full w-3/4 max-w-sm flex-col gap-4 border-l bg-background-100 transition-all", "translate-x-full data-[state=open]:translate-x-0"), "data-state": isOpen ? "open" : "closed", children: _jsx(GeistdocsChatErrorBoundary, { onClose: () => setIsOpen(false), children: _jsx(GeistdocsChatInner, { isOpen: isOpen }) }) }) }), _jsx("div", { className: "md:hidden", children: _jsx(Drawer, { onOpenChange: isMobile ? setIsOpen : undefined, open: isMobile ? isOpen : false, children: _jsxs(DrawerContent, { className: "h-[80dvh]", children: [_jsx(DrawerTitle, { className: "sr-only", children: "Ask AI" }), _jsx(DrawerDescription, { className: "sr-only", children: "Chat with the documentation." }), _jsx(GeistdocsChatErrorBoundary, { onClose: () => setIsOpen(false), children: _jsx(GeistdocsChatInner, { isOpen: isOpen }) })] }) }) })] }));
216
+ "fixed inset-y-0 right-0 z-45 flex h-full flex-col gap-4 border-l bg-background-100 transition-all", isExpanded ? "w-screen max-w-none border-l-0" : "w-3/4 max-w-sm", "translate-x-full data-[state=open]:translate-x-0"), "data-state": isOpen ? "open" : "closed", children: _jsx(GeistdocsChatErrorBoundary, { onClose: () => setIsOpen(false), children: _jsx(GeistdocsChatInner, { isExpanded: isExpanded, isOpen: isOpen, onExpandedChange: setIsExpanded }) }) }) }), _jsx("div", { className: "md:hidden", children: _jsx(Drawer, { onOpenChange: isMobile ? setIsOpen : undefined, open: isMobile ? isOpen : false, children: _jsxs(DrawerContent, { className: "h-[80dvh]", children: [_jsx(DrawerTitle, { className: "sr-only", children: "Ask AI" }), _jsx(DrawerDescription, { className: "sr-only", children: "Chat with the documentation." }), _jsx(GeistdocsChatErrorBoundary, { onClose: () => setIsOpen(false), children: _jsx(GeistdocsChatInner, { isOpen: isOpen }) })] }) }) })] }));
206
217
  };
@@ -1 +1 @@
1
- {"version":3,"file":"provider-client.d.ts","sourceRoot":"","sources":["../../src/internal/provider-client.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,KAAK,cAAc,EAAe,MAAM,OAAO,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAWjD,MAAM,WAAW,sBACf,SAAQ,cAAc,CAAC,OAAO,YAAY,CAAC;IAC3C,MAAM,EAAE,eAAe,CAAC;IACxB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AA2CD,eAAO,MAAM,iBAAiB,GAAI,OAAO,sBAAsB,4CAM9D,CAAC"}
1
+ {"version":3,"file":"provider-client.d.ts","sourceRoot":"","sources":["../../src/internal/provider-client.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,KAAK,cAAc,EAAe,MAAM,OAAO,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAYjD,MAAM,WAAW,sBACf,SAAQ,cAAc,CAAC,OAAO,YAAY,CAAC;IAC3C,MAAM,EAAE,eAAe,CAAC;IACxB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AA4CD,eAAO,MAAM,iBAAiB,GAAI,OAAO,sBAAsB,4CAM9D,CAAC"}
@@ -11,6 +11,7 @@ import { GeistdocsSearchDialog } from "./search";
11
11
  import { Toaster } from "./ui/sonner";
12
12
  import { TooltipProvider } from "./ui/tooltip";
13
13
  import { useIsMobile } from "./use-mobile";
14
+ import { GeistdocsWebMCP } from "./webmcp-client";
14
15
  const GeistdocsProviderInner = ({ config, search, lang, ...props }) => {
15
16
  const { i18n, i18nProvider } = createGeistdocsI18n(config);
16
17
  const { enabled, isOpen } = useGeistdocsChat();
@@ -19,6 +20,6 @@ const GeistdocsProviderInner = ({ config, search, lang, ...props }) => {
19
20
  return (_jsx("div", { className: cn("@container transition-[padding-right] duration-150 ease-[cubic-bezier(0.175,0.885,0.32,1.1)] motion-reduce:transition-none", enabled && isOpen && !isMobile ? "pr-96!" : null), "data-geistdocs-container": true, children: _jsxs(TooltipProvider, { children: [_jsx(RootProvider, { i18n: i18nProvider(lang ?? i18n.defaultLanguage), search: {
20
21
  SearchDialog: SearchDialogComponent,
21
22
  ...search,
22
- }, ...props }), _jsx(Toaster, {}), _jsx(GeistdocsChatShell, {})] }) }));
23
+ }, ...props }), _jsx(GeistdocsWebMCP, { config: config, lang: lang }), _jsx(Toaster, {}), _jsx(GeistdocsChatShell, {})] }) }));
23
24
  };
24
25
  export const GeistdocsProvider = (props) => (_jsx(GeistdocsConfigProvider, { config: props.config, children: _jsx(GeistdocsChatProvider, { config: props.config, children: _jsx(GeistdocsProviderInner, { ...props }) }) }));
@@ -0,0 +1,6 @@
1
+ import type { GeistdocsConfig } from "../config";
2
+ export declare const GeistdocsWebMCP: ({ config, lang, }: {
3
+ config: GeistdocsConfig;
4
+ lang?: string;
5
+ }) => null;
6
+ //# sourceMappingURL=webmcp-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webmcp-client.d.ts","sourceRoot":"","sources":["../../src/internal/webmcp-client.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAOjD,eAAO,MAAM,eAAe,GAAI,mBAG7B;IACD,MAAM,EAAE,eAAe,CAAC;IACxB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,SAiBA,CAAC"}
@@ -0,0 +1,21 @@
1
+ "use client";
2
+ import { useEffect } from "react";
3
+ import { createWebMCPTools, registerWebMCPTools, } from "./webmcp";
4
+ export const GeistdocsWebMCP = ({ config, lang, }) => {
5
+ useEffect(() => {
6
+ const context = document
7
+ .modelContext;
8
+ if (!(config.webmcp?.enabled && context?.registerTool)) {
9
+ return;
10
+ }
11
+ const tools = createWebMCPTools({
12
+ config,
13
+ lang,
14
+ location: window.location,
15
+ });
16
+ return registerWebMCPTools(context, tools, (error) => {
17
+ console.warn("Geistdocs WebMCP registration failed:", error);
18
+ });
19
+ }, [config, lang]);
20
+ return null;
21
+ };
@@ -0,0 +1,30 @@
1
+ import { type GeistdocsConfig } from "../config.js";
2
+ interface ToolExecutionContext {
3
+ signal?: AbortSignal;
4
+ }
5
+ interface WebMCPTool {
6
+ annotations: {
7
+ readOnlyHint: boolean;
8
+ untrustedContentHint: boolean;
9
+ };
10
+ description: string;
11
+ execute: (input: Record<string, unknown>, context?: ToolExecutionContext) => Promise<string>;
12
+ inputSchema: Record<string, unknown>;
13
+ name: string;
14
+ }
15
+ export interface WebMCPContext {
16
+ registerTool: (tool: WebMCPTool, options: {
17
+ signal: AbortSignal;
18
+ }) => Promise<void>;
19
+ }
20
+ interface WebMCPOptions {
21
+ config: GeistdocsConfig;
22
+ fetcher?: typeof fetch;
23
+ lang?: string;
24
+ location: Pick<Location, "href">;
25
+ requestTimeoutMs?: number;
26
+ }
27
+ export declare const createWebMCPTools: ({ config, fetcher, lang, location, requestTimeoutMs, }: WebMCPOptions) => WebMCPTool[];
28
+ export declare const registerWebMCPTools: (context: WebMCPContext, tools: WebMCPTool[], onError: (error: unknown) => void) => () => void;
29
+ export {};
30
+ //# sourceMappingURL=webmcp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webmcp.d.ts","sourceRoot":"","sources":["../../src/internal/webmcp.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,eAAe,EAGrB,MAAM,cAAc,CAAC;AAEtB,UAAU,oBAAoB;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,UAAU,UAAU;IAClB,WAAW,EAAE;QAAE,YAAY,EAAE,OAAO,CAAC;QAAC,oBAAoB,EAAE,OAAO,CAAA;KAAE,CAAC;IACtE,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,CACP,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,OAAO,CAAC,EAAE,oBAAoB,KAC3B,OAAO,CAAC,MAAM,CAAC,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,CACZ,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE;QAAE,MAAM,EAAE,WAAW,CAAA;KAAE,KAC7B,OAAO,CAAC,IAAI,CAAC,CAAC;CACpB;AAED,UAAU,aAAa;IACrB,MAAM,EAAE,eAAe,CAAC;IACxB,OAAO,CAAC,EAAE,OAAO,KAAK,CAAC;IACvB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IACjC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,eAAO,MAAM,iBAAiB,GAAI,wDAM/B,aAAa,KAAG,UAAU,EA+F5B,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAC9B,SAAS,aAAa,EACtB,OAAO,UAAU,EAAE,EACnB,SAAS,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,eAoBlC,CAAC"}
@@ -0,0 +1,102 @@
1
+ import { getPublicPath, withBasePath, } from "../config.js";
2
+ export const createWebMCPTools = ({ config, fetcher = fetch, lang, location, requestTimeoutMs = 15_000, }) => {
3
+ const getRequestSignal = (signal) => {
4
+ const deadline = AbortSignal.timeout(requestTimeoutMs);
5
+ return signal ? AbortSignal.any([signal, deadline]) : deadline;
6
+ };
7
+ const annotations = { readOnlyHint: true, untrustedContentHint: true };
8
+ return [
9
+ {
10
+ name: "search_docs",
11
+ description: `Search ${config.title} documentation in the current language. Returns matching titles, excerpts, and page URLs.`,
12
+ annotations,
13
+ inputSchema: {
14
+ type: "object",
15
+ properties: { query: { type: "string", minLength: 1, maxLength: 500 } },
16
+ required: ["query"],
17
+ additionalProperties: false,
18
+ },
19
+ execute: async (input, { signal } = {}) => {
20
+ if (typeof input.query !== "string" ||
21
+ !input.query.trim() ||
22
+ input.query.length > 500) {
23
+ throw new Error("query must contain between 1 and 500 characters.");
24
+ }
25
+ const url = new URL(getPublicPath("/api/search", config.basePath), location.href);
26
+ url.searchParams.set("query", input.query.trim());
27
+ url.searchParams.set("locale", lang ?? config.defaultLanguage ?? "en");
28
+ const response = await fetcher(url, {
29
+ signal: getRequestSignal(signal),
30
+ redirect: "error",
31
+ });
32
+ if (!response.ok) {
33
+ throw new Error(`Documentation search failed (${response.status}).`);
34
+ }
35
+ const results = await response.json();
36
+ if (!Array.isArray(results)) {
37
+ throw new Error("Documentation search returned an invalid response.");
38
+ }
39
+ return JSON.stringify(results.map((result) => {
40
+ if (typeof result !== "object" ||
41
+ result === null ||
42
+ !("url" in result) ||
43
+ typeof result.url !== "string") {
44
+ throw new Error("Documentation search returned an invalid result.");
45
+ }
46
+ return {
47
+ ...result,
48
+ url: withBasePath(result.url, config.basePath),
49
+ };
50
+ }));
51
+ },
52
+ },
53
+ {
54
+ name: "read_current_page",
55
+ description: "Read the current documentation page as Markdown. Navigate to a documentation page before calling this tool.",
56
+ annotations,
57
+ inputSchema: {
58
+ type: "object",
59
+ properties: {},
60
+ additionalProperties: false,
61
+ },
62
+ execute: async (_input, { signal } = {}) => {
63
+ const url = new URL(location.href);
64
+ url.hash = "";
65
+ url.search = "";
66
+ const response = await fetcher(url, {
67
+ headers: { Accept: "text/markdown" },
68
+ redirect: "error",
69
+ signal: getRequestSignal(signal),
70
+ });
71
+ if (!response.ok) {
72
+ throw new Error(`Documentation page could not be read (${response.status}).`);
73
+ }
74
+ if (!response.headers.get("content-type")?.includes("text/markdown")) {
75
+ throw new Error("The current page does not provide documentation Markdown.");
76
+ }
77
+ return response.text();
78
+ },
79
+ },
80
+ ];
81
+ };
82
+ export const registerWebMCPTools = (context, tools, onError) => {
83
+ const controller = new AbortController();
84
+ const register = async () => {
85
+ try {
86
+ for (const tool of tools) {
87
+ if (controller.signal.aborted) {
88
+ return;
89
+ }
90
+ await context.registerTool(tool, { signal: controller.signal });
91
+ }
92
+ }
93
+ catch (error) {
94
+ if (!controller.signal.aborted) {
95
+ controller.abort();
96
+ onError(error);
97
+ }
98
+ }
99
+ };
100
+ register();
101
+ return () => controller.abort();
102
+ };
package/docs/agents.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Geistdocs Package Docs
2
2
 
3
- These docs are bundled with `@vercel/geistdocs` 1.26.1 so agents can understand the installed package without web access.
3
+ These docs are bundled with `@vercel/geistdocs` 1.27.0 so agents can understand the installed package without web access.
4
4
  They are generated from `apps/template/content/docs` during the package build.
5
5
 
6
6
  ## How to use these files
@@ -45,3 +45,4 @@ They are generated from `apps/template/content/docs` during the package build.
45
45
  - [RSS](pages/rss.md): An automatically generated RSS 2.0 feed that keeps users informed when documentation is published or updated.
46
46
  - [Table of contents](pages/table-of-contents.md): Geistdocs builds the "On this page" outline from your headings, indents sub-headings under their parent, and tracks the active section along a straight vertical guide rail.
47
47
  - [Theme-Aware Image](pages/theme-aware-image.md): A component that swaps images based on the active theme, built on top of Next.js Image.
48
+ - [WebMCP](pages/webmcp.md): Expose documentation search and page reading to browser agents.
package/docs/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # Geistdocs Package Documentation
2
2
 
3
- These docs are bundled with `@vercel/geistdocs` 1.26.1.
3
+ These docs are bundled with `@vercel/geistdocs` 1.27.0.
4
4
  They describe how to build package-backed Geistdocs sites and how to use the package APIs from generated project adapters.
5
5
 
6
6
  ## Documentation Index
@@ -28,6 +28,7 @@ They describe how to build package-backed Geistdocs sites and how to use the pac
28
28
  - [RSS](pages/rss.md): An automatically generated RSS 2.0 feed that keeps users informed when documentation is published or updated.
29
29
  - [Table of contents](pages/table-of-contents.md): Geistdocs builds the "On this page" outline from your headings, indents sub-headings under their parent, and tracks the active section along a straight vertical guide rail.
30
30
  - [Theme-Aware Image](pages/theme-aware-image.md): A component that swaps images based on the active theme, built on top of Next.js Image.
31
+ - [WebMCP](pages/webmcp.md): Expose documentation search and page reading to browser agents.
31
32
 
32
33
  ---
33
34
 
@@ -2760,6 +2761,7 @@ Users can open the chat interface at any time by:
2760
2761
  Once open, users can:
2761
2762
 
2762
2763
  - Ask questions about any part of your documentation
2764
+ - Expand the desktop panel to a full-screen view for wide responses and code blocks
2763
2765
  - Upload files or images for context
2764
2766
  - View AI-powered search results from your docs
2765
2767
  - Get step-by-step guidance on complex topics
@@ -2916,7 +2918,7 @@ Conversations are automatically saved to the browser's IndexedDB, providing:
2916
2918
 
2917
2919
  The chat interface adapts to different screen sizes:
2918
2920
 
2919
- - **Desktop**: Slides in from the right side as a sidebar panel
2921
+ - **Desktop**: Slides in from the right side as a sidebar panel. Use **Expand chat** in the panel header to switch to a full-screen view, and **Collapse chat** or `Escape` to return to the sidebar.
2920
2922
  - **Mobile**: Opens as a bottom drawer.
2921
2923
 
2922
2924
  ## Configuration
@@ -4021,3 +4023,65 @@ Because this component relies on client-side theme detection, it is a client com
4021
4023
  | `height` | `number` | The height of the image in pixels |
4022
4024
  | `...rest` | `ImageProps` | Any additional props supported by the Next.js `Image` component |
4023
4025
 
4026
+
4027
+ ---
4028
+
4029
+ ---
4030
+ title: WebMCP
4031
+ description: Expose documentation search and page reading to browser agents.
4032
+ url: /docs/webmcp
4033
+ source: apps/template/content/docs/webmcp.mdx
4034
+ ---
4035
+
4036
+ # WebMCP
4037
+
4038
+ Geistdocs includes experimental WebMCP support. WebMCP is disabled by default. To opt in, add it to the `defineConfig` call in `lib/geistdocs/config.tsx`:
4039
+
4040
+ ```ts
4041
+ export const config = defineConfig({
4042
+ // ...
4043
+ webmcp: { enabled: true },
4044
+ });
4045
+ ```
4046
+
4047
+ The provider exposes two read-only tools:
4048
+
4049
+ | Tool | Input | Result |
4050
+ | --- | --- | --- |
4051
+ | `search_docs` | `query`, a nonempty string up to 500 characters | Results from the existing search API in the current language |
4052
+ | `read_current_page` | None | The current documentation page as Markdown |
4053
+
4054
+ Search respects the existing search visibility rules. Page reading uses the existing Markdown route and fails if the current page does not serve Markdown. Neither tool sends data to an external model or modifies documentation. Returned documentation is marked as untrusted content.
4055
+
4056
+ WebMCP requires a compatible browser with the experimental API enabled. Unsupported browsers continue to work normally. This feature uses browser-local tools, independently of the site's remote MCP discovery manifest.
4057
+
4058
+ ## Verify locally
4059
+
4060
+ Enable WebMCP testing as described in the [Chrome documentation](https://developer.chrome.com/docs/ai/webmcp). Open a documentation page and inspect its tools:
4061
+
4062
+ ```js
4063
+ const tools = await document.modelContext.getTools();
4064
+ const search = tools.find((tool) => tool.name === "search_docs");
4065
+ await document.modelContext.executeTool(search, JSON.stringify({ query: "configuration" }));
4066
+ const read = tools.find((tool) => tool.name === "read_current_page");
4067
+ await document.modelContext.executeTool(read, "{}");
4068
+ ```
4069
+
4070
+ Navigate to another documentation page and read it again. Repeat in a translated route and, when configured, under the site's base path. Disable the feature and verify the provider removes its tools.
4071
+
4072
+ ## agent-browser
4073
+
4074
+ With agent-browser 0.36.0 or newer, WebMCP is enabled by default in managed Chrome sessions:
4075
+
4076
+ ```bash
4077
+ agent-browser --session docs-check open http://localhost:3000/docs
4078
+ agent-browser --session docs-check webmcp list
4079
+ agent-browser --session docs-check webmcp invoke search_docs --params '{"query":"configuration"}'
4080
+ agent-browser --session docs-check webmcp invoke read_current_page --params '{}'
4081
+ agent-browser --session docs-check close
4082
+ ```
4083
+
4084
+ Discovery includes each tool's origin, frame, schema, and read-only annotations. Check the invocation's `status`: a successfully delivered command can still contain a failed tool execution.
4085
+
4086
+ Both tools limit network requests to 15 seconds. When the browser supplies an execution signal, cancellation also aborts the request. Some experimental browser versions, including Chrome 152, omit that signal: canceling an invocation in those versions does not immediately abort its underlying fetch, which remains bounded by the request deadline.
4087
+
@@ -214,8 +214,15 @@
214
214
  "title": "Theme-Aware Image",
215
215
  "type": "reference",
216
216
  "url": "/docs/theme-aware-image"
217
+ },
218
+ {
219
+ "description": "Expose documentation search and page reading to browser agents.",
220
+ "path": "pages/webmcp.md",
221
+ "source": "apps/template/content/docs/webmcp.mdx",
222
+ "title": "WebMCP",
223
+ "url": "/docs/webmcp"
217
224
  }
218
225
  ],
219
226
  "source": "apps/template/content/docs",
220
- "version": "1.26.1"
227
+ "version": "1.27.0"
221
228
  }
@@ -42,6 +42,7 @@ Users can open the chat interface at any time by:
42
42
  Once open, users can:
43
43
 
44
44
  - Ask questions about any part of your documentation
45
+ - Expand the desktop panel to a full-screen view for wide responses and code blocks
45
46
  - Upload files or images for context
46
47
  - View AI-powered search results from your docs
47
48
  - Get step-by-step guidance on complex topics
@@ -198,7 +199,7 @@ Conversations are automatically saved to the browser's IndexedDB, providing:
198
199
 
199
200
  The chat interface adapts to different screen sizes:
200
201
 
201
- - **Desktop**: Slides in from the right side as a sidebar panel
202
+ - **Desktop**: Slides in from the right side as a sidebar panel. Use **Expand chat** in the panel header to switch to a full-screen view, and **Collapse chat** or `Escape` to return to the sidebar.
202
203
  - **Mobile**: Opens as a bottom drawer.
203
204
 
204
205
  ## Configuration
@@ -0,0 +1,58 @@
1
+ ---
2
+ title: WebMCP
3
+ description: Expose documentation search and page reading to browser agents.
4
+ url: /docs/webmcp
5
+ source: apps/template/content/docs/webmcp.mdx
6
+ ---
7
+
8
+ # WebMCP
9
+
10
+ Geistdocs includes experimental WebMCP support. WebMCP is disabled by default. To opt in, add it to the `defineConfig` call in `lib/geistdocs/config.tsx`:
11
+
12
+ ```ts
13
+ export const config = defineConfig({
14
+ // ...
15
+ webmcp: { enabled: true },
16
+ });
17
+ ```
18
+
19
+ The provider exposes two read-only tools:
20
+
21
+ | Tool | Input | Result |
22
+ | --- | --- | --- |
23
+ | `search_docs` | `query`, a nonempty string up to 500 characters | Results from the existing search API in the current language |
24
+ | `read_current_page` | None | The current documentation page as Markdown |
25
+
26
+ Search respects the existing search visibility rules. Page reading uses the existing Markdown route and fails if the current page does not serve Markdown. Neither tool sends data to an external model or modifies documentation. Returned documentation is marked as untrusted content.
27
+
28
+ WebMCP requires a compatible browser with the experimental API enabled. Unsupported browsers continue to work normally. This feature uses browser-local tools, independently of the site's remote MCP discovery manifest.
29
+
30
+ ## Verify locally
31
+
32
+ Enable WebMCP testing as described in the [Chrome documentation](https://developer.chrome.com/docs/ai/webmcp). Open a documentation page and inspect its tools:
33
+
34
+ ```js
35
+ const tools = await document.modelContext.getTools();
36
+ const search = tools.find((tool) => tool.name === "search_docs");
37
+ await document.modelContext.executeTool(search, JSON.stringify({ query: "configuration" }));
38
+ const read = tools.find((tool) => tool.name === "read_current_page");
39
+ await document.modelContext.executeTool(read, "{}");
40
+ ```
41
+
42
+ Navigate to another documentation page and read it again. Repeat in a translated route and, when configured, under the site's base path. Disable the feature and verify the provider removes its tools.
43
+
44
+ ## agent-browser
45
+
46
+ With agent-browser 0.36.0 or newer, WebMCP is enabled by default in managed Chrome sessions:
47
+
48
+ ```bash
49
+ agent-browser --session docs-check open http://localhost:3000/docs
50
+ agent-browser --session docs-check webmcp list
51
+ agent-browser --session docs-check webmcp invoke search_docs --params '{"query":"configuration"}'
52
+ agent-browser --session docs-check webmcp invoke read_current_page --params '{}'
53
+ agent-browser --session docs-check close
54
+ ```
55
+
56
+ Discovery includes each tool's origin, frame, schema, and read-only annotations. Check the invocation's `status`: a successfully delivered command can still contain a failed tool execution.
57
+
58
+ Both tools limit network requests to 15 seconds. When the browser supplies an execution signal, cancellation also aborts the request. Some experimental browser versions, including Chrome 152, omit that signal: canceling an invocation in those versions does not immediately abort its underlying fetch, which remains bounded by the request deadline.
package/docs/sitemap.md CHANGED
@@ -26,3 +26,4 @@ Use it to choose focused page files from `docs/pages/` before reading the full `
26
26
  - [RSS](pages/rss.md) | URL: /docs/rss | Type: conceptual | Summary: An automatically generated RSS 2.0 feed that keeps users informed when documentation is published or updated.
27
27
  - [Table of contents](pages/table-of-contents.md) | URL: /docs/table-of-contents | Type: reference | Summary: Geistdocs builds the "On this page" outline from your headings, indents sub-headings under their parent, and tracks the active section along a straight vertical guide rail.
28
28
  - [Theme-Aware Image](pages/theme-aware-image.md) | URL: /docs/theme-aware-image | Type: reference | Summary: A component that swaps images based on the active theme, built on top of Next.js Image.
29
+ - [WebMCP](pages/webmcp.md) | URL: /docs/webmcp
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vercel/geistdocs",
3
3
  "description": "Runtime and CLI for Geistdocs projects.",
4
- "version": "1.26.1",
4
+ "version": "1.27.0",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -40,6 +40,7 @@ Users can open the chat interface at any time by:
40
40
  Once open, users can:
41
41
 
42
42
  - Ask questions about any part of your documentation
43
+ - Expand the desktop panel to a full-screen view for wide responses and code blocks
43
44
  - Upload files or images for context
44
45
  - View AI-powered search results from your docs
45
46
  - Get step-by-step guidance on complex topics
@@ -196,7 +197,7 @@ Conversations are automatically saved to the browser's IndexedDB, providing:
196
197
 
197
198
  The chat interface adapts to different screen sizes:
198
199
 
199
- - **Desktop**: Slides in from the right side as a sidebar panel
200
+ - **Desktop**: Slides in from the right side as a sidebar panel. Use **Expand chat** in the panel header to switch to a full-screen view, and **Collapse chat** or `Escape` to return to the sidebar.
200
201
  - **Mobile**: Opens as a bottom drawer.
201
202
 
202
203
  ## Configuration
@@ -20,6 +20,7 @@
20
20
  "---AI---",
21
21
  "open-in-chat",
22
22
  "agent-readiness",
23
+ "webmcp",
23
24
  "llms-txt",
24
25
  "mixedbread-retrieval",
25
26
  "ask-ai"
@@ -0,0 +1,54 @@
1
+ ---
2
+ title: WebMCP
3
+ description: Expose documentation search and page reading to browser agents.
4
+ ---
5
+
6
+ Geistdocs includes experimental WebMCP support. WebMCP is disabled by default. To opt in, add it to the `defineConfig` call in `lib/geistdocs/config.tsx`:
7
+
8
+ ```ts
9
+ export const config = defineConfig({
10
+ // ...
11
+ webmcp: { enabled: true },
12
+ });
13
+ ```
14
+
15
+ The provider exposes two read-only tools:
16
+
17
+ | Tool | Input | Result |
18
+ | --- | --- | --- |
19
+ | `search_docs` | `query`, a nonempty string up to 500 characters | Results from the existing search API in the current language |
20
+ | `read_current_page` | None | The current documentation page as Markdown |
21
+
22
+ Search respects the existing search visibility rules. Page reading uses the existing Markdown route and fails if the current page does not serve Markdown. Neither tool sends data to an external model or modifies documentation. Returned documentation is marked as untrusted content.
23
+
24
+ WebMCP requires a compatible browser with the experimental API enabled. Unsupported browsers continue to work normally. This feature uses browser-local tools, independently of the site's remote MCP discovery manifest.
25
+
26
+ ## Verify locally
27
+
28
+ Enable WebMCP testing as described in the [Chrome documentation](https://developer.chrome.com/docs/ai/webmcp). Open a documentation page and inspect its tools:
29
+
30
+ ```js
31
+ const tools = await document.modelContext.getTools();
32
+ const search = tools.find((tool) => tool.name === "search_docs");
33
+ await document.modelContext.executeTool(search, JSON.stringify({ query: "configuration" }));
34
+ const read = tools.find((tool) => tool.name === "read_current_page");
35
+ await document.modelContext.executeTool(read, "{}");
36
+ ```
37
+
38
+ Navigate to another documentation page and read it again. Repeat in a translated route and, when configured, under the site's base path. Disable the feature and verify the provider removes its tools.
39
+
40
+ ## agent-browser
41
+
42
+ With agent-browser 0.36.0 or newer, WebMCP is enabled by default in managed Chrome sessions:
43
+
44
+ ```bash
45
+ agent-browser --session docs-check open http://localhost:3000/docs
46
+ agent-browser --session docs-check webmcp list
47
+ agent-browser --session docs-check webmcp invoke search_docs --params '{"query":"configuration"}'
48
+ agent-browser --session docs-check webmcp invoke read_current_page --params '{}'
49
+ agent-browser --session docs-check close
50
+ ```
51
+
52
+ Discovery includes each tool's origin, frame, schema, and read-only annotations. Check the invocation's `status`: a successfully delivered command can still contain a failed tool execution.
53
+
54
+ Both tools limit network requests to 15 seconds. When the browser supplies an execution signal, cancellation also aborts the request. Some experimental browser versions, including Chrome 152, omit that signal: canceling an invocation in those versions does not immediately abort its underlying fetch, which remains bounded by the request deadline.
@@ -18,7 +18,7 @@
18
18
  "@streamdown/code": "^1.0.1",
19
19
  "@vercel/agent-readability": "^0.7.0",
20
20
  "@vercel/analytics": "^1.6.1",
21
- "@vercel/geistdocs": "1.26.1",
21
+ "@vercel/geistdocs": "1.27.0",
22
22
  "@vercel/speed-insights": "^1.3.1",
23
23
  "ai": "^6.0.132",
24
24
  "class-variance-authority": "^0.7.1",