@vercel/geistdocs 2.14.3 → 2.14.4
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 +1 -1
- package/dist/internal/chat/message-text.d.ts +6 -0
- package/dist/internal/chat/message-text.d.ts.map +1 -1
- package/dist/internal/chat/message-text.js +6 -0
- package/dist/internal/chat/prompt-input.d.ts.map +1 -1
- package/dist/internal/chat/prompt-input.js +2 -1
- package/dist/internal/eve-agent.d.ts +2 -2
- package/dist/internal/eve-agent.js +2 -2
- package/dist/routes/chat.d.ts +6 -0
- package/dist/routes/chat.d.ts.map +1 -1
- package/dist/routes/chat.js +47 -6
- package/docs/agents.md +1 -1
- package/docs/llms.txt +5 -1
- package/docs/manifest.json +1 -1
- package/docs/pages/ask-ai.md +4 -0
- package/package.json +1 -1
- package/template/content/docs/ask-ai.cn.mdx +4 -0
- package/template/content/docs/ask-ai.mdx +4 -0
- package/template/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -4,4 +4,4 @@ import{Option as Rn,program as A}from"commander";import{access as Ke,copyFile as
|
|
|
4
4
|
`);throw new AggregateError(i,`Mixedbread search sync did not complete:
|
|
5
5
|
${a}`)}return r},Ft=async({client:e,file:t,pollIntervalMs:n,pollTimeoutMs:r,sleep:i})=>{let s=t,o=Date.now()+r;for(;s.status==="pending"||s.status==="in_progress";){if(Date.now()>=o)throw new Error(`Mixedbread timed out while indexing file ${t.id}.`);await i(n),s=await e.retrieveStoreFile(t.id)}if(s.status!=="completed")throw new Error(`Mixedbread failed to index file ${t.id} (${s.status}).`);return s},Dt=async({client:e,desired:t,pollIntervalMs:n,pollTimeoutMs:r,sleep:i})=>{let s=await e.uploadFile({content:t.document.content,filename:`${U(t.document.id).slice(0,32)}.md`}),o;try{o=await e.createStoreFile({externalId:t.externalId,fileId:s,metadata:{...t.metadata,[g.rawFileId]:s}})}catch(a){try{await e.deleteFile(s)}catch(d){throw new AggregateError([a,d],`Mixedbread failed to attach and clean up raw file ${s}.`)}throw a}return Ft({client:e,file:o,pollIntervalMs:n,pollTimeoutMs:r,sleep:i})},Ie=async({client:e,concurrency:t=St,manifest:n,pollIntervalMs:r=_t,pollTimeoutMs:i=Tt,revision:s,revisionAncestors:o=[],revisionTimestamp:a,sleep:d=Rt})=>{let c=_e(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=>At(p,u,s,o,a)),m=new Map(l.map(p=>[p.document.id,p])),h=(await be(e)).flatMap(p=>{let y=q(p.metadata);return y?.siteId===u?[{file:p,metadata:y}]:[]}),x=new Map,P=new Set;for(let p of h){W(p.metadata,s,a)&&P.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)||P.has(p.document.id)));await Ee(_,t,p=>Dt({client:e,desired:p,pollIntervalMs:r,pollTimeoutMs:i,sleep:d}));let b=(await be(e)).flatMap(p=>{let y=q(p.metadata);return y?.siteId===u?[{file:p,metadata:y}]:[]}),D=new Set(b.filter(({metadata:p})=>W(p,s,a)).map(({metadata:p})=>p.documentId)),ie=new Set;for(let p of l){if(D.has(p.document.id))continue;let ae=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];ae&&ie.add(ae.file.id)}let oe=b.filter(({file:p,metadata:y})=>p.status!=="pending"&&p.status!=="in_progress"&&!W(y,s,a)&&Mt({currentRevision:s,currentRevisionAncestors:o,currentRevisionTimestamp:a,desired:m.get(y.documentId),metadata:y})&&!ie.has(p.id));return await Ee(oe,t,async({file:p,metadata:y})=>{await e.deleteFile(y.rawFileId??p.id),await e.deleteStoreFile(p.id)}),{deleted:oe.length,skipped:l.length-_.length,uploaded:_.length}};var Ot=50,$t=e=>`vercel integration add mixedbread --name docs-${e||"your-site-id"} --environment production`,ve=(e,t)=>kt("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Nt=e=>{let t=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),n=[];try{n=ve(e,["rev-list",`--max-count=${Ot+1}`,t||"HEAD"]).split(`
|
|
6
6
|
`).filter(Boolean)}catch{n=[]}let r=t||n[0],i;for(let s of Array.from(new Set([r,"HEAD"].filter(Boolean))))try{let o=Number(ve(e,["show","-s","--format=%ct",s]));if(Number.isFinite(o)){i=o;break}}catch{}return{revision:r,revisionAncestors:n.filter(s=>s!==r),revisionTimestamp:i}},Pe=async({allowNonProduction:e=!1,dir:t=".next"}={})=>{let n=process.cwd();Ct.loadEnvConfig(n,!1);let r=process.env.MXBAI_API_KEY?.trim(),i=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!=!!i)throw new Error("Mixedbread is partially configured. Set both MXBAI_API_KEY and MXBAI_STORE_ID.");let s;try{s=await Te({cwd:n,outputDirectory:t})}catch(a){if(!(r||i)){console.log("Geistdocs search sync skipped: no Mixedbread credentials or static search export were found.");return}throw a}if(s.provider!=="mixedbread"){console.log("Geistdocs search sync skipped: Ask AI uses local retrieval.");return}if(!(r&&i))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:",$t(s.siteId)].join(`
|
|
7
|
-
`));let o=await Ie({client:we({apiBaseUrl:process.env.MXBAI_BASE_URL,apiKey:r,storeId:i}),manifest:s,...Nt(n)});console.log(`Geistdocs search sync complete: ${o.uploaded} uploaded, ${o.deleted} deleted, ${o.skipped} unchanged.`)};import{readFileSync as Gt,writeFileSync as Ut}from"fs";import{mkdir as Lt,readFile as Z,writeFile as jt}from"fs/promises";import{dirname as Bt,extname as Vt,relative as Fe,resolve as j}from"path";import{intro as Jt,isCancel as Ht,log as I,multiselect as Xt,outro as L,spinner as Kt}from"@clack/prompts";import{glob as Yt}from"glob";import{Node as F,Project as qt,SyntaxKind as zt}from"ts-morph";var Wt="geistdocs.tsx",Qt="content/docs/**/*.mdx",ee=".translation-cache.json",Q=8,Ae=()=>({version:1,entries:{}}),Zt=async e=>{let t=await Z(e),{createHash:n}=await import("crypto");return n("sha256").update(t).digest("hex")},en=e=>{let t=j(process.cwd(),e);return Gt(t,"utf8")},Me=e=>F.isObjectLiteralExpression(e)?e.getProperties().flatMap(t=>{if(F.isPropertyAssignment(t)){let n=t.getNameNode();if(F.isIdentifier(n)||F.isStringLiteral(n))return[n.getText().replaceAll(/['"]/g,"")]}return[]}).filter(Boolean):[],tn=e=>{try{let t=new qt({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),n=en(e),s=t.createSourceFile(e,n,{overwrite:!0}).getVariableDeclarations().find(a=>a.getName()==="translations")?.getInitializer();if(!s)return[];if(F.isObjectLiteralExpression(s))return Me(s);let o=s.getFirstDescendantByKind(zt.ObjectLiteralExpression);return o?Me(o):[]}catch(t){let n=t instanceof Error?t.message:`${t}`;return I.warn(`Failed to read locales from ${e}: ${n}`),[]}},nn=async()=>{let e=await Xt({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 Ht(e)&&(L("Translation cancelled"),process.exit(0)),e},rn=async e=>(await Yt(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),sn=async()=>{let e=j(process.cwd(),ee);try{let t=await Z(e,"utf8"),n=JSON.parse(t);return n.version!==1||!n.entries?Ae():{version:1,entries:n.entries}}catch{return Ae()}},Re=e=>{let t=j(process.cwd(),ee),n=JSON.stringify(e,null,2);Ut(t,n,"utf8")},on=async e=>{let t=await Promise.all(e.map(async n=>[n,await Zt(n)]));return Object.fromEntries(t)},an=(e,t)=>{let n=Vt(e);return`${e.slice(0,-n.length)}.${t}${n}`},De=(e,t)=>`${Fe(process.cwd(),e)}::${t}`,cn=(e,t,n,r,i=!1)=>{let s=[],o=0;for(let a of t){let d=n[a];for(let c of e){let u=an(a,c),l=De(a,c),m=r.entries[l];if(!i&&m?.hash===d){o+=1;continue}s.push({locale:c,sourceFile:a,sourceHash:d,targetFile:u})}}return{tasks:s,skippedCount:o}},dn=async e=>{await Lt(Bt(e),{recursive:!0})},ln=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 s=await r.text();throw new Error(`API request failed (${r.status}): ${s}`)}let i=await r.json();if(!i.translation)throw new Error("API response did not include a translation");return i.translation},pn=async(e,t,n)=>{let r=await Z(e.sourceFile,"utf8"),i=await ln(t,r,e.locale);await dn(e.targetFile),await jt(e.targetFile,i,"utf8"),n.entries[De(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},ke=async(e,t)=>{Jt("Translate MDX content");let n=e??Qt,r=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",i=tn(t.config??Wt),s=await rn(n);s.length===0&&(I.error(`No MDX files found matching pattern: ${n}`),L("Translation cancelled"),process.exit(1)),I.info(`Found ${s.length} MDX file(s) matching pattern`),i.length===0&&(i=await nn());let o=j(process.cwd(),ee),a=await sn();await Re(a),I.info(`Using cache: ${o}`);let d=await on(s),{tasks:c,skippedCount:u}=cn(i,s,d,a,t.force);if(c.length===0){I.success("All translations are up to date!"),L(`Skipped ${u} file(s) (unchanged)`);return}let l=[];for(let h=0;h<c.length;h+=Q)l.push(c.slice(h,h+Q));I.info(`Processing ${c.length} translation(s) in ${l.length} batch(es) of up to ${Q}`),u>0&&I.info(`Skipped ${u} translation(s) (unchanged)`);let m=Kt();m.start("Translating content...");let f=0;for(let h of l)await Promise.all(h.map(async x=>{await pn(x,r,a),f+=1,m.message(`Translated ${f}/${c.length}: ${Fe(process.cwd(),x.targetFile)}`)})),await Re(a);m.stop("Translation complete!"),L(`Created/updated ${c.length} file(s)`)};import{access as un,copyFile as gn,mkdir as Ne,rm as re}from"fs/promises";import{dirname as mn,join as v}from"path";import{intro as fn,log as w,outro as B,spinner as Ge}from"@clack/prompts";import{glob as hn}from"glob";var wn=["**/*"],yn=["content/docs/**"],te=".geistdocs-tmp",xn=async(e,t)=>{let n=v(e,t);await re(n,{recursive:!0,force:!0}),await Ne(n,{recursive:!0})},ne=async e=>await re(e,{recursive:!0,force:!0}),Ce=async(e,t,n)=>(await hn(e,{cwd:n,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),bn=async e=>{try{return await un(e),!0}catch{return!1}},En=async(e,t,n)=>{let r=v(t,e),i=v(n,e);return await bn(r)?(await gn(r,i),{success:!0}):{success:!1,error:`Source file not found: ${r}`}},Sn=async(e,t)=>{let n=v(t,e);return await re(n,{force:!0}),{success:!0}},Oe=20,$e=async(e,t,n)=>{let r=[];for(let i=0;i<e.length;i+=n){let s=e.slice(i,i+n),o=await Promise.all(s.map(t));r.push(...o)}return r},_n=async(e,t,n,r,i)=>{let s={success:[],deleted:[],failed:[]},o=[...new Set(e.map(d=>mn(v(r,d))))];i.message(`Creating ${o.length} directories...`),await Promise.all(o.map(d=>Ne(d,{recursive:!0}))),i.message(`Updating ${e.length} files...`);let a=await $e(e,async d=>{let c=await En(d,n,r);return{file:d,...c}},Oe);for(let{file:d,success:c,error:u}of a)c?s.success.push(d):s.failed.push({file:d,error:u??"Unknown error"});if(t.length>0){i.message(`Deleting ${t.length} files...`);let d=await $e(t,async c=>{try{return await Sn(c,r),{file:c,success:!0}}catch(u){let l=u instanceof Error?u.message:`${u}`;return{file:c,success:!1,error:l}}},Oe);for(let c of d)c.success?s.deleted.push(c.file):s.failed.push({file:c.file,error:c.error})}return s},Tn=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}`)}},In=e=>e.includes("canary")?"canary":"latest",vn=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(S)}`);if(!t.ok)throw new Error(`Failed to resolve ${S}@${e}`);let r=(await t.json())["dist-tags"]?.[e];if(!r)throw new Error(`Could not find dist-tag ${e} for ${S}`);return r},Pn=async e=>{let t=await M(e),n=J(t,S);if(!n)return{currentVersion:n,nextVersion:void 0,updated:!1};let r=In(n),i=await vn(r);return n===i?{currentVersion:n,nextVersion:i,updateTag:r,updated:!1}:($(t,S,i),await O(e,t),{currentVersion:n,nextVersion:i,updateTag:r,updated:!0})},An=async(e,t,n)=>{let r=await M(e);if(!le(r,S))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:i,nextVersion:s,updateTag:o,updated:a}=await Pn(e);if(!a)return w.success(i?`@vercel/geistdocs is already at ${s} (${o}).`:"No package version update was needed."),B("Package-based site is already up to date."),!0;w.info(`Bumping ${S} from ${i} to ${s} (${o})`);let d=Ge();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},Mn=async(e,t,n,r,i)=>{let s=v(e,te),o=Ge(),a=i?.sync?s:t;o.start("Preparing template snapshot..."),i?.sync&&(await xn(e,te),await N(s)),o.message("Scanning for files...");let d=await Ce(n,r,a),c=[];if(i?.sync){o.message("Comparing with local files...");let l=await Ce(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."),i?.sync&&await ne(s),B("Update cancelled.");return}w.info(`Patterns: ${n.length}`),w.info(`Files to update: ${d.length}`),i?.sync&&w.info(`Files to delete: ${c.length}`),o.start("Updating files...");let u=await _n(d,c,a,e,o);i?.sync&&(o.message("Cleaning up..."),await ne(s)),o.stop("Update complete!"),Tn(u),B("Please review and test the changes carefully.")},Ue=async(e,t)=>{let n=process.cwd(),r=H(),i=e&&e.length>0?e:wn,s=e&&e.length>0?[]:yn;try{if(fn("Let's update your Geistdocs project!"),await An(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 Mn(n,r,i,s,t)}catch(o){let a=o instanceof Error?o.message:`${o}`;try{await ne(v(n,te))}catch{}w.error(`Failed to update project: ${a}`),process.exit(1)}};A.name("geistdocs").description("CLI for Geistdocs projects").version("2.14.3","-v, --version","Output the current version");A.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").addOption(new Rn("--brand <brand>","Navbar brand").choices(["vercel","labs"]).default("vercel")).option("--disable-git","Disable git initialization").action(he);A.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(Ue);A.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(ke);var Fn=A.command("search").description("Manage the external search index used by Ask AI");Fn.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(Pe);await A.parseAsync(process.argv).catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});
|
|
7
|
+
`));let o=await Ie({client:we({apiBaseUrl:process.env.MXBAI_BASE_URL,apiKey:r,storeId:i}),manifest:s,...Nt(n)});console.log(`Geistdocs search sync complete: ${o.uploaded} uploaded, ${o.deleted} deleted, ${o.skipped} unchanged.`)};import{readFileSync as Gt,writeFileSync as Ut}from"fs";import{mkdir as Lt,readFile as Z,writeFile as jt}from"fs/promises";import{dirname as Bt,extname as Vt,relative as Fe,resolve as j}from"path";import{intro as Jt,isCancel as Ht,log as I,multiselect as Xt,outro as L,spinner as Kt}from"@clack/prompts";import{glob as Yt}from"glob";import{Node as F,Project as qt,SyntaxKind as zt}from"ts-morph";var Wt="geistdocs.tsx",Qt="content/docs/**/*.mdx",ee=".translation-cache.json",Q=8,Ae=()=>({version:1,entries:{}}),Zt=async e=>{let t=await Z(e),{createHash:n}=await import("crypto");return n("sha256").update(t).digest("hex")},en=e=>{let t=j(process.cwd(),e);return Gt(t,"utf8")},Me=e=>F.isObjectLiteralExpression(e)?e.getProperties().flatMap(t=>{if(F.isPropertyAssignment(t)){let n=t.getNameNode();if(F.isIdentifier(n)||F.isStringLiteral(n))return[n.getText().replaceAll(/['"]/g,"")]}return[]}).filter(Boolean):[],tn=e=>{try{let t=new qt({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),n=en(e),s=t.createSourceFile(e,n,{overwrite:!0}).getVariableDeclarations().find(a=>a.getName()==="translations")?.getInitializer();if(!s)return[];if(F.isObjectLiteralExpression(s))return Me(s);let o=s.getFirstDescendantByKind(zt.ObjectLiteralExpression);return o?Me(o):[]}catch(t){let n=t instanceof Error?t.message:`${t}`;return I.warn(`Failed to read locales from ${e}: ${n}`),[]}},nn=async()=>{let e=await Xt({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 Ht(e)&&(L("Translation cancelled"),process.exit(0)),e},rn=async e=>(await Yt(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),sn=async()=>{let e=j(process.cwd(),ee);try{let t=await Z(e,"utf8"),n=JSON.parse(t);return n.version!==1||!n.entries?Ae():{version:1,entries:n.entries}}catch{return Ae()}},Re=e=>{let t=j(process.cwd(),ee),n=JSON.stringify(e,null,2);Ut(t,n,"utf8")},on=async e=>{let t=await Promise.all(e.map(async n=>[n,await Zt(n)]));return Object.fromEntries(t)},an=(e,t)=>{let n=Vt(e);return`${e.slice(0,-n.length)}.${t}${n}`},De=(e,t)=>`${Fe(process.cwd(),e)}::${t}`,cn=(e,t,n,r,i=!1)=>{let s=[],o=0;for(let a of t){let d=n[a];for(let c of e){let u=an(a,c),l=De(a,c),m=r.entries[l];if(!i&&m?.hash===d){o+=1;continue}s.push({locale:c,sourceFile:a,sourceHash:d,targetFile:u})}}return{tasks:s,skippedCount:o}},dn=async e=>{await Lt(Bt(e),{recursive:!0})},ln=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 s=await r.text();throw new Error(`API request failed (${r.status}): ${s}`)}let i=await r.json();if(!i.translation)throw new Error("API response did not include a translation");return i.translation},pn=async(e,t,n)=>{let r=await Z(e.sourceFile,"utf8"),i=await ln(t,r,e.locale);await dn(e.targetFile),await jt(e.targetFile,i,"utf8"),n.entries[De(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},ke=async(e,t)=>{Jt("Translate MDX content");let n=e??Qt,r=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",i=tn(t.config??Wt),s=await rn(n);s.length===0&&(I.error(`No MDX files found matching pattern: ${n}`),L("Translation cancelled"),process.exit(1)),I.info(`Found ${s.length} MDX file(s) matching pattern`),i.length===0&&(i=await nn());let o=j(process.cwd(),ee),a=await sn();await Re(a),I.info(`Using cache: ${o}`);let d=await on(s),{tasks:c,skippedCount:u}=cn(i,s,d,a,t.force);if(c.length===0){I.success("All translations are up to date!"),L(`Skipped ${u} file(s) (unchanged)`);return}let l=[];for(let h=0;h<c.length;h+=Q)l.push(c.slice(h,h+Q));I.info(`Processing ${c.length} translation(s) in ${l.length} batch(es) of up to ${Q}`),u>0&&I.info(`Skipped ${u} translation(s) (unchanged)`);let m=Kt();m.start("Translating content...");let f=0;for(let h of l)await Promise.all(h.map(async x=>{await pn(x,r,a),f+=1,m.message(`Translated ${f}/${c.length}: ${Fe(process.cwd(),x.targetFile)}`)})),await Re(a);m.stop("Translation complete!"),L(`Created/updated ${c.length} file(s)`)};import{access as un,copyFile as gn,mkdir as Ne,rm as re}from"fs/promises";import{dirname as mn,join as v}from"path";import{intro as fn,log as w,outro as B,spinner as Ge}from"@clack/prompts";import{glob as hn}from"glob";var wn=["**/*"],yn=["content/docs/**"],te=".geistdocs-tmp",xn=async(e,t)=>{let n=v(e,t);await re(n,{recursive:!0,force:!0}),await Ne(n,{recursive:!0})},ne=async e=>await re(e,{recursive:!0,force:!0}),Ce=async(e,t,n)=>(await hn(e,{cwd:n,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),bn=async e=>{try{return await un(e),!0}catch{return!1}},En=async(e,t,n)=>{let r=v(t,e),i=v(n,e);return await bn(r)?(await gn(r,i),{success:!0}):{success:!1,error:`Source file not found: ${r}`}},Sn=async(e,t)=>{let n=v(t,e);return await re(n,{force:!0}),{success:!0}},Oe=20,$e=async(e,t,n)=>{let r=[];for(let i=0;i<e.length;i+=n){let s=e.slice(i,i+n),o=await Promise.all(s.map(t));r.push(...o)}return r},_n=async(e,t,n,r,i)=>{let s={success:[],deleted:[],failed:[]},o=[...new Set(e.map(d=>mn(v(r,d))))];i.message(`Creating ${o.length} directories...`),await Promise.all(o.map(d=>Ne(d,{recursive:!0}))),i.message(`Updating ${e.length} files...`);let a=await $e(e,async d=>{let c=await En(d,n,r);return{file:d,...c}},Oe);for(let{file:d,success:c,error:u}of a)c?s.success.push(d):s.failed.push({file:d,error:u??"Unknown error"});if(t.length>0){i.message(`Deleting ${t.length} files...`);let d=await $e(t,async c=>{try{return await Sn(c,r),{file:c,success:!0}}catch(u){let l=u instanceof Error?u.message:`${u}`;return{file:c,success:!1,error:l}}},Oe);for(let c of d)c.success?s.deleted.push(c.file):s.failed.push({file:c.file,error:c.error})}return s},Tn=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}`)}},In=e=>e.includes("canary")?"canary":"latest",vn=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(S)}`);if(!t.ok)throw new Error(`Failed to resolve ${S}@${e}`);let r=(await t.json())["dist-tags"]?.[e];if(!r)throw new Error(`Could not find dist-tag ${e} for ${S}`);return r},Pn=async e=>{let t=await M(e),n=J(t,S);if(!n)return{currentVersion:n,nextVersion:void 0,updated:!1};let r=In(n),i=await vn(r);return n===i?{currentVersion:n,nextVersion:i,updateTag:r,updated:!1}:($(t,S,i),await O(e,t),{currentVersion:n,nextVersion:i,updateTag:r,updated:!0})},An=async(e,t,n)=>{let r=await M(e);if(!le(r,S))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:i,nextVersion:s,updateTag:o,updated:a}=await Pn(e);if(!a)return w.success(i?`@vercel/geistdocs is already at ${s} (${o}).`:"No package version update was needed."),B("Package-based site is already up to date."),!0;w.info(`Bumping ${S} from ${i} to ${s} (${o})`);let d=Ge();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},Mn=async(e,t,n,r,i)=>{let s=v(e,te),o=Ge(),a=i?.sync?s:t;o.start("Preparing template snapshot..."),i?.sync&&(await xn(e,te),await N(s)),o.message("Scanning for files...");let d=await Ce(n,r,a),c=[];if(i?.sync){o.message("Comparing with local files...");let l=await Ce(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."),i?.sync&&await ne(s),B("Update cancelled.");return}w.info(`Patterns: ${n.length}`),w.info(`Files to update: ${d.length}`),i?.sync&&w.info(`Files to delete: ${c.length}`),o.start("Updating files...");let u=await _n(d,c,a,e,o);i?.sync&&(o.message("Cleaning up..."),await ne(s)),o.stop("Update complete!"),Tn(u),B("Please review and test the changes carefully.")},Ue=async(e,t)=>{let n=process.cwd(),r=H(),i=e&&e.length>0?e:wn,s=e&&e.length>0?[]:yn;try{if(fn("Let's update your Geistdocs project!"),await An(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 Mn(n,r,i,s,t)}catch(o){let a=o instanceof Error?o.message:`${o}`;try{await ne(v(n,te))}catch{}w.error(`Failed to update project: ${a}`),process.exit(1)}};A.name("geistdocs").description("CLI for Geistdocs projects").version("2.14.4","-v, --version","Output the current version");A.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").addOption(new Rn("--brand <brand>","Navbar brand").choices(["vercel","labs"]).default("vercel")).option("--disable-git","Disable git initialization").action(he);A.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(Ue);A.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(ke);var Fn=A.command("search").description("Manage the external search index used by Ask AI");Fn.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(Pe);await A.parseAsync(process.argv).catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import type { UIMessage } from "ai";
|
|
2
|
+
/**
|
|
3
|
+
* Longest reader message Ask AI accepts, in characters. The chat input stops
|
|
4
|
+
* typing and pasting at this length, and the chat route truncates the last
|
|
5
|
+
* user message to it, since the route is publicly reachable.
|
|
6
|
+
*/
|
|
7
|
+
export declare const MAX_USER_MESSAGE_CHARS = 4000;
|
|
2
8
|
/**
|
|
3
9
|
* The Markdown a reader sees for a message: its non-blank text parts, in
|
|
4
10
|
* order, separated by blank lines. Reasoning, tool, and source parts are
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-text.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/message-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAEpC;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,GAAI,SAAS,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,KAAG,MAUtD,CAAC"}
|
|
1
|
+
{"version":3,"file":"message-text.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/message-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAEpC;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,OAAO,CAAC;AAE3C;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,GAAI,SAAS,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,KAAG,MAUtD,CAAC"}
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Longest reader message Ask AI accepts, in characters. The chat input stops
|
|
3
|
+
* typing and pasting at this length, and the chat route truncates the last
|
|
4
|
+
* user message to it, since the route is publicly reachable.
|
|
5
|
+
*/
|
|
6
|
+
export const MAX_USER_MESSAGE_CHARS = 4000;
|
|
1
7
|
/**
|
|
2
8
|
* The Markdown a reader sees for a message: its non-blank text parts, in
|
|
3
9
|
* order, separated by blank lines. Reasoning, tool, and source parts are
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-input.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/prompt-input.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AACrC,OAAO,EAEL,KAAK,gBAAgB,EAErB,KAAK,SAAS,EAGf,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"prompt-input.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/prompt-input.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AACrC,OAAO,EAEL,KAAK,gBAAgB,EAErB,KAAK,SAAS,EAGf,MAAM,OAAO,CAAC;AAKf,UAAU,oBAAoB;IAC5B,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;IACpB,QAAQ,EAAE,gBAAgB,CAAC,eAAe,CAAC,CAAC;IAC5C,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,WAAW,EAAE,SAAS,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAAC;IACnD,KAAK,EAAE,MAAM,CAAC;CACf;AAED,eAAO,MAAM,eAAe,GAAI,6DAO7B,oBAAoB,4CAoFtB,CAAC"}
|
|
@@ -3,6 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
3
3
|
import { useCallback, useEffect, } from "react";
|
|
4
4
|
import { IconArrowUp, IconStopCircle } from "#geistdocs-assets/icons";
|
|
5
5
|
import { Button } from "#geistdocs-ui/components/button";
|
|
6
|
+
import { MAX_USER_MESSAGE_CHARS } from "./message-text";
|
|
6
7
|
export const ChatPromptInput = ({ onChange, onStop, onSubmit, status, textareaRef, value, }) => {
|
|
7
8
|
const isGenerating = status === "submitted" || status === "streaming";
|
|
8
9
|
const isEmpty = value.trim().length === 0;
|
|
@@ -34,5 +35,5 @@ export const ChatPromptInput = ({ onChange, onStop, onSubmit, status, textareaRe
|
|
|
34
35
|
event.currentTarget.form?.requestSubmit();
|
|
35
36
|
}
|
|
36
37
|
};
|
|
37
|
-
return (_jsx("div", { className: "cursor-text rounded-[12px] border border-gray-300 border-solid pt-2 pb-2 shadow-xs transition-colors duration-250 focus-within:border-gray-500", children: _jsxs("form", { className: "flex flex-col items-center gap-2", onSubmit: onSubmit, children: [_jsx("textarea", { className: "min-h-0 w-full resize-none rounded-none border-0 bg-transparent px-4 py-2 font-sans text-copy-16 text-gray-1000 shadow-none outline-hidden ring-0 placeholder:text-gray-600 focus:outline-none focus-visible:ring-0 min-[768px]:text-copy-14", maxLength:
|
|
38
|
+
return (_jsx("div", { className: "cursor-text rounded-[12px] border border-gray-300 border-solid pt-2 pb-2 shadow-xs transition-colors duration-250 focus-within:border-gray-500", children: _jsxs("form", { className: "flex flex-col items-center gap-2", onSubmit: onSubmit, children: [_jsx("textarea", { className: "min-h-0 w-full resize-none rounded-none border-0 bg-transparent px-4 py-2 font-sans text-copy-16 text-gray-1000 shadow-none outline-hidden ring-0 placeholder:text-gray-600 focus:outline-none focus-visible:ring-0 min-[768px]:text-copy-14", maxLength: MAX_USER_MESSAGE_CHARS, name: "message", onChange: handleChange, onKeyDown: handleKeyDown, placeholder: "Ask a question...", ref: textareaRef, value: value }), _jsx("div", { className: "flex w-full items-center justify-end px-2", children: isGenerating && onStop ? (_jsx(Button, { className: "animate-fade-in-scale", onClick: onStop, prefix: _jsx(IconStopCircle, { className: "size-4" }), size: "small", typeName: "button", children: "Stop" })) : (_jsx(Button, { "aria-label": "Submit", className: "size-8 animate-fade-in-scale p-0", disabled: isEmpty, shape: "square", size: "small", svgOnly: true, typeName: "submit", children: _jsx(IconArrowUp, { className: "size-4" }) })) })] }) }));
|
|
38
39
|
};
|
|
@@ -87,8 +87,8 @@ export declare const resolveEveAgentUrl: ({ configUrl, hasProxy, optionUrl, }: {
|
|
|
87
87
|
}) => string | null;
|
|
88
88
|
/**
|
|
89
89
|
* Cap the text of the trailing user message. The chat client limits input
|
|
90
|
-
* to
|
|
91
|
-
* forward arbitrarily large payloads to the
|
|
90
|
+
* to the same length, but the route is publicly reachable and must not
|
|
91
|
+
* forward arbitrarily large payloads to the model.
|
|
92
92
|
*/
|
|
93
93
|
export declare const capLastUserMessageText: (messages: UIMessage[], limit: number) => UIMessage[];
|
|
94
94
|
/**
|
|
@@ -91,8 +91,8 @@ export const resolveEveAgentUrl = ({ configUrl, hasProxy, optionUrl, }) => {
|
|
|
91
91
|
};
|
|
92
92
|
/**
|
|
93
93
|
* Cap the text of the trailing user message. The chat client limits input
|
|
94
|
-
* to
|
|
95
|
-
* forward arbitrarily large payloads to the
|
|
94
|
+
* to the same length, but the route is publicly reachable and must not
|
|
95
|
+
* forward arbitrarily large payloads to the model.
|
|
96
96
|
*/
|
|
97
97
|
export const capLastUserMessageText = (messages, limit) => {
|
|
98
98
|
const lastMessage = messages.at(-1);
|
package/dist/routes/chat.d.ts
CHANGED
|
@@ -82,6 +82,12 @@ interface ChatEveAgentOptions {
|
|
|
82
82
|
visibleTools?: string[];
|
|
83
83
|
}
|
|
84
84
|
interface ChatRequestLimits {
|
|
85
|
+
/**
|
|
86
|
+
* Most message parts accepted in one request, counted across all
|
|
87
|
+
* messages. Larger requests receive 400.
|
|
88
|
+
* @default 2000
|
|
89
|
+
*/
|
|
90
|
+
maxMessageParts?: number;
|
|
85
91
|
/**
|
|
86
92
|
* Most messages accepted in one request. Larger requests receive 400.
|
|
87
93
|
* @default 200
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.d.ts","sourceRoot":"","sources":["../../src/routes/chat.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,KAAK,aAAa,EAQnB,MAAM,IAAI,CAAC;AAGZ,OAAO,EAAE,KAAK,eAAe,EAAiB,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"chat.d.ts","sourceRoot":"","sources":["../../src/routes/chat.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,KAAK,aAAa,EAQnB,MAAM,IAAI,CAAC;AAGZ,OAAO,EAAE,KAAK,eAAe,EAAiB,MAAM,WAAW,CAAC;AAMhE,OAAO,EAEL,KAAK,qBAAqB,EAG3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAIL,KAAK,qBAAqB,EAU3B,MAAM,uBAAuB,CAAC;AAW/B,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAEvD,KAAK,YAAY,GAAG,qBAAqB,CAAC;AA4B1C;;;GAGG;AACH,KAAK,mBAAmB,GACpB,WAAW,GACX,CAAC,CAAC,OAAO,EAAE,OAAO,KAAK,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC;AAE/D,UAAU,eAAe;IACvB,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;GAOG;AACH,KAAK,oBAAoB,GAAG,MAAM,GAAG,WAAW,CAAC;AAEjD,+EAA+E;AAC/E,UAAU,uBAAuB;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb;AAED,2EAA2E;AAC3E,KAAK,iCAAiC,GAAG,CAAC,OAAO,EAAE;IACjD,WAAW,CAAC,EAAE,uBAAuB,CAAC;CACvC,KAAK,qBAAqB,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAE7D,UAAU,mBAAmB;IAC3B;;;;;;;;;;;;;;OAcG;IACH,aAAa,CAAC,EAAE,OAAO,GAAG,iCAAiC,CAAC;IAC5D;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,qEAAqE;IACrE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AAED,UAAU,iBAAiB;IACzB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;OAOG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,UAAU,sBAAsB;IAC9B,MAAM,EAAE,IAAI,CACV,eAAe,EACb,IAAI,GACJ,UAAU,GACV,iBAAiB,GACjB,QAAQ,GACR,SAAS,GACT,cAAc,CACjB,CAAC;IACF;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;IACxC;;;OAGG;IACH,QAAQ,CAAC,EAAE,mBAAmB,CAAC;IAC/B,4DAA4D;IAC5D,UAAU,CAAC,EAAE,mBAAmB,CAAC;IACjC;;;OAGG;IACH,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B;;;OAGG;IACH,UAAU,CAAC,EAAE,qBAAqB,CAAC;IACnC;;;;;;OAMG;IACH,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,OAAO,CAAC,EAAE,YAAY,EAAE,CAAC;CAC1B;AAquDD,eAAO,MAAM,eAAe,GAAI,wGAW7B,sBAAsB;gBAqBE,OAAO;;CAkMjC,CAAC"}
|
package/dist/routes/chat.js
CHANGED
|
@@ -3,6 +3,7 @@ import { convertToModelMessages, createUIMessageStream, createUIMessageStreamRes
|
|
|
3
3
|
import { initAdvancedSearch } from "fumadocs-core/search/server";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { getPublicPath } from "../config";
|
|
6
|
+
import { MAX_USER_MESSAGE_CHARS } from "../internal/chat/message-text";
|
|
6
7
|
import { createSourceChunk, createSourceChunks, } from "../internal/chat/source-chunks";
|
|
7
8
|
import { createChatDocumentSearch, } from "../internal/chat-retrieval";
|
|
8
9
|
import { buildEveAgentTranscript, capLastUserMessageText, createEmptyEveAgentSession, getEveAgentMessageMetadata, hasPriorEveAgentTurn, normalizeAgentUrl, prewarmExistingEveAgentSession, resolveEveAgentUrl, startOrContinueEveAgentSession, streamEveAgentTurn, } from "../internal/eve-agent";
|
|
@@ -11,7 +12,9 @@ import { isPageVisibleForSurface, } from "../page-visibility";
|
|
|
11
12
|
const DEFAULT_CHAT_MODEL = "openai/gpt-5.6-sol";
|
|
12
13
|
const DEFAULT_MAX_REQUEST_BYTES = 1_000_000;
|
|
13
14
|
const DEFAULT_MAX_MESSAGES = 200;
|
|
15
|
+
const DEFAULT_MAX_MESSAGE_PARTS = 2000;
|
|
14
16
|
const DEFAULT_MAX_PAGE_CONTEXT_CHARS = 200_000;
|
|
17
|
+
const MAX_TOOL_CALL_ID_CHARS = 256;
|
|
15
18
|
const MAX_PAGE_CONTEXT_URL_CHARS = 2048;
|
|
16
19
|
const MAX_CLIENT_CONTEXT_TITLE_CHARS = 256;
|
|
17
20
|
const CONTEXT_INJECTION_MODES = [
|
|
@@ -19,7 +22,6 @@ const CONTEXT_INJECTION_MODES = [
|
|
|
19
22
|
"page-only",
|
|
20
23
|
];
|
|
21
24
|
const MAX_CONTEXT_CHARS = 1500;
|
|
22
|
-
const MAX_EVE_AGENT_MESSAGE_CHARS = 4000;
|
|
23
25
|
const MAX_PROXY_RELATED_PAGES = 5;
|
|
24
26
|
const MAX_TOOL_RESULTS = 8;
|
|
25
27
|
const TRAILING_SLASH_PATTERN = /\/$/;
|
|
@@ -676,6 +678,7 @@ const createChatErrorResponse = (error, status) => new Response(JSON.stringify({
|
|
|
676
678
|
});
|
|
677
679
|
const resolveLimits = (limits) => {
|
|
678
680
|
const resolved = {
|
|
681
|
+
maxMessageParts: limits?.maxMessageParts ?? DEFAULT_MAX_MESSAGE_PARTS,
|
|
679
682
|
maxMessages: limits?.maxMessages ?? DEFAULT_MAX_MESSAGES,
|
|
680
683
|
maxPageContextChars: limits?.maxPageContextChars ?? DEFAULT_MAX_PAGE_CONTEXT_CHARS,
|
|
681
684
|
maxRequestBytes: limits?.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES,
|
|
@@ -785,6 +788,39 @@ const createEveAgentPrewarmResponse = async ({ agentUrl, body, enabled, eveAgent
|
|
|
785
788
|
},
|
|
786
789
|
});
|
|
787
790
|
};
|
|
791
|
+
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
792
|
+
const isToolPartType = (type) => type === "dynamic-tool" || type.startsWith("tool-");
|
|
793
|
+
/**
|
|
794
|
+
* Checks the shape of client-sent message history before any conversion.
|
|
795
|
+
* The AI SDK converts every part of every message, so malformed tool parts
|
|
796
|
+
* (for example, a non-string `toolCallId`) or an unbounded number of parts
|
|
797
|
+
* would otherwise cost CPU and memory on the shared server process before
|
|
798
|
+
* the request is rejected.
|
|
799
|
+
*/
|
|
800
|
+
const validateMessageParts = (messages, limits) => {
|
|
801
|
+
let partCount = 0;
|
|
802
|
+
for (const message of messages) {
|
|
803
|
+
if (!(isPlainObject(message) && Array.isArray(message.parts))) {
|
|
804
|
+
return "each message must be an object with a parts array.";
|
|
805
|
+
}
|
|
806
|
+
partCount += message.parts.length;
|
|
807
|
+
if (partCount > limits.maxMessageParts) {
|
|
808
|
+
return `at most ${limits.maxMessageParts} message parts are allowed.`;
|
|
809
|
+
}
|
|
810
|
+
for (const part of message.parts) {
|
|
811
|
+
if (!(isPlainObject(part) && typeof part.type === "string")) {
|
|
812
|
+
return "each message part must be an object with a string type.";
|
|
813
|
+
}
|
|
814
|
+
if (isToolPartType(part.type) &&
|
|
815
|
+
!(typeof part.toolCallId === "string" &&
|
|
816
|
+
part.toolCallId.length > 0 &&
|
|
817
|
+
part.toolCallId.length <= MAX_TOOL_CALL_ID_CHARS)) {
|
|
818
|
+
return `toolCallId must be a non-empty string of at most ${MAX_TOOL_CALL_ID_CHARS} characters.`;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return null;
|
|
823
|
+
};
|
|
788
824
|
const parsePageContext = (value, limits) => {
|
|
789
825
|
if (value === undefined || value === null) {
|
|
790
826
|
return { value: undefined };
|
|
@@ -850,6 +886,12 @@ const resolveChatRequestBody = async ({ eveAgent, eveAgentUrl, limits, prewarmEn
|
|
|
850
886
|
response: createChatErrorResponse(`Invalid chat request: at most ${limits.maxMessages} messages are allowed.`, 400),
|
|
851
887
|
};
|
|
852
888
|
}
|
|
889
|
+
const messagesError = validateMessageParts(body.messages, limits);
|
|
890
|
+
if (messagesError) {
|
|
891
|
+
return {
|
|
892
|
+
response: createChatErrorResponse(`Invalid chat request: ${messagesError}`, 400),
|
|
893
|
+
};
|
|
894
|
+
}
|
|
853
895
|
const pageContext = parsePageContext(body.pageContext, limits);
|
|
854
896
|
if ("error" in pageContext) {
|
|
855
897
|
return {
|
|
@@ -925,13 +967,12 @@ const createEveAgentErrorStreamResponse = ({ error, messages, signal, }) => {
|
|
|
925
967
|
return createUIMessageStreamResponse({ stream });
|
|
926
968
|
};
|
|
927
969
|
const createEveAgentResponse = async ({ actualMessages, agentUrl, config, contextInjection, currentRoute, defaultLanguage, eveAgent, filterPage, languages, limits, messages, pageContext, req, routeSources, searchDocuments, sessionCodec, }) => {
|
|
928
|
-
const cappedMessages = capLastUserMessageText(actualMessages, MAX_EVE_AGENT_MESSAGE_CHARS);
|
|
929
970
|
const baseUrl = getSiteBaseUrl(config.siteUrl, req);
|
|
930
971
|
const pageOnly = contextInjection === "page-only";
|
|
931
972
|
const { messages: contextMessages, sourceDocs } = pageOnly
|
|
932
|
-
? { messages:
|
|
973
|
+
? { messages: actualMessages, sourceDocs: [] }
|
|
933
974
|
: await buildProxyMessages({
|
|
934
|
-
actualMessages
|
|
975
|
+
actualMessages,
|
|
935
976
|
config,
|
|
936
977
|
currentRoute,
|
|
937
978
|
defaultLanguage,
|
|
@@ -947,7 +988,7 @@ const createEveAgentResponse = async ({ actualMessages, agentUrl, config, contex
|
|
|
947
988
|
}
|
|
948
989
|
const lastMessageText = getMessageText(lastMessage);
|
|
949
990
|
const { continuation, prewarmed } = resolveEveAgentContinuation({
|
|
950
|
-
messages:
|
|
991
|
+
messages: actualMessages,
|
|
951
992
|
req,
|
|
952
993
|
sessionCodec,
|
|
953
994
|
});
|
|
@@ -1097,7 +1138,7 @@ export const createChatRoute = ({ config, contextInjection = "auto", eveAgent, f
|
|
|
1097
1138
|
return resolvedRequest.response;
|
|
1098
1139
|
}
|
|
1099
1140
|
const { currentRoute, messages, pageContext } = resolvedRequest.body;
|
|
1100
|
-
const actualMessages = messages.filter((message) => !isPageContextMessage(message));
|
|
1141
|
+
const actualMessages = capLastUserMessageText(messages.filter((message) => !isPageContextMessage(message)), MAX_USER_MESSAGE_CHARS);
|
|
1101
1142
|
if (eveAgentUrl) {
|
|
1102
1143
|
return await createEveAgentResponse({
|
|
1103
1144
|
actualMessages,
|
package/docs/agents.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Geistdocs Package Docs
|
|
2
2
|
|
|
3
|
-
These docs are bundled with `@vercel/geistdocs` 2.14.
|
|
3
|
+
These docs are bundled with `@vercel/geistdocs` 2.14.4 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
|
package/docs/llms.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Geistdocs Package Documentation
|
|
2
2
|
|
|
3
|
-
These docs are bundled with `@vercel/geistdocs` 2.14.
|
|
3
|
+
These docs are bundled with `@vercel/geistdocs` 2.14.4.
|
|
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
|
|
@@ -4594,10 +4594,13 @@ The Vertex route forwards `{ messages, platform: "vercel" }` with the `x-client-
|
|
|
4594
4594
|
| --------------------- | ---------------------------- | ---------------------- |
|
|
4595
4595
|
| `maxRequestBytes` | `1_000_000` bytes (1 MB) | `413` |
|
|
4596
4596
|
| `maxMessages` | `200` messages | `400` |
|
|
4597
|
+
| `maxMessageParts` | `2_000` parts, all messages | `400` |
|
|
4597
4598
|
| `maxPageContextChars` | `200_000` characters | `400` |
|
|
4598
4599
|
|
|
4599
4600
|
Rejected requests receive a JSON body in the form `{ "error": "..." }`. The route reads the request body as a stream and stops as soon as it passes `maxRequestBytes`, and rejects a request whose `Content-Length` header is over the cap without reading the body. An oversized `pageContext.content` is rejected, not truncated.
|
|
4600
4601
|
|
|
4602
|
+
The route also checks the shape of the message history before converting it for the model. Each message needs a `parts` array, each part needs a string `type`, and each tool part (`tool-*` or `dynamic-tool`) needs a `toolCallId` that is a non-empty string of at most 256 characters. Other requests receive `400`.
|
|
4603
|
+
|
|
4601
4604
|
`maxPageContextChars` only rejects `pageContext.content` that API callers send with the page text. The Ask AI client sends `pageContext: { url }` without content, and the route reads that page from the site's own sources; with `contextInjection: "page-only"`, that page's Markdown is truncated to `maxPageContextChars` before it is forwarded. `pageContext.url` must be a non-empty string of at most 2,048 characters in both shapes; other values receive `400`.
|
|
4602
4605
|
|
|
4603
4606
|
Change the limits with the `limits` option:
|
|
@@ -4609,6 +4612,7 @@ export const { POST, maxDuration } = createChatRoute({
|
|
|
4609
4612
|
limits: {
|
|
4610
4613
|
maxRequestBytes: 500_000,
|
|
4611
4614
|
maxMessages: 100,
|
|
4615
|
+
maxMessageParts: 1_000,
|
|
4612
4616
|
maxPageContextChars: 100_000,
|
|
4613
4617
|
},
|
|
4614
4618
|
});
|
package/docs/manifest.json
CHANGED
package/docs/pages/ask-ai.md
CHANGED
|
@@ -642,10 +642,13 @@ The Vertex route forwards `{ messages, platform: "vercel" }` with the `x-client-
|
|
|
642
642
|
| --------------------- | ---------------------------- | ---------------------- |
|
|
643
643
|
| `maxRequestBytes` | `1_000_000` bytes (1 MB) | `413` |
|
|
644
644
|
| `maxMessages` | `200` messages | `400` |
|
|
645
|
+
| `maxMessageParts` | `2_000` parts, all messages | `400` |
|
|
645
646
|
| `maxPageContextChars` | `200_000` characters | `400` |
|
|
646
647
|
|
|
647
648
|
Rejected requests receive a JSON body in the form `{ "error": "..." }`. The route reads the request body as a stream and stops as soon as it passes `maxRequestBytes`, and rejects a request whose `Content-Length` header is over the cap without reading the body. An oversized `pageContext.content` is rejected, not truncated.
|
|
648
649
|
|
|
650
|
+
The route also checks the shape of the message history before converting it for the model. Each message needs a `parts` array, each part needs a string `type`, and each tool part (`tool-*` or `dynamic-tool`) needs a `toolCallId` that is a non-empty string of at most 256 characters. Other requests receive `400`.
|
|
651
|
+
|
|
649
652
|
`maxPageContextChars` only rejects `pageContext.content` that API callers send with the page text. The Ask AI client sends `pageContext: { url }` without content, and the route reads that page from the site's own sources; with `contextInjection: "page-only"`, that page's Markdown is truncated to `maxPageContextChars` before it is forwarded. `pageContext.url` must be a non-empty string of at most 2,048 characters in both shapes; other values receive `400`.
|
|
650
653
|
|
|
651
654
|
Change the limits with the `limits` option:
|
|
@@ -657,6 +660,7 @@ export const { POST, maxDuration } = createChatRoute({
|
|
|
657
660
|
limits: {
|
|
658
661
|
maxRequestBytes: 500_000,
|
|
659
662
|
maxMessages: 100,
|
|
663
|
+
maxMessageParts: 1_000,
|
|
660
664
|
maxPageContextChars: 100_000,
|
|
661
665
|
},
|
|
662
666
|
});
|
package/package.json
CHANGED
|
@@ -499,10 +499,13 @@ export const ai = {
|
|
|
499
499
|
| --------------------- | ------------------------ | ------------ |
|
|
500
500
|
| `maxRequestBytes` | `1_000_000` 字节(1 MB) | `413` |
|
|
501
501
|
| `maxMessages` | `200` 条消息 | `400` |
|
|
502
|
+
| `maxMessageParts` | 所有消息共 `2_000` 个部分 | `400` |
|
|
502
503
|
| `maxPageContextChars` | `200_000` 个字符 | `400` |
|
|
503
504
|
|
|
504
505
|
被拒绝的请求会收到 `{ "error": "..." }` 格式的 JSON 响应。过长的 `pageContext.content` 会被拒绝,而不是被截断。
|
|
505
506
|
|
|
507
|
+
路由还会在为模型转换消息历史之前检查其结构。每条消息都必须包含 `parts` 数组,每个部分都必须有字符串类型的 `type`,每个工具部分(`tool-*` 或 `dynamic-tool`)的 `toolCallId` 都必须是最多 256 个字符的非空字符串,否则返回 `400`。
|
|
508
|
+
|
|
506
509
|
`maxPageContextChars` 只会拒绝 API 调用方随页面文本一起发送的 `pageContext.content`。Ask AI 客户端发送不含内容的 `pageContext: { url }`,路由会从站点自身的来源读取该页面;使用 `contextInjection: "page-only"` 时,该页面的 Markdown 会在转发前截断到 `maxPageContextChars`。两种形式中的 `pageContext.url` 都必须是最多 2,048 个字符的非空字符串,否则返回 `400`。
|
|
507
510
|
|
|
508
511
|
使用 `limits` 选项修改这些限制:
|
|
@@ -514,6 +517,7 @@ export const { POST, maxDuration } = createChatRoute({
|
|
|
514
517
|
limits: {
|
|
515
518
|
maxRequestBytes: 500_000,
|
|
516
519
|
maxMessages: 100,
|
|
520
|
+
maxMessageParts: 1_000,
|
|
517
521
|
maxPageContextChars: 100_000,
|
|
518
522
|
},
|
|
519
523
|
});
|
|
@@ -640,10 +640,13 @@ The Vertex route forwards `{ messages, platform: "vercel" }` with the `x-client-
|
|
|
640
640
|
| --------------------- | ---------------------------- | ---------------------- |
|
|
641
641
|
| `maxRequestBytes` | `1_000_000` bytes (1 MB) | `413` |
|
|
642
642
|
| `maxMessages` | `200` messages | `400` |
|
|
643
|
+
| `maxMessageParts` | `2_000` parts, all messages | `400` |
|
|
643
644
|
| `maxPageContextChars` | `200_000` characters | `400` |
|
|
644
645
|
|
|
645
646
|
Rejected requests receive a JSON body in the form `{ "error": "..." }`. The route reads the request body as a stream and stops as soon as it passes `maxRequestBytes`, and rejects a request whose `Content-Length` header is over the cap without reading the body. An oversized `pageContext.content` is rejected, not truncated.
|
|
646
647
|
|
|
648
|
+
The route also checks the shape of the message history before converting it for the model. Each message needs a `parts` array, each part needs a string `type`, and each tool part (`tool-*` or `dynamic-tool`) needs a `toolCallId` that is a non-empty string of at most 256 characters. Other requests receive `400`.
|
|
649
|
+
|
|
647
650
|
`maxPageContextChars` only rejects `pageContext.content` that API callers send with the page text. The Ask AI client sends `pageContext: { url }` without content, and the route reads that page from the site's own sources; with `contextInjection: "page-only"`, that page's Markdown is truncated to `maxPageContextChars` before it is forwarded. `pageContext.url` must be a non-empty string of at most 2,048 characters in both shapes; other values receive `400`.
|
|
648
651
|
|
|
649
652
|
Change the limits with the `limits` option:
|
|
@@ -655,6 +658,7 @@ export const { POST, maxDuration } = createChatRoute({
|
|
|
655
658
|
limits: {
|
|
656
659
|
maxRequestBytes: 500_000,
|
|
657
660
|
maxMessages: 100,
|
|
661
|
+
maxMessageParts: 1_000,
|
|
658
662
|
maxPageContextChars: 100_000,
|
|
659
663
|
},
|
|
660
664
|
});
|
package/template/package.json
CHANGED