UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6 lines • 16.4 kB
import{m as readNonBlankString}from"./string-coerce-CpTFcSwY.mjs";import{n as resolveFilesystemPath,s as resolveUserFilesystemPath}from"./home-dir-DEN5DisQ.mjs";import"./src-0ci69Prg.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as safeParseJsonRecord}from"./json-coercion-DNNwq4_v.mjs";import{n as parseBooleanValue}from"./boolean-Dt_JCqyW.mjs";import{t as isBlockedObjectKey}from"./prototype-keys-Dc7Yq32J.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import{i as INCLUDE_KEY}from"./includes-gwK90iIZ.mjs";import{m as resolveConfigPath}from"./paths-D_FOvGon.mjs";import"./errors-D37BJTfI.mjs";import{t as formatDiagnosticFilenameTimestamp}from"./timestamps-gtUruwBs.mjs";import{t as VERSION}from"./version-DrZ9Nfde.mjs";import{s as parseConfigJson5}from"./io.read-helpers-B0XuPBY2.mjs";import{n as isChannelConfigMetadataKey}from"./config-metadata-RS-_hyk8.mjs";import{a as redactPathForSupport,d as redactTextForSupport,f as sanitizeSupportConfigValue,p as sanitizeSupportSnapshotValue,u as redactSupportString}from"./diagnostic-support-redaction-fdb2R4EP.mjs";import"./io-Di_yuX3t.mjs";import{i as readLatestDiagnosticStabilityBundleSync,r as readDiagnosticStabilityBundleFileSync}from"./diagnostic-stability-bundle-BVFlI2lH.mjs";import{t as redactConfigObject}from"./redact-snapshot-B-h1qJ6D.mjs";import{n as buildConfigSchemaCore}from"./schema-BEC99qUT.mjs";import{t as assertNotUpdateCapturePath}from"./update-capture-paths-C5GOuESg.mjs";import{t as readConfiguredLogTail}from"./log-tail-Dl0kMOWb.mjs";import{i as textSupportBundleFile,n as jsonlSupportBundleFile,o as writeSupportBundleZip,r as supportBundleContents,t as jsonSupportBundleFile}from"./diagnostic-support-bundle-CJE9d-v5.mjs";import{t as collectRuntimeCapabilities}from"./runtime-capabilities-BZLmQGud.mjs";import fs from"node:fs";import process from"node:process";import path from"node:path";import{readRegularFileSync}from"@openclaw/fs-safe/advanced"; //!src/logging/diagnostic-support-log-redaction.ts const LOG_STRING_FIELD_RE=/^(?:action|channel|code|component|endpoint|event|handshake|kind|level|localAddr|logger|method|model|module|msg|name|outcome|phase|pluginId|provider|reason|remoteAddr|requestId|runId|service|source|status|subsystem|surface|target|time|traceId|type)$/iu;const LOG_SCALAR_FIELD_RE=/^(?:active|attempt|bytes|count|durationMs|enabled|exitCode|intervalMs|jobs|limitBytes|localPort|nextWakeAtMs|pid|port|queueDepth|queued|remotePort|statusCode|waitMs|waiting)$/iu;const OMITTED_LOG_FIELD_RE=/(?:authorization|body|chat|content|cookie|credential|detail|error|header|instruction|message|password|payload|prompt|result|secret|session[-_]?id|session[-_]?key|text|token|tool|transcript|url)/iu;const UNSAFE_LOG_MESSAGE_RE=/(?:\blastAssistant\s*=|\b(?:ai response|assistant said|chat text|message contents|prompt|raw webhook body|tool output|tool result|transcript|user said|webhook body)\b|auto-responding\b.*:\s*["']|partial for\b.*:)/iu;const MAX_LOG_STRING_LENGTH=240;const LOGTAPE_ARG_FIELD_RE=/^\d+$/u;const LOGTAPE_META_STRING_FIELDS=/* @__PURE__ */ new Map([[`logLevelName`,`level`],[`name`,`logger`]]);function sanitizeSupportLogRecord(e,t){let n;try{n=JSON.parse(e)}catch{return{omitted:`unparsed`,bytes:Buffer.byteLength(e,`utf8`)}}const r=asOptionalRecord(n);if(!r)return{omitted:`non-object`,bytes:Buffer.byteLength(e,`utf8`)};const i=Object.create(null);addLogObjectFields(i,r,t);addLogTapeMetaFields(i,r,t);addLogTapeArgFields(i,r,t);return Object.keys(i).length>0?i:{omitted:`no-safe-fields`,bytes:Buffer.byteLength(e,`utf8`)}}function addLogTapeMetaFields(e,t,n){const r=asOptionalRecord(t._meta);if(!r)return;for(const[t,i]of LOGTAPE_META_STRING_FIELDS){if(e[i]!==void 0)continue;const a=r[t];if(typeof a===`string`){if(t===`name`){const t=safeParseJsonRecord(a.trim());if(t){addLogObjectFields(e,t,n);continue}}e[i]=sanitizeLogString(a,n)}}}function addLogTapeArgFields(e,t,n){const r=Object.entries(t).filter(([e])=>LOGTAPE_ARG_FIELD_RE.test(e)).toSorted(([e],[t])=>Number(e)-Number(t));for(const[,t]of r){const r=typeof t===`string`?safeParseJsonRecord(t.trim()):asOptionalRecord(t);if(r){addLogObjectFields(e,r,n);continue}if(typeof t===`string`)addLogTapeMessageField(e,t,n)}}function addLogTapeMessageField(e,t,n){const r=sanitizeLogString(t,n);if(e.msg===void 0&&r&&!UNSAFE_LOG_MESSAGE_RE.test(r)){e.msg=r;return}addOmittedLogMessageMetadata(e,t)}function addOmittedLogMessageMetadata(e,t){e.omitted=`log-message`;e.omittedLogMessageBytes=numericLogMetadata(e.omittedLogMessageBytes)+Buffer.byteLength(t,`utf8`);e.omittedLogMessageCount=numericLogMetadata(e.omittedLogMessageCount)+1}function numericLogMetadata(e){return typeof e===`number`&&Number.isFinite(e)?e:0}function addLogObjectFields(e,t,n){for(const[r,i]of Object.entries(t)){if(OMITTED_LOG_FIELD_RE.test(r)||isBlockedObjectKey(r))continue;if(typeof i===`string`){if(!LOG_STRING_FIELD_RE.test(r))continue;const t=sanitizeLogString(i,n);if(r===`msg`&&(!t||UNSAFE_LOG_MESSAGE_RE.test(t))){addOmittedLogMessageMetadata(e,i);continue}e[r]=t}else if((LOG_STRING_FIELD_RE.test(r)||LOG_SCALAR_FIELD_RE.test(r))&&(typeof i===`number`||typeof i===`boolean`||i===null))e[r]=i}}function sanitizeLogString(e,t){return redactSupportString(e,t,{maxLength:MAX_LOG_STRING_LENGTH,truncationSuffix:``})} //!src/logging/diagnostic-support-export.ts const DEFAULT_LOG_LIMIT=5e3;const DEFAULT_LOG_MAX_BYTES=1e6;const SUPPORT_EXPORT_CONFIG_MAX_BYTES=8388608;const SUPPORT_EXPORT_PREFIX=`openclaw-diagnostics-`;const SUPPORT_EXPORT_SUFFIX=`.zip`;function safeScalar(e){if(typeof e===`boolean`)return e;if(typeof e===`number`&&Number.isFinite(e))return e;if(typeof e===`string`)return redactTextForSupport(e)===e&&/^[A-Za-z0-9_.:-]{1,120}$/u.test(e)?e:`<redacted>`}function sortedConfigEntryKeys(e){return Object.keys(asOptionalRecord(e)??{}).filter(e=>e!==INCLUDE_KEY).toSorted((e,t)=>e.localeCompare(t))}function configShapeReadFailure(e){const t={path:e.configPath,exists:Boolean(e.stat),parseOk:false,topLevelKeys:[]};if(e.stat){t.bytes=e.stat.size;t.mtime=e.stat.mtime.toISOString()}if(e.error)t.error=redactSupportString(e.error,e.redaction);return t}function readConfigExport(e,t){const n=redactPathForSupport(e,t);let r;try{assertNotUpdateCapturePath(e,t.stateDir);r=fs.statSync(e);const{buffer:i}=readRegularFileSync({filePath:e,maxBytes:SUPPORT_EXPORT_CONFIG_MAX_BYTES});const a=parseConfigJson5(i.toString(`utf8`));if(!a.ok)return{shape:configShapeReadFailure({configPath:n,redaction:t,stat:r,error:a.error})};const o=t.env;const s=asOptionalRecord(a.parsed)??{};const c=asOptionalRecord(s.gateway);const l=asOptionalRecord(c?.auth);const u=asOptionalRecord(s.discovery);const d=asOptionalRecord(u?.mdns);const f=asOptionalRecord(s.channels);const p=asOptionalRecord(s.plugins);const m=asOptionalRecord(asOptionalRecord(s.agents)?.entries);const h={path:n,exists:true,parseOk:true,bytes:r.size,mtime:r.mtime.toISOString(),topLevelKeys:Object.keys(s).toSorted((e,t)=>e.localeCompare(t))};if(c)h.gateway={mode:safeScalar(c.mode),bind:safeScalar(c.bind),port:safeScalar(c.port),authMode:safeScalar(l?.mode),tailscale:safeScalar(asOptionalRecord(c.tailscale)?.mode)};const g=o.OPENCLAW_DISABLE_BONJOUR?.trim();const _=g?parseBooleanValue(g):void 0;const v=!g?`unset`:_===true?`force-disabled`:_===false?`force-enabled`:`unrecognized`;if(d||v!==`unset`)h.discovery={mdnsMode:safeScalar(d?.mode),bonjourEnvOverride:v};if(f){const e=sortedConfigEntryKeys(f).filter(e=>!isChannelConfigMetadataKey(e));h.channels={count:e.length,ids:e}}if(p){const e=sortedConfigEntryKeys(p.entries);h.plugins={count:e.length,ids:e}}if(m)h.agents={count:sortedConfigEntryKeys(m).length};return{shape:h,sanitized:sanitizeSupportConfigValue(redactConfigObject(a.parsed,buildConfigSchemaCore().uiHints),t)}}catch(e){return{shape:configShapeReadFailure({configPath:n,redaction:t,stat:r,error:!r&&isMissingPathError(e)?void 0:e instanceof Error?e.message:String(e)})}}}function redactErrorForSupport(e,t){return redactSupportString(e instanceof Error?e.message:String(e),t)}async function collectSupportSnapshot(e){if(!e.reader)return{summary:{status:`skipped`}};try{const t=await e.reader();return{summary:{status:`included`,path:e.path},file:jsonSupportBundleFile(e.path,{status:`ok`,capturedAt:e.generatedAt,data:sanitizeSupportSnapshotValue(t,e.redaction)})}}catch(t){const n=redactErrorForSupport(t,e.redaction);return{summary:{status:`failed`,path:e.path,error:n},file:jsonSupportBundleFile(e.path,{status:`failed`,capturedAt:e.generatedAt,error:n})}}}function readStabilityBundle(e,t){if(e===false)return{status:`missing`,dir:`$OPENCLAW_STATE_DIR/logs/stability`};try{if(e!==void 0&&e!==`latest`)assertNotUpdateCapturePath(e,t);const n=e===void 0||e===`latest`?readLatestDiagnosticStabilityBundleSync({stateDir:t}):readDiagnosticStabilityBundleFileSync(e);if(n.status===`found`)assertNotUpdateCapturePath(n.path,t);return n}catch(e){return{status:`failed`,error:e}}}function sanitizeLogTail(e,t){return{status:`included`,file:redactPathForSupport(e.file,t),cursor:e.cursor,size:e.size,lineCount:e.lines.length,truncated:e.truncated,reset:e.reset,lines:e.lines.map(e=>sanitizeSupportLogRecord(e,t))}}function failedLogTail(e,t){const n=redactErrorForSupport(e,t);return{status:`failed`,file:`unavailable`,cursor:0,size:0,lineCount:0,truncated:false,reset:false,error:n,lines:[{omitted:`log-tail-read-failed`,error:n}]}}function logString(e,t){const n=e[t];return typeof n===`string`&&n.trim()?n:void 0}function classifyBonjourLogKind(e){if(e.includes(`disabling`))return`disabled`;if(e.includes(`restarting`))return`restarted`;if(e.includes(`suppressing ciao`))return`ciao_suppressed`;if(e.includes(`conflict`))return`conflict`;if(e.includes(`watchdog`))return`watchdog`;return`other`}function summarizeBonjourLogs(e){const t={count:0,warnings:0,flags:{disabled:false,restarted:false,ciaoSuppressed:false}};for(const n of e.lines){if(![`subsystem`,`logger`,`module`,`pluginId`,`component`].some(e=>logString(n,e)?.toLowerCase().includes(`bonjour`))&&logString(n,`msg`)?.toLowerCase().startsWith(`bonjour:`)!==true)continue;t.count+=1;const e=logString(n,`level`)?.toLowerCase();if(e===`warn`||e===`error`)t.warnings+=1;const r=logString(n,`msg`)?.toLowerCase()??``;t.flags.disabled||=r.includes(`disabling`);t.flags.restarted||=r.includes(`restarting`);t.flags.ciaoSuppressed||=r.includes(`suppressing ciao`);t.last={...logString(n,`time`)?{time:logString(n,`time`)}:{},...logString(n,`level`)?{level:logString(n,`level`)}:{},kind:classifyBonjourLogKind(r)}}return t}async function writeDiagnosticSupportExport(e){const t=process.env;const n=resolveStateDir(t);const r=/* @__PURE__ */ new Date;const i=e.outputPath;const a=`${SUPPORT_EXPORT_PREFIX}${formatDiagnosticFilenameTimestamp(r)}-${process.pid}${SUPPORT_EXPORT_SUFFIX}`;const o=readNonBlankString(i);let s;if(!o)s=path.join(n,`logs`,`support`,a);else{const e=o.startsWith(`~`)?resolveUserFilesystemPath(o):resolveFilesystemPath(o);s=e;try{if(fs.statSync(e).isDirectory())s=path.join(e,a)}catch{}}const c=r.toISOString();const l=resolveConfigPath(t,n);const u=readStabilityBundle(e.stabilityBundle,n);const d={env:t,stateDir:n};const f=e.logLimit??DEFAULT_LOG_LIMIT;const p=e.logMaxBytes??DEFAULT_LOG_MAX_BYTES;let m;try{const e=await readConfiguredLogTail({limit:f,maxBytes:p});assertNotUpdateCapturePath(e.file,d.stateDir);m=sanitizeLogTail(e,d)}catch(e){m=failedLogTail(e,d)}const h=readConfigExport(l,d);const[g,_,v,y]=await Promise.all([collectSupportSnapshot({path:`status/gateway-status.json`,reader:e.readStatusSnapshot,generatedAt:c,redaction:d}),collectSupportSnapshot({path:`health/gateway-health.json`,reader:e.readHealthSnapshot,generatedAt:c,redaction:d}),collectSupportSnapshot({path:`runtime/capabilities.json`,reader:collectRuntimeCapabilities,generatedAt:c,redaction:d}),collectSupportSnapshot({path:`runtime/gateway-capabilities.json`,reader:e.readGatewayCapabilities,generatedAt:c,redaction:d})]);const b={generatedAt:c,openclawVersion:VERSION,process:{platform:process.platform,arch:process.arch,node:process.versions.node,pid:process.pid},stateDir:redactPathForSupport(n,d),config:h.shape,logs:{file:m.file,cursor:m.cursor,size:m.size,lineCount:m.lineCount,truncated:m.truncated,reset:m.reset},stability:u.status===`found`?{status:`found`,path:redactPathForSupport(u.path,d),mtimeMs:u.mtimeMs,eventCount:u.bundle.snapshot.count,reason:u.bundle.reason,generatedAt:u.bundle.generatedAt}:u.status===`missing`?{status:`missing`,dir:redactPathForSupport(u.dir,d)}:{status:`failed`,path:u.path?redactPathForSupport(u.path,d):void 0,error:redactErrorForSupport(u.error,d)},bonjour:summarizeBonjourLogs(m),status:g.summary,health:_.summary,runtimeCapabilities:v.summary,gatewayCapabilities:y.summary};const x=[jsonSupportBundleFile(`diagnostics.json`,b),jsonSupportBundleFile(`config/shape.json`,h.shape),jsonSupportBundleFile(`config/sanitized.json`,h.sanitized??null),jsonlSupportBundleFile(`logs/openclaw-sanitized.jsonl`,m.lines.map(e=>JSON.stringify(e)))];for(const e of[g,_,v,y])if(e.file)x.push(e.file);if(u.status===`found`)x.push(jsonSupportBundleFile(`stability/latest.json`,u.bundle));const S=u.status===`found`?`included latest stability bundle (${u.bundle.snapshot.count} event(s))`:`no stability bundle included (${u.status})`;const C=h.shape.exists?`config shape included (${h.shape.parseOk?`parsed`:`parse failed`})`:h.shape.error??`config file not found`;const w=m.status===`failed`?`sanitized log tail unavailable (${m.error})`:`sanitized log tail (${m.lineCount} line(s), inspected ${m.size} byte(s), raw messages omitted)`;const supportSnapshotLine=(e,t)=>{if(t.status===`included`)return`${e} snapshot included (${t.path})`;if(t.status===`failed`)return`${e} snapshot failed (${t.error})`;return`${e} snapshot skipped`};const T=[`# OpenClaw Diagnostics Export`,``,`Attach this zip to the bug report. It is designed for maintainers to inspect without asking for raw logs first.`,``,`## Generated`,``,`Generated: ${c}`,`OpenClaw: ${VERSION}`,``,`## Contents`,``,`- ${S}`,`- ${w}`,`- ${C}`,`- ${supportSnapshotLine(`gateway status`,g.summary)}`,`- ${supportSnapshotLine(`gateway health`,_.summary)}`,`- ${supportSnapshotLine(`exporting process capabilities`,v.summary)}`,`- ${supportSnapshotLine(`gateway capabilities`,y.summary)}`,``,`## Maintainer Quick Read`,``,"- `manifest.json`: file inventory and privacy notes","- `diagnostics.json`: top-level summary of config, logs, Bonjour/mDNS, stability, status, and health","- `config/sanitized.json`: config values with credentials, private identifiers, and prompt text redacted","- `status/gateway-status.json`: sanitized service/connectivity snapshot","- `health/gateway-health.json`: sanitized Gateway health snapshot","- `runtime/capabilities.json`: exporting process capabilities and build identity","- `runtime/gateway-capabilities.json`: serving Gateway capabilities, when reachable","- `logs/openclaw-sanitized.jsonl`: sanitized log summaries and metadata","- `stability/latest.json`: newest payload-free stability bundle, when available",``,`## Privacy`,``,`- raw chat text, webhook bodies, tool outputs, tokens, cookies, and secrets are not included intentionally`,`- log records keep operational summaries and safe metadata fields`,`- status, health, and capability snapshots redact secret fields, payload-like fields, and account/message identifiers`,`- config output keeps useful settings but redacts secrets, private identifiers, and prompt text`].join(` `);x.push(textSupportBundleFile(`summary.md`,T));const E={version:1,generatedAt:c,openclawVersion:VERSION,platform:process.platform,arch:process.arch,node:process.versions.node,stateDir:redactPathForSupport(n,d),contents:supportBundleContents(x),privacy:{payloadFree:true,rawLogsIncluded:false,notes:[`Stability bundles are payload-free diagnostic snapshots.`,`Logs keep operational summaries and safe metadata fields; payload-like fields are omitted.`,`Status and health snapshots redact secrets, payload-like fields, and account/message identifiers.`,`Config output includes useful settings with credentials, private identifiers, and prompt text redacted.`]}};const D=await writeSupportBundleZip({outputPath:s,files:[jsonSupportBundleFile(`manifest.json`,E),...x]});return{path:D.path,bytes:D.bytes,manifest:E}}export{writeDiagnosticSupportExport};