ereniko commited on
Commit
ff322b9
·
unverified ·
1 Parent(s): 7b2f9d8

v0.4.1: Markdown tables, larger configurable context, README update

Browse files
Files changed (9) hide show
  1. README.md +31 -3
  2. css/app.css +6 -0
  3. index.html +4 -0
  4. js/agent.js +12 -6
  5. js/config-defaults.js +6 -1
  6. js/config.js +1 -1
  7. js/main.js +26 -1
  8. js/markdown.js +48 -1
  9. sw.js +1 -1
README.md CHANGED
@@ -20,13 +20,41 @@ custom_headers:
20
 
21
  An AI agent with its own Linux computer, entirely inside one web page.
22
 
23
- - **Model:** [LFM3-1.7B](https://huggingface.co/LiquidAI/LFM3-1.7B) (q4f16 ONNX) running on your GPU through WebGPU with [transformers.js](https://github.com/huggingface/transformers.js).
24
- - **Computer:** a real Debian (i386) machine running in the browser on [CheerpX](https://cheerpx.io), the engine behind [WebVM](https://webvm.io).
25
  - **Agent harness:** the model calls `run_command`, `write_file` and `read_file` tools. Commands run in the same terminal you see, so you can watch and take over at any time.
26
  - **File viewer:** browse the machine's files and open code (syntax highlighted), text, Markdown, images, audio and video. HTML pages open as sandboxed live previews together with the stylesheets, scripts, images and data files they reference, and links between pages work.
27
  - **Offline:** the first visit downloads everything (about 1.6 GB) into your browser's storage. After that it works with no internet connection.
28
 
29
- **Requirements:** desktop Chrome or Edge with WebGPU and `shader-f16` support, about 2.5 GB of free disk space, and 8 GB or more RAM. Open the app at its own URL (`https://<owner>-localwebagent.static.hf.space`), because the embedded view on huggingface.co can't enable the cross-origin isolation CheerpX needs.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  ## Licenses
32
 
 
20
 
21
  An AI agent with its own Linux computer, entirely inside one web page.
22
 
23
+ - **Model:** [LFM3-1.7B](https://huggingface.co/LiquidAI/LFM3-1.7B) (q4f16 ONNX) running on your GPU through WebGPU with [transformers.js](https://github.com/huggingface/transformers.js). If your device can't run it, you can [use an API model instead](#use-an-api-model).
24
+ - **Computer:** a real Debian (i386) machine running in the browser on [CheerpX](https://cheerpx.io), the engine behind [WebVM](https://webvm.io). It always runs on your device, whichever model you use.
25
  - **Agent harness:** the model calls `run_command`, `write_file` and `read_file` tools. Commands run in the same terminal you see, so you can watch and take over at any time.
26
  - **File viewer:** browse the machine's files and open code (syntax highlighted), text, Markdown, images, audio and video. HTML pages open as sandboxed live previews together with the stylesheets, scripts, images and data files they reference, and links between pages work.
27
  - **Offline:** the first visit downloads everything (about 1.6 GB) into your browser's storage. After that it works with no internet connection.
28
 
29
+ **Requirements for the local model:** desktop Chrome or Edge with WebGPU and `shader-f16` support, about 2.5 GB of free disk space, and 8 GB or more RAM. Open the app at its own URL (`https://<owner>-localwebagent.static.hf.space`), because the embedded view on huggingface.co can't enable the cross-origin isolation CheerpX needs.
30
+
31
+ ## Phones and low-memory devices
32
+
33
+ The local model needs about 1.4 GB of graphics memory. Most phones can't give that much to a browser tab, so the app warns you on phones and suggests an API model instead. You can still try the local model. If it fails to load, the app explains why (out of graphics memory, no WebGPU support, or a failed download), keeps Linux running, and offers to switch to an API model or try again. The raw error is under "Technical details".
34
+
35
+ To make the local model fit on more devices, the weights are kept on disk and read tensor by tensor while they are copied to the GPU, instead of being held in memory all at once. On phones and devices reporting less than 8 GB of RAM, the model also loads before Linux starts, so the two don't compete for memory.
36
+
37
+ ## Use an API model
38
+
39
+ Any OpenAI-compatible Chat Completions API works, for example OpenRouter, OpenAI, the Hugging Face router, Groq, or a local Ollama or LM Studio server. Open it from the setup screen ("Use an API model instead"), from the error message when the local model fails, or from **Settings → Model → Change**:
40
+
41
+ | Field | What to enter |
42
+ |---|---|
43
+ | Provider | A preset fills in the base URL. Choose "Other" for anything else. |
44
+ | Base URL | The API root, for example `https://openrouter.ai/api/v1`. |
45
+ | API key | Your provider's key. Leave it empty for local servers that don't need one. |
46
+ | Model ID | As your provider lists it. Pick a model that supports tool calling. |
47
+
48
+ Use **Test** to check the settings before saving. Only the model moves to the provider: the Linux machine and its files stay in your browser. That also means the agent needs an internet connection, and the provider receives your messages and the output of the commands the agent runs.
49
+
50
+ The key stays only until you close the tab, unless you turn on "Remember key on this device", which saves it in this browser's local storage. The provider must allow requests from web pages (CORS); OpenRouter, OpenAI and the Hugging Face router do. To go back to the local model, use "Use the local model" in the same dialog.
51
+
52
+ ## Settings
53
+
54
+ - **Context size:** how much of the conversation the model sees, in thousands of tokens. The defaults are 32k for the local model (longer prompts are slower and use more GPU memory) and 128k for API models (set it to your model's context window). Each backend keeps its own value. A single command's output can use up to about 15% of it; older output is trimmed only when the conversation no longer fits.
55
+ - **Reasoning:** let the model think before each step. Slower, more reliable on multi-step tasks.
56
+ - **Approve commands:** ask before running each command or writing a file.
57
+ - **Max steps per task** and **command timeout**.
58
 
59
  ## Licenses
60
 
css/app.css CHANGED
@@ -177,6 +177,12 @@ body.resizing iframe, body.resizing #terminal { pointer-events: none; }
177
  .md ul, .md ol { margin: 4px 0 10px; padding-left: 20px; } .md li { margin: 2px 0; }
178
  .md h3, .md h4, .md h5, .md h6 { margin: 14px 0 6px; font-size: 13.5px; font-weight: 600; }
179
  .md strong { font-weight: 600; }
 
 
 
 
 
 
180
  .md code { font: 12.5px var(--mono); background: var(--surface-2); border: 1px solid var(--border); padding: 1px 5px; border-radius: 6px; }
181
  .md pre.md-code { background: var(--code-bg); border: 1px solid var(--border); color: var(--code-text); padding: 12px 14px; border-radius: var(--radius); overflow-x: auto; margin: 8px 0; }
182
  .md pre.md-code code { background: none; border: 0; padding: 0; font-size: 12.5px; line-height: 1.6; }
 
177
  .md ul, .md ol { margin: 4px 0 10px; padding-left: 20px; } .md li { margin: 2px 0; }
178
  .md h3, .md h4, .md h5, .md h6 { margin: 14px 0 6px; font-size: 13.5px; font-weight: 600; }
179
  .md strong { font-weight: 600; }
180
+ .md-table { overflow-x: auto; margin: 8px 0 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); }
181
+ .md-table table { border-collapse: collapse; width: 100%; font-size: 12.5px; font-variant-numeric: tabular-nums; }
182
+ .md-table th, .md-table td { padding: 6px 10px; border-top: 1px solid var(--border); text-align: left; vertical-align: top; overflow-wrap: normal; }
183
+ .md-table th { border-top: 0; background: var(--surface-2); font-weight: 600; white-space: nowrap; }
184
+ .md-table tr + tr td { border-top: 1px solid var(--border); }
185
+ .md-table td + td, .md-table th + th { border-left: 1px solid var(--border); }
186
  .md code { font: 12.5px var(--mono); background: var(--surface-2); border: 1px solid var(--border); padding: 1px 5px; border-radius: 6px; }
187
  .md pre.md-code { background: var(--code-bg); border: 1px solid var(--border); color: var(--code-text); padding: 12px 14px; border-radius: var(--radius); overflow-x: auto; margin: 8px 0; }
188
  .md pre.md-code code { background: none; border: 0; padding: 0; font-size: 12.5px; line-height: 1.6; }
index.html CHANGED
@@ -196,6 +196,10 @@
196
  <span><span class="rs-title">Approve commands</span><span class="rs-desc">Ask before running each command or writing a file.</span></span>
197
  <input type="checkbox" class="switch" id="set-confirm">
198
  </label>
 
 
 
 
199
  <label class="row-setting">
200
  <span><span class="rs-title">Max steps per task</span></span>
201
  <input type="number" class="num" id="set-steps" min="1" max="50">
 
196
  <span><span class="rs-title">Approve commands</span><span class="rs-desc">Ask before running each command or writing a file.</span></span>
197
  <input type="checkbox" class="switch" id="set-confirm">
198
  </label>
199
+ <label class="row-setting">
200
+ <span><span class="rs-title">Context size (k tokens)</span><span class="rs-desc" id="set-context-desc"></span></span>
201
+ <input type="number" class="num" id="set-context" min="4" max="256" step="1">
202
+ </label>
203
  <label class="row-setting">
204
  <span><span class="rs-title">Max steps per task</span></span>
205
  <input type="number" class="num" id="set-steps" min="1" max="50">
js/agent.js CHANGED
@@ -111,19 +111,19 @@ export class Agent {
111
  if (!a.command?.trim()) throw new Error("missing 'command'");
112
  const timeoutSec = Math.min(600, Math.max(5, parseInt(a.timeout, 10) || this.settings.commandTimeoutSec));
113
  const r = await this.vm.exec(a.command, { timeoutSec });
114
- result = { text: formatExec(r, timeoutSec), exitCode: r.exitCode, output: r.output, timedOut: r.timedOut };
115
  } else if (call.name === "write_file") {
116
  if (!a.path) throw new Error("missing 'path'");
117
  let content = a.content ?? "";
118
  if (content && !content.endsWith("\n")) content += "\n"; // the call format strips it
119
  const r = await this.vm.writeFile(a.path, content);
120
- result = { text: formatExec(r), exitCode: r.exitCode, output: r.output };
121
  } else if (call.name === "read_file") {
122
  if (!a.path) throw new Error("missing 'path'");
123
  const s = Math.max(1, parseInt(a.start_line, 10) || 1);
124
  const e = Math.max(s, parseInt(a.end_line, 10) || s + 199);
125
  const r = await this.vm.exec(`nl -ba -w4 -s' ' -- ${shQuote(a.path)} | sed -n '${s},${e}p'`);
126
- result = { text: formatExec(r), exitCode: r.exitCode, output: r.output };
127
  } else {
128
  result = { text: `Unknown tool "${call.name}". Available tools: run_command, write_file, read_file.`, exitCode: null };
129
  }
@@ -134,15 +134,21 @@ export class Agent {
134
  return result.text;
135
  }
136
 
 
 
 
 
 
137
  // Keep the prompt within budget: shorten old tool outputs first, then drop old turns.
138
  #compact() {
139
  const budget = this.settings.contextBudgetTokens;
140
  const est = () => this.history.reduce((n, m) => n + Math.ceil(m.content.length / 3.2), 900);
141
  if (est() <= budget) return;
142
  const toolIdx = this.history.map((m, i) => (m.role === "tool" ? i : -1)).filter((i) => i >= 0);
 
143
  for (const i of toolIdx.slice(0, -2)) {
144
  const c = this.history[i].content;
145
- if (c.length > 400) this.history[i] = { role: "tool", content: c.slice(0, 300) + "\n... [older output truncated to save context]" };
146
  if (est() <= budget) return;
147
  }
148
  // Drop whole old exchanges (keep the latest user message and everything after it).
@@ -156,9 +162,9 @@ export class Agent {
156
  }
157
  }
158
 
159
- function formatExec(r, timeoutSec) {
160
  if (r.busy) return r.output;
161
- const out = r.output?.length ? truncateOutput(r.output) : "(no output)";
162
  let head = r.exitCode === null ? "exit code: unknown" : `exit code: ${r.exitCode}`;
163
  if (r.timedOut) head += ` (interrupted after ${timeoutSec}s timeout)`;
164
  return `${head}\n${out}`;
 
111
  if (!a.command?.trim()) throw new Error("missing 'command'");
112
  const timeoutSec = Math.min(600, Math.max(5, parseInt(a.timeout, 10) || this.settings.commandTimeoutSec));
113
  const r = await this.vm.exec(a.command, { timeoutSec });
114
+ result = { text: formatExec(r, this.#maxToolChars(), timeoutSec), exitCode: r.exitCode, output: r.output, timedOut: r.timedOut };
115
  } else if (call.name === "write_file") {
116
  if (!a.path) throw new Error("missing 'path'");
117
  let content = a.content ?? "";
118
  if (content && !content.endsWith("\n")) content += "\n"; // the call format strips it
119
  const r = await this.vm.writeFile(a.path, content);
120
+ result = { text: formatExec(r, this.#maxToolChars()), exitCode: r.exitCode, output: r.output };
121
  } else if (call.name === "read_file") {
122
  if (!a.path) throw new Error("missing 'path'");
123
  const s = Math.max(1, parseInt(a.start_line, 10) || 1);
124
  const e = Math.max(s, parseInt(a.end_line, 10) || s + 199);
125
  const r = await this.vm.exec(`nl -ba -w4 -s' ' -- ${shQuote(a.path)} | sed -n '${s},${e}p'`);
126
+ result = { text: formatExec(r, this.#maxToolChars()), exitCode: r.exitCode, output: r.output };
127
  } else {
128
  result = { text: `Unknown tool "${call.name}". Available tools: run_command, write_file, read_file.`, exitCode: null };
129
  }
 
134
  return result.text;
135
  }
136
 
137
+ // One tool result may use up to ~15% of the context budget (at least 4000 characters).
138
+ #maxToolChars() {
139
+ return Math.max(MAX_TOOL_OUTPUT, Math.round(this.settings.contextBudgetTokens * 3.2 * 0.15));
140
+ }
141
+
142
  // Keep the prompt within budget: shorten old tool outputs first, then drop old turns.
143
  #compact() {
144
  const budget = this.settings.contextBudgetTokens;
145
  const est = () => this.history.reduce((n, m) => n + Math.ceil(m.content.length / 3.2), 900);
146
  if (est() <= budget) return;
147
  const toolIdx = this.history.map((m, i) => (m.role === "tool" ? i : -1)).filter((i) => i >= 0);
148
+ const keep = Math.max(300, Math.round(this.#maxToolChars() / 10));
149
  for (const i of toolIdx.slice(0, -2)) {
150
  const c = this.history[i].content;
151
+ if (c.length > keep + 100) this.history[i] = { role: "tool", content: c.slice(0, keep) + "\n... [older output truncated to save context]" };
152
  if (est() <= budget) return;
153
  }
154
  // Drop whole old exchanges (keep the latest user message and everything after it).
 
162
  }
163
  }
164
 
165
+ function formatExec(r, maxChars, timeoutSec) {
166
  if (r.busy) return r.output;
167
+ const out = r.output?.length ? truncateOutput(r.output, maxChars) : "(no output)";
168
  let head = r.exitCode === null ? "exit code: unknown" : `exit code: ${r.exitCode}`;
169
  if (r.timedOut) head += ` (interrupted after ${timeoutSec}s timeout)`;
170
  return `${head}\n${out}`;
js/config-defaults.js CHANGED
@@ -6,5 +6,10 @@ export const DEFAULTS = {
6
  commandTimeoutSec: 90,
7
  maxNewTokens: 2048,
8
  thinkingBudget: 1536,
9
- contextBudgetTokens: 14000,
 
 
 
 
 
10
  };
 
6
  commandTimeoutSec: 90,
7
  maxNewTokens: 2048,
8
  thinkingBudget: 1536,
9
+ // How many tokens of conversation the model sees; older tool output is trimmed beyond it.
10
+ // The local default is moderate because long prompts are slow and use GPU memory;
11
+ // API models usually have 128k+ windows.
12
+ contextLocalTokens: 32768,
13
+ contextApiTokens: 128000,
14
+ contextBudgetTokens: 32768, // the active budget; main.js sets it from the two above
15
  };
js/config.js CHANGED
@@ -1,5 +1,5 @@
1
  // Central configuration. Everything that pins a version or a location lives here.
2
- export const APP_VERSION = "0.4.0";
3
 
4
  // --- Language model (loaded from the Hugging Face Hub, cached by transformers.js) ---
5
  export const MODEL_ID = "LiquidAI/LFM3-1.7B-ONNX";
 
1
  // Central configuration. Everything that pins a version or a location lives here.
2
+ export const APP_VERSION = "0.4.1";
3
 
4
  // --- Language model (loaded from the Hugging Face Hub, cached by transformers.js) ---
5
  export const MODEL_ID = "LiquidAI/LFM3-1.7B-ONNX";
js/main.js CHANGED
@@ -35,7 +35,13 @@ const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
35
  // ---------- settings ----------
36
  const settings = { ...DEFAULTS };
37
  try { Object.assign(settings, JSON.parse(localStorage.getItem("lwa-settings") || "{}")); } catch {}
38
- const saveSettings = () => { try { localStorage.setItem("lwa-settings", JSON.stringify(settings)); } catch {} };
 
 
 
 
 
 
39
 
40
  // ---------- status ----------
41
  function status(name, state, text) {
@@ -51,6 +57,12 @@ const usingApi = () => settings.backend === "api" && !!settings.api?.baseUrl &&
51
  const apiConfig = () => ({ baseUrl: settings.api.baseUrl, model: settings.api.model, key: loadApiKey() });
52
  const apiHost = () => { try { return new URL(settings.api.baseUrl).host; } catch { return settings.api?.baseUrl ?? ""; } };
53
 
 
 
 
 
 
 
54
  let llm = usingApi() ? new RemoteLLM(apiConfig()) : new LLM();
55
  let modelError = null; // why the local model failed to load, if it did
56
  const vm = new VM();
@@ -627,6 +639,11 @@ $("#open-settings").addEventListener("click", () => {
627
  $("#set-confirm").checked = settings.confirmCommands;
628
  $("#set-steps").value = settings.maxSteps;
629
  $("#set-timeout").value = settings.commandTimeoutSec;
 
 
 
 
 
630
  dlg.showModal();
631
  });
632
  dlg.addEventListener("close", () => {
@@ -634,6 +651,13 @@ dlg.addEventListener("close", () => {
634
  settings.confirmCommands = $("#set-confirm").checked;
635
  settings.maxSteps = Math.min(50, Math.max(1, Number($("#set-steps").value) || DEFAULTS.maxSteps));
636
  settings.commandTimeoutSec = Math.min(600, Math.max(5, Number($("#set-timeout").value) || DEFAULTS.commandTimeoutSec));
 
 
 
 
 
 
 
637
  saveSettings();
638
  syncToggles();
639
  });
@@ -693,6 +717,7 @@ $("#api-form").addEventListener("submit", async (e) => {
693
  settings.backend = "api";
694
  settings.api = { preset: f.preset, baseUrl: f.baseUrl, model: f.model };
695
  saveSettings();
 
696
  saveApiKey(f.key, $("#api-remember").checked);
697
  apiDlg.close();
698
  if (!$("#setup").hidden) return location.reload(); // re-run setup without the local model
 
35
  // ---------- settings ----------
36
  const settings = { ...DEFAULTS };
37
  try { Object.assign(settings, JSON.parse(localStorage.getItem("lwa-settings") || "{}")); } catch {}
38
+ // Older versions saved the active budget (14000) with everything else; the per-backend
39
+ // values replace it, so drop it to let the new defaults apply.
40
+ delete settings.contextBudgetTokens;
41
+ const saveSettings = () => {
42
+ const { contextBudgetTokens, ...persist } = settings; // derived, never stored
43
+ try { localStorage.setItem("lwa-settings", JSON.stringify(persist)); } catch {}
44
+ };
45
 
46
  // ---------- status ----------
47
  function status(name, state, text) {
 
57
  const apiConfig = () => ({ baseUrl: settings.api.baseUrl, model: settings.api.model, key: loadApiKey() });
58
  const apiHost = () => { try { return new URL(settings.api.baseUrl).host; } catch { return settings.api?.baseUrl ?? ""; } };
59
 
60
+ // The active context budget follows the backend.
61
+ const syncContextBudget = () => {
62
+ settings.contextBudgetTokens = usingApi() ? settings.contextApiTokens : settings.contextLocalTokens;
63
+ };
64
+ syncContextBudget();
65
+
66
  let llm = usingApi() ? new RemoteLLM(apiConfig()) : new LLM();
67
  let modelError = null; // why the local model failed to load, if it did
68
  const vm = new VM();
 
639
  $("#set-confirm").checked = settings.confirmCommands;
640
  $("#set-steps").value = settings.maxSteps;
641
  $("#set-timeout").value = settings.commandTimeoutSec;
642
+ $("#set-context").value = Math.round(settings.contextBudgetTokens / 1000);
643
+ $("#set-context").max = usingApi() ? 2000 : 256;
644
+ $("#set-context-desc").textContent = usingApi()
645
+ ? "How much of the conversation the API model sees, in thousands of tokens. Set it to your model's context window."
646
+ : "How much of the conversation the local model sees, in thousands of tokens. Larger is slower and uses more GPU memory.";
647
  dlg.showModal();
648
  });
649
  dlg.addEventListener("close", () => {
 
651
  settings.confirmCommands = $("#set-confirm").checked;
652
  settings.maxSteps = Math.min(50, Math.max(1, Number($("#set-steps").value) || DEFAULTS.maxSteps));
653
  settings.commandTimeoutSec = Math.min(600, Math.max(5, Number($("#set-timeout").value) || DEFAULTS.commandTimeoutSec));
654
+ const k = Number($("#set-context").value);
655
+ if (k && k !== Math.round(settings.contextBudgetTokens / 1000)) {
656
+ const key = usingApi() ? "contextApiTokens" : "contextLocalTokens";
657
+ settings[key] = Math.round(Math.min(usingApi() ? 2000 : 256, Math.max(4, k)) * 1000);
658
+ syncContextBudget();
659
+ $("#ctx").textContent = $("#ctx").textContent.replace(/\/ [\d,.\s]+ tokens/, `/ ${settings.contextBudgetTokens.toLocaleString()} tokens`);
660
+ }
661
  saveSettings();
662
  syncToggles();
663
  });
 
717
  settings.backend = "api";
718
  settings.api = { preset: f.preset, baseUrl: f.baseUrl, model: f.model };
719
  saveSettings();
720
+ syncContextBudget();
721
  saveApiKey(f.key, $("#api-remember").checked);
722
  apiDlg.close();
723
  if (!$("#setup").hidden) return location.reload(); // re-run setup without the local model
js/markdown.js CHANGED
@@ -1,5 +1,5 @@
1
  // Tiny, safe Markdown subset for agent replies: fenced code, inline code, bold,
2
- // italics, headings, lists, links (text only, never navigates), paragraphs.
3
  const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
4
 
5
  function inline(s) {
@@ -12,6 +12,46 @@ function inline(s) {
12
  return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code>${esc(codes[Number(i)])}</code>`);
13
  }
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  export function renderMarkdown(src) {
16
  const out = [];
17
  const lines = src.replace(/\r/g, "").split("\n");
@@ -30,6 +70,13 @@ export function renderMarkdown(src) {
30
  out.push(`<pre class="md-code"><code data-lang="${esc(fence[1])}">${esc(body.join("\n"))}</code></pre>`);
31
  continue;
32
  }
 
 
 
 
 
 
 
33
  const h = /^(#{1,4})\s+(.*)$/.exec(line);
34
  if (h) { flush(); out.push(`<h${h[1].length + 2}>${inline(h[2])}</h${h[1].length + 2}>`); i++; continue; }
35
  if (/^\s*([-*+]|\d+[.)])\s+/.test(line)) {
 
1
  // Tiny, safe Markdown subset for agent replies: fenced code, inline code, bold,
2
+ // italics, headings, lists, GFM tables, links (text only, never navigates), paragraphs.
3
  const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
4
 
5
  function inline(s) {
 
12
  return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code>${esc(codes[Number(i)])}</code>`);
13
  }
14
 
15
+ // ---------- GFM tables ----------
16
+ const TABLE_SEP = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
17
+
18
+ /** Splits a table row on pipes that are not escaped (\|) or inside `code`. */
19
+ function splitRow(line) {
20
+ let s = line.trim();
21
+ if (s.startsWith("|")) s = s.slice(1);
22
+ if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1);
23
+ const cells = [];
24
+ let cur = "";
25
+ let inCode = false;
26
+ for (let k = 0; k < s.length; k++) {
27
+ const ch = s[k];
28
+ if (ch === "\\" && s[k + 1] === "|") { cur += "|"; k++; continue; }
29
+ if (ch === "`") inCode = !inCode;
30
+ if (ch === "|" && !inCode) { cells.push(cur.trim()); cur = ""; continue; }
31
+ cur += ch;
32
+ }
33
+ cells.push(cur.trim());
34
+ return cells;
35
+ }
36
+
37
+ const isTableStart = (lines, i) => lines[i].includes("|") && i + 1 < lines.length && TABLE_SEP.test(lines[i + 1]) && lines[i + 1].includes("-");
38
+
39
+ function renderTable(lines, i) {
40
+ const head = splitRow(lines[i]);
41
+ const aligns = splitRow(lines[i + 1]).map((c) => (c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : c.startsWith(":") ? "left" : ""));
42
+ const cell = (tag, text, k) => `<${tag}${aligns[k] ? ` style="text-align:${aligns[k]}"` : ""}>${inline(text ?? "")}</${tag}>`;
43
+ let j = i + 2;
44
+ const rows = [];
45
+ while (j < lines.length && lines[j].trim() && lines[j].includes("|")) {
46
+ const cells = splitRow(lines[j]);
47
+ rows.push(`<tr>${head.map((_, k) => cell("td", cells[k], k)).join("")}</tr>`);
48
+ j++;
49
+ }
50
+ const html = `<div class="md-table"><table><thead><tr>${head.map((h, k) => cell("th", h, k)).join("")}</tr></thead>` +
51
+ `<tbody>${rows.join("")}</tbody></table></div>`;
52
+ return { html, next: j };
53
+ }
54
+
55
  export function renderMarkdown(src) {
56
  const out = [];
57
  const lines = src.replace(/\r/g, "").split("\n");
 
70
  out.push(`<pre class="md-code"><code data-lang="${esc(fence[1])}">${esc(body.join("\n"))}</code></pre>`);
71
  continue;
72
  }
73
+ if (isTableStart(lines, i)) {
74
+ flush();
75
+ const t = renderTable(lines, i);
76
+ out.push(t.html);
77
+ i = t.next;
78
+ continue;
79
+ }
80
  const h = /^(#{1,4})\s+(.*)$/.exec(line);
81
  if (h) { flush(); out.push(`<h${h[1].length + 2}>${inline(h[2])}</h${h[1].length + 2}>`); i++; continue; }
82
  if (/^\s*([-*+]|\d+[.)])\s+/.test(line)) {
sw.js CHANGED
@@ -6,7 +6,7 @@
6
  // (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
7
  // 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
8
  // CheerpX and multi-threaded WASM need, even when a host forgets to send them.
9
- const SHELL_VERSION = "lwa-shell-0.4.0";
10
  const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
11
  const CX_CACHE_PREFIX = "lwa-cheerpx-";
12
  const DISK_CACHE = "lwa-disk";
 
6
  // (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
7
  // 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
8
  // CheerpX and multi-threaded WASM need, even when a host forgets to send them.
9
+ const SHELL_VERSION = "lwa-shell-0.4.1";
10
  const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
11
  const CX_CACHE_PREFIX = "lwa-cheerpx-";
12
  const DISK_CACHE = "lwa-disk";