UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 13.3 kB
import{o as e}from"./transcript-record-coerce-eN4p5mcq.mjs";import{n as t}from"./transcript-global-singleton-DIJgobpU.mjs";import"./transcript-plugin-instance-invocation-7pP9ZY8b.mjs";import"./transcript-path-guards-DYqTo0Vr.mjs";import{a as n,o as r,r as i}from"./transcript-string-coerce-BxRUqIXb.mjs";import{i as a,l as o,r as s,s as c,t as l}from"./transcript-state-dir-BTeq06tQ.mjs";import"./transcript-paths-B5zwyc4S.mjs";import{n as u,r as d}from"./transcript-path-existence-DsAt-_G2.mjs";import{n as f,r as p}from"./transcript-agent-id-DmscQLD6.mjs";import{r as m}from"./transcript-session-key-normalization-CxaUSpng.mjs";import{n as h,r as g}from"./transcript-session-key-DI46891-.mjs";import{a as _}from"./transcript-paths-EL7FYwW9.mjs";import{r as v}from"./transcript-immutable-data-JqBMopGj.mjs";import{lt as y,nt as b}from"./transcript-openclaw-agent-db-schema-read-0j86l7zG.mjs";import{isMainThread as x}from"node:worker_threads";import S from"node:path";import C from"node:fs";import w from"node:os";import{probePathCaseInsensitiveSync as T,resolvePathPrefixSync as E,sameFileIdentity as D}from"@openclaw/fs-safe/advanced";const O=/^(?:(?:pnpm|npm|bunx|npx)\s+)?openclaw(?=\s|$)/,k=/(?:^|\s)--container(?:\s|=|$)/,A=/(?:^|\s)--profile(?:\s|=|$)/,j=/(?:^|\s)--dev(?:\s|$)/,M=/^(?:\s+--(?:dev|no-color|(?:profile|log-level)[=\s]+\S+))*\s+update(?:\s|$)/,N=/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/;function formatCliCommand(e,t=process.env){let n=t.OPENCLAW_CONTAINER_HINT?.trim(),r=n&&N.test(n)?n:void 0,i=s(t.OPENCLAW_PROFILE);if(!r&&!i||!O.test(e))return e;let a;return r&&!k.test(e)&&!M.test(e.replace(O,``))&&(a=`--container ${r}`),!r&&i&&!A.test(e)&&!j.test(e)&&(a=`--profile ${i}`),a?e.replace(O,e=>`${e} ${a}`):e}function hasExplicitModelPolicyAllow(t){return e(t)&&Object.hasOwn(t,`allow`)}const P={},F=[{id:`openclaw`,kind:`system`},{id:`crestodian`,kind:`system`}],I=new Set(F.map(e=>f(e.id)));function isReservedSystemAgentId(e){return I.has(f(e))}let L;const R=/* @__PURE__ */ new WeakMap;function withAgentRosterFactsBatch(e,t){let n=L;L=n?.config===e?n:{config:e,facts:readAgentRosterFacts(e)??{}};try{return t()}finally{L=n}}function readAgentRosterFacts(e){if(L?.config===e)return L.facts;let t=P.current,n=t?.config===e?t.revision:void 0;if(n===void 0&&!v(e))return;let r=R.get(e);return r&&r.publication===n||(r={publication:n,facts:{}},R.set(e,r)),r.facts}function collectAgentEntries(t,n,r){let i=readAgentRosterProperty(t);if(i?.kind===`entries`&&e(i.value)){let t=[];for(let a in i.value){if(!Object.hasOwn(i.value,a))continue;let o=i.value[a];if(e(o)){let e={...o,id:a};if(t.push(n?{entry:e,source:{kind:`entries`,key:a}}:e),t.length===r)break}}return t}if(i?.kind!==`list`||!Array.isArray(i.value))return[];let a=[];return i.value.some((e,t)=>(typeof e==`object`&&e&&a.push({entry:e,source:{kind:`list`,index:t}}),a.length===r)),n?a:a.map(({entry:e})=>e)}function listAgentEntriesWithSource(e){return collectAgentEntries(e,!0)}function listAgentEntries(e){return collectAgentEntries(e,!1)}function readAgentRosterProperty(t){if(!e(t))return;let n=t.agents;if(e(n))for(let e of[`entries`,`list`]){let t=n[e];if(Object.hasOwn(n,e)&&t!==void 0)return{kind:e,value:t}}}function hasAgentRosterProperty(e){return readAgentRosterProperty(e)!==void 0}function listAgentIds(e){let t=readAgentRosterFacts(e);if(t?.agentIds)return t.agentIds;let n=listAgentEntries(e),r=n.length===0&&!hasAgentRosterProperty(e)?[h]:[...new Set(n.map(e=>f(e?.id)))];return t&&(Object.freeze(r),t.agentIds=r),r}function listGatewayOwnedAgentIds(e){return[.../* @__PURE__ */ new Set([...listAgentIds(e),...F.map(({id:e})=>e)])]}function tryResolveSoleAgentId(e){let t=collectAgentEntries(e,!1,2);return t.length===0?hasAgentRosterProperty(e)?void 0:h:t.length===1?f(t[0].id):void 0}function tryResolveRawLegacyDefaultAgentId(e){if(e.agents?.ownership===`explicit`)return;let t=collectAgentEntries(e,!1).filter(e=>e.default===!0);return t.length===1?f(t[0].id):void 0}function tryResolveDefaultAgentId(e){return tryResolveRawLegacyDefaultAgentId(e)??tryResolveSoleAgentId(e)}function tryResolveLegacyDataOwner(e){return tryResolveDefaultAgentId(e)}function resolveMissingStorePathIdentity(e){try{let t=E(S.resolve(e));return S.resolve(t.existingPath,...t.unresolvedSegments)}catch{return}}function isPerAgentSessionStoreConfig(e){return!e?.trim()||e.includes(`{agentId}`)}function isSameFixedSessionStoreConfig(e,t,n){if(isPerAgentSessionStoreConfig(e)||isPerAgentSessionStoreConfig(t))return!1;let r=S.resolve(_(e,{env:n})),i=S.resolve(_(t,{env:n}));if(r===i)return!0;try{return D(C.statSync(r,{bigint:!0}),C.statSync(i,{bigint:!0}))}catch(e){let t=e.code;if(t!==`ENOENT`&&t!==`ENOTDIR`)return!0}let a=resolveMissingStorePathIdentity(r),o=resolveMissingStorePathIdentity(i);if(!a||!o||a===o)return!0;if(a.toLowerCase()!==o.toLowerCase())return!1;let s=T(a),c=T(o);return s!==!1&&c!==!1}function resolvePersistedSessionStoreOwner(e){if(isPerAgentSessionStoreConfig(e.session?.store))return{kind:`none`};let t=e.agents?.defaults?.sessionStore?.agentId?.trim();if(!t)return{kind:`none`};let n=f(t);return listAgentIds(e).some(e=>f(e)===n)?{kind:`configured`,agentId:n}:{kind:`retired`,agentId:n}}function resolvePersistedSessionStoreOwnerForKey(e,t){return g(t)===`legacy_or_alias`?resolvePersistedSessionStoreOwner(e):{kind:`none`}}function resolvePersistedSessionStoreOwnerForTarget(e){let t=resolvePersistedSessionStoreOwnerForKey(e.config,e.sessionKey);return t.kind===`none`||!e.storePath||isSameFixedSessionStoreConfig(e.config.session?.store,e.storePath,e.env??process.env)?t:{kind:`none`}}const z=/* @__PURE__ */ new Map,B=t(Symbol.for(`openclaw.agentDirPreparedPaths`),e=>{for(let t of e.values())t.close();e.clear()},`shared-state`);function registryPath(e,t,n=!1,r){let i=S.resolve(o(e,t)),a=b()?.ownsSchemaMaintenance===!0,s=a?void 0:B.get(i);if(s)return s.key;let c=r??normalizeAgentDirRegistryPath(i,t);if(a||!x||!n&&!z.has(c))return c;let l=[],d={key:c,close:()=>l.forEach(e=>e.close())};B.set(i,d);let f=!1;for(let e=i;S.dirname(e)!==e;e=S.dirname(e)){let t=S.basename(e);l.push(y(S.dirname(e),e=>{f||e!==void 0&&e!==t||(f=!0,u(i).then(e=>{B.get(i)===d&&e!==c&&(B.delete(i),d.close())}).catch(()=>{}).finally(()=>{f=!1}))}))}let p=Math.max(256,z.size+1);for(let[e,t]of B){if(B.size<=p)break;B.delete(e),t.close()}return c}function normalizeAgentDirRegistryPath(e,t=process.env){return d(o(e,t))}function registerResolvedAgentDir(e){let t=registryPath(e.agentDir,e.env,!0),n=z.get(t)??/* @__PURE__ */ new Set,r=f(e.agentId);return!n.has(r)&&(n.add(r),z.set(t,n),!0)}function resolveDefaultAgentWorkspaceDir(e=process.env,t=w.homedir){let r=e.OPENCLAW_WORKSPACE_DIR?.trim();if(r)return S.resolve(r);if(e.OPENCLAW_STATE_DIR?.trim())return S.join(l(e,t),`workspace`);let i=c(e,t),o=e.OPENCLAW_PROFILE?.trim();return o&&n(o)!=="default"?S.join(a(o,e,t),`workspace`):S.join(i,`.openclaw`,`workspace`)}resolveDefaultAgentWorkspaceDir();var AgentSelectionRequiredError=class extends Error{constructor(e,t){let n=t?.surface??`this operation`,r=t?.hint??`Select an agent explicitly; CLI callers can pass --agent <id>, channels can add a binding, and ambient services can set their agentId target.`;super(`Multiple agents are configured, but ${n} has no explicit owner. ${r}`),this.code=`AGENT_SELECTION_REQUIRED`,this.name=`AgentSelectionRequiredError`,this.agentIds=e,this.hint=r}};function resolveConfiguredAgentId(e,t){if(!listAgentIds(e).includes(t))throw Error(`Unknown agent id "${t}". Run ${formatCliCommand(`openclaw agents list`)} to see configured agents.`);return t}function resolveSoleAgentId(e,t){let n=tryResolveSoleAgentId(e);if(n)return n;let r=listAgentIds(e);throw r.length===0?Error("No agents configured. Run `openclaw onboard` or `openclaw agents add` first."):new AgentSelectionRequiredError(r,t)}function tryResolveLegacyDataOwnerAgentId(e){let t=readAgentRosterFacts(e);if(t?.legacyDataOwnerAgentId)return t.legacyDataOwnerAgentId.value;let n=tryResolveLegacyDataOwner(e);return t&&(t.legacyDataOwnerAgentId={value:n}),n}function tryResolveLegacyCompatibilityAgentId(e){let t=readAgentRosterFacts(e);if(t?.compatibilityAgentId)return t.compatibilityAgentId.value;let n;if(e.agents?.ownership===`explicit`){let t=r(e.agents.defaults?.systemAgent?.agentId),i=t?f(t):void 0;n=i&&listAgentIds(e).includes(i)?i:void 0}else n=tryResolveLegacyDataOwnerAgentId(e);return t&&(t.compatibilityAgentId={value:n}),n}function tryResolveAmbientOwnerAgentId(e,t){let n=r(t)??r(e.agents?.defaults?.systemAgent?.agentId);return n?f(n):tryResolveLegacyCompatibilityAgentId(e)??tryResolveSoleAgentId(e)}function resolveDefaultAgentId(e,t){return tryResolveRawLegacyDefaultAgentId(e)??resolveSoleAgentId(e,t)}const V={surface:`session agent resolution`,hint:`Pass an agentId, an agent-scoped session key, or a prepared fallbackAgentId.`};function resolveSelectedSessionAgentId(e){if(g(e.sessionKey)===`malformed_agent`)throw Error(`Malformed agent session key; refusing default-agent resolution.`);let t=e.agentId===void 0?null:p(e.agentId);if(t&&!t.ok)throw Error(`Invalid explicit agent id; refusing default-agent resolution.`);let n=t?.value,r=i(e.fallbackAgentId),a=r?f(r):null,o=e.sessionKey?.trim(),s=m(o),c=s?.agentId?f(s.agentId):null,l=e.config??{},u=resolvePersistedSessionStoreOwnerForKey(l,o);if(c&&n&&n!==c)throw new AgentSelectionRequiredError(listAgentIds(l),{surface:`session agent resolution`,hint:`The agent-scoped session key belongs to "${c}", not "${n}".`});let d=n??a;if(!c&&u.kind===`retired`)throw new AgentSelectionRequiredError(listAgentIds(l),{surface:`session agent resolution`,hint:`The shared fixed-store row belongs to retired agent "${u.agentId}".`});if(!c&&u.kind===`configured`&&d&&d!==u.agentId)throw new AgentSelectionRequiredError(listAgentIds(l),{surface:`session agent resolution`,hint:`The shared fixed-store row belongs to "${u.agentId}", not "${d}".`});return c??(u.kind===`configured`?u.agentId:void 0)??d??void 0}function resolveSessionAgentIdStrict(e){let t=resolveSelectedSessionAgentId(e),n=e.config??{};return t??tryResolveLegacyDataOwnerAgentId(n)??resolveDefaultAgentId(n,V)}const H=resolveSessionAgentIdStrict;function resolveAgentEntry(t,n){let r=f(n),i=readAgentRosterFacts(t);if(i){let e=(i.entryByNormalizedId??=buildAgentEntryIndex(t)).get(r);return e?e.clone?{...e.entry}:e.entry:void 0}let a=readAgentRosterProperty(t);if(a?.kind===`entries`&&e(a.value)){let t=a.value;for(let n in t){if(!Object.hasOwn(t,n))continue;let i=t[n];if(e(i)&&f(n)===r)return{...i,id:n}}}else if(a?.kind===`list`&&Array.isArray(a.value))return a.value.find(e=>typeof e==`object`&&!!e&&f(e.id)===r)}function buildAgentEntryIndex(e){let t=/* @__PURE__ */ new Map;for(let{entry:n,source:r}of listAgentEntriesWithSource(e)){let e=f(n?.id);t.has(e)||t.set(e,{clone:r.kind===`entries`,entry:n})}return t}function resolveAgentConfig(e,t){let n=f(t),r=resolveAgentEntry(e,n)??(!hasAgentRosterProperty(e)&&n===`main`?{id:n}:void 0);if(!r)return;let i=e.agents?.defaults;return{name:r.name,workspace:r.workspace,workspaceFileMode:r.workspaceFileMode??i?.workspaceFileMode,agentDir:r.agentDir,model:r.model,...r.models?{models:r.models}:{},...r.params?{params:r.params}:{},...r.runtime?{runtime:r.runtime}:{},...hasExplicitModelPolicyAllow(r.modelPolicy)?{modelPolicy:r.modelPolicy}:{},utilityModel:r.utilityModel,decisionModel:r.decisionModel,thinkingDefault:r.thinkingDefault,verboseDefault:r.verboseDefault??i?.verboseDefault,toolProgressDetail:r.toolProgressDetail??i?.toolProgressDetail,reasoningDefault:r.reasoningDefault,fastModeDefault:r.fastModeDefault??i?.fastModeDefault,newSessionPermissionMode:r.newSessionPermissionMode,contextInjection:r.contextInjection,bootstrapMaxChars:r.bootstrapMaxChars,bootstrapTotalMaxChars:r.bootstrapTotalMaxChars,experimental:r.experimental?{...i?.experimental,...r.experimental}:i?.experimental,skills:r.skills,memory:r.memory,humanDelay:r.humanDelay,typingMode:r.typingMode??i?.typingMode,tts:r.tts,...r.compaction?{compaction:r.compaction}:{},contextLimits:r.contextLimits?{...i?.contextLimits,...r.contextLimits}:i?.contextLimits,heartbeat:r.heartbeat,identity:r.identity,groupChat:r.groupChat,subagents:r.subagents,embeddedAgent:r.embeddedAgent,sandbox:r.sandbox,tools:r.tools}}function resolveEffectiveAgentDir(e,t,n){let r=f(t),i=resolveAgentConfig(e,r)?.agentDir?.trim(),a=n?.env??process.env;return i?o(i,a,n?.homedir):S.join(l(a,n?.homedir),`agents`,r,`agent`)}function resolveAgentDir(e,t,n=process.env){let r=resolveEffectiveAgentDir(e,t,{env:n});return registerResolvedAgentDir({agentId:t,agentDir:r,env:n}),r}export{P as C,isReservedSystemAgentId as S,listAgentIds as _,resolveDefaultAgentId as a,tryResolveSoleAgentId as b,tryResolveAmbientOwnerAgentId as c,normalizeAgentDirRegistryPath as d,resolvePersistedSessionStoreOwner as f,listAgentEntries as g,isPerAgentSessionStoreConfig as h,resolveConfiguredAgentId as i,tryResolveLegacyCompatibilityAgentId as l,resolvePersistedSessionStoreOwnerForTarget as m,resolveAgentDir as n,resolveEffectiveAgentDir as o,resolvePersistedSessionStoreOwnerForKey as p,resolveAgentEntry as r,H as s,AgentSelectionRequiredError as t,tryResolveLegacyDataOwnerAgentId as u,listGatewayOwnedAgentIds as v,formatCliCommand as w,withAgentRosterFactsBatch as x,readAgentRosterProperty as y};