openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6,670 lines • 225 kB
JavaScript
import { t as __exportAll } from "./rolldown-runtime-zBsNGFey.js";
import { B as isRecord, D as isBlockedObjectKey, F as normalizeOptionalString, M as normalizeUniqueStringEntriesLower, N as normalizeLowercaseStringOrEmpty, T as isMissingPathError, _ as resolveGlobalSingleton, g as resolveGlobalSet, v as mergeDeep, y as isPlainObject, z as asOptionalRecord } from "./runtime-doctor-migrations-JGL9tD-z.js";
import { n as parseBooleanValue } from "./boolean-Ci_8uN62.js";
import { h as tryProcessCwd, s as resolveStateDir, u as expandHomePrefix } from "./account-core-u1qUW4Od.js";
import { t as asFiniteNumber } from "./number-coercion-BtnBjAcf.js";
import { i as parseEnvTemplateSecretRef, u as expectDefined } from "./types.secrets-Dt3OCDui.js";
import "./boundary-path-BJflOsrm.js";
import { a as getSealedRuntimeJson5, i as resolvePreferredOpenClawTmpDir, l as resolveIncludeRoots, n as openRootFileSync, o as resolveConfigPath, r as DEFAULT_POSIX_TMP_ROOT, t as canUseRootFileOpen } from "./boundary-file-read-D04C1gj5.js";
import { n as pluginRuntimeProcessManifest, t as createRuntimeProcessEntrypoints } from "./runtime-process-manifest-B0mzdXd2.js";
import { createRequire } from "node:module";
import fsPromises from "node:fs/promises";
import { isPathInside as isPathInside$1 } from "@openclaw/fs-safe/path";
import path, { basename, dirname } from "node:path";
import fs, { mkdirSync } from "node:fs";
import { appendRegularFile, appendRegularFileSync } from "@openclaw/fs-safe/advanced";
import { createHash, randomUUID } from "node:crypto";
import os from "node:os";
import { fileURLToPath } from "node:url";
import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";
import { isMainThread, threadId } from "node:worker_threads";
import { Chalk } from "chalk";
import { Logger } from "tslog";
import { performance } from "node:perf_hooks";
import { channel } from "node:diagnostics_channel";
//#region src/shared/regexp.ts
/** Escape text so it can be embedded literally inside a RegExp pattern. */
function escapeRegExp(e) {
return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
//#endregion
//#region packages/normalization-core/src/utf16-slice.ts
function isHighSurrogate(e) {
return e >= 55296 && e <= 56319;
}
function isLowSurrogate(e) {
return e >= 56320 && e <= 57343;
}
/** Slices a UTF-16 string without returning dangling surrogate halves at either edge. */
function sliceUtf16Safe(e, t, n) {
const r = e.length;
let i = t < 0 ? Math.max(r + t, 0) : Math.min(t, r);
let a = n === void 0 ? r : n < 0 ? Math.max(r + n, 0) : Math.min(n, r);
if (a <= i) return "";
if (i > 0 && i < r) {
if (isLowSurrogate(e.charCodeAt(i)) && isHighSurrogate(e.charCodeAt(i - 1))) i += 1;
}
if (a > 0 && a < r) {
if (isHighSurrogate(e.charCodeAt(a - 1)) && isLowSurrogate(e.charCodeAt(a))) a -= 1;
}
return e.slice(i, a);
}
/** Truncates a UTF-16 string without cutting a surrogate pair in half. */
function truncateUtf16Safe(e, t) {
const n = Math.max(0, Math.floor(t));
if (e.length <= n) return e;
return sliceUtf16Safe(e, 0, n);
}
//#endregion
//#region packages/normalization-core/src/error-coercion.ts
const PROVIDER_AUTH_PERSISTENCE_ERROR_BRAND = Symbol.for("openclaw.provider-auth-persistence-error");
function isProviderAuthPersistenceError(e) {
try {
return PROVIDER_AUTH_PERSISTENCE_ERROR_BRAND in e && e[PROVIDER_AUTH_PERSISTENCE_ERROR_BRAND] === true;
} catch {
return false;
}
}
function isErrorObject(e) {
try {
if (e instanceof Error) return true;
return Object.prototype.toString.call(e) === "[object Error]";
} catch {
return false;
}
}
function isAggregateErrorObject(e) {
try {
if (e instanceof AggregateError) return true;
for (let t = Object.getPrototypeOf(e); t; t = Object.getPrototypeOf(t)) {
const e = Object.getOwnPropertyDescriptor(t, "constructor")?.value;
if (typeof e === "function" && e.name === "AggregateError") return true;
}
} catch {}
return false;
}
function readProperty(e, t) {
try {
return e[t];
} catch {
return;
}
}
function readErrorText(e, t) {
const n = readProperty(e, t);
return typeof n === "string" ? n : void 0;
}
function formatStatusAndCode(e) {
if ((typeof e !== "object" || e === null) && typeof e !== "function") return;
try {
if (Object.keys(e).some((e) => e !== "status" && e !== "code")) return;
} catch {}
const t = readProperty(e, "status");
const n = readProperty(e, "code");
if (t === void 0 && n === void 0) return;
return `status=${typeof t === "string" || typeof t === "number" ? String(t) : "unknown"} code=${typeof n === "string" || typeof n === "number" ? String(n) : "unknown"}`;
}
function stringifyUnknown(e) {
if (e === null || typeof e !== "object" && typeof e !== "function") return String(e);
try {
const t = JSON.stringify(e);
if (t !== void 0) return t;
} catch {}
try {
return Object.prototype.toString.call(e);
} catch {
return "Unknown error";
}
}
function readErrorCauses(e) {
if (!isErrorObject(e)) return [];
const t = readProperty(e, "cause");
const n = isAggregateErrorObject(e) ? readProperty(e, "errors") : void 0;
const r = isProviderAuthPersistenceError(e) ? [readProperty(e, "persistenceError"), readProperty(e, "cleanupError")] : [];
const i = readErrorText(e, "name") === "SuppressedError" ? [readProperty(e, "error"), readProperty(e, "suppressed")].map((e) => e == null ? String(e) : e) : [];
return [
...r,
t || void 0,
...Array.isArray(n) ? n : [],
...i
];
}
/** Formats unknown errors with cause/aggregate details and optional diagnostic redaction. */
function formatErrorMessage(e, t = {}) {
let n;
if (isErrorObject(e)) {
n = readErrorText(e, "message") || readErrorText(e, "name") || "Error";
const r = /* @__PURE__ */ new Set([n]);
const appendCauseMessage = (e) => {
if (!e || r.has(e)) return;
n += ` | ${e}`;
r.add(e);
};
if (t.includeCode) {
const t = readProperty(e, "code");
if (typeof t === "string" || typeof t === "number") appendCauseMessage(String(t));
}
const i = collectErrorGraphCandidates(e, readErrorCauses);
for (const e of i.slice(1)) if (isErrorObject(e)) {
const t = readErrorText(e, "message");
if (t && n.includes(t)) r.add(t);
else appendCauseMessage(t);
const i = readProperty(e, "code");
if (typeof i === "string" || typeof i === "number") appendCauseMessage(String(i));
} else if (typeof e === "string") appendCauseMessage(e);
else appendCauseMessage(formatStatusAndCode(e) ?? stringifyUnknown(e));
} else n = formatStatusAndCode(e) ?? stringifyUnknown(e);
return t.redact ? t.redact(n) : n;
}
/**
* Formats an error's stack so it always names the error. Bun can materialize
* `stack` during garbage collection with a bare `Error` header, dropping the
* message that V8-style stacks carry.
*/
function formatErrorStackWithMessage(e) {
const t = readErrorText(e, "name") || "Error";
const n = readErrorText(e, "message") ?? "";
const r = readProperty(e, "stack");
if (typeof r !== "string" || !r) return n || t;
if (!n || r.includes(n)) return r;
const i = `${t}: ${n}`;
const a = r.indexOf("\n");
const o = a < 0 ? r : r.slice(0, a);
return o === t ? i + r.slice(o.length) : `${i}\n${r}`;
}
/**
* Normalizes an unknown thrown value into an Error. Non-Error objects become
* the `cause` and have their enumerable fields copied so structured details
* (codes, statuses) survive the coercion.
*/
function toErrorObject(e, t) {
if (e instanceof Error) return e;
if (typeof e === "string") return new Error(e);
const n = new Error(t, { cause: e });
if (typeof e === "object" && e !== null || typeof e === "function") Object.assign(n, e);
return n;
}
/** Reads Error messages unchanged and stringifies every other value. */
function coerceErrorMessage(e) {
return e instanceof Error ? e.message : String(e);
}
function extractErrorCode(e) {
if (!e || typeof e !== "object") return;
const t = readProperty(e, "code");
return typeof t === "string" || typeof t === "number" ? String(t) : void 0;
}
function collectErrorGraphCandidates(e, t) {
if (e == null) return [];
const n = [e];
const r = (/* @__PURE__ */ new Set()).add(e);
for (const e of n) {
if (!e || typeof e !== "object" || !t) continue;
for (const i of t(e)) if (i != null && !r.has(i)) {
r.add(i);
n.push(i);
}
}
return n;
}
function collectNestedErrorCandidates(e) {
return collectErrorGraphCandidates(e, (e) => {
const t = [
readProperty(e, "cause"),
readProperty(e, "reason"),
readProperty(e, "original"),
readProperty(e, "error"),
readProperty(e, "suppressed"),
readProperty(e, "data")
];
const n = readProperty(e, "errors");
if (Array.isArray(n)) t.push(...n);
return t;
});
}
//#endregion
//#region src/utils/string-readers.ts
/** Reads the first parsed field, preserving order and defined falsy values. */
function readParsedField(e, t, n) {
for (const r of typeof t === "string" ? [t] : t) {
const t = n(e[r]);
if (t !== void 0) return t;
}
}
//#endregion
//#region src/infra/map-size.ts
/** Prunes a Map in insertion order until it fits the requested maximum size. */
function pruneMapToMaxSize(e, t) {
if (Number.isNaN(t) || t === Number.POSITIVE_INFINITY) return;
const n = Math.max(0, Math.floor(t));
if (n <= 0) {
e.clear();
return;
}
for (const t of e.keys()) {
if (e.size <= n) break;
e.delete(t);
}
}
//#endregion
//#region src/shared/detached-async-context.ts
const asyncHooks = typeof process === "undefined" ? void 0 : process.getBuiltinModule?.("node:async_hooks");
const detachedAsyncContext = asyncHooks ? resolveGlobalSingleton(Symbol.for("openclaw.detachedAsyncContext"), () => new asyncHooks.AsyncResource("openclaw.detached-async-context")) : void 0;
/** Runs under the context-free async root initialized before managed work can begin. */
function runInDetachedAsyncContext(e) {
return detachedAsyncContext ? detachedAsyncContext.runInAsyncScope(e) : e();
}
//#endregion
//#region src/infra/runtime-process-sealed-manifest.ts
const runtimeProcessSealedManifest = {
managedHandoff: {
ownerSource: "src/infra/update-managed-service-handoff-sealed.ts",
entries: [["postgresBridge", "managedHandoffPostgresBridge"]]
},
worker: {
ownerSource: "src/worker/worker-deploy-runtime.ts",
entries: [
["clientCredentials", "client-credential.worker"],
["codeModeNode", "code-mode-node.worker"],
["stateRead", "openclaw-state-read.worker"],
["workerNativeLifecycle", "worker-native-lifecycle.worker"],
["fileToolPlanning", "file-tool-planning.worker"],
["fileToolRead", "file-tool-read.worker"],
["gatewayStateOwnerHeartbeat", "gateway-state-owner-heartbeat.worker"],
["githubExec", "github-exec-launcher"],
["imageProcessor", "image-processor.worker"],
["serviceChildRelay", "service-child-relay"],
["sqliteSourceRevision", "sqlite-source-revision.worker"],
["sqliteStore", "sqlite-store.worker"],
["sharedStateStore", "sqlite-store.worker"]
]
},
serviceChildRelay: {
ownerSource: "src/process/supervisor/service-child-relay.ts",
entries: [["serviceChildGroupAnchor", "service-child-group-anchor"]]
}
};
//#endregion
//#region src/global-state.ts
let globalVerbose = false;
function isVerbose() {
return globalVerbose;
}
//#endregion
//#region src/infra/diagnostic-event-listener-presence.ts
/** Process-wide listener counts used to avoid telemetry work without consumers. */
const listenerPresence = resolveGlobalSingleton(Symbol.for("openclaw.diagnosticEventListenerPresence.v1"), () => ({
untrustedInterest: {
broadInterestCount: 0,
eventInterestDeltas: /* @__PURE__ */ new Map()
},
trustedInterest: {
broadInterestCount: 0,
eventInterestDeltas: /* @__PURE__ */ new Map()
},
interestListeners: /* @__PURE__ */ new Map(),
internalCount: 0,
trustedCount: 0,
promptStatsCount: 0
}));
function isInternalDiagnosticEventInterested(e, t, n) {
return (!e?.include || e.include.includes(t)) && !e?.exclude?.includes(t) && (!n || !e?.includeTrusted || e.includeTrusted.includes(t));
}
function hasInternalDiagnosticEventInterest(e, t = false) {
const n = t ? listenerPresence.trustedInterest : listenerPresence.untrustedInterest;
return n.broadInterestCount + (n.eventInterestDeltas.get(e) ?? 0) > 0;
}
//#endregion
//#region src/shared/async-store.ts
function enterAsyncStore(e, t) {
this.enterWith(e);
return t();
}
/** Enter once; the resource restores the caller's frame without copying it again. */
function runWithAsyncStore(e, t, n) {
if (e.getStore() === t) return n();
return new AsyncResource("OpenClawAsyncStore").runInAsyncScope(enterAsyncStore, e, t, n);
}
//#endregion
//#region src/plugins/plugin-instance-invocation.ts
var InvocationFrame = class InvocationFrame {
constructor(e, t = e.invocation) {
this.retentionOwner = e.retentionOwner;
this.invocation = t;
this.metadataScope = e.metadataScope;
this.cacheScope = e.cacheScope;
this.sourceCaptureStorage = e.sourceCaptureStorage;
}
get runtimePluginId() {}
withScopes(e) {
return new InvocationFrame(e);
}
};
/** Copy core scopes through the current owner so runtime-only fields survive. */
function createPluginExecutionFrame(e, t) {
return t ? t.withScopes(e) : new InvocationFrame(e);
}
const pluginExecutionContext = resolveGlobalSingleton(Symbol.for("openclaw.pluginInstanceInvocation"), () => {
const e = new AsyncLocalStorage();
return {
invocation: {
getStore() {
return e.getStore()?.invocation;
},
run(t, n) {
const r = e.getStore();
return r?.invocation === t ? n() : runWithAsyncStore(e, createPluginExecutionFrame({
...r,
invocation: t
}, r), n);
},
exit(t) {
const n = e.getStore();
return n?.invocation ? runWithAsyncStore(e, n.withScopes({
...n,
invocation: void 0
}), t) : t();
}
},
getFrame() {
return e.getStore();
},
runFrame(t, n) {
return runWithAsyncStore(e, t, n);
}
};
});
const pluginInstanceInvocation = pluginExecutionContext.invocation;
const getPluginExecutionFrame = pluginExecutionContext.getFrame;
const runWithPluginExecutionFrame = pluginExecutionContext.runFrame;
//#endregion
//#region src/infra/diagnostic-event-queue-policy.ts
const ASYNC_EVENT = {
priority: false,
publicExcluded: false
};
const DIAGNOSTIC_EVENT_POLICIES = [
{
...ASYNC_EVENT,
name: "worker.request"
},
{
...ASYNC_EVENT,
name: "diagnostic.gc",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.event_loop.sample",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.main_thread.stall",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.http.cancelled",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.rpc",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "sessions.list.baseline.retired"
},
{
...ASYNC_EVENT,
name: "sessions.list.retention",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "sessions.event.retention",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "sessions.event.rows.reset",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.ws.event",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.ws.connections",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "tool.execution.started"
},
{
...ASYNC_EVENT,
name: "tool.execution.completed",
priority: true
},
{
...ASYNC_EVENT,
name: "tool.execution.error",
priority: true
},
{
...ASYNC_EVENT,
name: "tool.execution.blocked",
priority: true
},
{
...ASYNC_EVENT,
name: "skill.used"
},
{
...ASYNC_EVENT,
name: "exec.process.completed"
},
{
...ASYNC_EVENT,
name: "exec.approval.followup_suppressed"
},
{
...ASYNC_EVENT,
name: "message.delivery.started"
},
{
...ASYNC_EVENT,
name: "message.delivery.completed"
},
{
...ASYNC_EVENT,
name: "message.delivery.error"
},
{
...ASYNC_EVENT,
name: "talk.event"
},
{
...ASYNC_EVENT,
name: "model.call.started"
},
{
...ASYNC_EVENT,
name: "model.call.completed",
priority: true
},
{
...ASYNC_EVENT,
name: "model.call.error",
priority: true
},
{
...ASYNC_EVENT,
name: "model.response.observed"
},
{
...ASYNC_EVENT,
name: "run.progress"
},
{
...ASYNC_EVENT,
name: "run.execution_phase"
},
{
...ASYNC_EVENT,
name: "agent.commentary"
},
{
...ASYNC_EVENT,
name: "harness.run.completed",
priority: true
},
{
...ASYNC_EVENT,
name: "harness.run.error",
priority: true
},
{
...ASYNC_EVENT,
name: "context.assembled"
},
{
...ASYNC_EVENT,
name: "log.record",
publicExcluded: true
}
];
const ASYNC_DIAGNOSTIC_EVENT_NAMES = DIAGNOSTIC_EVENT_POLICIES.map((e) => e.name);
const PRIORITY_ASYNC_DIAGNOSTIC_EVENT_NAMES = DIAGNOSTIC_EVENT_POLICIES.filter((e) => e.priority).map((e) => e.name);
const PUBLIC_EXCLUDED_DIAGNOSTIC_EVENT_NAMES = DIAGNOSTIC_EVENT_POLICIES.filter((e) => e.publicExcluded).map((e) => e.name);
//#endregion
//#region src/shared/async-context.ts
const context = resolveGlobalSingleton(Symbol.for("openclaw.asyncContext"), () => new AsyncLocalStorage());
/** A field in the immutable async frame, retaining its owner's value by reference. */
var AsyncContext = class {
constructor(e) {
this.key = e;
}
getStore() {
return context.getStore()?.[this.key];
}
run(e, t) {
const n = context.getStore();
const r = n?.[this.key];
if (Object.is(r, e)) return t();
const i = {
...n,
[this.key]: e
};
context.enterWith(i);
try {
return t();
} finally {
const e = context.getStore();
context.enterWith(e === i ? n : {
...e,
[this.key]: r
});
}
}
exit(e) {
return this.run(void 0, e);
}
/** Used by the single-copy runner, which owns restoration of the entire frame. */
enterWith(e) {
context.enterWith({
...context.getStore(),
[this.key]: e
});
}
};
//#endregion
//#region src/infra/diagnostic-trace-context.ts
const TRACE_ID_RE = /^[0-9a-f]{32}$/;
const SPAN_ID_RE = /^[0-9a-f]{16}$/;
const TRACE_FLAGS_RE = /^[0-9a-f]{2}$/;
const DIAGNOSTIC_TRACE_SCOPE_STATE_KEY = Symbol.for("openclaw.diagnosticTraceScope.state.v1");
function isNonZeroHex(e) {
return !/^0+$/.test(e);
}
const traceContext = new AsyncContext(DIAGNOSTIC_TRACE_SCOPE_STATE_KEY);
/** Returns whether a value is a non-zero W3C trace id. */
function isValidDiagnosticTraceId(e) {
return typeof e === "string" && TRACE_ID_RE.test(e) && isNonZeroHex(e);
}
/** Returns whether a value is a non-zero W3C span id. */
function isValidDiagnosticSpanId(e) {
return typeof e === "string" && SPAN_ID_RE.test(e) && isNonZeroHex(e);
}
/** Returns whether a value is a valid W3C trace-flags byte. */
function isValidDiagnosticTraceFlags(e) {
return typeof e === "string" && TRACE_FLAGS_RE.test(e);
}
/** Returns the trace context bound to the current async scope. */
function getActiveDiagnosticTraceContext() {
return traceContext.getStore();
}
//#endregion
//#region src/infra/diagnostic-event-snapshot.ts
const immutableSnapshots = /* @__PURE__ */ new WeakSet();
/** Owned envelopes contain data properties; their nested values still belong to producers. */
function cloneDiagnosticValueForListener(e, t = false) {
if (immutableSnapshots.has(e)) return e;
if (t && Object.getOwnPropertySymbols(e).length === 0 && Object.values(e).every((e) => isImmutableDiagnosticValue(e))) {
immutableSnapshots.add(e);
return Object.freeze(e);
}
const n = structuredClone(e);
if (freezeDiagnosticValue(n, /* @__PURE__ */ new WeakSet())) immutableSnapshots.add(n);
return n;
}
/** Capture lazily so filtered listeners never read the producer's payload. */
function createDiagnosticValueForListeners(e, t = false) {
let n;
return () => {
if (n) return n;
const r = cloneDiagnosticValueForListener(e, t);
if (immutableSnapshots.has(r)) n = r;
return r;
};
}
function isImmutableDiagnosticValue(e, t) {
if (!e || typeof e !== "object") return typeof e !== "function" && typeof e !== "symbol";
if (immutableSnapshots.has(e) || t?.has(e)) return true;
const n = Object.getPrototypeOf(e);
if (!Object.isFrozen(e) || n !== Object.prototype && n !== Array.prototype && n !== null) return false;
let r = t;
return Reflect.ownKeys(e).every((t) => {
const n = Object.getOwnPropertyDescriptor(e, t);
if (typeof t === "symbol" || !("value" in n)) return false;
if (n.value && typeof n.value === "object") (r ??= /* @__PURE__ */ new WeakSet()).add(e);
return isImmutableDiagnosticValue(n.value, r);
});
}
function freezeDiagnosticValue(e, t) {
if (!e || typeof e !== "object" || t.has(e)) return true;
if (ArrayBuffer.isView(e)) return false;
t.add(e);
const n = Object.getPrototypeOf(e);
let r = n === Object.prototype || n === Array.prototype || n === null;
for (const n of Object.values(e)) if (!freezeDiagnosticValue(n, t)) r = false;
Object.freeze(e);
return r;
}
function enrichDiagnosticEvent(e, t, n = true) {
const r = {};
for (const [e, n] of Object.entries(t)) {
if (isBlockedObjectKey(e)) continue;
r[e] = n;
}
if (n) r.trace ??= getActiveDiagnosticTraceContext();
e.seq += 1;
r.seq = e.seq;
r.ts = Date.now();
return r;
}
function captureQueuedDiagnosticEvent(e, t) {
try {
let n = false;
let r = false;
if (e.privateData || e.trustedListenersOnly) {
for (const i of t) if (isInternalDiagnosticEventInterested(i, e.event.type, e.metadata.trusted)) {
n = true;
if (i?.includePrivateData !== false) {
r = true;
break;
}
}
}
if (e.trustedListenersOnly && !n) return false;
e.event = cloneDiagnosticValueForListener(e.event, true);
if (e.privateData) try {
e.privateData = r ? cloneDiagnosticValueForListener(e.privateData) : void 0;
} catch (t) {
e.privateData = void 0;
console.error(`[diagnostic-events] private snapshot error type=${e.event.type}: ${String(t)}`);
}
return true;
} catch (t) {
console.error(`[diagnostic-events] queue snapshot error type=${e.event.type}: ${String(t)}`);
return false;
}
}
//#endregion
//#region src/infra/diagnostic-model-request-provenance.ts
const CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY = "coreModelRequestLifecycle";
//#endregion
//#region src/infra/diagnostic-otel-listener-provenance.ts
const trustedOtelDiagnosticListeners = /* @__PURE__ */ new WeakSet();
function isTrustedOtelDiagnosticListener(e) {
return trustedOtelDiagnosticListeners.has(e);
}
//#endregion
//#region src/infra/diagnostic-plugin-usage-provenance.ts
const hostPluginUsageIds = /* @__PURE__ */ new WeakMap();
function consumeHostPluginUsageDiagnosticEvent(e) {
const t = hostPluginUsageIds.get(e);
hostPluginUsageIds.delete(e);
return t;
}
//#endregion
//#region src/infra/diagnostic-semantic-run-progress-provenance.ts
const CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY = "coreSemanticRunProgress";
const coreSemanticRunProgressEvents = /* @__PURE__ */ new WeakMap();
function consumeCoreSemanticRunProgressDiagnosticEvent(e) {
const t = coreSemanticRunProgressEvents.get(e);
coreSemanticRunProgressEvents.delete(e);
return t;
}
//#endregion
//#region src/infra/diagnostic-tool-execution-liveness.ts
const TOOL_EXECUTION_LIVENESS_METADATA_KEY = "toolExecutionLiveness";
const state$1 = resolveGlobalSingleton(Symbol.for("openclaw.diagnosticToolExecutionLiveness"), () => ({
context: new AsyncContext(Symbol("toolExecutionDeadline")),
events: /* @__PURE__ */ new WeakMap()
}));
function consumeToolExecutionLivenessDiagnosticEvent(e) {
const t = state$1.events.get(e);
state$1.events.delete(e);
return t;
}
//#endregion
//#region src/infra/diagnostic-trace-propagation.ts
const DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY = Symbol.for("openclaw.diagnosticTracePropagation.state.v1");
const tracePropagationState = resolveGlobalSingleton(DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY, () => ({
marker: DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY,
bridges: /* @__PURE__ */ new Set(),
activeBridge: void 0
}));
/** Whether an exporter needs events prepared before their queued delivery. */
function hasDiagnosticTracePropagationConsumer() {
return tracePropagationState.activeBridge?.prepareEvent !== void 0;
}
function shouldPrepareDiagnosticTracePropagation(e) {
const t = tracePropagationState.activeBridge;
if (!t?.prepareEvent) return false;
if (!t.shouldPrepareEvent) return true;
try {
return t.shouldPrepareEvent(e);
} catch (e) {
console.error(`[diagnostic-trace-propagation] prepare filter error: ${String(e)}`);
return false;
}
}
function prepareDiagnosticTracePropagation(e, t) {
const n = tracePropagationState.activeBridge;
if (!n?.prepareEvent) return;
try {
n.prepareEvent(e, t);
} catch (t) {
console.error(`[diagnostic-trace-propagation] prepare error type=${e.type} seq=${e.seq}: ${String(t)}`);
}
}
//#endregion
//#region src/agents/usage.ts
const USAGE_COST_COMPONENTS = [
"input",
"output",
"cacheRead",
"cacheWrite"
];
function hasNonzeroUsage(e) {
if (!e || e.usageReport?.state === "unavailable") return false;
return [
e.input,
e.output,
e.cacheRead,
e.cacheWrite,
e.contextUsage?.state === "available" ? e.contextUsage.promptTokens : void 0,
e.contextUsage?.state === "available" ? e.contextUsage.totalTokens : void 0,
e.reasoningTokens,
e.total
].some((e) => typeof e === "number" && Number.isFinite(e) && e > 0) || e.contextUsage?.state === "unavailable";
}
/** Adapter-default zeros are not price evidence; billed totals and cost components are. */
function hasRecordedUsageCost(e) {
const t = asOptionalRecord(e);
const n = asFiniteNumber(t?.total);
return n !== void 0 && n >= 0 && (n > 0 || t?.totalOrigin === "provider-billed" || USAGE_COST_COMPONENTS.some((e) => (asFiniteNumber(t?.[e]) ?? 0) !== 0));
}
/** Empty transport snapshots synthesize $0; recorded cost evidence can establish an observation. */
function hasObservedModelUsage(e) {
return e?.usageReport !== void 0 || hasRecordedUsageCost(e?.cost) || hasNonzeroUsage(e);
}
//#endregion
//#region src/infra/diagnostic-flags-env.ts
function parseDiagnosticEnvFlags(e) {
const t = e?.trim() ?? "";
const n = t.toLowerCase();
if (!n) return {
flags: [],
disablesAll: false
};
if ([
"0",
"false",
"off",
"none"
].includes(n)) return {
flags: [],
disablesAll: true
};
if ([
"1",
"true",
"all",
"*"
].includes(n)) return {
flags: ["*"],
disablesAll: false
};
return {
flags: t.split(/[,\s]+/),
disablesAll: false
};
}
//#endregion
//#region src/infra/diagnostic-flags.ts
const DIAGNOSTICS_ENV = "OPENCLAW_DIAGNOSTICS";
/** Returns whether a diagnostic flag is enabled after config/env resolution. */
function isDiagnosticFlagEnabled(e, t, n = process.env) {
const r = t?.diagnostics?.flags ?? [];
const i = parseDiagnosticEnvFlags(n[DIAGNOSTICS_ENV]);
const a = i.disablesAll ? [] : normalizeUniqueStringEntriesLower([...r, ...i.flags]);
const o = normalizeLowercaseStringOrEmpty(e);
if (!o) return false;
for (const e of a) {
if (e === "*" || e === "all" || e === o) return true;
if (e.endsWith(".*") && o === e.slice(0, -2)) return true;
if (e.endsWith("*") && o.startsWith(e.slice(0, -1))) return true;
}
return false;
}
//#endregion
//#region src/infra/fs-safe-env.ts
const nativeModeKey = "OPENCLAW_FS_SAFE_NATIVE_MODE";
const legacyModeKeys = ["FS_SAFE_PYTHON_MODE", "OPENCLAW_FS_SAFE_PYTHON_MODE"];
const legacyKeys = [
...legacyModeKeys,
"FS_SAFE_PYTHON",
"OPENCLAW_FS_SAFE_PYTHON",
"OPENCLAW_PINNED_PYTHON",
"OPENCLAW_PINNED_WRITE_PYTHON"
];
const fallbacks = /* @__PURE__ */ new WeakMap();
let warned = false;
function nativeModeIsValid(e) {
const t = e?.trim().toLowerCase() ?? "";
return /^(?:0|false|off|never|1|true|on|auto|required|require)$/u.test(t);
}
function currentFallback(e) {
const t = fallbacks.get(e);
return t && e[t.key] === t.value ? t : void 0;
}
/** Read the operator/config inputs without promoting a derived native fallback. */
function fsSafeEnvInput(e) {
const t = currentFallback(e);
if (!t) return e;
const n = {
...e,
[t.key]: t.previous
};
if (!t.existed) delete n[t.key];
return n;
}
/** Retire our unchanged projection before an environment owner writes real inputs. */
function clearFsSafeEnvFallback(e) {
const t = currentFallback(e);
fallbacks.delete(e);
if (!t) return;
if (!t.existed) delete e[t.key];
else e[t.key] = t.previous;
}
/** Preserve OpenClaw's retired Python mode env contract below both native names. */
function normalizeFsSafeNativeEnv(e = process.env) {
clearFsSafeEnvFallback(e);
const t = legacyKeys.filter((t) => e[t] !== void 0);
if (t.length && e === process.env && !warned) {
warned = true;
process.emitWarning(`${t.join(", ")} is deprecated. OpenClaw maps legacy mode values to native mode only when neither FS_SAFE_NATIVE_MODE nor OPENCLAW_FS_SAFE_NATIVE_MODE selects a mode. Replace Python mode variables with native mode variables; interpreter path settings are ignored.`, {
code: "FS_SAFE_PYTHON_DEPRECATED",
type: "DeprecationWarning"
});
}
if (nativeModeIsValid(e.FS_SAFE_NATIVE_MODE) || nativeModeIsValid(e[nativeModeKey])) return;
const n = legacyModeKeys.map((t) => e[t]).find((e) => e !== void 0);
if (n === void 0) return;
const r = Object.keys(e);
const i = !r.includes(nativeModeKey) && Object.hasOwn(e, nativeModeKey) ? r.find((e) => e.toUpperCase() === nativeModeKey) ?? nativeModeKey : nativeModeKey;
const a = Object.hasOwn(e, i);
const o = e[i];
e[i] = n;
fallbacks.set(e, {
key: i,
value: n,
previous: o,
existed: a
});
}
//#endregion
//#region src/infra/env.ts
/** Interprets common human/operator truthy env strings. */
function isTruthyEnvValue(e) {
return parseBooleanValue(e) === true;
}
//#endregion
//#region src/infra/main-thread-stall.ts
const taskState = resolveGlobalSingleton(Symbol.for("openclaw.mainThreadTask"), () => ({ context: new AsyncLocalStorage() }));
/**
* Name code-owned work only; request text, paths, and identifiers do not belong in labels.
* Phases label synchronous segments; only task boundaries establish an inherited async name.
*/
function runWithMainThreadTask(e, t, n) {
const r = taskState.observer;
return r ? r.run(e, t, n) : t();
}
//#endregion
//#region src/infra/diagnostics-timeline.ts
const OPENCLAW_DIAGNOSTICS_TIMELINE_SCHEMA_VERSION = "openclaw.diagnostics.v1";
const MAX_PENDING_TIMELINE_BYTES = 65536;
/** Usage is a terminal observation, not proof of all requests hidden inside a logical call. */
function modelUsageTimelineAttributes(e) {
const t = { usageState: e?.usageReport?.state ?? (hasObservedModelUsage(e) ? "available" : "unreported") };
for (const n of [
"input",
"output",
"cacheRead",
"cacheWrite",
"cacheWrite1h",
"cacheWrite5m",
"reasoningTokens",
"promptTokens",
"total"
]) {
const r = e?.[n];
if (r !== void 0) t[n] = r;
}
return t;
}
function recordDiagnosticModelUsageTimeline(e) {
if (!isDiagnosticsTimelineEnabled()) return;
const t = e.trace ?? getActiveDiagnosticTraceContext();
emitDiagnosticsTimelineEvent({
type: "mark",
name: "model.usage",
provider: e.provider,
attributes: {
...modelUsageTimelineAttributes({
...e.usage,
usageReport: e.usageReport
}),
...e.model ? { model: e.model } : {},
...e.sessionId ? { sessionId: e.sessionId } : {},
...t ? { traceId: t.traceId } : {},
...e.purpose ? { purpose: e.purpose } : {},
...e.runtimeKind ? { runtimeKind: e.runtimeKind } : {},
...e.completionId ? { completionId: e.completionId } : {},
...e.attemptId ? { attemptId: e.attemptId } : {},
...e.costUsd !== void 0 ? { costUsd: e.costUsd } : {}
}
});
}
const activeDiagnosticsTimelineSpan = new AsyncLocalStorage();
const spanObserver = new AsyncLocalStorage();
const timelineWriter = resolveGlobalSingleton(Symbol.for("openclaw.diagnosticsTimelineWriter"), () => {
let e;
let t;
let n;
let r = false;
let i = false;
const a = /* @__PURE__ */ new Set();
function append(e, t) {
try {
const n = dirname(e.path);
if (!a.has(n)) {
mkdirSync(n, { recursive: true });
a.add(n);
}
appendRegularFileSync({
filePath: e.path,
content: t
});
} catch (t) {
e.failedWrites++;
if (!i) {
i = true;
console.warn(`[diagnostics] failed to write timeline event: ${String(t)}`);
}
}
}
function flush() {
if (n) {
clearImmediate(n);
n = void 0;
}
const e = t;
t = void 0;
if (e) append(e.capture, e.content);
}
process.once("exit", () => {
r = true;
flush();
});
return {
flush,
write(i, a, o) {
if (e?.path !== i) {
flush();
e = {
path: i,
id: randomUUID(),
sequence: 0,
failedWrites: 0
};
}
const s = serializeTimelineEvent({
...a,
attributes: {
...a.attributes,
captureId: e.id,
sequence: ++e.sequence,
failedWrites: e.failedWrites
}
}, o);
const c = Buffer.byteLength(s, "utf8");
if (t && t.bytes + c > MAX_PENDING_TIMELINE_BYTES) flush();
if (r || c > MAX_PENDING_TIMELINE_BYTES) {
append(e, s);
return;
}
if (t) {
t.content += s;
t.bytes += c;
} else t = {
capture: e,
content: s,
bytes: c
};
n ??= setImmediate(flush).unref();
}
};
});
/** Returns true when diagnostics flags and a JSONL output path both allow timeline writes. */
function isDiagnosticsTimelineEnabled(e = {}) {
const { config: t, env: n = process.env } = e;
const r = n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH;
if (typeof r !== "string" || r.trim().length === 0) return false;
return isDiagnosticFlagEnabled("timeline", t, n) || isDiagnosticFlagEnabled("diagnostics.timeline", t, n) || isTruthyEnvValue(n.OPENCLAW_DIAGNOSTICS);
}
function normalizeNumber(e) {
if (typeof e !== "number" || !Number.isFinite(e)) return;
return Math.max(0, Math.round(e * 1e3) / 1e3);
}
function normalizeAttributes(e) {
if (!e) return;
const t = {};
for (const [n, r] of Object.entries(e)) {
if (typeof r === "number") {
if (Number.isFinite(r)) t[n] = r;
continue;
}
if (typeof r === "string" || typeof r === "boolean" || r === null) t[n] = r;
}
return Object.keys(t).length > 0 ? t : void 0;
}
function serializeTimelineEvent(e, t) {
const n = normalizeAttributes(e.attributes);
const r = {
schemaVersion: OPENCLAW_DIAGNOSTICS_TIMELINE_SCHEMA_VERSION,
type: e.type,
timestamp: e.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
name: e.name,
...t.OPENCLAW_DIAGNOSTICS_RUN_ID ? { runId: t.OPENCLAW_DIAGNOSTICS_RUN_ID } : {},
...t.OPENCLAW_DIAGNOSTICS_ENV ? { envName: t.OPENCLAW_DIAGNOSTICS_ENV } : {},
pid: process.pid,
...e.runId ? { runId: e.runId } : {},
...e.envName ? { envName: e.envName } : {},
...typeof e.pid === "number" ? { pid: e.pid } : {},
phase: e.phase || void 0,
spanId: e.spanId || void 0,
parentSpanId: e.parentSpanId || void 0,
durationMs: normalizeNumber(e.durationMs),
errorName: e.errorName || void 0,
errorMessage: e.errorMessage || void 0,
p50Ms: normalizeNumber(e.p50Ms),
p95Ms: normalizeNumber(e.p95Ms),
p99Ms: normalizeNumber(e.p99Ms),
maxMs: normalizeNumber(e.maxMs),
activeSpanName: e.activeSpanName || void 0,
provider: e.provider || void 0,
operation: e.operation || void 0,
ok: typeof e.ok === "boolean" ? e.ok : void 0,
status: normalizeNumber(e.status),
command: e.command || void 0,
exitCode: e.exitCode,
signal: e.signal,
attributes: n
};
return `${JSON.stringify(r)}\n`;
}
/** Queues one normalized event; bounded batches append on the next event-loop turn. */
function emitDiagnosticsTimelineEvent(e, t = {}) {
const n = t.env ?? process.env;
if (!isDiagnosticsTimelineEnabled(t)) return;
const r = n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH?.trim();
if (!r) return;
timelineWriter.write(r, e, n);
}
//#endregion
//#region src/infra/worker-diagnostic-script.ts
const scriptBasename = (e) => basename(e).replace(/\.[cm]?[jt]s$/u, ".js");
const entries = createRuntimeProcessEntrypoints(import.meta.url);
const workerScripts = /* @__PURE__ */ new Map();
for (const e of Object.values(entries)) {
const t = scriptBasename(e.distWorkerPath);
workerScripts.set(t, t);
workerScripts.set(scriptBasename(e.sourceModulePath), t);
}
for (const e of Object.values(pluginRuntimeProcessManifest)) {
const t = scriptBasename(e.distWorkerPath);
workerScripts.set(t, t);
workerScripts.set(scriptBasename(e.package.distWorkerPath), t);
workerScripts.set(scriptBasename(`${e.sourceWorkerName}.js`), t);
}
for (const e of Object.values(runtimeProcessSealedManifest)) for (const [t, n] of e.entries) {
const e = scriptBasename(`${n}.mjs`);
if (!workerScripts.has(e)) workerScripts.set(e, scriptBasename(entries[t].distWorkerPath));
}
const workerScriptNames = new Set(workerScripts.values());
/** Imported diagnostics may contain arbitrary paths or names. Preserve only known scripts. */
function normalizeDiagnosticWorkerScript(e) {
return typeof e === "string" && workerScriptNames.has(e) ? e : "other";
}
function workerScriptName(e, t = false) {
if (t || e instanceof URL && e.protocol !== "file:") return "other";
return workerScripts.get(scriptBasename(e instanceof URL ? fileURLToPath(e) : e)) ?? "other";
}
//#endregion
//#region src/infra/diagnostic-events.ts
const EMPTY_DIAGNOSTIC_PRIVATE_DATA = Object.freeze({});
const MAX_ASYNC_DIAGNOSTIC_EVENTS = 1e4;
const MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN = 100;
const DIAGNOSTIC_EVENTS_STATE_KEY = Symbol.for("openclaw.diagnosticEvents.state.v1");
const ASYNC_DIAGNOSTIC_EVENT_TYPES = new Set(ASYNC_DIAGNOSTIC_EVENT_NAMES);
const PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES = new Set(PRIORITY_ASYNC_DIAGNOSTIC_EVENT_NAMES);
const diagnosticEventsState = resolveGlobalSingleton(DIAGNOSTIC_EVENTS_STATE_KEY, () => ({
marker: DIAGNOSTIC_EVENTS_STATE_KEY,
enabled: true,
seq: 0,
listeners: /* @__PURE__ */ new Map(),
trustedListeners: /* @__PURE__ */ new Map(),
toolExecutionListeners: /* @__PURE__ */ new Set(),
toolExecutionSeq: 0,
dispatchDepth: 0,
asyncQueue: [],
asyncDrainScheduled: false,
asyncDroppedEvents: 0,
asyncDroppedTrustedEvents: 0,
asyncDroppedUntrustedEvents: 0,
asyncDroppedPriorityEvents: 0
}));
/** Returns the current process-wide diagnostic dispatcher enable flag. */
function areDiagnosticsEnabledForProcess() {
return diagnosticEventsState.enabled;
}
function dispatchDiagnosticEvent(e, t, n, r, i = {}) {
if (e.dispatchDepth > 100) {
console.error(`[diagnostic-events] recursion guard tripped at depth=${e.dispatchDepth}, dropping type=${t.type}`);
return;
}
e.dispatchDepth += 1;
try {
const a = createDiagnosticValueForListeners(t, true);
const o = r && createDiagnosticValueForListeners(r);
if (!i.trustedListenersOnly) for (const [r, i] of e.listeners) {
if (!isInternalDiagnosticEventInterested(i, t.type, n.trusted)) continue;
try {
r(a(), n);
} catch (e) {
const n = e instanceof Error ? formatErrorStackWithMessage(e) : String(e);
console.error(`[diagnostic-events] listener error type=${t.type} seq=${t.seq}: ${n}`);
}
}
for (const [r, s] of e.trustedListeners) {
if (!isInternalDiagnosticEventInterested(s, t.type, n.trusted)) continue;
try {
const e = a();
const t = isTrustedOtelDiagnosticListener(r);
let c = EMPTY_DIAGNOSTIC_PRIVATE_DATA;
if (s?.includePrivateData !== false) {
c = o?.() ?? EMPTY_DIAGNOSTIC_PRIVATE_DATA;
if (t && (i.hostPluginId || Object.hasOwn(c, "hostPluginId"))) {
const e = {
...c,
hostPluginId: i.hostPluginId
};
if (!i.hostPluginId) Reflect.deleteProperty(e, "hostPluginId");
c = Object.freeze(e);
}
}
r(e, n, c);
} catch (e) {
const n = e instanceof Error ? formatErrorStackWithMessage(e) : String(e);
console.error(`[diagnostic-events] trusted listener error type=${t.type} seq=${t.seq}: ${n}`);
}
}
} finally {
e.dispatchDepth -= 1;
}
}
function isPriorityAsyncDiagnosticEvent(e) {
return e.metadata.trusted && PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES.has(e.event.type);
}
function noteAsyncDiagnosticDrop(e, t) {
e.asyncDroppedEvents += 1;
if (t.metadata.trusted) e.asyncDroppedTrustedEvents += 1;
else e.asyncDroppedUntrustedEvents += 1;
if (isPriorityAsyncDiagnosticEvent(t)) e.asyncDroppedPriorityEvents += 1;
}
function makeRoomForPriorityAsyncDiagnosticEvent(e) {
const t = e.asyncQueue.findIndex((e) => !isPriorityAsyncDiagnosticEvent(e));
if (t >= 0) return e.asyncQueue.splice(t, 1)[0];
return e.asyncQueue.shift();
}
function scheduleAsyncDiagnosticDrain(e) {
if (e.asyncDrainScheduled) return;
e.asyncDrainScheduled = true;
setImmediate(() => {
e.asyncDrainScheduled = false;
const t = e.asyncQueue.splice(0, MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN);
for (const n of t) dispatchDiagnosticEvent(e, n.event, n.metadata, n.privateData, n);
if (e.asyncQueue.length > 0) {
scheduleAsyncDiagnosticDrain(e);
return;
}
dispatchAsyncDiagnosticDropSummary(e);
});
}
function dispatchAsyncDiagnosticDropSummary(e) {
if (e.asyncDroppedEvents <= 0) return;
const t = e.asyncDroppedEvents;
const n = e.asyncDroppedTrustedEvents;
const r = e.asyncDroppedUntrustedEvents;
const i = e.asyncDroppedPriorityEvents;
e.asyncDroppedEvents = 0;
e.asyncDroppedTrustedEvents = 0;
e.asyncDroppedUntrustedEvents = 0;
e.asyncDroppedPriorityEvents = 0;
dispatchDiagnosticEvent(e, enrichDiagnosticEvent(e, {
type: "diagnostic.async_queue.dropped",
droppedEvents: t,
...n > 0 ? { droppedTrustedEvents: n } : {},
...r > 0 ? { droppedUntrustedEvents: r } : {},
...i > 0 ? { droppedPriorityEvents: i } : {},
queueLength: e.asyncQueue.length,
maxQueueLength: MAX_ASYNC_DIAGNOSTIC_EVENTS,
drainBatchSize: MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN
}), Object.freeze({
internal: true,
trusted: false
}));
}
function emitDiagnosticEventWithTrust(e, t, n = {}) {
const r = diagnosticEventsState;
const i = t && isToolExecutionEventInput(e) ? dispatchTrustedToolExecutionEvent(r, e) : void 0;
if (!r.enabled) return;
if (e.type === "security.event" && n.allowSecurityEvent !== true) return;
const a = hasInternalDiagnosticEventInterest(e.type, t);
if (!a && !(t && !n.queuedPhase && hasDiagnosticTracePropagationConsumer())) {
r.seq += 1;
return;
}
let o = enrichDiagnosticEvent(r, i ?? e, !n.queuedPhase);
if (t && o.type === "diagnostic.gc") {
switch (o.kind) {
case "scavenge":
case "mark_sweep_compact":
case "incremental":
case "weak_processing": break;
default: o.kind = void 0;
}
switch (o.reason) {
case "none":
case "forced":
case "synchronous_phantom_processing":
case "all_available_garbage":
case "all_external_memory":
case "schedule_idle":
case "construct_retained":
case "other": break;
default: o.reason = "other";
}
o.thread = o.thread === void 0 || o.thread === "main" ? "main" : normalizeDiagnosticWorkerScript(o.thread);
if (o.thread !== "code-mode-node.worker.js" || typeof o.workerSlot !== "number" || !Number.isInteger(o.workerSlot) || o.workerSlot < 1 || o.workerSlot > 64) o.workerSlot = void 0;
}
const { hostPluginId: s, internal: c = false, privateData: l } = n;
const u = n.trustedTraceContext === true;
const d = Object.freeze({
...c ? { internal: true } : {},
trusted: t,
...n.toolExecutionLiveness ? { [TOOL_EXECUTION_LIVENESS_METADATA_KEY]: n.toolExecutionLiveness } : {},
...n.coreModelRequestLifecycle ? { [CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY]: n.coreModelRequestLifecycle } : {},
...n.coreSemanticRunProgress ? { [CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY]: n.coreSemanticRunProgress } : {},
...u ? { trustedTraceContext: u } : {}
});
const f = t && !n.queuedPhase && shouldPrepareDiagnosticTracePropagation(o);
const p = a && (n.queuedPhase || ASYNC_DIAGNOSTIC_EVENT_TYPES.has(o.type));
if (p) {
if (r.asyncQueue.length >= MAX_ASYNC_DIAGNOSTIC_EVENTS) {
if (!t || !PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES.has(o.type)) {
noteAsyncDiagnosticDrop(r, {
event: o,
metadata: d,
privateData: l,
hostPluginId: s
});
return;
}
const e = makeRoomForPriorityAsyncDiagnosticEvent(r);
if (e) noteAsyncDiagnosticDrop(r, e);
}
const e = {
event: o,
metadata: d,
privateData: l,
hostPluginId: s
};
if (!captureQueuedDiagnosticEvent(e, r.trustedListeners.values())) return;
o = e.event;
r.asyncQueue.push(e);
}
if (f) {
if (!p) o = cloneDiagnosticValueForListener(o, true);
prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(o), d);
}
if (p) scheduleAsyncDiagnosticDrain(r);
else if (a) dispatchDiagnosticEvent(r, o, d, l, { hostPluginId: s });
}
function isToolExecutionEventInput(e) {
return e.type === "tool.execution.started" || e.type === "tool.execution.completed" || e.type === "tool.execution.error" || e.type === "tool.execution.blocked";
}
function dispatchTrustedToolExecutionEvent(e, t) {
e.toolExecutionSeq += 1;
if (e.toolExecutionListeners.size === 0) return;
let n;
try {
n = cloneDiagnosticValueForListener({
...t,
seq: e.toolExecutionSeq,
ts: Date.now()
}, true);
} catch (e) {
console.error(`[diagnostic-events] tool execution clone error type=${t.type}: ${String(e)}`);
return;
}
const r = createDiagnosticValueForListeners(n);
for (const t of e.toolExecutionListeners) try {
t(r());
} catch (e) {
console.error(`[diagnostic-events] tool execution listener error type=${n.type} seq=${n.seq}: ${String(e)}`);
}
return n;
}
/** Emits an untrusted diagnostic event from external/plugin-facing code. */
function emitDiagnosticEvent(e) {
emitDiagnosticEventWithTrust(e, false);
}
/** Emits an untrusted event whose trace context came from OpenClaw-owned scope. */
function emitDiagnosticEventWithTrustedTraceContext(e) {
emitDiagnosticEventWithTrust(e, false, { trustedTraceContext: true });
}
/** Emits a trusted diagnostic event from core/runtime-owned instrumentation. */
function emitTrustedDiagnosticEvent(e) {
if (e.type === "model.usage") recordDiagnosticModelUsageTimeline(e);
const t = consumeToolExecutionLivenessDiagnosticEvent(e);
const n = consumeHostPluginUsageDiagnosticEvent(e);
const r = consumeCoreSemanticRunProgressDiagnosticEvent(e);
emitDiagnosticEventWithTrust(e, true, {
...t ? { toolExecutionLiveness: t } : {},
...n ? {
hostPluginId: n,
internal: true
} : {},
...r ? { coreSemanticRunProgress: r } : {}
});
}
//#endregion
//#region src/utils/parse-json-compat.ts
/**
* JSON parser compatibility helper for persisted config, manifests, and legacy stores.
* Strict JSON stays the fast path; JSON5 is only the authored/legacy fallback.
*/
let json5Runtime;
function isJson5Parser(e) {
return typeof e === "object" && e !== null && "parse" in e && typeof e.parse === "function";
}
function setJson5Runtime(e) {
const t = isJson5Parser(e) ? e : typeof e === "object" && e !== null && "default" in e ? e.default : void 0;
if (!isJson5Parser(t)) throw new Error("json5 parser unavailable");
json5Runtime = t;
return t;
}
function loadJson5Parser() {
if (json5Runtime) return json5Runtime;
const e = getSealedRuntimeJson5();
if (e !== void 0) return setJson5Runtime(e);
if (typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) throw new Error("sealed JSON5 runtime was not registered before use");
return setJson5Runtime(createRequire(import.meta.url)("json5"));
}
/** Parses strict JSON first, then accepts JSON5 syntax such as comments and trailing commas. */
function parseJsonWithJson5Fallback(e, t) {
try {
return JSON.parse(e);
} catch {
return (t ?? loadJson5Parser()).parse(e);
}
}
//#endregion
//#region src/shared/dot-path.ts
/** Appends one config path segment without confusing literal record keys with traversal. */
function appendConfigPathSegment(e, t) {
if (typeof t === "number") return `${e}[${t}]`;
if (!/^[A-Za-z_$][A-Za-z0-9_$:-]*$/.test(t)) return `${e}[${JSON.stringify(t)}]`;
return e ? `${e}.${t}` : t;
}
//#endregion
//#region src/config/env-substitution.ts
const ENV_VAR_NAME_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
const DEFAULT_VALUE_OPERATOR = ":-";
/** Error thrown when a config value references a missing or empty environment variable. */
var MissingEnvVarError = class extends Error {
constructor(e, t) {
super(`Missing env var "${e}" referenced at config path: ${t}`);
this.varName = e;
this.configPath = t;
this.name = "MissingEnvVarError";
}
};
/** Rebuilds the authored placeholder text for a parsed token. */
function renderEnvTemplateToken(e) {
return e.defaultValue === void 0 ? `\${${e.name}}` : `\${${e.name}${DEFAULT_VALUE_OPERATOR}${e.defaultValue}}`;
}
function* iterateEnvTemplateTokens(e) {
for (let t = e.indexOf("$"); t !== -1; t = e.indexOf("$", t + 1)) {
const n = e[t + 1] === "$" && e[t + 2] === "{";
if (!n && e[t + 1] !== "{") continue;
const r = t + (n ? 3 : 2);
const i = e.indexOf("}", r);
if (i === -1) continue;
const a = e.slice(r, i);
const o = a.indexOf(DEFAULT_VALUE_OPERATOR);
const s = o === -1 ? a : a.slice(0, o);
const c = o === -1 ? void 0 : a.slice(o + 2);
if (!ENV_VAR_NAME_PATTERN.test(s) || c?.includes("$") || c?.includes("{")) continue;
yield {
kind: n ? "escaped" : "substitution",
name: s,
defaultValue: c,
start: t,
end: i
};
t = i;
}
}
function substituteString(e, t, n, r) {
if (!e.includes("$")) return e;
const i = parseEnvTemplateSecretRef(e);
if (i && !containsEnvVarReference(e)) r?.onPendingEnvSecretRef?.(i.id, n);
const a = [];
let o = 0;
for (const s of iterateEnvTemplateTokens(e)) {
a.push(e.slice(o, s.start));
o = s.end + 1;
if (s.kind === "escaped") {
a.push(renderEnvTemplateToken(s));
continue;
}
const c = t[s.name];
if (c === void 0 || c === "") {
if (s.defaultValue !== void 0) {
a.push(s.defaultValue);
continue;
}
if (r?.onMissing) {
r.onMissing({
varName: s.name,
configPath: n
});
if (i?.id === s.name) r.onPendingEnvSecretRef?.(s.name, n);
a.push(renderEnvTemplateToken(s));
continue;
}
throw new MissingEnvVarError(s.name, n);
}
if (i?.id === s.name) r?.onResolvedEnvSecretRef?.(s.name, n);
a.push(c);
}
a.push(e.slice(o));
return a.join("");
}
/** Detects unescaped `${VAR}` references without treating escaped `$${VAR}` as references. */
function containsEnvVarReference(e) {
for (const t of iterateEnvTemplateTokens(e)) if (t.kind === "substitution") return true;
return false;
}
/** Resolve config string templates, preserving unresolved text when onMissing is supplied. */
function resolveConfigEnvVars(e, t = process.env, n) {
const r = [];
const visit = (e, i) => {
if (typeof e === "string") return substituteString(e, t, i, n);
if (Array.isArray(e)) {
const t = e.length;
const n = [];
n.length = t;
let a = 0;
r.push(() => {
while (a < t) {
const t = a++;
if (t in e) {
n[t] = visit(e[t], `${i}[${t}]`);
return true;
}
}
return false;
});
return n;
}
if (isPlainObject(e)) {
const t = {};
const n = Object.entries(e)[Symbol.iterator]();
r.push(() => {
const e = n.next();
if (e.done) return false;
const [r, a] = e.value;
t[r] = visit(a, appendConfigPathSegment(i, r));
return true;
});
return t;
}
return e;
};
const i = visit(e, "");
for (let e = r.at(-1); e; e = r.at(-1)) if (!e()) r.pop();
return i;
}
//#endregion
//#region src/config/includes.ts
const INCLUDE_KEY = "$include";
const MAX_INCLUDE_DEPTH = 10;
const MAX_INCLUDE_FILE_BYTES = 2097152;
/** Maximum length for $include path and resolved path (CWE-22 hardening). */
const MAX_INCLUDE_PATH_LENGTH = 4096;
function isConfigContainer(e) {
return Array.isArray(e) || isPlainObject(e);
}
function includeLogicalPath(e) {
const t = [];
for (let n = e; n; n = n.parent) t.push(n.key);
return t.toReversed();
}
var ConfigIncludeError = class extends Error {
constructor(e, t, n) {
super(e);
this.includePath = t;
this.cause = n;
this.name = "ConfigIncludeError";
}
};
/** File access failed; the included configuration has not been validated. */
var ConfigIncludeReadError = class extends ConfigIncludeError {
constructor(...e) {
super(...e);
this.name = "ConfigIncludeReadError";
}
};
var CircularIncludeError = class extends ConfigIncludeError {
constructor(e) {
super(`Circular include detected: ${e.join(" -> ")}`, expectDefined(e[e.length - 1], "chain entry at chain.length 1"));
this.chain = e;
this.name = "CircularIncludeError";
}
};
/** Deep merge: arrays concatenate, objects merge recursively, primitives: source wins */
function deepMerge(e, t) {
return mergeDeep(e, t, {
arrays: "concat",
undefinedValues: "replace"
});
}
var IncludeProcessor = class {
constructor(e, t, n, r) {
this.basePath = e;
this.resolver = t;
this.boundary = n;
this.rootProjectionKeys = r;
}
get rootDir() {
return this.boundary.configRoot.rootDir;
}
process(e) {
const t = [];
let n = this.traverseValue(e, null, false, {
basePath: this.basePath,
visited: /* @__PURE__ */ new Set([path.normalize(this.basePath)]),
depth: 0
});
let r = void 0;
for (;;) {
const e = n.next(r);
if (e.done) {
const i = t.pop();
if (!i) return e.value;
r = e.value;
n = i;
continue;
}
t.push(n);
n = this.traverseValue(e.value.value, e.value.pathLink, e.value.hasArrayAncestor, e.value.context);
}
}
*traverseValue(e, t, n, r) {
if (Array.isArray(e)) {
const n = [];
for (const [i, a] of e.entries()) n.push(isConfigContainer(a) ? yield {
value: a,
pathLink: {
parent: t,
key: String(i)
},
hasArrayAncestor: true,
context: r
} : a);
return n;
}
if (!isPlainObject(e)) return e;
if (!("$include" in e)) {
const i = t === null;
const a = {};
for (const [o, s] of Object.entries(e)) {
if (i && this.rootProjectionKeys && !this.rootProjectionKeys.has(o)) continue;
a[o] = isConfigContainer(s) ? yield {
value: s,
pathLink: {
parent: t,
key: o
},
hasArrayAncestor: n,
context: r
} : s;
}
return a;
}
return yield* this.traverseInclude(e, t, n, r);
}
*traverseInclude(e, t, n, r) {
const i = e[INCLUDE_KEY];
const a = t === null;
const o = Object.keys(e).filter((e) => e !== "$include" && (!a || !this.rootProjectionKeys || this.rootProjectionKeys.has(e)));
const s = Array.isArray(i);
if (!s && typeof i !== "string") throw new ConfigIncludeError(`Invalid $include value: expected string or array of strings, got ${typeof i}`, String(i));
const c = [];
for (const e of s ? i : [i]) {
if (typeof e !== "string") throw new ConfigIncludeError(`Invalid $include array item: expected string, got ${typeof e}`, String(e));
const i = this.loadFileSync(e, r);
c.push({
value: yield {
value: i.parsed,
pathLink: t,
hasArrayAncestor: n,
context: i.nestedContext
},
targetPath: i.resolvedPath
});
}
const l = s ? c.reduce((e, t) => deepMerge(e, t.value), {}) : c[0].value;
this.resolver.onIncludeResolved?.({
path: includeLogicalPath(t),
value: l,
kind: s ? "multiple" : "single",
hasSiblingOverrides: o.length > 0,
hasArrayAncestor: n,
...s ? { targetPaths: c.map((e) => e.targetPath) } : { targetPath: c[0].targetPath }
});
if (o.length === 0) return l;
if (!isPlainObject(l)) throw new ConfigIncludeError("Sibling keys require included content to be an object", typeof i === "string" ? i : INCLUDE_KEY);
const u = {};
for (const i of o) {
const a = e[i];
u[i] = isConfigContainer(a) ? yield {
value: a,
pathLink: {
parent: t,
key: i
},
hasArrayAncestor: n,
context: r
} : a;
}
return deepMerge(l, u);
}
loadFileSync(e, t) {
const { resolvedPath: n, root: r } = this.resolvePath(e, t);
if (t.visited.has(n)) throw new CircularIncludeError([...t.visited, n]);
if (t.depth >= 10) throw new ConfigIncludeError(`Maximum include depth (${10}) exceeded at: ${e}`, e);
const i = this.readFile(e, n, r);
return {
parsed: this.parseFile(e, n, i),
resolvedPath: n,
nestedContext: {
basePath: n,
visited: /* @__PURE__ */ new Set([...t.visited, n]),
depth: t.depth + 1
}
};
}
resolvePath(e, t) {
if (e.includes("\0")) throw new ConfigIncludeError("Include path must not contain null bytes", e);
if (e.length >= MAX_INCLUDE_PATH_LENGTH) throw new ConfigIncludeError(`Include path exceeds maximum length (${MAX_INCLUDE_PATH_LENGTH} characters)`, e);
const n = path.dirname(t.basePath);
const r = path.isAbsolute(e) ? e : path.resolve(n, e);
const i = path.normalize(this.resolver.mapPath?.(r) ?? r);
if (i.length >= MAX_INCLUDE_PATH_LENGTH) throw new ConfigIncludeError(`Resolved include path exceeds maximum length (${MAX_INCLUDE_PATH_LENGTH} characters)`, e);
const a = this.findContainingRoot(i, "rootDir");
if (!a) throw new ConfigIncludeError(`Include path escapes config directory: ${e} (root: ${this.rootDir})`, e);
this.resolver.onLexicalPath?.(i);
try {
const t = fs.realpathSync(i);
const n = this.findContainingRoot(t, "rootRealDir");
if (!n) throw new ConfigIncludeError(`Include path resolves outside config directory (symlink): ${e} (root: ${this.rootDir})`, e);
return {
resolvedPath: i,
root: n
};
} catch (t) {
if (t instanceof ConfigIncludeError) throw t;
if (isMissingPathError(t)) return {
resolvedPath: i,
root: a
};
throw new ConfigIncludeReadError(`Failed to resolve include file realpath: ${e} (resolved: ${i})`, e, t instanceof Error ? t : void 0);
}
}
findContainingRoot(e, t) {
if (isPathInside$1(this.boundary.configRoot[t], e)) return this.boundary.configRoot;
for (const n of this.boundary.allowedRoots) if (isPathInside$1(n[t], e)) return n;
return null;
}
readFile(e, t, n) {
try {
if (this.resolver.readFileWithGuards) return this.resolver.readFileWithGuards({
includePath: e,
resolvedPath: t,
rootRealDir: n.rootRealDir
});
return this.resolver.readFile(t);
} catch (n) {
if (n instanceof ConfigIncludeError) throw n;
throw new ConfigIncludeReadError(`Failed to read include file: ${e} (resolved: ${t})`, e, n instanceof Error ? n : void 0);
}
}
parseFile(e, t, n) {
try {
return this.resolver.parseJson(n);
} catch (n) {
throw new ConfigIncludeError(`Failed to parse include file: ${e} (resolved: ${t})`, e, n instanceof Error ? n : void 0);
}
}
};
function safeRealpath(e) {
try {
return fs.realpathSync(e);
} catch {
return e;
}
}
/** Capture the lexical and canonical include roots once for a resolver traversal. */
function createConfigIncludeBoundary(e, t = []) {
const n = path.normalize(path.dirname(e));
return {
configRoot: {
rootDir: n,
rootRealDir: path.normalize(safeRealpath(n))
},
allowedRoots: t.filter((e) => typeof e === "string" && e.length > 0 && path.isAbsolute(e)).map((e) => {
const t = path.normalize(e);
return {
rootDir: t,
rootRealDir: path.normalize(safeRealpath(t))
};
})
};
}
function readConfigIncludeFileWithGuards(e) {
const t = e.ioFs ?? fs;
const n = e.maxBytes ?? MAX_INCLUDE_FILE_BYTES;
if (!canUseRootFileOpen(t)) {
const n = t.readFileSync(e.resolvedPath, "utf-8");
try {
e.onResolvedPath?.(path.normalize(t.realpathSync(e.resolvedPath)));
} catch {}
return n;
}
const r = openRootFileSync({
absolutePath: e.resolvedPath,
rootPath: e.rootRealDir,
rootRealPath: e.rootRealDir,
boundaryLabel: "config directory",
skipLexicalRootCheck: true,
rejectSymlinks: false,
maxBytes: n,
ioFs: t
});
if (!r.ok) {
if (r.reason === "validation") throw new ConfigIncludeError(`Include file failed security checks (regular file, max ${n} bytes, no hardlinks): ${e.includePath}`, e.includePath);
throw new ConfigIncludeReadError(`Failed to read include file: ${e.includePath} (resolved: ${e.resolvedPath})`, e.includePath, r.error instanceof Error ? r.error : void 0);
}
try {
const n = t.readFileSync(r.fd, "utf-8");
e.onResolvedPath?.(path.normalize(r.path));
return n;
} finally {
t.closeSync(r.fd);
}
}
const defaultResolver = {
readFile: (e) => fs.readFileSync(e, "utf-8"),
readFileWithGuards: readConfigIncludeFileWithGuards,
parseJson: parseJsonWithJson5Fallback
};
/**
* Resolves all $include directives in a parsed config object.
*/
function resolveConfigIncludes(e, t, n = defaultResolver, r = {}) {
const i = createConfigIncludeBoundary(t, r.allowedRoots ?? []);
return new IncludeProcessor(t, n, i).process(e);
}
/**
* Resolves one top-level config field through the canonical include graph while
* leaving unrelated top-level branches untouched. Early bootstrap readers use
* this when a malformed sibling must not hide an independently valid setting.
*/
function resolveConfigIncludesForTopLevelKey(e, t, n, r = defaultResolver, i = {}) {
const a = createConfigIncludeBoundary(t, i.allowedRoots ?? []);
return new IncludeProcessor(t, r, a, /* @__PURE__ */ new Set([n])).process(e);
}
//#endregion
//#region src/logging/state.ts
const LOGGING_STATE_KEY = Symbol.for("openclaw.loggingState");
const APPLIED_LOGGING_CONFIG_UNOWNED = "unowned";
function createUnownedAppliedLoggingConfig() {
return APPLIED_LOGGING_CONFIG_UNOWNED;
}
function createLoggingState() {
return {
appliedConfig: createUnownedAppliedLoggingConfig(),
cachedLogger: null,
cachedSettings: null,
cachedConsoleSettings: null,
overrideSettings: null,
invalidEnvLogLevelValue: null,
consolePatched: false,
forceConsoleToStderr: false,
earlyConsoleRoutingRestore: null,
consoleTimestampPrefix: false,
consoleSubsystemFilter: null,
streamErrorHandlersInstalled: false,
rawConsole: null
};
}
const globalStore = globalThis;
const loggingState = globalStore[LOGGING_STATE_KEY] ?? createLoggingState();
globalStore[LOGGING_STATE_KEY] = loggingState;
//#endregion
//#region src/logging/config.ts
let cachedLoggingConfig;
function resolveLoggingConfigSelector() {
const e = process.env;
return [
e.OPENCLAW_CONFIG_PATH,
e.OPENCLAW_STATE_DIR,
e.OPENCLAW_HOME,
e.OPENCLAW_PROFILE,
e.HOME,
e.USERPROFILE,
e.HOMEDRIVE,
e.HOMEPATH,
e.PREFIX,
e.ANDROID_DATA,
e.OPENCLAW_TEST_FAST,
tryProcessCwd() ?? ""
].map((e) => e ?? "").join("\0");
}
function resolvePartialDiagnosticLoggingConfig(e) {
if (!isRecord(e)) return;
const t = {};
if (typeof e.consoleStyle === "string") try {
const n = resolveConfigEnvVars({ consoleStyle: e.consoleStyle });
if (isRecord(n) && (n.consoleStyle === "pretty" || n.consoleStyle === "compact" || n.consoleStyle === "json")) t.consoleStyle = n.consoleStyle;
} catch {}
if (Array.isArray(e.redactPatterns)) try {
const n = resolveConfigEnvVars({ redactPatterns: e.redactPatterns });
if (isRecord(n) && Array.isArray(n.redactPatterns) && n.redactPatterns.every((e) => typeof e === "string")) t.redactPatterns = n.redactPatterns;
} catch {}
return Object.keys(t).length > 0 ? t : void 0;
}
/** Reads the logging block from config, caching by resolved config path. */
function readLoggingConfig() {
try {
if (loggingState.appliedConfig !== "unowned") return loggingState.appliedConfig;
const e = resolveLoggingConfigSelector();
if (cachedLoggingConfig?.selector === e) return cachedLoggingConfig.logging;
const t = resolveConfigPath();
if (!fs.existsSync(t)) {
cachedLoggingConfig = {
selector: e,
logging: void 0
};
return;
}
const n = parseJsonWithJson5Fallback(fs.readFileSync(t, "utf8"));
const r = resolveIncludeRoots();
let i;
try {
i = resolveConfigIncludesForTopLevelKey(n, t, "logging", void 0, { allowedRoots: r });
} catch {
const e = isRecord(n) ? n.logging : void 0;
if (e === void 0) return;
try {
i = resolveConfigIncludes({ logging: e }, t, void 0, { allowedRoots: r });
} catch {
return resolvePartialDiagnosticLoggingConfig(e);
}
}
let a;
try {
a = resolveConfigEnvVars(i);
} catch {
return resolvePartialDiagnosticLoggingConfig(isRecord(i) ? i.logging : void 0);
}
const o = isRecord(a) ? a.logging : void 0;
const s = isRecord(o) ? o : void 0;
cachedLoggingConfig = {
selector: e,
logging: s
};
return s;
} catch {
return;
}
}
//#endregion
//#region packages/net-policy/src/redact-sensitive-url.ts
const SENSITIVE_URL_QUERY_PARAM_NAMES = /* @__PURE__ */ new Set([
"token",
"key",
"api_key",
"apikey",
"secret",
"access_token",
"auth_token",
"password",
"pass",
"passwd",
"auth",
"jwt",
"session",
"id_token",
"code",
"client_secret",
"app_secret",
"hook_token",
"refresh_token",
"signature",
"x_amz_signature",
"x_amz_security_token",
"private_key",
"credential",
"authorization",
"sig",
"x_api_key",
"x_access_token",
"x_auth_token"
]);
const URL_QUERY_NAME_SEPARATOR_RE = /[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu;
const SUFFIXED_OR_SCOPED_TOKEN_QUERY_PARAM_RE = /(?:^|_)token(?:_[a-f0-9]{16,})?$/u;
const MAX_NESTED_URL_REDACTION_DEPTH = 8;
function normalizeUrlQueryParamName(e) {
let t = e.replace(URL_QUERY_NAME_SEPARATOR_RE, "");
for (let e = 0; e <= MAX_NESTED_URL_REDACTION_DEPTH; e += 1) {
let e;
try {
e = decodeURIComponent(t).replace(URL_QUERY_NAME_SEPARATOR_RE, "");
} catch {
break;
}
if (e === t) return {
value: normalizeLowercaseStringOrEmpty(t).replaceAll("-", "_"),
unresolvedEncoding: false
};
t = e;
}
return {
value: normalizeLowercaseStringOrEmpty(t).replaceAll("-", "_"),
unresolvedEncoding: t.includes("%")
};
}
/** True for auth-like URL query parameter names that should be redacted. */
function isSensitiveUrlQueryParamName(e) {
const t = normalizeUrlQueryParamName(e);
return t.unresolvedEncoding || SENSITIVE_URL_QUERY_PARAM_NAMES.has(t.value) || SUFFIXED_OR_SCOPED_TOKEN_QUERY_PARAM_RE.test(t.value);
}
//#endregion
//#region packages/acp-core/src/structured-auth-redaction.ts
const HTTP_AUTH_SCHEME_PATTERN = "[A-Za-z0-9!#$%&'*+.^_`|~-]+";
const HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN = String.raw`(?:\[REDACTED\]|[^\s\\"',;&#?<>)}\]]+)`;
const HTTP_AUTH_SERIALIZED_TAB_PATTERN = String.raw`\\{1,64}t`;
const HTTP_AUTH_SERIALIZED_INDENT_PATTERN = String.raw`(?:[ \t]+|${HTTP_AUTH_SERIALIZED_TAB_PATTERN})`;
const HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN = String.raw`(?:[ \t]*\r?\n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*\\{1,64}r\\{1,64}n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*\\{1,64}n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*${HTTP_AUTH_SERIALIZED_TAB_PATTERN}[ \t]*|[ \t]*)`;
const HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN = String.raw`(?:[ \t]*\r?\n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*\\{1,64}r\\{1,64}n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*\\{1,64}n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*${HTTP_AUTH_SERIALIZED_TAB_PATTERN}[ \t]*|[ \t]+)`;
const HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN = String.raw`(?:[ \t\r\n]*|[ \t]*\\{1,64}r\\{1,64}n(?:[ \t]*|${HTTP_AUTH_SERIALIZED_TAB_PATTERN})|[ \t]*\\{1,64}n(?:[ \t]*|${HTTP_AUTH_SERIALIZED_TAB_PATTERN})|[ \t]*${HTTP_AUTH_SERIALIZED_TAB_PATTERN}[ \t]*)`;
const HTTP_AUTH_HEADER_BOUNDARY_PATTERN = String.raw`(^|[^A-Za-z0-9_-]|\\{1,64}[rn])`;
const HTTP_AUTH_SERIALIZED_QUOTE_PATTERN = String.raw`(?:\\{1,64}["']|["']|)`;
const CREDENTIAL_STYLE_HEADER_REDACT_PATTERN = String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}(?:x-goog-api-key|api-key|apikey|x-api-token|x-access-token)${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}([^\s\\"',;]+)`;
const STRUCTURED_AUTH_HEADER_RE = new RegExp(String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}(?:Proxy-)?Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(${HTTP_AUTH_SCHEME_PATTERN})${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}`, "giu");
const AUTH_PARAM_TOKEN_RE = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+/u;
const AWS_SCOPE_VALUE_RE = /^[A-Za-z0-9!#$%&'*+.^_`|~:/-]+/u;
function skipHorizontalWhitespace(e, t) {
let n = t;
while (e[n] === " " || e[n] === " ") n += 1;
return n;
}
function skipSerializedBackslashes(e, t) {
let n = t;
while (n - t < 64 && e[n] === "\\") n += 1;
return n;
}
function readSerializedLineEnd(e, t) {
const n = skipSerializedBackslashes(e, t);
if (n === t) return null;
if (e[n] === "n") return n + 1;
if (e[n] !== "r") return null;
const r = skipSerializedBackslashes(e, n + 1);
return r > n + 1 && e[r] === "n" ? r + 1 : null;
}
function readSerializedTabEnd(e, t) {
const n = skipSerializedBackslashes(e, t);
return n > t && e[n] === "t" ? n + 1 : null;
}
function skipAuthWhitespace(e, t) {
let n = t;
for (;;) {
n = skipHorizontalWhitespace(e, n);
const t = readSerializedTabEnd(e, n);
if (t !== null) {
n = t;
continue;
}
const r = e[n] === "\r" && e[n + 1] === "\n" ? n + 2 : e[n] === "\n" ? n + 1 : readSerializedLineEnd(e, n);
if (r === null || e[r] !== " " && e[r] !== " " && readSerializedTabEnd(e, r) === null) return n;
n = r;
}
}
function readAuthParamName(e, t) {
const n = AUTH_PARAM_TOKEN_RE.exec(e.slice(t));
return n ? {
name: n[0].toLowerCase(),
end: t + n[0].length
} : null;
}
function isAuthHeaderStart(e, t) {
const n = e[t - 1];
if (!((n === "n" || n === "r") && e[t - 2] === "\\") && n !== void 0 && /[A-Za-z0-9_-]/u.test(n)) return false;
const r = "proxy-authorization";
const i = "authorization";
const a = e.slice(t, t + 19).toLowerCase();
const o = a === r ? r : a.startsWith(i) ? i : null;
if (!o) return false;
const s = t + o.length;
let c = skipSerializedBackslashes(e, s);
if (e[c] === "\"" || e[c] === "'") c += 1;
else if (c > s) return false;
c = skipHorizontalWhitespace(e, c);
return e[c] === ":" || e[c] === "=";
}
function findNextAuthParamStart(e, t) {
let n = t;
for (;;) {
n = skipAuthWhitespace(e, n);
if (n > t && isAuthHeaderStart(e, n)) return null;
if (n >= e.length || e[n] === "\r" || e[n] === "\n" || e[n] === ";") return null;
if (e[n] === ",") {
n += 1;
continue;
}
const r = readAuthParamName(e, n);
if (r) {
const t = skipAuthWhitespace(e, r.end);
if (e[t] === "=" && e[t + 1] !== "=") return n;
}
while (n < e.length) {
const r = skipAuthWhitespace(e, n);
if (r > n) {
n = r;
continue;
}
if (n > t && isAuthHeaderStart(e, n)) return null;
const i = e[n];
if (i === "\r" || i === "\n" || i === ";") return null;
n += 1;
if (i === ",") break;
}
}
}
function usesAuthParams(e) {
return e === "digest" || e === "hawk" || e.startsWith("aws4-");
}
function isAuthFieldEnd(e) {
return e === void 0 || e === "\r" || e === "\n" || e === ";" || e === "\\" || e === "\"" || e === "'" || e === "}" || e === "]";
}
function findAuthFieldEnd(e, t) {
let n = t;
while (n < e.length) {
const r = skipAuthWhitespace(e, n);
if (r > n) {
n = r;
continue;
}
if (n > t && isAuthHeaderStart(e, n)) break;
if (isAuthFieldEnd(e[n])) break;
n += 1;
}
return n;
}
function readParamValue(e, t, n) {
let r = 0;
while (e[t + r] === "\\") r += 1;
const i = r > 0 && e[t + r] === "\"";
const a = e[t] === "\"" || e[t] === "'" ? e[t] : void 0;
if (a || i) {
let n = t + (i ? r + 1 : 1);
while (n < e.length) {
if (e[n] === "\r" || e[n] === "\n") {
const t = skipAuthWhitespace(e, n);
if (t === n) break;
n = t;
continue;
}
if (i && e[n] === "\\") {
let t = n + 1;
while (e[t] === "\\") t += 1;
if (e[t] === "\"") {
if ((t - n) % (2 * (r + 1)) === r) return t + 1;
n = t + 1;
continue;
}
n = t;
continue;
}
if (!i && e[n] === "\\" && n + 1 < e.length) {
n += 2;
continue;
}
if (!i && e[n] === a) return n + 1;
n += 1;
}
return n > t + 1 ? n : null;
}
if (n.signedHeaders) {
const n = /^:?[A-Za-z0-9!#$%&'*+.^_`|~-]+(?:;:?[A-Za-z0-9!#$%&'*+.^_`|~-]+)*/u.exec(e.slice(t));
if (!n) return null;
const r = t + n[0].length;
const i = e[r];
return i === void 0 || i === "," || i === " " || i === " " || i === "\r" || i === "\n" ? r : null;
}
const o = (n.awsScope ? AWS_SCOPE_VALUE_RE : AUTH_PARAM_TOKEN_RE).exec(e.slice(t));
return o ? t + o[0].length : null;
}
function findStructuredAuthParamRanges(e) {
const t = [];
for (const n of e.matchAll(STRUCTURED_AUTH_HEADER_RE)) {
const r = (n[2] ?? "").toLowerCase();
let i = (n.index ?? 0) + n[0].length;
const a = i;
let o = i;
const s = readAuthParamName(e, i);
const c = s ? skipAuthWhitespace(e, s.end) : void 0;
if (!s || c === void 0 || e[c] !== "=" || e[c + 1] === "=") {
if (e[skipAuthWhitespace(e, i)] !== "," && !usesAuthParams(r)) continue;
const t = findNextAuthParamStart(e, i);
if (t === null) continue;
i = t;
}
for (;;) {
const t = readAuthParamName(e, i);
if (!t) break;
i = skipAuthWhitespace(e, t.end);
if (e[i] !== "=") break;
i = skipAuthWhitespace(e, i + 1);
const n = readParamValue(e, i, {
awsScope: r.startsWith("aws4-") && t.name === "credential",
signedHeaders: t.name === "signedheaders"
});
if (n === null) {
const t = findNextAuthParamStart(e, i);
if (t !== null) {
i = t;
continue;
}
o = Math.max(o, findAuthFieldEnd(e, i));
break;
}
o = n;
const a = skipAuthWhitespace(e, n);
if (e[a] !== ",") {
if (!isAuthFieldEnd(e[a])) {
const t = findNextAuthParamStart(e, a);
if (t !== null) {
i = t;
continue;
}
o = Math.max(o, findAuthFieldEnd(e, a));
}
break;
}
const s = findNextAuthParamStart(e, a + 1);
if (s === null) break;
i = s;
}
if (o > a) t.push({
start: a,
end: o
});
}
return t;
}
function redactStructuredAuthHeaders(e, t) {
const n = [];
let r = 0;
for (const i of findStructuredAuthParamRanges(e)) {
if (n.length === 0 || i.start > r) n.push(e.slice(r, i.start), t);
r = Math.max(r, i.end);
}
n.push(e.slice(r));
return n.join("");
}
//#endregion
//#region src/security/safe-regex.ts
const SAFE_REGEX_CACHE_MAX = 256;
const safeRegexCache = /* @__PURE__ */ new Map();
function createParseFrame() {
return {
lastToken: null,
containsRepetition: false,
hasAlternation: false,
branchMinLength: 0,
branchMaxLength: 0,
altMinLength: null,
altMaxLength: null
};
}
function addLength(e, t) {
if (!Number.isFinite(e) || !Number.isFinite(t)) return Number.POSITIVE_INFINITY;
return e + t;
}
function multiplyLength(e, t) {
if (!Number.isFinite(e)) return t === 0 ? 0 : Number.POSITIVE_INFINITY;
return e * t;
}
function recordAlternative(e) {
if (e.altMinLength === null || e.altMaxLength === null) {
e.altMinLength = e.branchMinLength;
e.altMaxLength = e.branchMaxLength;
return;
}
e.altMinLength = Math.min(e.altMinLength, e.branchMinLength);
e.altMaxLength = Math.max(e.altMaxLength, e.branchMaxLength);
}
function readQuantifier(e, t) {
const n = e[t];
const r = e[t + 1] === "?" ? 2 : 1;
if (n === "*") return {
consumed: r,
minRepeat: 0,
maxRepeat: null
};
if (n === "+") return {
consumed: r,
minRepeat: 1,
maxRepeat: null
};
if (n === "?") return {
consumed: r,
minRepeat: 0,
maxRepeat: 1
};
if (n !== "{") return null;
let i = t + 1;
while (i < e.length && /\d/.test(e.charAt(i))) i += 1;
if (i === t + 1) return null;
const a = Number.parseInt(e.slice(t + 1, i), 10);
let o = a;
if (e[i] === ",") {
i += 1;
const t = i;
while (i < e.length && /\d/.test(e.charAt(i))) i += 1;
o = i === t ? null : Number.parseInt(e.slice(t, i), 10);
}
if (e[i] !== "}") return null;
i += 1;
if (e[i] === "?") i += 1;
if (o !== null && o < a) return null;
return {
consumed: i - t,
minRepeat: a,
maxRepeat: o
};
}
function hasNestedRepetition(e) {
const t = [createParseFrame()];
let n = false;
const emitToken = (e) => {
const n = expectDefined(t[t.length - 1], "frames entry at frames.length 1");
n.lastToken = e;
if (e.containsRepetition) n.containsRepetition = true;
n.branchMinLength = addLength(n.branchMinLength, e.minLength);
n.branchMaxLength = addLength(n.branchMaxLength, e.maxLength);
};
const emitSimpleToken = () => {
emitToken({
containsRepetition: false,
hasAmbiguousAlternation: false,
minLength: 1,
maxLength: 1
});
};
for (let r = 0; r < e.length; r += 1) {
const i = e[r];
if (n) {
if (i === "\\") r += 1;
else if (i === "]") n = false;
continue;
}
if (i === "\\") {
r += 1;
emitSimpleToken();
continue;
}
if (i === "[") {
n = true;
emitSimpleToken();
continue;
}
if (i === "(") {
t.push(createParseFrame());
continue;
}
if (i === ")") {
if (t.length > 1) {
const e = t.pop();
if (e.hasAlternation) recordAlternative(e);
const n = e.hasAlternation ? e.altMinLength ?? 0 : e.branchMinLength;
const r = e.hasAlternation ? e.altMaxLength ?? 0 : e.branchMaxLength;
emitToken({
containsRepetition: e.containsRepetition,
hasAmbiguousAlternation: e.hasAlternation && e.altMinLength !== null && e.altMaxLength !== null && e.altMinLength !== e.altMaxLength,
minLength: n,
maxLength: r
});
}
continue;
}
if (i === "|") {
const e = expectDefined(t[t.length - 1], "frames entry at frames.length 1");
e.hasAlternation = true;
recordAlternative(e);
e.branchMinLength = 0;
e.branchMaxLength = 0;
e.lastToken = null;
continue;
}
const a = readQuantifier(e, r);
if (!a) {
emitSimpleToken();
continue;
}
r += a.consumed - 1;
const o = expectDefined(t[t.length - 1], "frames entry at frames.length 1");
const s = o.lastToken;
if (!s) continue;
if (s.containsRepetition) return true;
if (s.hasAmbiguousAlternation && a.maxRepeat === null) return true;
const c = s.minLength;
const l = s.maxLength;
s.minLength = multiplyLength(s.minLength, a.minRepeat);
s.maxLength = a.maxRepeat === null ? Number.POSITIVE_INFINITY : multiplyLength(s.maxLength, a.maxRepeat);
s.containsRepetition = true;
o.containsRepetition = true;
o.branchMinLength = o.branchMinLength - c + s.minLength;
o.branchMaxLength = addLength(Number.isFinite(o.branchMaxLength) && Number.isFinite(l) ? o.branchMaxLength - l : Number.POSITIVE_INFINITY, s.maxLength);
}
return false;
}
function compileSafeRegexDetailed(e, t = "") {
const n = e.trim();
if (!n) return {
regex: null,
source: n,
flags: t,
reason: "empty"
};
const r = `${t}::${n}`;
const i = safeRegexCache.get(r);
if (i) return i;
let a;
if (hasNestedRepetition(n)) a = {
regex: null,
source: n,
flags: t,
reason: "unsafe-nested-repetition"
};
else try {
a = {
regex: new RegExp(n, t),
source: n,
flags: t,
reason: null
};
} catch {
a = {
regex: null,
source: n,
flags: t,
reason: "invalid-regex"
};
}
safeRegexCache.set(r, a);
pruneMapToMaxSize(safeRegexCache, SAFE_REGEX_CACHE_MAX);
return a;
}
//#endregion
//#region src/security/config-regex.ts
/**
* Compile a single user-configured regex with the shared safe-regex guardrails.
* Returns null for blank patterns so optional config entries can be skipped silently.
*/
function compileConfigRegex(e, t = "") {
const n = compileSafeRegexDetailed(e, t);
if (n.reason === "empty") return null;
return {
regex: n.regex,
pattern: n.source,
flags: n.flags,
reason: n.reason
};
}
//#endregion
//#region src/logging/logger-file-message.ts
const MAX_FILE_LOG_MESSAGE_CHARS = 4096;
function clampMessage(e) {
return e.length > MAX_FILE_LOG_MESSAGE_CHARS ? `${truncateUtf16Safe(e, MAX_FILE_LOG_MESSAGE_CHARS)}...(truncated)` : e;
}
function stringifyFileLogMessagePart(e, t) {
if (t) return JSON.stringify(e);
if (typeof e === "string") return e;
if (typeof e === "number" || typeof e === "boolean" || typeof e === "bigint") return String(e);
if (isRecord(e) && typeof e.message === "string") return e.message;
}
function serializeFileLogRecord(e, t = []) {
const n = [];
const r = JSON.parse(JSON.stringify(e, function(e, t) {
while (n.length > 0 && n.at(-1) !== this) n.pop();
if (typeof t === "bigint") return String(t);
if (t !== null && typeof t === "object") {
if (n.includes(t)) return "[Circular]";
n.push(t);
}
return t;
}));
if (!isRecord(r)) throw new TypeError("File log records must serialize to objects");
const i = [];
for (const { key: e, json: n, primitiveText: a } of t) {
const t = a ?? stringifyFileLogMessagePart(r[e], n);
if (t?.trim()) i.push(t);
}
if (i.length > 0) {
const e = clampMessage(i.join(" "));
if (Object.hasOwn(r, "message")) r.message = e;
else {
const t = Object.entries(r);
t.splice(t.findIndex(([e]) => e === "hostname") + 1, 0, ["message", e]);
return JSON.stringify(Object.fromEntries(t));
}
}
return JSON.stringify(r);
}
//#endregion
//#region src/logging/redact-bounded.ts
const REDACT_REGEX_CHUNK_THRESHOLD = 32768;
const REDACT_REGEX_CHUNK_SIZE = 16384;
/** Applies a regex replacement in chunks once input crosses the redaction size threshold. */
function replacePatternBounded(e, t, n) {
if (e.length <= REDACT_REGEX_CHUNK_THRESHOLD) return e.replace(t, n);
let r;
for (let i = 0; i < e.length; i += REDACT_REGEX_CHUNK_SIZE) {
const a = e.slice(i, i + REDACT_REGEX_CHUNK_SIZE);
const o = a.replace(t, n);
if (r !== void 0) r += o;
else if (o !== a) r = e.slice(0, i) + o;
}
return r ?? e;
}
//#endregion
//#region src/logging/redact-edit-composition.ts
/** Compose sorted, disjoint current-value edits while retaining original source spans. */
function composeRedactionEdits(e, t, n) {
if (t.length === 0) return n;
const r = [];
let i = 0;
for (const e of t) {
if (i < e.start) r.push({
start: i,
end: e.start
});
r.push(e);
i = e.end;
}
if (i < e) r.push({
start: i,
end: e
});
const a = [];
let o = 0;
let s = 0;
let c = 0;
const consume = (t, n) => {
if (t === c) {
const t = r[o];
if (!t) return {
start: e,
end: e
};
const n = t.replacement === void 0 ? t.start + s : t.start;
return {
start: n,
end: t.replacement !== void 0 && s > 0 ? t.end : n
};
}
let i;
let l = 0;
while (c < t) {
const e = expectDefined(r[o], "current redaction piece");
const u = e.replacement?.length ?? e.end - e.start;
const d = Math.min(u - s, t - c);
const f = e.replacement === void 0 ? e.start + s : e.start;
const p = e.replacement === void 0 ? f + d : e.end;
i ??= f;
l = p;
if (n && d > 0) a.push({
start: f,
end: p,
replacement: e.replacement?.slice(s, s + d)
});
c += d;
s += d;
if (s === u) {
o += 1;
s = 0;
}
}
return {
start: i ?? l,
end: l
};
};
for (const e of n) {
consume(e.start, true);
a.push({
...consume(e.end, false),
replacement: e.replacement
});
}
while (o < r.length) {
const e = expectDefined(r[o], "remaining redaction piece");
consume(c + (e.replacement?.length ?? e.end - e.start) - s, true);
}
const l = [];
let u = [];
let d;
const flush = () => {
if (d) {
d.replacement = u.join("");
l.push(d);
d = void 0;
u = [];
}
};
for (const e of a) {
if (e.replacement === void 0) {
flush();
continue;
}
const t = d && d.start === e.start && d.end === e.end && e.start === e.end;
if (!d || e.start >= d.end && !t) {
flush();
d = {
start: e.start,
end: e.end,
replacement: ""
};
} else d.end = Math.max(d.end, e.end);
u.push(e.replacement);
}
flush();
return l;
}
/** Project source-span replacements onto a value that already contains replacements. */
function rebaseRedactionEdits(e, t) {
let n = 0;
const r = e.map((e) => {
const t = e.start + n;
n += e.replacement.length - (e.end - e.start);
return {
...e,
currentStart: t,
currentEnd: e.end + n
};
});
const boundary = (e, t) => {
let n = 0;
let i = r.length;
while (n < i) {
const t = n + i >>> 1;
const a = expectDefined(r[t], "source redaction span");
if (a.end < e || a.end === e && a.start !== a.end) n = t + 1;
else i = t;
}
const a = r[n];
if (a && (e > a.start || e === a.start && a.start === a.end)) return t ? a.currentEnd : a.currentStart;
const o = r[n - 1];
return e + (o ? o.currentEnd - o.end : 0);
};
return t.map((e) => ({
start: boundary(e.start, false),
end: boundary(e.end, true),
replacement: e.replacement
}));
}
function mergeRedactionEdits(e) {
e.sort((e, t) => e.start - t.start || e.end - t.end);
const t = [];
for (const n of e) {
const e = t.at(-1);
if (!e || n.start >= e.end) t.push({ ...n });
else if (n.start !== e.start || n.end !== e.end || n.replacement !== e.replacement) {
e.end = Math.max(e.end, n.end);
e.replacement = "***";
}
}
return t;
}
function applyRedactionEdits(e, t) {
const n = [];
let r = 0;
for (const i of mergeRedactionEdits(t)) {
n.push(e.slice(r, i.start), i.replacement);
r = i.end;
}
return n.join("") + e.slice(r);
}
//#endregion
//#region src/logging/redact-json-tokens.ts
const JSON_TOKEN_RE = /"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}[\]]/g;
function skipWhitespace(e, t) {
let n = t;
while (e[n] === " " || e[n] === " " || e[n] === "\r" || e[n] === "\n") n += 1;
return n;
}
function readScalarTokens(e, t) {
const n = [];
const r = [];
const i = {
key: "",
path: [],
origins: t,
origin: t.value,
objectPath: true
};
const valueContext = (e) => !e ? i : e.array ? {
...e.context,
origin: e.context.origins?.value ?? e.context.origin,
origins: e.context.origins?.children.get(String(e.nextIndex++))
} : expectDefined(e.field, "JSON object field context");
for (const t of e.matchAll(JSON_TOKEN_RE)) {
const i = t[0];
const a = r.at(-1);
if (i === "{" || i === "[") {
const e = valueContext(a);
const o = i === "[";
r.push({
array: o,
nextIndex: 0,
context: o ? {
...e,
objectPath: false
} : e,
start: t.index,
tokenStart: n.length
});
continue;
}
if (i === "}" || i === "]") {
const i = expectDefined(r.pop(), "JSON container");
if (i.tokenStart === n.length) {
const r = t.index + 1;
const a = e.slice(i.start, r);
n.push({
...i.context,
isKey: false,
string: false,
value: a,
start: i.start,
end: r,
escaped: false,
edits: [],
projectedEdits: [],
currentValue: a,
currentStart: i.start,
currentEnd: r
});
}
continue;
}
const o = t.index;
const s = o + i.length;
const c = i.startsWith("\"");
const l = c ? JSON.parse(i) : i;
const u = skipWhitespace(e, s);
const d = c && e[u] === ":";
let f;
if (d) {
const t = expectDefined(a, "JSON property container");
const n = t.context;
f = {
key: "",
path: [],
origin: n.origin,
objectPath: false,
rootKey: n.rootKey,
rootValueStart: n.rootValueStart
};
const i = skipWhitespace(e, u + 1);
t.field = {
key: l,
path: [...n.path, l],
origins: n.origins?.children.get(l),
origin: n.origins?.value ?? n.origin,
objectPath: n.objectPath,
rootKey: r.length === 1 ? l : n.rootKey,
rootValueStart: r.length === 1 ? i : n.rootValueStart
};
} else f = valueContext(a);
const p = d ? {
structured: false,
primitiveMask: false
} : f.origins?.value ?? f.origin;
n.push({
...f,
origin: p,
start: o,
end: s,
isKey: d,
string: c,
value: l,
escaped: c && i.includes("\\"),
edits: [],
projectedEdits: [],
currentValue: l,
currentStart: o,
currentEnd: s
});
}
return n;
}
function readBatchTokens(e, t, n = false) {
const r = [];
let i = 0;
for (const a of e.split("\n")) {
let e = false;
try {
JSON.parse(a);
e = true;
} catch {}
if (e) for (const e of readScalarTokens(a, t)) {
e.deferEncoding = !e.string;
e.start += i;
e.end += i;
e.currentStart += i;
e.currentEnd += i;
r.push(e);
}
else {
const e = r.at(-1);
if (!n && e?.raw && e.end + 1 === i) {
e.value += `\n${a}`;
e.currentValue = e.value;
e.end = e.currentEnd = i + a.length;
} else r.push({
raw: true,
origin: t.value,
key: "",
path: [],
objectPath: false,
isKey: false,
string: false,
value: a,
escaped: false,
start: i,
end: i + a.length,
currentStart: i,
currentEnd: i + a.length,
currentValue: a,
edits: [],
projectedEdits: []
});
}
i += a.length + 1;
}
return r;
}
//#endregion
//#region src/logging/redact-pattern-runtime.ts
function parseRedactPatternSource(e) {
const t = e.match(/^\/(.+)\/([gimsuy]*)$/);
if (!t) return [e, "gi"];
const n = t[1] ?? "";
const r = t[2] ?? "";
return [n, r.includes("g") ? r : `${r}g`];
}
const OPEN_REPEAT_RE = /^\{(\d+),\}/;
const BOUNDED_REPEAT_RE = /^\{(?:\d+(?:,\d*)?|,\d+)\}/;
const HEX_DIGIT_RE = /[0-9A-Fa-f]/;
const ASSERTION_ESCAPE_CHARS = /* @__PURE__ */ new Set(["b", "B"]);
const escapeHexValue = (e, t) => {
let n = 0;
for (let r = 0; r < 4; r += 1) {
const i = e[t + r];
if (i === void 0 || !HEX_DIGIT_RE.test(i)) return null;
n = n * 16 + Number.parseInt(i, 16);
}
return n;
};
/** True when the escape at `i` is a `\uXXXX` high-surrogate escape. */
const isHighSurrogateEscape = (e, t) => {
const n = escapeHexValue(e, t + 2);
return n !== null && n >= 55296 && n <= 56319;
};
/** True when the escape at `i` is a `\uXXXX` low-surrogate escape. */
const isLowSurrogateEscape = (e, t) => {
const n = escapeHexValue(e, t + 2);
return n !== null && n >= 56320 && n <= 57343;
};
/** End index (exclusive) of the single atom introduced by the escape at `i` (a backslash), or -1. */
function escapeAtomEnd(e, t) {
const n = e[t + 1];
if (n === void 0) return -1;
if (ASSERTION_ESCAPE_CHARS.has(n)) return t + 2;
if (n === "x") return HEX_DIGIT_RE.test(e[t + 2] ?? "") && HEX_DIGIT_RE.test(e[t + 3] ?? "") ? t + 4 : t + 2;
if ((n === "u" || n === "p" || n === "P") && e[t + 2] === "{") {
const n = e.indexOf("}", t + 3);
return n === -1 ? t + 2 : n + 1;
}
if (n === "u") {
let n = t + 2;
while (n < t + 6 && HEX_DIGIT_RE.test(e[n] ?? "")) n += 1;
return n;
}
if (n === "c") return t + 3;
if (n === "k" && e[t + 2] === "<") {
const n = e.indexOf(">", t + 3);
return n === -1 ? t + 2 : n + 1;
}
if (n >= "0" && n <= "9") {
let n = t + 2;
for (let t = n; t < e.length; t += 1) {
const r = e[t];
if (r === void 0 || r < "0" || r > "9") break;
n = t + 1;
}
return n;
}
return t + 2;
}
/** End index (exclusive) of the character class starting at `i` (an unescaped bracket). */
function classAtomEnd(e, t) {
let n = t + 1;
if (e[n] === "^") n += 1;
if (e[n] === "]") return -1;
while (n < e.length) {
const t = e[n];
if (t === "\\") {
n += 2;
continue;
}
if (t === "]") return n + 1;
n += 1;
}
return e.length;
}
/**
* Rewrites open-ended repeats `X{n,}` into `X{n}X*` for flat single-character atoms `X`
* (one literal, one escaped atom, or one bracket class). Greedy `X{n,}` and `X{n}X*`
* accept the same strings in the same backtracking order, but the latter never grows one
* backtrack stack entry per repetition, so multi-megabyte runs no longer overflow.
* Bounded repeats, quantifiers after groups, and quantified atoms are left untouched.
* `flags` decides atom boundaries for literal astral characters: under `u` a surrogate pair
* is one atom; without `u` JavaScript quantifies only the trailing code unit, so the pair
* must keep its per-unit handling and the original language.
*/
function rewriteOpenEndedRepeats(e, t = "") {
if (!e.includes("{")) return e;
let n = "";
let r = -1;
let i = -1;
let a = 0;
while (a < e.length) {
const o = e[a];
let s = a + 1;
let c = true;
if (o === "\\") {
s = escapeAtomEnd(e, a);
if (s < 0) {
s = a + 1;
c = false;
} else if (t.includes("u") && isHighSurrogateEscape(e, a) && e[s] === "\\" && isLowSurrogateEscape(e, s)) s = escapeAtomEnd(e, s);
else c = !ASSERTION_ESCAPE_CHARS.has(e[a + 1]);
} else if (o === "[") {
s = classAtomEnd(e, a);
if (s < 0) return e;
} else if (o === "{") {
const t = OPEN_REPEAT_RE.exec(e.slice(a));
const o = t && r >= 0 ? t : BOUNDED_REPEAT_RE.exec(e.slice(a));
if (o) {
n += o === t ? `{${t[1]}}${e.slice(r, i)}*` : o[0];
a += o[0].length;
if (e[a] === "?") {
n += "?";
a += 1;
}
r = -1;
continue;
}
} else if (t.includes("u") && o >= "\ud800" && o <= "\udbff" && a + 1 < e.length && e[a + 1] >= "\udc00" && e[a + 1] <= "\udfff") s = a + 2;
else c = !"*+?()|^$".includes(o);
n += e.slice(a, s);
r = c ? a : -1;
i = s;
a = s;
}
return n;
}
function readRedactMatch(e) {
const t = e.length > 0 && typeof e[e.length - 1] === "object" && e[e.length - 1] !== null ? e.length - 2 : e.length - 1;
const n = t - 1;
const r = typeof e[0] === "string" ? e[0] : "";
const i = e.slice(1, n).map((e) => typeof e === "string" ? e : "");
const a = typeof e[n] === "number" ? e[n] : -1;
return {
match: r,
groups: i,
input: typeof e[t] === "string" ? e[t] : "",
offset: a
};
}
const patternPrefilters = /* @__PURE__ */ new WeakMap();
function setRedactPatternPrefilter(e, t) {
if (patternPrefilters.has(e)) return;
const n = e.source;
const r = e.exec;
const i = e instanceof RegExp ? e.flags : void 0;
const a = e instanceof RegExp ? e[Symbol.replace] : void 0;
patternPrefilters.set(e, (o) => e.source !== n || e.exec !== r || e instanceof RegExp && (e.flags !== i || e[Symbol.replace] !== a) || t(o));
}
const indexedPatterns = /* @__PURE__ */ new WeakMap();
function selectSecretCapture(e, t) {
const n = {
index: -1,
value: e
};
for (let e = 0; e < t.length; e++) {
const r = t[e];
if (typeof r === "string" && r.length > 0) {
n.index = e;
n.value = r;
}
}
return n;
}
function getSecretCaptureStart(e, t, n, r, i) {
const a = i.index;
if (!(e instanceof RegExp) || r < 0 || !t) return n.lastIndexOf(i.value);
let o = indexedPatterns.get(e);
if (!o) {
o = new RegExp(e.source, `${e.flags.replace("d", "").replace("g", "")}dg`);
indexedPatterns.set(e, o);
}
o.lastIndex = r;
const s = o.exec(t);
const c = s?.indices?.[a + 1];
return s?.index === r && s[0] === n && c ? c[0] - r : n.lastIndexOf(i.value);
}
const globalPatterns = /* @__PURE__ */ new WeakMap();
function visitRedactMatches(e, t, n) {
if (patternPrefilters.get(t)?.(e) === false) return;
if (!(t instanceof RegExp)) {
for (const r of t.exec(e)) n(r, t);
return;
}
let r = t.global ? t : globalPatterns.get(t);
if (!r) {
r = new RegExp(t.source, `${t.flags}g`);
globalPatterns.set(t, r);
}
const i = r.unicode || r.flags.includes("v");
let a = 0;
while (a <= e.length) {
const o = r.lastIndex;
let s;
try {
r.lastIndex = a;
s = r.exec(e);
} finally {
r.lastIndex = o;
}
if (!s) return;
a = s.index + s[0].length;
if (!s[0]) {
const t = e.codePointAt(a);
a += i && t !== void 0 && t > 65535 ? 2 : 1;
}
n({
match: s[0],
groups: s.slice(1).map((e) => e ?? ""),
input: e,
offset: s.index
}, t);
}
}
function replaceRedactPattern(e, t, n, r) {
if (t instanceof RegExp) {
if (patternPrefilters.get(t)?.(e) === false) {
t.lastIndex = 0;
return e;
}
return e.replace(t, r ?? ((...e) => n(readRedactMatch(e))));
}
const i = [];
let a = 0;
visitRedactMatches(e, t, (t) => {
i.push(e.slice(a, t.offset), n(t));
a = t.offset + t.match.length;
});
return i.length ? i.join("") + e.slice(a) : e;
}
function redactPemBlock(e, t) {
const n = e.split(/\r?\n/).filter(Boolean);
if (n.length < 2) return "***";
return `${n[0]}\n${t}\n${n[n.length - 1]}`;
}
//#endregion
//#region src/logging/redact-json.ts
function stringBoundaries(e, t, n) {
const r = /* @__PURE__ */ new Map();
let i = 0;
for (let a = t; a < n; i += 1) {
r.set(a, i);
a += e[a] === "\\" ? e[a + 1] === "u" ? 6 : 2 : 1;
}
r.set(n, i);
return r;
}
function decodedBoundary(e, t, n) {
if (!t.escaped) return n - t.start - 1;
t.boundaries ??= stringBoundaries(e, t.start + 1, t.end - 1);
return t.boundaries.get(n);
}
function encodedBoundary(e, t, n) {
if (!t.escaped) return t.start + 1 + n;
if (!t.encodedBoundaries) {
t.boundaries ??= stringBoundaries(e, t.start + 1, t.end - 1);
t.encodedBoundaries = [];
for (const [e, n] of t.boundaries) t.encodedBoundaries[n] = e;
}
return expectDefined(t.encodedBoundaries[n], "decoded JSON edit boundary");
}
function projectMessageEdits(e, t, n, r) {
const i = new Map(n.parts.map((e) => [e.key, e]));
const a = [];
for (const o of t) {
if (!o.isKey && o.path.length === 1 && o.key === "message") continue;
const t = o.rootKey === void 0 ? void 0 : i.get(o.rootKey);
if (!t) continue;
if (!t.json && (o.isKey || (t.messageField ? o.path.length !== 2 || o.key !== "message" : o.path.length !== 1))) continue;
const s = r(o);
for (const r of s) {
let i;
let s;
let c = r.replacement;
if (t.json) {
const n = t.start - expectDefined(o.rootValueStart, "displayed JSON argument");
if (o.string) {
i = n + encodedBoundary(e, o, r.start);
s = n + encodedBoundary(e, o, r.end);
c = JSON.stringify(c).slice(1, -1);
} else {
i = n + o.start;
s = n + o.end;
c = JSON.stringify(c);
}
} else {
i = t.start + r.start;
s = t.start + r.end;
}
if (i < n.contentLength) a.push({
start: i,
end: Math.min(s, n.contentLength),
replacement: c,
scalar: t.json && !o.string
});
}
}
return a.toSorted((e, t) => e.start - t.start || e.end - t.end);
}
function firstIntersectingToken(e, t) {
let n = 0;
let r = e.length;
while (n < r) {
const i = n + r >>> 1;
if (expectDefined(e[i], "bounded JSON token search").currentEnd <= t) n = i + 1;
else r = i;
}
return n;
}
function updateCurrentToken(e, t) {
if (t.raw || t.deferEncoding) {
t.currentRaw = t.currentValue;
return;
}
const n = [];
const r = [];
let i = t.start + (t.string ? 1 : 0);
let a = 0;
let o = 0;
for (const s of t.edits) {
const c = t.string ? encodedBoundary(e, t, s.start) : t.start + s.start;
const l = t.string ? encodedBoundary(e, t, s.end) : t.start + s.end;
const u = JSON.stringify(s.replacement).slice(1, -1);
const d = a + c - i;
const f = d + u.length;
r.push({
start: d,
end: f,
decodedStart: s.start + o,
decodedEnd: s.start + o + s.replacement.length,
sourceEnd: l,
sourceDecodedEnd: s.end,
replacement: u
});
n.push(e.slice(i, c), u);
a = f;
o += s.replacement.length - (s.end - s.start);
i = l;
}
n.push(e.slice(i, t.end - (t.string ? 1 : 0)));
t.currentRaw = `"${n.join("")}"`;
t.encodedEdits = r;
}
function currentDecodedBoundary(e, t, n, r) {
const i = n - t.currentStart - 1;
const a = t.encodedEdits;
if (!a) return decodedBoundary(e, t, t.start + 1 + i);
let o = 0;
let s = a.length;
while (o < s) {
const e = o + s >>> 1;
if (expectDefined(a[e], "current encoded edit").end < i) o = e + 1;
else s = e;
}
const c = a[o];
if (c && i >= c.start) {
const e = i - c.start;
if (!c.replacement.includes("\\")) return c.decodedStart + e;
let t = r.get(c.replacement);
if (!t) {
t = stringBoundaries(c.replacement, 0, c.replacement.length);
r.set(c.replacement, t);
}
const n = t.get(e);
return n === void 0 ? void 0 : c.decodedStart + n;
}
const l = a[o - 1];
const u = decodedBoundary(e, t, i + (l ? l.sourceEnd - l.end : t.start + 1));
return u === void 0 ? void 0 : u + (l ? l.decodedEnd - l.sourceDecodedEnd : 0);
}
function commitPatternEdits(e) {
const t = e.pending;
e.pending = void 0;
if (!t) return false;
const n = mergeRedactionEdits(t);
const r = applyRedactionEdits(e.currentValue, n);
if (r === e.currentValue) return false;
e.edits = composeRedactionEdits(e.value.length, e.edits, n);
e.currentValue = r;
return true;
}
function changedRedactionEdits(e, t) {
let n = 0;
return t.filter((t) => {
while (e[n] && expectDefined(e[n], "previous configured edit").start < t.start) n += 1;
const r = e[n];
return !r || r.start !== t.start || r.end !== t.end || r.replacement !== t.replacement;
});
}
function commitOriginalEdits(e, t) {
if (t.length === 0) return false;
const n = mergeRedactionEdits([...e.edits, ...t]);
const r = applyRedactionEdits(e.value, n);
if (r === e.currentValue) return false;
e.edits = n;
e.currentValue = r;
return true;
}
function updateCurrentRecord(e, t, n, r) {
const i = [];
let a = 0;
let o = 0;
for (const s of n) {
const n = s.currentStart;
const c = s.currentEnd;
if (r.has(s)) {
updateCurrentToken(e, s);
const r = expectDefined(s.currentRaw, "changed JSON token");
i.push(t.slice(a, n), r);
a = c;
s.currentStart = n + o;
o += r.length - (c - n);
} else s.currentStart = n + o;
s.currentEnd = c + o;
}
i.push(t.slice(a));
return i.join("");
}
function projectedStringEnd(e, t, n, r, i, a) {
const o = new Set(n.parts.filter((e) => e.json).map((e) => e.key));
const s = projectMessageEdits(e, t, n, (e) => e.string && !e.isKey && e.rootKey !== void 0 && o.has(e.rootKey) ? [{
start: 0,
end: e.value.length,
replacement: ""
}] : []).filter((e) => e.end < n.contentLength);
const c = rebaseRedactionEdits(r.edits, s).filter((e) => e.start <= i && i < e.end && a <= e.end);
return c.length === 1 ? expectDefined(c[0], "displayed source string").end : r.currentValue.length;
}
function redactJsonRecord(e, t, n, r, i, a, o, s, c, l) {
let u = l ? [] : readScalarTokens(e, t);
const d = c ? u.find((e) => !e.isKey && e.path.length === 1 && e.key === "message") : void 0;
const f = /* @__PURE__ */ new Map();
let p = [];
let m = d?.value ?? "";
let h = e;
const g = /* @__PURE__ */ new Set();
for (const e of u) if (commitOriginalEdits(e, o(e))) g.add(e);
if (g.size > 0) h = updateCurrentRecord(e, h, u, g);
const _ = u.filter((e) => !e.isKey && e.string && !s(e, e.currentValue));
const projectMessage = () => {
if (!d || !c) return false;
const t = projectMessageEdits(e, u, c, (e) => {
const t = changedRedactionEdits(e.projectedEdits, e.edits);
e.projectedEdits = e.edits;
return t;
});
if (t.length === 0) return false;
const n = rebaseRedactionEdits(p, t);
const r = rebaseRedactionEdits(d.edits, t);
let i = 0;
for (let e = 0; e < r.length; e += 1) {
const a = expectDefined(r[e], "projected message edit");
const o = expectDefined(n[e], "projected source edit");
const s = expectDefined(t[e], "source projection");
while (d.edits[i] && expectDefined(d.edits[i], "generated message span").start < s.start) i += 1;
const c = d.edits[i];
const l = s.scalar && c?.start === s.start && c.end === s.end && a.replacement === JSON.stringify(c.replacement);
const u = d.currentValue.slice(a.start, a.end);
if (!l && u !== a.replacement && u !== m.slice(o.start, o.end)) a.replacement = s.scalar ? JSON.stringify("***") : "***";
}
d.pending = r;
m = applyRedactionEdits(m, n);
p = composeRedactionEdits(d.value.length, p, n);
return commitPatternEdits(d);
};
for (const [o, s] of n.entries()) {
const n = /* @__PURE__ */ new Set();
const p = /* @__PURE__ */ new Set();
const add = (e, t) => {
(e.pending ??= []).push(t);
p.add(e);
};
let m;
const visitDecodedMatch = (e, t) => {
const n = r(e, t);
const i = n?.redact(n);
if (i && i.end >= i.start) add(m, i);
};
for (const i of s) {
if (i.couldMatch && !i.couldMatch(h)) continue;
for (const a of i.patterns) {
if (o === 0) for (m of _) visitRedactMatches(m.currentValue, a, visitDecodedMatch);
else visitRedactMatches(h, a, (n) => {
const i = r(n, a);
if (!i || i.end < i.start) return;
if (l && u.length === 0) u = readBatchTokens(e, t, l.preserveLines);
for (let t = firstIntersectingToken(u, i.start); t < u.length; t += 1) {
const n = expectDefined(u[t], "serialized capture token");
if (n.currentStart >= i.end) break;
const r = n.raw || n.deferEncoding;
const a = r ? 0 : 1;
const o = i.start >= n.currentStart + a && i.end <= n.currentEnd - a;
if (l && n.isKey && !o) continue;
const s = n.currentValue;
if (!n.raw && !n.string && n.edits.length === 0) {
add(n, {
start: 0,
end: s.length,
replacement: "***"
});
continue;
}
let p = Math.max(i.start, n.currentStart + a);
let m = r ? p - n.currentStart : currentDecodedBoundary(e, n, p, f);
let g = Math.min(i.end, n.currentEnd - a);
let _ = r ? g - n.currentStart : currentDecodedBoundary(e, n, g, f);
if (m === void 0 || _ === void 0) {
while (m === void 0) m = currentDecodedBoundary(e, n, --p, f);
while (_ === void 0) _ = currentDecodedBoundary(e, n, ++g, f);
const t = n === d && c ? projectedStringEnd(e, u, c, n, m, _) : s.length;
add(n, {
start: m,
end: t,
replacement: "***"
});
continue;
}
if (_ < m || l && _ === m) continue;
const { start: v, end: y } = i;
const b = i.redact({
start: m,
end: _,
value: h.slice(Math.max(v, n.currentStart + a), Math.min(y, n.currentEnd - a))
});
if (!b) continue;
let x = "***";
if (o) try {
x = r ? b.replacement : JSON.parse(`"${b.replacement}"`);
} catch {}
add(n, {
...b,
replacement: x
});
}
});
if (p.size === 0) continue;
for (const e of p) if (!commitPatternEdits(e)) p.delete(e);
else if (o === 0) n.add(e);
if (o !== 0 && p.size > 0) h = updateCurrentRecord(e, h, u, p);
p.clear();
}
}
for (const e of u) if (o === 0) {
e.pending = i(e, e.currentValue);
if (commitPatternEdits(e)) n.add(e);
} else if (commitOriginalEdits(e, a(e))) n.add(e);
if ((o !== 0 || g.size > 0 || n.size > 0) && projectMessage() && d) n.add(d);
if (n.size > 0) h = updateCurrentRecord(e, h, u, n);
}
if (d && c) {
const e = c.finish(d.currentValue);
if (e !== d.currentValue) return applyRedactionEdits(h, [{
start: d.currentStart,
end: d.currentEnd,
replacement: JSON.stringify(e)
}]);
}
return applyRedactionEdits(h, u.flatMap((e) => e.deferEncoding && e.edits.length > 0 ? [{
start: e.currentStart,
end: e.currentEnd,
replacement: JSON.stringify(e.currentValue)
}] : []));
}
//#endregion
//#region src/logging/redact-pem.ts
const PEM_REDACT_PATTERN_SOURCE = String.raw`-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z ]*PRIVATE KEY-----`;
function createState() {
return {
scanner: {
offset: 0,
phase: "search",
dashes: 0,
keyword: "BEGIN ",
keywordOffset: 0,
start: 0,
suffix: ""
},
matchEnd: 0
};
}
function resetScanner(e, t) {
e.phase = "search";
e.dashes = t === "-" ? 1 : 0;
e.suffix = "";
}
function* readDelimiters(e, t) {
for (let n = 0; n < e.length; n += 1) {
if (t.phase === "search" && t.dashes === 0) {
const r = e.indexOf("-", n);
if (r === -1) {
t.offset += e.length - n;
return;
}
t.offset += r - n;
n = r;
}
const r = e.charCodeAt(n);
const i = r >= 97 && r <= 122 ? String.fromCharCode(r - 32) : e.charAt(n);
const a = t.offset++;
switch (t.phase) {
case "search":
if (i === "-") t.dashes = Math.min(5, t.dashes + 1);
else if (t.dashes === 5 && (i === "B" || i === "E")) {
t.phase = "keyword";
t.keyword = i === "B" ? "BEGIN " : "END ";
t.keywordOffset = 1;
t.start = a - 5;
} else t.dashes = 0;
break;
case "keyword":
if (i !== t.keyword.charAt(t.keywordOffset)) resetScanner(t, i);
else if (++t.keywordOffset === t.keyword.length) {
t.phase = "label";
t.suffix = "";
}
break;
case "label":
if (i >= "A" && i <= "Z" || i === " ") t.suffix = (t.suffix + i).slice(-11);
else if (i === "-" && t.suffix === "PRIVATE KEY") {
t.phase = "close";
t.dashes = 1;
} else resetScanner(t, i);
break;
case "close": if (i !== "-") resetScanner(t, i);
else if (++t.dashes === 5) {
t.phase = "search";
t.suffix = "";
yield {
kind: t.keyword === "BEGIN " ? "begin" : "end",
start: t.start,
end: a + 1
};
}
}
}
}
function consumeDelimiter(e, t) {
if (!e.open) {
if (t.kind === "begin" && t.start >= e.matchEnd) e.open = {
start: t.start,
end: t.end
};
return;
}
if (t.kind !== "end" || t.start <= e.open.end) return;
const n = {
start: e.open.start,
end: t.end,
bodyStart: e.open.end,
bodyEnd: t.start
};
e.open = void 0;
e.matchEnd = t.end;
return n;
}
function* matchPem(e, t, n) {
const r = {
...t,
scanner: { ...t.scanner },
open: t.open && { ...t.open }
};
const i = r.scanner.offset;
for (const t of readDelimiters(e, r.scanner)) {
const a = consumeDelimiter(r, t);
if (!a) continue;
const o = Math.max(0, (n ? a.bodyStart : a.start) - i);
const s = (n ? a.bodyEnd : a.end) - i;
if (s <= o) continue;
yield {
match: e.slice(o, s),
groups: [],
input: e,
offset: o,
...n ? { replacement: "…redacted…" } : {}
};
}
if (n && r.open) {
const t = Math.max(0, r.open.end - i);
if (t < e.length) yield {
match: e.slice(t),
groups: [],
input: e,
offset: t,
replacement: "…redacted…"
};
}
}
const PEM_REDACT_MATCHER = {
source: PEM_REDACT_PATTERN_SOURCE,
exec(e) {
return matchPem(e, createState(), false);
},
createContext() {
let e = false;
let t = true;
return {
resolve(n) {
e = n ? t : e;
t = e;
},
advance(t) {
const n = createState();
if (e) n.open = {
start: -1,
end: -1
};
for (const e of readDelimiters(t, n.scanner)) consumeDelimiter(n, e);
return n.open !== void 0;
},
prepend() {
const n = createState();
const r = createState();
r.open = {
start: -1,
end: -1
};
return {
consume(e) {
for (const t of readDelimiters(e, n.scanner)) {
consumeDelimiter(n, t);
consumeDelimiter(r, t);
}
},
finish() {
const i = n.open ? t : e;
const a = r.open ? t : e;
e = i;
t = a;
return e === t;
}
};
},
pattern: {
source: PEM_REDACT_PATTERN_SOURCE,
exec(t) {
const n = createState();
if (e) n.open = {
start: -1,
end: -1
};
return matchPem(t, n, true);
}
}
};
}
};
//#endregion
//#region src/logging/redact-patterns.ts
const PAYMENT_CREDENTIAL_ENV_KEYS = String.raw`CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN`;
const PAYMENT_CREDENTIAL_QUERY_KEYS = String.raw`card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token`;
const PAYMENT_CREDENTIAL_JSON_KEYS = String.raw`cardNumber|card_number|cardCvc|card_cvc|cardCvv|card_cvv|cvc|cvv|securityCode|security_code|paymentCredential|payment_credential|sharedPaymentToken|shared_payment_token`;
const AWS_SECRET_ACCESS_KEY_FIELD_KEYS = String.raw`aws[-_]?secret[-_]?access[-_]?key|awsSecretAccessKey|SecretAccessKey`;
const AUTH_QUERY_KEYS = String.raw`access[-_]?token|auth[-_]?token|hook[-_]?token|refresh[-_]?token|id[-_]?token|api[-_]?key|apikey|client[-_]?secret|app[-_]?secret|private[-_]?key|${AWS_SECRET_ACCESS_KEY_FIELD_KEYS}|credential|authorization|token|key|secret|password|pass|passwd|auth|jwt|session|code|signature|x[-_]?amz[-_]?(?:signature|security[-_]?token)`;
const FORM_BODY_FIRST_PAIR_KEYS = String.raw`${AUTH_QUERY_KEYS}|app[-_]?secret|credential|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
const STANDALONE_ASSIGNMENT_SECRET_KEYS = String.raw`access_token|refresh_token|id_token|auth[-_]?token|hook[-_]?token|api[-_]?key|client[-_]?secret|app[-_]?secret|private[-_]?key|authorization|jwt|token|secret|password|pass|passwd|credential|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
const CONFIG_ASSIGNMENT_SECRET_KEYS = String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|client[-_]?secret|app[-_]?secret|private[-_]?key|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|pass|passwd|credential|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
const CONFIG_COLON_ASSIGNMENT_SECRET_KEYS = String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|client[-_]?secret|app[-_]?secret|private[-_]?key|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|passwd|credential|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
const CONFIG_DIRECT_ASSIGNMENT_SECRET_KEYS = String.raw`access-token|refresh-token|id-token|auth-token|hook-token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|passphrase`;
const CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_SECRET_KEYS = String.raw`password|passphrase|pass|passwd`;
const CLI_SECRET_FLAG_KEYS = String.raw`${AWS_SECRET_ACCESS_KEY_FIELD_KEYS}|api[-_]?key|hook[-_]?token|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|password|passwd|credential|private[-_]?key|client[-_]?secret|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
const FORM_BODY_KEY_INVISIBLE_CHARS = String.raw`\p{C}\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u115F\u1160\u3164\uFFA0`;
const ENV_ASSIGNMENT_REDACT_PATTERN = String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${PAYMENT_CREDENTIAL_ENV_KEYS})\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1/g`;
const ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN = String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${PAYMENT_CREDENTIAL_ENV_KEYS})\b\s*[=:]\s*\\+(["'])([^\s"'\\]+)\\+\1/g`;
const STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN = String.raw`(^|[\s,;({\["])(?:${STANDALONE_ASSIGNMENT_SECRET_KEYS})=(["'\x60])((?:(?!\2)[^\r\n])+)\2`;
const STANDALONE_ASSIGNMENT_REDACT_PATTERN = String.raw`(^|[\s,;({\["])(?:${STANDALONE_ASSIGNMENT_SECRET_KEYS})=(["'\x60]?[^\s&#"'\x60<>]+)`;
const CONFIG_QUOTED_ASSIGNMENT_SECRET_KEYS = String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|pass|passwd|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
const CONFIG_QUOTED_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])(?:(?:${CONFIG_QUOTED_ASSIGNMENT_SECRET_KEYS})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*)(["'\x60])((?:(?!\2)[^\r\n])+)\2/g`;
const CONFIG_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])(?:(?:${CONFIG_COLON_ASSIGNMENT_SECRET_KEYS})\s*:\s*|(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})(?:\s+=\s*|=\s+))([^\s#"'\x60<>]+)/g`;
const CONFIG_DIRECT_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])(?:${CONFIG_DIRECT_ASSIGNMENT_SECRET_KEYS})=([^\s#"'\x60<>]+)/g`;
const CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])[a-z0-9][a-z0-9._-]{0,79}[-_](?:${CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*([^\s#"'\x60<>]+)/g`;
const CONFIG_NAMESPACED_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])[a-z0-9_.-]{1,80}\.(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*([^\s#"'\x60<>]+)/g`;
const STRUCTURED_JSON_SECRET_REDACT_PATTERN = String.raw`"(?:apiKey|api_key|apiToken|api_token|bearerToken|bearer_token|token|secret|password|passwd|${AWS_SECRET_ACCESS_KEY_FIELD_KEYS}|credential|authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|accessToken|access_token|refreshToken|refresh_token|idToken|id_token|authToken|auth_token|clientSecret|client_secret|privateKey|private_key|secret_value|raw_secret|secret_input|key_material)"\s*:\s*"([^"]+)"`;
const STRUCTURED_JSON_PAYMENT_REDACT_PATTERN = String.raw`"(?:${PAYMENT_CREDENTIAL_JSON_KEYS})"\s*:\s*"([^"]+)"`;
const AMBIGUOUS_QUOTED_SECRET_FIELD_REDACT_PATTERN = String.raw`(^|[\s,{])["']?(?:api[-_]key|access[-_]token|refresh[-_]token|id[-_]token|authToken|auth[-_]token|clientSecret|client[-_]secret|appSecret|app[-_]secret|private[-_]key|credential|authorization|secret[-_]value|raw[-_]secret|secret[-_]input|key[-_]material)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`;
const AMBIGUOUS_QUOTED_AUTH_FIELD_REDACT_PATTERN = String.raw`(^|[\s,{])["']?(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`;
const BASE64_SAFE_TOKEN_BOUNDARY = String.raw`(^|[^A-Za-z0-9])`;
const base64SafeToken = (e) => String.raw`${BASE64_SAFE_TOKEN_BOUNDARY}(?=${e})(?<!;base64,[A-Za-z0-9+/=]*)(${e})`;
const IDENTIFIER_SAFE_TOKEN_BOUNDARY = String.raw`(^|[^A-Za-z0-9_])`;
function isAwsValueCharacter(e) {
const t = e.charCodeAt(0);
return t >= 65 && t <= 90 || t >= 97 && t <= 122 || t >= 48 && t <= 57 || e === "/" || e === "+" || e === "=";
}
const AWS_SECRET_ACCESS_KEY_VALUE_RE = /(?=[A-Za-z0-9/+=]{0,39}[A-Z])(?=[A-Za-z0-9/+=]{0,39}[a-z])(?=[A-Za-z0-9/+=]{0,39}[0-9/+=])(?=[A-Za-z0-9/+=]{0,39}[G-Zg-z/+=])[A-Za-z0-9/+=]{40}/u;
function couldMatchAwsSecretAccessKey(e) {
for (let t = 39; t < e.length;) {
let n = t;
while (n > t - 40 && isAwsValueCharacter(e[n])) n--;
if (n === t - 40) return AWS_SECRET_ACCESS_KEY_VALUE_RE.test(e);
t = n + 40;
}
return false;
}
const AWS_VALUE_WHITESPACE_RE = /\s/;
const AWS_URL_SCHEME_CHARACTER_RE = /[A-Za-z0-9+.-]/;
const AWS_URL_SCHEME_START_RE = /[A-Za-z]/;
function* matchAwsSecretAccessKeys(e) {
if (!couldMatchAwsSecretAccessKey(e)) return;
const t = {
"\"": "\"",
"'": "'",
"`": "`",
"<": ">",
"(": ")",
"[": "]",
"{": "}"
};
let n = -1;
let r = -1;
let i;
let a = 0;
const o = [];
for (let s = 0; s <= e.length; s++) {
const c = e[s] ?? "";
const l = s === e.length || AWS_VALUE_WHITESPACE_RE.test(c);
const u = a;
a = c === "\\" ? a + 1 : 0;
if (c && isAwsValueCharacter(c)) {
if (n === -1) n = s;
} else if (n !== -1) {
if (s - n === 40) o.push({
start: n,
end: s,
origin: n,
url: i
});
else if (s - n > 40 && c === "@" && e[s - 41] === "/") o.push({
start: s - 40,
end: s,
origin: n,
url: i
});
n = -1;
}
if (l) {
if (i) i.end = Math.min(i.end, s);
for (const t of o) {
const n = t.url;
const r = n && !n.hasAt && n.portValid && (n.portStart === -1 || (n.authorityEnd === -1 ? n.end : n.authorityEnd) > n.portStart + 1);
const i = e[t.start - 1] ?? "";
const a = e[t.end] ?? "";
const o = t.start !== t.origin;
const s = n && n.portStart !== -1 && t.origin === n.portStart + 1 && n.authorityEnd > t.origin && t.end > n.authorityEnd && a === "@";
if (!o && (i === "_" || isAwsValueCharacter(i)) || a === "_" || e.slice(t.origin - 8, t.origin) === ";base64," || r && !s && t.start >= n.start && t.end <= n.end) continue;
const c = e.slice(t.start, t.end);
if (AWS_SECRET_ACCESS_KEY_VALUE_RE.test(c)) yield {
match: c,
groups: [c],
input: e,
offset: t.start
};
}
o.length = 0;
r = -1;
i = void 0;
continue;
}
if (i && s >= i.start) {
if (c === i.closing && u === i.closingEscapeDepth) {
i.end = Math.min(i.end, s);
i = void 0;
} else {
if ("?#\"'<>`|()[]{}".includes(c)) i.end = Math.min(i.end, s);
i.queryOrFragment ||= c === "?" || c === "#";
if (i.authorityEnd === -1) {
i.hasAt ||= c === "@";
if ("/?#".includes(c)) i.authorityEnd = s;
else if (s < i.end) {
if (c === ":") {
i.portValid &&= i.portStart === -1;
i.portStart = s;
} else if (i.portStart !== -1 && (c < "0" || c > "9")) i.portValid = false;
}
}
}
}
if (AWS_URL_SCHEME_CHARACTER_RE.test(c)) {
if (r === -1) r = s;
} else {
if ((!i || s >= i.end && !i.queryOrFragment) && c === ":" && e.startsWith("//", s + 1) && r !== -1 && AWS_URL_SCHEME_START_RE.test(e[r])) {
const n = e[r - 1];
let a = 0;
for (let t = r - 2; t >= 0 && e[t] === "\\"; t--) a++;
i = {
start: s + 3,
end: e.length,
authorityEnd: -1,
portStart: -1,
portValid: true,
hasAt: false,
queryOrFragment: false,
closing: n ? t[n] : void 0,
closingEscapeDepth: a
};
}
r = -1;
}
}
}
const AWS_SECRET_ACCESS_KEY_MATCHER = Object.freeze({
source: "aws-secret-access-key",
exec: matchAwsSecretAccessKeys,
couldMatch: couldMatchAwsSecretAccessKey
});
const BARE_PASS_KEY_RE = new RegExp(String.raw`(?<![A-Za-z0-9])(pass|${CONFIG_COLON_ASSIGNMENT_SECRET_KEYS})\s*:\s*`, "gi");
const BARE_PASS_VALUE_RE = /[^\s#"'\x60<>]+/y;
const ASCII_WORD_CHAR_RE = /[A-Za-z0-9]/;
const INLINE_WHITESPACE_RE = /[ \t\r\n]/;
function* matchBarePassAssignments(e) {
if (!/pass\s*:/.test(e)) return;
const t = [...e.matchAll(BARE_PASS_KEY_RE)];
if (t.length === 0) return;
let n = 0;
let r = false;
for (let i = 0; i < e.length; i++) {
const a = t[n];
if (!a) return;
if (i === a.index) {
n++;
const o = e[i - 1] ?? "";
const s = a[1] !== "pass" || o === "." || o === "-" || o === "_";
if (!(!s && !r && o === " " && ASCII_WORD_CHAR_RE.test(e[i - 2] ?? ""))) {
r = true;
let o = i + a[0].length;
if (!s) {
BARE_PASS_VALUE_RE.lastIndex = o;
const t = BARE_PASS_VALUE_RE.exec(e)?.[0];
if (t) {
o += t.length;
yield {
match: e.slice(i, o),
groups: [t],
input: e,
offset: i
};
}
}
let c = t[n];
while (c && c.index < o) {
n++;
c = t[n];
}
i = o - 1;
continue;
}
}
const o = e[i];
if (o === "\n" || o === "\r") r = false;
else if (o === "=") r = true;
else if (o === ":" && !INLINE_WHITESPACE_RE.test(e[i + 1] ?? " ")) r = true;
}
}
const BARE_PASS_ASSIGNMENT_MATCHER = Object.freeze({
source: "bare-pass-assignment",
exec: matchBarePassAssignments
});
const TELEGRAM_BOT_TOKEN_REDACT_PATTERN = String.raw`\bbot(\d{6,}:[A-Za-z0-9_-]{20,})\b`;
const TELEGRAM_TOKEN_REDACT_PATTERN = String.raw`\b(\d{6,}:[A-Za-z0-9_-]{20,})\b`;
const CREDENTIAL_STYLE_HEADER_KEYS = "x-goog-api-key|api-key|apikey|x-api-token|x-access-token";
const GATEWAY_SECURITY_HEADER_KEYS = "X-OpenClaw-Token|x-pomerium-jwt-assertion|X-Api-Key|X-Auth-Token";
const LOG_HEADER_BOUNDARY_PATTERN = String.raw`(^|[^A-Za-z0-9_?&-]|\\{1,64}[rn])`;
const CREDENTIAL_STYLE_COLON_HEADER_REDACT_PATTERN = String.raw`${LOG_HEADER_BOUNDARY_PATTERN}(?:${CREDENTIAL_STYLE_HEADER_KEYS})${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*:${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}([^\s\\"',;]+)`;
const CREDENTIAL_STYLE_EQUALS_ASSIGNMENT_REDACT_PATTERN = String.raw`${LOG_HEADER_BOUNDARY_PATTERN}(?:${CREDENTIAL_STYLE_HEADER_KEYS})${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*=${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}([^\s\\"',;]+)`;
const GATEWAY_SECURITY_COLON_HEADER_REDACT_PATTERN = String.raw`${LOG_HEADER_BOUNDARY_PATTERN}(?:${GATEWAY_SECURITY_HEADER_KEYS})\s*:\s*([^\s"',;]+)`;
const GATEWAY_SECURITY_EQUALS_ASSIGNMENT_REDACT_PATTERN = String.raw`${LOG_HEADER_BOUNDARY_PATTERN}(?:${GATEWAY_SECURITY_HEADER_KEYS})\s*=\s*([^\s"',;]+)`;
const HTTP_AUTH_HEADER_REDACT_PATTERNS = [
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}Proxy-Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}${HTTP_AUTH_SCHEME_PATTERN}${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`,
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}Proxy-Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})[ \t]*(?=${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(?!(?:Bearer|Basic|Bot)(?=${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}))${HTTP_AUTH_SCHEME_PATTERN}${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`,
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(?!(?:Bearer|Basic|Bot)(?=${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}))(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})[ \t]*(?=${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,
CREDENTIAL_STYLE_COLON_HEADER_REDACT_PATTERN,
CREDENTIAL_STYLE_EQUALS_ASSIGNMENT_REDACT_PATTERN
];
const AUTHORIZATION_BEARER_REDACT_PATTERN = String.raw`Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}Bearer${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`;
const AUTHORIZATION_BASIC_REDACT_PATTERN = String.raw`Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}Basic${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`;
const AUTHORIZATION_BOT_REDACT_PATTERN = String.raw`Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}Bot${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`;
const STANDALONE_BEARER_REDACT_PATTERN = String.raw`\bBearer\s+([-A-Za-z0-9._~+/=]{18,})(?![-A-Za-z0-9._~+/=])`;
const DEFAULT_REDACT_FIELD_PATTERNS = [
ENV_ASSIGNMENT_REDACT_PATTERN,
ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN,
STRUCTURED_JSON_SECRET_REDACT_PATTERN,
STRUCTURED_JSON_PAYMENT_REDACT_PATTERN,
AMBIGUOUS_QUOTED_SECRET_FIELD_REDACT_PATTERN,
AMBIGUOUS_QUOTED_AUTH_FIELD_REDACT_PATTERN,
String.raw`--(?:${CLI_SECRET_FLAG_KEYS})=([^\s"']+)`,
String.raw`--(?:${CLI_SECRET_FLAG_KEYS})\s+(?!(?:or|and)\b(?=\s+--))(["']?)([^\s"']+)\1`,
AUTHORIZATION_BEARER_REDACT_PATTERN,
AUTHORIZATION_BASIC_REDACT_PATTERN,
AUTHORIZATION_BOT_REDACT_PATTERN,
...HTTP_AUTH_HEADER_REDACT_PATTERNS,
GATEWAY_SECURITY_COLON_HEADER_REDACT_PATTERN,
GATEWAY_SECURITY_EQUALS_ASSIGNMENT_REDACT_PATTERN,
STANDALONE_BEARER_REDACT_PATTERN,
String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,
String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,
String.raw`(^|[\s,;])(?:${FORM_BODY_FIRST_PAIR_KEYS})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,
STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN,
STANDALONE_ASSIGNMENT_REDACT_PATTERN,
CONFIG_QUOTED_ASSIGNMENT_REDACT_PATTERN,
CONFIG_ASSIGNMENT_REDACT_PATTERN,
BARE_PASS_ASSIGNMENT_MATCHER,
CONFIG_DIRECT_ASSIGNMENT_REDACT_PATTERN,
CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_REDACT_PATTERN,
CONFIG_NAMESPACED_ASSIGNMENT_REDACT_PATTERN,
PEM_REDACT_PATTERN_SOURCE,
String.raw`(^|[\s,{])["']?(?:${AWS_SECRET_ACCESS_KEY_FIELD_KEYS})["']?\s*[:=]\s*(["']?)([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])\2`
];
const VENDOR_TOKEN_REDACT_PATTERNS = [
String.raw`\b(sk-[A-Za-z0-9_-]{8,})\b`,
String.raw`(ghp_[A-Za-z0-9]{10,})`,
String.raw`(github_pat_[A-Za-z0-9_]{10,})`,
String.raw`(gho_[A-Za-z0-9]{10,})`,
String.raw`(ghu_[A-Za-z0-9]{10,})`,
String.raw`(ghs_[A-Za-z0-9]{10,})`,
String.raw`(ghr_[A-Za-z0-9]{10,})`,
String.raw`(glpat-[A-Za-z0-9._=\-]{20,})`,
String.raw`(gloas-(?:[A-Fa-f0-9]{65,}|[A-Za-z0-9_-]{64}|[A-Fa-f0-9]{32,}))`,
String.raw`(gldt-[A-Za-z0-9_-]{20,})`,
String.raw`(glcbt-[A-Za-z0-9]{1,5}_[A-Za-z0-9_-]{20,})`,
String.raw`(glptt-[A-Za-z0-9_-]{40,})`,
String.raw`(glft-(?:[A-Za-z0-9_-]{20,}|[a-h0-9]+-[0-9]+_))`,
String.raw`(glimt-[A-Za-z0-9_-]{25,})`,
String.raw`(glagent-[A-Za-z0-9_-]{50,})`,
String.raw`(glwt-[A-Za-z0-9_-]{20,})`,
String.raw`(glsoat-[A-Za-z0-9_-]{20,})`,
String.raw`(glffct-[A-Za-z0-9_-]{20,})`,
String.raw`(glrt-[A-Za-z0-9._-]{20,})`,
String.raw`(glrtr?-[A-Za-z0-9_-]{27,300}\.[0-9a-z]{2}\.[0-9a-z]{9})`,
String.raw`(GR1348941[A-Za-z0-9_-]{20,})`,
String.raw`(_gitlab_session=[A-Za-z0-9%._-]{20,})`,
String.raw`(xox[baprs]-[A-Za-z0-9-]{10,})`,
String.raw`(xapp-[A-Za-z0-9-]{10,})`,
String.raw`(https:\/\/hooks\.slack\.com\/(?:services\/T[A-Z0-9]+\/B[A-Z0-9]+|workflows\/T[A-Z0-9]+\/A[A-Z0-9]+\/[0-9]{17,19})\/[A-Za-z0-9]{20,})`,
String.raw`(https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]{17,20}\/[A-Za-z0-9_-]{60,})`,
String.raw`discord(?:.|\n|\r){0,40}?\b([A-Za-z0-9_-]{24}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27})\b`,
String.raw`(gsk_[A-Za-z0-9_-]{10,})`,
String.raw`(AIza[0-9A-Za-z\-_]{20,})`,
String.raw`(ya29\.[0-9A-Za-z_\-./+=]{10,})`,
String.raw`(1//0[0-9A-Za-z_\-./+=]{10,})`,
String.raw`(GOCSPX-[A-Za-z0-9_-]{20,})`,
String.raw`(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,
String.raw`(pplx-[A-Za-z0-9_-]{10,})`,
String.raw`(fal_[A-Za-z0-9_-]{10,})`,
String.raw`${IDENTIFIER_SAFE_TOKEN_BOUNDARY}(fc-[A-Za-z0-9]{10,})`,
String.raw`(bb_live_[A-Za-z0-9_-]{10,})`,
base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`),
String.raw`(sk_live_[A-Za-z0-9]{10,})`,
String.raw`(sk_test_[A-Za-z0-9]{10,})`,
String.raw`(rk_live_[A-Za-z0-9]{10,})`,
String.raw`(SG\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,
String.raw`(npm_[A-Za-z0-9]{10,})`,
String.raw`(pypi-[A-Za-z0-9_-]{10,})`,
String.raw`(dop_v1_[A-Za-z0-9]{10,})`,
String.raw`(doo_v1_[A-Za-z0-9]{10,})`,
String.raw`(dor_v1_[A-Za-z0-9]{10,})`,
String.raw`(dp\.(?:ct|pt|sa|scim|audit)\.[A-Za-z0-9]{40,44})`,
String.raw`(dp\.st\.[A-Za-z0-9]{40,44})`,
String.raw`(dp\.st\.[a-z0-9_-]{2,35}\.[A-Za-z0-9]{40,44})`,
String.raw`(dckr_(?:pat|oat)_[A-Za-z0-9_-]{27,32})`,
String.raw`(bkua_[a-z0-9]{40})`,
String.raw`(CCIPAT_[A-Za-z0-9]{22}_[A-Fa-f0-9]{40})`,
String.raw`(sbp_[a-z0-9]{40})`,
base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`),
String.raw`(dd[pw]_[A-Za-z0-9]{36})`,
String.raw`(glsa_[A-Za-z0-9_]{41})`,
String.raw`(glc_eyJ[A-Za-z0-9+/=]{60,160})`,
String.raw`(nfp_[A-Za-z0-9_]{36})`,
String.raw`(CFPAT-[A-Za-z0-9_\-]{40,})`,
base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),
base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`),
base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`),
String.raw`(BBDC-[A-Za-z0-9+/@_-]{40,50})`,
String.raw`(HRKU-AA[A-Za-z0-9_-]{20,})`,
String.raw`(pat-(?:eu|na)1-[A-Za-z0-9]{8}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{12})`,
String.raw`(apify_api_[A-Za-z0-9\-]{20,})`,
String.raw`(FlyV1 fm\d+_[A-Za-z0-9+/=,_-]{100,})`,
String.raw`(fio-u-[A-Za-z0-9_-]{40,})`,
String.raw`(^|[^A-Za-z0-9_])(am_[A-Za-z0-9_-]{10,})`,
String.raw`(^|[^A-Za-z0-9_])(sk_[A-Za-z0-9_]{10,})`,
String.raw`(tvly-[A-Za-z0-9]{10,})`,
String.raw`(exa_[A-Za-z0-9]{10,})`,
String.raw`(syt_[A-Za-z0-9]{10,})`,
String.raw`(retaindb_[A-Za-z0-9]{10,})`,
String.raw`(hsk-[A-Za-z0-9]{10,})`,
String.raw`(mem0_[A-Za-z0-9]{10,})`,
String.raw`(brv_[A-Za-z0-9]{10,})`,
String.raw`(xai-[A-Za-z0-9]{30,})`,
String.raw`${IDENTIFIER_SAFE_TOKEN_BOUNDARY}(fw-[A-Za-z0-9]{30,})`,
String.raw`${IDENTIFIER_SAFE_TOKEN_BOUNDARY}(fw_[A-Za-z0-9]{30,})`,
String.raw`${IDENTIFIER_SAFE_TOKEN_BOUNDARY}(fpk_[A-Za-z0-9]{30,})`,
base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`),
base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`),
String.raw`(AKID[A-Za-z0-9]{10,})`,
String.raw`(LTAI[A-Za-z0-9]{10,})`,
String.raw`(hf_[A-Za-z0-9]{10,})`,
String.raw`(api_org_[A-Za-z0-9]{20,})`,
String.raw`(r8_[A-Za-z0-9]{10,})`,
TELEGRAM_BOT_TOKEN_REDACT_PATTERN,
TELEGRAM_TOKEN_REDACT_PATTERN
];
const DEFAULT_REDACT_PATTERNS = [
...DEFAULT_REDACT_FIELD_PATTERNS,
...VENDOR_TOKEN_REDACT_PATTERNS,
AWS_SECRET_ACCESS_KEY_MATCHER
];
function createBackendRedactPatterns() {
const e = /* @__PURE__ */ new Set([
"access_token",
"auth_token",
"awssecretaccesskey",
"aws_secret_access_key",
"hook_token",
"refresh_token",
"id_token",
"token",
"api_key",
"apikey",
"client_secret",
"app_secret",
"password",
"pass",
"passwd",
"auth",
"jwt",
"session",
"code",
"signature",
"x_amz_signature",
"x_amz_security_token",
"secret",
"secretaccesskey",
"credential",
"private_key",
"authorization",
"key",
"card_number",
"card_cvc",
"card_cvv",
"cvc",
"cvv",
"security_code",
"payment_credential",
"shared_payment_token"
]);
const t = new RegExp(`^(?:${CREDENTIAL_STYLE_HEADER_KEYS}|${GATEWAY_SECURITY_HEADER_KEYS})$`, "i");
const n = /* @__PURE__ */ new Set([CREDENTIAL_STYLE_EQUALS_ASSIGNMENT_REDACT_PATTERN, GATEWAY_SECURITY_EQUALS_ASSIGNMENT_REDACT_PATTERN]);
const r = /* @__PURE__ */ new Set([
ENV_ASSIGNMENT_REDACT_PATTERN,
ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN,
STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN,
STANDALONE_ASSIGNMENT_REDACT_PATTERN
]);
const i = new RegExp(String.raw`[:=](?<=(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})\s*[:=])`);
const a = new RegExp(String.raw`[:=](?<=(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})\s*[:=])\s*["'\x60]`);
const o = new RegExp(String.raw`[:=](?<=\.(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})\s*[:=])`);
const s = new RegExp(String.raw`=(?<=(?:^|[\s,;({\["])(?:${STANDALONE_ASSIGNMENT_SECRET_KEYS})=)`, "i");
return {
bodySecretKeys: e,
credentialHeaderField: t,
formAware: n,
shellReferencePreserving: r,
prefilters: new Map([
[ENV_ASSIGNMENT_REDACT_PATTERN, (e) => /KEY|TOKEN|SECRET|PASSWORD|PASSWD|CARD|CVC|CVV|SECURITY|PAYMENT/.test(e)],
[ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN, (e) => e.includes("\\")],
[STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN, (e) => /[=]["'`]/.test(e)],
[STANDALONE_ASSIGNMENT_REDACT_PATTERN, (e) => s.test(e)],
[CONFIG_QUOTED_ASSIGNMENT_REDACT_PATTERN, (e) => /["'`]/.test(e) && a.test(e)],
[CONFIG_ASSIGNMENT_REDACT_PATTERN, (e) => (e.includes(":") || e.includes("=")) && i.test(e)],
[CONFIG_DIRECT_ASSIGNMENT_REDACT_PATTERN, (e) => e.includes("=")],
[CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_REDACT_PATTERN, (e) => /[-_](?:password|passphrase|pass|passwd)\s*[:=]/.test(e)],
[CONFIG_NAMESPACED_ASSIGNMENT_REDACT_PATTERN, (e) => o.test(e)],
[AMBIGUOUS_QUOTED_SECRET_FIELD_REDACT_PATTERN, (e) => /["']/.test(e)],
[AMBIGUOUS_QUOTED_AUTH_FIELD_REDACT_PATTERN, (e) => /["']/.test(e)],
...HTTP_AUTH_HEADER_REDACT_PATTERNS.slice(0, 4).map((e) => [e, (e) => /authorization/i.test(e)]),
[CREDENTIAL_STYLE_COLON_HEADER_REDACT_PATTERN, (e) => /api-key|apikey|api-token|access-token/i.test(e)],
[CREDENTIAL_STYLE_EQUALS_ASSIGNMENT_REDACT_PATTERN, (e) => /api-key|apikey|api-token|access-token/i.test(e)],
[STRUCTURED_JSON_SECRET_REDACT_PATTERN, (e) => e.includes("\"")],
[STRUCTURED_JSON_PAYMENT_REDACT_PATTERN, (e) => e.includes("\"")],
[GATEWAY_SECURITY_COLON_HEADER_REDACT_PATTERN, (e) => /x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)],
[GATEWAY_SECURITY_EQUALS_ASSIGNMENT_REDACT_PATTERN, (e) => /x-openclaw-token|x-pomerium-jwt-assertion|x-api-key|x-auth-token/i.test(e)]
]),
chunkUnsafe: /* @__PURE__ */ new Set([
TELEGRAM_BOT_TOKEN_REDACT_PATTERN,
TELEGRAM_TOKEN_REDACT_PATTERN,
AUTHORIZATION_BEARER_REDACT_PATTERN,
AUTHORIZATION_BASIC_REDACT_PATTERN,
AUTHORIZATION_BOT_REDACT_PATTERN,
STANDALONE_BEARER_REDACT_PATTERN,
...HTTP_AUTH_HEADER_REDACT_PATTERNS,
...VENDOR_TOKEN_REDACT_PATTERNS.filter((e) => e.startsWith(BASE64_SAFE_TOKEN_BOUNDARY))
])
};
}
//#endregion
//#region src/logging/redact-linear-matchers.ts
const JS_WHITESPACE_CODES = /* @__PURE__ */ new Set([
9,
10,
11,
12,
13,
32,
160,
5760,
8232,
8233,
8239,
8287,
12288,
65279
]);
function isJsWhitespaceAt(e, t) {
if (t >= e.length) return false;
const n = e.charCodeAt(t);
return JS_WHITESPACE_CODES.has(n) || n >= 8192 && n <= 8202;
}
function isJsWhitespaceChar(e) {
return e !== void 0 && isJsWhitespaceAt(e, 0);
}
function isAlnumChar(e) {
if (e === void 0) return false;
const t = e.charCodeAt(0);
return t >= 48 && t <= 57 || t >= 65 && t <= 90 || t >= 97 && t <= 122;
}
function isLetterChar(e) {
if (e === void 0) return false;
const t = e.charCodeAt(0);
return t >= 65 && t <= 90 || t >= 97 && t <= 122;
}
function isWordChar(e) {
return e === "_" || isAlnumChar(e);
}
function isHexChar(e) {
if (e === void 0) return false;
const t = e.charCodeAt(0);
return t >= 48 && t <= 57 || t >= 65 && t <= 70 || t >= 97 && t <= 102;
}
function isDigitChar(e) {
return e !== void 0 && e.charCodeAt(0) >= 48 && e.charCodeAt(0) <= 57;
}
function isBase64UrlChar(e) {
return isAlnumChar(e) || e === "+" || e === "/" || e === "=";
}
const prefixRegexPools = /* @__PURE__ */ new Map();
/** Reuse compiled prefixes without sharing mutable lastIndex with a reentrant scan. */
function* scanPrefixOccurrences(e, t) {
let n = prefixRegexPools.get(t);
if (!n) {
n = [];
prefixRegexPools.set(t, n);
}
const r = n.pop() ?? new RegExp(t, "gi");
try {
r.lastIndex = 0;
for (let t = r.exec(e); t; t = r.exec(e)) yield t.index;
} finally {
r.lastIndex = 0;
n.push(r);
}
}
/** The `;base64,` exemption under the shared case-insensitive compilation of these rules. */
function isDataUrlPrefix(e, t) {
return t >= 8 && e.slice(t - 8, t).toLowerCase() === ";base64,";
}
function runEndOf(e, t, n) {
let r = t;
while (r < e.length && n(e[r])) r += 1;
return r;
}
function makeCachedRunEnd(e, t) {
let n = -1;
let r = -1;
return (i) => {
if (i < n || i >= r) {
n = i;
r = runEndOf(e, i, t);
}
return r;
};
}
/**
* Shared matcher for the `BASE64_SAFE_TOKEN_BOUNDARY` vendor rules. The boundary group is
* checked per candidate in O(1); the `(?<!;base64,[A-Za-z0-9+/=]*)` exemption walks each
* base64 run once because candidates advance left to right and share runs, replacing the
* unbounded lookbehind that rescanned the whole run from every candidate. The token-end
* function is created per exec() call so concurrent redactions never share scanner state.
*/
function makeBase64SafeTokenMatcher(e, t, n) {
function* exec(e) {
const r = n();
let i = -1;
let a = -1;
let o = 0;
for (const n of scanPrefixOccurrences(e, t)) {
if (n < o) continue;
if (n > 0 && isAlnumChar(e[n - 1])) continue;
if (n > 0) {
let t;
if (isBase64UrlChar(e[n - 1])) {
if (n - 1 >= i && n - 1 < a) t = i;
else {
let r = n - 1;
while (r > 0 && isBase64UrlChar(e[r - 1])) r -= 1;
i = r;
a = runEndOf(e, n, isBase64UrlChar);
t = r;
}
} else t = n;
if (isDataUrlPrefix(e, t)) continue;
}
const t = r(e, n);
if (t === null) continue;
const s = n > 0 ? n - 1 : 0;
yield {
match: e.slice(s, t),
groups: [n > 0 ? e[n - 1] : "", e.slice(n, t)],
input: e,
offset: s
};
o = t + 1;
}
}
return Object.freeze({
source: e,
exec
});
}
const GAAAA_VALUE_CHAR = (e) => isAlnumChar(e) || e === "_" || e === "=" || e === "-";
const ATBB_VALUE_CHAR = (e) => isAlnumChar(e) || e === "_" || e === "=" || e === "." || e === "-";
const AT_VALUE_CHAR = (e) => isAlnumChar(e) || e === "+" || e === "/" || e === "=" || e === "-" || e === "_";
function fixedTailTokenEnd(e, t, n) {
return (r, i) => {
const a = i + e + t;
for (let t = i + e; t < a; t++) if (!n(r[t])) return null;
return a;
};
}
/** `dapi` + 32 hex digits + an optional `-<digit>`; the optional tail is greedy like the regex. */
const dapiBodyEnd = fixedTailTokenEnd(4, 32, isHexChar);
function dapiTokenEnd(e, t) {
const n = dapiBodyEnd(e, t);
if (n === null) return null;
if (e[n] === "-" && isDigitChar(e[n + 1])) return n + 2;
return n;
}
/**
* `ATCTT3xFfG`/`ATATT` value: one or more class characters, then `=`, then exactly eight
* alphanumerics. Greedy backtracking lands on the rightmost `=` in the run whose next
* eight characters are alphanumerics; each run is scanned once and candidates share it.
*/
function makeAtEqualsTokenMatcher(e, t) {
const n = t.length;
const r = fixedTailTokenEnd(1, 8, isAlnumChar);
return makeBase64SafeTokenMatcher(e, t, () => {
let e = -1;
let t = -1;
let i;
return (a, o) => {
const s = o + n;
if (s < e || s >= t) {
t = runEndOf(a, s, AT_VALUE_CHAR);
e = s;
i = void 0;
for (let e = s; e < t; e++) if (a[e] === "=" && r(a, e) !== null) i = e;
}
const c = s + 1;
return i !== void 0 && i >= c ? i + 9 : null;
};
});
}
const GAAAA_TOKEN_MATCHER = makeBase64SafeTokenMatcher("vendor-token gAAAA (linear)", "gAAAA", () => (e, t) => {
const n = runEndOf(e, t + 5, GAAAA_VALUE_CHAR);
return n - (t + 5) >= 20 ? n : null;
});
const ATBB_TOKEN_MATCHER = makeBase64SafeTokenMatcher("vendor-token ATBB (linear)", "ATBB", () => (e, t) => {
const n = runEndOf(e, t + 4, ATBB_VALUE_CHAR);
return n - (t + 4) >= 16 ? n : null;
});
const AKIA_TOKEN_MATCHER = makeBase64SafeTokenMatcher("vendor-token AKIA (linear)", "AKIA", () => fixedTailTokenEnd(4, 16, isAlnumChar));
const ASIA_TOKEN_MATCHER = makeBase64SafeTokenMatcher("vendor-token ASIA (linear)", "ASIA", () => fixedTailTokenEnd(4, 16, isAlnumChar));
const DAPI_TOKEN_MATCHER = makeBase64SafeTokenMatcher("vendor-token dapi (linear)", "dapi", () => dapiTokenEnd);
const ATCTT_TOKEN_MATCHER = makeAtEqualsTokenMatcher("vendor-token ATCTT3xFfG (linear)", "ATCTT3xFfG");
const ATATT_TOKEN_MATCHER = makeAtEqualsTokenMatcher("vendor-token ATATT (linear)", "ATATT");
const JWT_REDACT_PATTERN = String.raw`(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`;
const JWT_SEGMENT_CHAR = (e) => isAlnumChar(e) || e === "_" || e === "-";
/** JWT rule: each `eyJ` candidate parses its three segments forward; class runs are shared. */
const JWT_MATCHER = Object.freeze({
source: "jwt (linear)",
*exec(e) {
const t = makeCachedRunEnd(e, JWT_SEGMENT_CHAR);
const n = makeCachedRunEnd(e, JWT_SEGMENT_CHAR);
const r = makeCachedRunEnd(e, JWT_SEGMENT_CHAR);
let i = 0;
for (const a of scanPrefixOccurrences(e, "eyj")) {
if (a < i) continue;
const o = t(a + 3);
if (o - (a + 3) < 10 || e[o] !== ".") continue;
const s = n(o + 1);
if (s - (o + 1) < 10 || e[s] !== ".") continue;
const c = r(s + 1);
if (c - (s + 1) < 10) continue;
const l = e.slice(a, c);
yield {
match: l,
groups: [l],
input: e,
offset: a
};
i = c;
}
}
});
const URL_USERINFO_REDACT_PATTERN = String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`;
const CONNECTION_STRING_REDACT_PATTERN = String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`;
const URL_USERINFO_SCHEMES = /* @__PURE__ */ new Set([
"http",
"https",
"ws",
"wss",
"ftp"
]);
const CONNECTION_STRING_SCHEMES = /* @__PURE__ */ new Set([
"postgres",
"postgresql",
"mysql",
"mongodb",
"mongodb+srv",
"redis",
"rediss",
"amqp",
"amqps"
]);
/**
* Shared matcher for the URL-userinfo and connection-string password rules. Both regexes are
* deterministic parses (each character class excludes its own terminators), so every `://`
* candidate parses forward once; failed password scans are memoized because later candidates
* share their tail regions.
*/
function makeUserInfoMatcher(e, t, n) {
function* exec(e) {
let r = 0;
let i = -1;
let a = e.indexOf("://");
while (a !== -1) {
let o = a;
while (o > 0 && isWordChar(e[o - 1])) o -= 1;
let s = e.slice(o, a).toLowerCase();
let c = o;
if (!t.has(s) && o >= 8 && s === "srv" && e.slice(o - 8, o).toLowerCase() === "mongodb+") {
s = "mongodb+srv";
c = o - 8;
}
if (a >= r && t.has(s) && (c === 0 || !isWordChar(e[c - 1]))) {
let t = a + 3;
while (t < e.length && e[t] !== ":" && e[t] !== "/" && e[t] !== "@" && !isJsWhitespaceAt(e, t)) t += 1;
if (e[t] === ":") {
const o = t + 1;
if (o >= i) {
const t = runEndOf(e, o, (e) => !n(e));
if (e[t] === "@" && t > o) {
yield {
match: e.slice(c, t + 1),
groups: [e.slice(o, t)],
input: e,
offset: c
};
r = t + 1;
a = e.indexOf("://", t + 1);
continue;
}
i = t;
}
}
}
a = e.indexOf("://", a + 1);
}
}
return Object.freeze({
source: e,
exec
});
}
const URL_USERINFO_MATCHER = makeUserInfoMatcher("url-userinfo (linear)", URL_USERINFO_SCHEMES, (e) => e === "/" || e === "@" || isJsWhitespaceChar(e));
const CONNECTION_STRING_MATCHER = makeUserInfoMatcher("connection-string (linear)", CONNECTION_STRING_SCHEMES, (e) => e === "@" || isJsWhitespaceChar(e));
const FORM_BODY_FIRST_PAIR_REDACT_PATTERN = String.raw`(^|[\s,;])(?:${FORM_BODY_FIRST_PAIR_KEYS})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`;
const FORM_FIRST_PAIR_KEYS_RE = new RegExp(`^(?:${FORM_BODY_FIRST_PAIR_KEYS})$`, "i");
const FORM_FIRST_PAIR_KEY_CHAR = (e) => isAlnumChar(e) || e === "-" || e === "_";
const FORM_FIRST_PAIR_TAIL_CHAR = (e) => isAlnumChar(e) || e === "_" || e === "." || e === "-";
/** The lookahead `&[A-Za-z_][A-Za-z0-9_.-]*=` is a deterministic forward check. */
function isFormPairBoundary(e, t) {
const n = e[t + 1];
if (!(n !== void 0 && (isLetterChar(n) || n === "_"))) return false;
return e[runEndOf(e, t + 2, FORM_FIRST_PAIR_TAIL_CHAR)] === "=";
}
/**
* Form first-pair rule: the value class excludes `&` and whitespace, so the greedy value
* always ends at the first `&` or whitespace and the lookahead is checked there alone;
* per-candidate value runs are shared so long runs are read once.
*/
const FORM_BODY_FIRST_PAIR_MATCHER = Object.freeze({
source: "form-body-first-pair (linear)",
*exec(e) {
const t = makeCachedRunEnd(e, (e) => e !== "&" && !isJsWhitespaceChar(e));
let n = 0;
let r = e.indexOf("=");
while (r !== -1) {
let i = r;
while (i > 0 && FORM_FIRST_PAIR_KEY_CHAR(e[i - 1])) i -= 1;
const a = e.slice(i, r);
if (r >= n && a.length > 0 && FORM_FIRST_PAIR_KEYS_RE.test(a) && (i === 0 || e[i - 1] === "," || e[i - 1] === ";" || isJsWhitespaceAt(e, i - 1))) {
const a = r + 1;
const o = t(a);
if (o > a && o < e.length && e[o] === "&" && isFormPairBoundary(e, o)) {
const t = i > 0 ? i - 1 : 0;
yield {
match: e.slice(t, o),
groups: [i > 0 ? e[i - 1] : "", e.slice(a, o)],
input: e,
offset: t
};
n = o;
r = e.indexOf("=", o);
continue;
}
}
r = e.indexOf("=", r + 1);
}
}
});
const STANDALONE_QUOTED_PREFIX_SOURCE = String.raw`(^|[\s,;({\["])(?:${STANDALONE_ASSIGNMENT_SECRET_KEYS})=(["'\x60])`;
const CONFIG_QUOTED_PREFIX_SOURCE = String.raw`(^|[\s,{])(?:(?:${CONFIG_QUOTED_ASSIGNMENT_SECRET_KEYS})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*)(["'\x60])`;
/**
* Shared matcher for the two quoted-value rules. The tempered dot `((?:(?!\2)[^\r\n])+)`
* forced a per-character lookahead and one backtrack stack entry per value character; the
* value here is a linear scan to the first closing quote or line end, and failed scans are
* memoized per quote character because later candidates share their tail regions.
*/
function makeQuotedAssignmentMatcher(e, t, n) {
const r = [];
function* exec(e) {
const i = r.pop() ?? new RegExp(t, n);
const a = /* @__PURE__ */ new Map();
let o = 0;
try {
for (;;) {
i.lastIndex = o;
const t = i.exec(e);
if (!t) return;
const n = t.index;
const r = t[2];
const s = n + t[0].length;
const c = a.get(r);
let l = -1;
if (!(c !== void 0 && s >= c.start && s < c.end)) {
l = s;
while (l < e.length) {
const t = e[l];
if (t === r || t === "\r" || t === "\n") break;
l += 1;
}
}
if (l > s && e[l] === r) {
const i = l + 1;
yield {
match: e.slice(n, i),
groups: [
t[1] ?? "",
r,
e.slice(s, l)
],
input: e,
offset: n
};
o = i;
} else {
if (l !== -1) a.set(r, {
start: s,
end: l
});
o = n + 1;
}
}
} finally {
i.lastIndex = 0;
r.push(i);
}
}
return Object.freeze({
source: e,
exec
});
}
const STANDALONE_QUOTED_MATCHER = makeQuotedAssignmentMatcher("standalone-quoted-assignment (linear)", STANDALONE_QUOTED_PREFIX_SOURCE, "gi");
const CONFIG_QUOTED_MATCHER = makeQuotedAssignmentMatcher("config-quoted-assignment (linear)", CONFIG_QUOTED_PREFIX_SOURCE, "g");
/** Default rule sources whose compilation routes to the linear matchers above. */
const LINEAR_MATCHER_SOURCES = /* @__PURE__ */ new Map([
[base64SafeToken(String.raw`gAAAA[A-Za-z0-9_=-]{20,}`), GAAAA_TOKEN_MATCHER],
[base64SafeToken(String.raw`ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`), ATCTT_TOKEN_MATCHER],
[base64SafeToken(String.raw`ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8}`), ATATT_TOKEN_MATCHER],
[base64SafeToken(String.raw`ATBB[A-Za-z0-9_=.-]{16,}`), ATBB_TOKEN_MATCHER],
[base64SafeToken(String.raw`dapi[0-9a-f]{32}(?:-\d)?`), DAPI_TOKEN_MATCHER],
[base64SafeToken(String.raw`AKIA[A-Z0-9]{16}`), AKIA_TOKEN_MATCHER],
[base64SafeToken(String.raw`ASIA[A-Z0-9]{16}`), ASIA_TOKEN_MATCHER],
[JWT_REDACT_PATTERN, JWT_MATCHER],
[URL_USERINFO_REDACT_PATTERN, URL_USERINFO_MATCHER],
[CONNECTION_STRING_REDACT_PATTERN, CONNECTION_STRING_MATCHER],
[FORM_BODY_FIRST_PAIR_REDACT_PATTERN, FORM_BODY_FIRST_PAIR_MATCHER],
[STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN, STANDALONE_QUOTED_MATCHER],
[CONFIG_QUOTED_ASSIGNMENT_REDACT_PATTERN, CONFIG_QUOTED_MATCHER]
]);
//#endregion
//#region src/logging/redact-mask.ts
const DEFAULT_REDACT_MIN_LENGTH = 18;
const DEFAULT_REDACT_KEEP_START = 6;
const SECRET_VALUE_TRAILING_DELIMITER_RE = /(["'`,;)}\]]+)$/u;
const SECRET_VALUE_SUFFIX_RE = /^["'`,;)}\]]*$/u;
const SECRET_VALUE_QUOTE_CHARS = /* @__PURE__ */ new Set([
"\"",
"'",
"`"
]);
function maskToken(e) {
if (e.length < DEFAULT_REDACT_MIN_LENGTH) return "***";
return `${sliceUtf16Safe(e, 0, DEFAULT_REDACT_KEEP_START)}…${sliceUtf16Safe(e, -4)}`;
}
function splitSecretValueForMask(e) {
const t = e[0] ?? "";
const n = SECRET_VALUE_QUOTE_CHARS.has(t) ? 1 : 0;
if (n) {
const n = e.lastIndexOf(t);
if (n > 0) {
const t = e.slice(n + 1);
if (SECRET_VALUE_SUFFIX_RE.test(t)) return {
maskable: e.slice(1, n),
suffix: t,
maskStart: 0,
maskEnd: n + 1
};
}
}
const r = e.slice(n);
const i = r.match(SECRET_VALUE_TRAILING_DELIMITER_RE)?.[1] ?? "";
const a = i && i.length < r.length ? r.slice(0, -i.length) : r;
return {
maskable: a,
suffix: a === r ? "" : i,
maskStart: 0,
maskEnd: n + a.length
};
}
function splitFormAwareCredentialValue(e) {
const t = e.search(/&[A-Za-z_][A-Za-z0-9_.-]*=/u);
return t < 0 ? {
secret: e,
suffix: ""
} : {
secret: e.slice(0, t),
suffix: e.slice(t)
};
}
function maskSecretValue(e) {
const { maskable: t, suffix: n } = splitSecretValueForMask(e);
return `${maskToken(t)}${n}`;
}
//#endregion
//#region src/logging/redact-performance.ts
const redactionPerformance = channel("openclaw.redaction");
/** The capture subscriber receives counts and synchronous CPU time, never text or patterns. */
function startRedactionMeasurement(e) {
if (!redactionPerformance.hasSubscribers) return;
const t = performance.now();
const n = process.threadCpuUsage();
return (r, i, a) => {
const o = performance.now() - t;
const s = process.threadCpuUsage(n);
redactionPerformance.publish({
operation: e,
outcome: r,
pid: process.pid,
threadId,
isMainThread,
elapsedMs: o,
threadCpuMs: (s.user + s.system) / 1e3,
...i === void 0 ? {} : { inputChars: i },
...a === void 0 ? {} : { patternCount: a }
});
};
}
//#endregion
//#region src/logging/redact-prefilter.ts
const FIELD_KEY_PREFILTER_RE = /KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH|COOKIE|SIGNATURE|CREDENTIAL|CARD|CVC|CVV|PAYMENT|security[-_]?code|\bpass\s*[=:]|\bpassphrase\s*[=:]|_(?:password|pass|passphrase|passwd)\s*[=:]|jwt\s*[=:]|session=|code=|\bsig\s*=/iu;
const SEPARATED_VENDOR_PREFILTER_RE = /sk-|GOCSPX-|gh[opsur]_|github_pat_|glpat-|gloas-|gldt-|glcbt-|glptt-|glft-|glimt-|glagent-|glwt-|glsoat-|glffct-|glrt-|glrtr-|_gitlab_session=|xox[baprs]-|xapp-|gsk_|pplx-|fal_|fc-|bb_live_|[sr]k_(?:live|test)_|npm_|pypi-|do[opr]_v1_|dckr_|bkua_|CCIPAT_|sbp_|dd[pw]_|glsa_|nfp_|CFPAT-|BBDC-|HRKU-|pat-(?:eu|na)1-|apify_api_|fio-u-|tvly-|exa_|syt_|retaindb_|mem0_|brv_|xai-|fw-|fw_|fpk_|(?:^|[^A-Za-z0-9_])(?:am_|sk_)|hf_|api_org_|r8_/iu;
const DEFAULT_REDACT_PREFILTER_RE = /PRIVATE KEY|\bBearer\s+|GR1348941|hooks\.slack\.com|discord|AIza|ya29\.|1\/\/0|eyJ|gAAAA|SG\.|dp\.(?:ct|pt|sa|st|scim|audit)\.|dapi[0-9a-f]|ATCTT3|ATATT|ATBB|FlyV1|A[KS]IA[A-Z0-9]|AKID|LTAI|\bbot\d{6,}:|\b\d{6,}:[A-Za-z0-9_-]{20,}/iu;
const OBFUSCATED_KEY_CHAR_RE = new RegExp(`[${FORM_BODY_KEY_INVISIBLE_CHARS}+%]`, "u");
const FULL_CONTEXT_REDACT_EXTRA_TRIGGERS_RE = /JWT|Bearer\s+|am_|sk_|(?<!\d)\d{6,}:[A-Za-z0-9_-]{20,}/i;
function couldMatchDefaultRedactPatterns(e) {
return FIELD_KEY_PREFILTER_RE.test(e) || (e.includes("-") || e.includes("_")) && SEPARATED_VENDOR_PREFILTER_RE.test(e) || DEFAULT_REDACT_PREFILTER_RE.test(e) || e.includes("://") && e.includes("@") || e.includes("=") && OBFUSCATED_KEY_CHAR_RE.test(e) || AWS_SECRET_ACCESS_KEY_MATCHER.couldMatch(e);
}
function couldMatchDefaultFullContextPatterns(e) {
return couldMatchDefaultRedactPatterns(e) || FULL_CONTEXT_REDACT_EXTRA_TRIGGERS_RE.test(e);
}
function couldMatchVendorRedactPatterns(e) {
return (e.includes("-") || e.includes("_")) && SEPARATED_VENDOR_PREFILTER_RE.test(e) || DEFAULT_REDACT_PREFILTER_RE.test(e) || FULL_CONTEXT_REDACT_EXTRA_TRIGGERS_RE.test(e);
}
function createRedactPrefilter(e) {
const t = /* @__PURE__ */ new Map();
return (n) => {
const r = t.get(n);
if (r !== void 0) return r;
const i = e(n);
t.set(n, i);
return i;
};
}
//#endregion
//#region src/plugins/record-groups.ts
function groupPluginRecords(e, t) {
const n = /* @__PURE__ */ new Map();
for (const r of e) {
const e = t(r);
const i = n.get(e);
if (i) i.push(r);
else n.set(e, [r]);
}
return n;
}
//#endregion
//#region src/logging/secret-redaction-registry.ts
const MIN_SECRET_VALUE_LENGTH = 6;
const state = resolveGlobalSingleton(Symbol.for("openclaw.secretRedactionRegistry"), () => ({
revision: 0,
registeredValues: /* @__PURE__ */ new Map(),
registeredValueRedactor: void 0
}));
function invalidateMatcher() {
state.revision += 1;
state.registeredValueRedactor = void 0;
}
/** Replaces registered exact values while preserving the caller's mask convention. */
function redactRegisteredSecretValues(e, t) {
if (!e || state.registeredValues.size === 0) return e;
state.registeredValueRedactor ??= createSecretValueRedactor([...state.registeredValues.keys()]);
return state.registeredValueRedactor(e, t);
}
function createSecretValueRedactor(e) {
let t;
let n;
return (r, i) => {
if (!r || e.length === 0) return r;
let a = false;
n ??= new Set(e.map((e) => e.charAt(0)));
for (const e of n) if (r.includes(e)) {
a = true;
break;
}
if (!a) return r;
if (!t) {
const n = groupPluginRecords(e.toSorted((e, t) => t.length - e.length), (e) => e.slice(0, MIN_SECRET_VALUE_LENGTH));
t = {
prefixes: new RegExp([...n.keys()].map(escapeRegExp).join("|"), "g"),
buckets: n
};
}
const { prefixes: o, buckets: s } = t;
const c = [];
o.lastIndex = 0;
for (let e = o.exec(r); e; e = o.exec(r)) {
const t = e.index;
const n = s.get(e[0])?.find((e) => r.startsWith(e, t));
if (n !== void 0) c.push({
index: t,
value: n
});
o.lastIndex = t + (n?.length ?? 1);
}
let l = "";
let u = 0;
for (const e of c) {
l += `${r.slice(u, e.index)}${i(e.value, e.index)}`;
u = e.index + e.value.length;
}
return l + r.slice(u);
};
}
function resetSecretRedactionRegistryForTest() {
state.registeredValues.clear();
invalidateMatcher();
}
if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.secretRedactionRegistryTestApi")] = { resetSecretRedactionRegistryForTest };
//#endregion
//#region src/infra/tls-certificate-errors.ts
const HOSTNAME_MISMATCH_CODES = /* @__PURE__ */ new Set(["ERR_TLS_CERT_ALTNAME_INVALID", "HOSTNAME_MISMATCH"]);
const CERTIFICATE_INVALID_CODES = /* @__PURE__ */ new Set([
"CERT_CHAIN_TOO_LONG",
"CERT_HAS_EXPIRED",
"CERT_NOT_YET_VALID",
"CERT_REJECTED",
"CERT_REVOKED",
"CERT_SIGNATURE_FAILURE",
"CERT_UNTRUSTED",
"CRL_HAS_EXPIRED",
"CRL_NOT_YET_VALID",
"CRL_SIGNATURE_FAILURE",
"DEPTH_ZERO_SELF_SIGNED_CERT",
"ERROR_IN_CERT_NOT_AFTER_FIELD",
"ERROR_IN_CERT_NOT_BEFORE_FIELD",
"ERROR_IN_CRL_LAST_UPDATE_FIELD",
"ERROR_IN_CRL_NEXT_UPDATE_FIELD",
"INVALID_CA",
"INVALID_PURPOSE",
"PATH_LENGTH_EXCEEDED",
"SELF_SIGNED_CERT_IN_CHAIN",
"UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
"UNABLE_TO_DECRYPT_CERT_SIGNATURE",
"UNABLE_TO_DECRYPT_CRL_SIGNATURE",
"UNABLE_TO_GET_CRL",
"UNABLE_TO_GET_ISSUER_CERT",
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
"UNABLE_TO_VERIFY_LEAF_SIGNATURE"
]);
const HOSTNAME_MISMATCH_PATTERNS = [
/hostname\/ip does not match certificate(?:'s)? altnames/i,
/hostname mismatch/i,
/host: .+ is not in the cert(?:ificate)?(?:'s)? altnames/i
];
const CERTIFICATE_INVALID_PATTERNS = [
/certificate has expired/i,
/certificate is not yet valid/i,
/self[- ]signed certificate/i,
/unable to get local issuer certificate/i,
/unable to verify the first certificate/i
];
const MAX_TLS_ERROR_DEPTH = 8;
function classifyCode(e) {
if (HOSTNAME_MISMATCH_CODES.has(e)) return "hostname_mismatch";
return CERTIFICATE_INVALID_CODES.has(e) ? "certificate_invalid" : null;
}
function classifyMessage(e) {
if (HOSTNAME_MISMATCH_PATTERNS.some((t) => t.test(e))) return "hostname_mismatch";
return CERTIFICATE_INVALID_PATTERNS.some((t) => t.test(e)) ? "certificate_invalid" : null;
}
function inspectTlsCertificateErrorInternal(e, t, n) {
if (n > MAX_TLS_ERROR_DEPTH) return null;
if (typeof e === "string") {
const t = classifyMessage(e);
return t ? {
kind: t,
message: e
} : null;
}
if (!e || typeof e !== "object" || t.has(e)) return null;
t.add(e);
const r = e;
const i = typeof r.code === "string" ? r.code.trim().toUpperCase() : void 0;
const a = typeof r.message === "string" && r.message.trim() ? r.message : void 0;
const o = i ? classifyCode(i) : null;
if (i && o) return {
kind: o,
code: i,
message: a ?? i
};
const s = Array.isArray(r.errors) ? r.errors : [];
for (const e of [
r.cause,
r.error,
...s
]) {
const r = inspectTlsCertificateErrorInternal(e, t, n + 1);
if (r) return r;
}
const c = a ? classifyMessage(a) : null;
return c && a ? {
kind: c,
message: a
} : null;
}
/** Classify deterministic Node/OpenSSL certificate validation failures. */
function inspectTlsCertificateError(e) {
return inspectTlsCertificateErrorInternal(e, /* @__PURE__ */ new Set(), 0);
}
//#endregion
//#region src/shared/assistant-error-format.ts
const HTTP_STATUS_DELIMITER_RE = /(?:\s*:\s*|\s+)/;
const HTTP_STATUS_PREFIX_RE = new RegExp(`^(?:http\\s*)?(\\d{3})${HTTP_STATUS_DELIMITER_RE.source}(.+)$`, "i");
const HTTP_STATUS_CODE_PREFIX_RE = new RegExp(`^(?:http\\s*)?(\\d{3})(?:${HTTP_STATUS_DELIMITER_RE.source}([\\s\\S]+))?$`, "i");
const CONNECTION_FAILED_MESSAGE = "Couldn't connect to the AI service. Check your connection, then try again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`.";
const TRANSPORT_ERRORS = [
{
code: /\beconnrefused\b/i,
phrases: /connection refused|actively refused/i,
message: CONNECTION_FAILED_MESSAGE
},
{
code: /\beconnreset\b|\beconnaborted\b|\benetreset\b|\bepipe\b/i,
phrases: /socket hang up|connection reset|connection aborted/i,
message: "Lost the connection to the AI service. Check the conversation before trying again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`."
},
{
code: /\benotfound\b|\beai_again\b|\benetunreach\b|\behostunreach\b|\behostdown\b/i,
phrases: /getaddrinfo|no such host|\bdns\b|network is unreachable|host is unreachable|fetch failed|connection error|network request failed/i,
message: CONNECTION_FAILED_MESSAGE
}
];
function isKnownTransportErrorCode(e) {
return TRANSPORT_ERRORS.some(({ code: t }) => t.exec(e)?.[0] === e) || inspectTlsCertificateError({ code: e })?.code === e;
}
//#endregion
//#region src/logging/structured-authorization-code.ts
function shouldRedactStructuredAuthorizationCode(e, t, n) {
if (e !== "code") return false;
const r = t.map((e) => e.toLowerCase());
if (r.length === 1 || r.at(-1) === "code" && [
"error",
"nodeerror",
"status",
"details",
"warnings"
].includes(r.at(-2) ?? "")) return false;
return !(n !== void 0 && r.length > 1 && r.slice(0, -1).every((e) => e === "cause") && isKnownTransportErrorCode(n));
}
//#endregion
//#region src/logging/redact.ts
const DEFAULT_REDACT_MODE = "tools";
const backendPatterns = createBackendRedactPatterns();
const shellReferencePreservingPatterns = /* @__PURE__ */ new WeakSet();
const builtInResolvedPatterns = /* @__PURE__ */ new WeakSet();
const vendorResolvedPatterns = /* @__PURE__ */ new WeakMap();
const vendorSources = new Set(VENDOR_TOKEN_REDACT_PATTERNS);
const chunkUnsafePatterns = /* @__PURE__ */ new WeakSet();
const canonicalBuiltInSources = new Set(DEFAULT_REDACT_PATTERNS.filter((e) => typeof e === "string"));
const formAwareEqualsAssignmentPatterns = /* @__PURE__ */ new WeakSet();
let defaultResolvedPatterns;
let warnedInvalidPatterns = false;
const FORM_BODY_KEY_OBFUSCATION_RE = new RegExp(String.raw`[${FORM_BODY_KEY_INVISIBLE_CHARS}+]`, "gu");
const FORM_BODY_KEY_SEPARATOR_RE = /[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu;
const FORM_BODY_PERCENT_ESCAPE_RE = /%[0-9A-Fa-f]{2}/u;
const FORM_BODY_KEY = String.raw`[${FORM_BODY_KEY_INVISIBLE_CHARS}+]*(?:[A-Za-z_]|%[0-9A-Fa-f]{2})(?:[A-Za-z0-9_.-]|%[0-9A-Fa-f]{2}|[${FORM_BODY_KEY_INVISIBLE_CHARS}+])*`;
const FORM_BODY_VALUE = "[^&\\s<>]*";
const URL_QUERY_VALUE = "[^&#\\s<>]*";
const FORM_BODY_PAIR = String.raw`${FORM_BODY_KEY}=${FORM_BODY_VALUE}`;
const FORM_BODY_RE = new RegExp(String.raw`^${FORM_BODY_PAIR}(?:&${FORM_BODY_PAIR})+$`, "u");
const FORM_BODY_SUBSTRING_RE = new RegExp(String.raw`(^|[\s:({\[,="'` + "`" + String.raw`])(${FORM_BODY_PAIR}(?:&${FORM_BODY_PAIR})+)`, "gu");
const ENCODED_FORM_PAIR_RE = new RegExp(String.raw`(^|[\s:({\[,="'` + "`" + String.raw`&])(${FORM_BODY_KEY})=(${FORM_BODY_VALUE})`, "gu");
const FORM_BODY_CONTEXT_SINGLE_PAIR_RE = new RegExp(String.raw`(\b(?:body|form(?:[-_\s]?body)?)\s*[:=]\s*(["'\x60]?))(${FORM_BODY_KEY})=(${FORM_BODY_VALUE})(["'\x60]?)`, "giu");
const URL_QUERY_PAIR_RE = new RegExp(String.raw`([?&])(${FORM_BODY_KEY})=(${URL_QUERY_VALUE})`, "gu");
const FORM_BODY_LINE_BREAK_SPLIT_RE = /(\r\n|\r|\n)/u;
const FORM_BODY_LINE_BREAK_SEGMENT_RE = /^(?:\r\n|\r|\n)$/u;
const STRUCTURED_SECRET_FIELD_RE = new RegExp(String.raw`^(?:api[-_]?key|apiKey|api[-_]?token|apiToken|bearer[-_]?token|bearerToken|token|secret|password|passwd|${AWS_SECRET_ACCESS_KEY_FIELD_KEYS}|credential|authorization|private[-_]?key|privateKey|access[-_]?token|accessToken|refresh[-_]?token|refreshToken|id[-_]?token|idToken|auth[-_]?token|authToken|client[-_]?secret|clientSecret|app[-_]?secret|appSecret|secret[-_]?value|secretValue|raw[-_]?secret|rawSecret|secret[-_]?input|secretInput|key|key[-_]?material|keyMaterial|jwt|session|signature|cookie|set[-_]?cookie|${PAYMENT_CREDENTIAL_QUERY_KEYS}|${PAYMENT_CREDENTIAL_JSON_KEYS})$`, "i");
const STRUCTURED_INTERNAL_SOURCE_PATH_VALUE_RE = /^\$WORKSPACE_DIR\/[A-Za-z0-9._/-]+\.jsonl$/u;
const STRUCTURED_APP_PASSWORD_FIELD_RE = /^(?:apple|icloud|app[-_]?specific[-_]?password|appSpecificPassword|application[-_]?password|text|content|message|error|errorMessage|detail|details|reason)$/i;
const APP_SPECIFIC_PASSWORD_RE = /\b([a-z]{4}-[a-z]{4}-[a-z]{4}-[a-z]{4})\b/g;
const BENIGN_APP_PASSWORD_WORDS = /* @__PURE__ */ new Set([
"case",
"claw",
"demo",
"file",
"main",
"name",
"open",
"path",
"slug",
"test"
]);
const STRUCTURED_SECRET_ENV_FIELD_RE = new RegExp(String.raw`^(?:(?:[A-Z0-9]+[_-])+(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD)|API[_-]?KEY|TOKEN|SECRET|PASSWORD|PASSWD|${PAYMENT_CREDENTIAL_ENV_KEYS})$`, "i");
function parsePattern(e) {
if (e === PEM_REDACT_PATTERN_SOURCE) return PEM_REDACT_MATCHER;
if (typeof e !== "string" && !(e instanceof RegExp)) return e !== null && typeof e === "object" && typeof e.exec === "function" ? e : null;
let t = typeof e === "string" ? LINEAR_MATCHER_SOURCES.get(e) ?? null : null;
let n = true;
if (e instanceof RegExp) {
if (e.flags.includes("g")) t = e;
else t = new RegExp(e.source, `${e.flags}g`);
} else if (!t && e.trim()) {
const [r, i] = parseRedactPatternSource(e);
const a = canonicalBuiltInSources.has(e) ? rewriteOpenEndedRepeats(r, i) : r;
t = compileConfigRegex(a, i)?.regex ?? null;
n = t !== null && t.source === a && t.flags === i && t.exec === RegExp.prototype.exec && t[Symbol.replace] === RegExp.prototype[Symbol.replace];
}
if (t && typeof e === "string" && backendPatterns.shellReferencePreserving.has(e)) shellReferencePreservingPatterns.add(t);
if (t && typeof e === "string" && backendPatterns.formAware.has(e)) formAwareEqualsAssignmentPatterns.add(t);
if (t && typeof e === "string" && (e.startsWith(IDENTIFIER_SAFE_TOKEN_BOUNDARY) || backendPatterns.chunkUnsafe.has(e))) chunkUnsafePatterns.add(t);
if (t && typeof e === "string") {
if (canonicalBuiltInSources.has(e)) builtInResolvedPatterns.add(t);
if (n && vendorSources.has(e) && !vendorResolvedPatterns.has(t)) {
const e = t.source;
const n = t.exec;
const r = t instanceof RegExp ? t.flags : void 0;
const i = t instanceof RegExp ? t[Symbol.replace] : void 0;
vendorResolvedPatterns.set(t, () => t.source === e && t.exec === n && (!(t instanceof RegExp) || t.flags === r && t[Symbol.replace] === i));
}
const r = backendPatterns.prefilters.get(e);
if (n && r) setRedactPatternPrefilter(t, r);
}
return t;
}
function resolvePatterns(e) {
if (usesBuiltInRedactPatterns(e)) {
defaultResolvedPatterns ??= DEFAULT_REDACT_PATTERNS.map(parsePattern).filter((e) => Boolean(e));
return defaultResolvedPatterns;
}
const t = /* @__PURE__ */ new Set();
let n = !Array.isArray(e);
for (const r of Array.isArray(e) ? e : []) {
const e = parsePattern(r);
if (e) t.add(e);
else n = true;
}
if (n) {
for (const e of resolvePatterns()) t.add(e);
if (!warnedInvalidPatterns) {
warnedInvalidPatterns = true;
try {
console.warn("[openclaw] Ignoring invalid logging.redactPatterns entries; keeping valid patterns and built-in redaction. Fix logging.redactPatterns in your config.");
} catch {}
}
}
t.add(AWS_SECRET_ACCESS_KEY_MATCHER);
return [...t];
}
function usesBuiltInRedactPatterns(e) {
return e === void 0 || e === DEFAULT_REDACT_PATTERNS || Array.isArray(e) && e.length === 0;
}
function normalizeSensitiveKeyName(e) {
const t = e.replace(FORM_BODY_KEY_SEPARATOR_RE, "");
try {
return decodeURIComponent(t).replace(FORM_BODY_KEY_SEPARATOR_RE, "").toLowerCase().replaceAll("-", "_");
} catch {
return t.toLowerCase().replaceAll("-", "_");
}
}
function isSensitiveBodyKey(e) {
return isSensitiveUrlQueryParamName(e) || backendPatterns.bodySecretKeys.has(normalizeSensitiveKeyName(e));
}
function hasEncodedOrInvisibleFormKey(e) {
return FORM_BODY_PERCENT_ESCAPE_RE.test(e) || e.replace(FORM_BODY_KEY_OBFUSCATION_RE, "") !== e;
}
function visitSensitiveAssignments(e, t, n) {
if (!e || t === "url" && !e.includes("?")) return;
if (t === "encoded" && !e.includes("%") && e.replace(FORM_BODY_KEY_OBFUSCATION_RE, "") === e) return;
if (t === "context" && !/[=:]/u.test(e)) return;
const visitPair = (e, r, i) => {
if (t === "encoded" && !hasEncodedOrInvisibleFormKey(e)) return;
if (!isSensitiveBodyKey(e)) return;
const { maskable: a, maskStart: o, maskEnd: s } = splitSecretValueForMask(r);
n(i + o, i + s, a);
};
if (t === "form") {
let t = 0;
for (const n of e.split("&")) {
const e = n.indexOf("=");
if (e >= 0) visitPair(n.slice(0, e), n.slice(e + 1), t + e + 1);
t += n.length + 1;
}
return;
}
const r = t === "url" ? URL_QUERY_PAIR_RE : t === "encoded" ? ENCODED_FORM_PAIR_RE : FORM_BODY_CONTEXT_SINGLE_PAIR_RE;
const i = t === "context" ? 3 : 2;
r.lastIndex = 0;
try {
for (let t = r.exec(e); t; t = r.exec(e)) {
const e = t[1] ?? "";
const n = t[i] ?? "";
visitPair(n, t[i + 1] ?? "", t.index + e.length + n.length + 1);
}
} finally {
r.lastIndex = 0;
}
}
function redactAssignmentValues(e, t, n) {
const r = [];
const i = [];
let a = 0;
visitSensitiveAssignments(e, t, (o, s, c) => {
const l = t === "url" ? maskToken(c) : "***";
r.push(e.slice(a, o), l);
if (n) i.push({
start: o,
end: s,
replacement: l
});
a = s;
});
if (i.length > 0) n?.(i);
return r.length > 0 ? r.join("") + e.slice(a) : e;
}
function redactFormBodyLine(e, t) {
if (!e.includes("=")) return e;
const n = redactAssignmentValues(redactAssignmentValues(e, "encoded", t), "context", t);
if (!n.includes("&")) return n;
if (FORM_BODY_RE.test(n)) return redactAssignmentValues(n, "form", t);
const r = [];
const i = n.replace(FORM_BODY_SUBSTRING_RE, (e, n, i, a) => {
const o = redactAssignmentValues(i, "form", t ? (e) => {
for (const t of e) r.push({
...t,
start: a + n.length + t.start,
end: a + n.length + t.end
});
} : void 0);
return o === i ? e : `${n}${o}`;
});
if (r.length > 0) t?.(r);
return redactAssignmentValues(redactAssignmentValues(i, "encoded", t), "context", t);
}
function redactFormBody(e, t) {
if (!e.includes("=")) return e;
if (FORM_BODY_LINE_BREAK_SPLIT_RE.test(e)) {
let n = 0;
return e.split(FORM_BODY_LINE_BREAK_SPLIT_RE).map((e) => {
const r = FORM_BODY_LINE_BREAK_SEGMENT_RE.test(e) ? e : redactFormBodyLine(e, t ? (e) => t(e.map((e) => ({
...e,
start: n + e.start,
end: n + e.end
}))) : void 0);
n += r.length;
return r;
}).join("");
}
return redactFormBodyLine(e, t);
}
function isShellReferenceToKey(e, t) {
if (!/^[A-Z_][A-Z0-9_]*$/.test(e)) return false;
const n = t.match(/^\$([A-Z_][A-Z0-9_]*)$/);
if (n) return n[1] === e;
return t.match(/^\$\{([A-Z_][A-Z0-9_]*)(?::[-=?+])?\}$/)?.[1] === e;
}
function maskSecretFieldValue(e, t) {
const n = t.match(/^\$\{([A-Z_][A-Z0-9_]*):[-=?+][^{}]+\}(?![\s\S])/);
if (n && n[1] === e) return `${t.slice(0, t.indexOf(":") + 2)}***}`;
return "***";
}
function shouldPreserveShellReferenceMatch(e, t) {
const n = e.match(/\b([A-Z_][A-Z0-9_]*)\b\s*[=:]/)?.[1];
return n ? isShellReferenceToKey(n, t) : false;
}
function isEmptyShellParameterExpansionTail(e) {
return /^[-=?+]\}$/.test(e);
}
function prepareRedactionCapture({ match: e, groups: t, input: n, offset: r, replacement: i }, a) {
if (e.includes("PRIVATE KEY-----")) return {
start: r,
end: r + e.length,
value: e,
redact: (e) => ({
start: e.start,
end: e.end,
value: e.value,
replacement: i ?? redactPemBlock(e.value, "…redacted…")
})
};
const o = selectSecretCapture(e, t);
if (o.value === "***") return;
const s = o.value === e ? 0 : getSecretCaptureStart(a, n, e, r, o);
if (s < 0) return;
const c = r + s;
return {
start: c,
end: c + o.value.length,
value: o.value,
redact: (t) => {
const n = t.value;
const r = formAwareEqualsAssignmentPatterns.has(a) ? splitFormAwareCredentialValue(n) : {
secret: n,
suffix: ""
};
if (splitSecretValueForMask(r.secret).maskable === "***") return;
const o = shellReferencePreservingPatterns.has(a);
if (o && (shouldPreserveShellReferenceMatch(e, n) || isEmptyShellParameterExpansionTail(n))) return;
const s = i ?? (o ? maskToken(n) : `${maskSecretValue(r.secret)}${r.suffix}`);
return {
start: t.start,
end: t.end,
replacement: s
};
}
};
}
function redactMatch(e, t) {
const n = prepareRedactionCapture(e, t);
const r = n?.redact(n);
return r ? e.match.slice(0, r.start - e.offset) + r.replacement + e.match.slice(r.end - e.offset) : e.match;
}
function redactText(e, t, n) {
const r = startRedactionMeasurement("text");
let i = "error";
try {
let r = redactFormBody(redactAssignmentValues(redactStructuredAuthHeaders(e, "***"), "url"));
let a;
const replace = (e) => redactMatch(e, a);
const replaceRegex = (...e) => replace(readRedactMatch(e));
let o;
let s = false;
for (a of t) {
if (vendorResolvedPatterns.get(a)?.()) {
if (o !== r) {
o = r;
s = couldMatchVendorRedactPatterns(r);
}
if (!s) {
if (a instanceof RegExp) a.lastIndex = 0;
continue;
}
}
r = a instanceof RegExp && !n?.fullContext && !builtInResolvedPatterns.has(a) && !chunkUnsafePatterns.has(a) ? replacePatternBounded(r, a, replaceRegex) : replaceRedactPattern(r, a, replace, replaceRegex);
}
i = "ok";
return r;
} finally {
r?.(i, e.length, t.length);
}
}
function looksLikeAppSpecificPassword(e) {
return e.split("-").every((e) => !BENIGN_APP_PASSWORD_WORDS.has(e.toLowerCase()));
}
function redactAppSpecificPasswords(e) {
if (!e.includes("-")) return e;
return e.replace(APP_SPECIFIC_PASSWORD_RE, (e, t) => looksLikeAppSpecificPassword(t) ? maskToken(t) : e);
}
function resolveConfigRedaction() {
const e = readLoggingConfig();
return {
mode: DEFAULT_REDACT_MODE,
patterns: e?.redactPatterns
};
}
function resolveRedactOptions(e) {
const t = e ?? resolveConfigRedaction();
const n = t.mode === "off" ? "off" : DEFAULT_REDACT_MODE;
return {
mode: n,
patterns: n === "off" ? [] : resolvePatterns(t.patterns)
};
}
function redactSensitiveText(e, t) {
if (!e) return e;
return redactSensitiveTextWithOptions(redactRegisteredSecretValues(e, maskToken), t ?? resolveConfigRedaction());
}
function redactSensitiveTextWithOptions(e, t) {
if (t.mode === "off") return e;
if (usesBuiltInRedactPatterns(t.patterns) && !couldMatchDefaultRedactPatterns(e)) return e;
return redactText(e, resolveRedactOptions(t).patterns);
}
function resolveToolPayloadRedaction(e = readLoggingConfig()) {
const t = e?.redactPatterns;
return {
mode: "tools",
patterns: Array.isArray(t) && t.length > 0 ? [...t, ...DEFAULT_REDACT_PATTERNS] : t
};
}
function redactToolPayloadText(e) {
return redactToolPayloadTextWithConfig(e, readLoggingConfig());
}
function redactToolPayloadTextWithConfig(e, t) {
return redactSensitiveText(e, resolveToolPayloadRedaction(t));
}
function isSensitiveFieldKey(e) {
return STRUCTURED_SECRET_FIELD_RE.test(e) || STRUCTURED_SECRET_ENV_FIELD_RE.test(e);
}
function isPublicShareIdPath(e) {
if (e.at(-1)?.toLowerCase() !== "id") return false;
return e.at(-2)?.toLowerCase().replaceAll("-", "").replaceAll("_", "") === "publicshare";
}
function redactSensitiveFieldValueWithOptions(e, t, n, r = [e], i = true, a = couldMatchDefaultRedactPatterns) {
const o = redactRegisteredSecretValues(t, maskToken);
if (isPublicShareIdPath(r)) return maskToken(o);
const s = resolveRedactOptions(n);
if (s.mode === "off") return o;
const c = !usesBuiltInRedactPatterns(n.patterns) || a(o) ? redactText(o, s.patterns) : o;
if (c !== t || STRUCTURED_APP_PASSWORD_FIELD_RE.test(e)) {
const e = redactAppSpecificPasswords(c);
if (e !== t) return e;
}
if (c !== t) return c;
return shouldRedactStructuredStringField(e, o, r, i) ? maskToken(o) : o;
}
function shouldRedactStructuredPrimitiveField(e, t) {
const n = e.toLowerCase();
return isPublicShareIdPath(t) || shouldRedactStructuredAuthorizationCode(n, t) || isSensitiveFieldKey(e);
}
function isPlainRedactableObject(e) {
const t = Object.getPrototypeOf(e);
return t === Object.prototype || t === null;
}
function redactStructuredSecretValue(e, t, n, r, i, a = e ? [e] : [], o = true) {
if (typeof t === "string") return redactSensitiveFieldValueWithOptions(e, t, r, a, o, i);
if (t === null || t === void 0) return t;
if (typeof t === "number" || typeof t === "boolean" || typeof t === "bigint") return shouldRedactStructuredPrimitiveField(e, a) ? "***" : t;
if (Array.isArray(t)) {
if (n.has(t)) return "[Circular]";
n.add(t);
const o = t.map((t) => redactStructuredSecretValue(e, t, n, r, i, a, false));
n.delete(t);
return o;
}
if (typeof t === "object") {
if (n.has(t)) return "[Circular]";
if (!isPlainRedactableObject(t)) return t;
n.add(t);
const e = Object.entries(t);
for (const t of e) {
const [e, s] = t;
t[1] = redactStructuredSecretValue(e, s, n, r, i, [...a, e], o);
}
n.delete(t);
return Object.fromEntries(e);
}
return t;
}
function redactSecretsWithOptions(e, t) {
if (typeof e === "string") return redactSensitiveText(e, t);
if (e === null || typeof e !== "object") return e;
return redactStructuredSecretValue("", e, /* @__PURE__ */ new WeakSet(), t, createRedactPrefilter(couldMatchDefaultRedactPatterns));
}
function redactSecrets(e) {
return redactSecretsWithOptions(e, resolveToolPayloadRedaction());
}
function preservesStructuredReference(e, t) {
return e.toLowerCase() === "session" && STRUCTURED_INTERNAL_SOURCE_PATH_VALUE_RE.test(t) || isShellReferenceToKey(e, t);
}
function shouldRedactStructuredStringField(e, t, n, r) {
return shouldRedactStructuredAuthorizationCode(e.toLowerCase(), n, r ? t : void 0) || isSensitiveFieldKey(e) && !preservesStructuredReference(e, t);
}
function classifyLogFieldProtection(e, t, n, r) {
return (r === void 0 ? shouldRedactStructuredPrimitiveField(e, t) : isPublicShareIdPath(t) || shouldRedactStructuredStringField(e, r, t, n)) ? "legacy" : backendPatterns.credentialHeaderField.test(e) ? "header" : void 0;
}
function getFieldRecordEdits(e, t) {
const { key: n, value: r, path: i, objectPath: a } = e;
if (t === "off" || !e.string && r === "null" || !classifyLogFieldProtection(n, i, a, e.string ? r : void 0)) return [];
return [{
start: 0,
end: r.length,
replacement: maskSecretFieldValue(n, r)
}];
}
function getTextRecordEdits(e, t, n) {
const { value: r } = e;
if (e.isKey || n && !e.origin.structured) return [];
if (n && e.origin.primitiveMask) return [{
start: 0,
end: r.length,
replacement: "***"
}];
if (!e.string) return [];
const i = [];
const a = redactRegisteredSecretValues(r, (e, t) => {
const n = maskToken(e);
i.push({
start: t,
end: t + e.length,
replacement: n
});
return n;
});
if (n && isPublicShareIdPath(e.path)) return [{
start: 0,
end: r.length,
replacement: maskToken(a)
}];
if (t === "off") return i;
let o = i;
const receive = (e) => {
o = composeRedactionEdits(r.length, o, e);
};
const s = findStructuredAuthParamRanges(a).map(({ start: e, end: t }) => ({
start: e,
end: t,
replacement: "***"
}));
receive(s);
redactFormBody(redactAssignmentValues(applyRedactionEdits(a, s), "url", receive), receive);
return o;
}
function getLegacyFieldRecordEdits(e, t) {
const { key: n, value: r, path: i, objectPath: a } = e;
if (e.isKey || !e.origin.structured || !e.string) return [];
if (isPublicShareIdPath(i)) return [];
const o = [];
if (t !== r || STRUCTURED_APP_PASSWORD_FIELD_RE.test(n)) {
for (const e of t.matchAll(APP_SPECIFIC_PASSWORD_RE)) if (looksLikeAppSpecificPassword(e[0])) o.push({
start: e.index,
end: e.index + e[0].length,
replacement: maskToken(e[0])
});
}
if (o.length > 0 || t !== r) return o;
return classifyLogFieldProtection(n, i, a, t) === "legacy" ? [{
start: 0,
end: t.length,
replacement: maskToken(t)
}] : [];
}
function* redactionEditMatches(e, t) {
for (const n of t) yield {
match: e.slice(n.start, n.end),
groups: [],
input: e,
offset: n.start,
replacement: n.replacement
};
}
const preparationPatterns = [
{
source: "registered secret values",
*exec(e) {
const t = [];
redactRegisteredSecretValues(e, (n, r) => {
t.push({
match: n,
groups: [],
input: e,
offset: r,
replacement: maskToken(n)
});
return n;
});
yield* t;
}
},
{
source: "structured authorization parameters",
*exec(e) {
for (const { start: t, end: n } of findStructuredAuthParamRanges(e)) yield {
match: e.slice(t, n),
groups: [],
input: e,
offset: t,
replacement: "***"
};
}
},
{
source: "URL query assignments",
*exec(e) {
const t = [];
redactAssignmentValues(e, "url", (e) => t.push(...e));
yield* redactionEditMatches(e, t);
}
},
{
source: "form bodies",
*exec(e) {
let t = [];
redactFormBody(e, (n) => {
t = composeRedactionEdits(e.length, t, n);
});
yield* redactionEditMatches(e, t);
}
}
];
const CONSOLE_STRUCTURAL_FIELDS = /* @__PURE__ */ new Set(["time", "level"]);
/** Converts native values once and applies configured and structural protection before output. */
function redactLogRecordForTransport(e, t) {
const n = startRedactionMeasurement("log-record");
let r = "error";
let i;
try {
const n = t?.redaction ?? resolveRedactOptions();
const a = {
value: {
structured: true,
primitiveMask: false
},
children: /* @__PURE__ */ new Map()
};
const o = [];
const s = JSON.stringify(e, function(e, t) {
while (o.length > 0 && o.at(-1)?.value !== this) o.pop();
const n = o.at(-1);
const r = Array.isArray(this);
const i = r && n ? n.key : e;
const s = r && n ? n.path : n ? [...n.path, e] : [];
const c = t;
const l = (n?.structured ?? true) && (c === null || typeof c !== "object" || Array.isArray(c) || isPlainRedactableObject(c));
const u = l && [
"number",
"boolean",
"bigint"
].includes(typeof c) && classifyLogFieldProtection(i, s, !r, void 0) === "legacy";
const d = t !== null && typeof t === "object" && o.some((e) => e.value === t);
const f = d ? "[Circular]" : typeof t === "bigint" ? String(t) : t;
const p = f !== null && typeof f === "object";
let m = a;
if (n && n.structured && (p || !l || u || d)) {
m = {
value: {
structured: l && !d,
primitiveMask: u
},
children: /* @__PURE__ */ new Map()
};
n.origins.children.set(e, m);
} else if (n) m = n.origins;
else a.value = {
structured: l,
primitiveMask: u
};
if (p) o.push({
value: f,
path: s,
key: i,
origins: m,
structured: l
});
return f;
});
i = s.length;
const c = createRedactPrefilter(couldMatchDefaultFullContextPatterns);
const l = JSON.parse(redactJsonRecord(s, a, [[{ patterns: n.patterns }], [{ patterns: preparationPatterns }, {
patterns: n.patterns,
...n.patterns === defaultResolvedPatterns ? { couldMatch: c } : {}
}]], prepareRedactionCapture, t ? getLegacyFieldRecordEdits : () => [], (e) => getFieldRecordEdits(e, n.mode), (e) => getTextRecordEdits(e, n.mode, t !== void 0), (e, t) => e.path.length === 1 && CONSOLE_STRUCTURAL_FIELDS.has(e.key) || n.patterns === defaultResolvedPatterns && !c(t), t?.message));
r = "ok";
return l;
} finally {
n?.(r, i);
}
}
//#endregion
//#region src/logging/timestamps.ts
const validTimeZoneCache = /* @__PURE__ */ new Map();
const timestampFormatterCache = /* @__PURE__ */ new Map();
let hostTimeZone;
let lastTimestampParts;
function isValidTimeZone(e) {
const t = validTimeZoneCache.get(e);
if (t !== void 0) return t;
let n;
try {
new Intl.DateTimeFormat("en", { timeZone: e }).format();
n = true;
} catch {
n = false;
}
validTimeZoneCache.set(e, n);
return n;
}
function resolveEffectiveTimeZone(e) {
const t = e ?? process.env.TZ;
return t && isValidTimeZone(t) ? t : hostTimeZone ??= Intl.DateTimeFormat().resolvedOptions().timeZone;
}
function getTimestampParts(e, t) {
const n = resolveEffectiveTimeZone(t);
const r = Math.floor(e.getTime() / 1e3);
if (lastTimestampParts?.second === r && lastTimestampParts.timeZone === n) return lastTimestampParts.parts;
let i = timestampFormatterCache.get(n);
if (!i) {
i = new Intl.DateTimeFormat("en", {
timeZone: n,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
fractionalSecondDigits: 3,
timeZoneName: "longOffset"
});
timestampFormatterCache.set(n, i);
}
const a = {};
for (const t of i.formatToParts(e)) a[t.type] = t.value;
lastTimestampParts = {
second: r,
timeZone: n,
parts: a
};
return a;
}
function formatTimestamp(e, t) {
const n = t?.style ?? "medium";
const r = getTimestampParts(e, t?.timeZone);
const i = r.timeZoneName ?? "GMT";
const a = i === "GMT" ? "+00:00" : i.slice(3);
const o = String(e.getUTCMilliseconds()).padStart(3, "0");
switch (n) {
case "short": return `${r.hour}:${r.minute}:${r.second}${a}`;
case "medium": return `${r.hour}:${r.minute}:${r.second}.${o}${a}`;
case "long": return `${r.year}-${r.month}-${r.day}T${r.hour}:${r.minute}:${r.second}.${o}${a}`;
}
throw new Error("Unsupported timestamp style");
}
//#endregion
//#region src/logging/json-console-line.ts
function formatJsonConsoleLine(e) {
const t = {
...e.meta,
time: formatTimestamp(/* @__PURE__ */ new Date(), { style: "long" }),
level: e.level,
...e.subsystem ? { subsystem: e.subsystem } : {},
message: e.message
};
return JSON.stringify(redactLogRecordForTransport(t));
}
/** Formats diagnostics that must bypass console capture without bypassing JSON console style. */
function formatConsoleDiagnosticLine(e) {
return (loggingState.overrideSettings?.consoleStyle ?? readLoggingConfig()?.consoleStyle) === "json" ? formatJsonConsoleLine(e) : e.message;
}
//#endregion
//#region src/logging/levels.ts
const ALLOWED_LOG_LEVELS = [
"silent",
"fatal",
"error",
"warn",
"info",
"debug",
"trace"
];
const MIN_LEVEL_BY_LOG_LEVEL = {
trace: 1,
debug: 2,
info: 3,
warn: 4,
error: 5,
fatal: 6,
silent: Number.POSITIVE_INFINITY
};
function tryParseLogLevel(e) {
if (typeof e !== "string") return;
const t = e.trim();
return ALLOWED_LOG_LEVELS.includes(t) ? t : void 0;
}
function normalizeLogLevel(e, t = "info") {
return tryParseLogLevel(e) ?? t;
}
function levelToMinLevel(e) {
return MIN_LEVEL_BY_LOG_LEVEL[e];
}
function isLogLevelEnabled(e, t) {
return e !== "silent" && t !== "silent" && levelToMinLevel(e) >= levelToMinLevel(t);
}
//#endregion
//#region src/logging/env-log-level.ts
/** Resolves OPENCLAW_LOG_LEVEL once per value, warning only when the invalid value changes. */
function resolveEnvLogLevelOverride() {
const e = normalizeOptionalString(process.env.OPENCLAW_LOG_LEVEL) ?? "";
if (!e) {
loggingState.invalidEnvLogLevelValue = null;
return;
}
const t = tryParseLogLevel(e);
if (t) {
loggingState.invalidEnvLogLevelValue = null;
return t;
}
if (loggingState.invalidEnvLogLevelValue !== e) {
loggingState.invalidEnvLogLevelValue = e;
const t = `[openclaw] Ignoring invalid OPENCLAW_LOG_LEVEL="${redactToolPayloadText(e)}" (allowed: ${ALLOWED_LOG_LEVELS.join("|")}).`;
process.stderr.write(`${formatConsoleDiagnosticLine({
level: "warn",
message: t
})}\n`);
}
}
//#endregion
//#region src/logging/log-directory.ts
/**
* Creates a log directory and its missing parents with a bounded number of mkdir calls.
* Node's recursive mkdirSync retries forever when a parent exists but refuses new
* children (a deleted directory that is still mounted, such as a stale systemd
* PrivateTmp), which would block the event loop inside the logger.
*/
function ensureLogDirectorySync(e, t = true, n = 511) {
try {
fs.mkdirSync(e, { mode: n });
} catch (r) {
const i = extractErrorCode(r);
if (i === "EEXIST" && fs.statSync(e).isDirectory()) return;
const a = path.dirname(e);
if (!t || i !== "ENOENT" || a === e) throw r;
ensureLogDirectorySync(a, true, n);
ensureLogDirectorySync(e, false, n);
}
}
//#endregion
//#region src/logging/log-file-shared.ts
const LOG_PREFIX = "openclaw";
const LOG_SUFFIX = ".log";
function canUseNodeFs() {
try {
return process.getBuiltinModule?.("fs") !== void 0;
} catch {
return false;
}
}
function formatLocalDate(e) {
return `${e.getFullYear()}-${String(e.getMonth() + 1).padStart(2, "0")}-${String(e.getDate()).padStart(2, "0")}`;
}
//#endregion
//#region src/logging/log-file-path.ts
const ROLLING_LOG_FILE_RE = /^(openclaw(?:-[a-z0-9-]+)?)-(\d{4}-\d{2}-\d{2})\.log$/u;
const MAX_LOG_PROFILE_SEGMENT_LENGTH = 220;
function encodeLogProfileSegment(e) {
let t = "";
for (const n of e) if (/^[a-z0-9]$/u.test(n)) t += n;
else if (n === "-") t += "--";
else if (n === "_") t += "-0";
else if (/^[A-Z]$/u.test(n)) t += `-1${n.toLowerCase()}`;
else t += `-2${n.codePointAt(0)?.toString(16) ?? "0"}-`;
return t;
}
function resolveLogProfileSegment() {
const e = process.env.OPENCLAW_PROFILE?.trim();
if (!e || e.toLowerCase() === "default") return null;
const t = encodeLogProfileSegment(e);
if (t.length <= MAX_LOG_PROFILE_SEGMENT_LENGTH) return t;
return `-3${createHash("sha256").update(e).digest("hex")}`;
}
/** Resolves today's default rolling log path for the active CLI profile. */
function resolveDefaultRollingLogFile(e) {
const t = /* @__PURE__ */ new Date();
let n = DEFAULT_POSIX_TMP_ROOT;
if (canUseNodeFs()) {
const t = resolveStateDir();
n = path.join(t, "logs");
if (e?.prepare !== false) {
ensureLogDirectorySync(t, true, 448);
n = resolvePreferredOpenClawTmpDir({
preferredDir: n,
tmpdir: () => path.join(t, "tmp")
});
}
}
const r = resolveLogProfileSegment();
const i = r ? `-${r}` : "";
return path.join(n, `${LOG_PREFIX}${i}-${formatLocalDate(t)}${LOG_SUFFIX}`);
}
/** Returns whether a configured path had the legacy default rolling filename shape. */
function isLegacyRollingLogFilePath(e) {
const t = path.basename(e);
return t === `${"openclaw"}-YYYY-MM-DD${".log"}` || ROLLING_LOG_FILE_RE.exec(t)?.[1] === "openclaw";
}
/** Advances a rolling log path to the requested date while preserving its profile family. */
function resolveRollingLogFilePathForDate(e, t) {
const n = ROLLING_LOG_FILE_RE.exec(path.basename(e));
if (!n) return isLegacyRollingLogFilePath(e) ? path.join(path.dirname(e), `${LOG_PREFIX}-${formatLocalDate(t)}${LOG_SUFFIX}`) : e;
return path.join(path.dirname(e), `${n[1]}-${formatLocalDate(t)}${LOG_SUFFIX}`);
}
//#endregion
//#region src/logging/logger-file-transport.ts
const DEFAULT_MAX_QUEUED_RECORDS = 4096;
const MAX_APPEND_BATCH_BYTES = 65536;
const MAX_ROTATED_LOG_FILES = 5;
const MAX_TRACKED_APPEND_FAILURE_FILES = 64;
let queue = [];
let queueStart = 0;
let activeBatch = null;
let activeIndex = 0;
let droppedCount = 0;
let droppedTarget = null;
let scheduledFlush = null;
let flushPromise = null;
let processExiting = false;
let processHooksInstalled = false;
const warnedRotationFiles = /* @__PURE__ */ new Map();
const warnedAppendFiles = /* @__PURE__ */ new Set();
let appendFailureTrackingSaturated = false;
function rotatedLogPath(e, t) {
const n = path.extname(e);
return `${e.slice(0, e.length - n.length)}.${t}${n}`;
}
function rotateLogFile(e) {
try {
ensureLogDirectorySync(path.dirname(e));
fs.rmSync(rotatedLogPath(e, MAX_ROTATED_LOG_FILES), { force: true });
for (let t = 4; t >= 1; t -= 1) {
const n = rotatedLogPath(e, t);
if (fs.existsSync(n)) fs.renameSync(n, rotatedLogPath(e, t + 1));
}
if (fs.existsSync(e)) fs.renameSync(e, rotatedLogPath(e, 1));
return true;
} catch {
return false;
}
}
async function getCurrentLogFileBytes(e) {
try {
return (await fsPromises.stat(e)).size;
} catch {
return 0;
}
}
function getCurrentLogFileBytesSync(e) {
try {
return fs.statSync(e).size;
} catch {
return 0;
}
}
function buildDroppedMarker(e, t) {
const n = /* @__PURE__ */ new Date();
const r = `[openclaw] file log queue overflow; dropped ${t} oldest record${t === 1 ? "" : "s"}`;
const i = {
0: r,
_meta: {
date: n,
hostname: e.hostname,
logLevelName: "WARN",
name: "openclaw"
},
time: formatTimestamp(n, { style: "long" }),
hostname: e.hostname,
message: r,
dropped: t
};
return {
...e,
payload: `${JSON.stringify(i)}\n`
};
}
function writeFileTransportWarning(e, t) {
try {
const n = redactSensitiveText(e);
const r = `${formatConsoleDiagnosticLine({
level: "warn",
message: n
})}\n`;
if (t) fs.writeSync(process.stderr.fd, r);
else process.stderr.write(r);
return true;
} catch {
return false;
}
}
function warnAboutRotationFailure(e, t) {
if (warnedRotationFiles.get(e.file) === e.maxFileBytes) return;
warnedRotationFiles.set(e.file, e.maxFileBytes);
writeFileTransportWarning(`[openclaw] log file rotation failed; continuing writes file=${e.file} maxFileBytes=${e.maxFileBytes}`, t);
}
function warnAboutAppendFailure(e, t) {
if (warnedAppendFiles.has(e.file)) return;
const n = warnedAppendFiles.size >= MAX_TRACKED_APPEND_FAILURE_FILES;
if (n && appendFailureTrackingSaturated) return;
if (!writeFileTransportWarning(n ? "[openclaw] log file append failure diagnostics saturated; suppressing new file targets" : `[openclaw] log file append failed; records dropped; check that the path is a writable regular file; file=${e.file}`, t)) return;
if (n) appendFailureTrackingSaturated = true;
else warnedAppendFiles.add(e.file);
}
function clearAppendFailure(e) {
if (warnedAppendFiles.delete(e.file)) appendFailureTrackingSaturated = false;
}
function claimQueuedEntries() {
const e = queueStart === 0 ? queue : [...queue.slice(queueStart), ...queue.slice(0, queueStart)];
queue = [];
queueStart = 0;
if (droppedCount > 0 && droppedTarget) e.unshift(buildDroppedMarker(droppedTarget, droppedCount));
droppedCount = 0;
droppedTarget = null;
return e;
}
function prepareWrite(e, t, n, r, i) {
let a = Buffer.byteLength(e.payload, "utf8");
if (t.bytes > 0 && t.bytes + a > e.maxFileBytes) {
if (rotateLogFile(e.file)) {
t.bytes = 0;
warnedRotationFiles.delete(e.file);
} else warnAboutRotationFailure(e, n);
}
let o = i + 1;
if (n) return {
payload: e.payload,
payloadBytes: a,
nextIndex: o
};
const s = [e.payload];
for (; o < r.length; o += 1) {
const n = r[o];
if (!n || n.file !== e.file || n.maxFileBytes !== e.maxFileBytes) break;
const i = Buffer.byteLength(n.payload, "utf8");
if (a + i > MAX_APPEND_BATCH_BYTES || t.bytes + a + i > e.maxFileBytes) break;
s.push(n.payload);
a += i;
}
return {
payload: s.join(""),
payloadBytes: a,
nextIndex: o
};
}
async function writeEntries(e) {
const t = /* @__PURE__ */ new Map();
for (let n = 0; n < e.length;) {
if (processExiting) return;
const r = e[n];
if (!r) return;
let i = t.get(r.file);
if (!i) {
i = { bytes: await getCurrentLogFileBytes(r.file) };
if (processExiting) return;
t.set(r.file, i);
}
const a = prepareWrite(r, i, false, e, n);
activeIndex = a.nextIndex;
try {
await appendRegularFile({
filePath: r.file,
content: a.payload
});
i.bytes += a.payloadBytes;
clearAppendFailure(r);
} catch {
warnAboutAppendFailure(r, false);
} finally {
for (const t of e.slice(n, a.nextIndex)) t.payload = "";
n = a.nextIndex;
}
}
}
function writeEntriesSync(e) {
const t = /* @__PURE__ */ new Map();
for (let n = 0; n < e.length;) {
const r = e[n];
if (!r) return;
let i = t.get(r.file);
if (!i) {
i = { bytes: getCurrentLogFileBytesSync(r.file) };
t.set(r.file, i);
}
const a = prepareWrite(r, i, true, e, n);
try {
appendRegularFileSync({
filePath: r.file,
content: a.payload
});
i.bytes += a.payloadBytes;
clearAppendFailure(r);
} catch {
warnAboutAppendFailure(r, true);
}
r.payload = "";
n = a.nextIndex;
}
}
async function runFlushLoop() {
for (;;) {
if (processExiting) return;
const e = claimQueuedEntries();
if (e.length === 0) return;
activeBatch = e;
activeIndex = 0;
await writeEntries(e);
activeBatch = null;
activeIndex = 0;
}
}
function startFlush() {
if (flushPromise || processExiting) return;
const e = runFlushLoop().catch(() => void 0);
flushPromise = e;
e.then(() => {
flushPromise = null;
if (queue.length > 0 || droppedCount > 0) scheduleFlush();
});
}
function scheduleFlush() {
if (scheduledFlush || flushPromise || processExiting) return;
scheduledFlush = setImmediate(() => {
scheduledFlush = null;
startFlush();
});
}
function handleProcessBeforeExit() {
flushFileLogQueue();
}
function handleProcessExit() {
processExiting = true;
drainFileLogQueueSync();
}
function installProcessHooks() {
if (processHooksInstalled) return;
processHooksInstalled = true;
process.on("beforeExit", handleProcessBeforeExit);
process.on("exit", handleProcessExit);
}
/** Enqueues one serialized record without waiting for filesystem I/O. */
function enqueueFileLog(e) {
if (processExiting) {
writeEntriesSync([e]);
return;
}
installProcessHooks();
if (queue.length >= DEFAULT_MAX_QUEUED_RECORDS) {
const t = queue[queueStart];
if (t) {
t.payload = "";
droppedTarget ??= t;
droppedCount += 1;
}
queue[queueStart] = e;
queueStart = (queueStart + 1) % queue.length;
} else queue.push(e);
scheduleFlush();
}
/** Waits until every record currently queued for the async transport has settled. */
async function flushFileLogQueue() {
for (;;) {
if (scheduledFlush) {
clearImmediate(scheduledFlush);
scheduledFlush = null;
}
if (!flushPromise && (queue.length > 0 || droppedCount > 0)) startFlush();
const e = flushPromise;
if (!e) return;
await e;
}
}
/** Synchronously rescues pending records for process.exit() and crash-adjacent paths. */
function drainFileLogQueueSync() {
if (scheduledFlush) {
clearImmediate(scheduledFlush);
scheduledFlush = null;
}
const e = activeBatch ? activeBatch.slice(activeIndex) : [];
activeBatch = null;
activeIndex = 0;
e.push(...claimQueuedEntries());
writeEntriesSync(e);
}
const fileLogTransport = resolveGlobalSingleton(Symbol.for("openclaw.fileLogTransport"), () => {
if (process.env.VITEST !== "true") installProcessHooks();
return {
drainSync: drainFileLogQueueSync,
enqueue: enqueueFileLog,
flush: flushFileLogQueue
};
});
//#endregion
//#region src/logging/logger.ts
const DEFAULT_LOG_FILE = `${DEFAULT_POSIX_TMP_ROOT}/openclaw.log`;
const MAX_LOG_AGE_MS = 864e5;
const DEFAULT_MAX_LOG_FILE_BYTES = 104857600;
let cachedHostname = null;
const MAX_DIAGNOSTIC_LOG_BINDINGS_JSON_CHARS = 8192;
const MAX_DIAGNOSTIC_LOG_MESSAGE_CHARS = 4096;
const MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT = 32;
const MAX_DIAGNOSTIC_LOG_ATTRIBUTE_VALUE_CHARS = 2048;
const MAX_DIAGNOSTIC_LOG_NAME_CHARS = 120;
const MAX_FILE_LOG_CONTEXT_VALUE_CHARS = 512;
const DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE = /^[A-Za-z0-9_.:-]{1,64}$/u;
function clampLogText(e, t) {
return e.length > t ? `${truncateUtf16Safe(e, t)}...(truncated)` : e;
}
function sanitizeDiagnosticLogText(e, t) {
return clampLogText(redactSensitiveText(clampLogText(e, t)), t);
}
function normalizeDiagnosticLogName(e) {
if (!e || e.trim().startsWith("{")) return;
const t = sanitizeDiagnosticLogText(e.trim(), MAX_DIAGNOSTIC_LOG_NAME_CHARS);
return DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE.test(t) ? t : void 0;
}
function assignDiagnosticLogAttribute(e, t, n, r) {
if (t.count >= MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT) return;
const i = n.trim();
if (isBlockedObjectKey(i)) return;
if (redactSensitiveText(i) !== i) return;
if (!DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE.test(i)) return;
let a;
if (typeof r === "string") a = sanitizeDiagnosticLogText(r, MAX_DIAGNOSTIC_LOG_ATTRIBUTE_VALUE_CHARS);
else if (typeof r === "boolean" || typeof r === "number" && Number.isFinite(r)) a = r;
else return;
e[i] = a;
t.count += 1;
}
function addDiagnosticLogAttributesFrom(e, t, n) {
if (!n) return;
for (const r in n) {
if (t.count >= MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT) break;
if (!Object.hasOwn(n, r) || r === "trace") continue;
assignDiagnosticLogAttribute(e, t, r, n[r]);
}
}
function isPlainLogRecordObject(e) {
if (!isRecord(e)) return false;
const t = Object.getPrototypeOf(e);
return t === Object.prototype || t === null;
}
function normalizeTraceContext(e) {
const t = asOptionalRecord(e);
if (!t || !isValidDiagnosticTraceId(t.traceId)) return;
if (t.spanId !== void 0 && !isValidDiagnosticSpanId(t.spanId)) return;
if (t.parentSpanId !== void 0 && !isValidDiagnosticSpanId(t.parentSpanId)) return;
if (t.traceFlags !== void 0 && !isValidDiagnosticTraceFlags(t.traceFlags)) return;
return {
traceId: t.traceId,
...t.spanId ? { spanId: t.spanId } : {},
...t.parentSpanId ? { parentSpanId: t.parentSpanId } : {},
...t.traceFlags ? { traceFlags: t.traceFlags } : {}
};
}
function extractTraceContext(e) {
return normalizeTraceContext(e) ?? normalizeTraceContext(asOptionalRecord(e)?.trace);
}
function getSortedNumericLogEntries(e) {
return Object.entries(e).filter(([e]) => /^\d+$/.test(e)).toSorted((e, t) => Number(e[0]) - Number(t[0]));
}
function normalizeFileLogContextValue(e) {
if (typeof e === "string") {
const t = e.trim();
return t ? clampLogText(t, MAX_FILE_LOG_CONTEXT_VALUE_CHARS) : void 0;
}
if (typeof e === "boolean" || typeof e === "number" && Number.isFinite(e)) return String(e);
}
function readFirstContextString(e, t) {
for (const n of e) {
const e = n ? readParsedField(n, t, normalizeFileLogContextValue) : void 0;
if (e) return e;
}
}
function resolveLogHostname() {
if (cachedHostname) return cachedHostname;
const e = os.hostname().trim();
if (!e) return "unknown";
cachedHostname = e;
return e;
}
function withResolvedLogMetaHostname(e, t) {
return isRecord(e) ? {
...e,
hostname: t
} : e;
}
function extractLogBindingPrefix(e) {
if (typeof e[0] === "string" && e[0].length <= MAX_DIAGNOSTIC_LOG_BINDINGS_JSON_CHARS && e[0].trim().startsWith("{")) try {
const t = JSON.parse(e[0]);
if (isRecord(t)) return {
bindings: t,
args: e.slice(1)
};
} catch {}
return { args: e };
}
function resolveLogTraceContext(e, t) {
for (const n of [e, ...t]) {
const e = extractTraceContext(n);
if (e) return {
trace: e,
trustedTraceContext: false
};
}
const n = getActiveDiagnosticTraceContext();
return n ? {
trace: n,
trustedTraceContext: true
} : { trustedTraceContext: false };
}
function prepareFileLogRecord(e) {
const t = getSortedNumericLogEntries(e);
const { bindings: n, args: r } = extractLogBindingPrefix(t.map(([, e]) => e));
const { trace: i } = resolveLogTraceContext(n, r);
const a = isPlainLogRecordObject(r[0]) ? r[0] : void 0;
const o = [
a,
n,
e
];
const s = a && typeof a.message !== "string" ? 1 : 0;
const c = t.slice(t.length - r.length + s).map(([e, t]) => {
const n = {
key: e,
json: t != null && ![
"string",
"number",
"boolean",
"bigint"
].includes(typeof t) && !(t instanceof Error) && !(isPlainLogRecordObject(t) && typeof t.message === "string")
};
if (typeof t === "number" && !Number.isFinite(t)) n.primitiveText = String(t);
return n;
});
const l = readFirstContextString(o, ["agent_id", "agentId"]);
const u = readFirstContextString(o, [
"session_id",
"sessionId",
"sessionKey"
]);
const d = readFirstContextString(o, ["channel", "messageProvider"]);
return {
fields: {
hostname: resolveLogHostname(),
...l ? { agent_id: l } : {},
...u ? { session_id: u } : {},
...d ? { channel: d } : {},
...i
},
messageParts: c
};
}
function buildDiagnosticLogRecord(e) {
const t = e["_meta"];
const { bindings: n, args: r } = extractLogBindingPrefix(getSortedNumericLogEntries(e).map(([, e]) => e));
const { trace: i, trustedTraceContext: a } = resolveLogTraceContext(n, r);
const o = r[0];
const s = isPlainLogRecordObject(o) ? o : void 0;
if (s) r.shift();
let c = "";
if (r.length > 0 && typeof r[r.length - 1] === "string") c = sanitizeDiagnosticLogText(String(r.pop()), MAX_DIAGNOSTIC_LOG_MESSAGE_CHARS);
else if (r.length === 1 && (typeof r[0] === "number" || typeof r[0] === "boolean")) {
c = String(r[0]);
r.length = 0;
}
if (!c) c = "log";
const l = Object.create(null);
const u = { count: 0 };
addDiagnosticLogAttributesFrom(l, u, n);
addDiagnosticLogAttributesFrom(l, u, s);
const d = {};
if (t?.path?.fileLine) {
const e = Number(t.path.fileLine);
if (Number.isFinite(e)) d.line = e;
}
if (t?.path?.method) d.functionName = sanitizeDiagnosticLogText(t.path.method, MAX_DIAGNOSTIC_LOG_NAME_CHARS);
const f = normalizeDiagnosticLogName(t?.name);
const p = t?.parentNames?.map(normalizeDiagnosticLogName).filter((e) => Boolean(e));
return {
event: {
type: "log.record",
level: t?.logLevelName ?? "INFO",
message: c,
...f ? { loggerName: f } : {},
...p?.length ? { loggerParents: p } : {},
...Object.keys(l).length > 0 ? { attributes: l } : {},
...Object.keys(d).length > 0 ? { code: d } : {},
...i ? { trace: i } : {}
},
trustedTraceContext: a
};
}
function attachDiagnosticEventTransport(e) {
e.attachTransport({
format: () => "",
write: (e) => {
if (!areDiagnosticsEnabledForProcess() || !hasInternalDiagnosticEventInterest("log.record")) return;
try {
const t = buildDiagnosticLogRecord(redactSecrets(e));
(t.trustedTraceContext ? emitDiagnosticEventWithTrustedTraceContext : emitDiagnosticEvent)(t.event);
} catch {}
}
});
}
function canUseSilentVitestFileLogFastPath(e) {
return process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG !== "1" && !e && !loggingState.overrideSettings;
}
function resolveDefaultActiveLogFile(e = false) {
if (process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG === "1") return path.join(process.cwd(), ".artifacts", "test-logs", `${LOG_PREFIX}-vitest-${process.pid}-${formatLocalDate(/* @__PURE__ */ new Date())}${LOG_SUFFIX}`);
return resolveDefaultRollingLogFile(e ? void 0 : { prepare: false });
}
function resolveSettings(e = false) {
if (!canUseNodeFs()) return {
level: "silent",
file: DEFAULT_LOG_FILE,
maxFileBytes: DEFAULT_MAX_LOG_FILE_BYTES,
rolling: false,
defaultFile: false
};
const t = resolveEnvLogLevelOverride();
if (canUseSilentVitestFileLogFastPath(t)) return {
level: "silent",
file: resolveDefaultRollingLogFile(e ? void 0 : { prepare: false }),
maxFileBytes: DEFAULT_MAX_LOG_FILE_BYTES,
rolling: true,
defaultFile: true
};
const n = loggingState.overrideSettings ?? readLoggingConfig();
const r = process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG !== "1" ? "silent" : "info";
const i = normalizeLogLevel(n?.level, r);
const a = t ?? i;
const o = n?.file ? isLegacyRollingLogFilePath(n.file) : true;
return {
level: a,
file: resolveActiveLogFileWithMode(n?.file ?? resolveDefaultActiveLogFile(e), o),
maxFileBytes: resolveMaxLogFileBytes(n?.maxFileBytes),
rolling: o,
defaultFile: !n?.file
};
}
function getRuntimeSettings() {
const e = loggingState.cachedSettings ?? resolveSettings();
loggingState.cachedSettings = e;
return e;
}
function isFileLogLevelEnabled(e) {
return isLogLevelEnabled(e, getRuntimeSettings().level);
}
function inheritLogLevel(e, t) {
let resolveLevel = t;
Object.defineProperty(e.settings, "minLevel", {
configurable: true,
enumerable: true,
get: () => resolveLevel(),
set: (e) => {
resolveLevel = () => e;
}
});
}
var RuntimeLogger = class extends Logger {
getSubLogger(e, t) {
const n = e?.minLevel ?? this.settings.minLevel;
const r = super.getSubLogger({
...e,
minLevel: n === Infinity ? levelToMinLevel("fatal") : n
}, t);
if (e?.minLevel == null) inheritLogLevel(r, () => this.settings.minLevel);
else if (n === Infinity) r.settings.minLevel = n;
return r;
}
};
function buildLogger() {
const e = new RuntimeLogger({
name: "openclaw",
mask: { keys: [] },
meta: { property: "_meta" },
minLevel: levelToMinLevel("fatal"),
type: "hidden"
});
inheritLogLevel(e, () => levelToMinLevel(getRuntimeSettings().level));
let t;
let n;
e.attachTransport({
format: () => "",
write: (e) => {
try {
const r = getRuntimeSettings();
if (r.level === "silent") return;
if (n?.settings !== r) n = {
settings: r,
file: r.defaultFile ? resolveDefaultActiveLogFile(true) : r.file
};
const i = resolveActiveLogFileWithMode(n.file, r.rolling);
if (i !== t) {
t = i;
try {
ensureLogDirectorySync(path.dirname(t));
if (r.rolling) pruneOldRollingLogs(path.dirname(t));
} catch {}
}
const a = formatTimestamp(e.date ?? /* @__PURE__ */ new Date(), { style: "long" });
const { fields: o, messageParts: s } = prepareFileLogRecord(e);
const c = serializeFileLogRecord({
...e,
_meta: withResolvedLogMetaHostname(e["_meta"], o.hostname),
time: a,
...o
}, s);
fileLogTransport.enqueue({
file: t,
hostname: o.hostname,
maxFileBytes: r.maxFileBytes,
payload: `${c}\n`
});
} catch {}
}
});
attachDiagnosticEventTransport(e);
return e;
}
function resolveMaxLogFileBytes(e) {
if (typeof e === "number" && Number.isFinite(e) && e > 0) return Math.floor(e);
return DEFAULT_MAX_LOG_FILE_BYTES;
}
function getLogger() {
const e = loggingState.cachedLogger;
if (e) return e;
getRuntimeSettings();
const t = buildLogger();
loggingState.cachedLogger = t;
return t;
}
function getChildLogger(e, t) {
const n = getLogger();
const r = e ? JSON.stringify(e) : void 0;
return n.getSubLogger({
name: r,
prefix: e ? [r ?? ""] : [],
...t?.level ? { minLevel: levelToMinLevel(t.level) } : {}
});
}
function resolveActiveLogFileWithMode(e, t) {
const n = expandHomePrefix(e);
return t ? resolveRollingLogFilePathForDate(n, /* @__PURE__ */ new Date()) : n;
}
function pruneOldRollingLogs(e) {
try {
const t = fs.readdirSync(e, { withFileTypes: true });
const n = Date.now() - MAX_LOG_AGE_MS;
for (const r of t) {
if (!r.isFile()) continue;
if (!r.name.startsWith(`${"openclaw"}-`) || !r.name.endsWith(".log")) continue;
const t = path.join(e, r.name);
try {
if (fs.statSync(t).mtimeMs < n) fs.rmSync(t, { force: true });
} catch {}
}
} catch {}
}
//#endregion
//#region packages/terminal-core/src/progress-line.ts
let activeStream = null;
/** Clear the active progress line when it is attached to a TTY stream. */
function clearActiveProgressLine() {
if (!activeStream?.isTTY) return;
activeStream.write("\r\x1B[2K");
}
//#endregion
//#region src/cli/signal-exit-barrier.ts
const processExitOwner = resolveGlobalSingleton(Symbol.for("openclaw.signalExitOwner"), () => ({}));
const activeBarriers = resolveGlobalSet(Symbol.for("openclaw.signalExitBarriers"), "close-and-restart");
const activeGates = resolveGlobalSet(Symbol.for("openclaw.signalExitGates"), "close-and-restart");
const activeFinalizers = resolveGlobalSet(Symbol.for("openclaw.signalExitFinalizers"), "close-and-restart");
const signalObservers = resolveGlobalSet(Symbol.for("openclaw.signalExitObservers"), "close-and-restart");
/** Temporary artifacts remain available until other shutdown owners have drained. */
function registerSignalExitFinalizer(e) {
activeFinalizers.add(e);
return () => activeFinalizers.delete(e);
}
const gatewayStartupSignals = resolveGlobalSingleton(Symbol.for("openclaw.gatewayStartupSignals"), () => ({}));
//#endregion
//#region src/logging/console.ts
function normalizeConsoleLevel(e) {
if (isVerbose()) return "debug";
if (!e && process.env.VITEST === "true" && process.env.OPENCLAW_TEST_CONSOLE !== "1") return "silent";
return normalizeLogLevel(e, "info");
}
function normalizeConsoleStyle(e) {
if (e === "compact" || e === "json" || e === "pretty") return e;
if (!process.stdout.isTTY) return "compact";
return "pretty";
}
function resolveConsoleSettings() {
const e = resolveEnvLogLevelOverride();
if (process.env.VITEST === "true" && process.env.OPENCLAW_TEST_CONSOLE !== "1" && !isVerbose() && !e && !loggingState.overrideSettings) return {
level: "silent",
style: normalizeConsoleStyle(void 0)
};
const t = loggingState.overrideSettings ?? readLoggingConfig();
return {
level: e ?? normalizeConsoleLevel(t?.consoleLevel),
style: normalizeConsoleStyle(t?.consoleStyle)
};
}
function getConsoleSettings() {
const e = loggingState.cachedConsoleSettings;
if (e) return e;
const t = resolveConsoleSettings();
loggingState.cachedConsoleSettings = t;
return t;
}
function shouldLogSubsystemToConsole(e) {
const t = loggingState.consoleSubsystemFilter;
if (!t || t.length === 0) return true;
const n = normalizeOptionalString(e);
if (!n) return false;
return t.some((e) => n === e || n.startsWith(`${e}/`));
}
const NODE_PROCESS_WARNING_PREFIX = `(${process.release.name}:${process.pid}) `;
function formatConsoleTimestamp(e) {
const t = /* @__PURE__ */ new Date();
if (e === "pretty") return formatTimestamp(t, { style: "short" }).replace(/[+-]\d{2}:\d{2}$/, "");
return formatTimestamp(t, { style: "long" });
}
//#endregion
//#region packages/terminal-core/src/restore.ts
const RESET_SEQUENCE = "\x1B[0m\x1B[?25h\x1B[?1000l\x1B[?1002l\x1B[?1003l\x1B[?1006l\x1B[?2004l\x1B[<u\x1B[>4;0m";
function restoreTerminalState(e, t = {}) {
const n = t.resumeStdinIfPaused ?? t.resumeStdin ?? false;
const r = t.resetStream ?? process.stdout;
const restore = (t, n) => {
try {
n();
} catch (n) {
const r = e ? ` (${e})` : "";
const i = `[terminal] restore ${t} failed${r}: ${String(n)}`;
try {
process.stderr.write(`${i}\n`);
} catch (e) {
console.error(`[terminal] restore reporting failed${r}: ${String(e)}`);
}
}
};
restore("progress line", clearActiveProgressLine);
const i = process.stdin;
if (i.isTTY && typeof i.setRawMode === "function") {
restore("raw mode", () => i.setRawMode(false));
if (n && typeof i.isPaused === "function" && i.isPaused()) restore("stdin resume", () => i.resume());
}
if (r.isTTY) restore("terminal reset", () => r.write(RESET_SEQUENCE));
}
//#endregion
//#region src/runtime.ts
function shouldEmitRuntimeLog(e = process.env) {
if (e.VITEST !== "true") return true;
if (e.OPENCLAW_TEST_RUNTIME_LOG === "1") return true;
return typeof console.log.mock === "object";
}
function shouldEmitRuntimeStdout(e = process.env) {
if (e.VITEST !== "true") return true;
if (e.OPENCLAW_TEST_RUNTIME_LOG === "1") return true;
return typeof process.stdout.write.mock === "object";
}
function isPipeClosedError(e) {
const t = e?.code;
return t === "EPIPE" || t === "EIO";
}
function writeStdout(e) {
if (!shouldEmitRuntimeStdout()) return;
clearActiveProgressLine();
const t = e.endsWith("\n") ? e : `${e}\n`;
try {
process.stdout.write(t);
} catch (e) {
if (isPipeClosedError(e)) return;
throw e;
}
}
function createRuntimeIo() {
return {
log: (...e) => {
if (!shouldEmitRuntimeLog()) return;
clearActiveProgressLine();
console.log(...e);
},
error: (...e) => {
clearActiveProgressLine();
console.error(...e);
},
writeStdout,
writeJson: (e, t = 2) => {
writeStdout(JSON.stringify(e, void 0, t > 0 ? t : void 0));
}
};
}
/** Keep terminal reset bytes off stdout when the invocation owns machine-readable output. */
function restoreRuntimeTerminalState(e, t = {}) {
const n = t.resetStream ?? (loggingState.forceConsoleToStderr ? process.stderr : void 0);
restoreTerminalState(e, {
...t,
...n ? { resetStream: n } : {}
});
}
const defaultRuntime = {
...createRuntimeIo(),
exit: (e, t) => {
restoreRuntimeTerminalState("runtime exit", {
resumeStdinIfPaused: false,
...t?.resetStream ? { resetStream: t.resetStream } : {}
});
throw new ExitError(e);
}
};
/** Signals a deferred or non-exiting runtime exit so callers can unwind owned resources. */
var ExitError = class extends Error {
constructor(e, t) {
super(t ?? `exit ${e}`);
this.code = e;
this.name = "ExitError";
}
};
//#endregion
//#region src/logging/subsystem.ts
var subsystem_exports = /* @__PURE__ */ __exportAll({ createSubsystemLogger: () => createSubsystemLogger });
function isRichConsoleEnv() {
const e = normalizeLowercaseStringOrEmpty(process.env.TERM);
if (process.env.COLORTERM || process.env.TERM_PROGRAM) return true;
return e.length > 0 && e !== "dumb";
}
const consoleColors = [];
const SUBSYSTEM_COLORS = [
"cyan",
"green",
"yellow",
"blue",
"magenta",
"red"
];
const SUBSYSTEM_COLOR_OVERRIDES = /* @__PURE__ */ new Map([["gmail-watcher", "blue"]]);
const SUBSYSTEM_PREFIXES_TO_DROP = /* @__PURE__ */ new Set([
"gateway",
"channels",
"providers"
]);
const CHANNEL_SUBSYSTEM_PREFIXES = /* @__PURE__ */ new Set([
"clickclack",
"discord",
"feishu",
"googlechat",
"imessage",
"irc",
"line",
"matrix",
"mattermost",
"msteams",
"nextcloud-talk",
"nostr",
"openclaw-weixin",
"qqbot",
"signal",
"slack",
"synology-chat",
"telegram",
"tlon",
"twitch",
"webchat",
"wecom",
"whatsapp",
"yuanbao",
"zalo",
"zalouser"
]);
function pickSubsystemColor(e) {
const t = SUBSYSTEM_COLOR_OVERRIDES.get(e);
if (t) return t;
let n = 0;
for (let t = 0; t < e.length; t += 1) n = n * 31 + e.charCodeAt(t) | 0;
const r = Math.abs(n) % SUBSYSTEM_COLORS.length;
return expectDefined(SUBSYSTEM_COLORS[r], "subsystem colors entry at idx");
}
function formatSubsystemForConsole(e) {
const t = e.split("/").filter(Boolean);
const n = t.join("/") || e;
while (t[0] !== void 0 && SUBSYSTEM_PREFIXES_TO_DROP.has(t[0])) t.shift();
const r = t.at(0);
if (r === void 0) return n;
if (CHANNEL_SUBSYSTEM_PREFIXES.has(normalizeLowercaseStringOrEmpty(r))) return r;
return t.slice(-2).join("/");
}
function stripRedundantSubsystemPrefixForConsole(e, t) {
if (!t) return e;
if (e.startsWith("[")) {
const n = e.indexOf("]");
if (n > 1) {
const r = e.slice(1, n);
if (normalizeLowercaseStringOrEmpty(r) === normalizeLowercaseStringOrEmpty(t)) return e.slice(n + 1).replace(/^ */, "");
}
}
const n = e.slice(0, t.length);
if (normalizeLowercaseStringOrEmpty(n) !== normalizeLowercaseStringOrEmpty(t)) return e;
const r = e.slice(t.length, t.length + 1);
if (r !== ":" && r !== " ") return e;
return e.slice(t.length).replace(/^ *:? */, "");
}
function createConsoleLineFormatter(e) {
const t = formatSubsystemForConsole(e);
const n = `[${t}]`;
const r = pickSubsystemColor(t);
return (e, i, a) => {
const o = typeof process.env.FORCE_COLOR === "string" && process.env.FORCE_COLOR.trim().length > 0 && process.env.FORCE_COLOR.trim() !== "0" || !process.env.NO_COLOR && (process.stdout.isTTY || process.stderr.isTTY || isRichConsoleEnv()) ? 1 : 0;
const s = consoleColors[o] ??= new Chalk({ level: o });
const c = e === "error" || e === "fatal" ? s.red : e === "warn" ? s.yellow : e === "debug" || e === "trace" ? s.gray : s.cyan;
const l = stripRedundantSubsystemPrefixForConsole(redactSensitiveText(i), t);
const u = a === "pretty" || loggingState.consoleTimestampPrefix ? s.gray(formatConsoleTimestamp(a)) : "";
const d = s[r](n);
return `${u ? `${u} ${d}` : d} ${c(l)}`;
};
}
function writeConsoleLine(e, t, n = {}) {
clearActiveProgressLine();
const r = process.platform === "win32" && process.env.GITHUB_ACTIONS === "true" ? t.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "?").replace(/[\uD800-\uDFFF]/g, "?") : t;
const i = n.redacted ? r : redactSensitiveText(r);
const a = loggingState.rawConsole ?? console;
if (loggingState.forceConsoleToStderr || e === "error" || e === "fatal") (a.error ?? console.error)(i);
else if (e === "warn") (a.warn ?? console.warn)(i);
else (a.log ?? console.log)(i);
}
function shouldSuppressProbeConsoleLine(e) {
if (isVerbose()) return false;
if (e.level === "error" || e.level === "fatal") return false;
const t = typeof e.message === "string" ? e.message : "";
if (!e.suppressProbeMessages) return false;
if ((typeof e.meta?.runId === "string" ? e.meta.runId : typeof e.meta?.sessionId === "string" ? e.meta.sessionId : void 0)?.startsWith("probe-")) return true;
return /(sessionId|runId)=probe-/.test(t);
}
const CONSOLE_META_LEVELS = /* @__PURE__ */ new Set([
"warn",
"error",
"fatal"
]);
const CONSOLE_META_MAX_CHARS = 2048;
function formatConsoleMetaValue(e) {
if (e === void 0) return;
if (typeof e === "string") return /\s|=/.test(e) || e.length === 0 ? JSON.stringify(e) : e;
if (e === null || typeof e === "number" || typeof e === "boolean") return String(e);
return JSON.stringify(e);
}
/** Preserve native error diagnostics before any sink reduces non-enumerable fields to `{}`. */
function prepareLogMetaRecord(e, t = false) {
let n;
for (const [r, i] of Object.entries(e)) if (i instanceof Error) {
n ??= { ...e };
n[r] = {
name: i.name,
message: i.message,
errorCode: extractErrorCode(i),
stack: t ? i.stack?.split("\n").slice(0, 6).join("\n") : i.stack
};
}
return n ?? e;
}
/**
* Renders structured fields as one compact `key=value` tail so warn/error/fatal
* records keep their diagnostics in plain-text sinks such as journald, which only
* see the console line. The JSON console style and the file sink carry the same
* fields natively, so only plain styles call this.
*
* Fields pass through the shared console transport redactor before flattening, so
* key-aware protection such as `apiToken` survives the loss of structure and the
* length cap can only clip text that is already masked. That redactor also owns
* circular references, bigints, and values with no JSON form, and returns parsed
* data, so rendering a value here cannot re-enter a stateful `toJSON`.
*/
function formatConsoleMeta(e) {
let t;
try {
t = redactLogRecordForTransport(e);
} catch {
return "";
}
const n = [];
for (const [e, r] of Object.entries(t)) {
const t = formatConsoleMetaValue(r);
if (t !== void 0) n.push(`${e}=${t}`);
}
const r = n.join(" ");
return r.length > CONSOLE_META_MAX_CHARS ? `${r.slice(0, CONSOLE_META_MAX_CHARS)}...(truncated)` : r;
}
function logToFile(e, t, n, r) {
if (t === "silent") return;
if (r && Object.keys(r).length > 0) e[t](r, n);
else e[t](n);
}
function createSubsystemLogger(e) {
const t = normalizeOptionalString(e) ?? "unknown";
const n = t === "agent/embedded" || t.startsWith("agent/embedded/") || t === "model-fallback" || t.startsWith("model-fallback/");
let r;
let i;
let a;
const getFileLogger = (e) => {
r ??= getChildLogger({ subsystem: t });
if (e === "error" || e === "fatal" || e !== "info" && areDiagnosticsEnabledForProcess() && hasInternalDiagnosticEventInterest("log.record")) return r;
if (!i) {
i = r.getSubLogger({ stack: { capture: "off" } });
i.settings.parentNames = r.settings.parentNames;
}
return i;
};
const emitLog = (e, r, i) => {
const o = getConsoleSettings();
const s = i?.consoleMessage !== false && isLogLevelEnabled(e, o.level) && shouldLogSubsystemToConsole(t);
const c = isFileLogLevelEnabled(e);
if (!s && !c) return;
let l;
let u = i;
let d = i;
if (i && Object.keys(i).length > 0) {
const { consoleMessage: e, ...t } = i;
if (typeof e === "string") l = e;
u = Object.keys(t).length > 0 ? prepareLogMetaRecord(t) : void 0;
d = u && s ? prepareLogMetaRecord(t, true) : void 0;
}
if (c) logToFile(getFileLogger(e), e, r, u);
if (!s) return;
const f = o.style !== "json" && l === void 0 && d && CONSOLE_META_LEVELS.has(e) ? formatConsoleMeta(d) : "";
const p = l ?? (f ? `${r} ${f}` : r);
if (shouldSuppressProbeConsoleLine({
level: e,
suppressProbeMessages: n,
message: p,
meta: d
})) return;
writeConsoleLine(e, o.style === "json" ? formatJsonConsoleLine({
level: e,
subsystem: t,
message: r,
meta: d
}) : (a ??= createConsoleLineFormatter(t))(e, p, o.style), { redacted: true });
};
return {
subsystem: t,
isEnabled(e, n = "any") {
const r = isLogLevelEnabled(e, getConsoleSettings().level) && shouldLogSubsystemToConsole(t);
const i = isFileLogLevelEnabled(e);
if (n === "console") return r;
if (n === "file") return i;
return r || i;
},
trace(e, t) {
emitLog("trace", e, t);
},
debug(e, t) {
emitLog("debug", e, t);
},
info(e, t) {
emitLog("info", e, t);
},
warn(e, t) {
emitLog("warn", e, t);
},
error(e, t) {
emitLog("error", e, t);
},
fatal(e, t) {
emitLog("fatal", e, t);
},
raw(e) {
if (isFileLogLevelEnabled("info")) logToFile(getFileLogger("info"), "info", e, { raw: true });
const r = getConsoleSettings();
if (isLogLevelEnabled("info", r.level) && shouldLogSubsystemToConsole(t)) {
if (shouldSuppressProbeConsoleLine({
level: "info",
suppressProbeMessages: n,
message: e
})) return;
writeConsoleLine("info", r.style === "json" ? formatJsonConsoleLine({
level: "info",
subsystem: t,
message: e
}) : e, { redacted: r.style === "json" });
}
},
child(e) {
return createSubsystemLogger(`${t}/${e}`);
}
};
}
//#endregion
export { toErrorObject as C, escapeRegExp as E, formatErrorMessage as S, truncateUtf16Safe as T, hasInternalDiagnosticEventInterest as _, redactSensitiveText as a, collectNestedErrorCandidates as b, workerScriptName as c, normalizeFsSafeNativeEnv as d, isDiagnosticFlagEnabled as f, runWithAsyncStore as g, getPluginExecutionFrame as h, getChildLogger as i, runWithMainThreadTask as l, AsyncContext as m, subsystem_exports as n, areDiagnosticsEnabledForProcess as o, parseDiagnosticEnvFlags as p, registerSignalExitFinalizer as r, emitTrustedDiagnosticEvent as s, createSubsystemLogger as t, fsSafeEnvInput as u, runInDetachedAsyncContext as v, sliceUtf16Safe as w, extractErrorCode as x, coerceErrorMessage as y };