v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
- var ai = A.ai;
- var t = ai.t;
-
- var PRIVATE = ".private";
- var PRIVATE_FILES = ["Summary.md", "Conversation.md", "plan.md", "bugs.md", "instructions.md", "design.md"];
- var PRIVATE_DIRS = ["crawler", "sandbox", "recipes"];
- var TEXT_EXT = ["html", "htm", "php", "phtml", "inc", "css", "scss", "sass", "less", "js", "mjs", "cjs", "ts", "jsx", "tsx",
- "json", "jsonc", "md", "markdown", "txt", "xml", "svg", "sql", "csv", "tsv", "yml", "yaml", "ini", "conf", "twig", "tpl",
- "vue", "svelte", "webmanifest", "htaccess", "gitignore", "editorconfig", "example"];
- var TEXT_NAMES = [".htaccess", ".gitignore", ".editorconfig", ".user.ini", "robots.txt", "humans.txt", "LICENSE", "README"];
- var RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;
- var READ_MAX = 60000;
- var READ_LINES = 600;
- var WRITE_MAX = 512 * 1024;
- var OVERWRITE_FREE = 8000;
- var LIST_MAX = 400;
- var SEARCH_MAX = 100;
- var SEARCH_FILES = 3000;
- var SEARCH_FILE_MAX = 1024 * 1024;
- var SNAP_MAX = 80;
- var SNAP_BYTES = 8 * 1024 * 1024;
- var DIFF_LIMIT = 1500;
- var FETCH_MAX = 40000;
-
- function toolError(key, params) {
- var e = new Error(t(key, params));
- e.tool = true;
- return e;
- }
-
- function provider() {
- if (!A.fs.provider) throw toolError("ai.tool.err_no_folder");
- return A.fs.provider;
- }
-
- function cleanPath(raw, allowRoot) {
- var p = String(raw == null ? "" : raw).trim().replace(/^\.\/+/, "").replace(/\/+$/, "");
- if (!p) {
- if (allowRoot) return "";
- throw toolError("ai.tool.err_path_empty");
- }
- if (p.length > 260) throw toolError("ai.tool.err_path_long");
- if (/^\//.test(p) || /^~/.test(p) || /^[a-z][a-z0-9+.-]*:/i.test(p)) throw toolError("ai.tool.err_path_absolute", { path: p });
- if (/[\u0000-\u001f<>:"|?*\\]/.test(p)) throw toolError("ai.tool.err_path_chars", { path: p });
- var segs = p.split("/");
- segs.forEach(function (s) {
- if (!s || s === "." || s === "..") throw toolError("ai.tool.err_path_dots", { path: p });
- if (RESERVED.test(s) || /[. ]$/.test(s)) throw toolError("ai.tool.err_path_reserved", { path: p });
- });
- return segs.join("/");
- }
-
- function isPrivate(path) {
- return path === PRIVATE || path.indexOf(PRIVATE + "/") === 0;
- }
-
- function inHidden(path) {
- return path.split("/").some(function (s) { return A.fs.HIDDEN_DIRS.indexOf(s) >= 0; });
- }
-
- function guardRead(raw) {
- var p = cleanPath(raw);
- if (ai.isExcluded(p)) throw toolError("ai.tool.err_excluded", { path: p });
- if (A.fs.isBinary(p)) throw toolError("ai.tool.err_binary", { path: p });
- return p;
- }
-
- function guardWrite(raw) {
- var p = cleanPath(raw);
- if (ai.isExcluded(p)) throw toolError("ai.tool.err_excluded", { path: p });
- if (inHidden(p)) throw toolError("ai.tool.err_hidden", { path: p });
- var name = util.basename(p);
- if (TEXT_NAMES.indexOf(name) < 0 && TEXT_EXT.indexOf(util.ext(name)) < 0) throw toolError("ai.tool.err_ext", { path: p });
- return p;
- }
-
- function useMemory(path) {
- return isPrivate(path) && !!A.fs.provider && A.fs.provider.kind === "memory";
- }
-
- var mem = null;
-
- async function memory() {
- var key = "ai.private." + (A.fs.provider ? A.fs.provider.name : "");
- if (!mem || mem.key !== key) mem = { key: key, files: (await A.idb.get(key)) || {} };
- return mem;
- }
-
- async function memorySave() {
- await A.idb.set(mem.key, mem.files);
- }
-
- var io = {
- kind: async function (path) {
- if (!path) return "dir";
- if (useMemory(path)) {
- var m = await memory();
- if (m.files[path] != null) return "file";
- return Object.keys(m.files).some(function (k) { return k.indexOf(path + "/") === 0; }) || path === PRIVATE ? "dir" : null;
- }
- var prov = provider();
- if (!(await prov.exists(path))) return null;
- try {
- await prov.readFile(path);
- return "file";
- } catch (e) {
- return "dir";
- }
- },
-
- exists: async function (path) {
- return (await io.kind(path)) != null;
- },
-
- read: async function (path) {
- var tab = A.tabs.byPath(path);
- if (tab && tab.kind === "text") return A.tabs.textOf(tab);
- if (useMemory(path)) {
- var m = await memory();
- if (m.files[path] == null) throw toolError("ai.tool.err_not_found", { path: path });
- return m.files[path];
- }
- try {
- return await provider().readText(path);
- } catch (e) {
- throw toolError("ai.tool.err_not_found", { path: path });
- }
- },
-
- write: async function (path, text) {
- if (useMemory(path)) {
- var m = await memory();
- m.files[path] = text;
- await memorySave();
- return;
- }
- await provider().write(path, text);
- },
-
- remove: async function (path) {
- if (useMemory(path)) {
- var m = await memory();
- Object.keys(m.files).forEach(function (k) { if (k === path || k.indexOf(path + "/") === 0) delete m.files[k]; });
- await memorySave();
- return;
- }
- await provider().remove(path);
- },
-
- list: async function (dir) {
- if (useMemory(dir || "") || (dir === PRIVATE && A.fs.provider && A.fs.provider.kind === "memory")) {
- var m = await memory();
- var prefix = dir ? dir + "/" : "";
- var seen = {};
- Object.keys(m.files).forEach(function (k) {
- if (k.indexOf(prefix) !== 0) return;
- var rest = k.slice(prefix.length).split("/");
- seen[rest[0]] = rest.length > 1 ? "dir" : "file";
- });
- return Object.keys(seen).sort().map(function (n) { return { name: n, kind: seen[n] }; });
- }
- var entries = await provider().list(dir || "");
- if (!dir && A.fs.provider.kind === "memory") {
- var mm = await memory();
- if (Object.keys(mm.files).length && !entries.some(function (e) { return e.name === PRIVATE; })) entries = entries.concat([{ name: PRIVATE, kind: "dir" }]);
- }
- return entries;
- },
-
- ensureDir: async function (dir) {
- if (!dir || useMemory(dir)) return;
- var prov = provider();
- if (await prov.exists(dir)) return;
- var parent = util.dirname(dir);
- if (parent) await io.ensureDir(parent);
- try { await prov.createDir(dir); } catch (e) { if (!(await prov.exists(dir))) throw e; }
- },
-
- move: async function (from, to, kind) {
- if (useMemory(from) || useMemory(to)) {
- var m = await memory();
- Object.keys(m.files).forEach(function (k) {
- if (k === from || k.indexOf(from + "/") === 0) {
- m.files[to + k.slice(from.length)] = m.files[k];
- delete m.files[k];
- }
- });
- await memorySave();
- return;
- }
- var prov = provider();
- var fromDir = util.dirname(from), toDir = util.dirname(to);
- var current = from;
- if (fromDir !== toDir) {
- await io.ensureDir(toDir);
- current = await prov.move(from, toDir, kind);
- }
- if (util.basename(current) !== util.basename(to)) current = await prov.rename(current, util.basename(to), kind);
- return current;
- }
- };
-
- function textOf(path) {
- return io.read(path);
- }
-
- function commonEdges(a, b) {
- var start = 0;
- var max = Math.min(a.length, b.length);
- while (start < max && a.charCodeAt(start) === b.charCodeAt(start)) start++;
- var end = 0;
- while (end < max - start && a.charCodeAt(a.length - 1 - end) === b.charCodeAt(b.length - 1 - end)) end++;
- return { from: start, toA: a.length - end, toB: b.length - end };
- }
-
- function replaceTabText(tab, text) {
- var current = A.tabs.textOf(tab);
- if (current === text) return;
- var e = commonEdges(current, text);
- var changes = { from: e.from, to: e.toA, insert: text.slice(e.from, e.toB) };
- if (tab === A.tabs.active) {
- A.editor.view.dispatch({ changes: changes, userEvent: "input.ai" });
- } else {
- tab.state = tab.state.update({ changes: changes }).state;
- tab.dirty = !tab.state.doc.eq(tab.savedDoc);
- }
- }
-
- async function applyText(path, text) {
- var tab = A.tabs.byPath(path);
- if (tab && tab.kind === "text") {
- var wasDirty = tab.dirty;
- replaceTabText(tab, text);
- if (wasDirty) {
- A.tabs.render();
- return { disk: false, tab: true };
- }
- await io.write(path, text);
- tab.savedDoc = A.tabs.stateOf(tab).doc;
- tab.dirty = false;
- A.tabs.render();
- A.emit("saved", tab);
- return { disk: true, tab: true };
- }
- await io.write(path, text);
- A.emit("saved", { path: path, name: util.basename(path) });
- return { disk: true, tab: false };
- }
-
- async function refreshTree(paths) {
- var dirs = {};
- paths.forEach(function (p) { if (p != null) dirs[util.dirname(p)] = true; });
- if (A.explorer && A.fs.provider) {
- for (var d of Object.keys(dirs)) {
- try { await A.explorer.refresh(d); } catch (e) { }
- }
- } else {
- A.emit("files-changed");
- }
- }
-
- function trimEdges(a, b) {
- var s = 0;
- while (s < a.length && s < b.length && a[s] === b[s]) s++;
- var e = 0;
- while (e < a.length - s && e < b.length - s && a[a.length - 1 - e] === b[b.length - 1 - e]) e++;
- return { s: s, e: e };
- }
-
- function myers(a, b) {
- var n = a.length, m = b.length;
- var v = { 1: 0 };
- var trace = [];
- for (var d = 0; d <= n + m; d++) {
- if (d > DIFF_LIMIT) return null;
- trace.push(Object.assign({}, v));
- for (var k = -d; k <= d; k += 2) {
- var x = k === -d || (k !== d && v[k - 1] < v[k + 1]) ? v[k + 1] : v[k - 1] + 1;
- var y = x - k;
- while (x < n && y < m && a[x] === b[y]) { x++; y++; }
- v[k] = x;
- if (x >= n && y >= m) return backtrack(trace, n, m);
- }
- }
- return null;
- }
-
- function backtrack(trace, n, m) {
- var x = n, y = m;
- var out = [];
- for (var d = trace.length - 1; d >= 0; d--) {
- var v = trace[d];
- var k = x - y;
- var prevK = k === -d || (k !== d && v[k - 1] < v[k + 1]) ? k + 1 : k - 1;
- var prevX = v[prevK];
- var prevY = prevX - prevK;
- while (x > prevX && y > prevY) { out.push({ t: " ", a: x - 1, b: y - 1 }); x--; y--; }
- if (d > 0) {
- if (x === prevX) out.push({ t: "+", b: y - 1 });
- else out.push({ t: "-", a: x - 1 });
- }
- x = prevX;
- y = prevY;
- }
- return out.reverse();
- }
-
- function diffLines(before, after) {
- var a = before == null ? [] : String(before).split("\n");
- var b = after == null ? [] : String(after).split("\n");
- var edge = trimEdges(a, b);
- var midA = a.slice(edge.s, a.length - edge.e);
- var midB = b.slice(edge.s, b.length - edge.e);
- var ops = myers(midA, midB);
- if (!ops) {
- ops = midA.map(function (l, i) { return { t: "-", a: i }; }).concat(midB.map(function (l, i) { return { t: "+", b: i }; }));
- }
- var out = [];
- for (var i = 0; i < edge.s; i++) out.push({ t: " ", text: a[i], la: i + 1, lb: i + 1 });
- ops.forEach(function (o) {
- if (o.t === " ") out.push({ t: " ", text: midA[o.a], la: edge.s + o.a + 1, lb: edge.s + o.b + 1 });
- else if (o.t === "-") out.push({ t: "-", text: midA[o.a], la: edge.s + o.a + 1 });
- else out.push({ t: "+", text: midB[o.b], lb: edge.s + o.b + 1 });
- });
- var offA = a.length - edge.e, offB = b.length - edge.e;
- for (var j = 0; j < edge.e; j++) out.push({ t: " ", text: a[offA + j], la: offA + j + 1, lb: offB + j + 1 });
- return out;
- }
-
- function hunks(lines, context) {
- context = context == null ? 3 : context;
- var result = [];
- var cur = null;
- var lastChange = -Infinity;
- lines.forEach(function (l, i) {
- if (l.t === " ") return;
- var start = Math.max(0, i - context);
- if (cur && start <= lastChange + context + 1) {
- for (var j = cur.end + 1; j <= i; j++) cur.lines.push(lines[j]);
- cur.end = i;
- } else {
- if (cur) result.push(cur);
- cur = { lines: lines.slice(start, i + 1), end: i };
- }
- lastChange = i;
- });
- if (cur) {
- var stop = Math.min(lines.length - 1, cur.end + context);
- for (var k = cur.end + 1; k <= stop; k++) cur.lines.push(lines[k]);
- result.push(cur);
- }
- return result;
- }
-
- function diffStats(lines) {
- var add = 0, del = 0;
- lines.forEach(function (l) { if (l.t === "+") add++; else if (l.t === "-") del++; });
- return { add: add, del: del };
- }
-
- function unified(before, after, maxLines) {
- var lines = diffLines(before, after);
- var out = [];
- hunks(lines).forEach(function (h) {
- var first = h.lines[0];
- out.push("@@ -" + (first.la || 0) + " +" + (first.lb || 0) + " @@");
- h.lines.forEach(function (l) { out.push(l.t + l.text); });
- });
- if (maxLines && out.length > maxLines) return out.slice(0, maxLines).join("\n") + "\n" + t("ai.tool.diff_more", { n: out.length - maxLines });
- return out.join("\n");
- }
-
- function diffView(before, after) {
- var lines = diffLines(before, after);
- var stats = diffStats(lines);
- var box = util.el("div", { class: "ath-ai-diff" });
- box.appendChild(util.el("div", { class: "ath-ai-diff-stats" }, [
- util.el("span", { class: "is-add" }, "+" + stats.add),
- util.el("span", { class: "is-del" }, "−" + stats.del)
- ]));
- var pre = util.el("div", { class: "ath-ai-diff-body orb-mono" });
- var shown = 0;
- hunks(lines).forEach(function (h, hi) {
- if (shown > 800) return;
- if (hi) pre.appendChild(util.el("div", { class: "ath-ai-diff-gap" }, "⋯"));
- h.lines.forEach(function (l) {
- shown++;
- if (shown > 800) return;
- pre.appendChild(util.el("div", { class: "ath-ai-diff-line" + (l.t === "+" ? " is-add" : l.t === "-" ? " is-del" : "") }, [
- util.el("span", { class: "ath-ai-diff-no" }, l.t === "+" ? "" : String(l.la || "")),
- util.el("span", { class: "ath-ai-diff-no" }, l.t === "-" ? "" : String(l.lb || "")),
- util.el("span", { class: "ath-ai-diff-text" }, (l.t === " " ? " " : l.t) + " " + l.text)
- ]));
- });
- });
- if (shown > 800) pre.appendChild(util.el("div", { class: "ath-ai-diff-gap" }, t("ai.tool.diff_more", { n: shown - 800 })));
- if (!lines.some(function (l) { return l.t !== " "; })) pre.appendChild(util.el("div", { class: "ath-ai-diff-gap" }, t("ai.tool.diff_none")));
- box.appendChild(pre);
- return box;
- }
-
- var snaps = { key: null, list: [] };
-
- function snapKey() {
- return "ai.snapshots." + (A.fs.provider ? A.fs.provider.name : "");
- }
-
- async function loadSnaps() {
- var key = snapKey();
- if (snaps.key !== key) {
- var stored = await A.idb.get(key);
- snaps = { key: key, list: Array.isArray(stored) ? stored : [] };
- }
- return snaps.list;
- }
-
- async function saveSnaps() {
- var list = snaps.list;
- while (list.length > SNAP_MAX) list.shift();
- var size = function () {
- return list.reduce(function (n, s) { return n + (s.before || "").length + (s.after || "").length; }, 0);
- };
- while (list.length > 1 && size() > SNAP_BYTES) list.shift();
- await A.idb.set(snaps.key, list);
- A.emit("ai-changes", list.length);
- }
-
- function opLabel(change) {
- return t("ai.change.op_" + change.op, { path: change.path, to: change.to || "" });
- }
-
- function needsApproval(change) {
- if (change.op === "delete" || change.op === "move") return true;
- if (change.private) return true;
- if (change.op === "overwrite" && change.large) return true;
- return ai.get("approval") !== "auto";
- }
-
- async function approve(change, reason) {
- var body = util.el("div", { class: "ath-ai-approve" }, [
- util.el("p", { class: "ath-dialog-text" }, opLabel(change)),
- reason ? util.el("p", { class: "ath-ai-approve-reason" }, reason) : null,
- change.private ? util.el("p", { class: "ath-set-hint" }, t("ai.change.private_note")) : null,
- change.op === "delete" ? util.el("p", { class: "ath-set-hint" }, t("ai.change.delete_note")) : null,
- change.op === "move" || change.op === "copy" ? null : diffView(change.before, change.after)
- ]);
- var answer = await A.ui.dialog({
- title: ai.t("ai.change.title"),
- body: body,
- size: "lg",
- actions: [
- { label: t("ai.change.reject"), value: false, kind: "ghost" },
- { label: t(change.op === "delete" ? "ai.change.approve_delete" : "ai.change.approve"), value: true, kind: change.op === "delete" ? "danger" : "primary" }
- ]
- });
- return answer === true;
- }
-
- async function commit(change, ctx) {
- var approved = true;
- var prefix = ctx && ctx.autoApprovePrefix;
- var inSandbox = !!prefix && change.path.indexOf(prefix) === 0 && (!change.to || change.to.indexOf(prefix) === 0) && change.op !== "delete" && change.op !== "move";
- if (!inSandbox && needsApproval(change)) approved = await approve(change, ctx && ctx.reason);
- if (!approved) return { applied: false };
- var record = {
- id: "s" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
- at: Date.now(),
- runId: ctx && ctx.runId || null,
- op: change.op,
- path: change.path,
- to: change.to || null,
- before: change.before,
- after: change.after,
- undone: false
- };
- var info = {};
- if (change.op === "create" || change.op === "edit" || change.op === "overwrite") {
- if (change.op === "create") await io.ensureDir(util.dirname(change.path));
- info = await applyText(change.path, change.after);
- if (change.op === "create") await refreshTree([change.path]);
- } else if (change.op === "copy") {
- await io.ensureDir(util.dirname(change.to));
- await io.write(change.to, change.after);
- A.emit("saved", { path: change.to, name: util.basename(change.to) });
- await refreshTree([change.to]);
- } else if (change.op === "delete") {
- await io.remove(change.path);
- A.tabs.removePath(change.path);
- await refreshTree([change.path]);
- } else if (change.op === "move") {
- await io.move(change.path, change.to, "file");
- A.tabs.renamePath(change.path, change.to);
- await refreshTree([change.path, change.to]);
- }
- if (ai.get("snapshots")) {
- await loadSnaps();
- snaps.list.push(record);
- await saveSnaps();
- }
- var event = { record: record, info: info, diff: ai.get("diff") && change.op !== "move" ? unified(change.before, change.after, 200) : null };
- A.emit("ai-change", event);
- return { applied: true, record: record, info: info };
- }
-
- async function undo(id) {
- await loadSnaps();
- var rec = snaps.list.find(function (s) { return s.id === id; });
- if (!rec || rec.undone) return false;
- var conflict = false;
- if (rec.op === "create" || rec.op === "edit" || rec.op === "overwrite") {
- var now = (await io.exists(rec.path)) ? await textOf(rec.path) : null;
- conflict = now !== rec.after;
- } else if (rec.op === "copy") {
- var copied = (await io.exists(rec.to)) ? await textOf(rec.to) : null;
- conflict = copied !== rec.after;
- } else if (rec.op === "delete") {
- conflict = await io.exists(rec.path);
- } else if (rec.op === "move") {
- conflict = (await io.exists(rec.path)) || !(await io.exists(rec.to));
- }
- if (conflict && !(await A.ui.confirm(t("ai.change.undo"), t("ai.change.undo_conflict", { path: rec.path }), t("ai.change.undo_anyway"), true))) return false;
- if (rec.op === "create") {
- if (await io.exists(rec.path)) {
- await io.remove(rec.path);
- A.tabs.removePath(rec.path);
- }
- await refreshTree([rec.path]);
- } else if (rec.op === "edit" || rec.op === "overwrite") {
- await applyText(rec.path, rec.before);
- } else if (rec.op === "copy") {
- if (await io.exists(rec.to)) await io.remove(rec.to);
- A.tabs.removePath(rec.to);
- await refreshTree([rec.to]);
- } else if (rec.op === "delete") {
- await io.ensureDir(util.dirname(rec.path));
- await io.write(rec.path, rec.before);
- await refreshTree([rec.path]);
- } else if (rec.op === "move") {
- if (await io.exists(rec.to)) {
- await io.move(rec.to, rec.path, "file");
- A.tabs.renamePath(rec.to, rec.path);
- }
- await refreshTree([rec.path, rec.to]);
- }
- rec.undone = true;
- await saveSnaps();
- A.ui.toast(t("ai.change.undone", { path: rec.path }), "success");
- return true;
- }
-
- async function undoRun(runId) {
- await loadSnaps();
- var list = snaps.list.filter(function (s) { return s.runId === runId && !s.undone; }).reverse();
- var n = 0;
- for (var rec of list) if (await undo(rec.id)) n++;
- return n;
- }
-
- var TEMPLATE_KEYS = {
- "Summary.md": "ai.priv.tpl_summary",
- "Conversation.md": "ai.priv.tpl_conversation",
- "plan.md": "ai.priv.tpl_plan",
- "bugs.md": "ai.priv.tpl_bugs",
- "instructions.md": "ai.priv.tpl_instructions",
- "design.md": "ai.priv.tpl_design"
- };
-
- var HTACCESS = "<IfModule mod_authz_core.c>\n Require all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n Deny from all\n</IfModule>\n";
-
- var priv = (ai.private = {
- DIR: PRIVATE,
- FILES: PRIVATE_FILES,
- DIRS: PRIVATE_DIRS,
-
- path: function (name) {
- return PRIVATE + "/" + name;
- },
-
- memoryMode: function () {
- return !!A.fs.provider && A.fs.provider.kind === "memory";
- },
-
- exists: async function (name) {
- if (!A.fs.provider) return false;
- return io.exists(priv.path(name));
- },
-
- read: async function (name) {
- if (!A.fs.provider) return null;
- var p = priv.path(name);
- if (!(await io.exists(p))) return null;
- return io.read(p);
- },
-
- write: async function (name, text) {
- if (!(await priv.ensure())) return false;
- var p = priv.path(name);
- await io.ensureDir(util.dirname(p));
- var existed = await io.exists(p);
- await applyText(p, text);
- if (!existed) await refreshTree([p]);
- return true;
- },
-
- template: function (name) {
- return TEMPLATE_KEYS[name] ? ai.t(TEMPLATE_KEYS[name]) + "\n" : "";
- },
-
- ensure: async function () {
- provider();
- if (priv.memoryMode()) return true;
- if (await io.exists(PRIVATE)) {
- if (!(await io.exists(PRIVATE + "/.htaccess"))) await io.write(PRIVATE + "/.htaccess", HTACCESS);
- return true;
- }
- var addIgnore = false;
- if (!ai.get("privateWarned")) {
- var choice = await A.ui.dialog({
- title: ai.t("ai.priv.warn_title"),
- body: util.el("div", {}, [
- util.el("p", { class: "ath-dialog-text" }, ai.t("ai.priv.warn_text")),
- util.el("p", { class: "ath-set-hint" }, ai.t("ai.priv.warn_htaccess"))
- ]),
- actions: [
- { label: A.t("common.cancel"), value: null, kind: "ghost" },
- { label: ai.t("ai.priv.create_only"), value: "create", kind: "secondary" },
- { label: ai.t("ai.priv.create_ignore"), value: "ignore", kind: "primary" }
- ]
- });
- if (!choice) return false;
- ai.set("privateWarned", true);
- addIgnore = choice === "ignore";
- }
- await io.ensureDir(PRIVATE);
- await io.write(PRIVATE + "/.htaccess", HTACCESS);
- if (addIgnore) await priv.addToGitignore();
- await refreshTree([PRIVATE, PRIVATE + "/.htaccess"]);
- return true;
- },
-
- addToGitignore: async function () {
- var current = (await io.exists(".gitignore")) ? await io.read(".gitignore") : "";
- if (/^\/?\.private\/?\s*$/m.test(current)) return false;
- await applyText(".gitignore", current + (current && !/\n$/.test(current) ? "\n" : "") + ".private/\n");
- await refreshTree([".gitignore"]);
- return true;
- },
-
- create: async function (name) {
- if (await priv.exists(name)) return true;
- return priv.write(name, priv.template(name));
- },
-
- createDir: async function (dir) {
- if (!(await priv.ensure())) return false;
- var p = priv.path(dir);
- if (priv.memoryMode()) return true;
- await io.ensureDir(p);
- await refreshTree([p + "/x"]);
- return true;
- },
-
- status: async function () {
- var out = { files: {}, dirs: {}, memory: priv.memoryMode(), folder: !!A.fs.provider };
- if (!A.fs.provider) return out;
- for (var f of PRIVATE_FILES) out.files[f] = await io.exists(priv.path(f));
- for (var d of PRIVATE_DIRS) out.dirs[d] = await io.exists(priv.path(d));
- return out;
- }
- });
-
- function numbered(text, start, end) {
- var lines = text.split("\n");
- var from = Math.max(1, start || 1);
- var to = Math.min(lines.length, end || lines.length);
- var width = String(to).length;
- var out = [];
- var chars = 0;
- var cut = false;
- for (var i = from; i <= to; i++) {
- var row = (new Array(width + 1).join(" ") + i).slice(-width) + "| " + lines[i - 1];
- chars += row.length + 1;
- if (chars > READ_MAX || i - from >= READ_LINES) { cut = true; to = i - 1; break; }
- out.push(row);
- }
- return { text: out.join("\n"), from: from, to: to, total: lines.length, cut: cut };
- }
-
- function nearby(text, old) {
- var lines = text.split("\n");
- var firstLine = String(old).split("\n").map(function (l) { return l.trim(); }).find(Boolean) || "";
- var best = -1, bestScore = 0;
- var words = (firstLine.toLowerCase().match(/[\p{L}\p{N}_-]{2,}/gu) || []).filter(function (w, i, all) { return all.indexOf(w) === i; });
- lines.forEach(function (l, i) {
- var lower = l.toLowerCase();
- var score = l.trim() === firstLine ? 100 : words.reduce(function (n, w) { return n + (lower.indexOf(w) >= 0 ? 1 : 0); }, 0);
- if (score > bestScore) { bestScore = score; best = i; }
- });
- if (best < 0) return null;
- return numbered(text, Math.max(1, best + 1 - 3), Math.min(lines.length, best + 1 + 6)).text;
- }
-
- function countOccurrences(text, needle) {
- if (!needle) return 0;
- var n = 0, i = 0;
- while ((i = text.indexOf(needle, i)) >= 0) { n++; i += needle.length; }
- return n;
- }
-
- function globRe(glob) {
- var src = String(glob).split("").map(function (c) {
- if (c === "*") return "[^/]*";
- if (c === "?") return "[^/]";
- return c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
- }).join("").replace(/\[\^\/\]\*\[\^\/\]\*/g, ".*");
- return new RegExp((glob.indexOf("/") >= 0 ? "^" : "(?:^|/)") + src + "$", "i");
- }
-
- function outline(path, text) {
- var ext = util.ext(path);
- var lines = text.split("\n");
- var items = [];
- function add(i, label) { if (items.length < 60) items.push((i + 1) + ": " + label.trim().slice(0, 120)); }
- lines.forEach(function (line, i) {
- var m;
- if (/^(html?|php|phtml|inc|twig|tpl|svg|vue)$/.test(ext)) {
- if ((m = /<(h[1-6])[^>]*>([^<]{1,100})/i.exec(line))) add(i, m[1] + " " + m[2]);
- else if ((m = /<title>([^<]{1,100})/i.exec(line))) add(i, "title " + m[1]);
- else if ((m = /<(header|nav|main|section|article|aside|footer|form|dialog|table)\b[^>]*?(?:\b(?:id|class)="([^"]{1,60})")?/i.exec(line))) add(i, "<" + m[1] + (m[2] ? " " + m[2] : "") + ">");
- else if ((m = /\bid="([^"]{1,60})"/.exec(line))) add(i, "#" + m[1]);
- else if ((m = /<(?:script|link)\b[^>]*(?:src|href)="([^"]{1,100})"/i.exec(line))) add(i, "asset " + m[1]);
- if (ext !== "html" && ext !== "htm" && (m = /\b(function|class)\s+(\w+)/.exec(line))) add(i, m[1] + " " + m[2]);
- if ((m = /\b(require|include)(?:_once)?\s*\(?\s*['"]([^'"]+)/.exec(line))) add(i, m[1] + " " + m[2]);
- } else if (/^(css|scss|sass|less)$/.test(ext)) {
- if ((m = /^\s{0,2}(@media[^{]+|@supports[^{]+|@keyframes\s+\S+|:root|[^@\s][^{;]{0,80})\s*\{/.exec(line))) add(i, m[1]);
- } else if (/^(js|mjs|cjs|ts|jsx|tsx)$/.test(ext)) {
- if ((m = /\b(?:async\s+)?function\s*\*?\s*(\w+)/.exec(line))) add(i, "function " + m[1]);
- else if ((m = /\bclass\s+(\w+)/.exec(line))) add(i, "class " + m[1]);
- else if ((m = /^\s*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?(?:\([^)]*\)|\w+)\s*=>/.exec(line))) add(i, "function " + m[1]);
- else if ((m = /addEventListener\(\s*['"](\w+)/.exec(line))) add(i, "on " + m[1]);
- } else if (/^(md|markdown)$/.test(ext)) {
- if ((m = /^(#{1,4})\s+(.+)/.exec(line))) add(i, m[1] + " " + m[2]);
- } else if (ext === "sql") {
- if ((m = /\b(create\s+table|create\s+view)\s+[`"]?(\w+)/i.exec(line))) add(i, m[1] + " " + m[2]);
- }
- });
- return items;
- }
-
- async function walk(dir, depth, out, includePrivate) {
- if (out.length >= LIST_MAX) return;
- var entries;
- try { entries = await io.list(dir); } catch (e) { return; }
- for (var e of entries) {
- if (out.length >= LIST_MAX) return;
- var p = util.join(dir, e.name);
- if (e.kind === "dir") {
- if (A.fs.HIDDEN_DIRS.indexOf(e.name) >= 0) continue;
- if (!dir && e.name === PRIVATE && !includePrivate) {
- out.push(p + "/ " + t("ai.tool.private_marker"));
- continue;
- }
- out.push(p + "/");
- if (depth > 1) await walk(p, depth - 1, out, includePrivate);
- } else {
- if (A.fs.HIDDEN_FILES.indexOf(e.name) >= 0) continue;
- out.push(p + (ai.isExcluded(p) ? " " + t("ai.tool.excluded_marker") : ""));
- }
- }
- }
-
- function wrapData(source, text) {
- return "[" + t("ai.tool.data_header", { source: source }) + "]\n" + text;
- }
-
- function hide(text, path) {
- return ai.redact ? ai.redact.apply(text, path).text : text;
- }
-
- function hostOf(url) {
- try {
- var u = new URL(url);
- if (!/^https?:$/.test(u.protocol)) return null;
- return u.hostname.toLowerCase();
- } catch (e) {
- return null;
- }
- }
-
- function domainAllowed(host) {
- var match = function (d) { return host === d || host.slice(-(d.length + 1)) === "." + d; };
- if (ai.domains("deny").some(match)) return false;
- var allow = ai.domains("allow");
- return !allow.length || allow.some(match);
- }
-
- function htmlToMarkdown(html, base) {
- var doc = new DOMParser().parseFromString(html, "text/html");
- doc.querySelectorAll("script, style, noscript, iframe, svg, nav, footer, header, form, button, template").forEach(function (n) { n.remove(); });
- var root = doc.querySelector("main, article, [role=main]") || doc.body || doc.documentElement;
- function abs(href) {
- try { return new URL(href, base).href; } catch (e) { return href; }
- }
- function walkNode(node, list) {
- if (node.nodeType === 3) return node.nodeValue.replace(/\s+/g, " ");
- if (node.nodeType !== 1) return "";
- var tag = node.tagName.toLowerCase();
- var inner = function () { return Array.prototype.map.call(node.childNodes, function (c) { return walkNode(c, list); }).join(""); };
- if (/^h[1-6]$/.test(tag)) return "\n\n" + new Array(Number(tag[1]) + 1).join("#") + " " + inner().trim() + "\n\n";
- if (tag === "p" || tag === "div" || tag === "section") return "\n\n" + inner().trim() + "\n\n";
- if (tag === "br") return "\n";
- if (tag === "pre") return "\n\n```\n" + node.textContent.replace(/\n+$/, "") + "\n```\n\n";
- if (tag === "code") return "`" + node.textContent + "`";
- if (tag === "strong" || tag === "b") return "**" + inner().trim() + "**";
- if (tag === "em" || tag === "i") return "*" + inner().trim() + "*";
- if (tag === "a") {
- var href = node.getAttribute("href");
- var label = inner().trim();
- return href && label ? "[" + label + "](" + abs(href) + ")" : label;
- }
- if (tag === "img") return node.getAttribute("alt") ? "![" + node.getAttribute("alt") + "]" : "";
- if (tag === "ul" || tag === "ol") {
- var ordered = tag === "ol";
- return "\n\n" + Array.prototype.filter.call(node.children, function (c) { return c.tagName === "LI"; }).map(function (li, i) {
- return (ordered ? (i + 1) + ". " : "- ") + walkNode(li, list).trim();
- }).join("\n") + "\n\n";
- }
- if (tag === "tr") return "| " + Array.prototype.map.call(node.children, function (c) { return walkNode(c, list).trim().replace(/\|/g, "\\|"); }).join(" | ") + " |\n";
- if (tag === "table") return "\n\n" + inner() + "\n\n";
- return inner();
- }
- return walkNode(root, []).replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
- }
-
- function slug(text) {
- return String(text || "page").toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "")
- .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "page";
- }
-
- var TOOLS = [
- {
- name: "list_files",
- perm: "read",
- description: "List files and folders in the open project. Use a small depth first and go deeper only where needed.",
- parameters: { type: "object", properties: {
- dir: { type: "string", description: "Folder relative to the project root, empty for the root." },
- depth: { type: "integer", description: "How many folder levels to list (1-6, default 2)." }
- } },
- run: async function (args) {
- var dir = cleanPath(args.dir, true);
- var depth = Math.max(1, Math.min(6, Number(args.depth) || 2));
- if (dir && (await io.kind(dir)) !== "dir") throw toolError("ai.tool.err_not_dir", { path: dir });
- var out = [];
- await walk(dir, depth, out, isPrivate(dir) || ai.get("privateIndex"));
- if (out.length >= LIST_MAX) out.push(t("ai.tool.list_cut", { n: LIST_MAX }));
- return out.length ? out.join("\n") : t("ai.tool.list_empty");
- }
- },
- {
- name: "read_file",
- perm: "read",
- description: "Read a text file. Lines are prefixed with their number and \"| \"; that prefix is not part of the file. Large files are cut: request a range with start_line/end_line. Prefer search_files or file_outline to find the right range first.",
- parameters: { type: "object", properties: {
- path: { type: "string", description: "File path relative to the project root." },
- start_line: { type: "integer", description: "First line to read (1-based)." },
- end_line: { type: "integer", description: "Last line to read (inclusive)." }
- }, required: ["path"] },
- run: async function (args) {
- var p = guardRead(args.path);
- var text = hide(await textOf(p), p);
- var r = numbered(text, Number(args.start_line) || 1, Number(args.end_line) || 0);
- var head = t("ai.tool.read_head", { path: p, from: r.from, to: r.to, total: r.total });
- var tail = r.cut || r.to < r.total ? "\n" + t("ai.tool.read_cut", { next: r.to + 1, total: r.total }) : "";
- return wrapData(p, head + "\n" + r.text + tail);
- }
- },
- {
- name: "file_outline",
- perm: "read",
- description: "Get a compact outline of a file (headings, ids, sections, functions, CSS selectors) with line numbers. Cheaper than reading the whole file.",
- parameters: { type: "object", properties: { path: { type: "string" } }, required: ["path"] },
- run: async function (args) {
- var p = guardRead(args.path);
- var text = await textOf(p);
- var items = outline(p, text).map(function (line) { return hide(line, p); });
- return wrapData(p, t("ai.tool.outline_head", { path: p, total: text.split("\n").length }) + "\n" + (items.length ? items.join("\n") : t("ai.tool.outline_empty")));
- }
- },
- {
- name: "search_files",
- perm: "read",
- description: "Search the text of project files. Returns matching lines as path:line: text. Use it to find where something is defined before reading.",
- parameters: { type: "object", properties: {
- query: { type: "string", description: "Text to find (case-insensitive) or a regular expression when regex is true." },
- regex: { type: "boolean" },
- glob: { type: "string", description: "Optional file name filter, e.g. *.css or pages/*.php." },
- max_results: { type: "integer" }
- }, required: ["query"] },
- run: async function (args) {
- var query = String(args.query || "");
- if (!query) throw toolError("ai.tool.err_query");
- var re;
- try {
- re = args.regex ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
- } catch (e) {
- throw toolError("ai.tool.err_regex", { message: e.message });
- }
- var filter = args.glob ? globRe(args.glob) : null;
- var max = Math.max(1, Math.min(SEARCH_MAX, Number(args.max_results) || 50));
- var files = (await A.fs.allFiles()).filter(function (p) {
- return !A.fs.isBinary(p) && !ai.isExcluded(p) && (!filter || filter.test(p));
- }).slice(0, SEARCH_FILES);
- var out = [];
- for (var p of files) {
- if (out.length >= max) break;
- var text;
- try {
- var tab = A.tabs.byPath(p);
- if (tab && tab.kind === "text") text = A.tabs.textOf(tab);
- else {
- var file = await provider().readFile(p);
- if (file.size > SEARCH_FILE_MAX) continue;
- text = await file.text();
- }
- } catch (e) { continue; }
- var lines = text.split("\n");
- for (var i = 0; i < lines.length && out.length < max; i++) {
- if (re.test(lines[i])) out.push(p + ":" + (i + 1) + ": " + hide(lines[i].trim(), p).slice(0, 200));
- }
- }
- if (!out.length) return t("ai.tool.search_none", { query: query });
- var joined = out.join("\n");
- return wrapData(t("ai.tool.search_source"), joined + (out.length >= max ? "\n" + t("ai.tool.search_cut", { n: max }) : ""));
- }
- },
- {
- name: "create_file",
- perm: "write",
- description: "Create a new text file. Fails if the file already exists (use edit_file for changes). Parent folders are created automatically.",
- parameters: { type: "object", properties: {
- path: { type: "string" },
- content: { type: "string" }
- }, required: ["path", "content"] },
- run: async function (args, ctx) {
- var p = guardWrite(args.path);
- var content = String(args.content == null ? "" : args.content);
- if (content.length > WRITE_MAX) throw toolError("ai.tool.err_too_big", { max: Math.round(WRITE_MAX / 1024) });
- if (await io.exists(p)) throw toolError("ai.tool.err_exists", { path: p });
- if (isPrivate(p) && !(await priv.ensure())) throw toolError("ai.tool.err_private_declined");
- var r = await commit({ op: "create", path: p, before: null, after: content, private: isPrivate(p) }, ctx);
- if (!r.applied) return { content: t("ai.tool.rejected", { path: p }), isError: true };
- return t("ai.tool.created", { path: p, lines: content.split("\n").length }) + memoryNote(p, r);
- }
- },
- {
- name: "edit_file",
- perm: "write",
- description: "Edit a file with exact text replacements. Each edit's \"old\" must appear exactly once in the current file (copy it exactly, without line-number prefixes, with enough surrounding lines to be unique). All edits are applied together or not at all. Prefer several small edits over rewriting.",
- parameters: { type: "object", properties: {
- path: { type: "string" },
- edits: { type: "array", items: { type: "object", properties: {
- old: { type: "string", description: "Exact current text to replace." },
- new: { type: "string", description: "Replacement text." }
- }, required: ["old", "new"] } }
- }, required: ["path", "edits"] },
- run: async function (args, ctx) {
- var p = guardWrite(args.path);
- if (!(await io.exists(p))) throw toolError("ai.tool.err_not_found", { path: p });
- var edits = Array.isArray(args.edits) ? args.edits : [];
- if (!edits.length) throw toolError("ai.tool.err_no_edits");
- var before = await textOf(p);
- var after = before;
- for (var i = 0; i < edits.length; i++) {
- var old = String(edits[i].old == null ? "" : edits[i].old);
- var rep = String(edits[i].new == null ? "" : edits[i].new);
- if (!old) throw toolError("ai.tool.err_old_empty", { n: i + 1 });
- var count = countOccurrences(after, old);
- if (count !== 1) {
- var near = ai.allowed("read") && count === 0 ? nearby(after, old) : null;
- if (near) near = hide(near, p);
- var key = count === 0 ? "ai.tool.err_old_missing" : "ai.tool.err_old_many";
- return { content: t(key, { n: i + 1, count: count, path: p }) + (near ? "\n" + t("ai.tool.nearby") + "\n" + near : ""), isError: true };
- }
- after = after.replace(old, function () { return rep; });
- }
- if (after === before) return t("ai.tool.no_change", { path: p });
- if (after.length > WRITE_MAX) throw toolError("ai.tool.err_too_big", { max: Math.round(WRITE_MAX / 1024) });
- var r = await commit({ op: "edit", path: p, before: before, after: after, private: isPrivate(p) }, ctx);
- if (!r.applied) return { content: t("ai.tool.rejected", { path: p }), isError: true };
- var s = diffStats(diffLines(before, after));
- return t("ai.tool.edited", { path: p, add: s.add, del: s.del }) + memoryNote(p, r);
- }
- },
- {
- name: "overwrite_file",
- perm: "write",
- description: "Replace the whole content of an existing file. Only for small files (under about 8 KB) or when the user explicitly asked for a full rewrite (set user_requested). For other changes use edit_file.",
- parameters: { type: "object", properties: {
- path: { type: "string" },
- content: { type: "string" },
- user_requested: { type: "boolean", description: "True only if the user explicitly asked to rewrite the whole file." }
- }, required: ["path", "content"] },
- run: async function (args, ctx) {
- var p = guardWrite(args.path);
- if (!(await io.exists(p))) throw toolError("ai.tool.err_not_found", { path: p });
- var before = await textOf(p);
- var content = String(args.content == null ? "" : args.content);
- if (content.length > WRITE_MAX) throw toolError("ai.tool.err_too_big", { max: Math.round(WRITE_MAX / 1024) });
- var large = before.length > OVERWRITE_FREE;
- if (large && !args.user_requested) return { content: t("ai.tool.err_overwrite_large", { path: p, size: Math.round(before.length / 1024) }), isError: true };
- var r = await commit({ op: "overwrite", path: p, before: before, after: content, private: isPrivate(p), large: large }, ctx);
- if (!r.applied) return { content: t("ai.tool.rejected", { path: p }), isError: true };
- return t("ai.tool.overwritten", { path: p }) + memoryNote(p, r);
- }
- },
- {
- name: "delete_file",
- perm: "write",
- description: "Delete a file. The user always has to confirm.",
- parameters: { type: "object", properties: { path: { type: "string" }, reason: { type: "string" } }, required: ["path"] },
- run: async function (args, ctx) {
- var p = guardWrite(args.path);
- if ((await io.kind(p)) !== "file") throw toolError("ai.tool.err_not_found", { path: p });
- var before = await textOf(p);
- var r = await commit({ op: "delete", path: p, before: before, after: null, private: isPrivate(p) }, Object.assign({}, ctx, { reason: args.reason }));
- if (!r.applied) return { content: t("ai.tool.rejected", { path: p }), isError: true };
- return t("ai.tool.deleted", { path: p });
- }
- },
- {
- name: "move_file",
- perm: "write",
- description: "Move or rename a file. The user always has to confirm.",
- parameters: { type: "object", properties: { from: { type: "string" }, to: { type: "string" }, reason: { type: "string" } }, required: ["from", "to"] },
- run: async function (args, ctx) {
- var from = guardWrite(args.from);
- var to = guardWrite(args.to);
- if ((await io.kind(from)) !== "file") throw toolError("ai.tool.err_not_found", { path: from });
- if (await io.exists(to)) throw toolError("ai.tool.err_exists", { path: to });
- var text = await textOf(from);
- var r = await commit({ op: "move", path: from, to: to, before: text, after: text, private: isPrivate(from) || isPrivate(to) }, Object.assign({}, ctx, { reason: args.reason }));
- if (!r.applied) return { content: t("ai.tool.rejected", { path: from }), isError: true };
- return t("ai.tool.moved", { from: from, to: to });
- }
- },
- {
- name: "copy_file",
- perm: "write",
- description: "Copy a text file, for example into .private/sandbox/ to experiment without touching the original.",
- parameters: { type: "object", properties: { from: { type: "string" }, to: { type: "string" } }, required: ["from", "to"] },
- run: async function (args, ctx) {
- var from = guardRead(args.from);
- var to = guardWrite(args.to);
- if ((await io.kind(from)) !== "file") throw toolError("ai.tool.err_not_found", { path: from });
- if (await io.exists(to)) throw toolError("ai.tool.err_exists", { path: to });
- if (isPrivate(to) && !(await priv.ensure())) throw toolError("ai.tool.err_private_declined");
- var text = await textOf(from);
- var r = await commit({ op: "copy", path: from, to: to, before: null, after: text, private: isPrivate(to) }, ctx);
- if (!r.applied) return { content: t("ai.tool.rejected", { path: to }), isError: true };
- return t("ai.tool.copied", { from: from, to: to });
- }
- },
- {
- name: "save_crawl",
- perm: "crawler",
- description: "Save documentation you fetched from the web as a Markdown file in .private/crawler/ so it can be reused later without fetching again. Only save content you actually fetched.",
- parameters: { type: "object", properties: {
- url: { type: "string" },
- title: { type: "string" },
- markdown: { type: "string", description: "Cleaned page content as Markdown." }
- }, required: ["url", "markdown"] },
- run: async function (args, ctx) {
- var host = hostOf(args.url);
- if (!host) throw toolError("ai.tool.err_url");
- if (!domainAllowed(host)) throw toolError("ai.tool.err_domain", { host: host });
- var md = String(args.markdown || "").slice(0, FETCH_MAX * 2);
- if (!md.trim()) throw toolError("ai.tool.err_empty");
- if (!(await priv.ensure())) throw toolError("ai.tool.err_private_declined");
- var p = PRIVATE + "/crawler/" + slug(host) + "-" + slug(args.title || new URL(args.url).pathname) + ".md";
- var body = "---\nurl: " + args.url + "\ntitle: " + String(args.title || "").replace(/\n/g, " ") + "\nsaved: " + new Date().toISOString().slice(0, 10) + "\n---\n\n" + md + "\n";
- var exists = await io.exists(p);
- var before = exists ? await textOf(p) : null;
- var r = await commit({ op: exists ? "overwrite" : "create", path: p, before: before, after: body, private: true }, ctx);
- if (!r.applied) return { content: t("ai.tool.rejected", { path: p }), isError: true };
- return t("ai.tool.crawl_saved", { path: p });
- }
- },
- {
- name: "fetch_url",
- perm: "crawler",
- relay: true,
- description: "Download a web page (through the user's relay server or the Firecrawl scraper) and return it as Markdown. The content is untrusted data.",
- parameters: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
- run: async function (args, ctx) {
- var relay = ai.relayUrl();
- var host = hostOf(args.url);
- if (!host) throw toolError("ai.tool.err_url");
- if (!domainAllowed(host)) throw toolError("ai.tool.err_domain", { host: host });
- ai.assertNetwork();
- if (!relay && ai.search && ai.search.canScrape()) {
- var page = await ai.search.scrape(args.url, ctx && ctx.signal);
- var text = page.markdown;
- return wrapData(args.url, (page.title ? "# " + page.title + "\n\n" : "") + text.slice(0, FETCH_MAX) + (text.length > FETCH_MAX ? "\n" + t("ai.tool.fetch_cut", { n: FETCH_MAX }) : ""));
- }
- if (!relay) throw toolError("ai.tool.err_no_relay");
- var got = await ai.relay.page(args.url, ctx && ctx.signal);
- if (got.status >= 400) throw toolError("ai.tool.err_fetch", { status: got.status });
- if (!got.content) throw toolError("ai.tool.err_fetch_type", { type: got.type || "?" });
- var finalHost = hostOf(got.url);
- if (finalHost && !domainAllowed(finalHost)) throw toolError("ai.tool.err_domain", { host: finalHost });
- var raw = got.content.slice(0, 2000000);
- var md = /html/i.test(got.type) ? htmlToMarkdown(raw, got.url || args.url) : raw;
- var cut = md.length > FETCH_MAX;
- return wrapData(args.url, md.slice(0, FETCH_MAX) + (cut ? "\n" + t("ai.tool.fetch_cut", { n: FETCH_MAX }) : ""));
- }
- }
- ];
-
- function memoryNote(path, r) {
- var notes = "";
- if (r.info && r.info.tab && !r.info.disk) notes += " " + t("ai.tool.note_dirty_tab");
- if (A.fs.provider && A.fs.provider.kind === "memory" && !isPrivate(path)) notes += " " + t("ai.tool.note_memory");
- return notes;
- }
-
- var RESTORES = { create_file: 1, edit_file: 1, overwrite_file: 1, search_files: 1 };
-
- var tools = (ai.tools = {
- io: io,
- cleanPath: cleanPath,
- guardRead: guardRead,
- guardWrite: guardWrite,
- isPrivate: isPrivate,
- outline: outline,
- numbered: numbered,
- diffLines: diffLines,
- unified: unified,
- diffView: diffView,
- htmlToMarkdown: htmlToMarkdown,
- commit: commit,
- undo: undo,
- undoRun: undoRun,
-
- register: function (def) {
- var i = TOOLS.findIndex(function (x) { return x.name === def.name; });
- if (i >= 0) TOOLS[i] = def;
- else TOOLS.push(def);
- },
-
- available: function () {
- return TOOLS.filter(function (tool) {
- if (!ai.allowed(tool.perm)) return false;
- if (tool.perm === "write" && !ai.allowed("read")) return false;
- if (tool.gate && !tool.gate()) return false;
- var scraper = !!ai.search && ai.search.canScrape();
- if (tool.relay && !ai.relayUrl() && !scraper) return false;
- if (tool.name === "save_crawl" && !ai.allowed("web") && !ai.relayUrl() && !scraper) return false;
- return true;
- }).map(function (tool) {
- return { name: tool.name, description: tool.description, parameters: tool.parameters };
- });
- },
-
- run: async function (call, ctx) {
- var tool = TOOLS.find(function (x) { return x.name === call.name; });
- if (!tool) return { content: t("ai.tool.err_unknown", { name: call.name }), isError: true };
- if (!ai.allowed(tool.perm)) return { content: t("ai.tool.err_perm", { name: call.name }), isError: true };
- if (call.invalid) return { content: t("ai.tool.err_json"), isError: true };
- if (tool.folder !== false && !A.fs.provider && tool.perm !== "crawler") return { content: t("ai.tool.err_no_folder"), isError: true };
- var input = call.input || {};
- if (ai.redact && RESTORES[tool.name]) {
- var restored = ai.redact.restoreArgs(input);
- if (restored.missing.length) return { content: t("ai.redact.err_missing", { ids: restored.missing.join(", ") }), isError: true };
- input = restored.input;
- }
- try {
- var out = await tool.run(input, ctx || {});
- return typeof out === "string" ? { content: out, isError: false } : out;
- } catch (e) {
- if (e.name === "AbortError") throw e;
- if (!e.tool) console.error(e);
- return { content: e.message || String(e), isError: true };
- }
- },
-
- snapshots: async function () {
- return (await loadSnaps()).slice().reverse();
- },
-
- clearSnapshots: async function () {
- await loadSnaps();
- snaps.list = [];
- await saveSnaps();
- },
-
- projectOutline: async function (maxChars) {
- if (!A.fs.provider) return "";
- maxChars = maxChars || 6000;
- var files = (await A.fs.allFiles()).filter(function (p) { return !ai.isExcluded(p); });
- var lines = [t("ai.tool.project_head", { name: A.fs.provider.name, n: files.length })];
- files.slice(0, 250).forEach(function (p) { lines.push("- " + p); });
- if (files.length > 250) lines.push(t("ai.tool.list_cut", { n: 250 }));
- var key = files.filter(function (p) {
- return /^(index|home|main|style|styles|app|script|functions|config)\.(html?|php|css|js)$/i.test(util.basename(p)) && p.split("/").length <= 2;
- }).slice(0, 8);
- var text = lines.join("\n");
- for (var p of key) {
- if (text.length > maxChars) break;
- try {
- var items = outline(p, await textOf(p)).slice(0, 25);
- if (items.length) text += "\n\n" + t("ai.tool.outline_head", { path: p, total: "?" }) + "\n" + items.join("\n");
- } catch (e) { }
- }
- return text.slice(0, maxChars);
- }
- });
-
- A.on("workspace", function () {
- mem = null;
- snaps = { key: null, list: [] };
- A.emit("ai-changes", 0);
- });
- })();
-