UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

12 lines • 22.2 kB
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import"./utils-Dlk0IYAa.mjs";import{t as FsSafeError,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId,r as normalizeAgentIdStrict}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{g as isReservedSystemAgentId,n as listAgentEntries}from"./agent-roster-4XrgUgPK.mjs";import{n as createOpenClawAgentDatabasePathMatcher}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{u as resolveSessionTranscriptsDirForAgent}from"./paths-CcxgiC3g.mjs";import{E as toAgentEntriesRecord,N as normalizeAgentDirRegistryPath,a as resolveAgentDir,f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{t as OPENCLAW_AGENT_SCHEMA_VERSION}from"./openclaw-schema-versions-rhFQpVhP.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{c as getStateDatabaseSchemaLease,l as hasActiveGatewayStateOwner}from"./gateway-state-owner-D_klysuh.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{t as getDatabaseEngineInput}from"./context-DZjni16e.mjs";import{N as runWithAgentCreationClaim}from"./openclaw-agent-db-resources-KCMTIo4b.mjs";import{y as DuplicateAgentError}from"./openclaw-state-worker-error-Ca5E4dEV.mjs";import{r as createSqliteWorkerOperationAdmission}from"./sqlite-worker-operation-admission-BZvXBQev.mjs";import"./openclaw-agent-db-contract-CiyWpx1X.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{i as runOpenClawStateWorkerOperation}from"./openclaw-state-worker-store-7se2aIrr.mjs";import{t as ConfigMutationConflictError}from"./mutation-conflict-qTMp0e4U.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{r as hasResolvedRosterBeforeMigrations}from"./agent-roster-provenance-5AqnirlB.mjs";import{O as releaseAgentDatabaseHeldAdmission}from"./agent-database-admission-DiJx9iIl.mjs";import{a as readAgentDeletionJournalForCreation,c as readAgentDeletionRecoveryHoldsInWorker}from"./agent-deletion-journal.read-DL01GJPw.mjs";import{i as recordAgentProvenance}from"./agent-provenance-DgTm-0eu.mjs";import{b as resolveAuthProfileDatabasePath}from"./sqlite-y_WDH-Xr.mjs";import{o as prepareSharedAuthStoreOwnership}from"./path-resolve-TSS6dv07.mjs";import{s as claimCompletedAgentDeletion}from"./agent-lifecycle-registry-CT_mqsZ8.mjs";import{a as prepareOpenClawAgentDatabaseExecution}from"./openclaw-agent-execution-Pq_Dn2BS.mjs";import{s as resolveConfiguredAgentDatabaseTargets}from"./targets-DZpbOEi4.mjs";import{o as transformConfigFileWithRetry,s as withConfigMutationExclusive}from"./mutate-DcH8aT_4.mjs";import"./config-DkZ8y8Gv.mjs";import{n as assertCurrentAgentDeletionRecoveryHolds,r as createWorkspaceFileMutationGuard}from"./workspace-filesystem-CD_uVvIK.mjs";import{r as DEFAULT_IDENTITY_FILENAME}from"./workspace-bootstrap-policy-B71K4ysN.mjs";import{l as sanitizeAgentIdentityLine,n as createAgentIdentityConfig,o as mergeIdentityMarkdownContent}from"./identity-file-CqfXu01D.mjs";import{r as findAgentEntryIndex,t as applyAgentConfig}from"./agents.config-BvTJi_N_.mjs";import{a as isWorkspaceBootstrapPending,t as ensureAgentWorkspace}from"./workspace-1G3FI-0P.mjs";import{n as loadAgentRole,t as listAgentRoles}from"./agent-roles-Bf9EiaQR.mjs";import{t as createAgentSchemaInspectionWorker}from"./openclaw-agent-schema-inspection-worker-BkUPol72.mjs";import{r as parseBindingSpecs,t as applyAgentBindings}from"./agents.bindings-Bnd-pbi6.mjs";import{t as migrateLegacyMainSessionKeys}from"./legacy-main-session-migration-CkkPPEtJ.mjs";import{realpathSync,statSync}from"node:fs";import fs$1 from"node:fs/promises"; //!src/state/agent-deletion-recovery.ts async function resolveAgentDeletionRecoveryHoldsInWorker(e,t,n){const r=captureOpenClawStateWorkerContext();const i={predicate:e,paths:t};await runOpenClawStateWorkerOperation(r,e=>e.execute({type:`agentRecovery.resolveHolds`,input:i}),{assertCurrent:n,createAdmission:()=>({nativeLocations:[r.admission.databasePath],admission:createSqliteWorkerOperationAdmission((e,t)=>{if(e.stage!==`transaction`&&e.stage!==`commit`)throw new Error(`Agent recovery requires transaction admission`);r.admission.assertCurrent();n();t()})})});releaseAgentDatabaseHeldAdmission(t,{env:r.environment})} //!src/agents/agent-create-identity.ts async function writeIdentityFile(e){const t=createWorkspaceFileMutationGuard(e.guard);const n=await root(e.workspaceDir);let r;try{r=(await n.read(DEFAULT_IDENTITY_FILENAME,{hardlinks:`reject`})).buffer.toString(`utf-8`)}catch(e){if(!(e instanceof FsSafeError&&e.code===`not-found`))throw e}const i=mergeIdentityMarkdownContent(r,e.identity);t?.();await n.write(DEFAULT_IDENTITY_FILENAME,i,{encoding:`utf8`,assertBeforeMutation:t})} //!src/agents/agent-create-retained-postgres.ts async function assertRetainedPostgresAgentStores(e){try{var t=_usingCtx();if(!getDatabaseEngineInput(`agent`))return;const{agentId:n,assertCurrent:r}=e;const i=t.a(createAgentSchemaInspectionWorker());for(const t of resolveConfiguredAgentDatabaseTargets(e.config,{env:process.env,agentId:n})){if(!statSync(t.path,{throwIfNoEntry:false})?.isFile())continue;const refusal=()=>new DuplicateAgentError(`Cannot create agent "${n}": retained PostgreSQL anchor "${t.path}" has no verified matching initialized namespace. Restore a matching backup with openclaw backup restore <archive> --target <fresh-directory>. If the history is intentionally gone, stop the Gateway, move this anchor and its SQLite sidecars outside the state and agent directories, then retry agents add. See https://docs.openclaw.ai/gateway/postgresql#recover-a-retained-agent-store.`);const unverifiable=(e,r=e)=>new DuplicateAgentError(`Cannot create agent "${n}": could not verify retained PostgreSQL store "${t.path}": ${formatErrorMessage(e)}. Check that database.postgres.connection reaches the intended server, then retry. If the server is correct and this store's namespace is gone, see https://docs.openclaw.ai/gateway/postgresql#recover-a-retained-agent-store.`,r instanceof Error?{cause:r}:void 0);r?.();let e;try{e=await i.inspect({pathname:t.path,agentId:n,env:process.env,supportedVersion:42,inspectOwnership:true})}catch(e){throw unverifiable(e)}r?.();if(!e)continue;if(e.failure||e.reason!==void 0)throw unverifiable(e.reason||e.failure,e.failure);if(e.version<=0||e.version>42||e.agentSchemaMeta?.agentId!==n||e.agentSchemaMeta.role!==`agent`||e.agentSchemaMeta.schemaVersion!==e.version)throw refusal()}}catch(e){t.e=e}finally{await t.d()}} //!src/agents/agent-create-retained-stores.ts function selectedRecoveryPaths(e,t,n,r,i){if(!n.some(e=>e.agentId===t))return[];const a=resolveAgentDir(e,t);if(i!==void 0&&normalizeAgentDirRegistryPath(i)!==normalizeAgentDirRegistryPath(a)&&findAgentEntryIndex(listAgentEntries(e),t)>=0)return[];const o=resolveConfiguredAgentDatabaseTargets(applyAgentConfig(e,{agentId:t,agentDir:i??a}),{env:process.env,registeredDatabases:n});return n.filter(e=>e.agentId===t&&statSync(e.path,{throwIfNoEntry:false})?.isFile()&&o.some(n=>n.agentId===t&&r(n.path,e.path))).map(e=>e.path)}async function migrateRetainedAgentStores(e){try{var t=_usingCtx();const n=process.env;const r=[...new Set(e.paths)].filter(e=>statSync(e,{throwIfNoEntry:false})?.isFile());if(r.length>0&&!e.allowRestore)throw new DuplicateAgentError(`Agent ${e.agentId} has retained databases. Run openclaw agents add ${e.agentId} to restore the preserved store explicitly.`);const i=[];const a=t.a(createAgentSchemaInspectionWorker());for(const t of r){e.assertCurrent();const r=await a.inspect({pathname:t,agentId:e.agentId,env:n,supportedVersion:42,inspectOwnership:true,allowClosedWal:true});if(!r||r.failure||r.reason||r.agentSchemaMeta?.role!==`agent`||r.agentSchemaMeta.agentId!==e.agentId||r.agentSchemaMeta.schemaVersion!==r.version||r.version<=0||r.version>42)throw new DuplicateAgentError(`Cannot restore agent "${e.agentId}": could not verify the preserved database ${t}. Run openclaw doctor --fix to inspect its ownership and schema.`);if(r.version<42)i.push({kind:`agent`,path:t,agentId:e.agentId,foundVersion:r.version,supportedVersion:42})}if(i.length===0)return;const o=resolveOpenClawStateSqlitePath(n);if(hasActiveGatewayStateOwner(o))throw new DuplicateAgentError(`Agent "${e.agentId}" needs a database schema migration before restoration. Stop the Gateway, then run openclaw agents add ${e.agentId} again; its held data is unchanged.`);const[{completeDoctorMigrationBackups:s},{prepareDoctorDatabaseMigrations:c},{withStateDatabaseSchemaMaintenanceAsync:l},{migrateOpenClawAgentDatabaseForMaintenance:u},{withAgentDatabaseMaintenanceLease:d},{createOpenClawDatabaseMaintenanceScope:f}]=await Promise.all([import(`./doctor-migration-backup-artifacts-B1HEXTfr.mjs`),import(`./doctor-schema-migrations-Dm3PgDer.mjs`),import(`./state-database-maintenance-DiH6C_ew.mjs`),import(`./openclaw-agent-db-maintenance-2oTVO4eZ.mjs`),import(`./openclaw-agent-db-maintenance-lease-Bq_j-5f-.mjs`),import(`./openclaw-state-db-async-lifecycle-D8_rltWE.mjs`)]);await l({databasePath:o},async()=>{e.assertCurrent();const t=getStateDatabaseSchemaLease(o);const a=f({schemaMaintenance:true,assertOwnerCurrent:()=>t.assertCurrent(),assertDatabaseAccess:t.assertDatabaseAccess});try{const t=await a.run(()=>c({env:n,pendingDatabasePaths:i.map(({path:e})=>e),pendingMigrations:i,databasePaths:r,agentDatabaseTargets:r.map(t=>({agentId:e.agentId,path:t,realPath:realpathSync.native(t),source:`deletion`}))}));if(!t.versionMigrations?.length)await a.run(()=>d({env:n,processBound:true},async a=>{for(const r of i){await u({agentId:e.agentId,pathname:r.path,env:n},a);t.changes.push(`Upgraded agent database schema in ${r.path}: v${r.foundVersion} -> v${r.supportedVersion}.`)}s(n,r)}));const o=createSubsystemLogger(`agents/restore`);t.changes.forEach(e=>o.info(e));t.warnings.forEach(e=>o.warn(e));e.assertCurrent()}finally{await a.close()}})}catch(e){t.e=e}finally{await t.d()}} //!src/agents/agent-create.ts const BOOTSTRAP_AGENT_ID=`main`;var InvalidAgentBindingsError=class extends Error{};var UnfinishedRoleBootstrapError=class extends Error{};function createError(e,t,n){return{status:`error`,reason:e,message:t,...n?{agentId:n}:{}}}function validateAgentIdInput(e,t={}){const n=t.displayName??e;const r=normalizeAgentIdStrict(e);if(!r.ok)return{ok:false,reason:`invalid-name`,message:`Agent name "${n}" has no valid id characters. Use at least one letter a-z or digit.`};const i=r.value;if(isReservedSystemAgentId(i))return{ok:false,reason:`reserved-id`,message:`"${i}" is reserved`,agentId:i};return{ok:true,agentId:i}}function isInjectedBootstrapMainEntry(e){return e?.id===BOOTSTRAP_AGENT_ID&&Object.keys(e).every(e=>e===`id`)}function describeLegacySessionOutcome(e){const t=(e.sourceKeys??[]).map((t,n)=>`${e.paths?.[n]??e.paths?.[0]??`session store`}#${t}`);switch(e.kind){case`divergent-aliases`:case`divergent-canonical`:return`${e.kind} for ${e.canonicalKey??`the current session`}; preserved claims ${t.join(`, `)||`could not be reconciled`} must be quarantined`;case`legacy-json-store`:return`legacy JSON session store ${e.paths?.join(`, `)??`requires import`}`;case`store-unreadable`:return`unreadable session store ${e.paths?.join(`, `)??`unknown`}${e.detail?` (${e.detail})`:``}`;case`migrated-in-place`:case`migrated-cross-store`:case`canonical-exists-identical`:return`legacy claim ${t.join(`, `)||e.canonicalKey||`requires migration`}`;case`not-armed`:return e.detail===`owner-unresolved`?`legacy main sessions have no unambiguous configured owner; set agents.defaults.sessionStore.agentId to the intended live owner`:`legacy main session migration is not armed (${e.detail??`unknown reason`})`;case`no-legacy-rows`:return`the current session-store layout has no matching completed migration ledger`}return e.kind}async function evaluateMainCreationGate(e,t){const n=listAgentEntries(e).map(e=>normalizeAgentId(e.id));if(t!==BOOTSTRAP_AGENT_ID||n.includes(BOOTSTRAP_AGENT_ID)||!n.some(e=>e!==BOOTSTRAP_AGENT_ID))return;const r=await migrateLegacyMainSessionKeys({cfg:e,forceScan:true,legacyAgentId:BOOTSTRAP_AGENT_ID,mode:`detect`});const i=r.outcomes.every(e=>e.kind===`no-legacy-rows`);if(r.armed?!r.ledgerComplete:!i)return createError(`legacy-session-migration-required`,`Cannot create agent "main": ${r.outcomes.map(describeLegacySessionOutcome).join(`; `)}. Run openclaw doctor --fix, then retry.`,t);if((await prepareSharedAuthStoreOwnership()).location!==`state-db`)return createError(`shared-auth-store-owned-by-main`,`Cannot create agent "main" while agents/main/agent owns the shared auth store. Run openclaw doctor --fix to relocate shared auth, then retry.`,t)}async function checkAgentCreationGate(e){const t=normalizeAgentId(e);return await withConfigMutationExclusive(async e=>{const n=await evaluateMainCreationGate(e,t);if(n)return n;try{await assertRetainedPostgresAgentStores({config:applyAgentConfig(e,{agentId:t}),agentId:t})}catch(e){if(e instanceof DuplicateAgentError)return createError(`already-exists`,e.message,t);throw e}})}async function createAgent(e){const t=e.stagedConfig?e.stagedConfig.writeSnapshot.snapshot.hash??null:e.expectedConfigHash;const n=(e.entry?.name?.trim()||e.entry?.id||e.name||``).trim();if(!n)return createError(`invalid-name`,`agent name is required`);const r=validateAgentIdInput(e.entry?.id??n,{displayName:n});if(!r.ok)return createError(r.reason,r.message,r.agentId);const i=r.agentId;const a=i===BOOTSTRAP_AGENT_ID&&e.bootstrapMain===true;const o=e.bootstrapMain===true||e.bootstrapFirstAgent===true;const withCreationClaim=e=>runWithAgentCreationClaim({agentId:i},e);const s=e.role?await loadAgentRole(e.role):void 0;const c=sanitizeAgentIdentityLine(n);const l=normalizeOptionalString(e.model);const u=(s?{...s.identity,...e.entry?.identity}:void 0)??e.entry?.identity??createAgentIdentityConfig({name:c,emoji:e.emoji,avatar:e.avatar})??{name:c};const d=e.entry?.workspace??e.workspace;const f=d?.trim()?resolveUserPath(d.trim()):void 0;const p=e.entry?.agentDir??e.agentDir;const m=p?.trim()?resolveUserPath(p.trim()):void 0;const h=e.transformConfig??transformConfigFileWithRetry;let g;let _=false;let v=false;let y=[];const b=createOpenClawAgentDatabasePathMatcher();const recoveryHoldPredicate=()=>({agentId:i,held:y,applies:_||!o});const assertRecoveryPathCurrent=()=>{if(!b.isCurrent())throw new DuplicateAgentError(`Agent ${i} preserved database changed during restoration; its hold remains. Restore the original database and retry agents add.`)};const assertRecoveryCurrent=()=>{assertRecoveryPathCurrent();const e=recoveryHoldPredicate();if(e.applies)assertCurrentAgentDeletionRecoveryHolds(e)};const hasBootstrapHold=async()=>(await readAgentDeletionRecoveryHoldsInWorker()).some(e=>e.agentId===i);const assertHost=()=>{e.beforePersistentApply?.();if(!v)e.assertIdentityInputAllowed?.();assertRecoveryPathCurrent()};const beforePersistentApply=()=>{assertHost();assertRecoveryCurrent()};try{return await withConfigMutationExclusive(async n=>{y=o?[]:await readAgentDeletionRecoveryHoldsInWorker();const r=selectedRecoveryPaths(n,i,y,b,m).filter(t=>e.restorePaths?.includes(t)??true);if(r.length===0&&y.some(e=>e.agentId===i))return createError(`already-exists`,`Agent ${i} has held databases. Restore its original agentDir and session.store configuration, then rerun agents add to restore the preserved store.`,i);const d=r.length>0||o&&await hasBootstrapHold()?void 0:await evaluateMainCreationGate(n,i);if(d)return d;beforePersistentApply();const p=o&&await hasBootstrapHold()?void 0:await readAgentDeletionJournalForCreation(i);beforePersistentApply();if(p&&!p.cleanupCompleted)return createError(`deletion-pending`,`agent "${i}" deletion cleanup is still pending`,i);const x=r.length>0||p?.deleteFiles===false;let S=false;const C=await h({afterWrite:{mode:`auto`},maxAttempts:1,writeOptions:{...e.stagedConfig?.writeSnapshot.writeOptions,...e.bootstrapFirstAgent?{allowedAgentRosterRemovals:[BOOTSTRAP_AGENT_ID]}:{},assertConfigPathForWrite:()=>{e.stagedConfig?.writeSnapshot.writeOptions.assertConfigPathForWrite?.();beforePersistentApply()},assertBeforePublish:()=>{e.stagedConfig?.writeSnapshot.writeOptions.assertBeforePublish?.();e.assertBeforePublish?.()}},transform:async(n,d)=>{if((e.stagedConfig||Object.hasOwn(e,`expectedConfigHash`))&&d.previousHash!==t)throw new ConfigMutationConflictError(`config changed before agent creation or restoration`,{retryable:false});const h=e.bootstrapFirstAgent===true&&hasResolvedRosterBeforeMigrations(d.snapshot);if(e.bootstrapFirstAgent&&h)throw new DuplicateAgentError;const y=e.bootstrapFirstAgent===true;const b=y?[]:listAgentEntries(n);const C=findAgentEntryIndex(b,i);const w=b[C];if(C>=0&&x)await migrateRetainedAgentStores({agentId:i,allowRestore:!o,paths:r.length>0?r:resolveConfiguredAgentDatabaseTargets(n,{env:process.env,agentId:i}).map(e=>e.path),assertCurrent:beforePersistentApply});if(C>=0&&p?.cleanupCompleted){if(!await claimCompletedAgentDeletion(i,p.operationId))throw new Error(`agent "${i}" deletion tombstone changed during creation`);S=true}if(a&&b.length>0&&!b.some(e=>normalizeAgentId(e.id)===BOOTSTRAP_AGENT_ID))throw new DuplicateAgentError;if(C>=0&&!a&&r.length===0)throw new DuplicateAgentError;if(C>=0&&(r.length>0||a&&(b.length!==1||!isInjectedBootstrapMainEntry(w)||d.snapshot.exists)))return{nextConfig:n,result:{status:`existing`,agentId:i,name:w?.name??c,workspace:resolveAgentWorkspaceDir(n,i),agentDir:resolveAgentDir(n,i),bootstrapPending:false}};_=true;const T=f??resolveAgentWorkspaceDir(n,i);const E=m??resolveAgentDir(n,i);const D=y?{...n,agents:{...n.agents,entries:{}}}:e.stagedConfig?.config??n;let O=applyAgentConfig(D,{agentId:i,name:c,workspace:T,agentDir:E,model:l,identity:u});if(e.entry||s){const t=listAgentEntries(O);const n=findAgentEntryIndex(t,i);t[n]={...t[n],...s?{subagents:e.role===`coordinator`?{allowAgents:listAgentRoles().filter(e=>e!==`coordinator`),delegationMode:`prefer`}:{allowAgents:[]}}:{},...e.entry,id:i,name:c,workspace:T,agentDir:E,identity:u};O={...O,agents:{...O.agents,entries:toAgentEntriesRecord(t)}}}const k=parseBindingSpecs({agentId:i,specs:e.bindingSpecs,config:O});if(k.errors.length>0)throw new InvalidAgentBindingsError(k.errors.join(` `));const A=k.bindings.length?applyAgentBindings(O,k.bindings):void 0;O=A?.config??O;await assertRetainedPostgresAgentStores({config:O,agentId:i,assertCurrent:beforePersistentApply});if(x)await migrateRetainedAgentStores({agentId:i,allowRestore:!o,paths:r.length>0?r:resolveConfiguredAgentDatabaseTargets(O,{env:process.env,agentId:i}).map(e=>e.path),assertCurrent:beforePersistentApply});const j=s?false:e.skipBootstrap??O.agents?.defaults?.skipBootstrap;if(s&&await isWorkspaceBootstrapPending(T))throw new UnfinishedRoleBootstrapError;beforePersistentApply();const M=await ensureAgentWorkspace({dir:T,guard:{assertHost,recoveryHoldPredicate:recoveryHoldPredicate()},ensureBootstrapFiles:!j&&!e.deferInitialization,purpose:e.purpose,...s?{templates:e.entry?.identity?{...s.files,[DEFAULT_IDENTITY_FILENAME]:mergeIdentityMarkdownContent(s.files[DEFAULT_IDENTITY_FILENAME],u)}:s.files}:{},skipOptionalBootstrapFiles:s?[]:e.skipOptionalBootstrapFiles??O.agents?.defaults?.skipOptionalBootstrapFiles});if(M.dir!==T){const e=listAgentEntries(O);const t=findAgentEntryIndex(e,i);const n=e[t];if(t>=0&&n){e[t]={...n,id:i,workspace:M.dir};O={...O,agents:{...O.agents,entries:toAgentEntriesRecord(e)}}}}beforePersistentApply();await fs$1.mkdir(resolveSessionTranscriptsDirForAgent(i),{recursive:true});if(!s&&!M.bootstrapPending&&!j&&!e.deferInitialization){await writeIdentityFile({workspaceDir:M.dir,identity:u,guard:{assertHost,recoveryHoldPredicate:recoveryHoldPredicate()}});v=true}beforePersistentApply();await withCreationClaim(async()=>{g=await e.prepareConfigCommit?.(O)??void 0;beforePersistentApply();await prepareOpenClawAgentDatabaseExecution({agentId:i,path:resolveAuthProfileDatabasePath(E)},assertHost)});return{nextConfig:O,result:{status:C>=0?`existing`:`created`,agentId:i,name:c,workspace:M.dir,agentDir:E,...l?{model:l}:{},bootstrapPending:M.bootstrapPending===true,...A?{bindingResult:A}:{}}}}});const w=g;g=void 0;const T={...C.result,config:C.nextConfig,configPath:C.path,...typeof C.persistedHash===`string`?{configHash:C.persistedHash}:{}};e.onCommitted?.(T);if(w)await withCreationClaim(async()=>await w.commit());if(p?.cleanupCompleted&&!S&&C.result?.status===`created`&&!await claimCompletedAgentDeletion(i,p.operationId))throw new Error(`agent "${i}" deletion tombstone changed during creation`);if(T.status===`created`){await recordAgentProvenance(i,e.provenance??{createdVia:`operator`});if(!e.deferInitialization){const{provisionDefaultProactiveJob:t}=await import(`./default-proactive-job-Poirer_t.mjs`);await t(T.config,i,{cadenceMs:e.proactiveCadenceMs,commitGuard:assertHost,recoveryHoldPredicate:recoveryHoldPredicate()})}}if(r.length>0){assertRecoveryCurrent();const t=selectedRecoveryPaths(T.config,i,y,b);const n=r.filter(e=>t.includes(e));await resolveAgentDeletionRecoveryHoldsInWorker(recoveryHoldPredicate(),n,e.restorePaths?beforePersistentApply:assertRecoveryPathCurrent)}return T})}catch(e){if(g){const t=g;try{await withCreationClaim(async()=>await t.rollback())}catch(t){throw new Error(`${String(e)}\nstaged config rollback failed: ${String(t)}`,{cause:t})}}if(e instanceof DuplicateAgentError)return createError(`already-exists`,e.message||`agent "${i}" already exists`,i);if(e instanceof InvalidAgentBindingsError)return createError(`invalid-bindings`,e.message,i);if(e instanceof UnfinishedRoleBootstrapError)return createError(`unfinished-bootstrap`,`The workspace has an unfinished bootstrap. Complete it first or choose a new workspace for this role.`,i);if(e instanceof FsSafeError)return createError(`unsafe-identity-file`,`unsafe workspace file "${DEFAULT_IDENTITY_FILENAME}"`,i);throw e}}export{createAgent as n,validateAgentIdInput as r,checkAgentCreationGate as t};