openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
166 lines (165 loc) • 5.23 kB
JavaScript
import { k as resolveDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { execFileSync } from "node:child_process";
//#region src/agents/date-time.ts
/**
* Normalizes timestamps and formats user-facing dates/times for agent prompts.
*/
let cachedTimeFormat;
let dateStampFormatter;
let userTimeFormatter;
/** Resolve a valid IANA timezone from config, host preferences, or UTC. */
function resolveUserTimezone(e) {
const t = e?.trim();
if (t) try {
getDateStampFormatter(t);
return t;
} catch {}
return Intl.DateTimeFormat().resolvedOptions().timeZone?.trim() || "UTC";
}
/** Resolve 12/24-hour display preference, detecting the host for `auto`. */
function resolveUserTimeFormat(e) {
if (e === "12" || e === "24") return e;
if (cachedTimeFormat) return cachedTimeFormat;
cachedTimeFormat = detectSystemTimeFormat() ? "24" : "12";
return cachedTimeFormat;
}
function getDateStampFormatter(e) {
if (dateStampFormatter?.timeZone === e) return dateStampFormatter.formatter;
const t = new Intl.DateTimeFormat("en-US", {
timeZone: e,
year: "numeric",
month: "2-digit",
day: "2-digit"
});
dateStampFormatter = {
timeZone: e,
formatter: t
};
return t;
}
/** Format a stable YYYY-MM-DD stamp in the requested timezone. */
function formatDateStamp(e, t) {
const n = resolveDateTimestampMs(e);
const r = new Date(n);
const i = getDateStampFormatter(t).formatToParts(r);
return `${i.find((e) => e.type === "year")?.value}-${i.find((e) => e.type === "month")?.value}-${i.find((e) => e.type === "day")?.value}`;
}
/** Build current turn context using the configured timezone or the canonical host fallback. */
function buildTemporalContextText(e) {
const t = resolveUserTimezone(e.configuredTimezone);
return [
"## Temporal Context",
`Current date: ${formatDateStamp(Date.now(), t)}`,
`Time zone: ${t}`,
...e.sessionStatusAvailable ? ["For the exact current time, use `session_status`."] : []
].join("\n");
}
/** Normalize Date, second, millisecond, or parseable string timestamps. */
function normalizeTimestamp(e) {
if (e == null) return;
let t;
if (e instanceof Date) t = e.getTime();
else if (typeof e === "number" && Number.isFinite(e)) t = e < 0xe8d4a51000 ? Math.round(e * 1e3) : Math.round(e);
else if (typeof e === "string") {
const n = e.trim();
if (!n) return;
if (/^\d+(\.\d+)?$/.test(n)) {
const e = Number(n);
if (Number.isFinite(e)) t = Math.round(e * (n.includes(".") || n.length < 13 ? 1e3 : 1));
} else {
const e = Date.parse(n);
if (!Number.isNaN(e)) t = e;
}
}
if (t === void 0 || !Number.isSafeInteger(t)) return;
try {
return {
timestampMs: t,
timestampUtc: new Date(t).toISOString()
};
} catch {
return;
}
}
/** Add normalized timestamp fields without overwriting valid existing values. */
function withNormalizedTimestamp(e, t) {
const n = normalizeTimestamp(t);
if (!n) return e;
return {
...e,
timestampMs: typeof e.timestampMs === "number" && Number.isFinite(e.timestampMs) ? e.timestampMs : n.timestampMs,
timestampUtc: typeof e.timestampUtc === "string" && e.timestampUtc.trim() ? e.timestampUtc : n.timestampUtc
};
}
function detectSystemTimeFormat() {
try {
if (process.platform === "darwin") {
const e = execFileSync("defaults", [
"read",
"-g",
"AppleICUForce24HourTime"
], {
encoding: "utf8",
timeout: 500,
stdio: [
"pipe",
"pipe",
"pipe"
]
}).trim();
if (e === "1" || e === "0") return e === "1";
} else if (process.platform === "win32") {
const e = execFileSync("powershell", ["-Command", "(Get-Culture).DateTimeFormat.ShortTimePattern"], {
encoding: "utf8",
timeout: 1e3
}).trim();
if (e.startsWith("H") || e.startsWith("h")) return e.startsWith("H");
}
} catch {}
return new Intl.DateTimeFormat(void 0, { hour: "numeric" }).resolvedOptions().hour12 === false;
}
function ordinalSuffix(e) {
if (e >= 11 && e <= 13) return "th";
return [
"th",
"st",
"nd",
"rd"
][e % 10] ?? "th";
}
/** Format the prompt-facing localized time string with weekday and date. */
function formatUserTime(e, t, n) {
const r = n === "24";
try {
let i = userTimeFormatter?.timeZone === t && userTimeFormatter.format === n ? userTimeFormatter.formatter : void 0;
if (!i) {
i = new Intl.DateTimeFormat("en-US", {
timeZone: t,
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
hour: r ? "2-digit" : "numeric",
minute: "2-digit",
hourCycle: r ? "h23" : "h12"
});
userTimeFormatter = {
timeZone: t,
format: n,
formatter: i
};
}
const a = i.formatToParts(e);
const o = {};
for (const e of a) if (e.type !== "literal") o[e.type] = e.value;
if (!o.weekday || !o.year || !o.month || !o.day || !o.hour || !o.minute) return;
const s = Number.parseInt(o.day, 10);
const c = ordinalSuffix(s);
const l = r ? `${o.hour}:${o.minute}` : `${o.hour}:${o.minute} ${o.dayPeriod}`;
return `${o.weekday}, ${o.month} ${s}${c}, ${o.year} - ${l}`;
} catch {
return;
}
}
//#endregion
export { resolveUserTimezone as a, resolveUserTimeFormat as i, formatDateStamp as n, withNormalizedTimestamp as o, formatUserTime as r, buildTemporalContextText as t };