openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
32 lines • 22.3 kB
JavaScript
import{C as isRecord,_ as normalizeOptionalLowercaseString,c as ignoreMissingPath,n as resolveGlobalMap,v as normalizeOptionalString}from"./global-singleton-CTnqrmaI.js";import{b as resolveIdentityPathViaExistingAncestor,g as normalizeAgentId,x as resolveIdentityPathViaExistingAncestorSync}from"./runtime-doctor-migrations-D8alsOFs.js";import{C as LEGACY_IMPLICIT_AGENT_ID,c as resolveStateDir,d as resolveProfileStateDir,f as expandHomePrefix,g as resolveUserPath,i as isPathInside,m as resolveRequiredHomeDir,w as classifySessionKeyShape}from"./account-core-34NfXidI.js";import"./number-coercion-BhEzZ9ku.js";import{n as runInDetachedAsyncContext}from"./boundary-path-93ijeUSt.js";import"./boundary-file-read-D9ria5A8.js";import"./openclaw-agent-db.paths-D0bfBkSQ.js";import{t as resolveRuntimeWorkerArgv}from"./runtime-worker-url-qeNVkG2b.js";import{t as resolveRuntimeProcessEntrypointUrl}from"./runtime-process-url-ZdotaiSy.js";import{i as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-2fT8FMwD.js";import fsPromises from"node:fs/promises";import path from"node:path";import fs from"node:fs";import{resolvePathPrefixSync,sameFileIdentity}from"@openclaw/fs-safe/advanced";import os from"node:os";import{isProxy}from"node:util/types";import{isMainThread}from"node:worker_threads";import{spawn}from"node:child_process";import{EventEmitter}from"node:events";
//!src/shared/immutable-data.ts
const MAX_FROZEN_PLAIN_DATA_ADMISSIONS=262144;let deeplyFrozenPlainData=/* @__PURE__ */ new WeakSet;let frozenPlainDataAdmissions=0;function boundFrozenPlainData(e){if(frozenPlainDataAdmissions>MAX_FROZEN_PLAIN_DATA_ADMISSIONS){deeplyFrozenPlainData=new WeakSet([e]);frozenPlainDataAdmissions=1}}function isPlainDataObject(e){if(isProxy(e))return false;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Array.isArray(e)&&t===Array.prototype}function inspectPlainData(e,t,n=true){if(!e||typeof e!==`object`)return typeof e!==`function`;if(deeplyFrozenPlainData.has(e))return true;if(!t&&n&&(isProxy(e)||!Object.isFrozen(e)))return false;let r=true;const i=/* @__PURE__ */ new Set;const a=[e];while(a.length){const e=a.pop();if(i.has(e))continue;if(!isPlainDataObject(e)){if(!t)return false;r=false;continue}if(!t&&n&&!Object.isFrozen(e))return false;i.add(e);for(const n of Reflect.ownKeys(e)){const i=Object.getOwnPropertyDescriptor(e,n);const o=i.value;if(!(`value`in i)||typeof o===`function`){if(!t)return false;r=false;continue}if(o&&typeof o===`object`&&!deeplyFrozenPlainData.has(o))a.push(o)}if(t)Object.freeze(e)}if(r&&(t||n)){for(const e of i)deeplyFrozenPlainData.add(e);frozenPlainDataAdmissions+=i.size;boundFrozenPlainData(e)}return r}function isDeeplyFrozenPlainData(e){return inspectPlainData(e,false)}
//!src/config/runtime-config-publication.ts
const runtimeConfigPublication={};
//!src/system-agent/agent-id.ts
const SYSTEM_AGENT_ID=`openclaw`;const SYSTEM_AGENT_ROSTER_ENTRIES=[{id:SYSTEM_AGENT_ID,kind:`system`},{id:`crestodian`,kind:`system`}];const RESERVED_SYSTEM_AGENT_IDS=new Set(SYSTEM_AGENT_ROSTER_ENTRIES.map(e=>normalizeAgentId(e.id)));function isReservedSystemAgentId(e){return RESERVED_SYSTEM_AGENT_IDS.has(normalizeAgentId(e))}
//!src/agents/agent-roster.ts
let activeAgentRosterFactsBatch;const agentRosterFacts=/* @__PURE__ */ new WeakMap;function readAgentRosterFacts(e){if(activeAgentRosterFactsBatch?.config===e)return activeAgentRosterFactsBatch.facts;const t=runtimeConfigPublication.current;const n=t?.config===e?t.revision:void 0;if(n===void 0&&!isDeeplyFrozenPlainData(e))return;let r=agentRosterFacts.get(e);if(!r||r.publication!==n){r={publication:n,facts:{}};agentRosterFacts.set(e,r)}return r.facts}function collectAgentEntries(e,t,n){const r=readAgentRosterProperty(e);if(r?.kind===`entries`&&isRecord(r.value)){const e=[];for(const i in r.value){if(!Object.hasOwn(r.value,i))continue;const a=r.value[i];if(isRecord(a)){const r={...a,id:i};e.push(t?{entry:r,source:{kind:`entries`,key:i}}:r);if(e.length===n)break}}return e}if(r?.kind!==`list`||!Array.isArray(r.value))return[];const i=[];r.value.some((e,t)=>{if(e!==null&&typeof e===`object`)i.push({entry:e,source:{kind:`list`,index:t}});return i.length===n});return t?i:i.map(({entry:e})=>e)}function listAgentEntriesWithSource(e){return collectAgentEntries(e,true)}function listAgentEntries(e){return collectAgentEntries(e,false)}function readAgentRosterProperty(e){if(!isRecord(e))return;const t=e.agents;if(!isRecord(t))return;for(const e of[`entries`,`list`]){const n=t[e];if(Object.hasOwn(t,e)&&n!==void 0)return{kind:e,value:n}}}function hasAgentRosterProperty(e){return readAgentRosterProperty(e)!==void 0}function listAgentIds(e){const t=readAgentRosterFacts(e);if(t?.agentIds)return t.agentIds;const n=listAgentEntries(e);const r=n.length===0&&!hasAgentRosterProperty(e)?[LEGACY_IMPLICIT_AGENT_ID]:[...new Set(n.map(e=>normalizeAgentId(e?.id)))];if(t){Object.freeze(r);t.agentIds=r}return r}function listGatewayOwnedAgentIds(e){return[.../* @__PURE__ */ new Set([...listAgentIds(e),...SYSTEM_AGENT_ROSTER_ENTRIES.map(({id:e})=>e)])]}function tryResolveSoleAgentId(e){const t=collectAgentEntries(e,false,2);if(t.length===0){if(!hasAgentRosterProperty(e))return LEGACY_IMPLICIT_AGENT_ID;return}return t.length===1?normalizeAgentId(t[0].id):void 0}function tryResolveRawLegacyDefaultAgentId(e){if(e.agents?.ownership===`explicit`)return;const t=collectAgentEntries(e,false).filter(e=>e.default===true);return t.length===1?normalizeAgentId(t[0].id):void 0}function tryResolveDefaultAgentId(e){return tryResolveRawLegacyDefaultAgentId(e)??tryResolveSoleAgentId(e)}function tryResolveLegacyDataOwner(e){return tryResolveDefaultAgentId(e)}
//!src/config/model-policy-allowlist-migration.ts
function hasExplicitModelPolicyAllow(e){return isRecord(e)&&Object.hasOwn(e,`allow`)}
//!src/config/sessions/session-sqlite-target-paths.ts
const MULTI_STORE_PATH_SENTINEL=`(multiple)`;function resolveConcreteSessionStorePath(e){const t=e?.trim();if(!t||t===`(multiple)`||t.includes(`{agentId}`))return;return t}function resolveUnsuffixedSqliteTargetFromSessionStorePath(e){const t=resolveConcreteSessionStorePath(e);if(!t)throw new Error(`Session storage requires a concrete store path`);const n=path.resolve(t);if(n.endsWith(`.sqlite`)){const e=resolveAgentIdFromSqliteDatabasePath(n);return{path:n,...e?{agentId:e}:{shared:true}}}const r=path.dirname(n);if(path.basename(n)!==`sessions.json`){const e=path.basename(n,path.extname(n))||`openclaw-agent`;return{path:path.join(r,`${e}.sqlite`)}}if(path.basename(r)!==`sessions`)return{path:path.join(r,`openclaw-agent.sqlite`)};const i=path.dirname(r);if(path.basename(path.dirname(i))!==`agents`)return{path:path.join(r,`openclaw-agent.sqlite`)};return{agentId:normalizeAgentId(path.basename(i)),path:path.join(i,`agent`,`openclaw-agent.sqlite`)}}function listSqliteTargetCandidatePathsForSessionStorePath(e,t){const n=resolveUnsuffixedSqliteTargetFromSessionStorePath(e);if(n.agentId||n.shared)return[n.path];const r=path.dirname(n.path);const i=path.basename(n.path,`.sqlite`);const a=t?`${i}.${normalizeAgentId(t)}`:void 0;const o=/* @__PURE__ */ new Set([path.basename(n.path)]);try{for(const e of fs.readdirSync(r)){const t=e.replace(/-(?:wal|shm|journal)$/u,``);if(t.startsWith(`${i}.`)&&t.endsWith(`.sqlite`)&&(!a||parseSqliteTargetSuffixIndex(t,a)!==void 0))o.add(t)}}catch(e){ignoreMissingPath(e)}return[...o].map(e=>path.join(r,e))}function parseSqliteTargetSuffixIndex(e,t){if(e===`${t}.sqlite`)return 1;if(!e.startsWith(`${t}.`)||!e.endsWith(`.sqlite`))return;const n=e.slice(t.length+1,-7);if(!/^[1-9]\d*$/.test(n))return;const r=Number(n);return Number.isSafeInteger(r)&&r>=2&&String(r)===n?r:void 0}function resolveAgentIdFromSqliteDatabasePath(e){if(path.basename(e)!==`openclaw-agent.sqlite`)return;const t=path.dirname(e);if(path.basename(t)!==`agent`)return;const n=path.dirname(t);if(path.basename(path.dirname(n))!==`agents`)return;return normalizeAgentId(path.basename(n))}
//!src/config/sessions/paths.ts
function resolveSessionTranscriptsDirForAgent(e,t=process.env,n=()=>resolveRequiredHomeDir(t,os.homedir)){if(!e?.trim())throw new Error(`Session storage path requires an explicit agent id.`);const r=resolveStateDir(t,n);const i=normalizeAgentId(e);return path.join(r,`agents`,i,`sessions`)}var SessionStoreAgentIdRequiredError=class extends Error{constructor(){super(`Session store path requires an explicit agent id.`);this.name=`SessionStoreAgentIdRequiredError`}};function resolveSessionStorePathCore(e,t){const n=t?.env??process.env;const homedir=()=>resolveRequiredHomeDir(n,os.homedir);if(!e){if(!t?.agentId?.trim())throw new SessionStoreAgentIdRequiredError;return`${resolveSessionTranscriptsDirForAgent(t.agentId,n,homedir)}${path.sep}sessions.json`}let r=e;if(r.includes(`{agentId}`)){if(!t?.agentId?.trim())throw new SessionStoreAgentIdRequiredError;const e=normalizeAgentId(t.agentId);r=r.replaceAll(`{agentId}`,e)}if(r.startsWith(`~`))r=expandHomePrefix(r,{home:resolveRequiredHomeDir(n,homedir),env:n,homedir});return path.isAbsolute(r)?path.resolve(r):path.resolve(resolveStateDir(n,homedir),r)}
//!src/config/sessions/session-store-config.ts
function isPerAgentSessionStoreConfig(e){return!e?.trim()||e.includes(`{agentId}`)}
//!src/config/sessions/session-store-owner.ts
function resolvePersistedSessionStoreOwner(e){if(isPerAgentSessionStoreConfig(e.session?.store))return{kind:`none`};const t=e.agents?.defaults?.sessionStore?.agentId?.trim();if(!t)return{kind:`none`};const n=normalizeAgentId(t);return listAgentIds(e).some(e=>normalizeAgentId(e)===n)?{kind:`configured`,agentId:n}:{kind:`retired`,agentId:n}}function resolvePersistedSessionStoreOwnerForKey(e,t){return classifySessionKeyShape(t)===`legacy_or_alias`?resolvePersistedSessionStoreOwner(e):{kind:`none`}}
//!src/infra/directory-watch-host.ts
let host;let nextId=0;const MAX_RETIRED_WATCHES=64;function startHost(){const e=spawn(process.execPath,[...resolveRuntimeWorkerArgv(resolveRuntimeProcessEntrypointUrl(`directoryWatchHost`)),String(process.pid)],{stdio:[`pipe`,`pipe`,`ignore`],detached:true,env:{...process.env,NODE_OPTIONS:void 0}});const t={child:e,watches:/* @__PURE__ */ new Map,retired:0};let n=``;e.stdout.setEncoding(`utf8`).on(`data`,e=>{const r=(n+e).split(`
`);n=r.pop()??``;for(const e of r){const n=JSON.parse(e);const r=t.watches.get(n.id);if(!r)continue;if(n.event)r.emit(`change`,n.event,n.filename??void 0);else{t.watches.delete(n.id);r.emit(`error`,/* @__PURE__ */ new Error(`Directory watch host lost the watch`),true)}}});const lost=()=>{if(host===t)host=void 0;const e=Array.from(t.watches.values());t.watches.clear();for(const t of e)t.emit(`error`,/* @__PURE__ */ new Error(`Directory watch host exited`),false)};e.on(`error`,lost).on(`exit`,lost);e.stdin.on(`error`,()=>{});e.unref();for(const t of[e.stdin,e.stdout])t.unref?.();return t}function register(e,t,n){e.watches.set(t,n);e.child.stdin.write(`${JSON.stringify({id:t,path:n.path,recursive:n.recursive})}\n`)}function watchDirectory(e,t,n=false){const r=nextId++;const i=Object.assign(new EventEmitter,{path:e,recursive:n});i.on(`change`,t);try{register(host??=startHost(),r,i)}catch(e){host?.watches.delete(r);queueMicrotask(()=>i.emit(`error`,e,false))}return Object.assign(i,{close(){i.removeAllListeners(`change`);const e=host;if(!e?.watches.delete(r))return;if(e.watches.size&&(process.platform!==`darwin`||++e.retired<MAX_RETIRED_WATCHES)){e.child.stdin.write(`${JSON.stringify({id:r})}\n`);return}host=void 0;if(e.watches.size){const t=host=startHost();for(const[n,r]of e.watches)register(t,n,r);e.watches.clear()}e.child.stdin.end()}})}
//!src/infra/owned-directory-observation.ts
const directories=/* @__PURE__ */ new Map;const sources=/* @__PURE__ */ new Map;let fallback;let fallbackDueAtMs=Infinity;const REPAIR_INTERVAL_MS=3e4;function nextFallback(e=REPAIR_INTERVAL_MS){const t=Date.now();const n=(Math.floor(t/e)+1)*e;return{atMs:n,elapsedAtMs:performance.now()+n-t}}function fallbackRemaining(e){return Math.min(e.nextFallback.atMs-Date.now(),e.nextFallback.elapsedAtMs-performance.now())}function retainEarlierFallback(e,t){e.nextFallback.atMs=Math.min(e.nextFallback.atMs,t.atMs);e.nextFallback.elapsedAtMs=Math.min(e.nextFallback.elapsedAtMs,t.elapsedAtMs)}function scheduleFallback(e){if(!directories.size)return;const t=e?fallbackRemaining(e):Math.min(...Array.from(directories.values(),fallbackRemaining));const n=performance.now()+Math.max(0,Math.ceil(t));if(fallback&&fallbackDueAtMs<=n)return;clearTimeout(fallback);fallbackDueAtMs=n;fallback=runInDetachedAsyncContext(()=>setTimeout(()=>{reconcile()},Math.max(0,Math.ceil(t))).unref())}async function reconcile(){fallback=void 0;const e=Array.from(directories.values()).filter(e=>fallbackRemaining(e)<=0);const t=/* @__PURE__ */ new Map;for(const n of e){n.nextFallback=nextFallback(n.reconcileIntervalMs);const e=n.source;if((!e||!await fsPromises.access(e.path).then(()=>true,()=>false)||e.path!==n.path&&await fsPromises.access(n.path).then(()=>true,()=>false))&&n.source===e)for(const r of e?.directories??[n])t.set(r,e)}for(const[e,n]of t)if(directories.get(e.key)!==e||e.source!==n)t.delete(e);for(const e of t.keys())detach(e);for(const e of t.keys())attach(e);for(const t of e){if(directories.get(t.key)!==t)continue;notify(t)}scheduleFallback()}function detach(e){const t=e.source;e.source=void 0;if(!t)return;t.directories=t.directories.filter(t=>t!==e);if(!t.directories.length){sources.delete(t.key);t.watcher.close()}}function notify(e,t,n){for(const r of e.listeners)r(t,n)}function attach(e,t=e.watchRoot){const n=e.recursive&&t===e.watchRoot;const r=JSON.stringify([t,n]);const i=sources.get(r);if(i){i.directories=[...i.directories,e];e.source=i;return}const a=path.basename(t);const o=runInDetachedAsyncContext(()=>watchDirectory(t,(e,n)=>{const i=sources.get(r);if(!i||i.watcher!==o)return;i.admitted=true;const s=i.directories;const c=e===`rename`&&(!n||n===a);let l;for(const r of s)if(r.path===t||!n||c||isPathInside(r.path,l??=path.resolve(t,n))||isPathInside(l,r.path))notify(r,r.path===t?n:void 0,e);if(e===`rename`){let e;for(const r of s)if(c||r.watchRoot!==t&&n!==void 0&&isPathInside(l??=path.resolve(t,n),r.watchRoot))(e??=[]).push(r);if(!e)return;for(const t of e)detach(t);for(const t of e)if(directories.get(t.key)===t){attach(t);retainEarlierFallback(t,nextFallback(t.reconcileIntervalMs));scheduleFallback(t)}}},n));const s={key:r,path:t,watcher:o,admitted:false,directories:[e]};sources.set(r,s);e.source=s;o.on(`error`,(e,n)=>{for(const e of s.directories){detach(e);const r=path.dirname(t);if(n&&!s.admitted&&r!==t){attach(e,r);continue}notify(e);retainEarlierFallback(e,nextFallback());scheduleFallback(e)}})}function observeOwnedDirectory(e,t,n={}){const r=path.resolve(e);const i=n.watchRoot?path.resolve(n.watchRoot):r;const a=n.recursive??false;const o=n.reconcileIntervalMs??REPAIR_INTERVAL_MS;const s=JSON.stringify([r,i,a,o]);let c=directories.get(s);if(!c){c={key:s,path:r,watchRoot:i,recursive:a,reconcileIntervalMs:o,listeners:[],nextFallback:{atMs:Infinity,elapsedAtMs:Infinity}};directories.set(s,c);attach(c)}const listener=(e,n)=>t(e,n);c.listeners=[...c.listeners,listener];retainEarlierFallback(c,nextFallback(o));scheduleFallback(c);return{isWatching:()=>c.listeners.includes(listener)&&c.source!==void 0,close(){c.listeners=c.listeners.filter(e=>e!==listener);if(c.listeners.length||directories.get(s)!==c)return;directories.delete(s);detach(c);if(!directories.size){clearTimeout(fallback);fallback=void 0}}}}
//!src/agents/agent-dir-registry.ts
const agentIdsByDir=/* @__PURE__ */ new Map;const preparedPaths=resolveGlobalMap(Symbol.for(`openclaw.agentDirPreparedPaths`),e=>{for(const t of e.values())t.close();e.clear()},`shared-state`);function registryPath(e,t,n=false,r){const i=path.resolve(resolveUserPath(e,t));const a=getOpenClawDatabaseMaintenanceScope()?.ownsSchemaMaintenance===true;const o=a?void 0:preparedPaths.get(i);if(o)return o.key;const s=r??normalizeAgentDirRegistryPath(i,t);if(a||!isMainThread||!n&&!agentIdsByDir.has(s))return s;const c=[];const l={key:s,close:()=>c.forEach(e=>e.close())};preparedPaths.set(i,l);let u=false;for(let e=i;path.dirname(e)!==e;e=path.dirname(e)){const t=path.basename(e);c.push(observeOwnedDirectory(path.dirname(e),e=>{if(!u&&(e===void 0||e===t)){u=true;resolveIdentityPathViaExistingAncestor(i).then(e=>{if(preparedPaths.get(i)===l&&e!==s){preparedPaths.delete(i);l.close()}}).catch(()=>{}).finally(()=>{u=false})}}))}const d=Math.max(256,agentIdsByDir.size+1);for(const[e,t]of preparedPaths){if(preparedPaths.size<=d)break;preparedPaths.delete(e);t.close()}return s}function normalizeAgentDirRegistryPath(e,t=process.env){return resolveIdentityPathViaExistingAncestorSync(resolveUserPath(e,t))}function registerResolvedAgentDir(e){const t=registryPath(e.agentDir,e.env,true);const n=agentIdsByDir.get(t)??/* @__PURE__ */ new Set;const r=normalizeAgentId(e.agentId);if(n.has(r))return false;n.add(r);agentIdsByDir.set(t,n);return true}
//!src/agents/workspace-default-path.ts
function resolveDefaultAgentWorkspaceDir(e=process.env,t=os.homedir){const n=e.OPENCLAW_WORKSPACE_DIR?.trim();if(n)return path.resolve(n);if(e.OPENCLAW_STATE_DIR?.trim())return path.join(resolveStateDir(e,t),`workspace`);const r=resolveRequiredHomeDir(e,t);const i=e.OPENCLAW_PROFILE?.trim();if(i&&normalizeOptionalLowercaseString(i)!=="default")return path.join(resolveProfileStateDir(i,e,t),`workspace`);return path.join(r,`.openclaw`,`workspace`)}
//!src/agents/workspace-default.ts
const DEFAULT_AGENT_WORKSPACE_DIR=resolveDefaultAgentWorkspaceDir();
//!src/agents/agent-scope-config.ts
var AgentSelectionRequiredError=class extends Error{constructor(e,t){const n=t?.surface??`this operation`;const 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 tryResolveLegacyDataOwnerAgentId(e){const t=readAgentRosterFacts(e);if(t?.legacyDataOwnerAgentId)return t.legacyDataOwnerAgentId.value;const n=tryResolveLegacyDataOwner(e);if(t)t.legacyDataOwnerAgentId={value:n};return n}function tryResolveLegacyCompatibilityAgentId(e){const t=readAgentRosterFacts(e);if(t?.compatibilityAgentId)return t.compatibilityAgentId.value;let n;if(e.agents?.ownership===`explicit`){const t=normalizeOptionalString(e.agents.defaults?.systemAgent?.agentId);const r=t?normalizeAgentId(t):void 0;n=r&&listAgentIds(e).includes(r)?r:void 0}else n=tryResolveLegacyDataOwnerAgentId(e);if(t)t.compatibilityAgentId={value:n};return n}function tryResolveAmbientOwnerAgentId(e,t){const n=normalizeOptionalString(t)??normalizeOptionalString(e.agents?.defaults?.systemAgent?.agentId);return n?normalizeAgentId(n):tryResolveLegacyCompatibilityAgentId(e)??tryResolveSoleAgentId(e)}function resolveAgentEntry(e,t){const n=normalizeAgentId(t);const r=readAgentRosterFacts(e);if(r){const t=(r.entryByNormalizedId??=buildAgentEntryIndex(e)).get(n);return t?t.clone?{...t.entry}:t.entry:void 0}const i=readAgentRosterProperty(e);if(i?.kind===`entries`&&isRecord(i.value)){const e=i.value;for(const t in e){if(!Object.hasOwn(e,t))continue;const r=e[t];if(isRecord(r)&&normalizeAgentId(t)===n)return{...r,id:t}}return}if(i?.kind===`list`&&Array.isArray(i.value))return i.value.find(e=>e!==null&&typeof e===`object`&&normalizeAgentId(e.id)===n)}function buildAgentEntryIndex(e){const t=/* @__PURE__ */ new Map;for(const{entry:n,source:r}of listAgentEntriesWithSource(e)){const e=normalizeAgentId(n?.id);if(!t.has(e))t.set(e,{clone:r.kind===`entries`,entry:n})}return t}function resolveAgentConfig(e,t){const n=normalizeAgentId(t);const r=resolveAgentEntry(e,n)??(!hasAgentRosterProperty(e)&&n===`main`?{id:n}:void 0);if(!r)return;const 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){const r=normalizeAgentId(t);const i=resolveAgentConfig(e,r)?.agentDir?.trim();const a=n?.env??process.env;return i?resolveUserPath(i,a,n?.homedir):path.join(resolveStateDir(a,n?.homedir),`agents`,r,`agent`)}function resolveAgentDir(e,t,n=process.env){const r=resolveEffectiveAgentDir(e,t,{env:n});registerResolvedAgentDir({agentId:t,agentDir:r,env:n});return r}export{tryResolveSoleAgentId as _,tryResolveLegacyCompatibilityAgentId as a,isPerAgentSessionStoreConfig as c,parseSqliteTargetSuffixIndex as d,resolveUnsuffixedSqliteTargetFromSessionStorePath as f,readAgentRosterProperty as g,listGatewayOwnedAgentIds as h,tryResolveAmbientOwnerAgentId as i,resolveSessionStorePathCore as l,listAgentIds as m,resolveAgentDir as n,observeOwnedDirectory as o,listAgentEntries as p,resolveEffectiveAgentDir as r,resolvePersistedSessionStoreOwnerForKey as s,AgentSelectionRequiredError as t,listSqliteTargetCandidatePathsForSessionStorePath as u,isReservedSystemAgentId as v,isDeeplyFrozenPlainData as y};