UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

957 lines (956 loc) • 35.9 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { c as runOutsideAsyncWorkScope } from "./async-work-scope-BXagjUap.mjs"; import { t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs"; import { r as normalizeAgentIdStrict } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { i as getRuntimeConfigAppliedHash, j as hashRuntimeConfigValue } from "./runtime-snapshot-WbwbY5b7.mjs"; import { a as hasGatewayClientCap, n as GATEWAY_CLIENT_IDS, t as GATEWAY_CLIENT_CAPS } from "./client-info-Cm1BcrMm.mjs"; import { Ac as validateAgentsCreateParams, Fc as validateAgentsListParams, Ic as validateAgentsUpdateParams, Mc as validateAgentsFilesGetParams, Nc as validateAgentsFilesListParams, Oc as validateAgentsAvatarGenerateParams, Pc as validateAgentsFilesSetParams, jc as validateAgentsDeleteParams, kc as validateAgentsAvatarGenerateResult } from "./src-BX8OAe1J.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { S as attachRuntimeConfigWriteApplication, s as readConfigFileSnapshot, w as createRuntimeConfigWriteApplication } from "./io.runtime-DsJ2dLCQ.mjs"; import { C as runWithGatewayDetachedWorkContinuation, a as captureGatewayRootWorkAdmissionContinuationScope } from "./gateway-work-admission-79pid1hQ.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { f as resolveGatewayOperatorRoleActor, m as resolveOperatorRolePolicy, n as authorizeCurrentOperatorRoleScopes } from "./operator-role-policy-DhcqVpmG.mjs"; import { t as SessionMutationAuthorizationChangedError } from "./session-mutation-authorization-error-0K0ZVV7q.mjs"; import { r as resolveAgentMainSessionKey } from "./main-session-BNL3-mRV.mjs"; import { t as OPENCLAW_TRANSCRIPT_ARTIFACT_PROVIDER } from "./transcript-model-DRGmnGZ9.mjs"; import { i as OPENCLAW_TRANSCRIPT_ARTIFACT_API } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs"; import "./config-CMA-J084.mjs"; import { r as prepareOperatorModelPresentation } from "./operator-model-presentation-BAAXja2o.mjs"; import { l as WORKSPACE_BOOTSTRAP_FILENAMES, n as DEFAULT_BOOTSTRAP_FILENAME, r as DEFAULT_IDENTITY_FILENAME } from "./workspace-bootstrap-policy-D7EJ00Ub.mjs"; import { a as loadAgentIdentityFromWorkspaceAsync, l as sanitizeAgentIdentityLine, n as createAgentIdentityConfig, s as normalizeIdentityForFile, t as buildIdentityMarkdownForWrite } from "./identity-file-C4Fvs-OY.mjs"; import { n as assertAgentDeletionTargetsUnchanged, t as AgentDeletionTargetsPendingError } from "./agent-workspace-roster-transition-B9fDuucP.mjs"; import { t as applyAgentConfig } from "./agents.config-T4w0h7rr.mjs"; import { n as captureGatewayOperatorRunAuthority } from "./operator-run-authority-3Pm3MQDA.mjs"; import { n as resolveAgentIdentity } from "./identity-Cd2mxvzm.mjs"; import { n as listAgentsForGateway } from "./session-utils-store-CiI_s_OK.mjs"; import { i as getAgentWorkspaceAccess } from "./workspace-access-CnjZBg1i.mjs"; import { t as MAX_WORKSPACE_BOOTSTRAP_FILE_BYTES } from "./workspace-bootstrap-read-BnNa91FJ.mjs"; import { i as isExpectedAbsentBootstrapFile, o as isWorkspaceSetupCompleted, t as ensureAgentWorkspace } from "./workspace-DLlXz3VE.mjs"; import { r as emitSessionsChanged } from "./session-change-event-DFgDuXAu.mjs"; import { n as readPreparedServerMethodModelCatalogs, t as readPreparedServerMethodModelCatalog } from "./optional-model-catalog-D8GNpUVH.mjs"; import { r as resolveOperatorSessionCreation } from "./session-creation-provenance-DCFhTDpD.mjs"; import { t as respondError } from "./response-C7fEiIN1.mjs"; import { n as defineValidatedGatewayHandler, r as defineValidatedGatewayMethod, t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { a as readGatewayRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs"; import { r as validateAgentIdInput } from "./agent-create-l2Gq2JQH.mjs"; import { o as verifySetupInferenceConfig } from "./setup-inference-turn-C9QsFM4y.mjs"; import { r as enqueueWorkspaceFileUpdate } from "./workspace-fs-e2DnPT_x.mjs"; import { t as workerInferenceMetadata } from "./inference-placement-DTrb-mxJ.mjs"; import "./session-utils-CavYkLyd.mjs"; import { r as buildUsageWithNoCost, t as buildAssistantMessage } from "./stream-message-shared-CBUzFwdv.mjs"; import { n as localStateOwnerChangedError, t as captureLocalStateMutationGuard } from "./local-state-owner-CnxUSfeW.mjs"; import { r as isLlmOperatorAuthorizationError } from "./runtime-llm-error-CLYpmGmT.mjs"; import { n as BlobsterUnsupportedRuntimeError, t as BlobsterGenerationAuthorityChangedError } from "./blobster-generation-errors-c69Tukr-.mjs"; import { u as AgentSharedStoreOwnerError } from "./agent-delete-databases-CZFdBpRL.mjs"; import { a as captureGatewayClientUploadCommitGuard } from "./upload-policy-Dp8z9OKP.mjs"; import { n as resolveConfiguredAgentIdOrRespondError } from "./agent-id-shared-YyMfd879.mjs"; import { n as startSlowRequestDiagnostics } from "./slow-request-diagnostics-DXxiICr7.mjs"; import { a as isConfiguredAgent, c as validateAgentModelSelectionUpdate, n as AgentModelSelectionError, o as isImplicitAgentModelUpdate, r as createAgentConfigEntry, s as updateAgentConfigEntry, t as AgentConfigPreconditionError } from "./agents-config-mutations-CJI0-Cra.mjs"; import { n as deleteGatewayAgent, t as AgentSharedAuthStoreOwnerError } from "./agents-delete-Db5Ee-es.mjs"; import { t as reviveAgentDatabasesAfterConfigCommit } from "./server-reload-agent-databases-Cbi9gdNX.mjs"; import { t as startSessionCreateDiagnostics } from "./session-create-diagnostics-Bq3dGmHh.mjs"; import { t as createGatewaySession } from "./session-create-service-D_50iC0B.mjs"; import { i as handleTrustedInternalChatSend } from "./chat-send-handler-CzQYcege.mjs"; import { n as createSystemAgentGatewayRuntime } from "./system-agent-execution-DVrppBhT.mjs"; import path from "node:path"; import fs from "node:fs/promises"; //#region src/gateway/server-methods/agents-avatar.ts const agentAvatarGenerateHandler = defineValidatedGatewayMethod("agents.avatar.generate", validateAgentsAvatarGenerateParams, async ({ params: e, respond: t, context: n, client: r, signal: i, hasCurrentClientAuthority: a }) => { const assertCurrent = () => { i?.throwIfAborted(); if (a?.() === false) throw new BlobsterGenerationAuthorityChangedError(); }; const o = await captureGatewayOperatorRunAuthority({ client: r, context: n, hasCurrentClientAuthority: a, invocationAuthority: { assertCurrent, signal: i } }); if (!o) { t(false, void 0, errorShape(ErrorCodes.FORBIDDEN, "Avatar generation requires an authenticated operator.")); return; } try { const { generateBlobsterForAgent: r } = await import("./blobster-generation-BoySXW39.mjs"); assertCurrent(); const a = await r({ cfg: n.getRuntimeConfig(), agentId: e.agentId, prompt: e.prompt, assertCurrent, operatorAuthority: o.authority, signal: i }); assertCurrent(); if (!validateAgentsAvatarGenerateResult(a)) throw new Error("Invalid avatar preview."); t(true, a, void 0); } finally { o.release(); } }, (e) => { if (e instanceof BlobsterGenerationAuthorityChangedError) return errorShape(ErrorCodes.UNAVAILABLE, e.message); if (isLlmOperatorAuthorizationError(e)) return errorShape(ErrorCodes.FORBIDDEN, "Avatar generation is not authorized for this operator or model. Choose an allowed model or ask a Gateway administrator to update your role's model policy."); if (e instanceof BlobsterUnsupportedRuntimeError) return errorShape(ErrorCodes.UNAVAILABLE, "The selected agent runtime cannot generate avatars without tools. Choose a supported runtime and try again."); return errorShape(ErrorCodes.UNAVAILABLE, "Could not generate a valid Blobster with the selected model. Try a shorter description or another configured model."); }); //#endregion //#region src/gateway/server-methods/agents-files.ts const CORE_FILE_NAMES = WORKSPACE_BOOTSTRAP_FILENAMES.filter((e) => e !== DEFAULT_IDENTITY_FILENAME); const CORE_FILE_NAMES_POST_ONBOARDING = CORE_FILE_NAMES.filter((e) => e !== DEFAULT_BOOTSTRAP_FILENAME); const ALLOWED_FILE_NAMES = new Set(WORKSPACE_BOOTSTRAP_FILENAMES); function resolveAgentWorkspaceFileOrRespondError(e, t, n) { const r = resolveConfiguredAgentIdOrRespondError(e.agentId, n, t); if (!r) return null; const i = e.name.trim(); if (!ALLOWED_FILE_NAMES.has(i)) { respondError(t, ErrorCodes.INVALID_REQUEST, `unsupported file "${i}"`); return null; } return { agentId: r, workspaceDir: resolveAgentWorkspaceDir(n, r), name: i }; } async function statWorkspaceFileSafely(e, t) { try { const n = await e?.stat(t); return n?.isFile && !n.isSymbolicLink && n.nlink <= 1 ? { size: n.size, updatedAtMs: Math.floor(n.mtimeMs) } : null; } catch { return null; } } function respondWorkspaceFileUnsafe(e, t) { respondError(e, ErrorCodes.INVALID_REQUEST, `unsafe workspace file "${t}"`); } async function writeWorkspaceFileOrRespond(e) { const t = getAgentWorkspaceAccess(e.workspaceDir); if (t) { if (Buffer.byteLength(e.content) > 2097152) throw new Error("Workspace document exceeds its write bound"); e.assertCurrent?.(); await t.bridge.writeFile({ filePath: e.name, data: e.content, mkdir: false }); if (getAgentWorkspaceAccess(e.workspaceDir) !== t) throw new Error("Workspace access changed while saving Agent identity"); return true; } e.assertCurrent?.(); await fs.mkdir(e.workspaceDir, { recursive: true }); try { await (await root(e.workspaceDir)).write(e.name, e.content, { encoding: "utf8", assertBeforeMutation: e.assertCurrent }); } catch (t) { if (t instanceof FsSafeError) { respondWorkspaceFileUnsafe(e.respond, e.name); return false; } throw t; } return true; } async function readWorkspaceFileContent(e, t) { try { const n = getAgentWorkspaceAccess(e); if (n) { const r = await n.bridge.readFile({ filePath: t, maxBytes: MAX_WORKSPACE_BOOTSTRAP_FILE_BYTES }); if (getAgentWorkspaceAccess(e) !== n) throw new Error("Workspace access changed while reading Agent identity"); if (r.length > 2097152) throw new Error("Workspace document exceeds its read bound"); return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(r); } return (await (await root(e)).read(t, { hardlinks: "reject" })).buffer.toString("utf-8"); } catch (e) { if (isMissingPathError(e)) return; throw e; } } async function buildIdentityMarkdownOrRespondUnsafe(e) { try { return await buildIdentityMarkdownForWrite({ ...e, readWorkspaceFileContent }); } catch (t) { if (t instanceof FsSafeError) { respondWorkspaceFileUnsafe(e.respond, DEFAULT_IDENTITY_FILENAME); return null; } throw t; } } async function readWorkspaceFileHash(e, t) { try { const n = await e.read(t, { hardlinks: "reject" }); return sha256Hex(n.buffer); } catch (e) { if (isMissingPathError(e)) return; throw e; } } function respondWorkspaceFileConflict(e, t, n) { respondError(e, ErrorCodes.INVALID_REQUEST, `agent file "${t}" changed since it was read`, { details: { type: "agent_file_conflict", name: t, ...n ? { currentHash: n } : {} } }); } const agentFileHandlers = { "agents.files.list": async ({ params: e, respond: t, context: n }) => { if (!assertValidParams(e, validateAgentsFilesListParams, "agents.files.list", t)) return; const r = n.getRuntimeConfig(); const i = resolveConfiguredAgentIdOrRespondError(e.agentId, r, t); if (!i) return; const a = resolveAgentWorkspaceDir(r, i); let o = false; try { o = await isWorkspaceSetupCompleted(a); } catch {} const s = getAgentWorkspaceAccess(a); const c = s ? null : await root(a).catch(() => null); const l = o ? CORE_FILE_NAMES_POST_ONBOARDING : CORE_FILE_NAMES; t(true, { agentId: i, workspace: a, files: await Promise.all(l.map(async (e) => { let t; if (s) { const n = await s.bridge.stat({ filePath: e }); if (getAgentWorkspaceAccess(a) !== s) throw new Error("Workspace access changed while listing Agent documents"); t = n?.type === "file" ? { size: n.size, updatedAtMs: Math.floor(n.mtimeMs) } : null; } else t = await statWorkspaceFileSafely(c, e); return Object.assign({ name: e, path: path.join(a, e), missing: t === null }, t ?? { expectedAbsent: isExpectedAbsentBootstrapFile(e) }); })) }, void 0); }, "agents.files.get": async ({ params: e, respond: t, context: n }) => { if (!assertValidParams(e, validateAgentsFilesGetParams, "agents.files.get", t)) return; const r = resolveAgentWorkspaceFileOrRespondError(e, t, n.getRuntimeConfig()); if (!r) return; const { agentId: i, workspaceDir: a, name: o } = r; const s = path.join(a, o); const respondFile = (e) => t(true, { agentId: i, workspace: a, file: { name: o, path: s, missing: e === void 0, ...e ?? { expectedAbsent: isExpectedAbsentBootstrapFile(o) } } }, void 0); const c = getAgentWorkspaceAccess(a); let l; if (c) { const e = await c.bridge.stat({ filePath: o }); if (getAgentWorkspaceAccess(a) !== c) throw new Error("Workspace access changed while reading an Agent document"); if (!e) { respondFile(); return; } const t = await c.bridge.readFile({ filePath: o, maxBytes: MAX_WORKSPACE_BOOTSTRAP_FILE_BYTES }); if (getAgentWorkspaceAccess(a) !== c || t.length > 2097152) throw new Error("Workspace document read is no longer valid"); l = { size: t.length, updatedAtMs: Math.floor(e.mtimeMs), hash: sha256Hex(t), content: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(t) }; } else { let e; try { e = await (await root(a)).read(o, { hardlinks: "reject" }); } catch (e) { if (isMissingPathError(e)) { respondFile(); return; } if (e instanceof FsSafeError) { respondWorkspaceFileUnsafe(t, o); return; } throw e; } l = { size: e.stat.size, updatedAtMs: Math.floor(e.stat.mtimeMs), hash: sha256Hex(e.buffer), content: e.buffer.toString("utf-8") }; } respondFile(l); }, "agents.files.set": async ({ params: e, respond: t, context: n }) => { if (!assertValidParams(e, validateAgentsFilesSetParams, "agents.files.set", t)) return; const r = resolveAgentWorkspaceFileOrRespondError(e, t, n.getRuntimeConfig()); if (!r) return; const { agentId: i, workspaceDir: a, name: o } = r; if (e.expectedWorkspace !== void 0 && e.expectedWorkspace !== a) { respondError(t, ErrorCodes.INVALID_REQUEST, `Agent workspace changed since "${o}" was read. Your draft is preserved. Reload to use the current workspace file, or Overwrite to save this draft there.`, { details: { type: "agent_file_conflict", name: o } }); return; } const s = getAgentWorkspaceAccess(a); const c = path.join(a, o); const l = e.content; let u = null; let d; if (Buffer.byteLength(e.content) > 2097152) throw new Error("Workspace document exceeds its write bound"); if (s) { const assertCurrent = () => { if (getAgentWorkspaceAccess(a) !== s) throw new Error("Workspace access changed while saving an Agent document"); }; const n = s.bridge.createFileExclusive; if (e.expectedMissing && !n) { respondError(t, ErrorCodes.INVALID_REQUEST, "This workspace host cannot safely create a missing Agent document. Update its workspace provider, or create the file on that host and reload it before saving."); return; } d = await enqueueWorkspaceFileUpdate(async () => { assertCurrent(); if (e.expectedMissing && n) { const e = await n({ filePath: o, data: l, mkdir: true }); assertCurrent(); return e === "exists" ? { currentHash: void 0 } : void 0; } const t = e.expectedHash?.toLowerCase(); if (t) { const e = await s.bridge.stat({ filePath: o }); assertCurrent(); let n; if (e) { const e = await s.bridge.readFile({ filePath: o, maxBytes: MAX_WORKSPACE_BOOTSTRAP_FILE_BYTES }); assertCurrent(); if (e.length > 2097152) throw new Error("Workspace document exceeds its read bound"); n = sha256Hex(e); } if (n !== t) return { currentHash: n }; } await s.bridge.writeFile({ filePath: o, data: e.content, mkdir: true }); assertCurrent(); }); } else { await fs.mkdir(a, { recursive: true }); try { u = await root(a); const t = u; const n = e.expectedHash?.toLowerCase(); d = await enqueueWorkspaceFileUpdate(async () => { if (e.expectedMissing) { try { await t.create(o, l, { encoding: "utf8", atomic: true }); } catch (e) { if (e instanceof FsSafeError && e.code === "already-exists") return { currentHash: void 0 }; throw e; } return; } if (n) { const e = await readWorkspaceFileHash(t, o); if (e !== n) return { currentHash: e }; } await t.write(o, l, { encoding: "utf8" }); }); } catch (e) { if (!(e instanceof FsSafeError)) throw e; respondWorkspaceFileUnsafe(t, o); return; } } if (d) { respondWorkspaceFileConflict(t, o, d.currentHash); return; } const f = s ? { size: Buffer.byteLength(l) } : await statWorkspaceFileSafely(u, o); if (o === "IDENTITY.md") { await loadAgentIdentityFromWorkspaceAsync(a); n.broadcast("agent.identity.changed", { agentId: i }); } t(true, { ok: true, agentId: i, workspace: a, file: { name: o, path: c, missing: false, size: f?.size, ...!s ? { updatedAtMs: f?.updatedAtMs } : {}, hash: sha256Hex(l), content: l } }, void 0); } }; //#endregion //#region src/shared/agent-onboarding.ts /** The creation preview and saved first assistant turn share the same opening. */ function buildAgentOnboardingGreeting(e) { const t = e?.trim(); return t ? `Hi, I’m ${t}. Happy to help.` : "Hi! Happy to help."; } //#endregion //#region src/gateway/server-methods/agents-onboarding.ts /** Verify the primary route before the creation owner writes any agent state. */ async function prepareAgentOnboarding(e, t, n) { const r = readGatewayRequestMutationAuthority(e); const i = e.context.getRuntimeConfig(); const a = getRuntimeConfigAppliedHash(); const assertCurrent = () => { r.assertCurrent(); if (a === null || !e.context.isConfigReloadSettled() || e.context.getRuntimeConfig() !== i || getRuntimeConfigAppliedHash() !== a) throw new Error("Gateway settings changed or are not active yet. Wait for application to finish, then retry creation."); }; assertCurrent(); const o = await readConfigFileSnapshot(); assertCurrent(); if (!o.exists || !o.valid || hashRuntimeConfigValue(o.sourceConfig) !== a) throw new Error("Gateway settings are saved but not active yet. Wait for application to finish, then retry creation."); const s = applyAgentConfig(i, { agentId: t, ...n.model ? { model: n.model } : {}, ...n.workspace ? { workspace: n.workspace } : {} }); const c = await verifySetupInferenceConfig({ config: s, agentId: t, modelTarget: "primary", requireExecutionOwner: false, runtime: createSystemAgentGatewayRuntime(), assertSourceCurrent: assertCurrent, signal: e.signal }); assertCurrent(); if (!c.ok) throw new Error(c.error); return { expectedConfigHash: o.hash ?? null, assertCurrent }; } /** Creation has committed; greeting publication failure must retain that agent's receipt. */ async function completeAgentOnboarding(e, t, n) { try { var r = _usingCtx(); const i = r.u(startSessionCreateDiagnostics()); const a = e.context.getRuntimeConfig(); const o = resolveAgentMainSessionKey({ cfg: a, agentId: t }); try { const r = readGatewayRequestMutationAuthority(e); const s = await createGatewaySession({ cfg: a, getCurrentConfig: e.context.getRuntimeConfig, agentId: t, key: o, commandSource: "webchat", creation: resolveOperatorSessionCreation(e.client), requestingOperatorScopes: e.client?.connect.scopes, requestingOperatorProfileId: e.client?.authenticatedUserProfile?.profileId, operatorRoleActor: resolveGatewayOperatorRoleActor(e.client), commitGuard: r.assertCurrent, initialAssistantMessage: { message: buildAssistantMessage({ model: { api: OPENCLAW_TRANSCRIPT_ARTIFACT_API, provider: OPENCLAW_TRANSCRIPT_ARTIFACT_PROVIDER, id: "onboarding" }, content: [{ type: "text", text: buildAgentOnboardingGreeting(n) }], stopReason: "stop", usage: buildUsageWithNoCost({}) }), idempotencyKey: `agents.create:${t}:opening` }, onPhase: i?.mark, onCreatedSessionCommitted: (n) => e.sessionMutationAuthorization?.recordCreatedSession?.({ agentId: t, sessionKey: o, storePath: n.storePath, sessionId: n.entry.sessionId, entry: n.entry, lifecycleRevision: n.entry.lifecycleRevision }) }); if (!s.ok) throw new Error(s.error.message); emitSessionsChanged(e.context, { agentId: t, sessionKey: o, reason: "created" }); return { sessionKey: o, status: "completed" }; } catch (e) { return { sessionKey: o, status: "error", error: formatErrorMessage(e) }; } } catch (e) { r.e = e; } finally { r.d(); } } /** Start the first real agent turn after the create receipt has reached the UI. */ async function startAgentOnboardingConversation(e, t, n) { try { var r = _usingCtx(); const i = e.sessionMutationAuthorization?.retain?.(); r.u({ [Symbol.dispose]: () => i?.() }); let a; try { await runOutsideAsyncWorkScope(() => handleTrustedInternalChatSend({ ...e, req: { ...e.req, method: "chat.send" }, params: { sessionKey: n, agentId: t, message: [ "A short introduction has already been saved in this agent's conversation. Ask the user in plain text: What role would you like me to take on?", "Offer these four single-agent roles: Chief of staff (coordinates work and priorities), Researcher (finds and summarizes evidence), Writer (turns notes and sources into drafts), and Reviewer (checks work against requirements). Invite the user to describe a different role if they prefer. Do not offer a team. Ask only about the role in this opening turn; do not ask for their goal or mention a later follow-up yet. End the message there and wait for their reply.", "After the user replies, ask one open-ended follow-up that invites a little detail about the specific thing they want to achieve. Tailor it to their answer, but do not provide another list or hard-code the follow-up wording. Then continue normally after they answer.", "This agent already exists. Do not propose creating an agent or ask the user to approve its creation." ].join("\n\n"), idempotencyKey: `agents.create:${t}:onboarding-question`, deliver: false, suppressCommandInterpretation: true, systemInputProvenance: { kind: "internal_system", sourceTool: "agents_create_onboarding" } }, respond: (...e) => { a ??= e; } }, void 0, { transcript: { display: false }, toolsAllow: [] })); if (a && !a[0]) throw new Error(formatErrorMessage(a[2])); } catch (n) { e.context.logGateway.warn(`could not start onboarding for agent ${t}: ${formatErrorMessage(n)}`); } } catch (e) { r.e = e; } finally { r.d(); } } //#endregion //#region src/gateway/server-methods/agents.ts function respondAgentNotFound(e, t) { e(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `agent "${t}" not found`)); } function createAgentConfigApplication(e) { const t = createRuntimeConfigWriteApplication(captureGatewayRootWorkAdmissionContinuationScope()?.run); return { attach: (e) => attachRuntimeConfigWriteApplication(e, t), confirm: async (n) => { const r = t.claimed ? await t.result : "unclaimed"; if (r === "applied") return true; const i = `Agent configuration was saved but its application to the active Gateway was not confirmed (${r}); run config.get, then apply the saved config or restart the Gateway.`; if (n) n(i); else e(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, i)); return false; } }; } const agentsHandlers = { "agents.avatar.generate": agentAvatarGenerateHandler, "agents.list": defineValidatedGatewayHandler("agents.list", validateAgentsListParams, async ({ params: e, respond: t, context: n, client: r }) => { const i = n.getRuntimeConfig(); const a = resolveOperatorRolePolicy(r, i)?.agents?.length === 0; const o = listAgentIds(i); const s = a ? /* @__PURE__ */ new Map() : n.readPreparedGatewayModelCatalogBatch ? await readPreparedServerMethodModelCatalogs(n, o, { includeSessionRowPolicy: false }) : new Map(await Promise.all(o.map(async (e) => [e, await readPreparedServerMethodModelCatalog(n, { agentId: e, includeSessionRowPolicy: false })]))); const c = { modelCatalogByAgentId: s, includeSystem: hasGatewayClientCap(r?.connect.caps, GATEWAY_CLIENT_CAPS.AGENT_KIND), httpAvatarBasePath: r?.connect.client.id === GATEWAY_CLIENT_IDS.CONTROL_UI ? i.gateway?.controlUi?.basePath ?? "" : void 0 }; const l = a ? [] : resolveOperatorRolePolicy(r, n.getRuntimeConfig())?.agents; const u = l && l !== "*" ? new Set(l) : void 0; const d = await listAgentsForGateway(i, { ...c, agentIds: u }); const f = n.getRuntimeConfig(); const p = authorizeCurrentOperatorRoleScopes(r, f); if (p) { t(false, void 0, p); return; } const m = resolveOperatorRolePolicy(r, f)?.agents; const h = m && m !== "*" ? d.agents.filter((e) => m.includes(e.id)) : d.agents; const g = prepareOperatorModelPresentation({ cfg: f, policyConfig: n.getCommittedRuntimeConfig?.() ?? f, client: r }); const _ = f.cloudWorkers?.requiredProfile; const v = _ ? f.cloudWorkers?.profiles?.[_] : void 0; t(true, { ...e.includeSessionPlacement === true ? { ...d, sessionPlacement: _ ? { requiredProfile: { id: _, ...v ? { providerId: v.provider, executionModes: n.workerEnvironmentService?.supportsExecutionMode(_, "worker-turn") === true ? ["worker-turn"] : [], ...workerInferenceMetadata({ providerId: v.provider, profileSnapshot: v }) } : {} } } : {} } : d, agents: g ? h.map((e) => g.forAgent(e.id, s.get(e.id)?.entries).agent(e)) : h }, void 0); }), "agents.create": async (e) => { try { var t = _usingCtx(); const { params: n, respond: r, client: i, context: a } = e; const o = t.u(startSlowRequestDiagnostics(a.logGateway, "slow agent create", "agents.create", "preflight")); if (!assertValidParams(n, validateAgentsCreateParams, "agents.create", r)) return; let s; try { s = n.expectedOwnerId ? captureLocalStateMutationGuard(n.expectedOwnerId, e) : void 0; } catch (e) { r(false, void 0, localStateOwnerChangedError(e)); return; } let c; if (n.onboarding) { const t = validateAgentIdInput(n.agentId ?? n.name, { displayName: n.name }); if (!t.ok) { r(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, t.message)); return; } try { o?.mark("inference"); c = await prepareAgentOnboarding(e, t.agentId, n); } catch (e) { r(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, formatErrorMessage(e))); return; } } const l = createAgentConfigApplication(r); try { o?.mark("persistAgent"); const t = await createAgentConfigEntry({ name: n.name, ...n.agentId ? { entry: { id: n.agentId, name: n.name } } : {}, workspace: n.workspace, model: n.model, emoji: n.emoji, avatar: n.avatar, beforePersistentApply: () => { s?.(); c?.assertCurrent(); }, ...c ? { expectedConfigHash: c.expectedConfigHash } : {}, assertIdentityInputAllowed: captureGatewayClientUploadCommitGuard({ method: "agents.create", requestParams: n, client: i, context: a }) }, l.attach({})); if (t.status === "error") { r(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, t.message)); return; } o?.mark("reviveDatabases"); await reviveAgentDatabasesAfterConfigCommit([t.agentId], (e) => a.logGateway.warn(e)); o?.mark("applyConfig"); let u; const d = await l.confirm(c ? (e) => { u = e; } : void 0); if (!d && !c) return; if (d) o?.mark("createChat"); let f = c ? u ? { status: "error", sessionKey: resolveAgentMainSessionKey({ cfg: a.getRuntimeConfig(), agentId: t.agentId }), error: u } : await completeAgentOnboarding(e, t.agentId, t.name) : void 0; let p; if (f?.status === "completed" && i) try { p = await captureGatewayOperatorRunAuthority({ client: i, context: a, hasCurrentClientAuthority: e.hasCurrentClientAuthority }); if (!p) throw new Error("Could not retain operator authority for the agent's first turn."); } catch (e) { f = { status: "error", sessionKey: f.sessionKey, error: formatErrorMessage(e) }; } o?.mark("response"); r(true, { ok: true, agentId: t.agentId, name: t.name, workspace: t.workspace, agentDir: t.agentDir, ...t.model ? { model: t.model } : {}, ...f ? { onboarding: f } : {} }, void 0); if (f?.status === "completed" && (!i || p)) { const n = i && p ? { ...e, client: { ...i, internal: { ...i.internal, operatorRunAuthority: p.authority } } } : e; runWithGatewayDetachedWorkContinuation(async () => { try { await startAgentOnboardingConversation(n, t.agentId, f.sessionKey); } finally { p?.release(); } }, "agents:create-onboarding").catch((e) => { a.logGateway.warn(`could not start onboarding for agent ${t.agentId}: ${formatErrorMessage(e)}`); }); } } catch (e) { if (e instanceof SessionMutationAuthorizationChangedError) { r(false, void 0, e.error); return; } throw e; } } catch (e) { t.e = e; } finally { t.d(); } }, "agents.update": async ({ params: e, respond: t, context: n, client: r }) => { if (!assertValidParams(e, validateAgentsUpdateParams, "agents.update", t)) return; const i = captureGatewayClientUploadCommitGuard({ method: "agents.update", requestParams: e, client: r, context: n }); let a = false; const assertUploadAllowed = () => { if (!a) i?.(); }; const o = n.getRuntimeConfig(); const s = normalizeAgentIdStrict(e.agentId); if (!s.ok) { respondAgentNotFound(t, e.agentId); return; } const c = s.value; const l = normalizeOptionalString(e.workspace); const u = l ? resolveUserPath(l) : void 0; const d = e.model === null ? null : normalizeOptionalString(e.model); const f = normalizeOptionalString(e.name); const p = f ? sanitizeAgentIdentityLine(f) : void 0; const m = createAgentIdentityConfig({ name: p, emoji: e.emoji, avatar: e.avatar }); const h = Boolean(m); const g = { agentId: c, ...p ? { name: p } : {}, ...u ? { workspace: u } : {}, ...d !== void 0 ? { model: d } : {}, ...e.agentRuntime ? { agentRuntime: e.agentRuntime } : {}, ...m ? { identity: m } : {} }; const _ = validateAgentModelSelectionUpdate(e); if (_) { t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, _)); return; } const v = isConfiguredAgent(o, c); if (!v && !isImplicitAgentModelUpdate(o, g)) { respondAgentNotFound(t, c); return; } const y = v ? applyAgentConfig(o, g) : o; const b = createAgentConfigApplication(t); try { let e; if (u) { await assertAgentDeletionTargetsUnchanged(o, y); const t = Boolean(y.agents?.defaults?.skipBootstrap); e = await ensureAgentWorkspace({ dir: u, guard: { assertHost: assertUploadAllowed }, ensureBootstrapFiles: !t, skipOptionalBootstrapFiles: y.agents?.defaults?.skipOptionalBootstrapFiles }); } const n = normalizeIdentityForFile(resolveAgentIdentity(y, c)); if (n && (u || h)) { const r = resolveAgentWorkspaceDir(y, c); const i = resolveAgentWorkspaceDir(o, c); const s = u && r !== i ? i : void 0; const l = [r, ...s ? [s] : []].map((e) => [e, getAgentWorkspaceAccess(e)]); const assertWorkspaceAccessCurrent = () => { assertUploadAllowed?.(); for (const [e, t] of l) if (getAgentWorkspaceAccess(e) !== t) throw new Error("Workspace access changed while updating Agent identity"); }; const d = await buildIdentityMarkdownOrRespondUnsafe({ respond: t, workspaceDir: r, identity: n, fallbackWorkspaceDir: s, preferFallbackWorkspaceContent: Boolean(s) && e?.identityPathCreated === true }); if (d === null) return; assertWorkspaceAccessCurrent(); if (!await writeWorkspaceFileOrRespond({ respond: t, workspaceDir: r, name: "IDENTITY.md", content: d, assertCurrent: assertWorkspaceAccessCurrent })) return; a = true; assertWorkspaceAccessCurrent(); } await updateAgentConfigEntry({ ...g, assertCurrent: assertUploadAllowed }, b.attach({})); } catch (e) { if (e instanceof SessionMutationAuthorizationChangedError) { t(false, void 0, e.error); return; } if (e instanceof AgentConfigPreconditionError) { respondAgentNotFound(t, c); return; } if (e instanceof AgentModelSelectionError || e instanceof AgentDeletionTargetsPendingError) { t(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, e.message)); return; } throw e; } if (await b.confirm()) t(true, { ok: true, agentId: c }, void 0); }, "agents.delete": async ({ params: e, respond: t, context: n }) => { if (!assertValidParams(e, validateAgentsDeleteParams, "agents.delete", t)) return; const r = normalizeAgentIdStrict(e.agentId); if (!r.ok) { respondAgentNotFound(t, e.agentId); return; } const i = r.value; const a = e.deleteFiles ?? true; const o = createAgentConfigApplication(t); try { const e = await deleteGatewayAgent(i, a, n, { writeOptions: o.attach({}) }); if (!await o.confirm()) return; if (e.purgeFailed || e.failed?.length) { const n = e.failed?.map(({ path: e, reason: t }) => `${e}: ${t}`) ?? []; if (e.purgeFailed) n.unshift("session-store cleanup failed"); t(false, e, errorShape(ErrorCodes.UNAVAILABLE, `Agent "${i}" was removed from configuration, but deletion cleanup is still pending: ${n.join("; ")}. Resolve the cleanup failure, then retry agents.delete.`)); return; } t(true, e, void 0); } catch (e) { if (e instanceof AgentSharedAuthStoreOwnerError || e instanceof AgentSharedStoreOwnerError) { t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e.message)); return; } if (e instanceof AgentConfigPreconditionError) { t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e.message)); return; } throw e; } }, ...agentFileHandlers }; //#endregion export { agentsHandlers };