返回实用工具

XIALEI 工具箱 · 工作原理

源代码与详细说明。

公开五个实用工具。了解每个工具的功能、文件如何协作,以及使用或修改前需要检查的事项。

11 源文件

Drupal 转 React/Vue 初始项目

导入已授权的 Drupal 公开 JSON:API 内容,并打包为 React 或 Vue 网站初始项目。可选的读取模块允许管理员启用来自 Xialei 的只读浏览器访问。

工作原理

  1. 转换器检查 HTTPS 网站地址和授权确认,发现内容类型,并在限制范围内分页读取 JSON:API,不发送凭据。
  2. 导入的标题、URL 别名和纯文本正文形成临时浏览器快照。导出器创建 package.json、Vite 配置、前端代码、样式、报告和说明,然后使用 fflate 压缩。
  3. 生成的 React/Vue 应用在加载页面时读取 Drupal 实时内容。如果请求失败,会明确标注并显示导出快照。
  4. Drupal 模块默认禁用。管理员表单保存配置;事件订阅器仅允许 https://xialei.com 对 JSON:API 发出 GET 和有限的 OPTIONS 请求。Drupal 内容权限仍然生效。

所需条件

转换器:提供已授权公开 JSON:API 内容的 Drupal 网站。读取模块:Drupal 10/11 和核心 JSON:API。导出应用:Node.js、支持页面路由回退的网站托管,以及单独配置的允许来源。

隐私、安全和限制

不是主题克隆:富文本、媒体、自定义字段、菜单、翻译、搜索、表单、账号和电商需另行实现。CORS 不是授权机制。请先在测试站点验证模块;尚未在运行中的 Drupal 网站验证。

文件和完整源代码

xialei_reader/config/install/xialei_reader.settings.yml

模块默认配置:浏览器分享禁用,直到管理员启用。

2 行 · 源文本,不在此执行
enabled: false

xialei_reader/config/schema/xialei_reader.schema.yml

在 Drupal 配置系统中声明 enabled 为布尔值。

8 行 · 源文本,不在此执行
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

随工具包分发的完整安装、使用、隐私及故障排查说明。

21 行 · 源文本,不在此执行
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 请求和响应监听器:准确来源的只读浏览器分享及有限预检响应。它不授予内容权限。

62 行 · 源文本,不在此执行
<?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 管理员配置表单,读取和保存模块启用设置。

32 行 · 源文本,不在此执行
<?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

模块名称、描述、Drupal 版本支持和 JSON:API 依赖。

9 行 · 源文本,不在此执行
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

向 Drupal 管理菜单添加设置链接。

6 行 · 源文本,不在此执行
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

管理员设置地址、表单类和所需管理权限。

8 行 · 源文本,不在此执行
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

使用 Drupal 配置服务注册 CORS 事件订阅器。

7 行 · 源文本,不在此执行
services:
  xialei_reader.cors:
    class: Drupal\xialei_reader\EventSubscriber\CorsSubscriber
    arguments: ['@config.factory']
    tags:
      - { name: event_subscriber }

src/lib/drupalExport.ts

ZIP 导出器及完整的 React/Vue 生成模板、实时 Drupal 读取器、快照回退、配置和报告。

82 行 · 源文本,不在此执行
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

转换器界面、公开内容验证与导入、预览和下载操作。其脚本导入下方展示的导出器。

212 行 · 源文本,不在此执行
---
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 &amp; 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 &amp; 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 &amp; 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 源文件

Ollama 安装工具

一个非官方、需用户确认的 Ollama 官方安装器包装工具,分别支持 Windows、macOS 和 Linux。

工作原理

  1. 首先检查平台和现有安装。如果已安装 Ollama,显示版本并保持不变。
  2. 下载前要求准确输入 YES。Shell 脚本将官方 HTTPS 安装器下载到临时目录;Windows 脚本下载官方程序并验证 Authenticode 签名和 Ollama 发布者。
  3. 运行官方安装器,检查安装版本并清理临时文件。随后需另行选择和下载 AI 模型。

所需条件

兼容的 Windows/macOS 或 64 位 x86/ARM Linux;网络连接及官方安装器所需权限。Linux 需要 curl。ChromeOS 需启用兼容的 Linux 开发环境。

隐私、安全和限制

不包含模型、GPU 驱动或公开 API 配置。Shell 下载使用 HTTPS,但未固定独立验证的校验和。不要为运行未签名包装脚本而关闭系统保护。尚未在实际设备验证安装。

文件和完整源代码

ollama-setup/Install Ollama.command

macOS 入口,启动相邻的 shell 安装器并保留结果显示。

8 行 · 源文本,不在此执行
#!/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 安装器:检查现有 Ollama、获取许可、验证官方程序签名、安装、检查版本并清理临时文件。

36 行 · 源文本,不在此执行
$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 安装器,包含平台检查、YES 许可、官方 HTTPS 下载、临时文件清理和版本检查。

36 行 · 源文本,不在此执行
#!/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

随工具包分发的完整安装、使用、隐私及故障排查说明。

22 行 · 源文本,不在此执行
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

网站设置和下载页面:双语说明、要求及链接。此 Astro 文件用于网站,而非本地安装目录。

34 行 · 源文本,不在此执行
---
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 源文件

Xialei AI 智能助手

独立浏览器工作流助手及小型 Python 启动器。HTML 包含界面、工作流执行和对所选 AI 服务的直接请求。

工作原理

  1. 解压完整工具包。launch.py 仅读取相邻的助手 HTML,并在 127.0.0.1:8765 提供访问。它检查 Host 头且仅接受两个助手页面路径,不暴露其他文件。
  2. 在设置中选择服务和模型,提供自己的密钥或兼容本地服务器。助手执行 AI 提示、清单、草稿和保存笔记等工作流步骤,并支持导入导出。
  3. 设置、密钥、工作流和输入保存在浏览器 localStorage,而不是 Xialei 数据库。云端 AI 步骤会将输入发送给所选服务;本地启动器并不使这些步骤离线运行。

所需条件

启动器需要 Python 3、现代浏览器,以及自己的受支持 AI 服务或单独安装的 OpenAI 兼容本地模型服务。有些服务限制浏览器直接请求。

隐私、安全和限制

浏览器存储中的密钥未加密。使用受限制的个人密钥,不要放入分发工具包。使用本地 AI 时,仅授权启动器的准确来源,不要允许所有来源(即使旧版界面提示通配符)。这不是无限制系统助手或后台服务。尚未验证实际 AI 服务连接。

文件和完整源代码

agent-setup/launch.py

标准库本机 HTTP 服务器。读取工具包 HTML、限制路径及 Host 值、打开浏览器,并持续运行直到关闭。

46 行 · 源文本,不在此执行
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

随工具包分发的完整安装、使用、隐私及故障排查说明。

17 行 · 源文本,不在此执行
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 入口:使用 Python 启动器运行相邻 Python 脚本,并保留窗口显示消息。

4 行 · 源文本,不在此执行
@echo off
py -3 "%~dp0launch.py"
pause

agent-setup/Start Agent.command

macOS/Linux 入口:定位自身目录并启动相邻 Python 脚本。请保留完整工具包文件。

6 行 · 源文本,不在此执行
#!/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 入口:定位自身目录并启动相邻 Python 脚本。请保留完整工具包文件。

4 行 · 源文本,不在此执行
#!/bin/sh
HERE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$HERE/launch.py"

xialei-agent-beta.html

完整独立应用:HTML 界面、CSS、服务请求、工作流步骤、设置和浏览器存储。复制到 .html 文件,而非 Python 脚本。

673 行 · 源文本,不在此执行
<!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

网站设置和下载页面:双语说明、要求及链接。此 Astro 文件用于网站,而非本地安装目录。

50 行 · 源文本,不在此执行
---
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 源文件

FLUX 本地图像生成

使用 Black Forest Labs FLUX.1 schnell、PyTorch、Diffusers 和 Gradio 的非官方本地图像工作室。不包含模型权重或 Python。

工作原理

  1. setup.py 检查 Python 3.10–3.12,要求输入 YES 后创建 .venv 并安装软件包。.ready 标记避免重复安装。可选 Hugging Face 密钥通过隐藏输入传递给登录库。
  2. app.py 等待非空提示及明确的模型下载许可。模型只加载一次,选择 NVIDIA CUDA、Apple Metal 或 CPU,并在支持时使用节省内存的 VAE 切片和分块。
  3. 生成采用四次推理步骤、引导值 0、最大序列长度 256 和 512×512 输出。Gradio 最多排队八个请求,每次生成一张图像,仅在本机提供服务并禁用公开分享。

所需条件

Python 3.10–3.12、Hugging Face 模型下载权限、至少 50 GB 磁盘及大量内存。32 GB RAM 和大显存 GPU 只是起始建议,不保证兼容;仅 CPU 可能需超过 64 GB。NVIDIA 需要兼容驱动和 CUDA PyTorch。

隐私、安全和限制

首次下载软件包和模型需要网络。缓存后在本地生成。删除工具包不会删除 Hugging Face 模型缓存或保存的登录。FLUX.1 schnell 使用 Apache 2.0;请查看官方条款。尚未验证实际设备推理。

文件和完整源代码

flux-setup/app.py

Gradio 图像界面和按需 FLUX 管线加载;选择设备和精度、确认下载许可、生成图像并报告失败。

47 行 · 源文本,不在此执行
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

随工具包分发的完整安装、使用、隐私及故障排查说明。

20 行 · 源文本,不在此执行
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

检查 Python、获取许可、安装隔离环境、按需登录 Hugging Face,并启动图像应用。

50 行 · 源文本,不在此执行
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 入口:使用 Python 启动器运行相邻 Python 脚本,并保留窗口显示消息。

4 行 · 源文本,不在此执行
@echo off
py -3 "%~dp0setup.py"
pause

flux-setup/Start FLUX.command

macOS/Linux 入口:定位自身目录并启动相邻 Python 脚本。请保留完整工具包文件。

6 行 · 源文本,不在此执行
#!/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 入口:定位自身目录并启动相邻 Python 脚本。请保留完整工具包文件。

4 行 · 源文本,不在此执行
#!/bin/sh
HERE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$HERE/setup.py"

src/pages/flux-setup.astro

网站设置和下载页面:双语说明、要求及链接。此 Astro 文件用于网站,而非本地安装目录。

40 行 · 源文本,不在此执行
---
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>

8 源文件

AutoFix 按需自动修复

面向系统管理员的 Python 标准库工具。将简单描述匹配到六种固定修复方案之一,每种方案包含只读诊断、明确修复和复查。不带参数运行时,会先自动安装并进行只读安全与网络检查。

工作原理

  1. 启动器不带参数运行 autofix.py,即 --auto:install() 将三个 .py 文件和 README 复制到 ~/.xialei-autofix/app,并创建 autofix 命令(WindowsApps\autofix.cmd 或 ~/.local/bin/autofix)。使用 sudo 或已从安装副本运行时跳过安装。
  2. autofix_security.run_checks 使用带超时的固定只读命令,读取防火墙、磁盘加密、更新、恶意软件与系统防护、登录设置、监听所有接口的端口、Wi-Fi 安全、TLS 证书验证和代理。结果分为 OK/WARN/RISK/UNKNOWN 并保存为带日期的报告。随后诊断 DNS、网络、磁盘和防火墙,每个失败项走正常的 YES 流程。
  3. 请求文字与中英文关键词匹配,选择 dns、network、disk、time、print 或 firewall。文字仅用于匹配,从不执行。--issue 跳过匹配;--list 列出方案。
  4. 首先运行不做更改的诊断。若未发现问题则停止。否则显示准确命令,检查管理员权限但不自动提升,并要求准确输入 YES(--dry-run 时直接停止)。
  5. 修复使用固定参数列表执行,不经过 shell,超时 120 秒。随后再次诊断。匹配的问题、诊断、命令、退出码和云端连接追加写入用户目录中的 autofix-log.txt。
  6. 可选 API 连接:--link-api 验证 https(或本机 http)OpenAI 兼容地址,发送测试请求,成功后才保存配置。未匹配的请求由 AI 归类为一个方案 ID;其他回复一律忽略。
  7. 可选 MCP 服务:--mcp 通过标准输入输出使用 JSON-RPC,提供 list_issues、match_request、diagnose、security_check 和 apply_fix。未使用 --allow-fixes 启动时拒绝 apply_fix,且仍需通过管理员和远程会话检查。

所需条件

Windows、macOS 或 Linux 上的 Python 3.8+。时间修复、Windows 网络和打印修复、macOS/Linux DNS 修复(及 macOS 网络修复)需要管理员权限。Linux 需要 systemd-resolved、NetworkManager、timedatectl 和 CUPS。云端连接需要自己的 API 密钥或本地模型。

隐私、安全和限制

未连接时完全离线:只有未匹配的描述会发送给已连接的 AI,从不发送密钥或日志。密钥未加密保存在用户目录(macOS/Linux 仅所有者可读)。磁盘清理仅处理用户临时目录。在 SSH/远程桌面会话中拒绝网络和防火墙修复。安全检查只针对本机,不扫描其他设备。已在 Linux 使用模拟防火墙/端口工具、模拟 AI 服务和 MCP 会话测试;Windows 和 macOS 检查、真实服务和特定助手尚未验证。

文件和完整源代码

autofix-setup/autofix_cloud.py

云端连接:地址验证、经验证的 OpenAI 兼容 API 连接、仅限方案的 AI 分类、私有配置存储、支持代理的连通性检查和 MCP JSON-RPC 标准输入输出服务。

170 行 · 源文本,不在此执行
"""Cloud links for Xialei AutoFix: a verified AI API (OpenAI-compatible) and an MCP stdio server."""
import contextlib
import io
import ipaddress
import json
import os
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime

LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
MCP_PROTOCOL = "2025-06-18"


def config_path(home):
    return home / "config.json"


def load_config(home):
    try:
        return json.loads(config_path(home).read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return {}


def save_config(home, cfg):
    home.mkdir(parents=True, exist_ok=True)
    path = config_path(home)
    path.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
    with contextlib.suppress(OSError):
        os.chmod(path, 0o600)


def unlink(home):
    with contextlib.suppress(FileNotFoundError):
        config_path(home).unlink()


def safe_proxy(url):
    parts = urllib.parse.urlsplit(url)
    return f"{parts.hostname}:{parts.port}" if parts.port else (parts.hostname or "set")


def validate_url(url):
    parts = urllib.parse.urlsplit(url.strip())
    host = (parts.hostname or "").lower()
    if not host:
        raise ValueError("The address needs a host name, e.g. https://api.openai.com/v1")
    if parts.scheme == "https":
        return url.strip().rstrip("/")
    if parts.scheme == "http" and host in LOCAL_HOSTS:
        return url.strip().rstrip("/")
    with contextlib.suppress(ValueError):
        if parts.scheme == "http" and ipaddress.ip_address(host).is_loopback:
            return url.strip().rstrip("/")
    raise ValueError("Use https:// (plain http:// is allowed only for a model on this computer).")


def reachable(url, timeout=8):
    try:
        req = urllib.request.Request(url, method="HEAD")
        with urllib.request.urlopen(req, timeout=timeout, context=ssl.create_default_context()):
            return True
    except urllib.error.HTTPError:
        return True
    except (urllib.error.URLError, OSError, ValueError):
        return False


def _chat(cfg, messages, timeout=30):
    body = json.dumps({"model": cfg["model"], "messages": messages, "temperature": 0, "max_tokens": 20}).encode()
    req = urllib.request.Request(cfg["url"] + "/chat/completions", data=body, headers={
        "Content-Type": "application/json", "Authorization": "Bearer " + cfg["key"]})
    with urllib.request.urlopen(req, timeout=timeout, context=ssl.create_default_context()) as r:
        data = json.load(r)
    content = data["choices"][0]["message"]["content"]
    if not isinstance(content, str):
        raise ValueError("unexpected response")
    return content.strip()


def describe_error(e):
    if isinstance(e, urllib.error.HTTPError):
        if e.code in (401, 403):
            return f"The service rejected the key (HTTP {e.code})."
        if e.code == 404:
            return "Endpoint or model not found (HTTP 404). Check the address ends in /v1 and the model name."
        return f"The service returned HTTP {e.code}."
    if isinstance(e, (urllib.error.URLError, OSError)):
        return "Cannot reach the service. Check the internet connection, proxy and firewall."
    return "The service sent a response AutoFix could not read."


def verify(cfg):
    try:
        reply = _chat(cfg, [{"role": "user", "content": "Reply with the single word OK."}])
    except (urllib.error.URLError, OSError, ValueError, KeyError, IndexError, TypeError) as e:
        return False, describe_error(e)
    return (True, "Verified.") if reply else (False, "The service replied with an empty answer.")


def link_api(home, url, model, key):
    cfg = {"url": validate_url(url), "model": model.strip(), "key": key.strip()}
    if not cfg["model"] or not cfg["key"]:
        raise ValueError("A model name and API key are required.")
    ok, detail = verify(cfg)
    if ok:
        cfg["verified_at"] = datetime.now().isoformat(timespec="seconds")
        save_config(home, cfg)
    return ok, detail


def classify(cfg, request, choices):
    system = ("You route IT support requests. Answer with exactly one word from this list and nothing else: "
              + ", ".join(list(choices) + ["none"]) + ". " + "; ".join(f"{k} = {v}" for k, v in choices.items()))
    try:
        reply = _chat(cfg, [{"role": "system", "content": system}, {"role": "user", "content": request[:500]}])
    except (urllib.error.URLError, OSError, ValueError, KeyError, IndexError, TypeError) as e:
        return None, describe_error(e)
    word = reply.lower().strip(" .`'\"\n")
    return (word, "") if word in choices else (None, "The AI service found no matching fix.")


def serve_mcp(name, version, tools, call, log):
    out = sys.stdout
    sys.stdout = sys.stderr

    def send(msg):
        out.write(json.dumps(msg) + "\n")
        out.flush()

    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            msg = json.loads(line)
        except ValueError:
            send({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
            continue
        if not isinstance(msg, dict) or msg.get("id") is None:
            continue
        mid, method, params = msg["id"], msg.get("method"), msg.get("params") or {}
        if method == "initialize":
            client = params.get("clientInfo") or {}
            log(f"MCP LINKED client={client.get('name', 'unknown')} version={client.get('version', '')}")
            result = {"protocolVersion": params.get("protocolVersion", MCP_PROTOCOL),
                      "capabilities": {"tools": {}}, "serverInfo": {"name": name, "version": version}}
        elif method == "ping":
            result = {}
        elif method == "tools/list":
            result = {"tools": tools}
        elif method == "tools/call":
            buf = io.StringIO()
            try:
                with contextlib.redirect_stdout(buf):
                    text, is_error = call(params.get("name"), params.get("arguments") or {})
            except Exception as e:
                log(f"MCP TOOL ERROR {type(e).__name__}")
                text, is_error = "The tool failed. See the AutoFix log on this computer.", True
            detail = buf.getvalue().strip()
            result = {"content": [{"type": "text", "text": (detail + "\n" + text).strip()}], "isError": is_error}
        else:
            send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "Method not found"}})
            continue
        send({"jsonrpc": "2.0", "id": mid, "result": result})

autofix-setup/autofix_security.py

各操作系统的只读安全检查:防火墙状态、磁盘加密、更新、恶意软件与系统防护、登录设置、监听端口、Wi-Fi 安全、TLS 验证和代理,以及分级报告生成。

253 行 · 源文本,不在此执行
"""Read-only security checks for this computer and its network connection."""
import datetime
import os
import platform
import re
import shutil
import socket
import ssl
import subprocess
import urllib.parse
import urllib.request
from pathlib import Path

SYSTEM = platform.system()
OK, WARN, RISK, UNKNOWN = "OK", "WARN", "RISK", "UNKNOWN"
MAC_FIREWALL = "/usr/libexec/ApplicationFirewall/socketfilterfw"
RISKY_PORTS = {21: "FTP", 23: "Telnet", 445: "Windows file sharing (SMB)", 3389: "Remote Desktop", 5900: "VNC screen sharing",
               3306: "MySQL", 5432: "PostgreSQL", 6379: "Redis", 9200: "Elasticsearch", 27017: "MongoDB", 11434: "Ollama AI server"}


def _out(argv, timeout=30):
    if not (shutil.which(argv[0]) or os.path.exists(argv[0])):
        return None
    try:
        r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired):
        return None
    return r.stdout + r.stderr


def _ps(command):
    out = _out(["powershell", "-NoProfile", "-NonInteractive", "-Command", command], 60)
    return out.strip() if out else ""


def firewall_state():
    if SYSTEM == "Windows":
        states = re.findall(r"\s(ON|OFF)\s*$", _out(["netsh", "advfirewall", "show", "allprofiles", "state"]) or "", re.M)
        if not states:
            return None, "Could not read the Windows Firewall state."
        off = states.count("OFF")
        return off == 0, "Windows Firewall is on for all network profiles." if not off else f"Windows Firewall is off for {off} of {len(states)} network profiles."
    if SYSTEM == "Darwin":
        out = (_out([MAC_FIREWALL, "--getglobalstate"]) or "").lower()
        if "enabled" in out:
            return True, "The macOS firewall is on."
        return (False, "The macOS firewall is off.") if "disabled" in out else (None, "Could not read the macOS firewall state.")
    if shutil.which("firewall-cmd"):
        out = (_out(["firewall-cmd", "--state"]) or "").strip()
        return out == "running", f"firewalld is {out or 'unknown'}."
    if shutil.which("ufw"):
        out = _out(["ufw", "status"]) or ""
        if "Status: active" in out:
            return True, "The ufw firewall is active."
        if "Status: inactive" in out:
            return False, "The ufw firewall is inactive."
        return None, "Run with sudo to read the ufw firewall state."
    return None, "No firewalld or ufw firewall found. Check nftables/iptables rules manually."


def _encryption():
    if SYSTEM == "Windows":
        out = _out(["manage-bde", "-status", os.environ.get("SystemDrive", "C:")]) or ""
        if "Protection On" in out:
            return OK, "BitLocker protects the system drive."
        if "Protection Off" in out:
            return RISK, "BitLocker is off on the system drive. A lost or stolen device exposes its files."
        return UNKNOWN, "Run as administrator to read the BitLocker state."
    if SYSTEM == "Darwin":
        out = _out(["fdesetup", "status"]) or ""
        if "FileVault is On" in out:
            return OK, "FileVault disk encryption is on."
        return (RISK, "FileVault is off. Turn it on in System Settings > Privacy & Security.") if "Off" in out else (UNKNOWN, "Could not read FileVault.")
    out = _out(["lsblk", "-n", "-o", "TYPE"])
    if out is None:
        return UNKNOWN, "lsblk not found."
    return (OK, "An encrypted disk (LUKS) is in use.") if "crypt" in out.split() else (WARN, "No encrypted disk detected. Laptops and portable machines should use full-disk encryption.")


def _updates():
    if SYSTEM == "Windows":
        out = _ps("(Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 1).InstalledOn.ToString('yyyy-MM-dd')")
        try:
            days = (datetime.date.today() - datetime.date.fromisoformat(out[:10])).days
        except ValueError:
            return UNKNOWN, "Could not read the Windows update history."
        return (OK if days <= 45 else WARN), f"Last Windows update installed {days} days ago." + ("" if days <= 45 else " Run Windows Update.")
    if SYSTEM == "Darwin":
        out = _out(["softwareupdate", "-l"], 120)
        if out is None:
            return UNKNOWN, "Could not check Software Update."
        if "No new software available" in out:
            return OK, "macOS is up to date."
        n = len(re.findall(r"^\s*\* ", out, re.M))
        return (WARN, f"{n} macOS update(s) waiting. Install them in System Settings > General > Software Update.") if n else (UNKNOWN, "Could not read the update list.")
    if shutil.which("apt-get"):
        out = _out(["apt-get", "-s", "-o", "Debug::NoLocking=1", "upgrade"], 120) or ""
        pending = [l for l in out.splitlines() if l.startswith("Inst ")]
        security = [l for l in pending if "security" in l.lower()]
        auto = Path("/etc/apt/apt.conf.d/20auto-upgrades")
        auto_on = auto.exists() and 'Unattended-Upgrade "1"' in auto.read_text(errors="ignore")
        note = " Automatic security updates are on." if auto_on else " Automatic security updates are off (install unattended-upgrades)."
        if security:
            return RISK, f"{len(security)} security update(s) and {len(pending) - len(security)} other update(s) waiting.{note}"
        return (WARN if pending or not auto_on else OK), f"{len(pending)} update(s) waiting (based on the last package list refresh).{note}"
    return UNKNOWN, "Package manager not supported for update checks. Check updates manually."


def _accounts():
    found = []
    if SYSTEM == "Windows":
        try:
            import winreg
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System") as k:
                lua = winreg.QueryValueEx(k, "EnableLUA")[0]
            found.append((OK, "User Account Control", "User Account Control is on.") if lua else (RISK, "User Account Control", "User Account Control is off. Programs can change the system without asking."))
        except OSError:
            found.append((UNKNOWN, "User Account Control", "Could not read the User Account Control setting."))
        smb1 = _ps("(Get-SmbServerConfiguration).EnableSMB1Protocol")
        if smb1 in ("True", "False"):
            found.append((RISK, "Old file sharing (SMBv1)", "SMBv1 is on. It is outdated and was used by WannaCry; turn it off.") if smb1 == "True" else (OK, "Old file sharing (SMBv1)", "SMBv1 is off."))
        av = _ps("(Get-MpComputerStatus).RealTimeProtectionEnabled")
        found.append((OK, "Malware protection", "Microsoft Defender real-time protection is on.") if av == "True" else
                     (RISK, "Malware protection", "Microsoft Defender real-time protection is off.") if av == "False" else
                     (UNKNOWN, "Malware protection", "Microsoft Defender status unavailable. If you use other antivirus software, check it is active."))
    elif SYSTEM == "Darwin":
        gk = _out(["spctl", "--status"]) or ""
        found.append((OK, "Gatekeeper", "Gatekeeper only allows trusted apps.") if "enabled" in gk else (RISK, "Gatekeeper", "Gatekeeper is off. Apps from anywhere can run."))
        sip = _out(["csrutil", "status"]) or ""
        found.append((OK, "System Integrity Protection", "System Integrity Protection is on.") if "enabled" in sip else (RISK, "System Integrity Protection", "System Integrity Protection is off or unknown."))
        auto = _out(["defaults", "read", "/Library/Preferences/com.apple.loginwindow", "autoLoginUser"])
        if auto and "does not exist" not in auto:
            found.append((WARN, "Automatic login", "Automatic login is on. Anyone who opens the Mac gets in without a password."))
    else:
        configs = [Path("/etc/ssh/sshd_config"), *sorted(Path("/etc/ssh/sshd_config.d").glob("*.conf"))] if Path("/etc/ssh").is_dir() else []
        text = "\n".join(p.read_text(errors="ignore") for p in configs if p.is_file() and os.access(p, os.R_OK))
        if text:
            settings = dict(re.findall(r"^\s*(PermitRootLogin|PasswordAuthentication)\s+(\S+)", text, re.M | re.I))
            root = settings.get("PermitRootLogin", "")
            found.append((RISK, "SSH root login", "SSH allows direct root login with a password. Set PermitRootLogin to no.") if root.lower() == "yes" else (OK, "SSH root login", "SSH does not allow root password login."))
            if settings.get("PasswordAuthentication", "").lower() == "yes":
                found.append((WARN, "SSH passwords", "SSH accepts passwords. Keys are safer, especially on internet-facing servers."))
        shadow = Path("/etc/shadow")
        if shadow.exists():
            found.append((RISK, "Password file", "/etc/shadow is readable by every user.") if shadow.stat().st_mode & 0o004 else (OK, "Password file", "/etc/shadow is protected."))
    return found


def listening_ports():
    if SYSTEM == "Linux" and shutil.which("ss"):
        out, idx = _out(["ss", "-H", "-tuln"]), 4
    else:
        out, idx = _out(["netstat", "-an"]), 1 if SYSTEM == "Windows" else 3
    if out is None:
        return None
    ports = set()
    for line in out.splitlines():
        parts = line.split()
        if len(parts) <= idx or (idx != 4 and "LISTEN" not in line):
            continue
        m = re.match(r"^(.*)[.:](\d+)$", parts[idx])
        if m and m.group(1).strip("[]") in ("0.0.0.0", "*", "::", ""):
            ports.add(int(m.group(2)))
    return ports


def _ports():
    ports = listening_ports()
    if ports is None:
        return UNKNOWN, "Could not list open ports."
    risky = sorted(p for p in ports if p in RISKY_PORTS)
    if risky:
        names = ", ".join(f"{p} {RISKY_PORTS[p]}" for p in risky)
        return WARN, f"Open to the whole network: {names}. Close them or limit them with the firewall unless they are needed."
    return OK, f"{len(ports)} port(s) open to the network; none of the commonly attacked services found."


def _wifi():
    if SYSTEM == "Windows":
        out = _out(["netsh", "wlan", "show", "interfaces"]) or ""
        auth = re.search(r"^\s*Authentication\s*:\s*(.+)$", out, re.M)
        if not auth:
            return None
        return (RISK, "This computer is on an open Wi-Fi network with no password. Others nearby can see unencrypted traffic.") if auth.group(1).strip().lower() == "open" else (OK, f"Wi-Fi security: {auth.group(1).strip()}.")
    if SYSTEM == "Linux" and shutil.which("nmcli"):
        for line in (_out(["nmcli", "-t", "-f", "ACTIVE,SECURITY", "dev", "wifi"]) or "").splitlines():
            if line.startswith("yes:"):
                sec = line[4:].strip()
                return (OK, f"Wi-Fi security: {sec}.") if sec and sec != "--" else (RISK, "This computer is on an open Wi-Fi network with no password.")
    return None


def _https(host="www.microsoft.com"):
    ctx = ssl.create_default_context()
    try:
        with socket.create_connection((host, 443), timeout=8) as raw, ctx.wrap_socket(raw, server_hostname=host) as tls:
            cert = tls.getpeercert()
    except ssl.SSLCertVerificationError:
        return RISK, "A secure website's certificate could not be verified. The clock may be wrong, or traffic may be intercepted."
    except OSError:
        return UNKNOWN, "Could not reach a secure website directly (offline, or a proxy is required)."
    issuer = dict(x[0] for x in cert.get("issuer", ())).get("organizationName", "unknown")
    return OK, f"Secure connections verify correctly (certificate issued by {issuer})."


def _proxy():
    proxy = urllib.request.getproxies().get("https")
    if not proxy:
        return OK, "No proxy; this computer connects directly."
    parts = urllib.parse.urlsplit(proxy if "://" in proxy else f"http://{proxy}")
    return OK, f"Connections go through the proxy {parts.hostname}:{parts.port or ''}."


def run_checks(progress=print):
    findings = []

    def add(status, area, title, detail):
        findings.append((status, area, title, detail))
        progress(f"  [{status:7}] {title}: {detail}")

    fw_ok, fw_detail = firewall_state()
    add(OK if fw_ok else RISK if fw_ok is False else UNKNOWN, "System", "Firewall", fw_detail)
    add(*_with("System", "Disk encryption", _encryption()))
    add(*_with("System", "Updates", _updates()))
    for status, title, detail in _accounts():
        add(status, "System", title, detail)
    add(*_with("Network", "Open ports", _ports()))
    wifi = _wifi()
    if wifi:
        add(*_with("Network", "Wi-Fi", wifi))
    add(*_with("Network", "Secure connections", _https()))
    add(*_with("Network", "Proxy", _proxy()))
    return findings


def _with(area, title, result):
    return result[0], area, title, result[1]


def summary(findings):
    counts = {s: sum(f[0] == s for f in findings) for s in (RISK, WARN, OK, UNKNOWN)}
    return f"{counts[RISK]} risk(s), {counts[WARN]} warning(s), {counts[OK]} passed, {counts[UNKNOWN]} could not be checked"


def write_report(home, findings, header):
    home.mkdir(parents=True, exist_ok=True)
    path = home / f"security-report-{datetime.datetime.now():%Y%m%d-%H%M%S}.txt"
    lines = [header, summary(findings), ""]
    order = {RISK: 0, WARN: 1, UNKNOWN: 2, OK: 3}
    lines += [f"[{s}] {area} · {title}: {detail}" for s, area, title, detail in sorted(findings, key=lambda f: order[f[0]])]
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return path

autofix-setup/autofix.py

主工具:自动安装、全面检查流程、关键词匹配、六种诊断与修复方案、管理员和远程会话检查、YES 确认、无 shell 命令执行、复查、本地日志、云端连接选项和 MCP 工具处理。

544 行 · 源文本,不在此执行
#!/usr/bin/env python3
"""Xialei AutoFix (beta): describe an issue, review the diagnosis and fix, approve with YES."""
import argparse
import ctypes
import datetime
import getpass
import os
import platform
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.parse
import urllib.request
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import autofix_cloud as cloud  # noqa: E402
import autofix_security as security  # noqa: E402

VERSION = "0.3.0-beta"
KIT_FILES = ["autofix.py", "autofix_cloud.py", "autofix_security.py", "README.txt"]
SYSTEM = platform.system()
HOME = Path(os.environ.get("AUTOFIX_HOME") or Path.home() / ".xialei-autofix")
LOG = HOME / "autofix-log.txt"
TEMP_AGE_DAYS = 7
PROBES = [("www.microsoft.com", 443), ("www.apple.com", 443), ("1.1.1.1", 443)]


def is_admin():
    try:
        return bool(ctypes.windll.shell32.IsUserAnAdmin()) if SYSTEM == "Windows" else os.geteuid() == 0
    except Exception:
        return False


def remote_session():
    if os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_CLIENT"):
        return "SSH"
    if SYSTEM == "Windows" and os.environ.get("SESSIONNAME", "").upper().startswith("RDP"):
        return "Remote Desktop"
    return None


def log(line):
    try:
        HOME.mkdir(parents=True, exist_ok=True)
        with LOG.open("a", encoding="utf-8") as f:
            f.write(f"{datetime.datetime.now().isoformat(timespec='seconds')}  {line}\n")
    except OSError:
        pass


def have(cmd):
    return shutil.which(cmd) is not None


def run(argv):
    print("  $ " + " ".join(argv))
    try:
        r = subprocess.run(argv, capture_output=True, text=True, timeout=120)
    except (OSError, subprocess.TimeoutExpired) as e:
        log(f"RUN {argv} FAILED {type(e).__name__}")
        print(f"    failed: {e}")
        return False
    out = (r.stdout + r.stderr).strip()
    if out:
        print("    " + out[-800:].replace("\n", "\n    "))
    log(f"RUN {argv} EXIT {r.returncode}")
    return r.returncode == 0


def can_resolve(host="example.com"):
    try:
        socket.getaddrinfo(host, 443)
        return True
    except OSError:
        return False


def can_connect(host, port):
    try:
        with socket.create_connection((host, port), timeout=5):
            return True
    except OSError:
        return False


def mac_interface():
    try:
        out = subprocess.run(["route", "-n", "get", "default"], capture_output=True, text=True, timeout=10).stdout
    except (OSError, subprocess.TimeoutExpired):
        return None
    m = re.search(r"interface:\s*(\S+)", out)
    return m.group(1) if m else None


def old_temp_files():
    root = Path(tempfile.gettempdir())
    cutoff = time.time() - TEMP_AGE_DAYS * 86400
    found = []
    for p in root.rglob("*"):
        try:
            if p.is_file() and not p.is_symlink() and p.stat().st_mtime < cutoff:
                found.append(p)
        except OSError:
            continue
    return found


def diag_dns():
    ok = can_resolve()
    return ok, "Name lookup works." if ok else "Name lookup for example.com failed."


def diag_network():
    probes = list(PROBES)
    cfg = cloud.load_config(HOME)
    if cfg.get("url"):
        parts = urllib.parse.urlsplit(cfg["url"])
        probes.insert(0, (parts.hostname, parts.port or (443 if parts.scheme == "https" else 80)))
    direct = any(can_connect(h, p) for h, p in probes)
    msg = "Direct connection to the internet works." if direct else "Direct connection to the internet failed."
    proxy = urllib.request.getproxies().get("https")
    if proxy:
        via = cloud.reachable("https://www.microsoft.com")
        msg += f" Proxy {cloud.safe_proxy(proxy)}: {'works' if via else 'failed'}."
        return direct or via, msg
    return direct, msg


def diag_disk():
    u = shutil.disk_usage(Path.home())
    free = u.free / u.total * 100
    files = old_temp_files()
    size = 0
    for f in files:
        try:
            size += f.stat().st_size
        except OSError:
            continue
    return free > 10, f"{free:.1f}% free on the home drive. {len(files)} temp files older than {TEMP_AGE_DAYS} days ({size / 1e6:.1f} MB)."


def diag_time():
    return None, f"Local time: {datetime.datetime.now().astimezone():%Y-%m-%d %H:%M:%S %Z}. Compare it with a trusted clock."


def diag_print():
    if SYSTEM == "Windows":
        return None, "The Windows print spooler will be restarted."
    if not have("lpstat"):
        return True, "No CUPS printing system found."
    r = subprocess.run(["lpstat", "-o"], capture_output=True, text=True)
    jobs = [l for l in r.stdout.splitlines() if l.strip()]
    return not jobs, f"{len(jobs)} queued print job(s)."


def fix_dns():
    if SYSTEM == "Windows":
        return run(["ipconfig", "/flushdns"])
    if SYSTEM == "Darwin":
        return run(["dscacheutil", "-flushcache"]) and run(["killall", "-HUP", "mDNSResponder"])
    for argv in (["resolvectl", "flush-caches"], ["systemd-resolve", "--flush-caches"]):
        if have(argv[0]):
            return run(argv)
    print("  No supported DNS cache service found on this Linux system (nothing to flush).")
    return False


def fix_network():
    if SYSTEM == "Windows":
        ok = run(["ipconfig", "/release"])
        ok = run(["ipconfig", "/renew"]) and ok
        return run(["ipconfig", "/flushdns"]) and ok
    if SYSTEM == "Darwin":
        iface = mac_interface() or "en0"
        return run(["ipconfig", "set", iface, "DHCP"])
    if have("nmcli"):
        run(["nmcli", "networking", "off"])
        return run(["nmcli", "networking", "on"])
    print("  NetworkManager (nmcli) not found. Restart your distribution's network service from the console.")
    return False


def fix_disk():
    removed = 0
    for f in old_temp_files():
        try:
            f.unlink()
            removed += 1
        except OSError:
            continue
    log(f"DISK removed {removed} temp files")
    print(f"  Removed {removed} old temp files (files in use were skipped).")
    return True


def fix_time():
    if SYSTEM == "Windows":
        if run(["w32tm", "/resync"]):
            return True
        run(["net", "start", "w32time"])
        return run(["w32tm", "/resync"])
    if SYSTEM == "Darwin":
        return run(["sntp", "-sS", "time.apple.com"])
    if have("timedatectl"):
        return run(["timedatectl", "set-ntp", "true"])
    print("  timedatectl not found. Enable your distribution's time sync service.")
    return False


def fix_firewall():
    if SYSTEM == "Windows":
        return run(["netsh", "advfirewall", "set", "allprofiles", "state", "on"])
    if SYSTEM == "Darwin":
        return run([security.MAC_FIREWALL, "--setglobalstate", "on"])
    if have("firewall-cmd"):
        return run(["systemctl", "enable", "--now", "firewalld"])
    if have("ufw"):
        return run(["ufw", "--force", "enable"])
    print("  No firewalld or ufw found. Install one with your package manager, then run AutoFix again.")
    return False


def fix_print():
    if SYSTEM == "Windows":
        return run(["net", "stop", "spooler"]) and run(["net", "start", "spooler"])
    return run(["cancel", "-a"])


RECIPES = {
    "dns": dict(title="Websites will not load / DNS errors", words=["dns", "website", "site", "resolve", "domain", "域名", "网站", "解析"],
                diagnose=diag_dns, fix=fix_dns, admin={"Windows": False, "Darwin": True, "Linux": True}, cuts_remote=False,
                plan={"Windows": "ipconfig /flushdns", "Darwin": "dscacheutil -flushcache; killall -HUP mDNSResponder", "Linux": "resolvectl flush-caches"}),
    "network": dict(title="No internet / cloud connection", words=["internet", "network", "offline", "wifi", "connection", "cloud", "网络", "断网", "连接", "云"],
                    diagnose=diag_network, fix=fix_network, admin={"Windows": True, "Darwin": True, "Linux": False}, cuts_remote=True,
                    plan={"Windows": "ipconfig /release; ipconfig /renew; ipconfig /flushdns", "Darwin": "ipconfig set <active interface> DHCP", "Linux": "nmcli networking off; nmcli networking on"}),
    "disk": dict(title="Disk is full / low storage", words=["disk", "storage", "space", "full", "temp", "磁盘", "空间", "存储"],
                 diagnose=diag_disk, fix=fix_disk, admin={"Windows": False, "Darwin": False, "Linux": False}, cuts_remote=False,
                 plan={"Windows": f"delete your temp files older than {TEMP_AGE_DAYS} days", "Linux": f"delete your temp files older than {TEMP_AGE_DAYS} days"}),
    "time": dict(title="Clock is wrong / certificate errors", words=["time", "clock", "date", "certificate", "ssl", "时间", "时钟", "证书"],
                 diagnose=diag_time, fix=fix_time, admin={"Windows": True, "Darwin": True, "Linux": True}, cuts_remote=False,
                 plan={"Windows": "w32tm /resync (starts the time service if needed)", "Darwin": "sntp -sS time.apple.com", "Linux": "timedatectl set-ntp true"}),
    "print": dict(title="Printer queue is stuck", words=["print", "printer", "spooler", "queue", "打印", "打印机"],
                  diagnose=diag_print, fix=fix_print, admin={"Windows": True, "Darwin": False, "Linux": False}, cuts_remote=False,
                  plan={"Windows": "net stop spooler; net start spooler", "Linux": "cancel -a (your queued jobs)"}),
    "firewall": dict(title="Firewall is off", words=["firewall", "security", "secure", "hack", "防火墙", "安全"],
                     diagnose=security.firewall_state, fix=fix_firewall, admin={"Windows": True, "Darwin": True, "Linux": True}, cuts_remote=True,
                     plan={"Windows": "netsh advfirewall set allprofiles state on", "Darwin": "socketfilterfw --setglobalstate on",
                           "Linux": "systemctl enable --now firewalld, or ufw --force enable (blocks incoming connections you have not allowed)"}),
}


def plan_text(r):
    return r["plan"].get(SYSTEM, r["plan"].get("Linux"))


def blocker(r):
    if r["admin"].get(SYSTEM) and not is_admin():
        hint = "Run the launcher as Administrator" if SYSTEM == "Windows" else "Run again with sudo"
        return f"This fix needs administrator rights. {hint}. Nothing changed."
    session = remote_session()
    if r["cuts_remote"] and session:
        return f"This fix can interrupt remote connections and would cut off your {session} session. Run it at the machine's console. Nothing changed."
    return None


def match(request):
    text = request.lower()
    scores = {k: sum(w in text for w in r["words"]) for k, r in RECIPES.items()}
    best = max(scores, key=scores.get)
    return best if scores[best] else None


def resolve_request(request, offline):
    key = match(request)
    if key or offline:
        return key
    cfg = cloud.load_config(HOME)
    if not cfg.get("verified_at"):
        return None
    host = urllib.parse.urlsplit(cfg["url"]).hostname
    print(f"No keyword match. Asking your linked AI service ({host}); only your description is sent.")
    key, note = cloud.classify(cfg, request, {k: r["title"] for k, r in RECIPES.items()})
    log(f"AI MATCH host={host} -> {key}")
    if note:
        print(note)
    return key


def apply_fix(key):
    r = RECIPES[key]
    log(f"APPLY {key}")
    r["fix"]()
    ok, detail = r["diagnose"]()
    log(f"RECHECK {key}: {detail}")
    return ok, detail


def handle(key, dry_run):
    r = RECIPES[key]
    print(f"\n== {r['title']} ==")
    ok, detail = r["diagnose"]()
    print(f"Diagnosis: {detail}")
    log(f"DIAGNOSE {key}: {detail}")
    if ok is True:
        print("No problem detected. Nothing changed.")
        return
    print(f"Proposed fix: {plan_text(r)}")
    reason = blocker(r)
    if reason:
        print(reason)
        return
    if dry_run:
        print("Dry run: nothing changed.")
        return
    if input("Apply this fix? Type YES: ").strip() != "YES":
        print("Cancelled. Nothing changed.")
        log(f"CANCELLED {key}")
        return
    _, detail = apply_fix(key)
    print(f"Re-check: {detail}")


def install():
    here = Path(__file__).resolve().parent
    target = HOME / "app"
    if os.environ.get("SUDO_USER"):
        print("Install skipped while running with sudo. Run the launcher once without sudo to install.")
        return
    if here == target:
        return
    target.mkdir(parents=True, exist_ok=True)
    for name in KIT_FILES:
        shutil.copy2(here / name, target / name)
    script = target / "autofix.py"
    if SYSTEM == "Windows":
        bindir = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "Microsoft" / "WindowsApps"
        shim = bindir / "autofix.cmd"
        text = f'@echo off\r\nwhere py >nul 2>nul\r\nif %errorlevel%==0 (py -3 "{script}" %*) else (python "{script}" %*)\r\n'
    else:
        bindir = Path.home() / ".local" / "bin"
        shim = bindir / "autofix"
        text = f'#!/bin/sh\nexec python3 "{script}" "$@"\n'
    try:
        bindir.mkdir(parents=True, exist_ok=True)
        shim.write_text(text, encoding="utf-8")
        shim.chmod(0o755)
    except OSError as e:
        print(f"Installed to {target}, but the 'autofix' command could not be created ({e.strerror}).")
        log("INSTALL partial")
        return
    on_path = str(bindir) in os.environ.get("PATH", "").split(os.pathsep)
    print(f"Installed {VERSION} to {target}. Type 'autofix' in a terminal to run it" + ("." if on_path else f" (add {bindir} to PATH first)."))
    log(f"INSTALL {VERSION} -> {target}")


def security_check(progress=print):
    progress("Checking this computer's security and network connection (read-only)...")
    findings = security.run_checks(progress)
    path = security.write_report(HOME, findings, f"Xialei AutoFix {VERSION} security report · {SYSTEM} · {socket.gethostname()} · {datetime.datetime.now():%Y-%m-%d %H:%M}")
    log(f"SECURITY CHECK {security.summary(findings)} -> {path.name}")
    return findings, path


def full_check(dry_run):
    print("\n== Full check ==")
    findings, path = security_check()
    print(f"\nSecurity: {security.summary(findings)}. Report saved to {path}")
    print("\nChecking common problems...")
    todo = []
    for key in ("dns", "network", "disk", "firewall"):
        ok, detail = RECIPES[key]["diagnose"]()
        print(f"  [{'OK' if ok else 'PROBLEM' if ok is False else 'UNKNOWN':7}] {RECIPES[key]['title']}: {detail}")
        if ok is False:
            todo.append(key)
    if not todo:
        print("No fixable problems found. Review any RISK or WARN lines above; they include advice.")
    for key in todo:
        handle(key, dry_run)


MCP_TOOLS = [
    {"name": "list_issues", "description": "List the issues AutoFix can diagnose and fix on this computer.",
     "inputSchema": {"type": "object", "properties": {}}},
    {"name": "match_request", "description": "Match a plain-language problem description to an AutoFix issue id.",
     "inputSchema": {"type": "object", "properties": {"request": {"type": "string"}}, "required": ["request"]}},
    {"name": "diagnose", "description": "Run the read-only diagnosis for an issue. Changes nothing.",
     "inputSchema": {"type": "object", "properties": {"issue": {"type": "string", "enum": list(RECIPES)}}, "required": ["issue"]}},
    {"name": "security_check", "description": "Run a read-only security check of this computer and its network connection (firewall, disk encryption, updates, malware protection, accounts, open ports, Wi-Fi, secure connections). Changes nothing.",
     "inputSchema": {"type": "object", "properties": {}}},
    {"name": "apply_fix", "description": "Apply the fixed, reviewed fix for an issue and re-check. Only works if the administrator started AutoFix with --allow-fixes.",
     "inputSchema": {"type": "object", "properties": {"issue": {"type": "string", "enum": list(RECIPES)}}, "required": ["issue"]}},
]


def mcp_call(allow_fixes):
    def call(name, args):
        if name == "list_issues":
            return "\n".join(f"{k}: {r['title']} (fix: {plan_text(r)})" for k, r in RECIPES.items()), False
        if name == "match_request":
            key = match(str(args.get("request", "")))
            log(f"MCP MATCH -> {key}")
            return (key or "none"), False
        if name == "security_check":
            findings, path = security_check(lambda line: None)
            lines = [f"[{s}] {area} · {title}: {detail}" for s, area, title, detail in findings]
            return f"{security.summary(findings)}. Report: {path}\n" + "\n".join(lines), False
        key = args.get("issue")
        if key not in RECIPES:
            return "Unknown issue. Call list_issues first.", True
        r = RECIPES[key]
        if name == "diagnose":
            ok, detail = r["diagnose"]()
            log(f"MCP DIAGNOSE {key}: {detail}")
            state = "no problem detected" if ok is True else "problem found" if ok is False else "cannot confirm automatically"
            return f"{detail} ({state}). Proposed fix: {plan_text(r)}", False
        if name == "apply_fix":
            if not allow_fixes:
                return "Fixes are disabled. The administrator must restart AutoFix with --mcp --allow-fixes on this computer.", True
            reason = blocker(r)
            if reason:
                return reason, True
            ok, detail = r["diagnose"]()
            if ok is True:
                return f"{detail} No problem detected. Nothing changed.", False
            ok, detail = apply_fix(key)
            return f"Re-check: {detail}", ok is False
        return "Unknown tool.", True
    return call


def link(url, model):
    key = os.environ.get("AUTOFIX_API_KEY") or getpass.getpass("API key (hidden): ")
    try:
        ok, detail = cloud.link_api(HOME, url, model, key)
    except ValueError as e:
        ok, detail = False, str(e)
    log(f"LINK API {'verified' if ok else 'failed'}")
    print(f"{'Linked and verified' if ok else 'Not linked'}: {detail}")
    return ok


def status():
    cfg = cloud.load_config(HOME)
    if not cfg.get("url"):
        print("Cloud AI: not linked (keyword matching only).")
        return
    print(f"Cloud AI: {cfg['url']} · model {cfg['model']} · verified {cfg.get('verified_at', 'never')}")
    proxy = urllib.request.getproxies().get("https")
    print(f"Proxy: {cloud.safe_proxy(proxy) if proxy else 'none'}")


def main():
    p = argparse.ArgumentParser(description=f"Xialei AutoFix {VERSION}")
    p.add_argument("request", nargs="*", help='describe the issue, e.g. "websites will not load"')
    p.add_argument("--issue", choices=RECIPES, help="choose an issue directly")
    p.add_argument("--dry-run", action="store_true", help="diagnose and show the fix without changing anything")
    p.add_argument("--list", action="store_true", help="list supported issues")
    p.add_argument("--auto", action="store_true", help="install, then check security, network and common problems (default with no arguments)")
    p.add_argument("--install", action="store_true", help="install AutoFix in your user folder and add the 'autofix' command")
    p.add_argument("--security-check", action="store_true", help="read-only security check of this computer and network")
    p.add_argument("--offline", action="store_true", help="never contact the linked AI service")
    p.add_argument("--link-api", metavar="URL", help="link an OpenAI-compatible API, e.g. https://api.openai.com/v1")
    p.add_argument("--model", help="model name used with --link-api")
    p.add_argument("--verify", action="store_true", help="re-test the linked API")
    p.add_argument("--unlink", action="store_true", help="remove the linked API and its key from this computer")
    p.add_argument("--status", action="store_true", help="show cloud link and proxy status")
    p.add_argument("--mcp", action="store_true", help="run as an MCP server for an AI client (stdio)")
    p.add_argument("--allow-fixes", action="store_true", help="with --mcp: let the AI client apply fixes")
    auto = len(sys.argv) == 1
    a = p.parse_args()

    if a.mcp:
        log(f"MCP START allow_fixes={a.allow_fixes}")
        cloud.serve_mcp("xialei-autofix", VERSION, MCP_TOOLS, mcp_call(a.allow_fixes), log)
        return
    print(f"Xialei AutoFix {VERSION} · {SYSTEM} · log: {LOG}")
    if a.link_api:
        if not a.model:
            p.error("--link-api needs --model")
        sys.exit(0 if link(a.link_api, a.model) else 1)
    if a.unlink:
        cloud.unlink(HOME)
        log("UNLINK API")
        print("Linked API and key removed from this computer.")
        return
    if a.verify:
        cfg = cloud.load_config(HOME)
        if not cfg.get("url"):
            print("No API linked. Use --link-api URL --model NAME.")
            sys.exit(1)
        ok, detail = cloud.verify(cfg)
        if ok:
            cfg["verified_at"] = datetime.datetime.now().isoformat(timespec="seconds")
            cloud.save_config(HOME, cfg)
        log(f"VERIFY API {'ok' if ok else 'failed'}")
        print(detail)
        sys.exit(0 if ok else 1)
    if a.status:
        status()
        return
    if a.list:
        for k, r in RECIPES.items():
            print(f"  {k:8} {r['title']}")
        return
    if a.install:
        install()
        return
    if a.security_check:
        findings, path = security_check()
        print(f"\n{security.summary(findings)}. Report saved to {path}")
        return
    if a.auto or auto:
        install()
        full_check(a.dry_run)
        request = input("\nDescribe another issue, or press Enter to finish: ").strip()
        if not request:
            return
        a.request = [request]
    key = a.issue
    if not key:
        request = " ".join(a.request) or input("Describe the issue (e.g. 'printer stuck', 'disk full'): ")
        key = resolve_request(request, a.offline)
        log(f"REQUEST -> {key}")
    if not key:
        print("No matching fix. Supported issues:")
        for k, r in RECIPES.items():
            print(f"  {k:8} {r['title']}")
        return
    handle(key, a.dry_run)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nCancelled.")
        sys.exit(130)

autofix-setup/README.txt

随工具包分发的完整安装、使用、隐私及故障排查说明。

85 行 · 源文本,不在此执行
Xialei AutoFix 0.3 — public beta (released 1 December 2026)

For system administrators on Windows (including domain/office networks), macOS and Linux. Describe an issue in plain words ("websites will not load", "printer stuck", "disk full"). AutoFix matches it to a known fix, runs a read-only diagnosis, shows the exact command it would run, and changes nothing until you type YES. After a fix it re-checks the problem. Each step is logged.

SUPPORTED ISSUES
  dns      Websites will not load / DNS errors   flush DNS cache
  network  No internet / cloud connection        Windows: release/renew IP + flush DNS · macOS: renew DHCP on the active interface · Linux: restart NetworkManager networking
  disk     Disk is full / low storage            delete YOUR temp files older than 7 days
  time     Clock is wrong / certificate errors   resync system time
  print    Printer queue is stuck                Windows: restart spooler · macOS/Linux: cancel your queued jobs
  firewall Firewall is off                       turn the firewall on (Linux: firewalld or ufw)

AUTOMATIC INSTALL AND FULL CHECK
When you open a launcher (or run autofix.py with no options), AutoFix:
  1. installs itself to .xialei-autofix/app in your user folder and adds an "autofix" command
     (Windows: %LOCALAPPDATA%\Microsoft\WindowsApps\autofix.cmd · macOS/Linux: ~/.local/bin/autofix)
  2. runs a read-only security check of this computer and its network connection:
     firewall, disk encryption (BitLocker/FileVault/LUKS), system updates, malware protection (Windows),
     User Account Control and old SMBv1 sharing (Windows), Gatekeeper, System Integrity Protection and
     automatic login (Mac), SSH root/password login and password-file protection (Linux),
     ports open to the whole network, open Wi-Fi, secure-connection certificates and proxy
  3. checks DNS, internet connection, disk space and firewall, and offers a fix for each problem (YES each time)
The security report is saved as .xialei-autofix/security-report-<date>.txt. Other findings include advice; AutoFix does not change them.
It checks THIS computer and its connection only. It does not scan other devices on your network.
Run as administrator / with sudo for the most complete results. Installing is skipped under sudo.
  --security-check           security check only
  --install                  install only

REQUIREMENTS
Python 3.8 or newer. No extra packages. Keep the three .py files together.

WINDOWS (including office networks)
Double-click "Start AutoFix.bat". It also works when the kit sits on a network share (\\server\share). For network, time and printer fixes, right-click the .bat and choose "Run as administrator". Corporate proxy settings and the Windows certificate store are used automatically.

MAC
Open "Start AutoFix.command". DNS, network and time fixes need administrator rights: in Terminal run  sudo python3 autofix.py

LINUX
Run  sh start-autofix.sh  (add sudo for DNS and time fixes). The network fix needs NetworkManager (nmcli). Proxy settings come from the https_proxy variable.

REMOTE SAFETY
The network and firewall fixes can interrupt remote connections. AutoFix refuses them inside SSH or Remote Desktop sessions so you do not lock yourself out. Run it at the console.

LINK A CLOUD AI SERVICE (optional)
When a description does not match any keyword, a linked AI service can choose the right fix. It can only pick one of the six fixes above; it never supplies commands. The link is tested before it is saved.
  python3 autofix.py --link-api https://api.openai.com/v1 --model gpt-4o-mini
  (the key is typed hidden, or read from the AUTOFIX_API_KEY variable; any OpenAI-compatible service works, including a local Ollama at http://127.0.0.1:11434/v1)
  python3 autofix.py --status      show the link and proxy
  python3 autofix.py --verify      test the link again
  python3 autofix.py --unlink      remove the link and key
  --offline                        never contact the AI service
Only the description is sent, and only when keywords do not match. The key is stored unencrypted in your user folder (.xialei-autofix/config.json, readable only by you on macOS/Linux). Use a restricted key.

CONNECT AN AI ASSISTANT WITH MCP (optional)
AutoFix can act as an MCP server so an MCP-capable AI assistant (for example Claude Desktop or an IDE agent) can list issues, match requests, run diagnoses and the security check and, if you allow it, apply fixes. Add this to the assistant's MCP configuration:
  { "mcpServers": { "xialei-autofix": { "command": "python3", "args": ["/full/path/to/autofix.py", "--mcp"] } } }
  On Windows use "py" as the command and a path such as "C:\\Tools\\autofix-setup\\autofix.py".
Diagnosis only by default. To let the assistant apply fixes, add "--allow-fixes" to args. Administrator and remote-session checks still apply. The link is recorded in the log when the assistant connects.

USEFUL OPTIONS
  --list                     list supported issues
  --dry-run "disk full"      diagnose only, change nothing
  --issue dns                skip the description step

LOG
.xialei-autofix/autofix-log.txt in your user folder. It records matched issues, diagnoses, commands, exit codes and cloud links (never your key). Nothing is uploaded.

SAFETY
- AutoFix never elevates itself.
- Commands are fixed in the script. Your description, AI replies and MCP requests only choose an issue; they are never executed.
- Review the .py files before running them on machines you administer. Test on one machine first.

LIMITS
Beta. Tested on Linux, including the install, the security check (with simulated firewall and port tools), the cloud link with a stand-in service and an MCP session. The Windows and Mac security checks are written for those systems but have not been run on them. Not yet verified on real Windows or macOS machines, with a real cloud AI provider or with a specific AI assistant. It fixes common causes only; if the re-check still fails, investigate further. Not a background or monitoring service.

中文说明
适用于 Windows(包括公司域网络)、macOS 和 Linux 的系统管理员。用简单的话描述问题,AutoFix 先只读诊断,显示准确命令,输入 YES 后才执行,并在修复后复查。
Windows:双击 "Start AutoFix.bat",可从网络共享目录运行;网络、时间和打印修复需“以管理员身份运行”。自动使用公司代理和 Windows 证书库。
Mac:打开 "Start AutoFix.command";DNS、网络和时间修复需 sudo。Linux:运行 sh start-autofix.sh;网络修复需要 NetworkManager。
自动安装与全面检查:打开启动器后,AutoFix 会自动安装到用户目录并添加 autofix 命令,然后只读检查本机安全和网络连接(防火墙、磁盘加密、系统更新、恶意软件防护、账户设置、对外开放的端口、开放 Wi-Fi、安全连接证书和代理),并检查 DNS、网络、磁盘和防火墙问题,每项修复都需输入 YES。报告保存为 .xialei-autofix/security-report-日期.txt。只检查本机,不扫描网络中的其他设备。
远程安全:在 SSH 或远程桌面会话中会拒绝网络和防火墙修复,避免断开连接。
连接云端 AI(可选):python3 autofix.py --link-api 地址 --model 模型名。保存前会先测试连接。AI 只能从六种修复中选择,不能提供命令。--offline 可完全离线。
MCP(可选):在 AI 助手的 MCP 配置中添加 autofix.py --mcp。默认只诊断;加上 --allow-fixes 才允许 AI 助手执行修复,管理员权限和远程会话检查仍然有效。
日志保存在用户目录 .xialei-autofix/autofix-log.txt,不记录密钥,不上传数据。测试版,请先在一台电脑上试用。

autofix-setup/Start AutoFix.bat

Windows 入口:使用 Python 启动器运行相邻 Python 脚本,并保留窗口显示消息。

8 行 · 源文本,不在此执行
@echo off
rem pushd maps a temporary drive letter when the kit is opened from a network share (\\server\share)
pushd "%~dp0"
where py >nul 2>nul
if %errorlevel%==0 (py -3 autofix.py %*) else (python autofix.py %*)
popd
pause

autofix-setup/Start AutoFix.command

macOS/Linux 入口:定位自身目录并启动相邻 Python 脚本。请保留完整工具包文件。

6 行 · 源文本,不在此执行
#!/bin/sh
base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 1
python3 "$base/autofix.py"
printf '\nPress Enter to close. '
read -r answer

autofix-setup/start-autofix.sh

macOS/Linux 入口:定位自身目录并启动相邻 Python 脚本。请保留完整工具包文件。

4 行 · 源文本,不在此执行
#!/bin/sh
base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 1
exec python3 "$base/autofix.py" "$@"

src/pages/autofix-setup.astro

网站设置和下载页面:双语说明、要求及链接。此 Astro 文件用于网站,而非本地安装目录。

75 行 · 源文本,不在此执行
---
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 zh = language === 'zh';
const copy = (en: string, cn: string) => zh ? cn : en;
const issues = [
  ['dns', copy('Websites will not load', '网站打不开'), copy('Flushes the DNS cache, then checks name lookup again.', '清除 DNS 缓存,然后再次检查域名解析。')],
  ['network', copy('No internet / cloud connection', '无法连接网络 / 云端'), copy('Checks direct and proxy connections. Windows renews the IP address, macOS renews DHCP, Linux restarts NetworkManager. Refused inside SSH or Remote Desktop.', '检查直连和代理连接。Windows 续订 IP,macOS 续订 DHCP,Linux 重启 NetworkManager。在 SSH 或远程桌面会话中会拒绝执行。')],
  ['disk', copy('Disk is full', '磁盘已满'), copy('Removes your own temporary files older than seven days. Files in use are skipped.', '删除您自己超过七天的临时文件。正在使用的文件会被跳过。')],
  ['time', copy('Clock wrong / certificate errors', '时间错误 / 证书错误'), copy('Resynchronises the system clock with the operating system’s time service.', '使用系统时间服务重新同步时钟。')],
  ['print', copy('Printer queue stuck', '打印队列卡住'), copy('Windows: restarts the print spooler. macOS/Linux: cancels your queued jobs.', 'Windows:重启打印后台程序。macOS/Linux:取消您的排队任务。')],
  ['firewall', copy('Firewall is off', '防火墙未开启'), copy('Turns the firewall on: Windows Firewall, the macOS firewall, or firewalld/ufw on Linux. Refused inside SSH or Remote Desktop.', '开启防火墙:Windows 防火墙、macOS 防火墙或 Linux 的 firewalld/ufw。在 SSH 或远程桌面会话中会拒绝执行。')],
];
const checks = [
  [copy('Firewall', '防火墙'), copy('On for every network profile', '所有网络配置均已开启')],
  [copy('Disk encryption', '磁盘加密'), 'BitLocker · FileVault · LUKS'],
  [copy('Updates', '系统更新'), copy('Waiting and automatic security updates', '待安装更新及自动安全更新')],
  [copy('Malware & system protection', '恶意软件与系统防护'), copy('Defender, UAC, SMBv1 · Gatekeeper, SIP', 'Defender、UAC、SMBv1 · Gatekeeper、SIP')],
  [copy('Sign-in safety', '登录安全'), copy('Mac automatic login · SSH root and password login', 'Mac 自动登录 · SSH root 与密码登录')],
  [copy('Open ports', '开放端口'), copy('Remote Desktop, file sharing, databases and more open to the whole network', '对整个网络开放的远程桌面、文件共享、数据库等')],
  [copy('Wi-Fi', 'Wi-Fi'), copy('Warns on open networks with no password', '连接无密码开放网络时警告')],
  [copy('Secure connections', '安全连接'), copy('Certificates verify; proxy in use', '证书验证及代理使用情况')],
];
---
<Layout title={copy('AutoFix — Request-based fixes for system administrators | Xialei', 'AutoFix — 面向系统管理员的按需自动修复 | Xialei')} lang={language} description="Installs itself, checks your computer's security and network, and fixes common issues after you approve with YES. Free beta for Windows, macOS and Linux.">
  <Header />
  <main class="setup">
    <a class="back" href="/#tools">{copy('← Back to Tools', '← 返回实用工具')}</a>
    <header>
      <p class="eyebrow">{copy('XIALEI TOOLBOX · PUBLIC BETA · RELEASED 1 DECEMBER 2026', 'XIALEI 工具箱 · 公开测试版 · 2026 年 12 月 1 日发布')}</p>
      <h1>{copy('Describe the issue.', '描述问题。')}<br /><span>{copy('Approve the fix.', '批准修复。')}</span></h1>
      <p class="lead">{copy('AutoFix turns a plain-language request such as “printer stuck” or “disk full” into a diagnosis, a clearly stated fix and a re-check. Nothing changes until you type YES, and every step is written to a local log.', 'AutoFix 将“打印机卡住”或“磁盘已满”等简单描述转换为诊断、明确的修复方案和修复后检查。在您输入 YES 之前不会进行任何更改,每一步都会写入本地日志。')}</p>
      <a class="download" href="/downloads/xialei-autofix-setup-beta.zip" download>{copy('Download AutoFix · ZIP', '下载 AutoFix · ZIP')}</a>
      <p class="caption">{copy('Free · No signup · Python 3.8+ · Windows, macOS, Linux', '免费 · 无需注册 · Python 3.8+ · Windows、macOS、Linux')}</p>
    </header>
    <aside class="notice"><strong>{copy('You stay in control.', '控制权在您手中。')}</strong> {copy('AutoFix never raises its own permissions and never runs your typed words, AI replies or assistant requests as commands. It works offline unless you link a cloud service. If a fix needs administrator rights, it stops and tells you how to rerun it.', 'AutoFix 不会自行提升权限,也不会把您输入的文字、AI 回复或助手请求当作命令执行。除非您连接云服务,否则完全离线运行。如果修复需要管理员权限,它会停止并告诉您如何重新运行。')}</aside>
    <section aria-labelledby="flow"><h2 id="flow">{copy('How a request is handled', '请求处理流程')}</h2>
      <ol class="flow">
        <li><strong>{copy('Request', '请求')}</strong><span>{copy('Type the problem in English or Chinese.', '用中文或英文输入问题。')}</span></li>
        <li><strong>{copy('Diagnose', '诊断')}</strong><span>{copy('A read-only check confirms whether the problem exists.', '只读检查确认问题是否存在。')}</span></li>
        <li><strong>{copy('Approve', '批准')}</strong><span>{copy('The exact command is shown. Type YES to apply.', '显示准确命令。输入 YES 才会执行。')}</span></li>
        <li><strong>{copy('Re-check & log', '复查与记录')}</strong><span>{copy('The check runs again and the result is logged.', '再次检查并记录结果。')}</span></li>
      </ol>
    </section>
    <section aria-labelledby="auto"><h2 id="auto">{copy('Installs itself, then checks everything', '自动安装,然后全面检查')}</h2>
      <p class="lead">{copy('Open the launcher once. AutoFix installs itself in your user folder, adds an autofix command, and runs a read-only check of this computer’s security and network connection. It saves a report, then offers a fix for each problem it can repair — one YES at a time.', '打开一次启动器。AutoFix 会安装到用户目录、添加 autofix 命令,并只读检查本机安全和网络连接。它会保存报告,然后逐项提供可修复问题的修复方案,每项都需输入 YES。')}</p>
      <ul class="checks">{checks.map(([title, text]) => <li><strong>{title}</strong><span>{text}</span></li>)}</ul>
      <p class="caption">{copy('It checks this computer and its connection only — it does not scan other devices on your network. Findings it cannot fix safely, such as encryption or updates, come with clear advice. Run as administrator for the most complete results.', '只检查本机及其连接,不扫描网络中的其他设备。无法安全自动修复的问题(如加密或更新)会附带明确建议。以管理员身份运行可获得最完整的结果。')}</p>
    </section>
    <section aria-labelledby="issues"><h2 id="issues">{copy('Supported issues', '支持的问题')}</h2>
      <div class="platform-grid">{issues.map(([id, title, text]) => <article><p class="tag">{id.toUpperCase()}</p><h3>{title}</h3><p>{text}</p></article>)}</div>
    </section>
    <section aria-labelledby="cloud"><h2 id="cloud">{copy('Connect to the cloud — only after it is verified', '连接云端 — 验证通过后才启用')}</h2>
      <div class="cloud-grid">
        <article><p class="tag">API</p><h3>{copy('Link an AI service', '连接 AI 服务')}</h3><p>{copy('Link any OpenAI-compatible service, or a local model. AutoFix sends a test request and saves the link only if it succeeds. Then, when your description matches no keyword, the AI picks one of the six fixes. It can never supply its own commands.', '连接任何 OpenAI 兼容服务或本地模型。AutoFix 会发送测试请求,只有成功才保存连接。之后当描述不匹配关键词时,AI 从六种修复中选择一种,永远不能提供自己的命令。')}</p><code>autofix.py --link-api https://api.openai.com/v1 --model gpt-4o-mini</code></article>
        <article><p class="tag">MCP</p><h3>{copy('Let an AI assistant call it', '让 AI 助手调用')}</h3><p>{copy('Add AutoFix to an MCP-capable assistant such as Claude Desktop or an IDE agent. The assistant can list issues, run diagnoses and the security check. It can apply fixes only if you start AutoFix with --allow-fixes, and the administrator-rights and remote-session checks still apply.', '将 AutoFix 添加到支持 MCP 的助手(例如 Claude Desktop 或 IDE 智能体)。助手可以列出问题、运行诊断和安全检查。只有使用 --allow-fixes 启动时才能执行修复,管理员权限和远程会话检查仍然有效。')}</p><code>{'{"command": "python3", "args": ["/path/autofix.py", "--mcp"]}'}</code></article>
      </div>
      <p class="caption">{copy('Use --status to see the link and proxy, --verify to test it again, --unlink to remove it, and --offline to never contact the cloud. The key is stored only in your user folder.', '使用 --status 查看连接和代理,--verify 重新测试,--unlink 删除连接,--offline 完全不连接云端。密钥只保存在您的用户目录中。')}</p>
    </section>
    <section class="next"><h2>{copy('Run it', '运行方式')}</h2><ol>
      <li><strong>Windows.</strong> {copy('Extract the ZIP and double-click Start AutoFix.bat. It also runs from a network share, and it uses your office proxy and Windows certificates automatically. For network, time, printer and firewall fixes, right-click it and choose Run as administrator.', '解压 ZIP 并双击 Start AutoFix.bat。也可从网络共享目录运行,并自动使用公司代理和 Windows 证书。网络、时间、打印和防火墙修复请右键选择“以管理员身份运行”。')}</li>
      <li><strong>Mac.</strong> {copy('Open Start AutoFix.command. DNS, network, time and firewall fixes need sudo autofix in Terminal.', '打开 Start AutoFix.command。DNS、网络、时间和防火墙修复需在终端运行 sudo autofix。')}</li>
      <li><strong>Linux.</strong> {copy('Run sh start-autofix.sh, then sudo autofix for DNS, time and firewall fixes. The network fix uses NetworkManager. Use --dry-run to check without changing anything.', '运行 sh start-autofix.sh,DNS、时间和防火墙修复再运行 sudo autofix。网络修复使用 NetworkManager。使用 --dry-run 只检查不修改。')}</li>
    </ol><a href={zh ? '/tool-source?lang=zh#autofix' : '/tool-source#autofix'}>{copy('Read the complete source code →', '查看完整源代码 →')}</a></section>
    <details><summary>{copy('What this beta does — and does not do', '测试版的功能与限制')}</summary><p>{copy('AutoFix covers six common causes with fixed, reviewed commands and runs a read-only security check. It is not a monitoring agent, does not run in the background and does not scan other devices. It has been tested on Linux, including the install, the security check with simulated system tools, the API link against a stand-in service and an MCP session; Windows, macOS, real cloud providers and specific AI assistants have not been verified yet. Try it on one machine before using it across a fleet.', 'AutoFix 使用固定且经过审查的命令处理六种常见问题,并进行只读安全检查。它不是监控程序,不在后台运行,也不扫描其他设备。已在 Linux 环境测试,包括安装、使用模拟系统工具的安全检查、使用模拟服务测试 API 连接以及 MCP 会话;尚未在 Windows、macOS、真实云服务和特定 AI 助手上验证。请先在一台电脑上试用,再推广到多台设备。')}</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;transition:background .2s,transform .2s}.download:hover{background:#c6edf7;transform:translateY(-2px)}.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,.next strong{color:#edf6ff}.cloud-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin:24px 0}.cloud-grid article{padding:24px;border:1px solid #345063;border-radius:16px;background:#102233;min-width:0}.cloud-grid article p:not(.tag){color:#c4d7e6}.cloud-grid code{display:block;margin-top:16px;padding:12px;background:#06101a;border-radius:8px;color:#a5def0;font-size:.8125rem;overflow-x:auto;white-space:nowrap}.flow{list-style:none;padding:0;display:grid;grid-template-columns:repeat(4,1fr);gap:16px;counter-reset:s}.checks{list-style:none;padding:0;margin:24px 0;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px}.checks li{padding:16px;border:1px solid #345063;border-left:3px solid #a6e3d6;border-radius:12px;background:#102233;display:flex;flex-direction:column;gap:8px;font-size:.875rem;color:#c4d7e6;transition:border-color .2s,transform .2s}.checks li:hover{border-color:#a6e3d6;transform:translateY(-2px)}.checks strong{color:#edf6ff;font-size:1rem}.flow li{counter-increment:s;padding:24px 16px;border:1px solid #345063;border-radius:16px;background:#102233;display:flex;flex-direction:column;gap:8px;color:#c4d7e6;transition:border-color .2s,transform .2s}.flow li:hover,.platform-grid article:hover{border-color:#a6e3d6;transform:translateY(-2px)}.flow li::before{content:counter(s);width:32px;height:32px;border-radius:50%;background:#a6e3d6;color:#10212b;font-weight:600;display:grid;place-items:center}.flow strong{color:#edf6ff}.platform-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin:24px 0}.platform-grid article{padding:24px;border:1px solid #345063;border-radius:16px;background:#102233;transition:border-color .2s,transform .2s}.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:800px){.flow,.checks{grid-template-columns:1fr 1fr}.platform-grid{grid-template-columns:1fr 1fr}}@media(max-width:560px){.setup{padding-top:40px}.flow,.platform-grid,.cloud-grid,.checks{grid-template-columns:1fr}}
</style>