openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
336 lines (335 loc) • 16.7 kB
JavaScript
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { f as syncDirectoryIfSupported, o as publishFileNoClobber } from "./directory-durability-DlnWwNmv.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { o as DEFAULT_TOOLS_FILENAME, t as DEFAULT_AGENTS_FILENAME } from "./workspace-bootstrap-policy-D7EJ00Ub.mjs";
import "./workspace-DLlXz3VE.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { i as resolveBootstrapMaxChars } from "./bootstrap-BoYamcpL.mjs";
import { t as noteDoctorMigrationResult } from "./doctor-migration-notes-BBiomgyk.mjs";
import fs from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
import { readRegularFile } from "@openclaw/fs-safe/advanced";
import { isUtf8 } from "node:buffer";
//#region src/commands/doctor-tools-md-migration.ts
/** Doctor-owned migration from workspace TOOLS.md into the AGENTS.md Tools section. */
const MIGRATED_SUBSECTION_HEADING = "### Local notes (migrated from TOOLS.md)";
const NO_CLOBBER_PUBLICATION = {
strategy: "link-or-copy",
durability: "degrade"
};
const LEGACY_TOOLS_MD_TEMPLATE = "# TOOLS.md - Local Notes\n\nSkills define _how_ tools work. This file is for _your_ specifics — the stuff that's unique to your setup: camera names and locations, SSH hosts and aliases, preferred TTS voices, speaker/room names, device nicknames, anything environment-specific.\n\n## Examples\n\n```markdown\n### Cameras\n\n- living-room → Main area, 180° wide angle\n- front-door → Entrance, motion-triggered\n\n### SSH\n\n- home-server → 192.168.1.100, user: admin\n\n### TTS\n\n- Preferred voice: \"Nova\" (warm, slightly British)\n- Default speaker: Kitchen HomePod\n```\n\n## Why Separate?\n\nSkills are shared. Your setup is yours. Keeping them apart means you can update skills without losing your notes, and share skills without leaking your infrastructure.\n\n---\n\nAdd whatever helps you do your job. This is your cheat sheet.\n\n## Related\n\n- [Agent workspace](/concepts/agent-workspace)\n";
const LEGACY_TOOLS_DEV_MD_TEMPLATE = "# TOOLS.md - User Tool Notes (editable)\n\nThis file is for _your_ notes about external tools and conventions. It does not define which tools exist; OpenClaw provides built-in tools internally, and skills add the rest.\n\n## Examples\n\n### imsg\n\n- Send an iMessage/SMS: describe who/what, confirm before sending.\n- Prefer short messages; avoid sending secrets.\n\n### sag\n\n- Text-to-speech: specify voice, target speaker/room, and whether to stream.\n\nAdd whatever else you want the assistant to know about your local toolchain.\n\n## Related\n\n- [TOOLS.md template](/reference/templates/TOOLS)\n";
const LEGACY_TOOLS_DEV_FALLBACK = "# TOOLS.md - User Tool Notes (editable)\n\nAdd your local tool notes here.\n";
function shouldMergeToolsMd(e) {
return e.trim().length > 0 && e !== LEGACY_TOOLS_MD_TEMPLATE && e !== LEGACY_TOOLS_DEV_MD_TEMPLATE && e !== LEGACY_TOOLS_DEV_FALLBACK;
}
const LEGACY_AGENTS_TOOLS_GUIDANCE_REWRITES = [
["Skills provide your tools. When you need one, check its `SKILL.md`. Keep local notes (camera names, SSH details, voice preferences) in `TOOLS.md`.", "Skills define how tools work. Keep environment-specific local notes in this section."],
["- Keep environment-specific notes in `TOOLS.md` (notes for skills).", "- Keep environment-specific notes in this file's `## Tools` section."],
["- Keep environment-specific notes in `TOOLS.md` (Notes for Skills).", "- Keep environment-specific notes in this file's `## Tools` section."],
["- You learn a lesson -> update `AGENTS.md`, `TOOLS.md`, or the relevant skill.", "- You learn a lesson -> update `AGENTS.md` or the relevant skill."],
["- When you learn a lesson → update AGENTS.md, TOOLS.md, or the relevant skill", "- When you learn a lesson → update AGENTS.md or the relevant skill"],
["Skills 提供你的工具。当你需要某个工具时,查看它的 `SKILL.md`。在 `TOOLS.md` 中保存本地笔记(摄像头名称、SSH 详情、语音偏好等)。", "Skills 定义工具的使用方式。请将环境特定的本地笔记保存在本节中。"],
["技能提供你的工具。当你需要某个工具时,查看它的 `SKILL.md`。在 `TOOLS.md` 中保存本地笔记(摄像头名称、SSH 详情、语音偏好等)。", "技能定义工具的使用方式。请将环境特定的本地笔记保存在本节中。"],
["- 在 `TOOLS.md` 中保存环境特定的笔记(Skills 注意事项)。", "- 将环境特定的笔记保存在本文件的 `## Tools` 部分。"],
["- 将环境相关的备注保存在 `TOOLS.md`(Skills 备注)中。", "- 将环境相关的备注保存在本文件的 `## Tools` 部分。"],
["- 将环境相关的备注保存在 `TOOLS.md`(技能备注)中。", "- 将环境相关的备注保存在本文件的 `## Tools` 部分。"],
["- 当你学到教训 → 更新 AGENTS.md、TOOLS.md 或相关 Skills 文件", "- 当你学到教训 → 更新 AGENTS.md 或相关 Skills 文件"],
["- 当你学到教训 → 更新 AGENTS.md、TOOLS.md 或相关技能文件", "- 当你学到教训 → 更新 AGENTS.md 或相关技能文件"]
];
function resolveToolsMdMigrationWorkspaceTargets(e) {
const t = /* @__PURE__ */ new Map();
for (const n of listAgentIds(e)) {
const r = resolveAgentWorkspaceDir(e, n);
const i = path.resolve(r);
const a = t.get(i) ?? {
primaryAgentId: n,
agentIds: [],
workspaceDir: r
};
a.agentIds.push(n);
t.set(i, a);
}
return [...t.values()];
}
function sameFileIdentity$1(e, t) {
return e?.dev === t?.dev && e?.ino === t?.ino;
}
function samePosixPermissions(e, t) {
return e.uid === t.uid && e.gid === t.gid && (e.mode & 4095) === (t.mode & 4095);
}
function addsPosixReaders(e, t) {
for (const n of /* @__PURE__ */ new Set([
e.uid,
t.uid,
void 0
])) for (const r of [false, true]) for (const i of [false, true]) {
if (e.gid === t.gid && r !== i) continue;
const a = n === e.uid ? 256 : r ? 32 : 4;
const o = n === t.uid ? 256 : i ? 32 : 4;
if ((t.mode & o) !== 0 && (e.mode & a) === 0) return true;
}
return false;
}
async function assertSourceReadersPreserved(e, t) {
const n = await readMigrationFileSnapshot(e.path);
if (n.content !== e.content || !n.stat || !sameFileIdentity$1(n.stat, e.stat) || !samePosixPermissions(n.stat, e.stat)) throw new Error("TOOLS.md changed during migration");
if (addsPosixReaders(n.stat, t)) throw new Error("Merging TOOLS.md would grant additional POSIX readers. Review both files' owners, groups, and read permissions before rerunning doctor.");
}
async function readMigrationFileSnapshot(e, t = false) {
let n;
try {
n = await fs$1.lstat(e);
} catch (e) {
if (t && e.code === "ENOENT") return { content: "" };
throw e;
}
if (!n.isFile() || n.nlink > 1) throw new Error(`${path.basename(e)} must be an unlinked regular file for automatic migration`);
const r = await readRegularFile({ filePath: e });
const i = await fs$1.lstat(e);
if (r.stat.nlink !== 1 || !sameFileIdentity$1(r.stat, n) || !sameFileIdentity$1(i, r.stat)) throw new Error(`${path.basename(e)} changed while opening it for migration`);
if (!isUtf8(r.buffer)) throw new Error(`File is not valid UTF-8: ${e}; preserve its bytes and convert a copy to UTF-8 before retrying`);
return {
content: r.buffer.toString("utf8"),
stat: i
};
}
async function readToolsMd(e) {
const t = (await fs$1.readdir(e).catch(() => [])).filter((e) => e.startsWith(`${"TOOLS.md"}.doctor-importing-`) || e.startsWith(`${"AGENTS.md"}.doctor-backup-`));
if (t.length > 0) throw new Error(`Interrupted v2026.7.2-beta.5 migration artifact(s) left untouched: ${t.join(", ")}. Restore the desired file manually before rerunning doctor.`);
const n = path.join(e, DEFAULT_TOOLS_FILENAME);
const r = await readMigrationFileSnapshot(n, true);
if (!r.stat) return;
return {
path: n,
content: r.content,
sha256: sha256Hex(r.content),
stat: r.stat
};
}
function appendWithSpacing(e, t, n = "") {
const spacing = (e) => e.endsWith("\n\n") ? "" : e.endsWith("\n") ? "\n" : "\n\n";
return `${e}${e.length === 0 ? "" : spacing(e)}${t}${n.length === 0 ? "" : spacing(t)}${n}`;
}
function mergeToolsMdIntoAgentsMd(e, t) {
const n = rewriteLegacyAgentsToolsGuidance(e);
const r = n.indexOf(MIGRATED_SUBSECTION_HEADING);
if (r >= 0 && n.includes(t)) return n;
const i = r >= 0 ? t : `${MIGRATED_SUBSECTION_HEADING}\n\n${t}`;
const a = r >= 0 ? r + 40 : findToolsSection(n)?.insertAt;
if (a === void 0) return appendWithSpacing(n, `## Tools\n\n${i}`);
return appendWithSpacing(n.slice(0, a), i, n.slice(a));
}
function rewriteLegacyAgentsToolsGuidance(e) {
let t = e;
for (const [e, n] of LEGACY_AGENTS_TOOLS_GUIDANCE_REWRITES) t = t.replaceAll(e, n);
return t === e ? e : ensureLocalNotesHeading(t);
}
function findToolsSection(e) {
let t = 0;
let n = 0;
let r;
for (const i of e.match(/.*(?:\n|$)/gu) ?? []) {
if (i === "") continue;
const e = i.replace(/\n$/u, "");
const a = /^\s*(`{3,}|~{3,})/u.exec(e)?.[1];
const o = /^\s*(`{3,}|~{3,})\s*$/u.exec(e)?.[1];
const s = a?.[0];
if (s && !r) r = {
marker: s,
length: a.length
};
else if (o && r && o[0] === r.marker && o.length >= r.length) r = void 0;
else if (!r) {
const r = /^(#{1,6})\s+(.+?)\s*#*\s*$/u.exec(e);
if (r) {
const e = r[1].length;
if (n > 0 && e <= 2) return {
headingEnd: n,
insertAt: t
};
if (e === 2 && r[2].trim().toLowerCase() === "tools") n = t + i.length;
}
}
t += i.length;
}
return n > 0 ? {
headingEnd: n,
insertAt: e.length
} : void 0;
}
function ensureLocalNotesHeading(e) {
const t = findToolsSection(e);
if (!t) return e;
const n = e.slice(t.headingEnd, t.insertAt);
if (/^###\s+Local notes(?:\s|$)/imu.test(n)) return e;
return `${e.slice(0, t.headingEnd)}\n### Local notes\n${e.slice(t.headingEnd)}`;
}
async function collectToolsMdMigrationFindings(e) {
const t = {
checkId: "core/doctor/tools-md-migration",
severity: "warning",
fixHint: `Run ${formatCliCommand("openclaw doctor --fix")} to merge TOOLS.md into AGENTS.md.`
};
const n = [];
for (const r of resolveToolsMdMigrationWorkspaceTargets(e)) try {
const i = await readToolsMd(r.workspaceDir);
if (i) {
n.push({
...t,
target: r.primaryAgentId,
path: i.path,
message: `Agent "${r.primaryAgentId}" still stores local tool notes in TOOLS.md.`,
requirement: "legacy-tools-md"
});
if (shouldMergeToolsMd(i.content)) {
const a = path.join(r.workspaceDir, DEFAULT_AGENTS_FILENAME);
const o = (await readMigrationFileSnapshot(a, true)).content;
const s = mergeToolsMdIntoAgentsMd(o, i.content).length;
/** One finding per agent whose own bootstrap budget cannot hold the merged file. */
for (const i of r.agentIds) {
const r = resolveBootstrapMaxChars(e, i);
if (s <= r) continue;
n.push({
...t,
target: i,
path: a,
message: `Agent "${i}" TOOLS.md migration will produce a ${s}-character AGENTS.md, exceeding its configured bootstrapMaxChars limit of ${r}. Raise \`agents.entries.*.bootstrapMaxChars\` for this agent, or \`agents.defaults.bootstrapMaxChars\` as fallback, to preserve all migrated instructions.`,
requirement: "tools-md-merged-bootstrap-limit"
});
}
}
}
} catch (e) {
n.push({
...t,
target: r.primaryAgentId,
path: path.join(r.workspaceDir, DEFAULT_TOOLS_FILENAME),
message: `Agent "${r.primaryAgentId}" TOOLS.md cannot be migrated: ${formatErrorMessage(e)}`,
severity: "error",
requirement: "tools-md-migration-blocked"
});
}
return n;
}
async function maybeMigrateToolsMd(e) {
const t = e.env ?? process.env;
const n = [];
const r = [];
for (const o of resolveToolsMdMigrationWorkspaceTargets(e.cfg)) try {
const r = await readToolsMd(o.workspaceDir);
if (!r) continue;
if (!e.shouldRepair) {
note(`${shortenHomePath(r.path)} will be archived and merged into AGENTS.md when customized.`, "TOOLS.md migration preview");
continue;
}
const s = shouldMergeToolsMd(r.content);
const c = o.primaryAgentId.replace(/[^A-Za-z0-9._-]+/g, "-");
const l = path.join(resolveStateDir(t), "backups", "tools-md-migration", `${c}-${r.sha256}.md`);
const u = path.dirname(l);
await fs$1.mkdir(u, {
recursive: true,
mode: 448
});
const d = `${l}.doctor-writing-${process.pid}-${Date.now()}`;
try {
try {
var i = _usingCtx();
const e = i.a(await fs$1.open(d, "wx", 384));
await e.writeFile(r.content, "utf8");
await e.sync();
} catch (e) {
i.e = e;
} finally {
await i.d();
}
await publishFileNoClobber(d, l, NO_CLOBBER_PUBLICATION);
await fs$1.rm(d);
await syncDirectoryIfSupported(u);
} catch (e) {
await fs$1.rm(d, { force: true });
if (e.code !== "EEXIST") throw e;
if (sha256Hex(await fs$1.readFile(l, "utf8")) !== r.sha256) throw new Error(`TOOLS.md migration archive collision at ${l}`, { cause: e });
}
const f = path.join(o.workspaceDir, DEFAULT_AGENTS_FILENAME);
const p = path.dirname(f);
const m = `${path.basename(f)}.doctor-writing-`;
const h = (await fs$1.readdir(p).catch(() => [])).filter((e) => e.startsWith(m));
for (const e of h) {
const t = path.join(p, e);
const n = await fs$1.lstat(t);
if (!n.isFile() || n.nlink !== 1) throw new Error(`interrupted AGENTS.md write must be an unlinked regular file: ${t}`);
await fs$1.rm(t);
}
if (h.length > 0) await syncDirectoryIfSupported(p);
const g = (await readMigrationFileSnapshot(f, true)).content;
const _ = s ? mergeToolsMdIntoAgentsMd(g, r.content) : rewriteLegacyAgentsToolsGuidance(g);
if (_ !== g) {
const e = s && !g.includes(r.content) ? r : void 0;
const t = await readMigrationFileSnapshot(f, true);
if (t.content !== g) throw new Error("AGENTS.md changed during TOOLS.md migration");
const n = t.stat;
const i = n?.mode ?? 384;
const o = `${f}.doctor-writing-${process.pid}-${Date.now()}`;
try {
let t;
try {
var a = _usingCtx();
const r = a.a(await fs$1.open(o, "wx", 384));
await r.writeFile(_, "utf8");
if (process.platform !== "win32" && n) {
await r.chmod(0);
await r.chown(n.uid, n.gid);
}
if (process.platform !== "win32" && e) await assertSourceReadersPreserved(e, n ?? await r.stat());
if (n) await r.chmod(i);
t = await r.stat();
if (process.platform !== "win32" && n && !samePosixPermissions(t, n)) throw new Error("AGENTS.md ownership or permissions could not be preserved");
await r.sync();
} catch (e) {
a.e = e;
} finally {
await a.d();
}
const r = await readMigrationFileSnapshot(f, true);
if (r.content !== g || !sameFileIdentity$1(r.stat, n) || process.platform !== "win32" && r.stat && n && !samePosixPermissions(r.stat, n)) throw new Error("AGENTS.md changed during TOOLS.md migration");
if (process.platform !== "win32" && e) await assertSourceReadersPreserved(e, t);
await fs$1.rename(o, f);
await syncDirectoryIfSupported(path.dirname(f));
} catch (e) {
await fs$1.rm(o, { force: true });
throw e;
}
if ((await readMigrationFileSnapshot(f)).content !== _) throw new Error("AGENTS.md changed after TOOLS.md migration was written");
}
await syncDirectoryIfSupported(o.workspaceDir);
const v = await readMigrationFileSnapshot(r.path);
if (sha256Hex(v.content) !== r.sha256) throw new Error("TOOLS.md changed during migration");
const y = fs.lstatSync(r.path);
if (!v.stat || !sameFileIdentity$1(y, v.stat) || !sameFileIdentity$1(y, r.stat)) throw new Error("TOOLS.md changed during migration");
fs.unlinkSync(r.path);
await syncDirectoryIfSupported(o.workspaceDir);
n.push(s ? `Merged ${shortenHomePath(r.path)} into AGENTS.md and archived the original.` : `Removed untouched ${shortenHomePath(r.path)} after archiving it.`);
} catch (e) {
r.push(`Agent "${o.primaryAgentId}" TOOLS.md was not migrated: ${formatErrorMessage(e)}`);
}
noteDoctorMigrationResult({
changes: n,
warnings: r
}, { changesTitle: "TOOLS.md migration" });
return {
changes: n,
warnings: r
};
}
//#endregion
export { collectToolsMdMigrationFindings, maybeMigrateToolsMd };