THE XIALEI TOOLBOX · UNDER THE HOOD
The code. The explanations.
All four Tools, opened up. Understand what each tool does, how its files fit together, and what to check before using or modifying it.
11 SOURCE FILES
Drupal to React/Vue starter
Imports authorized public Drupal JSON:API content and packages it as a React or Vue website starter. The optional reader module lets a Drupal administrator allow read-only browser access from Xialei.
How it works
- The converter checks your HTTPS site address and permission confirmation, discovers content types, and follows limited JSON:API pagination without sending credentials.
- Imported titles, URL aliases and plain-text bodies form a temporary browser snapshot. The export builder creates package.json, Vite configuration, frontend code, styles, a report and a README, then compresses them with fflate.
- The generated React/Vue app reads live Drupal content on page load. If that request fails, it clearly labels and displays the exported snapshot instead.
- The Drupal module starts disabled. Its admin form saves a configuration setting; its event subscriber allows only the exact https://xialei.com origin on JSON:API GET/limited OPTIONS requests. Drupal content permissions still apply.
What you need
Converter: a Drupal site exposing authorized public JSON:API content. Reader module: Drupal 10/11 with core JSON:API. Exported app: Node.js and a frontend host with page-route fallback and its own allowed origin.
Privacy, safety & limits
Not a theme clone: rich body formatting, media, custom fields, menus, translations, search, forms, accounts and commerce need separate work. CORS is not authorization. Test the module on staging; it has not been verified in a running Drupal site.
Files & complete source code
xialei_reader/config/install/xialei_reader.settings.yml
Default module configuration: browser sharing is disabled until an administrator enables it.
enabled: false
xialei_reader/config/schema/xialei_reader.schema.yml
Declares the enabled configuration value as a boolean for Drupal’s configuration system.
xialei_reader.settings:
type: config_object
label: 'Xialei reader settings'
mapping:
enabled:
type: boolean
label: 'Allow read-only requests from https://xialei.com'
xialei_reader/README.txt
Complete installation, usage, privacy and troubleshooting notes distributed with this kit.
Xialei Public Content Reader — 0.1.0 beta
Requires Drupal 10 or 11 and core JSON:API.
INSTALL
1. Back up your site and test on staging first.
2. Extract this ZIP. Place the xialei_reader folder in your Drupal web root's modules/custom directory.
3. In Administration > Extend, enable Xialei Public Content Reader (and JSON:API).
4. Open Configuration > Web services > Xialei public content reader.
5. Review anonymous content permissions, field exposure, and JSON:API read-only settings. Test anonymously that only intended published content is accessible. This module does not change those settings.
6. Check Allow https://xialei.com to read public JSON:API content, then Save configuration.
7. Clear Drupal and CDN caches. Retry from the live https://xialei.com converter, using your Drupal HTTPS root address.
Only the exact https://xialei.com origin is allowed, not preview domains. GET and its OPTIONS preflight are supported; credentials and writes are not enabled. Drupal still enforces all existing access checks. CORS is a browser sharing rule, not a content permission or a way to prevent other clients reading public data.
Server, CDN, firewall, and existing Drupal CORS middleware can block requests before this module runs. Ask your administrator to reconcile those rules; never disable access checks. For the exported website, configure its own origin separately.
DISABLE
Uncheck the setting, save, and clear Drupal/CDN caches. You can also uninstall the module. Already downloaded content cannot be revoked.
This beta has not been tested in a running Drupal installation. Review and test before production use. No external requests, credentials, or content modifications are performed by this module.
xialei_reader/src/EventSubscriber/CorsSubscriber.php
Drupal request/response listener: exact-origin read-only browser sharing and limited preflight responses. It does not grant content access.
<?php
namespace Drupal\xialei_reader\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class CorsSubscriber implements EventSubscriberInterface {
protected $configFactory;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
public static function getSubscribedEvents() {
return [KernelEvents::REQUEST => ['preflight', 300], KernelEvents::RESPONSE => ['response', -300]];
}
protected function eligible($request) {
return $this->configFactory->get('xialei_reader.settings')->get('enabled')
&& $request->headers->get('Origin') === 'https://xialei.com'
&& preg_match('#^/jsonapi(?:/|$)#', $request->getPathInfo());
}
public function preflight(RequestEvent $event) {
$request = $event->getRequest();
if (!$event->isMainRequest() || !$this->eligible($request) || $request->getMethod() !== 'OPTIONS') {
return;
}
if ($request->headers->get('Access-Control-Request-Method') !== 'GET') {
return;
}
$headers = strtolower($request->headers->get('Access-Control-Request-Headers', ''));
foreach (array_filter(array_map('trim', explode(',', $headers))) as $header) {
if ($header !== 'accept') {
return;
}
}
$event->setResponse(new Response('', 204));
}
public function response(ResponseEvent $event) {
$request = $event->getRequest();
if (!$event->isMainRequest() || !preg_match('#^/jsonapi(?:/|$)#', $request->getPathInfo())) {
return;
}
$response = $event->getResponse();
$response->setVary('Origin', false);
if (!$this->eligible($request) || !in_array($request->getMethod(), ['GET', 'OPTIONS'], true)) {
return;
}
$response->headers->set('Access-Control-Allow-Origin', 'https://xialei.com');
$response->headers->set('Access-Control-Allow-Methods', 'GET, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Accept');
$response->headers->remove('Access-Control-Allow-Credentials');
}
}
xialei_reader/src/Form/SettingsForm.php
Drupal administrator configuration form that reads and saves the module’s enabled setting.
<?php
namespace Drupal\xialei_reader\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
class SettingsForm extends ConfigFormBase {
public function getFormId() {
return 'xialei_reader_settings';
}
protected function getEditableConfigNames() {
return ['xialei_reader.settings'];
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['enabled'] = [
'#type' => 'checkbox',
'#title' => $this->t('Allow https://xialei.com to read public JSON:API content'),
'#default_value' => $this->config('xialei_reader.settings')->get('enabled'),
'#description' => $this->t('Only GET requests are allowed. This does not grant permissions or make private content public. Review anonymous access and field exposure before enabling. Existing server or CDN CORS rules may also need adjustment.'),
];
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config('xialei_reader.settings')->set('enabled', (bool) $form_state->getValue('enabled'))->save();
parent::submitForm($form, $form_state);
}
}
xialei_reader/xialei_reader.info.yml
Module identity, description, Drupal version support and JSON:API dependency.
name: Xialei Public Content Reader
type: module
description: Administrator-controlled read-only CORS for the Xialei converter. Does not grant content access.
package: Web services
core_version_requirement: ^10 || ^11
dependencies:
- drupal:jsonapi
configure: xialei_reader.settings
xialei_reader/xialei_reader.links.menu.yml
Adds the settings link to Drupal’s administration menu.
xialei_reader.settings:
title: 'Xialei public content reader'
description: 'Allow Xialei to read content already available anonymously.'
parent: system.admin_config_services
route_name: xialei_reader.settings
xialei_reader/xialei_reader.routing.yml
Admin settings URL, form class and required administration permission.
xialei_reader.settings:
path: '/admin/config/services/xialei-reader'
defaults:
_form: '\Drupal\xialei_reader\Form\SettingsForm'
_title: 'Xialei public content reader'
requirements:
_permission: 'administer site configuration'
xialei_reader/xialei_reader.services.yml
Registers the CORS event subscriber with Drupal’s configuration service.
services:
xialei_reader.cors:
class: Drupal\xialei_reader\EventSubscriber\CorsSubscriber
arguments: ['@config.factory']
tags:
- { name: event_subscriber }
src/lib/drupalExport.ts
ZIP builder and the complete generated React/Vue templates, live Drupal reader, snapshot fallback, configuration and report.
import { strToU8, zipSync } from 'fflate';
export interface DrupalPage {
id: string;
title: string;
body: string;
path: string;
type: string;
}
export function createDrupalExport(origin: string, endpoints: string[], pages: DrupalPage[], framework: 'react' | 'vue') {
const shared = `export const source = ${JSON.stringify(origin)};
export const endpoints = ${JSON.stringify(endpoints)};
export const snapshot = ${JSON.stringify(pages)};
const text = value => new DOMParser().parseFromString(String(value || ''), 'text/html').body.textContent || '';
export async function loadPages() {
const pages = [];
for (const endpoint of endpoints) {
let next = new URL(endpoint, source).href;
const seen = new Set();
while (next) {
const url = new URL(next, source);
if (url.origin !== source || !url.pathname.startsWith('/jsonapi/')) throw new Error('Unexpected Drupal pagination URL');
if (seen.has(url.href) || seen.size >= 20) throw new Error('Content exceeds the supported pagination limit');
seen.add(url.href);
const response = await fetch(url, {headers: {Accept: 'application/vnd.api+json'}, credentials: 'omit'});
if (!response.ok) throw new Error('Drupal returned ' + response.status);
const data = await response.json();
if (!Array.isArray(data.data)) throw new Error('Unexpected Drupal response');
for (const item of data.data) {
const a = item.attributes || {};
if (a.status === false) continue;
const alias = a.path?.alias;
const path = typeof alias === 'string' && /^\\/(?!\\/)/.test(alias) && !/[\\\\?#]/.test(alias) ? alias : '/node/' + (Number(a.drupal_internal__nid) || encodeURIComponent(item.id));
pages.push({id:item.id, title:String(a.title || 'Untitled'), body:text(a.body?.processed || a.body?.value), path, type:item.type});
}
next = data.links?.next?.href || null;
}
}
return pages;
}
`;
const css = `*{box-sizing:border-box}body{margin:0;background:#f4f7fa;color:#172b3a;font:16px/1.6 system-ui,sans-serif}header,main,footer{max-width:1100px;margin:auto;padding:32px 24px}header{border-bottom:1px solid #d5dfe7}h1,h2{line-height:1.2}a{color:#096799}nav{display:flex;gap:16px;flex-wrap:wrap}article{background:white;padding:32px;border:1px solid #d5dfe7;border-radius:16px;margin:24px 0}.body{white-space:pre-wrap}.notice{padding:16px;background:#fff0cf;color:#604400}button{padding:12px;border:0;background:#096799;color:white;border-radius:8px;cursor:pointer}footer{color:#4f6677}`;
const files: Record<string, string> = {
'package.json': JSON.stringify({ name: 'drupal-frontend', private: true, version: '1.0.0', type: 'module', scripts: { dev: 'vite', build: 'vite build', preview: 'vite preview' }, dependencies: framework === 'react' ? { react: '^19.0.0', 'react-dom': '^19.0.0' } : { vue: '^3.5.0' }, devDependencies: framework === 'react' ? { vite: '^6.0.0', '@vitejs/plugin-react': '^4.3.0' } : { vite: '^6.0.0', '@vitejs/plugin-vue': '^5.2.0' } }, null, 2),
'index.html': '<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Drupal content website</title></head><body><div id="app"></div><script type="module" src="/src/main.js"></script></body></html>',
'src/drupal.js': shared,
'src/style.css': css,
'conversion-report.json': JSON.stringify({ source: origin, framework, exportedPages: pages.length, endpoints, limitations: ['Plain-text body content only; original themes and rich formatting are not converted.', 'Menus are generated from imported pages, not Drupal menu configuration.', 'Media relationships, custom fields, translations, forms, accounts, search and commerce require separate implementation.', 'Drupal must permit public read access and browser requests from the deployed frontend.', 'Configure frontend hosting to serve index.html for page routes.', 'Pagination is limited to 20 responses per content type.'] }, null, 2),
'README.md': `# Drupal ${framework} frontend\n\nDrupal stays unchanged and remains the content editor. This starter reads the selected public JSON:API content types at page load. It includes an import snapshot, clearly labelled if live loading fails.\n\n## Run and publish\nInstall Node.js, then run npm install and npm run dev. For publishing run npm run build and deploy dist to a static host. Configure the host to serve index.html for all page routes.\n\n## Drupal setup\nEnable core JSON:API, allow anonymous access only to intended published content, and configure CORS for your frontend origin. Never place admin credentials or secret tokens in this frontend.\n\n## Scope\nThis is a content-based starter, not a theme or functionality clone. Body HTML is converted to plain text for safe rendering. Review conversion-report.json before publishing. Preserve source URL aliases where possible and review redirects and SEO separately.\n`,
};
if (framework === 'react') {
files['vite.config.js'] = "import {defineConfig} from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({plugins:[react()]});";
files['src/main.js'] = "import React from 'react'; import {createRoot} from 'react-dom/client'; import App from './App.jsx'; import './style.css'; createRoot(document.getElementById('app')).render(React.createElement(App));";
files['src/App.jsx'] = `import {useEffect,useState} from 'react';
import {source,snapshot,loadPages} from './drupal';
export default function App(){
const [pages,setPages]=useState(snapshot),[notice,setNotice]=useState('Loading live Drupal content…'),[path,setPath]=useState(location.pathname);
useEffect(()=>{let active=true;loadPages().then(p=>{if(active){setPages(p);setNotice('');}}).catch(()=>{if(active)setNotice('Live Drupal content could not be loaded. Showing the exported snapshot. Check Drupal access and CORS settings.');});const pop=()=>setPath(location.pathname);addEventListener('popstate',pop);return()=>{active=false;removeEventListener('popstate',pop);};},[]);
const go=(event,p)=>{event.preventDefault();history.pushState({},'',p);setPath(p);};
const selected=pages.find(p=>p.path===path);
return <><header><h1>Drupal content website</h1><nav><a href="/" onClick={e=>go(e,'/')}>Home</a><a href={source} target="_blank" rel="noopener noreferrer">Original Drupal site</a></nav></header><main>{notice&&<p className="notice" role="status">{notice}</p>}{selected?<article><h2>{selected.title}</h2><p className="body">{selected.body}</p></article>:path==='/'?<><h2>Published pages</h2>{pages.length?pages.map(p=><article key={p.id}><h2><a href={p.path} onClick={e=>go(e,p.path)}>{p.title}</a></h2><p>{p.body.slice(0,240)}</p></article>):<p>No published content is available.</p>}</>:<><h2>Page not found</h2><a href="/" onClick={e=>go(e,'/')}>Back to home</a></>}</main><footer>Content managed in Drupal · React frontend</footer></>;
}`;
} else {
files['vite.config.js'] = "import {defineConfig} from 'vite'; import vue from '@vitejs/plugin-vue'; export default defineConfig({plugins:[vue()]});";
files['src/main.js'] = "import {createApp} from 'vue'; import App from './App.vue'; import './style.css'; createApp(App).mount('#app');";
files['src/App.vue'] = `<script setup>
import {ref,computed,onMounted,onUnmounted} from 'vue';
import {source,snapshot,loadPages} from './drupal';
const pages=ref(snapshot),notice=ref('Loading live Drupal content…'),path=ref(location.pathname);
const selected=computed(()=>pages.value.find(p=>p.path===path.value));
const pop=()=>path.value=location.pathname;
const go=(event,p)=>{event.preventDefault();history.pushState({},'',p);path.value=p;};
let active=true;
onMounted(async()=>{addEventListener('popstate',pop);try{const data=await loadPages();if(active){pages.value=data;notice.value='';}}catch{if(active)notice.value='Live Drupal content could not be loaded. Showing the exported snapshot. Check Drupal access and CORS settings.';}});
onUnmounted(()=>{active=false;removeEventListener('popstate',pop);});
</script>
<template><header><h1>Drupal content website</h1><nav><a href="/" @click="go($event,'/')">Home</a><a :href="source" target="_blank" rel="noopener noreferrer">Original Drupal site</a></nav></header><main><p v-if="notice" class="notice" role="status">{{notice}}</p><article v-if="selected"><h2>{{selected.title}}</h2><p class="body">{{selected.body}}</p></article><template v-else-if="path==='/'"><h2>Published pages</h2><article v-for="p in pages" :key="p.id"><h2><a :href="p.path" @click="go($event,p.path)">{{p.title}}</a></h2><p>{{p.body.slice(0,240)}}</p></article><p v-if="!pages.length">No published content is available.</p></template><template v-else><h2>Page not found</h2><a href="/" @click="go($event,'/')">Back to home</a></template></main><footer>Content managed in Drupal · Vue frontend</footer></template>`;
}
return zipSync(Object.fromEntries(Object.entries(files).map(([path, content]) => [path, strToU8(content)])));
}
src/pages/drupal-converter.astro
Converter interface, public-content validation/import, preview and download actions. Its script imports the export builder shown below.
---
import Layout from '../layouts/Layout.astro';
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
---
<Layout title="Drupal to React/Vue Starter — Beta | Xia Lei" description="Try the beta Drupal content converter: download a React or Vue starter while keeping Drupal as your backend. Planned release: 1 December 2026.">
<Header />
<main class="converter">
<header class="converter-hero">
<p class="eyebrow">THE XIALEI TOOLBOX · PUBLIC BETA</p>
<h1>Keep your content.<br /><span>Reimagine your frontend.</span></h1>
<p class="lead">Drupal content to React/Vue starter. Keep editing in Drupal; build your next website with a fresh frontend.</p>
<div class="hero-actions"><a class="module-download" href="#connect-heading">Start your import →</a><a class="hero-secondary" href="#module-heading">Get the Drupal module</a></div>
<div class="pipeline" aria-label="Drupal content becomes a React or Vue starter"><span>Drupal <small>Your content home</small></span><b aria-hidden="true">→</b><span>React / Vue <small>Your next frontend</small></span></div>
</header>
<aside class="release-notice" aria-label="Beta release information">
<strong>Beta — available to try now</strong>
<p>Version 1.0 release planned for <time datetime="2026-12-01">1 December 2026</time>. Try the public-content import and review your downloaded starter before using it for a live website.</p>
<a href="mailto:xialei@xialei.com?subject=Drupal%20converter%20beta%20feedback">Send beta feedback →</a>
</aside>
<div class="steps"><span><b>01</b> Connect Drupal</span><span><b>02</b> Choose content</span><span><b>03</b> Download starter</span></div>
<section class="panel" aria-labelledby="module-heading">
<h2 id="module-heading">Allow access from Drupal administration</h2>
<p>Own or administer the Drupal site? Download our small beta module for Drupal 10 and 11. It adds a setting to allow read-only browser requests from https://xialei.com. It does not make private content public or change content permissions.</p>
<p><a class="module-download" href="/downloads/xialei-reader-beta.zip" download>Download Drupal reader module · Beta ZIP</a></p>
<details class="install-guide"><summary>Installation & administrator setup</summary>
<ol>
<li>Back up your site and test the module on a staging copy first.</li>
<li>Ask your administrator to extract the module into Drupal’s custom modules folder and enable <strong>Xialei Public Content Reader</strong> under <strong>Extend</strong>.</li>
<li>Review anonymous access to the intended published content and keep JSON:API read-only.</li>
<li>Go to <strong>Configuration → Web services → Xialei public content reader</strong>, enable the checkbox, and save.</li>
<li>Clear Drupal and CDN caches, then retry the converter from the live Xialei website.</li>
</ol>
</details>
<p>Disabled by default. Only the exact Xialei origin is supported, not preview addresses. Existing hosting or CORS rules may still require administrator changes. The downloaded starter’s own website address needs separate permission after publishing.</p>
<p>This module is an unverified Drupal beta; installation instructions and disabling steps are included in the ZIP.</p>
</section>
<section class="panel">
<p class="panel-kicker">STEP 01 · CONNECT</p>
<h2 id="connect-heading">Connect your Drupal site</h2>
<p>For Drupal 8.7+ with JSON:API enabled. Public content must be readable, and Drupal must allow browser requests from this website.</p>
<form id="connect-form">
<label for="site-url">Drupal website address</label>
<input id="site-url" type="url" placeholder="Paste your Drupal website address" required />
<label for="framework">New frontend</label>
<select id="framework"><option value="react">React</option><option value="vue">Vue</option></select>
<label class="permission"><input id="permission" type="checkbox" required /> I own this site or have permission to import its public content.</label>
<button id="connect" type="submit">Discover content types</button>
</form>
<p id="status" role="status" aria-live="polite"></p>
</section>
<section class="panel" aria-labelledby="options-heading">
<p class="panel-kicker">CONVERSION OPTIONS</p>
<h2 id="options-heading">What would you like to bring across?</h2>
<p>This beta supports the content starter below. Advanced options are listed for clarity but cannot be selected or included in your download yet.</p>
<div class="conversion-options">
<article><span class="option-status available">Included in beta</span><h3>Content starter</h3><p>Page titles, plain text, URL aliases, basic page navigation and live Drupal content. Choose React or Vue above and your content types after connecting.</p></article>
<article><span class="option-status">Not available yet</span><h3>Images & media</h3><p>Preserve images, captions and linked media. Requires access to Drupal’s media and file relationships.</p></article>
<article><span class="option-status">Not available yet</span><h3>Original menus</h3><p>Preserve Drupal menu structure and ordering rather than generate basic page navigation.</p></article>
<article><span class="option-status">Not available yet</span><h3>Translations</h3><p>Bring across language versions with language-specific navigation and page addresses.</p></article>
<article><span class="option-status">Requires a custom rebuild</span><h3>Theme & design</h3><p>Drupal’s theme cannot be automatically converted. Recreating the original design needs a separate frontend design project.</p></article>
</div>
</section>
<section class="panel" id="selection" hidden>
<p class="panel-kicker">STEP 02 · SELECT</p>
<h2>Choose what to import</h2>
<p>Only published node content is imported. Select the page and article types you want in your new website.</p>
<div id="content-types"></div>
<button id="export" type="button">Import and download ZIP</button>
</section>
<section class="panel" id="result" hidden>
<p class="panel-kicker">STEP 03 · READY</p>
<h2>Your content preview</h2><p id="result-summary"></p><div id="preview"></div>
<button id="download-again" type="button">Download again</button>
<p>Your starter is ready for review, not automatically published. Follow the launch checklist below.</p>
<a class="hero-secondary" href="#launch-heading">What happens next? →</a>
</section>
<section class="panel" aria-labelledby="launch-heading">
<p class="panel-kicker">AFTER YOUR DOWNLOAD</p>
<h2 id="launch-heading">Your client’s launch checklist</h2>
<p>The ZIP is a website starter, not a hosted website. Your client can hand it to their developer or hosting partner along with these steps.</p>
<ol>
<li><strong>Review the export.</strong> Extract the ZIP and read the included setup instructions and conversion report. Check page content, addresses and anything that still needs rebuilding.</li>
<li><strong>Finish the website.</strong> Have a developer run the starter, apply the client’s branding and complete missing images, menus, translations or other required features.</li>
<li><strong>Arrange hosting.</strong> Deploy the finished website with HTTPS and a domain. The host must send page-address requests to the starter’s main page so direct links work.</li>
<li><strong>Allow the new website to read Drupal.</strong> Ask the Drupal administrator to permit the new website’s exact address for read-only browser requests. The downloadable module permits Xialei only, not the client’s new website.</li>
<li><strong>Test before launch.</strong> Check navigation, direct page links, mobile layouts and live content updates. Confirm private content remains inaccessible and no administrator credentials are included.</li>
<li><strong>Keep Drupal running.</strong> The client continues editing in Drupal. Maintain its hosting, security updates and backups; the embedded snapshot is a fallback, not a replacement for live Drupal.</li>
</ol>
<p>No Drupal content is changed by converting. Do not switch the client’s domain until the new website is reviewed and ready.</p>
</section>
<section class="scope">
<h2>A content starter, not a one-click clone</h2>
<div class="scope-grid"><div><h3>Included</h3><p>Public page titles, text bodies, URL aliases, page navigation, live Drupal reading, a clearly labelled backup snapshot, and a conversion report.</p></div><div><h3>Not converted automatically</h3><p>Your original theme, images and media relationships, custom fields, menus, translations, forms, search, user accounts, or commerce. Body formatting is converted to plain text.</p></div></div>
<h3>If the connection fails</h3><p>Ask your Drupal administrator to enable JSON:API and permit public reads of the intended content. Configure Drupal’s CORS settings to allow this website for importing and your new frontend’s address after publishing. Do not expose private content or put administrator credentials into the frontend.</p>
<p>The download is a source-code project, not a hosted website. It includes setup instructions and a report for deployment and review. Imports are processed in your browser, not saved to this website.</p>
<a href="/drupal-guide">Read the Drupal guide →</a>
</section>
</main>
<Footer />
</Layout>
<script>
import { createDrupalExport, type DrupalPage } from '../lib/drupalExport';
const form = document.querySelector<HTMLFormElement>('#connect-form')!;
const site = document.querySelector<HTMLInputElement>('#site-url')!;
const framework = document.querySelector<HTMLSelectElement>('#framework')!;
const status = document.querySelector<HTMLElement>('#status')!;
const connect = document.querySelector<HTMLButtonElement>('#connect')!;
const selection = document.querySelector<HTMLElement>('#selection')!;
const types = document.querySelector<HTMLElement>('#content-types')!;
const exportButton = document.querySelector<HTMLButtonElement>('#export')!;
const result = document.querySelector<HTMLElement>('#result')!;
let origin = '';
let archive: Uint8Array | null = null;
let archiveFramework = 'react';
const request = async (url: string) => {
const target = new URL(url, origin);
if (target.origin !== origin || !target.pathname.startsWith('/jsonapi')) throw new Error('Drupal returned an unexpected content address.');
const response = await fetch(target, { headers: { Accept: 'application/vnd.api+json' }, credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(20000) });
if (!response.ok) throw new Error(`Drupal returned ${response.status}. Check JSON:API and public content permissions.`);
const text = await response.text();
if (text.length > 10000000) throw new Error('The response is too large. Import a smaller content type.');
return JSON.parse(text);
};
const download = () => {
if (!archive) return;
const url = URL.createObjectURL(new Blob([new Uint8Array(archive)], {type: 'application/zip'}));
const link = document.createElement('a'); link.href = url; link.download = `drupal-${archiveFramework}-frontend.zip`; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
};
form.addEventListener('submit', async event => {
event.preventDefault(); selection.hidden = true; result.hidden = true; archive = null;
connect.disabled = true; types.replaceChildren(); status.textContent = 'Discovering public Drupal content types…';
try {
const url = new URL(site.value);
if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw new Error('Use an HTTPS Drupal root address without a path, query, or credentials.');
origin = url.origin;
const data = await request(`${origin}/jsonapi`);
if (!data.links || typeof data.links !== 'object') throw new Error('No JSON:API discovery links found.');
for (const [name, value] of Object.entries(data.links)) {
if (!/^node--[a-z0-9_]+$/.test(name)) continue;
const href = typeof value === 'string' ? value : (value as {href?: string})?.href;
if (!href) continue;
const endpoint = new URL(href, origin);
if (endpoint.origin !== origin || !endpoint.pathname.startsWith('/jsonapi/node/')) continue;
const label = document.createElement('label'); label.className = 'type-choice';
const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.value = endpoint.pathname; checkbox.checked = true;
label.append(checkbox, document.createTextNode(name.replace('node--', '').replaceAll('_', ' '))); types.append(label);
}
if (!types.childElementCount) throw new Error('No public node content types were discovered. Check your Drupal configuration.');
selection.hidden = false; status.textContent = `${types.childElementCount} content types discovered. Choose the types to import.`;
} catch (error) {
status.textContent = error instanceof TypeError ? 'Cannot connect from this browser. Check the address, JSON:API, HTTPS, and Drupal CORS permissions.' : error instanceof Error ? error.message : 'Unable to discover Drupal content.';
} finally { connect.disabled = false; }
});
exportButton.addEventListener('click', async () => {
const endpoints = Array.from(types.querySelectorAll<HTMLInputElement>('input:checked')).map(input => input.value);
if (!endpoints.length) { status.textContent = 'Select at least one content type.'; return; }
connect.disabled = true; exportButton.disabled = true; site.disabled = true; framework.disabled = true; result.hidden = true;
try {
const pages: DrupalPage[] = [];
const ids = new Set<string>();
for (const endpoint of endpoints) {
let next: string | null = `${origin}${endpoint}?page[limit]=50`;
const seen = new Set<string>();
while (next) {
if (seen.has(next) || seen.size >= 20) throw new Error('Pagination exceeds 20 responses for a content type. Import a smaller type. No partial export was generated.');
seen.add(next); status.textContent = `Importing content… ${pages.length} pages read.`;
const data = await request(next);
if (!Array.isArray(data.data)) throw new Error('Drupal did not return a content collection.');
for (const item of data.data) {
const a = item.attributes;
if (!a || typeof item.id !== 'string' || typeof item.type !== 'string' || typeof a.title !== 'string') throw new Error('Unsupported content response: expected titled Drupal nodes.');
if (a.status === false || ids.has(item.id)) continue;
ids.add(item.id);
const body = new DOMParser().parseFromString(String(a.body?.processed || a.body?.value || ''), 'text/html').body.textContent || '';
const alias = a.path?.alias;
const path = typeof alias === 'string' && /^\/(?!\/)/.test(alias) && !/[\\?#]/.test(alias) ? alias : `/node/${Number(a.drupal_internal__nid) || encodeURIComponent(item.id)}`;
pages.push({ id: item.id, title: a.title, body, path, type: item.type });
if (pages.length > 2000) throw new Error('This import exceeds 2,000 pages. Select fewer content types. No partial export was generated.');
}
next = data.links?.next?.href || null;
}
}
if (!pages.length) throw new Error('No published pages were returned. Nothing was exported.');
archiveFramework = framework.value;
archive = createDrupalExport(origin, endpoints, pages, archiveFramework as 'react' | 'vue');
document.querySelector('#result-summary')!.textContent = `${pages.length} pages imported into a ${archiveFramework === 'react' ? 'React' : 'Vue'} starter. Previewing the first 5. Review the included report before publishing.`;
const preview = document.querySelector('#preview')!; preview.replaceChildren();
pages.slice(0, 5).forEach(page => { const article = document.createElement('article'); const title = document.createElement('h3'); title.textContent = page.title; const body = document.createElement('p'); body.textContent = page.body.slice(0, 300) || 'No standard body field.'; article.append(title, body); preview.append(article); });
result.hidden = false; status.textContent = 'Export ready. Drupal was not changed.'; download();
} catch (error) { status.textContent = error instanceof TypeError ? 'Import failed. Check Drupal CORS permissions and network access; no partial website was exported.' : error instanceof Error ? error.message : 'Import failed.'; }
finally { connect.disabled = false; exportButton.disabled = false; site.disabled = false; framework.disabled = false; }
});
document.querySelector('#download-again')!.addEventListener('click', download);
</script>
<style>
.module-download{display:inline-block;padding:16px 24px;border-radius:8px;background:#8bd2ed;color:#10212b;font-weight:600;text-decoration:none}.module-download:hover{background:#b4e6f7}.module-download:focus-visible{outline:2px solid #b4e6f7;outline-offset:4px}.panel ol{padding-left:24px;color:#bdcbd8}.panel li{margin:8px 0}
.release-notice{margin:24px 0;padding:24px;border:1px solid #52677a;border-left:4px solid #8bd2ed;border-radius:8px;background:#14202d}.release-notice strong{color:#eef5fa}.release-notice p{margin:8px 0 16px;color:#bdcbd8;max-width:720px}.release-notice a{color:#8bd2ed}.release-notice a:focus-visible{outline:2px solid #b4e6f7;outline-offset:4px}
.converter{max-width:1040px;margin:auto;padding:64px 24px 96px;color:#e8eef4;line-height:1.5}.eyebrow{color:#7ac9e8;letter-spacing:.14em;font-size:.8rem}h1{font-size:clamp(2.5rem,6vw,4.5rem);line-height:1.2;margin:16px 0 24px}h2,h3{line-height:1.2}.lead{font-size:1.2rem;max-width:720px;color:#bdcbd8}.steps{display:flex;flex-wrap:wrap;gap:24px;margin:40px 0;color:#8bd2ed}.panel{background:#14202d;border:1px solid #344657;border-radius:16px;padding:32px;margin:24px 0}.panel p,.scope p{color:#bdcbd8}form{display:grid;gap:16px;max-width:680px}input[type=url],select{width:100%;padding:16px;background:#0b1520;color:#eef5fa;border:1px solid #52677a;border-radius:8px;font:inherit}.permission,.type-choice{display:flex;align-items:center;gap:12px}input[type=checkbox]{width:20px;height:20px;accent-color:#66c6e8}button{width:fit-content;padding:16px 24px;border:0;border-radius:8px;background:#8bd2ed;color:#10212b;font:600 1rem system-ui;cursor:pointer}button:disabled{opacity:.6;cursor:wait}button:hover:not(:disabled){background:#b4e6f7}#status{color:#f3d18d;margin-bottom:0;overflow-wrap:anywhere}.type-choice{padding:12px 0}.scope{margin-top:48px}.scope-grid{display:grid;grid-template-columns:1fr 1fr;gap:32px}.scope a{color:#8bd2ed}#preview article{border-top:1px solid #344657;padding:16px 0}#preview p{white-space:pre-wrap}input:focus-visible,select:focus-visible,button:focus-visible{outline:2px solid #b4e6f7;outline-offset:4px}[hidden]{display:none!important}@media(max-width:640px){.panel{padding:24px}.scope-grid{grid-template-columns:1fr;gap:8px}.steps{gap:16px;font-size:.9rem}}
.converter{max-width:1120px;padding-top:72px;background:radial-gradient(ellipse at 85% 8%,#174e6340,transparent 42%),radial-gradient(ellipse at 5% 25%,#24645325,transparent 40%),#091522;border-radius:24px;margin-top:24px;margin-bottom:48px;padding-left:40px;padding-right:40px}
.converter-hero{padding:16px 0 24px}.converter-hero h1{font-size:clamp(2.5rem,5vw,4rem);letter-spacing:-.04em;max-width:900px;font-weight:600}.converter-hero h1 span{color:#a6e3d6}.converter-hero .lead{line-height:1.5;max-width:640px}
.hero-actions{display:flex;align-items:center;flex-wrap:wrap;gap:24px;margin:32px 0}.hero-secondary{color:#d1e4f0;text-decoration:none;border-bottom:1px solid #547488;padding:8px 0}.hero-secondary:hover{color:#a6e3d6}
.pipeline{display:flex;align-items:center;gap:24px;max-width:640px;padding:24px;border:1px solid #345063;border-radius:16px;background:#102538}.pipeline span{flex:1;font-size:1.25rem;font-weight:600}.pipeline small{display:block;margin-top:8px;color:#b7cddd;font-size:.875rem;font-weight:400}.pipeline b{color:#a6e3d6;font-size:1.5rem}
.release-notice{border-left-color:#a6e3d6;background:#0e2130;margin:16px 0 32px}.release-notice p{font-size:.9375rem}.steps{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin:32px 0}.steps span{display:flex;align-items:center;gap:16px;padding:16px;border-bottom:1px solid #345063;color:#d5e6f0}.steps b{font-size:.875rem;color:#a6e3d6}
.panel{background:#102233;border-color:#345063;border-radius:16px;padding:32px;box-shadow:0 16px 40px #00000018}.panel h2{font-size:1.5rem;margin:8px 0 16px}.panel .panel-kicker{color:#a6e3d6;font-size:.75rem;letter-spacing:.12em;font-weight:600}.panel p{max-width:800px}.install-guide{margin:24px 0;padding:16px;background:#091a29;border:1px solid #345063;border-radius:8px}.install-guide summary{cursor:pointer;color:#e8f2f8;font-weight:600}.install-guide summary:focus-visible,.hero-secondary:focus-visible{outline:2px solid #a6e3d6;outline-offset:4px}
#connect-form{max-width:none;grid-template-columns:minmax(0,2fr) minmax(0,1fr);column-gap:24px}#connect-form label[for=site-url]{grid-column:1;grid-row:1}#site-url{grid-column:1;grid-row:2}#connect-form label[for=framework]{grid-column:2;grid-row:1}#framework{grid-column:2;grid-row:2}.permission,#connect{grid-column:1/-1}.permission{padding:16px;background:#091a29;border-radius:8px;font-size:.9375rem}.permission input,.type-choice input{flex-shrink:0}input[type=url],select{box-sizing:border-box;min-width:0}.type-choice{padding:16px;border:1px solid #345063;border-radius:8px;margin:8px 0;background:#091a29}#export{margin-top:16px}#status:empty{display:none}#status:not(:empty){padding:16px;background:#091a29;border-radius:8px}
.scope{padding-top:24px;border-top:1px solid #345063}.scope-grid{gap:24px;margin:24px 0}.scope-grid>div{padding:24px;background:#102233;border:1px solid #345063;border-radius:16px}.scope-grid h3{margin-top:0;color:#a6e3d6}.module-download,button{font-size:.9375rem}#connect-heading,#module-heading{scroll-margin-top:112px}
@media(max-width:640px){.converter{margin:0;padding:40px 24px 64px;border-radius:0}.panel{padding:24px}.steps{grid-template-columns:1fr;gap:8px}.steps span{padding:8px 0}.pipeline{gap:16px;padding:16px}.pipeline span{font-size:1rem}.pipeline small{font-size:.75rem}.hero-actions{gap:16px}#connect-form{grid-template-columns:1fr}#connect-form label[for=site-url],#site-url,#connect-form label[for=framework],#framework{grid-column:1;grid-row:auto}.scope-grid{grid-template-columns:1fr}.module-download{box-sizing:border-box;max-width:100%}}
.conversion-options{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;margin-top:24px}.conversion-options article{padding:24px;background:#091a29;border:1px solid #345063;border-radius:12px}.conversion-options h3{margin:16px 0 8px;font-size:1.125rem}.option-status{display:inline-block;color:#f0d299;background:#3b301d;padding:4px 8px;border-radius:8px;font-size:.75rem}.option-status.available{color:#a6e3d6;background:#163d36}#launch-heading{scroll-margin-top:112px}@media(max-width:640px){.conversion-options{grid-template-columns:1fr}}
</style>
5 SOURCE FILES
Ollama setup toolkit
An unofficial consent-based wrapper around the official Ollama installer, with different launch paths for Windows, macOS and Linux.
How it works
- Check platform and existing installation first. If Ollama already exists, show its version and leave it unchanged.
- Require the exact YES confirmation before downloading. The shell script downloads the official HTTPS installer into a temporary folder; the Windows script downloads the official executable and verifies its Authenticode signature and Ollama publisher.
- Run the upstream installer, check the installed version and clean temporary downloads. Choose and download an AI model separately afterward.
What you need
Compatible Windows/macOS or 64-bit x86/ARM Linux; internet access and any permissions requested by the upstream installer. Linux needs curl. ChromeOS requires an enabled compatible Linux development environment.
Privacy, safety & limits
No bundled models, GPU drivers or public API configuration. Shell downloads are HTTPS but not pinned to an independently verified checksum. Never disable OS protections to run an unsigned wrapper. Physical-device installations remain unverified.
Files & complete source code
ollama-setup/Install Ollama.command
macOS entry point that starts the neighboring shell installer and leaves its result visible.
#!/bin/sh
base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 1
sh "$base/install-ollama.sh"
result=$?
printf '\nPress Enter to close. '
read -r answer
exit "$result"
ollama-setup/install-ollama-windows.ps1
PowerShell installer: checks existing Ollama, asks for consent, verifies the official executable signature, installs, checks the version and removes temporary files.
$ErrorActionPreference = 'Stop'
try {
Write-Host 'Xialei Ollama Setup — beta'
if (Get-Command ollama -ErrorAction SilentlyContinue) {
Write-Host 'Ollama is already installed. No changes made.'
& ollama --version
exit 0
}
Write-Host 'Downloads the official Ollama Windows installer and checks its publisher signature.'
Write-Host 'The installation changes this computer and may start a background app. No models are downloaded.'
if ((Read-Host 'Type YES to continue') -cne 'YES') { Write-Host 'Cancelled.'; exit 0 }
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$work = Join-Path ([IO.Path]::GetTempPath()) ('xialei-ollama-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $work | Out-Null
try {
$installer = Join-Path $work 'OllamaSetup.exe'
Invoke-WebRequest -Uri 'https://ollama.com/download/OllamaSetup.exe' -OutFile $installer -UseBasicParsing
$signature = Get-AuthenticodeSignature -FilePath $installer
if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch '(?:^|,\s*)O=Ollama(?: Inc\.?)?(?:,|$)') {
throw 'Installer signature is invalid or its publisher is not recognized as Ollama. Nothing was installed. Use the official download page instead.'
}
$process = Start-Process -FilePath $installer -ArgumentList '/VERYSILENT','/NORESTART' -Wait -PassThru
if ($process.ExitCode -ne 0) { throw "Ollama installer returned exit code $($process.ExitCode)." }
$binary = Join-Path $env:LOCALAPPDATA 'Programs\Ollama\ollama.exe'
if (-not (Test-Path -LiteralPath $binary)) { throw 'Installer finished, but Ollama was not found in its expected location. Check installed apps and the official instructions.' }
& $binary --version
if ($LASTEXITCODE -ne 0) { throw 'Ollama was installed but its version check failed.' }
Write-Host 'Ollama is installed. Choose and download an AI model separately.'
} finally {
if (Test-Path -LiteralPath $work) { Remove-Item -LiteralPath $work -Recurse -Force }
}
} catch {
Write-Host ('Setup failed: ' + $_.Exception.Message) -ForegroundColor Red
exit 1
}
ollama-setup/install-ollama.sh
macOS/Linux installer with platform checks, YES consent, HTTPS official download, temporary-file cleanup and installed-version check.
#!/bin/sh
set -eu
printf '\nXialei Ollama Setup — beta\n'
case "$(uname -s)" in
Darwin|Linux) ;;
*) printf 'This installer supports macOS and Linux only.\n'; exit 1 ;;
esac
case "$(uname -m)" in
x86_64|aarch64|arm64) ;;
*) printf 'Unsupported processor. See https://ollama.com/download for supported hardware.\n'; exit 1 ;;
esac
if command -v ollama >/dev/null 2>&1; then
printf 'Ollama is already installed. No changes made.\n'
ollama --version
exit 0
fi
printf 'This downloads and runs the official installer from https://ollama.com/install.sh.\n'
printf 'Internet access is required. It may request administrator permission and install a background service.\n'
printf 'No AI models are downloaded and no network exposure settings are changed by this wrapper.\n'
printf 'Continue? Type YES: '
read -r answer
[ "$answer" = 'YES' ] || { printf 'Cancelled.\n'; exit 0; }
command -v curl >/dev/null 2>&1 || { printf 'curl is required. Ask your system administrator to install it.\n'; exit 1; }
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM
curl --fail --show-error --location --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 180 https://ollama.com/install.sh -o "$work/install.sh"
[ -s "$work/install.sh" ] || { printf 'Empty installer received. Nothing was executed.\n'; exit 1; }
sh "$work/install.sh"
if command -v ollama >/dev/null 2>&1; then
ollama --version
printf '\nOllama is installed. Choose a model separately; model size affects memory and storage.\n'
else
printf 'Installer finished, but Ollama was not found in this session. Reopen your terminal or app and check the official instructions.\n'
exit 1
fi
ollama-setup/README.txt
Complete installation, usage, privacy and troubleshooting notes distributed with this kit.
Xialei Ollama Setup — public beta
This is an independent convenience wrapper, not an official Ollama product. It downloads the latest official installer when run. An internet connection and your consent are required. Review these scripts before running them on a computer you own or administer. They do not download models or configure public access to Ollama.
MAC
Use Install Ollama.command. macOS may require permission to run a downloaded script; do not disable Gatekeeper. If macOS blocks it, use the official installer at https://ollama.com/download/mac. The underlying official installer determines hardware and OS support.
WINDOWS
Right-click install-ollama-windows.ps1 and choose Run with PowerShell. Your system policy may block unsigned scripts; this beta wrapper is unsigned. Do not disable your system's security policy: use https://ollama.com/download/windows instead. The wrapper verifies the downloaded executable's Authenticode signature and publisher, then runs its unattended installation mode. Restart your terminal after installation.
LINUX
The install-ollama.sh script requires a compatible 64-bit x86 or ARM Linux system and curl. Ask your administrator to execute it with sh. The official installer may request sudo and configure a background service. GPU support depends on your drivers and hardware. No model download is included.
CHROMEOS
Chrome is a browser, not an installable Ollama operating system. On a compatible Chromebook, open Settings > Developers > Linux development environment, enable it, and use the Linux script inside that environment. Managed devices may prohibit Linux. GPU acceleration may be unavailable; smaller models may still run on the CPU. This is conditional Linux support, not a native Chrome extension.
AFTER INSTALLATION
Open Ollama or its terminal interface and choose a model suitable for available memory and disk space. Follow https://docs.ollama.com/quickstart. Large models may be slow or fail on modest hardware. Keep the API private; do not expose it to the internet without proper access controls. Consult the official docs for upgrades and removal.
VERIFICATION LIMITS
Scripts have not been executed on real macOS, Windows or ChromeOS hardware in this project environment. Official installers can change. Downloads use HTTPS; the Windows executable additionally has its signature checked. The shell installer is downloaded from the official HTTPS origin but is not pinned to an independently verified checksum. This is not a version-pinned production deployment system.
src/pages/ollama-setup.astro
Website setup/download page: bilingual instructions, requirements and links. This Astro file belongs in the website, not in the local installation folder.
---
import Layout from '../layouts/Layout.astro';
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
---
<Layout title="Ollama Setup — Free DevOps Toolkit | Xia Lei" description="Download a consent-based Ollama installer toolkit for Mac, Windows and Linux, with ChromeOS setup guidance.">
<Header />
<main class="setup">
<a class="back" href="/#tools">← Back to Tools</a>
<header>
<p class="eyebrow">XIALEI TOOLBOX · PUBLIC BETA</p>
<h1>Your local AI.<br /><span>A simpler setup.</span></h1>
<p class="lead">Install Ollama with a small, readable DevOps toolkit. Choose your platform, approve the installation, and start exploring models on your own computer.</p>
<a class="download" href="/downloads/xialei-ollama-setup-beta.zip" download>Download installer toolkit · ZIP</a>
<p class="caption">Free download · No signup · No bundled AI models</p>
</header>
<aside class="notice"><strong>You stay in control.</strong> These scripts fetch Ollama’s official installers after you confirm. A website cannot install software on your computer automatically. This independent toolkit is unsigned and has not been tested on every platform; never disable security protections to run it.</aside>
<section aria-labelledby="platforms"><h2 id="platforms">Choose your platform</h2>
<div class="platform-grid">
<article><p class="tag">MACOS</p><h3>Mac</h3><p>Extract the ZIP and open <strong>Install Ollama.command</strong>. Keep the downloaded files together. Type YES when prompted; the official installer may ask for administrator permission.</p><p>If macOS blocks the script, use Ollama’s official installer rather than disabling Gatekeeper.</p><a href="https://ollama.com/download/mac" target="_blank" rel="noopener noreferrer">Official Mac download ↗</a></article>
<article><p class="tag">WINDOWS</p><h3>Windows</h3><p>Extract the ZIP. Right-click <strong>install-ollama-windows.ps1</strong> and choose <strong>Run with PowerShell</strong>. Approve the prompt. The toolkit checks the official installer’s digital signature before starting installation.</p><p>If your security policy blocks unsigned scripts, use the official installer instead.</p><a href="https://ollama.com/download/windows" target="_blank" rel="noopener noreferrer">Official Windows download ↗</a></article>
<article><p class="tag">LINUX</p><h3>Linux</h3><p>Ask your administrator to run the included <strong>install-ollama.sh</strong> script with sh. It checks the operating system and processor, requests your consent, then downloads and runs Ollama’s installer.</p><p>A compatible 64-bit system, internet access and curl are required. Administrator permission may be requested.</p><a href="https://ollama.com/download/linux" target="_blank" rel="noopener noreferrer">Official Linux instructions ↗</a></article>
<article><p class="tag">LINUX ENVIRONMENT REQUIRED</p><h3>ChromeOS / Chromebook</h3><p>Chrome itself cannot run this installer. On a compatible Chromebook, enable <strong>Settings → Developers → Linux development environment</strong>, then use the Linux script inside that environment.</p><p>School or work devices may restrict this. GPU acceleration is not guaranteed; CPU-only performance depends on your hardware.</p></article>
</div>
</section>
<section class="next"><h2>After installation</h2><ol><li><strong>Check Ollama is available.</strong> Open the app or a new terminal. The installer also attempts a version check.</li><li><strong>Choose an AI model.</strong> Models are a separate download and can use several gigabytes of storage and memory. Start small on modest hardware.</li><li><strong>Keep it private.</strong> This toolkit does not configure public API access. Do not expose your local Ollama service to the internet without authentication.</li></ol><a href="https://docs.ollama.com/quickstart" target="_blank" rel="noopener noreferrer">Follow Ollama’s getting-started guide ↗</a></section>
<details><summary>What this beta does—and does not do</summary><p>Already-installed Ollama is left unchanged. Failed downloads stop installation. Windows checks the executable’s publisher signature; Mac and Linux fetch the official shell installer over HTTPS, without an independently pinned checksum. Official installer behavior and requirements may change.</p><p>This is a convenience toolkit, not an official Ollama product or a version-pinned enterprise deployment system. It does not install GPU drivers separately, download models, create accounts, or configure your firewall. See the included README for limitations and troubleshooting.</p></details>
</main>
<Footer />
</Layout>
<style>
.setup{max-width:1040px;margin:auto;padding:64px 24px 96px;color:#edf6ff;line-height:1.5;background:radial-gradient(ellipse at 80% 10%,#14546340,transparent 45%),#091522}.back,a{color:#a5def0}.back{text-decoration:none;font-size:.875rem}header{padding:40px 0 24px}.eyebrow,.tag{color:#a6e3d6;font-size:.75rem;letter-spacing:.12em;font-weight:600}h1{font-size:clamp(2.75rem,6vw,4.5rem);line-height:1.2;letter-spacing:-.04em;margin:16px 0 24px;font-weight:600}h1 span{color:#a6e3d6}h2,h3{line-height:1.2}h2{font-size:1.75rem}h3{font-size:1.25rem}.lead{max-width:720px;font-size:1.125rem;color:#c4d7e6}.download{display:inline-block;margin-top:16px;background:#a5def0;color:#10212b;padding:16px 24px;border-radius:8px;font-weight:600;text-decoration:none}.download:hover{background:#c6edf7}.caption{font-size:.875rem;color:#b6cbdc}.notice,.next,details{padding:24px;background:#102538;border:1px solid #345063;border-radius:16px;margin:24px 0;color:#c4d7e6}.notice strong{color:#edf6ff}.platform-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px;margin:24px 0}.platform-grid article{padding:24px;border:1px solid #345063;border-radius:16px;background:#102233}.platform-grid article p:not(.tag){color:#c4d7e6}.platform-grid h3{margin:8px 0 16px}.next li{margin:16px 0}.next ol{padding-left:24px}summary{cursor:pointer;color:#edf6ff;font-weight:600}a:focus-visible,summary:focus-visible{outline:2px solid #a6e3d6;outline-offset:4px}@media(max-width:640px){.setup{padding-top:40px}.platform-grid{grid-template-columns:1fr;gap:16px}.download{max-width:100%;box-sizing:border-box}}
</style>
7 SOURCE FILES
Xialei AI Agent
A standalone browser workflow assistant plus a small Python launcher. The HTML contains the interface, workflow execution and direct calls to the selected AI provider.
How it works
- Extract the complete kit. launch.py reads only the neighboring agent HTML and serves it on 127.0.0.1:8765. It checks the Host header and accepts only the two agent page paths, without exposing other files.
- Choose your provider/model in Settings and supply your own key or compatible local server. The agent executes workflow steps, including AI prompts, checklists, drafts and note-saving, and supports workflow import/export.
- Settings, keys, workflows and input are stored in browser localStorage, not in Xialei’s database. Cloud AI steps send input to your chosen provider; the local launcher does not make those steps offline.
What you need
Python 3 for the launcher, a modern browser, and your own supported AI provider or separately installed OpenAI-compatible local model service. Some providers restrict direct browser requests.
Privacy, safety & limits
Keys in browser storage are unencrypted. Use restricted personal keys and never distribute them in a kit. For local AI, authorize only the exact launcher origin, not all origins (even if older inline help suggests a wildcard). This is not an unrestricted OS agent or a background service. Real provider connections remain unverified.
Files & complete source code
agent-setup/launch.py
Standard-library, loopback-only HTTP server. Reads the bundled HTML, restricts paths and Host values, opens a browser and stays running until closed.
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import webbrowser
def main():
page = Path(__file__).with_name('xialei-agent-beta.html')
if not page.is_file():
print('Missing agent file. Extract the entire ZIP and keep its files together.')
return 1
content = page.read_bytes()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.headers.get('Host') not in ('127.0.0.1:8765', 'localhost:8765'):
self.send_error(403)
return
if self.path not in ('/', '/xialei-agent-beta.html'):
self.send_error(404)
return
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(content)))
self.send_header('Cache-Control', 'no-store')
self.send_header('X-Content-Type-Options', 'nosniff')
self.end_headers()
self.wfile.write(content)
try:
with HTTPServer(('127.0.0.1', 8765), Handler) as server:
address = 'http://127.0.0.1:8765'
print('Xialei Agent is running locally at ' + address)
print('Keep this window open. Close it or press Ctrl+C to stop.')
webbrowser.open(address)
server.serve_forever()
except OSError:
print('Could not start. Another application may be using port 8765. Close an existing agent launcher and try again.')
return 1
except KeyboardInterrupt:
print('\nAgent stopped.')
return 0
if __name__ == '__main__':
raise SystemExit(main())
agent-setup/README.txt
Complete installation, usage, privacy and troubleshooting notes distributed with this kit.
Xialei AI Agent — local setup beta
Your own copy for Windows, macOS and Linux. This is a browser-based workflow assistant, not a native desktop app and not an AI model. No administrator rights, package installs or public service are required by the launcher.
1. Install Python 3 from https://www.python.org/downloads/ if unavailable. On Windows include its Python launcher.
2. Extract the whole ZIP into your own folder. Keep all files together.
3. Windows: open Start Agent.bat. macOS: open Start Agent.command. Linux: run start-agent.sh with sh. If your OS blocks an unsigned script, do not disable protections; use Python to open launch.py instead.
4. Your browser opens the agent on http://127.0.0.1:8765 . Keep the launcher window open while using it.
5. Open Settings, choose your AI provider, enter your own key/server and an available model, then use the connection test. Supported choices: Claude, OpenAI, Grok, Gemini and OpenAI-compatible local/other servers. Provider billing and model availability are separate from this tool. Some providers block browser-origin calls; those connections require provider-supported browser access or a separately managed compatible service.
6. Create or choose a workflow, provide its input, and run it. Export workflows to back them up or move them to another computer. Import those exported files in your new copy. Provider settings/keys must be configured separately on each computer.
For local AI, install Ollama or another OpenAI-compatible server separately and download a suitable model. Select Local / other, use http://localhost:11434/v1 for Ollama and enter the exact installed model name. If browser requests are blocked, authorize ONLY http://127.0.0.1:8765 in the local service's allowed-origin settings and restart that service. Do not allow all origins or expose your local service to the internet. The agent does not install models or modify service configuration.
Privacy: the existing standalone agent stores workflow/input/provider settings, including keys, in this browser profile on this computer. They are not encrypted. Use personal restricted keys, not shared organization secrets; never send keys to clients in the ZIP. Cloud-provider steps send their input to that chosen provider. Local launch does not make cloud AI offline. Do not clear browser site data without exporting workflows first. The launcher serves only the bundled HTML, binds to loopback and does not list or expose other files.
You can also open xialei-agent-beta.html directly without Python, but file-origin storage and provider access vary by browser. The localhost launcher is the recommended option. Close the launcher to stop. The tool does not run unattended in the background and does not grant the AI unrestricted access to OS files or programs. This beta is not a signed native installer. Launcher checks do not verify a real AI provider or physical-device browser behavior.
agent-setup/Start Agent.bat
Windows entry point: starts the neighboring Python script using the Python launcher and keeps the window open for messages.
@echo off
py -3 "%~dp0launch.py"
pause
agent-setup/Start Agent.command
macOS/Linux entry point: resolves its own folder and starts the neighboring Python script. Keep the complete kit together.
#!/bin/sh
HERE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$HERE/launch.py"
printf '\nPress Enter to close.'
read -r answer
agent-setup/start-agent.sh
macOS/Linux entry point: resolves its own folder and starts the neighboring Python script. Keep the complete kit together.
#!/bin/sh
HERE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$HERE/launch.py"
xialei-agent-beta.html
The complete standalone app: HTML interface, CSS, provider requests, workflow steps, settings and browser storage. Copy it into an .html file, not into a Python script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Xialei Agent (Beta)</title>
<style>
:root {
--bg: #0b1120; --panel: #111827; --panel-2: #1f2937; --line: #263244;
--text: #e5e7eb; --muted: #94a3b8; --primary: #14b8a6; --primary-2: #2dd4bf;
--accent: #f59e0b; --success: #22c55e; --warning: #eab308; --error: #ef4444; --info: #38bdf8;
}
* { box-sizing: border-box; }
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, sans-serif; background: var(--bg); color: var(--text); line-height: 1.5; }
button, input, select, textarea { font: inherit; color: inherit; }
header { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 16px 24px; border-bottom: 1px solid var(--line); background: rgba(17,24,39,.9); position: sticky; top: 0; z-index: 5; backdrop-filter: blur(8px); }
.brand { display: flex; align-items: center; gap: 12px; font-weight: 600; }
.brand .logo { width: 32px; height: 32px; border-radius: 8px; background: linear-gradient(135deg, var(--primary), var(--info)); display: grid; place-items: center; color: #04201d; font-weight: 700; }
.badge { font-size: 11px; padding: 2px 8px; border-radius: 999px; background: rgba(245,158,11,.15); color: var(--accent); border: 1px solid rgba(245,158,11,.4); }
.tabs { display: flex; gap: 4px; background: var(--panel-2); padding: 4px; border-radius: 10px; }
.tab { border: 0; background: transparent; padding: 8px 16px; border-radius: 8px; cursor: pointer; color: var(--muted); transition: all .2s; }
.tab.active { background: var(--primary); color: #04201d; font-weight: 600; }
.btn { border: 1px solid var(--line); background: var(--panel-2); padding: 8px 16px; border-radius: 8px; cursor: pointer; transition: all .2s; }
.btn:hover { border-color: var(--primary); transform: translateY(-1px); }
.btn.primary { background: var(--primary); color: #04201d; border-color: var(--primary); font-weight: 600; }
.btn.primary:hover { background: var(--primary-2); }
.btn:disabled { opacity: .5; cursor: not-allowed; transform: none; }
.provider-pill { font-size: 13px; color: var(--muted); }
.provider-pill strong { color: var(--text); }
main { padding: 24px; }
.view { display: none; }
.view.active { display: block; animation: fade .25s ease; }
@keyframes fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
.grid { display: grid; grid-template-columns: 240px 1fr 360px; gap: 24px; align-items: start; }
@media (max-width: 1100px) { .grid { grid-template-columns: 1fr; } }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 16px; }
.panel h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 0 0 16px; font-weight: 600; }
.palette-item { display: flex; align-items: center; gap: 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; margin-bottom: 8px; background: var(--panel-2); cursor: grab; transition: all .2s; user-select: none; }
.palette-item:hover { border-color: var(--primary); transform: translateX(3px); }
.palette-item small { display: block; color: var(--muted); font-size: 12px; line-height: 1.3; }
.icon { width: 32px; height: 32px; flex: none; border-radius: 8px; display: grid; place-items: center; font-size: 12px; font-weight: 700; }
.dropzone { min-height: 360px; border: 2px dashed var(--line); border-radius: 12px; padding: 16px; transition: all .2s; }
.dropzone.over { border-color: var(--primary); background: rgba(20,184,166,.06); }
.empty { text-align: center; color: var(--muted); padding: 64px 16px; }
.step { background: var(--panel-2); border: 1px solid var(--line); border-radius: 12px; margin-bottom: 12px; transition: border-color .2s, opacity .2s; }
.step.dragging { opacity: .4; }
.step.running { border-color: var(--info); box-shadow: 0 0 0 3px rgba(56,189,248,.15); }
.step.done { border-color: rgba(34,197,94,.5); }
.step.failed { border-color: var(--error); }
.step-head { display: flex; align-items: center; gap: 12px; padding: 12px; cursor: grab; }
.step-head .num { color: var(--muted); font-size: 12px; width: 48px; }
.step-head .title { flex: 1; font-weight: 600; background: transparent; border: 1px solid transparent; border-radius: 6px; padding: 4px 8px; }
.step-head .title:focus { border-color: var(--line); outline: none; background: var(--panel); }
.icon-btn { background: transparent; border: 0; color: var(--muted); cursor: pointer; padding: 4px 8px; border-radius: 6px; }
.icon-btn:hover { color: var(--text); background: var(--panel); }
.step-body { padding: 0 12px 12px; display: grid; gap: 8px; }
.step-body.collapsed { display: none; }
label { font-size: 12px; color: var(--muted); display: grid; gap: 4px; }
input, select, textarea { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 8px 12px; width: 100%; }
input:focus, select:focus, textarea:focus { outline: none; border-color: var(--primary); }
textarea { resize: vertical; min-height: 72px; }
textarea.code { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 13px; min-height: 140px; }
.hint { font-size: 12px; color: var(--muted); }
.hint code { background: var(--panel); padding: 1px 4px; border-radius: 4px; }
.toolbar { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; }
.log { display: grid; gap: 8px; margin-top: 16px; max-height: 60vh; overflow: auto; }
.log-entry { border: 1px solid var(--line); border-radius: 10px; padding: 12px; background: var(--panel-2); font-size: 14px; }
.log-entry .log-title { font-size: 12px; color: var(--muted); margin-bottom: 4px; display: flex; justify-content: space-between; gap: 8px; }
.log-entry pre { margin: 0; white-space: pre-wrap; word-break: break-word; font-family: inherit; }
.log-entry.error { border-color: var(--error); }
.log-entry.error .log-title { color: var(--error); }
.log-entry a { color: var(--primary-2); }
.center { max-width: 760px; margin: 0 auto; }
.templates { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin-top: 16px; }
.template { text-align: left; padding: 16px; border-radius: 12px; border: 1px solid var(--line); background: var(--panel-2); cursor: pointer; transition: all .2s; }
.template:hover { border-color: var(--primary); transform: translateY(-2px); }
.template strong { display: block; margin-bottom: 4px; }
.template span { color: var(--muted); font-size: 13px; }
.modal-back { position: fixed; inset: 0; background: rgba(2,6,23,.7); display: none; place-items: center; z-index: 20; padding: 16px; }
.modal-back.open { display: grid; animation: fade .2s ease; }
.modal { background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 24px; width: 100%; max-width: 480px; display: grid; gap: 16px; }
.modal h3 { margin: 0; }
.row { display: flex; gap: 8px; justify-content: flex-end; }
.notice { font-size: 13px; padding: 12px; border-radius: 10px; background: rgba(56,189,248,.08); border: 1px solid rgba(56,189,248,.3); color: #bae6fd; }
.notice.warn { background: rgba(234,179,8,.08); border-color: rgba(234,179,8,.35); color: #fde68a; }
.toast { position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%) translateY(20px); background: var(--panel-2); border: 1px solid var(--line); padding: 10px 16px; border-radius: 10px; opacity: 0; transition: all .25s; pointer-events: none; z-index: 30; }
.toast.show { opacity: 1; transform: translateX(-50%); }
</style>
</head>
<body>
<header>
<div class="brand"><div class="logo">XA</div>Xialei Agent <span class="badge">BETA</span></div>
<nav class="tabs" role="tablist">
<button class="tab active" data-view="builder">Builder</button>
<button class="tab" data-view="autopilot">Autopilot</button>
<button class="tab" data-view="code">Code</button>
</nav>
<div style="display:flex;gap:12px;align-items:center">
<span class="provider-pill" id="providerPill"></span>
<button class="btn" id="openSettings">AI settings</button>
</div>
</header>
<main>
<section class="view active" id="view-builder">
<div class="grid">
<aside class="panel">
<h2>Steps</h2>
<div id="palette"></div>
<p class="hint">Drag a step into your workflow, or click it to add it at the end.</p>
</aside>
<section class="panel">
<div class="toolbar">
<button class="btn" id="templatesBtn">Templates</button>
<button class="btn" id="exportBtn">Save workflow file</button>
<button class="btn" id="importBtn">Open workflow file</button>
<button class="btn" id="clearBtn">Clear</button>
<input type="file" id="importFile" accept=".json,application/json" hidden />
</div>
<div class="dropzone" id="dropzone"></div>
<p class="hint">Use <code>{{input}}</code> for your task text, <code>{{previous}}</code> for the last step's result, or <code>{{step2}}</code> for a specific step.</p>
</section>
<aside class="panel">
<h2>Run</h2>
<label>Your task or notes
<textarea id="taskInput" rows="6" placeholder="Paste an email, your to-do notes, a meeting transcript..."></textarea>
</label>
<div class="toolbar" style="margin:12px 0 0">
<button class="btn primary" id="runBtn">Run workflow</button>
<button class="btn" id="stopBtn" disabled>Stop</button>
</div>
<div class="log" id="log"></div>
</aside>
</div>
</section>
<section class="view" id="view-autopilot">
<div class="center panel">
<h2>Autopilot</h2>
<p>Describe what you want done. Your AI plans the steps, you review them in the Builder, then run.</p>
<label>Goal
<textarea id="goalInput" rows="4" placeholder="e.g. Turn my meeting notes into a summary, a to-do list, and a follow-up email to the team"></textarea>
</label>
<div class="toolbar" style="margin-top:12px">
<button class="btn primary" id="planBtn">Plan the steps</button>
</div>
<p class="hint">Autopilot never adds "Run code" steps. You stay in control of anything that runs code.</p>
<h2 style="margin-top:24px">Or start from a template</h2>
<div class="templates" id="templateList"></div>
</div>
</section>
<section class="view" id="view-code">
<div class="center panel">
<h2>Workflow as code</h2>
<p>Every workflow is plain JSON. Edit it here, paste one from a friend, or ask your AI to write one for you.</p>
<textarea class="code" id="codeEditor" rows="22" spellcheck="false"></textarea>
<div class="toolbar" style="margin-top:12px">
<button class="btn primary" id="applyCode">Apply to builder</button>
<button class="btn" id="refreshCode">Reload from builder</button>
</div>
</div>
</section>
</main>
<div class="modal-back" id="settingsModal">
<div class="modal">
<h3>Connect your AI</h3>
<div class="notice">Your key is saved only in this browser on this computer and is sent only to the AI company you choose.</div>
<label>AI provider
<select id="providerSelect"></select>
</label>
<label>Model <input id="modelInput" /></label>
<label id="baseUrlWrap">Server address <input id="baseUrlInput" placeholder="http://localhost:11434/v1" /></label>
<label>API key <input id="keyInput" type="password" autocomplete="off" /></label>
<p class="hint" id="keyHelp"></p>
<div class="row">
<button class="btn" id="testKey">Test connection</button>
<button class="btn" data-close>Cancel</button>
<button class="btn primary" id="saveSettings">Save</button>
</div>
</div>
</div>
<div class="modal-back" id="askModal">
<div class="modal">
<h3>Your agent needs input</h3>
<p id="askQuestion"></p>
<textarea id="askAnswer" rows="4"></textarea>
<div class="row">
<button class="btn" id="askCancel">Stop workflow</button>
<button class="btn primary" id="askOk">Continue</button>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<script>
(() => {
const STORE = { settings: 'xa.settings', flow: 'xa.workflow', input: 'xa.input' };
const PROVIDERS = {
claude: { name: 'Claude (Anthropic)', model: 'claude-sonnet-4-5', help: 'Get a key at console.anthropic.com > API Keys.' },
openai: { name: 'ChatGPT (OpenAI)', model: 'gpt-4o-mini', help: 'Get a key at platform.openai.com > API keys.' },
grok: { name: 'Grok (xAI)', model: 'grok-3-mini', help: 'Get a key at console.x.ai > API Keys.' },
gemini: { name: 'Gemini (Google)', model: 'gemini-2.5-flash', help: 'Get a key at aistudio.google.com > Get API key.' },
custom: { name: 'Local / other (OpenAI-compatible)', model: 'llama3.1', help: 'For Ollama, LM Studio and similar. Ollama needs OLLAMA_ORIGINS=* set so the browser can reach it. Key is optional.' },
};
const STEP_TYPES = {
ai: { label: 'Ask AI', desc: 'Any instruction', color: '#14b8a6', mono: 'AI',
fields: [{ key: 'prompt', label: 'Instruction', type: 'textarea', value: 'Help me with this:\n\n{{previous}}' }] },
summarize: { label: 'Summarize', desc: 'Shorten long text', color: '#38bdf8', mono: 'SU',
fields: [{ key: 'style', label: 'Style', type: 'select', options: ['5 bullet points', 'one short paragraph', 'a single sentence'], value: '5 bullet points' },
{ key: 'text', label: 'Text', type: 'textarea', value: '{{previous}}' }] },
checklist: { label: 'To-do list', desc: 'Pull out action items', color: '#22c55e', mono: 'TD',
fields: [{ key: 'text', label: 'From', type: 'textarea', value: '{{previous}}' }] },
email: { label: 'Draft email', desc: 'Write or reply', color: '#f59e0b', mono: 'EM',
fields: [{ key: 'tone', label: 'Tone', type: 'select', options: ['friendly', 'formal', 'short and direct'], value: 'friendly' },
{ key: 'brief', label: 'What the email is about', type: 'textarea', value: '{{previous}}' }] },
translate: { label: 'Translate', desc: 'Into any language', color: '#a3e635', mono: 'TR',
fields: [{ key: 'language', label: 'Language', type: 'text', value: 'Chinese' },
{ key: 'text', label: 'Text', type: 'textarea', value: '{{previous}}' }] },
ask: { label: 'Ask me', desc: 'Pause for your answer', color: '#fb7185', mono: '?',
fields: [{ key: 'question', label: 'Question to ask you', type: 'text', value: 'Anything to add before I continue?' }] },
open: { label: 'Open app or site', desc: 'Website or app link', color: '#60a5fa', mono: 'GO',
fields: [{ key: 'url', label: 'Link (https://, mailto:, slack://, ...)', type: 'text', value: 'https://calendar.google.com' }] },
save: { label: 'Save to file', desc: 'Download the result', color: '#cbd5e1', mono: 'SV',
fields: [{ key: 'filename', label: 'File name', type: 'text', value: 'agent-result.txt' },
{ key: 'text', label: 'Content', type: 'textarea', value: '{{previous}}' }] },
code: { label: 'Run code', desc: 'JavaScript, for pros', color: '#f97316', mono: '{}',
fields: [{ key: 'code', label: 'JavaScript (return a value; you get input, previous, steps, ai)', type: 'code',
value: '// Example: count words, then ask AI for a title\nconst words = previous.split(/\\s+/).filter(Boolean).length;\nconst title = await ai("Give a 5-word title for:\\n" + previous);\nreturn `${title}\\n(${words} words)`;' }] },
};
const PLANNABLE = Object.keys(STEP_TYPES).filter((t) => t !== 'code');
const TEMPLATES = [
{ name: 'Morning plan', about: 'Notes in, prioritised day plan out', steps: [
{ type: 'checklist', title: 'Find my tasks', config: { text: '{{input}}' } },
{ type: 'ai', title: 'Prioritise', config: { prompt: 'Order these tasks by importance and urgency. Put a rough time next to each and plan my day from 9am:\n\n{{previous}}' } },
{ type: 'open', title: 'Open my calendar', config: { url: 'https://calendar.google.com' } },
] },
{ name: 'Reply to an email', about: 'Paste an email, get a reply draft', steps: [
{ type: 'summarize', title: 'What do they want?', config: { style: 'a single sentence', text: '{{input}}' } },
{ type: 'ask', title: 'My answer', config: { question: 'What do you want to tell them?' } },
{ type: 'email', title: 'Draft reply', config: { tone: 'friendly', brief: 'Reply to this email:\n{{input}}\n\nMy answer: {{previous}}' } },
] },
{ name: 'Meeting follow-up', about: 'Transcript to summary, actions and email', steps: [
{ type: 'summarize', title: 'Summary', config: { style: '5 bullet points', text: '{{input}}' } },
{ type: 'checklist', title: 'Action items', config: { text: '{{input}}' } },
{ type: 'email', title: 'Team email', config: { tone: 'short and direct', brief: 'Meeting summary:\n{{step1}}\n\nActions:\n{{step2}}' } },
{ type: 'save', title: 'Save notes', config: { filename: 'meeting-notes.txt', text: '{{step1}}\n\n{{step2}}\n\n{{step3}}' } },
] },
];
const $ = (id) => document.getElementById(id);
const el = (tag, props = {}, children = []) => {
const node = Object.assign(document.createElement(tag), props);
for (const child of [].concat(children)) node.append(child);
return node;
};
const uid = () => Math.random().toString(36).slice(2, 10);
const readJSON = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
let settings = readJSON(STORE.settings, { provider: 'claude', keys: {}, models: {}, baseUrl: '' });
let flow = readJSON(STORE.flow, []);
let abort = null;
const toast = (msg) => {
const t = $('toast'); t.textContent = msg; t.classList.add('show');
clearTimeout(toast.timer); toast.timer = setTimeout(() => t.classList.remove('show'), 2400);
};
function makeStep(type, title, config = {}) {
const def = STEP_TYPES[type];
const base = Object.fromEntries(def.fields.map((f) => [f.key, f.value]));
return { id: uid(), type, title: title || def.label, config: { ...base, ...config } };
}
function sanitizeFlow(data) {
const list = Array.isArray(data) ? data : data?.steps;
if (!Array.isArray(list)) throw new Error('Expected a list of steps.');
return list.filter((s) => s && STEP_TYPES[s.type]).map((s) => {
const step = makeStep(s.type, typeof s.title === 'string' ? s.title.slice(0, 80) : '');
for (const f of STEP_TYPES[s.type].fields) {
if (s.config && typeof s.config[f.key] === 'string') step.config[f.key] = s.config[f.key];
}
return step;
});
}
function loadFlow(steps, { trusted = false } = {}) {
if (!trusted && steps.some((s) => s.type === 'code') &&
!confirm('This workflow contains "Run code" steps. Only continue if you trust where it came from. Load it?')) return false;
flow = steps; save(); renderFlow(); return true;
}
function save() { localStorage.setItem(STORE.flow, JSON.stringify(flow)); }
// ---------- Palette ----------
function renderPalette() {
const pal = $('palette');
for (const [type, def] of Object.entries(STEP_TYPES)) {
const item = el('div', { className: 'palette-item', draggable: true, title: 'Drag or click to add' }, [
iconFor(def),
el('div', {}, [el('div', { textContent: def.label }), el('small', { textContent: def.desc })]),
]);
item.addEventListener('dragstart', (e) => e.dataTransfer.setData('text/plain', 'new:' + type));
item.addEventListener('click', () => { flow.push(makeStep(type)); save(); renderFlow(); toast(def.label + ' added'); });
pal.append(item);
}
}
function iconFor(def) {
const icon = el('div', { className: 'icon', textContent: def.mono });
icon.style.background = def.color + '22'; icon.style.color = def.color;
return icon;
}
// ---------- Workflow ----------
function renderFlow() {
const zone = $('dropzone');
zone.replaceChildren();
if (!flow.length) {
zone.append(el('div', { className: 'empty' }, [
el('div', { textContent: 'Drop steps here to build your agent.' }),
el('div', { className: 'hint', textContent: 'Start simple: one "Ask AI" step. Add more as you go.' }),
]));
}
flow.forEach((step, index) => zone.append(renderStep(step, index)));
if (document.querySelector('.tab.active')?.dataset.view === 'code') refreshCode();
}
function renderStep(step, index) {
const def = STEP_TYPES[step.type];
const body = el('div', { className: 'step-body' });
for (const f of def.fields) {
let input;
if (f.type === 'select') {
input = el('select', {}, f.options.map((o) => el('option', { value: o, textContent: o })));
} else if (f.type === 'textarea' || f.type === 'code') {
input = el('textarea', { className: f.type === 'code' ? 'code' : '', spellcheck: f.type !== 'code' });
} else {
input = el('input', { type: 'text' });
}
input.value = step.config[f.key] ?? '';
input.addEventListener('input', () => { step.config[f.key] = input.value; save(); });
body.append(el('label', {}, [f.label, input]));
}
if (step.type === 'code') body.prepend(el('div', { className: 'notice warn', textContent: 'Code runs on your computer with access to this page. Only use code you wrote or trust.' }));
const title = el('input', { className: 'title', value: step.title });
title.addEventListener('input', () => { step.title = title.value; save(); });
const toggle = el('button', { className: 'icon-btn', textContent: 'Edit', title: 'Show or hide settings' });
toggle.addEventListener('click', () => body.classList.toggle('collapsed'));
const remove = el('button', { className: 'icon-btn', textContent: 'Remove' });
remove.addEventListener('click', () => { flow.splice(index, 1); save(); renderFlow(); });
const card = el('div', { className: 'step', draggable: true }, [
el('div', { className: 'step-head' }, [el('span', { className: 'num', textContent: 'Step ' + (index + 1) }), iconFor(def), title, toggle, remove]),
body,
]);
card.dataset.id = step.id;
card.addEventListener('dragstart', (e) => {
if (e.target !== card) return;
e.dataTransfer.setData('text/plain', 'move:' + index); card.classList.add('dragging');
});
card.addEventListener('dragend', () => card.classList.remove('dragging'));
card.querySelectorAll('input,textarea,select').forEach((n) => {
n.addEventListener('focus', () => { card.draggable = false; });
n.addEventListener('blur', () => { card.draggable = true; });
});
return card;
}
function dropIndex(zone, y) {
const cards = [...zone.querySelectorAll('.step')];
const i = cards.findIndex((c) => y < c.getBoundingClientRect().top + c.offsetHeight / 2);
return i === -1 ? cards.length : i;
}
const zone = $('dropzone');
zone.addEventListener('dragover', (e) => { e.preventDefault(); zone.classList.add('over'); });
zone.addEventListener('dragleave', (e) => { if (!zone.contains(e.relatedTarget)) zone.classList.remove('over'); });
zone.addEventListener('drop', (e) => {
e.preventDefault(); zone.classList.remove('over');
const data = e.dataTransfer.getData('text/plain');
let at = dropIndex(zone, e.clientY);
if (data.startsWith('new:') && STEP_TYPES[data.slice(4)]) {
flow.splice(at, 0, makeStep(data.slice(4)));
} else if (data.startsWith('move:')) {
const from = Number(data.slice(5));
const [moved] = flow.splice(from, 1);
if (!moved) return;
if (from < at) at -= 1;
flow.splice(at, 0, moved);
} else return;
save(); renderFlow();
});
// ---------- AI providers ----------
async function callAI(prompt, signal) {
const p = settings.provider;
const key = (settings.keys[p] || '').trim();
const model = (settings.models[p] || PROVIDERS[p].model).trim();
const system = 'You are a helpful personal assistant agent completing one step of a task. Reply with the result only, no preamble.';
if (!key && p !== 'custom') throw new Error('Add your ' + PROVIDERS[p].name + ' API key in AI settings first.');
let res, data;
if (p === 'claude') {
res = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST', signal,
headers: { 'content-type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01', 'anthropic-dangerous-direct-browser-access': 'true' },
body: JSON.stringify({ model, max_tokens: 2048, system, messages: [{ role: 'user', content: prompt }] }),
});
data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error?.message || 'Claude returned ' + res.status);
return (data.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n').trim();
}
if (p === 'gemini') {
res = await fetch('https://generativelanguage.googleapis.com/v1beta/models/' + encodeURIComponent(model) + ':generateContent', {
method: 'POST', signal,
headers: { 'content-type': 'application/json', 'x-goog-api-key': key },
body: JSON.stringify({ systemInstruction: { parts: [{ text: system }] }, contents: [{ role: 'user', parts: [{ text: prompt }] }] }),
});
data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error?.message || 'Gemini returned ' + res.status);
return (data.candidates?.[0]?.content?.parts || []).map((x) => x.text || '').join('').trim();
}
const base = p === 'openai' ? 'https://api.openai.com/v1' : p === 'grok' ? 'https://api.x.ai/v1' : (settings.baseUrl || 'http://localhost:11434/v1').replace(/\/$/, '');
const headers = { 'content-type': 'application/json' };
if (key) headers.authorization = 'Bearer ' + key;
res = await fetch(base + '/chat/completions', {
method: 'POST', signal, headers,
body: JSON.stringify({ model, messages: [{ role: 'system', content: system }, { role: 'user', content: prompt }] }),
});
data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error?.message || PROVIDERS[p].name + ' returned ' + res.status);
const text = data.choices?.[0]?.message?.content;
if (typeof text !== 'string') throw new Error('The AI sent back an empty answer.');
return text.trim();
}
// ---------- Running ----------
function fill(template, ctx) {
return String(template || '').replace(/\{\{\s*(input|previous|step(\d+))\s*\}\}/g, (_, name, n) => {
if (name === 'input') return ctx.input;
if (name === 'previous') return ctx.previous;
return ctx.steps[Number(n) - 1] ?? '';
});
}
function safeLink(raw) {
try {
const url = new URL(raw.trim());
if (['javascript:', 'data:', 'vbscript:', 'file:', 'blob:'].includes(url.protocol)) return null;
return url.href;
} catch { return null; }
}
function askUser(question) {
return new Promise((resolve, reject) => {
$('askQuestion').textContent = question;
$('askAnswer').value = '';
$('askModal').classList.add('open');
setTimeout(() => $('askAnswer').focus(), 50);
const done = (fn) => { $('askModal').classList.remove('open'); $('askOk').onclick = $('askCancel').onclick = null; fn(); };
$('askOk').onclick = () => done(() => resolve($('askAnswer').value));
$('askCancel').onclick = () => done(() => reject(new Error('Stopped by you.')));
});
}
async function runStep(step, ctx, signal, logEntry) {
const c = Object.fromEntries(Object.entries(step.config).map(([k, v]) => [k, fill(v, ctx)]));
switch (step.type) {
case 'ai': return callAI(c.prompt, signal);
case 'summarize': return callAI('Summarize the following as ' + c.style + ':\n\n' + c.text, signal);
case 'checklist': return callAI('Extract every action item from the text below as a checklist. One per line starting with "[ ] ". Include who and when if mentioned.\n\n' + c.text, signal);
case 'email': return callAI('Write a ' + c.tone + ' email with a subject line. Context:\n\n' + c.brief, signal);
case 'translate': return callAI('Translate into ' + c.language + '. Keep formatting:\n\n' + c.text, signal);
case 'ask': return askUser(c.question);
case 'open': {
const href = safeLink(c.url);
if (!href) throw new Error('That link is not valid: ' + c.url);
const win = window.open(href, '_blank', 'noopener');
logEntry.append(el('a', { href, target: '_blank', rel: 'noopener', textContent: win ? 'Opened. Click to open again.' : 'Your browser blocked the pop-up. Click here to open.' }));
return ctx.previous;
}
case 'save': {
const blob = new Blob([c.text], { type: 'text/plain;charset=utf-8' });
const a = el('a', { href: URL.createObjectURL(blob), download: c.filename.replace(/[\\/:*?"<>|]/g, '_') || 'agent-result.txt' });
document.body.append(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 2000);
return c.text;
}
case 'code': {
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const fn = new AsyncFunction('input', 'previous', 'steps', 'ai', step.config.code);
const out = await fn(ctx.input, ctx.previous, [...ctx.steps], (p) => callAI(String(p), signal));
return typeof out === 'string' ? out : JSON.stringify(out, null, 2) ?? '';
}
}
throw new Error('Unknown step');
}
async function runFlow() {
if (!flow.length) return toast('Add at least one step first.');
const log = $('log');
log.replaceChildren();
document.querySelectorAll('.step').forEach((s) => s.classList.remove('running', 'done', 'failed'));
abort = new AbortController();
$('runBtn').disabled = true; $('stopBtn').disabled = false;
const input = $('taskInput').value;
localStorage.setItem(STORE.input, input);
const ctx = { input, previous: input, steps: [] };
for (let i = 0; i < flow.length; i++) {
const step = flow[i];
const card = document.querySelector('.step[data-id="' + step.id + '"]');
card?.classList.add('running');
const entry = el('div', { className: 'log-entry' });
const head = el('div', { className: 'log-title' }, [el('span', { textContent: (i + 1) + '. ' + step.title }), el('span', { textContent: 'working...' })]);
entry.append(head); log.append(entry);
entry.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
try {
const out = await runStep(step, ctx, abort.signal, entry);
ctx.previous = out ?? ''; ctx.steps.push(ctx.previous);
head.lastChild.textContent = 'done';
entry.insertBefore(el('pre', { textContent: ctx.previous }), head.nextSibling);
if (step.type !== 'open') entry.append(copyButton(ctx.previous));
card?.classList.replace('running', 'done');
} catch (err) {
card?.classList.replace('running', 'failed');
entry.classList.add('error');
head.lastChild.textContent = 'failed';
const msg = err.name === 'AbortError' ? 'Stopped.' :
err instanceof TypeError ? 'Could not reach the AI. Check your internet connection, key and provider settings.' : err.message;
entry.append(el('pre', { textContent: msg }));
break;
}
}
$('runBtn').disabled = false; $('stopBtn').disabled = true; abort = null;
}
function copyButton(text) {
const b = el('button', { className: 'icon-btn', textContent: 'Copy' });
b.addEventListener('click', async () => { await navigator.clipboard.writeText(text).catch(() => {}); toast('Copied'); });
return b;
}
// ---------- Autopilot ----------
async function plan() {
const goal = $('goalInput').value.trim();
if (!goal) return toast('Describe your goal first.');
const btn = $('planBtn'); btn.disabled = true; btn.textContent = 'Planning...';
const spec = PLANNABLE.map((t) => '- ' + t + ': ' + STEP_TYPES[t].desc + '. config keys: ' + STEP_TYPES[t].fields.map((f) => f.key + (f.options ? ' (one of ' + f.options.join(' | ') + ')' : '')).join(', ')).join('\n');
const prompt = 'Plan a workflow of 2 to 6 steps for this goal: "' + goal + '"\n\nAvailable step types:\n' + spec +
'\n\nIn text fields you may use {{input}} (the user\'s pasted task text), {{previous}} (last result) and {{stepN}}.\n' +
'Reply with ONLY a JSON array like [{"type":"summarize","title":"Short title","config":{...}}]. No other text.';
try {
const raw = await callAI(prompt);
const json = raw.slice(raw.indexOf('['), raw.lastIndexOf(']') + 1);
const steps = sanitizeFlow(JSON.parse(json)).filter((s) => s.type !== 'code');
if (!steps.length) throw new Error('The AI did not return any usable steps. Try rewording your goal.');
loadFlow(steps, { trusted: true });
switchView('builder');
toast('Plan ready. Review the steps, add your task text, then Run.');
} catch (err) {
toast(err instanceof SyntaxError ? 'The AI answer was not a valid plan. Try again.' : err.message);
} finally { btn.disabled = false; btn.textContent = 'Plan the steps'; }
}
function renderTemplates() {
for (const tpl of TEMPLATES) {
const card = el('button', { className: 'template' }, [el('strong', { textContent: tpl.name }), el('span', { textContent: tpl.about })]);
card.addEventListener('click', () => {
loadFlow(tpl.steps.map((s) => makeStep(s.type, s.title, s.config)), { trusted: true });
switchView('builder'); toast(tpl.name + ' loaded');
});
$('templateList').append(card);
}
}
// ---------- Code view ----------
function refreshCode() {
$('codeEditor').value = JSON.stringify({ version: 1, steps: flow.map(({ type, title, config }) => ({ type, title, config })) }, null, 2);
}
$('refreshCode').addEventListener('click', refreshCode);
$('applyCode').addEventListener('click', () => {
try {
if (loadFlow(sanitizeFlow(JSON.parse($('codeEditor').value)))) toast('Workflow updated');
} catch (err) { toast('Could not read that: ' + err.message); }
});
// ---------- Views, files, settings ----------
function switchView(name) {
document.querySelectorAll('.tab').forEach((t) => t.classList.toggle('active', t.dataset.view === name));
document.querySelectorAll('.view').forEach((v) => v.classList.toggle('active', v.id === 'view-' + name));
if (name === 'code') refreshCode();
}
document.querySelectorAll('.tab').forEach((t) => t.addEventListener('click', () => switchView(t.dataset.view)));
$('templatesBtn').addEventListener('click', () => switchView('autopilot'));
$('clearBtn').addEventListener('click', () => { if (flow.length && confirm('Remove all steps?')) { flow = []; save(); renderFlow(); } });
$('exportBtn').addEventListener('click', () => {
refreshCode();
const a = el('a', { href: URL.createObjectURL(new Blob([$('codeEditor').value], { type: 'application/json' })), download: 'my-agent-workflow.json' });
document.body.append(a); a.click(); a.remove();
});
$('importBtn').addEventListener('click', () => $('importFile').click());
$('importFile').addEventListener('change', async (e) => {
const file = e.target.files[0]; e.target.value = '';
if (!file) return;
try { if (loadFlow(sanitizeFlow(JSON.parse(await file.text())))) toast('Workflow opened'); }
catch (err) { toast('Could not open that file: ' + err.message); }
});
$('runBtn').addEventListener('click', runFlow);
$('stopBtn').addEventListener('click', () => abort?.abort());
$('planBtn').addEventListener('click', plan);
function updatePill() {
const p = PROVIDERS[settings.provider];
const pill = $('providerPill');
pill.replaceChildren('Using ', el('strong', { textContent: p.name }), settings.keys[settings.provider] || settings.provider === 'custom' ? '' : ' (no key yet)');
}
function fillSettingsForm(p) {
$('modelInput').value = settings.models[p] || PROVIDERS[p].model;
$('keyInput').value = settings.keys[p] || '';
$('baseUrlInput').value = settings.baseUrl || '';
$('baseUrlWrap').style.display = p === 'custom' ? '' : 'none';
$('keyHelp').textContent = PROVIDERS[p].help;
}
for (const [id, p] of Object.entries(PROVIDERS)) $('providerSelect').append(el('option', { value: id, textContent: p.name }));
$('providerSelect').addEventListener('change', (e) => fillSettingsForm(e.target.value));
$('openSettings').addEventListener('click', () => {
$('providerSelect').value = settings.provider; fillSettingsForm(settings.provider);
$('settingsModal').classList.add('open');
});
const readForm = () => {
const p = $('providerSelect').value;
return { ...settings, provider: p, keys: { ...settings.keys, [p]: $('keyInput').value.trim() },
models: { ...settings.models, [p]: $('modelInput').value.trim() }, baseUrl: $('baseUrlInput').value.trim() };
};
$('saveSettings').addEventListener('click', () => {
settings = readForm();
localStorage.setItem(STORE.settings, JSON.stringify(settings));
$('settingsModal').classList.remove('open'); updatePill(); toast('AI settings saved');
});
$('testKey').addEventListener('click', async () => {
const saved = settings; settings = readForm();
const btn = $('testKey'); btn.disabled = true; btn.textContent = 'Testing...';
try { await callAI('Reply with the single word: ready'); toast('Connected. Your AI is ready.'); }
catch (err) { toast(err instanceof TypeError ? 'Could not reach the AI. Check the provider and key.' : err.message); }
finally { settings = saved; btn.disabled = false; btn.textContent = 'Test connection'; }
});
document.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', () => b.closest('.modal-back').classList.remove('open')));
$('taskInput').value = localStorage.getItem(STORE.input) || '';
renderPalette(); renderTemplates(); renderFlow(); updatePill();
if (!flow.length) loadFlow(TEMPLATES[0].steps.map((s) => makeStep(s.type, s.title, s.config)), { trusted: true });
if (!settings.keys[settings.provider] && settings.provider !== 'custom') $('openSettings').click();
})();
</script>
</body>
</html>
src/pages/agent-setup.astro
Website setup/download page: bilingual instructions, requirements and links. This Astro file belongs in the website, not in the local installation folder.
---
import Layout from '../layouts/Layout.astro';
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
const language = Astro.url.searchParams.get('lang') || Astro.cookies.get('site_language')?.value || 'en';
const copy = (en: string, zh: string) => language === 'zh' ? zh : en;
---
<Layout title={copy('Your Own Xialei AI Agent | Xia Lei', '设置自己的 Xialei AI 助手 | Xia Lei')} description={copy('Download and run your own Xialei AI Agent on Windows, macOS or Linux.', '下载并在 Windows、macOS 或 Linux 上运行自己的 Xialei AI 助手。')}>
<Header />
<main class="setup">
<a href="/#tools">{copy('← Back to Tools', '← 返回实用工具')}</a>
<header>
<p class="eyebrow">XIALEI TOOLBOX · {copy('PUBLIC BETA', '公开测试版')}</p>
<h1>{copy('Your agent.', '你的助手。')}<br /><span>{copy('Your computer. Your choice.', '你的电脑,你的选择。')}</span></h1>
<p class="lead">{copy('Download your own copy of the Xialei AI Agent. Build workflows, connect your own AI provider or compatible local model, and run it in your browser on Windows, macOS or Linux.', '下载自己的 Xialei AI 助手副本。构建工作流,连接自己的 AI 服务或兼容的本地模型,并在 Windows、macOS 或 Linux 的浏览器中运行。')}</p>
<a class="download" href="/downloads/xialei-agent-setup-beta.zip" download>{copy('Download local setup kit · ZIP', '下载本地设置工具包 · ZIP')}</a>
<p><a href="/downloads/xialei-agent-beta.html" download>{copy('HTML-only download', '仅下载 HTML')}</a> · <a href="/downloads/xialei-agent-beta.html">{copy('Try in browser', '在浏览器中试用')}</a></p>
</header>
<aside><strong>{copy('A personal copy, not a bundled AI model.', '个人副本,不包含 AI 模型。')}</strong> {copy('The kit includes the agent, local launchers and instructions. Install Python 3 first if needed. No paid AI account, provider key or local model is included. This is a browser-based beta, not a signed native desktop installer.', '工具包包含助手、本地启动器和说明。如有需要请先安装 Python 3。不包含付费 AI 账号、服务密钥或本地模型。这是浏览器版测试工具,并非已签名的原生桌面安装程序。')}</aside>
<section><h2>{copy('Set up on your computer', '在你的电脑上设置')}</h2>
<p>{copy('Extract the whole ZIP and keep its files together. The included launcher opens a private local browser address; keep its window open while using the agent.', '解压整个 ZIP 并保留所有文件。启动器会打开私有的本地浏览器地址;使用时请保持启动器窗口打开。')}</p>
<div class="platforms">
<article><h3>Windows</h3><p>{copy('Install Python 3 with its launcher, then open Start Agent.bat.', '安装带启动器的 Python 3,然后打开 Start Agent.bat。')}</p></article>
<article><h3>macOS</h3><p>{copy('Install Python 3, then open Start Agent.command.', '安装 Python 3,然后打开 Start Agent.command。')}</p></article>
<article><h3>Linux</h3><p>{copy('Use Python 3 and have your administrator run the included start-agent.sh with sh.', '使用 Python 3,并请管理员用 sh 运行附带的 start-agent.sh。')}</p></article>
</div>
<p><a href="https://www.python.org/downloads/">{copy('Official Python download', 'Python 官方下载')}</a></p>
<p>{copy('If your OS blocks an unsigned launcher, do not disable security protections. Use Python to open the included launch.py instead. An HTML-only copy can also be opened directly, but browser restrictions vary.', '若系统阻止未签名启动器,请勿关闭安全保护;可使用 Python 打开附带的 launch.py。也可直接打开 HTML 副本,但浏览器限制可能不同。')}</p>
</section>
<section><h2>{copy('Connect your own AI', '连接自己的 AI')}</h2><ol>
<li>{copy('Open Settings. Choose Claude, OpenAI, Grok, Gemini, or Local / other for an OpenAI-compatible server.', '打开 Settings,选择 Claude、OpenAI、Grok、Gemini,或 Local / other(兼容 OpenAI 的服务器)。')}</li>
<li>{copy('Enter your own provider key and an available model. For local AI, install Ollama or another compatible server separately, download a model, and enter its server address and exact model name.', '输入自己的服务密钥和可用模型。本地 AI 需另行安装 Ollama 或其他兼容服务器、下载模型,并填写服务器地址及准确的模型名称。')}</li>
<li>{copy('Use the connection test, choose or create a workflow, enter your task, and run it. Export workflows to move them to another computer; configure provider settings separately there.', '测试连接,选择或创建工作流,输入任务并运行。导出工作流即可移到其他电脑;在新电脑上另行设置 AI 服务。')}</li>
</ol><a href="/ollama-setup">{copy('Need a local model? Get the Ollama toolkit →', '需要本地模型?获取 Ollama 工具 →')}</a>
<p>{copy('Some providers block browser connections. Local services may need to allow the agent’s exact local address, http://127.0.0.1:8765. Do not permit every origin or expose the service publicly. The kit does not change those settings automatically.', '部分服务会阻止浏览器连接。本地服务可能需要允许助手的准确地址 http://127.0.0.1:8765;请勿允许所有来源或公开服务。工具包不会自动更改这些设置。')}</p></section>
<aside><strong>{copy('Keep your keys private.', '保护你的密钥。')}</strong> {copy('The existing standalone agent keeps settings, including keys, in this browser profile without encryption. Use personal restricted keys, never include keys in a client download, and export workflows before clearing browser data. Cloud AI sends task content to your chosen provider and may charge fees; local installation alone does not make it offline.', '现有独立助手将设置(包括密钥)保存在此浏览器配置中,未加密。请使用个人受限密钥,不要在给客户的下载包中包含密钥,并在清除浏览器数据前导出工作流。云 AI 会将任务内容发送给所选服务且可能收费;本地安装不代表离线运行。')}</aside>
<p>{copy('Launchers have been checked locally; actual browser connections to AI providers and behavior on physical devices remain unverified. This assistant does not grant AI unrestricted control of your operating system.', '启动器已在当前环境中检查;与实际 AI 服务的浏览器连接及实体设备上的行为尚未验证。此助手不会授予 AI 无限制控制操作系统的权限。')}</p>
</main>
<Footer />
</Layout>
<style>
.setup { max-width:1040px; margin:auto; padding:64px 24px 96px; color:#edf6ff; line-height:1.5; background:radial-gradient(ellipse at 80% 10%,#14546340,transparent 45%),#091522; }
a { color:#a5def0; } header { padding:40px 0 24px; } .eyebrow { color:#a6e3d6; font-size:.75rem; letter-spacing:.12em; font-weight:600; }
h1 { font-size:clamp(2.5rem,6vw,4.5rem); line-height:1.2; margin:16px 0 24px; font-weight:600; } h1 span { color:#a6e3d6; } h2,h3 { line-height:1.2; color:#edf6ff; }
.lead { max-width:720px; font-size:1.125rem; color:#c4d7e6; } .download { display:inline-block; margin:16px 0; background:#a5def0; color:#10212b; padding:16px 24px; border-radius:8px; font-weight:600; text-decoration:none; }
aside,section { padding:24px; background:#102538; border:1px solid #345063; border-radius:16px; margin:24px 0; color:#c4d7e6; } strong { color:#edf6ff; } li { margin:16px 0; } ol { padding-left:24px; }
.platforms { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:24px; } a:focus-visible { outline:2px solid #a6e3d6; outline-offset:4px; }
@media(max-width:640px) { .setup { padding:40px 16px; } .platforms { grid-template-columns:1fr; gap:8px; } aside,section { padding:16px; } }
</style>
7 SOURCE FILES
FLUX local image generation
An unofficial local image studio using Black Forest Labs’ FLUX.1 schnell, PyTorch, Diffusers and Gradio. Model weights and Python are not included.
How it works
- setup.py checks Python 3.10–3.12 and requires YES before creating .venv and installing packages. A .ready marker prevents repeated installation. An optional hidden Hugging Face token is passed to its login library.
- app.py waits for a nonempty prompt and explicit model-download approval. It loads the model once, selecting NVIDIA CUDA, Apple Metal or CPU and memory-saving VAE slicing/tiling where supported.
- Generation uses four inference steps, guidance scale 0, a maximum sequence length of 256 and a 512×512 output. Gradio queues up to eight requests and runs one generation at a time, serving only on loopback with public sharing disabled.
What you need
Python 3.10–3.12, approved Hugging Face model access, at least 50 GB disk space and substantial memory. 32 GB RAM/high-memory GPU is a starting recommendation, not a guarantee; CPU-only can need over 64 GB. NVIDIA needs compatible drivers/CUDA PyTorch.
Privacy, safety & limits
Initial package/model downloads need internet. Generation runs locally once cached. Deleting the kit does not remove the Hugging Face model cache or saved login. FLUX.1 schnell uses Apache 2.0; review upstream terms. Physical-device inference remains unverified.
Files & complete source code
flux-setup/app.py
Gradio image interface and lazy FLUX pipeline loading; selects device/precision, applies download consent, generates images and reports failures.
import gradio as gr
import torch
from diffusers import FluxPipeline
def main():
pipeline = None
def generate(prompt, approved):
nonlocal pipeline
if not prompt.strip():
raise gr.Error('Describe the image you would like to create.')
if not approved:
raise gr.Error('Confirm the model download and hardware requirements first.')
try:
if pipeline is None:
cuda = torch.cuda.is_available()
mps = torch.backends.mps.is_available()
dtype = torch.bfloat16 if cuda and torch.cuda.is_bf16_supported() else torch.float16 if cuda or mps else torch.float32
candidate = FluxPipeline.from_pretrained('black-forest-labs/FLUX.1-schnell', torch_dtype=dtype)
if cuda:
candidate.enable_model_cpu_offload()
elif mps:
candidate.to('mps')
candidate.enable_vae_slicing()
candidate.enable_vae_tiling()
pipeline = candidate
return pipeline(prompt=prompt.strip(), guidance_scale=0.0,
num_inference_steps=4, max_sequence_length=256,
width=512, height=512).images[0]
except Exception:
raise gr.Error('Generation failed. Check Hugging Face access and login, internet access, disk space and available memory. Restart the launcher after changing your setup.') from None
with gr.Blocks(title='Xialei FLUX local beta') as app:
gr.Markdown('# FLUX local image studio\nIndependent Xialei beta using Black Forest Labs’ FLUX.1 schnell. Images are generated on this computer, not by a cloud image service.')
gr.Markdown('First generation downloads tens of GB from Hugging Face. Accept the model’s access conditions and sign in through the launcher. Allow at least 50 GB free disk space; 32 GB system memory and a high-memory GPU are a starting recommendation, not a guarantee. CPU generation is especially slow and may need more memory. Close the launcher to stop the local service.')
prompt = gr.Textbox(label='Describe your image', lines=4, max_lines=8)
approved = gr.Checkbox(label='I approve downloading the model and understand the hardware requirements.')
button = gr.Button('Generate image', variant='primary')
image = gr.Image(label='Your image — use the download button to save', type='pil', interactive=False)
button.click(generate, [prompt, approved], image, concurrency_limit=1)
app.queue(max_size=8).launch(server_name='127.0.0.1', share=False, inbrowser=True)
if __name__ == '__main__':
main()
flux-setup/README.txt
Complete installation, usage, privacy and troubleshooting notes distributed with this kit.
Xialei FLUX local setup toolkit — unofficial beta
Uses Black Forest Labs FLUX.1 schnell (Apache 2.0).
Official model/access terms: https://huggingface.co/black-forest-labs/FLUX.1-schnell
1. Install Python 3.10–3.12 with pip from https://www.python.org/downloads/ . On Windows include the Python launcher.
2. Sign in to Hugging Face and accept the official model access conditions. Create a read-only token if needed.
3. Extract this whole folder into a writable location. Keep all files together.
4. Windows: open Start FLUX.bat. macOS: open Start FLUX.command. Linux: run start-flux.sh with your shell. If your OS blocks the unsigned launcher, use Python to open setup.py instead; do not disable security protections.
5. Type YES to allow package installation. Enter your Hugging Face token when prompted (hidden input), or leave blank if already logged in. The official Hugging Face library stores the token on your computer, not on Xialei.
6. A local browser interface opens. Describe an image, approve the model download, then select Generate image. Save the result with its download button.
Packages are installed in .venv inside this folder. Models are cached by Hugging Face in your home folder; deleting this toolkit alone does not remove the model cache or saved login. Subsequent launches reuse installed packages and model files. Internet is needed for setup and the first model download; cached generation runs locally. No API payment required.
Allow at least 50 GB free disk space. 32 GB RAM and a high-memory NVIDIA GPU (roughly 16 GB VRAM or more with CPU offload) are a starting recommendation, not guaranteed compatibility. Apple Silicon uses Metal when available, sharing system memory. CPU-only mode is much slower and can require over 64 GB RAM. This is an unquantized model, not a lightweight Chromebook installer. Intel Macs use CPU mode. NVIDIA acceleration requires compatible drivers and a CUDA-enabled PyTorch installation; default packages may use CPU depending on platform. GPU drivers are not installed by this toolkit.
The app binds only to 127.0.0.1; no public sharing link is enabled. It does not deliberately send prompts to an image-generation API. Third-party package/model downloads contact PyPI and Hugging Face. Model loading may take a long time. To stop, close the launcher. Failed downloads, insufficient memory, missing approval or unsupported hardware can prevent generation. Reduce other memory use, check access, and reopen the launcher.
Independent wrapper, not affiliated with or endorsed by Black Forest Labs. No model weights or Python runtime bundled. Wrapper and app have not been tested on physical Mac/Windows/Linux hardware. Review upstream licensing and acceptable-use conditions before use.
flux-setup/setup.py
Checks Python, obtains consent, installs an isolated environment, logs into Hugging Face if requested and launches the image app.
import getpass
import os
from pathlib import Path
import subprocess
import sys
import venv
def main():
if not (3, 10) <= sys.version_info[:2] <= (3, 12):
print('Please install Python 3.10, 3.11 or 3.12, then open this launcher again.')
return 1
root = Path(__file__).resolve().parent
environment = root / '.venv'
python = environment / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')
ready = environment / '.ready'
if not ready.exists():
print('Xialei FLUX beta: independent, unofficial local setup toolkit.')
print('Installs Python packages from PyPI into this folder. No model is downloaded yet.')
print('First image generation downloads tens of GB from Hugging Face after access approval.')
print('Allow at least 50 GB free disk space. High-memory hardware is strongly recommended.')
if input('Type YES to install: ').strip() != 'YES':
print('Cancelled. Nothing installed.')
return 0
venv.create(environment, with_pip=True)
subprocess.run([str(python), '-m', 'pip', 'install', '--upgrade', 'pip'], check=True)
subprocess.run([str(python), '-m', 'pip', 'install', 'torch>=2.4,<3',
'diffusers>=0.35,<1', 'transformers>=4.44,<5', 'accelerate>=1,<2',
'sentencepiece', 'protobuf', 'gradio>=5,<6'], check=True)
ready.touch()
print('Accept access conditions at https://huggingface.co/black-forest-labs/FLUX.1-schnell first.')
print('Optional read-only Hugging Face token; saved by Hugging Face on this computer.')
token = getpass.getpass('Token (leave blank to use an existing login): ').strip()
if token:
result = subprocess.run([str(python), '-c',
'from huggingface_hub import login; import sys; login(token=sys.stdin.read().strip(), add_to_git_credential=False)'],
input=token, text=True, capture_output=True)
if result.returncode:
print('Login failed. Check your token and approved model access, then reopen the launcher.')
return 1
return subprocess.run([str(python), str(root / 'app.py')], cwd=root).returncode
if __name__ == '__main__':
try:
sys.exit(main())
except (OSError, subprocess.CalledProcessError):
print('Setup failed. Check internet access, free disk space and Python availability, then try again.')
sys.exit(1)
flux-setup/Start FLUX.bat
Windows entry point: starts the neighboring Python script using the Python launcher and keeps the window open for messages.
@echo off
py -3 "%~dp0setup.py"
pause
flux-setup/Start FLUX.command
macOS/Linux entry point: resolves its own folder and starts the neighboring Python script. Keep the complete kit together.
#!/bin/sh
HERE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$HERE/setup.py"
printf '\nPress Enter to close.'
read -r answer
flux-setup/start-flux.sh
macOS/Linux entry point: resolves its own folder and starts the neighboring Python script. Keep the complete kit together.
#!/bin/sh
HERE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$HERE/setup.py"
src/pages/flux-setup.astro
Website setup/download page: bilingual instructions, requirements and links. This Astro file belongs in the website, not in the local installation folder.
---
import Layout from '../layouts/Layout.astro';
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
const zh = Astro.url.searchParams.get('lang') === 'zh' || Astro.cookies.get('site_language')?.value === 'zh';
const copy = (en: string, cn: string) => zh ? cn : en;
---
<Layout title={copy('FLUX Local Image Toolkit | Xia Lei', 'FLUX 本地图像生成工具 | Xia Lei')} description={copy('Generate images locally with a downloadable FLUX.1 schnell setup toolkit.', '下载 FLUX.1 schnell 安装工具,在自己的电脑上生成图像。')}>
<Header />
<main class="setup">
<a href="/#tools">{copy('← Back to Tools', '← 返回实用工具')}</a>
<header>
<p class="eyebrow">XIALEI TOOLBOX · {copy('PUBLIC BETA', '公开测试版')}</p>
<h1>{copy('Your words. Your images.', '你的文字,你的图像。')}<br /><span>{copy('Generated locally.', '在本地生成。')}</span></h1>
<p class="lead">{copy('Create images on your own computer with Black Forest Labs’ FLUX.1 schnell. This independent toolkit installs the software and opens a private, local image studio in your browser.', '使用 Black Forest Labs 的 FLUX.1 schnell 在自己的电脑上创建图像。这个独立工具会安装所需软件,并在浏览器中打开私有的本地图像工作室。')}</p>
<a class="download" href="/downloads/xialei-flux-setup-beta.zip" download>{copy('Download FLUX toolkit · ZIP', '下载 FLUX 工具 · ZIP')}</a>
<p>{copy('Windows · macOS · Linux · Python 3.10–3.12 required', 'Windows · macOS · Linux · 需要 Python 3.10–3.12')}</p>
</header>
<aside><strong>{copy('Check before downloading.', '下载前请确认。')}</strong> {copy('This is a large, unquantized model—not a lightweight installer. Allow at least 50 GB free disk space. 32 GB RAM and a high-memory GPU are a starting recommendation, not guaranteed compatibility. CPU-only generation can need over 64 GB RAM and is very slow. Ordinary Chromebooks are not recommended.', '这是大型、未量化的模型,并非轻量级安装包。请预留至少 50 GB 磁盘空间。32 GB 内存和大显存 GPU 是初步建议,并不保证兼容。仅 CPU 运行可能需要超过 64 GB 内存,且非常慢。不建议普通 Chromebook 使用。')}</aside>
<section><h2>{copy('From setup to your first image', '从安装到第一张图像')}</h2>
<ol>
<li><strong>{copy('Install Python first.', '先安装 Python。')}</strong> {copy('Use Python 3.10–3.12 with pip; on Windows include the Python launcher.', '安装带 pip 的 Python 3.10–3.12;Windows 需包含 Python 启动器。')} <a href="https://www.python.org/downloads/">{copy('Official Python download', 'Python 官方下载')}</a></li>
<li><strong>{copy('Approve model access.', '授权模型访问。')}</strong> {copy('Sign in to Hugging Face and accept the official model download conditions. Prepare a read-only access token for the launcher. It is stored on your computer by Hugging Face, not sent to Xialei.', '登录 Hugging Face 并接受官方模型下载条件。为启动器准备只读访问令牌;令牌由 Hugging Face 保存在你的电脑上,不会发送给 Xialei。')} <a href="https://huggingface.co/black-forest-labs/FLUX.1-schnell">{copy('Official model and access conditions', '官方模型及访问条件')}</a></li>
<li><strong>{copy('Extract and launch.', '解压并启动。')}</strong> {copy('Keep all files together. Windows: open Start FLUX.bat. Mac: open Start FLUX.command. Linux: have your administrator run the included start-flux.sh. Type YES to approve installation and enter your token when asked. If your system blocks the unsigned launcher, do not disable security protections; use Python to open setup.py instead.', '请保留所有文件。Windows 打开 Start FLUX.bat;Mac 打开 Start FLUX.command;Linux 请管理员运行 start-flux.sh。输入 YES 同意安装,并按提示输入令牌。若系统阻止未签名启动器,请勿关闭安全保护,可使用 Python 打开 setup.py。')}</li>
<li><strong>{copy('Describe, generate, save.', '描述、生成、保存。')}</strong> {copy('In the local browser studio, enter your description and confirm the model download. The first generation downloads tens of gigabytes; later runs reuse the cache. Save your image with its download button. Close the launcher to stop the studio.', '在本地浏览器工作室中输入描述并确认模型下载。首次生成会下载数十 GB 文件,后续使用缓存。使用图像上的下载按钮保存;关闭启动器即可停止工作室。')}</li>
</ol>
</section>
<section><h2>{copy('Private by design. Hardware dependent.', '本地运行,依赖硬件。')}</h2><p>{copy('The studio listens only on your own computer and does not enable a public sharing link. Images are generated locally, not through a paid cloud image API. Installation and model downloads contact PyPI and Hugging Face. NVIDIA acceleration needs compatible drivers and CUDA-enabled PyTorch; the toolkit does not install drivers. Apple Silicon uses Metal when available; Intel Macs use CPU mode.', '工作室仅在本机监听,不开启公开分享链接。图像在本地生成,不使用付费云图像 API。安装和模型下载会连接 PyPI 和 Hugging Face。NVIDIA 加速需要兼容驱动和支持 CUDA 的 PyTorch,工具不安装驱动。Apple Silicon 在可用时使用 Metal,Intel Mac 使用 CPU。')}</p><p>{copy('Independent Xialei beta, not affiliated with or endorsed by Black Forest Labs. Uses FLUX.1 schnell (Apache 2.0); review the official model conditions. Model files are not bundled. Actual installation and image generation have not been verified on physical Windows, Mac or Linux machines.', '这是独立的 Xialei 测试工具,与 Black Forest Labs 无隶属关系,也未获其背书。使用 FLUX.1 schnell(Apache 2.0),请查看官方模型条件。下载包不包含模型。尚未在实际 Windows、Mac 或 Linux 设备上验证安装和图像生成。')}</p></section>
</main>
<Footer />
</Layout>
<style>
.setup { max-width:1040px; margin:auto; padding:64px 24px 96px; color:#edf6ff; line-height:1.5; background:radial-gradient(ellipse at 80% 10%,#14546340,transparent 45%),#091522; }
a { color:#a5def0; } header { padding:40px 0 24px; } .eyebrow { color:#a6e3d6; font-size:.75rem; letter-spacing:.12em; font-weight:600; }
h1 { font-size:clamp(2.5rem,6vw,4.5rem); line-height:1.2; letter-spacing:-.04em; margin:16px 0 24px; font-weight:600; } h1 span { color:#a6e3d6; } h2 { line-height:1.2; }
.lead { max-width:720px; font-size:1.125rem; color:#c4d7e6; } .download { display:inline-block; margin:16px 0; background:#a5def0; color:#10212b; padding:16px 24px; border-radius:8px; font-weight:600; text-decoration:none; }
aside,section { padding:24px; background:#102538; border:1px solid #345063; border-radius:16px; margin:24px 0; color:#c4d7e6; } strong,h2 { color:#edf6ff; } li { margin:16px 0; } ol { padding-left:24px; }
a:focus-visible { outline:2px solid #a6e3d6; outline-offset:4px; } @media(max-width:640px) { .setup { padding:40px 16px; } aside,section { padding:16px; } }
</style>
XIA LEI