UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

42 lines • 18.3 kB
import{S as asOptionalRecord,h as normalizeLowercaseStringOrEmpty,i as resolveGlobalSingleton,p as normalizeUniqueStringEntries,v as normalizeOptionalString}from"./global-singleton-CTnqrmaI.js";import{f as DEFAULT_ACCOUNT_ID,g as normalizeAgentId,l as resolveAccountKey,m as normalizeOptionalAccountId,p as normalizeAccountId,u as resolveChannelAccountKey}from"./runtime-doctor-migrations-D8alsOFs.js";import"./number-coercion-BhEzZ9ku.js";import"./fs-safe-BnA-Wq_f.js";import{hasNodeErrorCode,isPathInside as isPathInside$1,normalizeWindowsPathForComparison as normalizeWindowsPathForComparison$1}from"@openclaw/fs-safe/path";import path from"node:path";import fs from"node:fs";import os from"node:os"; //!src/config/channel-account-config.ts function mergeAccountConfig(e){const t=/* @__PURE__ */ new Set([`accounts`,...e.omitKeys??[]]);const n=Object.fromEntries(Object.entries(e.channelConfig??{}).filter(([e])=>!t.has(e)));const r=e.accountConfig;const i={...n,...r};const a=i;for(const[t,i]of Object.entries(e.inheritEmptyKeys??{})){const e=r?.[t];const o=i===`array`?Array.isArray(e)?e:void 0:asOptionalRecord(e);if(o&&Object.keys(o).length===0)a[t]=n[t]}for(const t of e.nestedObjectKeys??[]){const e=asOptionalRecord(n[t]);const i=asOptionalRecord(r?.[t]);if(e&&i)a[t]={...e,...i}}if(e.preserveRootAllowFrom&&Array.isArray(n.allowFrom)&&Array.isArray(r?.allowFrom)){if(n.allowFrom.some(e=>{const t=String(e).trim();return t.length>0&&t!==`*`})&&r.allowFrom.some(e=>String(e).trim()===`*`)){const e=r.allowFrom.filter(e=>String(e).trim()!==`*`);a.allowFrom=e.length>0?e:n.allowFrom}}return i}function resolveMergedAccountConfig(e){const t=e.channelId?resolveChannelAccountKey(e.accounts,e.accountId,e.channelId,e.normalizeAccountId,e.accountKeyPolicy):resolveAccountKey(e.accounts,e.accountId,e.normalizeAccountId,e.accountKeyPolicy);const n=t===void 0?void 0:e.accounts?.[t];return mergeAccountConfig({...e,accountConfig:n})} //!packages/session-url-contract/src/session-key.ts const DEFAULT_MAIN_KEY=`main`;function parseAgentSessionKeyParts(e){if(!e.startsWith(`agent:`)&&e.slice(0,6).toLowerCase()!==`agent:`)return null;const t=e.indexOf(`:`,6);if(t===-1)return null;const n=e.slice(6,t).trim();const r=e.slice(t+1);return n&&r&&!r.startsWith(`:`)?{agentId:n,rest:r}:null}function normalizeMainKey(e){return normalizeLowercaseStringOrEmpty(e)||`main`}function buildAgentMainSessionKey(e){return`agent:${normalizeAgentId(e.agentId)}:${normalizeMainKey(e.mainKey)}`} //!packages/session-url-contract/src/share.ts const CONTROL_UI_RESERVED_ROUTE_SEGMENTS=Object.freeze([`activity`,`ai-agents`,`appearance`,`approve`,`apps`,`ask`,`automation`,`automations`,`channels`,`chat`,`templates`,`communications`,`config`,`cron`,`custodian`,`dashboard`,`dashboards`,`debug`,`focus`,`infrastructure`,`lobsterdex`,`logs`,`mcp`,`meetings`,`memory-import`,`model-providers`,`model-setup`,`new`,`nodes`,`plugin`,`plugins`,`portals`,`profile`,`sessions`,`settings`,`share`,`skills`,`systems`,`terminal`,`usage`,`workboard`,`worktrees`]); //!packages/session-url-contract/src/session-key-normalization.ts const SIGNAL_GROUP_ID_PATTERN=/(^|:)signal:group:([^:]+)/gi;const MATRIX_ROOM_KEY_PATTERN=/^(?:(?:agent:[^:]*:)+:*)?matrix:(?:channel|group):/i;const MATRIX_DM_THREAD_KEY_PATTERN=/^(?:agent:[^:]+:)*(?:[^:]+|(?:matrix:(?:[^:]+:)?)?direct:.+):thread:(\$.+)$/i;function matrixDmThreadEventId(e){return MATRIX_DM_THREAD_KEY_PATTERN.exec(e)?.[1]}function matrixEventThreadIdStart(e){const t=e.toLowerCase().includes(`:thread:$`)?matrixDmThreadEventId(e):void 0;return t?e.length-t.length:-1}const NORMALIZED_SESSION_KEY_CACHE_MAX_ENTRIES=2048;const NORMALIZED_SESSION_KEY_CACHE_MAX_LENGTH=4096;const normalizedSessionKeyCache=/* @__PURE__ */ new Map;function writeNormalizedSessionKeyCache(e,t){if(e.length>NORMALIZED_SESSION_KEY_CACHE_MAX_LENGTH)return;normalizedSessionKeyCache.set(e,t);if(normalizedSessionKeyCache.size>NORMALIZED_SESSION_KEY_CACHE_MAX_ENTRIES){const e=normalizedSessionKeyCache.keys().next();if(!e.done)normalizedSessionKeyCache.delete(e.value)}}function collectCasePreservedSpans(e){const t=[];const n=matrixEventThreadIdStart(e);if(n>=0)t.push({start:n,end:e.length,trim:false});for(const n of e.matchAll(SIGNAL_GROUP_ID_PATTERN)){const e=n[0];const r=n[2]??``;const i=n.index+e.length-r.length;t.push({start:i,end:i+r.length,trim:true})}const r=MATRIX_ROOM_KEY_PATTERN.exec(e);if(!r||r[0].length>=e.length)return t;const i=r[0].length;const a=e.slice(i);const o=normalizeLowercaseStringOrEmpty(a).lastIndexOf(`:thread:`);if(o===-1){t.push({start:i,end:e.length,trim:false});return t}t.push({start:i,end:i+o,trim:false});const s=i+o+8;if(s<e.length)t.push({start:s,end:e.length,trim:false});return t}function normalizeSessionKeyPreservingOpaquePeerIds(e){const t=normalizeOptionalString(e);if(!t)return``;const n=normalizedSessionKeyCache.get(t);if(n!==void 0)return n;const r=t.toLowerCase();if(!r.includes(`signal:`)&&!r.includes(`matrix:`)&&!r.includes(`:thread:$`))return r;const i=collectCasePreservedSpans(t).filter(e=>e.end>e.start).toSorted((e,t)=>e.start-t.start);let a=``;let o=0;for(const e of i){if(e.start<o)continue;a+=normalizeLowercaseStringOrEmpty(t.slice(o,e.start));const n=t.slice(e.start,e.end);a+=e.trim?n.trim():n;o=e.end}a+=normalizeLowercaseStringOrEmpty(t.slice(o));writeNormalizedSessionKeyCache(t,a);return a}function parseAgentSessionKey(e){return parseAgentSessionKeyParts(normalizeSessionKeyPreservingOpaquePeerIds(e))} //!src/routing/session-key.ts const LEGACY_IMPLICIT_AGENT_ID=`main`;const DEFAULT_AGENT_ID=LEGACY_IMPLICIT_AGENT_ID;function classifySessionKeyShape(e){const t=(e??``).trim();if(!t)return`missing`;if(parseAgentSessionKey(t))return`agent`;return normalizeLowercaseStringOrEmpty(t).startsWith(`agent:`)?`malformed_agent`:`legacy_or_alias`} //!src/channels/plugins/account-helpers.ts function createAccountListHelpers(e,t){function hasImplicitDefaultAccount(n){const r=n.channels?.[e];return Boolean(t?.hasImplicitDefaultAccount?.(n)||t?.implicitDefaultAccount?.channelKeys?.some(e=>hasConfiguredAccountValue(r?.[e]))||t?.implicitDefaultAccount?.envVars?.some(e=>hasConfiguredAccountValue(process.env[e])))}function resolveConfiguredDefaultAccountId(t){const n=t.channels?.[e];return normalizeOptionalAccountId(typeof n?.defaultAccount===`string`?n.defaultAccount:void 0)}function listConfiguredAccountIds(n){const r=(n.channels?.[e])?.accounts;if(!r||typeof r!==`object`)return[];const i=Object.keys(r).filter(Boolean);const a=t?.normalizeAccountId;if(!a)return i;return normalizeUniqueStringEntries(i.map(e=>a(e)))}function listAccountIds(e){return listCombinedAccountIds({configuredAccountIds:listConfiguredAccountIds(e),additionalAccountIds:t?.additionalAccountIds?.(e),implicitAccountId:t?.resolveImplicitAccountId?t.resolveImplicitAccountId(e):hasImplicitDefaultAccount(e)?DEFAULT_ACCOUNT_ID:void 0,fallbackAccountIdWhenEmpty:t?.fallbackAccountIdWhenEmpty===false?void 0:t?.fallbackAccountIdWhenEmpty??`default`})}function resolveDefaultAccountId(e){return resolveListedDefaultAccountId({accountIds:listAccountIds(e),configuredDefaultAccountId:resolveConfiguredDefaultAccountId(e),allowUnlistedDefaultAccount:t?.allowUnlistedDefaultAccount})}return{listConfiguredAccountIds,listAccountIds,resolveDefaultAccountId,resolveAccountConfig:(n,r)=>{const i=n.channels?.[e];const a=i?.accounts;return resolveMergedAccountConfig({channelConfig:i,channelId:e,accounts:a,accountId:r,omitKeys:t?.omitKeys,normalizeAccountId:t?.normalizeAccountId,nestedObjectKeys:t?.nestedObjectKeys})}}}function hasConfiguredAccountValue(e){if(typeof e===`string`)return e.trim().length>0;return e!==void 0&&e!==null}function listCombinedAccountIds(e){const t=new Set([...e.configuredAccountIds,...e.additionalAccountIds??[],...e.implicitAccountId?[e.implicitAccountId]:[]].filter(Boolean));if(t.size===0&&e.fallbackAccountIdWhenEmpty)return[e.fallbackAccountIdWhenEmpty];return[...t].toSorted((e,t)=>e.localeCompare(t))}function resolveListedDefaultAccountId(e){const t=e.configuredDefaultAccountId;const n=e.normalizeListedAccountId??normalizeAccountId;if(t&&(e.allowUnlistedDefaultAccount||e.accountIds.some(e=>n(e)===t)))return t;if(e.accountIds.includes(`default`))return DEFAULT_ACCOUNT_ID;if(e.ambiguousFallbackAccountId&&e.accountIds.length>1)return e.ambiguousFallbackAccountId;return e.accountIds[0]??`default`} //!packages/normalization-core/src/home-dir.ts function normalizeHomeDirValue(e){const t=e?.trim();return t&&t!==`undefined`&&t!==`null`?t:void 0}function normalizeSafe(e){try{return normalizeHomeDirValue(e())}catch{return}}function resolveTermuxHome(e){const t=normalizeHomeDirValue(e.PREFIX);if(!t||!normalizeHomeDirValue(e.ANDROID_DATA))return;if(!/(?:^|\/)com\.termux\/files\/usr\/?$/u.test(t.replace(/\\/gu,`/`)))return;return path.resolve(t,`..`,`home`)}function resolveRawOsHomeDir(e,t){return normalizeHomeDirValue(e.HOME)??normalizeHomeDirValue(e.USERPROFILE)??resolveTermuxHome(e)??normalizeSafe(t)}function resolveOsHomeDir(e=process.env,t=os.homedir){const n=resolveRawOsHomeDir(e,t);return n?path.resolve(n):void 0}function resolveEffectiveHomeDir(e=process.env,t=os.homedir,n){const r=normalizeHomeDirValue(e.OPENCLAW_HOME);if(!r)return resolveOsHomeDir(e,t);if(r===`~`||r.startsWith(`~/`)||r.startsWith(`~\\`)){const i=resolveRawOsHomeDir(e,t);if(!i)return n?.preserveUnresolvedTilde?path.resolve(r):void 0;return path.resolve(r.replace(/^~(?=$|[\\/])/,()=>i))}return path.resolve(r)} //!packages/terminal-core/src/ansi-sequences.ts const ANSI_OSC_INTRODUCER_PATTERN=`(?:\\x1b\\]|\\x9d)`;const ANSI_STRING_TERMINATOR_PATTERN=`(?:\\x1b\\\\|\\x07|\\x9c)`;const ANSI_OSC_PATTERN=`${ANSI_OSC_INTRODUCER_PATTERN}[^\\x07\\x1b\\x9c]*${ANSI_STRING_TERMINATOR_PATTERN}`;const ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN=`[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`;const ansiOscAtIndexRegex=new RegExp(ANSI_OSC_PATTERN,`y`);function matchAnsiOscAt(e,t){ansiOscAtIndexRegex.lastIndex=t;return ansiOscAtIndexRegex.exec(e)?.[0]}function scanAnsiCsiAt(e,t){const n=e.charCodeAt(t);if(n!==155&&(n!==27||e.charCodeAt(t+1)!==91))return;let r=t+(n===155?1:2);const i=[];let a=false;while(r<e.length){const t=e.charCodeAt(r);if(t===24||t===26){r+=1;a=true;break}if(t===27||t===155){a=true;break}if(t<=31||t===127){i.push(e.charAt(r));r+=1;continue}if(t>=32&&t<=63){r+=1;continue}if(t>=64&&t<=126)r+=1;a=true;break}return{controls:i,ended:a,value:e.slice(t,r)}} //!packages/terminal-core/src/ansi.ts const ANSI_OSC_SEQUENCE_PATTERN=`${ANSI_OSC_INTRODUCER_PATTERN}[\\s\\S]*?${ANSI_STRING_TERMINATOR_PATTERN}`;const ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX=new RegExp(`${ANSI_OSC_SEQUENCE_PATTERN}|${ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN}`,`y`);const graphemeSegmenter=new Intl.Segmenter(void 0,{granularity:`grapheme`});function hasAnsiIntroducer(e){return e.includes(`\x1B`)||e.includes(`›`)||e.includes(``)}function stripAnsiInternal(e,t){if(!hasAnsiIntroducer(e))return e;const n=[];let r=0;let i=0;while(i<e.length){const a=e.charCodeAt(i);if(a!==27&&a!==155&&a!==157){i+=1;continue}const o=matchAnsiOscAt(e,i);const s=o?void 0:scanAnsiCsiAt(e,i);ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX.lastIndex=i;const c=!o&&t.compatibilityGrammar?ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX.exec(e)?.[0]:void 0;let l=o?.length??s?.value.length??c?.length;if(l===void 0){i+=1;continue}if(s&&!s.ended&&t.preserveIncompleteCsi)break;if(s?.controls.length===0&&c)l=Math.max(l,c.length);n.push(e.slice(r,i),...s?.controls??[]);i+=l;r=i}n.push(e.slice(r));return n.join(``)}function stripAnsi(e){return stripAnsiInternal(e,{compatibilityGrammar:false})}const LOG_CONTROL_CHARS_REGEX=new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}${String.fromCharCode(127)}-${String.fromCharCode(159)}]`,`g`);function sanitizeForLog(e){return stripAnsi(e).replace(LOG_CONTROL_CHARS_REGEX,``)} //!packages/terminal-core/src/safe-text.ts function sanitizeTerminalText(e){return stripAnsi(e).replace(/[\p{Cc}\p{Bidi_Control}]/gu,e=>e===`\r`?`\\r`:e===` `?`\\n`:e===` `?`\\t`:``)} //!src/infra/safe-cwd.ts function tryProcessCwd(){try{return process.cwd()}catch{return}} //!src/infra/home-dir.ts function getUserPathBaseDirectory(){return resolveGlobalSingleton(Symbol.for(`openclaw.userPathBaseDirectory`),()=>{const{AsyncLocalStorage:e}=process.getBuiltinModule(`async_hooks`);return new e})}function resolveRequiredHomeDir(e=process.env,t=os.homedir){const n=resolveEffectiveHomeDir(e,t)??tryProcessCwd();if(n)return path.resolve(n);throw new Error(`Unable to resolve an OpenClaw home: set OPENCLAW_HOME, HOME, or USERPROFILE, or run from an existing directory.`)}function resolveRequiredOsHomeDir(e=process.env,t=os.homedir){const n=resolveOsHomeDir(e,t)??tryProcessCwd();if(n)return path.resolve(n);throw new Error(`Unable to resolve an OS home: set HOME or USERPROFILE, or run from an existing directory.`)}function expandHomePrefix(e,t){if(!e.startsWith(`~`))return e;const n=normalizeHomeDirValue(t?.home)??resolveEffectiveHomeDir(t?.env??process.env,t?.homedir??os.homedir);if(!n)return e;return e.replace(/^~(?=$|[\\/])/,()=>n)}function resolveAgainstUserBase(e){const t=getUserPathBaseDirectory().getStore();return t?path.resolve(t,e):path.resolve(e)}function resolvePathWithHome(e,t,n,r=resolveAgainstUserBase){const i=e.trim();if(!i)return i;return r(i.startsWith(`~`)?expandHomePrefix(i,{home:n(t?.env??process.env,t?.homedir??os.homedir),env:t?.env,homedir:t?.homedir}):i)}function resolveHomeRelativePath(e,t){return resolvePathWithHome(e,t,resolveRequiredHomeDir)}function resolveUserPath(e,t=process.env,n=os.homedir){if(!e)return``;return resolveHomeRelativePath(e,{env:t,homedir:n})} //!src/cli/profile-utils.ts const PROFILE_NAME_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/i;function isValidProfileName(e){return PROFILE_NAME_RE.test(e)}function normalizeProfileName(e){const t=e?.trim();if(!t)return null;if(normalizeLowercaseStringOrEmpty(t)==="default")return null;if(!isValidProfileName(t))return null;return t}function resolveProfileStateDir(e,t,n){const r=e.trim();if(!isValidProfileName(r))throw new Error(`Invalid profile name: ${JSON.stringify(e)}`);const i=normalizeLowercaseStringOrEmpty(r)==="default"?``:`-${r}`;return path.join(resolveRequiredHomeDir(t,n),`.openclaw${i}`)} //!src/infra/lru-cache.ts var LruCache=class{#e;#t;#n;#r=/* @__PURE__ */ new Map;#i=0;constructor(e,t){this.#e=Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):1;this.#t=t?.maxBytes??Number.POSITIVE_INFINITY;this.#n=t?.sizeOf}get size(){return this.#r.size}clear(){this.#r.clear();this.#i=0}keys(){return this.#r.keys()}delete(e){if(!this.#r.has(e))return false;this.#i-=this.#n?.(this.#r.get(e))??0;return this.#r.delete(e)}deleteValue(e){for(const[t,n]of this.#r)if(n===e)this.delete(t)}peek(e){return this.#r.get(e)}get(e){if(!this.#r.has(e))return;const t=this.#r.get(e);this.#r.delete(e);this.#r.set(e,t);return t}set(e,t){this.delete(e);this.#r.set(e,t);this.#i+=this.#n?.(t)??0;for(const e of this.#r.keys()){if(this.#r.size<=this.#e&&this.#i<=this.#t)break;this.delete(e)}}}; //!src/config/state-dir.ts const absoluteStateDirs=new LruCache(64);function resolveNewStateDir(e=resolveRequiredHomeDir){return path.join(e(),`.openclaw`)}function resolveStateDir(e=process.env,t=os.homedir){const n=e.OPENCLAW_STATE_DIR?.trim();if(n&&process.platform!==`win32`&&path.isAbsolute(n)){const e=absoluteStateDirs.peek(n);if(e!==void 0)return e;const t=path.resolve(n);absoluteStateDirs.set(n,t);return t}if(n)return resolveHomeRelativePath(n,{env:e,homedir:t});return resolveStateDirFromHome(e,()=>resolveRequiredHomeDir(e,t))}function resolveStateDirFromHome(e,t){const n=normalizeProfileName(e.OPENCLAW_PROFILE);return n?resolveProfileStateDir(n,e,t):resolveNewStateDir(t)} //!src/infra/config-dir.ts function resolveConfigDir(e=process.env,t=os.homedir){const n=e.OPENCLAW_STATE_DIR?.trim();if(n)return resolveUserPath(n,e,t);const r=e.OPENCLAW_CONFIG_PATH?.trim();if(r)return path.dirname(resolveUserPath(r,e,t));return resolveStateDir(e,t)} //!src/infra/path-guards.ts function normalizeWindowsPathPreservingCase(e){const t=path.win32.normalize(e);if(!t.startsWith(`\\\\?\\`))return t;const n=t.slice(4);return n.toUpperCase().startsWith(`UNC\\`)?`\\\\${n.slice(4)}`:n} //!src/infra/home-display.ts function shortenPathWithHome(e,{home:t,prefix:n}){if(e===t)return n;if(e.startsWith(`${t}/`)||process.platform===`win32`&&e.startsWith(`${t}\\`))return`${n}${e.slice(t.length)}`;if(process.platform===`win32`&&path.win32.isAbsolute(e)&&isPathInside$1(t,e)){const r=path.win32.relative(normalizeWindowsPathPreservingCase(t),normalizeWindowsPathPreservingCase(e));return path.win32.join(n,r)}return e} //!src/infra/abort-signal.ts function isAbortError(e){if(!e||typeof e!==`object`)return false;try{if((`name`in e?String(e.name):``)===`AbortError`)return true;return(`message`in e&&typeof e.message===`string`?e.message:``)===`This operation was aborted`}catch{return false}} //!src/utils.ts function resolveHomeDir(){return resolveEffectiveHomeDir(process.env,os.homedir)}const HOME_TEXT_START=String.raw`(?<=^|[\s"'\x60(\[{<=:;]|file://)`;const HOME_TEXT_DELIMITER=String.raw`[\s"'\x60)\]}>]`;const HOME_TEXT_LIST_NEXT=String.raw`[:;](?=[/\\~$]|[A-Za-z]:)`;function resolveHomeDisplayPrefix(){const e=resolveHomeDir();if(!e)return;if(normalizeHomeDirValue(process.env.OPENCLAW_HOME))return{home:e,prefix:`$OPENCLAW_HOME`};return{home:e,prefix:`~`}}function shortenHomePath(e){const t=resolveHomeDisplayPrefix();if(!t)return e;return shortenPathWithHome(e,t)}let CONFIG_DIR=resolveConfigDir();export{LEGACY_IMPLICIT_AGENT_ID as C,normalizeMainKey as D,buildAgentMainSessionKey as E,parseAgentSessionKeyParts as O,DEFAULT_AGENT_ID as S,normalizeSessionKeyPreservingOpaquePeerIds as T,tryProcessCwd as _,normalizeWindowsPathForComparison$1 as a,createAccountListHelpers as b,resolveStateDir as c,resolveProfileStateDir as d,expandHomePrefix as f,resolveUserPath as g,resolveRequiredOsHomeDir as h,isPathInside$1 as i,mergeAccountConfig as k,LruCache as l,resolveRequiredHomeDir as m,isAbortError as n,normalizeWindowsPathPreservingCase as o,resolveHomeRelativePath as p,hasNodeErrorCode as r,resolveConfigDir as s,shortenHomePath as t,normalizeProfileName as u,sanitizeTerminalText as v,classifySessionKeyShape as w,hasConfiguredAccountValue as x,sanitizeForLog as y};