UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

609 lines (608 loc) • 26.6 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs"; import { n as normalizeAgentId, r as normalizeAgentIdStrict } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { g as isReservedSystemAgentId, n as listAgentEntries } from "./agent-roster-t1ooUdXp.mjs"; import { n as createOpenClawAgentDatabasePathMatcher } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { u as resolveSessionTranscriptsDirForAgent } from "./paths-DvQ5AJvD.mjs"; import { E as toAgentEntriesRecord, N as normalizeAgentDirRegistryPath, a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { c as getStateDatabaseSchemaLease, l as hasActiveGatewayStateOwner } from "./gateway-state-owner-Bnv5owvG.mjs"; import { C as runWithAgentCreationClaim } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs"; import { y as DuplicateAgentError } from "./openclaw-state-worker-error-C8y1JGQN.mjs"; import { t as getDatabaseEngineInput } from "./context-DE59wyBs.mjs"; import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs"; import "./openclaw-agent-db-contract-aCH9b8Uc.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs"; import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { r as hasResolvedRosterBeforeMigrations } from "./agent-roster-provenance-DiT1dDed.mjs"; import { E as releaseAgentDatabaseHeldAdmission } from "./agent-database-admission-CL6wHJ_N.mjs"; import { a as readAgentDeletionJournalForCreation, c as readAgentDeletionRecoveryHoldsInWorker } from "./agent-deletion-journal.read-DjOO2RZM.mjs"; import { i as recordAgentProvenance } from "./agent-provenance-BRzUETpY.mjs"; import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs"; import { o as prepareSharedAuthStoreOwnership } from "./path-resolve-CpNl_n1M.mjs"; import { s as claimCompletedAgentDeletion } from "./agent-lifecycle-registry-CdPY7sE9.mjs"; import { o as prepareOpenClawAgentDatabaseExecution } from "./openclaw-agent-execution-C4FyHhb0.mjs"; import { s as resolveConfiguredAgentDatabaseTargets } from "./targets-BVE0__Jb.mjs"; import { o as transformConfigFileWithRetry, s as withConfigMutationExclusive } from "./mutate-DhAOi0-2.mjs"; import "./config-CMA-J084.mjs"; import { r as DEFAULT_IDENTITY_FILENAME } from "./workspace-bootstrap-policy-D7EJ00Ub.mjs"; import { l as sanitizeAgentIdentityLine, n as createAgentIdentityConfig, o as mergeIdentityMarkdownContent } from "./identity-file-C4Fvs-OY.mjs"; import { r as findAgentEntryIndex, t as applyAgentConfig } from "./agents.config-T4w0h7rr.mjs"; import { a as isWorkspaceBootstrapPending, m as createWorkspaceFileMutationGuard, p as assertCurrentAgentDeletionRecoveryHolds, t as ensureAgentWorkspace } from "./workspace-DLlXz3VE.mjs"; import { n as loadAgentRole, t as listAgentRoles } from "./agent-roles-BJUCg-FF.mjs"; import { t as createAgentSchemaInspectionWorker } from "./openclaw-agent-schema-inspection-worker-J31vzzWl.mjs"; import { r as parseBindingSpecs, t as applyAgentBindings } from "./agents.bindings-Cz76H01e.mjs"; import { t as migrateLegacyMainSessionKeys } from "./legacy-main-session-migration-DtdSvuXY.mjs"; import { realpathSync, statSync } from "node:fs"; import fs$1 from "node:fs/promises"; //#region src/state/agent-deletion-recovery.ts /** Resolve the captured recovery holds while creation retains its original path authority. */ 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 }); } //#endregion //#region 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 }); } //#endregion //#region src/agents/agent-create-retained-postgres.ts /** Inspect retained identities before creation can change a workspace, namespace, or config. */ 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: 38, 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 > 38 || e.agentSchemaMeta?.agentId !== n || e.agentSchemaMeta.role !== "agent" || e.agentSchemaMeta.schemaVersion !== e.version) throw refusal(); } } catch (e) { t.e = e; } finally { await t.d(); } } //#endregion //#region 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); } /** Explicit restoration prepares old stores under Doctor custody before they become live. */ 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: 38, 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 > 38) 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 < 38) i.push({ kind: "agent", path: t, agentId: e.agentId, foundVersion: r.version, supportedVersion: 38 }); } 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-iqehb2Km.mjs"), import("./doctor-schema-migrations-DXJxWq4T.mjs"), import("./state-database-maintenance-DSQZwdaL.mjs"), import("./openclaw-agent-db-maintenance-BtbBVK74.mjs"), import("./openclaw-agent-db-maintenance-lease-ecVd8SLK.mjs"), import("./openclaw-state-db-async-lifecycle-svBk4d27.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(); } } //#endregion //#region 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); } /** Read-only early check for guided flows that stage side effects before their final create. */ 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(); } }, 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("\n")); const A = k.bindings.length ? applyAgentBindings(O, k.bindings) : void 0; O = A?.config ?? O; 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 }); await assertRetainedPostgresAgentStores({ config: O, agentId: i, 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, 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) { await writeIdentityFile({ workspaceDir: M.dir, identity: u, guard: { assertHost, recoveryHoldPredicate: recoveryHoldPredicate() } }); v = true; } beforePersistentApply(); await withCreationClaim(async () => { g = await e.prepareConfigCommit?.() ?? 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" }); const { provisionDefaultProactiveJob: t } = await import("./default-proactive-job-HLb7iPB_.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; } } //#endregion export { createAgent as n, validateAgentIdInput as r, checkAgentCreationGate as t };