openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
200 lines (199 loc) • 7.37 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { r as DEFAULT_IDENTITY_FILENAME } from "./workspace-bootstrap-policy-D7EJ00Ub.mjs";
import fs from "node:fs";
import path from "node:path";
import { openRootFileSync, readFileDescriptorBoundedSync } from "@openclaw/fs-safe/advanced";
import { FsSafeError } from "@openclaw/fs-safe/errors";
import { isUtf8 } from "node:buffer";
//#region src/agents/identity-file.ts
const MAX_IDENTITY_FILE_BYTES = 4194304;
const WRITABLE_IDENTITY_FIELDS = [
["name", "Name"],
["theme", "Theme"],
["emoji", "Emoji"],
["avatar", "Avatar"]
];
const RICH_IDENTITY_LABELS = [
"name",
"creature",
"vibe",
"theme",
"emoji",
"avatar"
];
function isRichIdentityLabel(e) {
return RICH_IDENTITY_LABELS.some((t) => t === e);
}
const IDENTITY_PLACEHOLDER_VALUES = /* @__PURE__ */ new Set([
"not set yet",
"pick something you like",
"ai? robot? familiar? ghost in the machine? something weirder?",
"how do you come across? sharp? warm? chaotic? calm?",
"your signature - pick one that feels right",
"workspace-relative path, http(s) url, or data uri"
]);
function sanitizeAgentIdentityLine(e) {
return e.replace(/\s+/g, " ").trim();
}
function normalizeIdentityForFile(e) {
const t = {};
for (const [n] of WRITABLE_IDENTITY_FIELDS) {
const r = e?.[n]?.trim();
if (r) t[n] = r;
}
return Object.keys(t).length ? t : void 0;
}
function createAgentIdentityConfig(e) {
return normalizeIdentityForFile({
...e.name ? { name: sanitizeAgentIdentityLine(e.name) } : {},
emoji: sanitizeAgentIdentityLine(normalizeOptionalString(e.emoji) ?? ""),
avatar: sanitizeAgentIdentityLine(normalizeOptionalString(e.avatar) ?? "")
});
}
function normalizeIdentityValue(e) {
let t = e.trim();
t = t.replace(/^[*_`\s]+|[*_`\s]+$/g, "").trim();
if (t.startsWith("(") && t.endsWith(")")) t = t.slice(1, -1).trim();
t = t.replace(/[\u2013\u2014]/g, "-");
return normalizeLowercaseStringOrEmpty(t.replace(/\s+/g, " "));
}
function normalizeIdentityLabel(e) {
return normalizeLowercaseStringOrEmpty(e.replace(/[*_`]/g, ""));
}
function parseIdentityLine(e) {
const t = e.trim().replace(/^\s*-\s*/, "").replace(/^([*_`]+)([A-Za-z]+):\1/u, "$2:");
const n = t.indexOf(":");
return n === -1 ? void 0 : {
label: normalizeIdentityLabel(t.slice(0, n)),
value: t.slice(n + 1)
};
}
function stripIdentityValueDecoration(e) {
let t = e.trim();
for (;;) {
const e = t.match(/^(\*{1,2}|_{1,2}|`+)([\s\S]+)\1$/u);
const n = e?.[1];
const r = e?.[2];
if (!n || r === void 0) return t;
t = r.trim();
if (n.startsWith("`")) return t;
}
}
function parseIdentityMarkdown(e) {
const t = {};
for (const n of e.split(/\r?\n/)) {
const e = parseIdentityLine(n);
if (!e) continue;
const r = stripIdentityValueDecoration(e.value);
if (!r || IDENTITY_PLACEHOLDER_VALUES.has(normalizeIdentityValue(r))) continue;
if (isRichIdentityLabel(e.label)) t[e.label] = r;
}
return Object.keys(t).length > 0 ? t : null;
}
function resolveIdentityInsertIndex(e) {
const t = e.findLastIndex((e) => isRichIdentityLabel(parseIdentityLine(e)?.label ?? ""));
if (t >= 0) return t + 1;
const n = e.findIndex((e) => e.trim().startsWith("#"));
if (n === -1) return 0;
let r = n + 1;
while (r < e.length && e[r]?.trim() === "") r += 1;
return r;
}
/**
* Merge writable identity fields into existing IDENTITY.md content, replacing
* duplicate labels and preserving unrelated markdown.
*/
function mergeIdentityMarkdownContent(e, t) {
const n = e ? e.replace(/\r\n/g, "\n").split("\n") : ["# IDENTITY.md - Agent Identity", ""];
for (const [e, r] of WRITABLE_IDENTITY_FIELDS) {
const i = t[e]?.trim();
if (!i) continue;
const a = `- ${r}: ${i}`;
const [o, ...s] = n.reduce((t, n, r) => {
if (n.trim().startsWith("-") && parseIdentityLine(n)?.label === e) t.push(r);
return t;
}, []);
if (o !== void 0) {
n[o] = a;
for (const e of s.toReversed()) n.splice(e, 1);
continue;
}
const c = resolveIdentityInsertIndex(n);
n.splice(c, 0, a);
}
return n.join("\n").replace(/\n*$/, "\n");
}
async function buildIdentityMarkdownForWrite(e) {
const t = e.fallbackWorkspaceDir ? e.preferFallbackWorkspaceContent ? [e.fallbackWorkspaceDir, e.workspaceDir] : [e.workspaceDir, e.fallbackWorkspaceDir] : [e.workspaceDir];
for (const n of t) {
const t = await e.readWorkspaceFileContent(n, DEFAULT_IDENTITY_FILENAME);
if (t !== void 0) return mergeIdentityMarkdownContent(t, e.identity);
}
return mergeIdentityMarkdownContent(void 0, e.identity);
}
/** Shared admission kernel for the worker and the shipped synchronous SDK reader. */
function readIdentityFileSnapshot(e) {
try {
const t = fs.realpathSync(e.identityPath);
const n = openRootFileSync({
absolutePath: t,
rootPath: path.dirname(t),
rootRealPath: path.dirname(t),
boundaryLabel: "identity file directory",
rejectHardlinks: false
});
if (!n.ok) return { kind: "missing" };
try {
const { size: t, mtimeMs: r, ctimeMs: i } = n.stat;
const { dev: a, ino: o } = n.exactIdentity;
if (t > MAX_IDENTITY_FILE_BYTES) return { kind: "too-large" };
const s = JSON.stringify([
n.path,
String(a),
String(o),
t,
r,
i
]);
if (s === e.knownRevision) return { kind: "unchanged" };
const c = readFileDescriptorBoundedSync(n.fd, MAX_IDENTITY_FILE_BYTES);
if (!isUtf8(c)) return { kind: "invalid-encoding" };
const l = parseIdentityMarkdown(c.toString("utf-8"));
return {
kind: "loaded",
revision: s,
size: c.byteLength,
identity: l
};
} finally {
fs.closeSync(n.fd);
}
} catch (e) {
return { kind: e instanceof FsSafeError && e.code === "too-large" ? "too-large" : "missing" };
}
}
/** Load a specific identity file when it exists and contains real values. */
async function loadAgentIdentityFromFile(e) {
const { prepareIdentityFile: t } = await import("./identity-file-runtime-CkpWazK7.mjs");
const n = await t(e);
if (n.kind === "invalid-encoding") throw new Error(`Identity file ${e} must be valid UTF-8`);
if (n.kind === "too-large") throw new Error(`Identity file ${e} exceeds the maximum size of ${MAX_IDENTITY_FILE_BYTES} bytes`, { cause: new FsSafeError("too-large", `File exceeds ${MAX_IDENTITY_FILE_BYTES} bytes: ${e}`) });
return n.kind === "loaded" ? n.identity : null;
}
/** Retained synchronous contract for the shipped agent-avatar Plugin SDK facade. */
function loadAgentIdentityFromWorkspace(e) {
const t = readIdentityFileSnapshot({ identityPath: path.join(e, DEFAULT_IDENTITY_FILENAME) });
return t.kind === "loaded" ? t.identity : null;
}
/** Workspace presentation treats unavailable or unreadable identity files as absent. */
async function loadAgentIdentityFromWorkspaceAsync(e) {
try {
const { prepareIdentityFile: t } = await import("./identity-file-runtime-CkpWazK7.mjs");
const n = await t(path.join(e, DEFAULT_IDENTITY_FILENAME));
return n.kind === "loaded" ? n.identity : null;
} catch {
return null;
}
}
//#endregion
export { loadAgentIdentityFromWorkspaceAsync as a, readIdentityFileSnapshot as c, loadAgentIdentityFromWorkspace as i, sanitizeAgentIdentityLine as l, createAgentIdentityConfig as n, mergeIdentityMarkdownContent as o, loadAgentIdentityFromFile as r, normalizeIdentityForFile as s, buildIdentityMarkdownForWrite as t };