UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

700 lines (699 loc) • 31.6 kB
import { d as normalizeSortedUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs"; import { t as shouldRejectHardlinkedPluginFiles } from "./hardlink-policy-Kq1Lxk7_.mjs"; import { p as resolveConfigSnapshotHash } from "./io.read-helpers-qAcqsRC0.mjs"; import { Bt as validateWorkerDesktopObserveParams, Di as validateEnvironmentsStatusParams, Rt as validateWorkerDesktopLaunchParams, Ti as validateEnvironmentsSessionExecParams, _i as validateEnvironmentsAdoptSuggestedProfileParams, bi as validateEnvironmentsListParams, fi as validateDesktopLaunchParams, hi as validateDesktopReleaseParams, pi as validateDesktopObserveParams, vi as validateEnvironmentsCreateParams, xi as validateEnvironmentsPrepareParams, yi as validateEnvironmentsDestroyParams } from "./src-BX8OAe1J.mjs"; import { i as preparePluginModule } from "./plugin-module-loader-cache-DgNX_BTY.mjs"; import { i as passesManifestOwnerBasePolicy } from "./manifest-owner-policy-B8Brw4Zo.mjs"; import { t as getPluginSetupModuleLoader } from "./plugin-setup-module-D_W6TtnO.mjs"; import { c as prepareSessionSourceAuthority } from "./session-source-authority-TlTpfRVE.mjs"; import { r as resolvePluginRootPublicSurfaceLocation } from "./public-surface-runtime-JyTrzr-T.mjs"; import { t as DEFAULT_EXEC_APPROVAL_TIMEOUT_MS } from "./exec-approvals-core-puBAw1bE.mjs"; import { t as ADMIN_SCOPE, u as WRITE_SCOPE } from "./operator-scopes-CULmYfyY.mjs"; import { i as listAvailableManifestContractPlugins, s as loadManifestMetadataSnapshot } from "./manifest-contract-eligibility-DoGGge-2.mjs"; import { l as readConfigFileSnapshotForWrite } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { r as authorizeOperatorScopesForRequiredScope } from "./method-scopes-Dpyb0Ck-.mjs"; import { o as resolveSessionStorePathForScope } from "./session-store-path-BIJyO4vM.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { m as resolveOperatorRolePolicy } from "./operator-role-policy-DhcqVpmG.mjs"; import { o as getGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs"; import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { r as resolveSandboxRuntimeStatus } from "./runtime-status-C5ZOG7YR.mjs"; import { n as captureSessionEntrySourceAssertion } from "./session-entry-source-authority-Bxiv7qVT.mjs"; import { t as resolveWorkerPlacementCapabilities } from "./placement-capabilities-CtyNh6Uw.mjs"; import { o as prepareExecApprovalsCurrentRead } from "./exec-approvals-store-BUZ9uOWF.mjs"; import "./exec-approvals-rOfoWejC.mjs"; import { t as prepareExecDefaults } from "./exec-defaults-BaVI-sJD.mjs"; import { r as sanitizeExecApprovalDisplayTextWithStatus } from "./exec-approval-text-sanitize-Xx3Q87a8.mjs"; import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs"; import { n as NODE_DESKTOP_STREAM_COMMAND } from "./node-desktop-stream-BZM2AiRA.mjs"; import { t as readKnownNodeCatalog } from "./node-catalog-read--dF2oXwI.mjs"; import { r as respondUnavailableOnThrow, t as respondError } from "./response-C7fEiIN1.mjs"; import { n as defineValidatedGatewayHandler, r as defineValidatedGatewayMethod, t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { t as createAgentRuntimeIdentity } from "./agent-runtime-identity-token-BK52eBqW.mjs"; import { a as readGatewayRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs"; import { t as workerInferenceMetadata } from "./inference-placement-DTrb-mxJ.mjs"; import { d as resolveRequiredNodeCommandAuthority, l as resolveNodeCommandAllowlist, o as isNodeCommandAllowed } from "./node-command-policy-DkH-pkTr.mjs"; import { n as readNodeSessionWithheldCommands } from "./node-registry-CE_3ElcX.mjs"; import { t as lookupCronRunExecSource } from "./cron-run-exec-source-BiohUkNP.mjs"; import { t as DesktopCredentialsRequiredError } from "./host-source-errors-DR8Pa8uB.mjs"; import { t as bindApprovalRequesterMetadata } from "./approval-shared-C8HrUVTB.mjs"; import { t as handlePendingApprovalRequestWithDelivery } from "./approval-request-delivery-2N7Slhd-.mjs"; import { n as getNodeDesktopService } from "./node-source-context-BNOn0rnL.mjs"; import { i as summarizeWorkerEnvironment, n as resolveSessionEnvironmentCaller, r as captureSessionEnvironmentToolPolicy, t as environmentsSessionHandlers } from "./environments.session-PvVngUtb.mjs"; //#region src/plugins/worker-profile-suggestions.ts const log = createSubsystemLogger("plugins"); /** Reads only declared setup surfaces; configured profiles remain the sole placement authority. */ async function resolveSuggestedWorkerProfile(e) { if (Object.keys(e.config.cloudWorkers?.profiles ?? {}).length > 0) return; const t = normalizePluginsConfig(e.config.plugins); const n = loadManifestMetadataSnapshot({ config: e.config }); const r = listAvailableManifestContractPlugins({ snapshot: n, config: e.config, contract: "workerProfileSuggestions" }).filter((e) => passesManifestOwnerBasePolicy({ plugin: e, normalizedConfig: t })); for (const t of r) try { const n = resolvePluginRootPublicSurfaceLocation({ pluginRoot: t.rootDir, pluginId: t.id, entrySource: t.source, artifactBasename: "worker-profile-api.js" }); if (!n) throw new Error("missing worker-profile-api discovery artifact"); const r = preparePluginModule({ ...n, boundaryLabel: "plugin root", surfaceLabel: "worker profile discovery", origin: t.origin, pluginId: t.id, rejectHardlinks: shouldRejectHardlinkedPluginFiles(t) }).modulePath; const i = getPluginSetupModuleLoader(t, r, n.boundaryRoot); const a = await i.initialize(() => { const e = i(r); if (!e || typeof e !== "object" || !("discoverWorkerProfile" in e) || typeof e.discoverWorkerProfile !== "function") throw new Error("worker-profile-api must export discoverWorkerProfile"); return e.discoverWorkerProfile; })({ refresh: e.refresh }); if (a) { if (!t.contracts?.workerProfileSuggestions?.includes(a.profile.provider)) throw new Error("suggested profile uses an undeclared worker provider"); return a; } } catch (e) { log.warn(`Worker profile discovery unavailable for ${t.id}: ${String(e)}`); } } //#endregion //#region src/gateway/desktop/observe-requester.ts function resolveDesktopObserveRequester(e) { const { client: t, hasCurrentClientAuthority: n } = e; if (!t) return; return { connId: t.connId, operatorName: t.authenticatedUserProfile?.displayName?.trim() || t.authenticatedUserId?.trim() || void 0, signal: t.connectionSignal, remoteIngressPrincipal: t.internal?.remoteIngressPrincipal, isCurrent: () => t.invalidated !== true && !t.connectionSignal?.aborted && n?.() !== false }; } //#endregion //#region src/gateway/server-methods/environments.profiles.ts function listWorkerProfiles(e) { if (!e.workerEnvironmentService || !e.workerPlacementDispatchService) return []; const t = e.getRuntimeConfig().cloudWorkers?.profiles ?? {}; return Object.entries(t).flatMap(([e, t]) => { const n = typeof t.provider === "string" ? t.provider.trim() : ""; return e.trim() && n ? [{ id: e.trim(), providerId: n, ...workerInferenceMetadata({ providerId: n, profileSnapshot: t }) }] : []; }).toSorted((e, t) => e.id.localeCompare(t.id)); } async function listWorkerProfilesWithMachines(e) { const t = listWorkerProfiles(e); return await Promise.all(t.map(async (t) => { const n = ["worker-turn", "remote-exec"].filter((n) => e.workerEnvironmentService?.supportsExecutionMode(t.id, n) === true); const r = n[0]; const i = e.workerEnvironmentService?.readProviderDisplayId(t.id); const a = Object.assign(t, r ? { executionMode: r, executionModes: n } : {}, i ? { providerDisplayId: i } : {}); try { const [n, r] = await Promise.all([e.workerEnvironmentService?.listMachineOptions?.(t.id), e.workerEnvironmentService?.listOperatingSystems?.(t.id)]); const i = n ?? []; return Object.assign(a, i.length > 0 ? { machines: i } : {}, r && r.length > 1 ? { operatingSystems: r } : {}); } catch (n) { e.logGateway.warn(`worker machine catalog unavailable (${t.id}): ${formatForLog(n)}`); return a; } })); } //#endregion //#region src/gateway/server-methods/environments.session-exec-approval.ts /** Reuses operator approval custody; a decision authorizes this exact admitted invocation only. */ async function approveSessionEnvironmentCommand(e) { const { options: t, binding: n, assertCurrent: r } = e; const i = t.context.execApprovalManager; if (!i) throw new Error("Execution approval service is unavailable"); r(); const a = t.client?.internal?.syntheticClient ? getGatewayToolCallerIdentity() : void 0; const o = t.client?.internal?.agentRuntimeIdentity ?? (a?.operationalRunInstance ? await createAgentRuntimeIdentity({ ...a, operationalRunInstance: a.operationalRunInstance }) : void 0); r(); if (a && !o) throw new Error("Environment command approval requires the current admitted run"); const s = sanitizeExecApprovalDisplayTextWithStatus(JSON.stringify({ argv: e.argv, ...e.input === void 0 ? {} : { stdin: e.input } })); if (s.truncated || s.oversized) throw new Error("Environment command is too large to review completely; split it into smaller commands"); const c = i.create({ command: s.text, host: "worker", ...n, runId: o?.operationalRunInstance.runId, allowedDecisions: ["allow-once", "deny"], warningText: `${e.background ? "Start a background process" : "Run a command"} in attached environment ${n.environmentId}.${e.input === void 0 ? "" : ` The command receives ${Buffer.byteLength(e.input)} bytes on stdin.`} Approval is limited to this environment and invocation.`, turnSourceChannel: o?.turnSourceChannel, turnSourceTo: o?.turnSourceTo, turnSourceAccountId: o?.turnSourceAccountId, turnSourceThreadId: o?.turnSourceThreadId }, DEFAULT_EXEC_APPROVAL_TIMEOUT_MS); bindApprovalRequesterMetadata({ record: c, client: t.client }); c.approvalAuthority = r; c.approvalSignals = e.signal ? [e.signal] : []; if (o) c.agentRuntimeDelegatedAuthority = o.delegatedAuthority; if (o?.executionIdentity) c.executionIdentityToken = o.executionIdentity; const { decision: l } = await i.register(c, DEFAULT_EXEC_APPROVAL_TIMEOUT_MS); l.catch(() => void 0); let u = false; await handlePendingApprovalRequestWithDelivery({ approvalKind: "exec", manager: i, record: c, context: t.context, clientConnId: t.client?.connId, twoPhase: false, deliverToApprovalClientsOnly: lookupCronRunExecSource(o?.operationalRunInstance.runId)?.agentId === n.agentId, forwardRequest: t.context.forwardExecApprovalRequest, getIosPushDelivery: () => t.context.execApprovalIosPushDelivery, respond: (e, t, n) => { if (!e) throw new Error(n?.message ?? "Execution approval failed"); }, afterDecision: async (e) => { r(); u = e === "allow-once" && await i.consumeAllowOnce(c.id); r(); }, afterDecisionErrorLabel: "environment exec approvals: approval follow-up failed" }); r(); if (!u) throw new Error("Environment command was not approved"); } //#endregion //#region src/gateway/server-methods/environments.session-exec.ts const environmentsSessionExecHandlers = { "environments.session.exec": defineValidatedGatewayMethod("environments.session.exec", validateEnvironmentsSessionExecParams, async (e) => { const { params: t, respond: n, context: r } = e; const i = await resolveSessionEnvironmentCaller(e, t); let a; try { const o = { ...i.identity, storePath: resolveSessionStorePathForScope(i.identity, r.getRuntimeConfig()) }; const s = await readSessionEntryReadOnlyInWorker(o, i.assertCurrent); a = await prepareSessionSourceAuthority(captureSessionEntrySourceAssertion({ scope: o, expected: s, fields: [ "sessionId", "lifecycleRevision", "execHost", "execNode", "permissionMode", "sandbox", "sandboxMode", "createdActor" ], assertCurrent: i.assertCurrent, assertHostCurrent: i.assertCurrent, refuse() { throw new Error("The selected session changed before its operation committed."); } })); const c = r.workerEnvironmentService; const l = c?.getSessionAttachment(i.identity.sessionId); if (!c || !l || t.environmentId !== void 0 && t.environmentId !== l.environmentId) throw new Error("No matching environment is attached to this conversation"); const u = t.action ?? "run"; const d = { argv: t.argv ? [...t.argv] : ["openclaw-internal-workspace-process"], input: t.input, timeoutMs: t.timeoutMs, processId: t.processId }; const f = captureSessionEnvironmentToolPolicy(e, i, u === "run" || u === "start" ? "exec" : "process"); const p = await prepareExecApprovalsCurrentRead(captureOpenClawStateWorkerContext()); let m = false; const resolvePolicy = () => { const e = r.getRuntimeConfig(); a.assertCurrent(); const t = prepareExecDefaults({ cfg: e, ...i.identity, sessionEntry: s }, resolveSandboxRuntimeStatus({ cfg: e, ...i.identity, preparedSessionEntry: s ?? null })); return t.kind === "resolved" ? t.defaults : t.resolve(p()); }; const requiresApproval = (e) => e.security !== "full" || e.ask === "always" || f.cronExecAskAlways; const assertCurrent = () => { f.assertAllowed(); c.assertSessionAttachment(l); const e = resolvePolicy(); if (e.security === "deny") throw new Error("Conversation policy denies environment command execution"); if (u === "run" || u === "start") { if (e.security === "allowlist" && e.ask === "off") throw new Error("Attached environment commands cannot inherit this host's executable allowlist"); if (e.effectiveHost !== "gateway") throw new Error("The conversation's exec policy binds commands to a different host"); } return e; }; const h = assertCurrent(); if ((u === "run" || u === "start") && requiresApproval(h)) { await approveSessionEnvironmentCommand({ options: e, binding: l, argv: d.argv, input: d.input, background: u === "start", assertCurrent, signal: i.signal }); m = true; } const assertDispatch = () => { const e = assertCurrent(); if (u === "run" || u === "start") { if (!m && requiresApproval(e)) throw new Error("Environment execution policy now requires approval; retry the command"); } }; assertDispatch(); const g = await c.execSessionAttachment(l, { argv: d.argv, ...d.input === void 0 ? {} : { input: d.input }, ...d.timeoutMs === void 0 ? {} : { timeoutMs: d.timeoutMs }, ...u === "run" ? {} : { process: { action: u, processId: d.processId } }, transportRetry: "never", signal: i.signal, assertCurrent: assertDispatch }); assertCurrent(); n(true, { environmentId: l.environmentId, ...g }); } finally { try { await a?.release?.(); } finally { i.release(); } } }, (e) => errorShape(ErrorCodes.INVALID_REQUEST, e instanceof Error ? e.message : "Environment execution failed")) }; //#endregion //#region src/gateway/server-methods/environments.ts async function listSuggestedWorkerProfile(e) { const t = e.getRuntimeConfig(); if (Object.keys(t.cloudWorkers?.profiles ?? {}).length > 0) return; const n = await resolveSuggestedWorkerProfile({ config: t }); if (!n || e.getRuntimeConfig() !== t) return; return { id: n.id, providerId: n.profile.provider, ...n.providerDisplayId ? { providerDisplayId: n.providerDisplayId } : {} }; } async function requireActiveCloudProfile(e) { const t = (await listWorkerProfilesWithMachines(e)).find((e) => e.id === "cloud"); if (!t) throw new Error("The cloud worker profile is saved but is not active on this Gateway. Wait for the Gateway to restart, then retry; if it does not restart, restart it manually."); return t; } const adoptSuggestedWorkerProfile = defineValidatedGatewayHandler("environments.adoptSuggestedProfile", validateEnvironmentsAdoptSuggestedProfileParams, async (e) => { const { context: t, respond: n } = e; const r = readGatewayRequestMutationAuthority(e); await respondUnavailableOnThrow(n, async () => { const { snapshot: i } = await readConfigFileSnapshotForWrite(); r.assertCurrent(); if (i.sourceConfig.cloudWorkers?.profiles?.cloud) { const e = await requireActiveCloudProfile(t); r.assertCurrent(); n(true, { profile: e }, void 0); return; } const a = await resolveSuggestedWorkerProfile({ config: i.config, refresh: true }); r.assertCurrent(); if (!a || a.id !== "cloud") { n(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, "No cloud worker profile is available to configure")); return; } const o = resolveConfigSnapshotHash(i); const { configHandlers: s } = await import("./config-OP2_JJbD.mjs"); r.assertCurrent(); let c = false; await s["config.patch"]({ ...e, req: { ...e.req, method: "config.patch" }, params: { raw: JSON.stringify({ cloudWorkers: { profiles: { cloud: a.profile } } }), ...o ? { baseHash: t.configRevisionProjector.projectRawHash(o) } : {}, response: "summary" }, sessionMutationCommitGuard: r.assertCurrent, respond: (e, t, r, i) => { if (e) c = true; else n(false, t, r, i); } }); if (!c) return; const l = await requireActiveCloudProfile(t); r.assertCurrent(); n(true, { profile: l }, void 0); }); }); function respondDesktopObserveFailure(e, t, n) { if (t instanceof DesktopCredentialsRequiredError) { respondError(e, ErrorCodes.INVALID_REQUEST, t.message, { details: { code: t.detailCode, auth: t.auth } }); return; } respondError(e, ErrorCodes.UNAVAILABLE, t instanceof Error ? t.message : n); } async function respondDesktopObserve(e) { const { request: t, context: n, respond: r } = e; if (t.source.kind !== "environment") { const i = t.source.kind === "host"; if (i && n.getRuntimeConfig().desktop?.host?.enabled !== true) { respondError(e.respond, ErrorCodes.INVALID_REQUEST, "gateway host desktop is disabled; enable the Desktop lab (config: desktop.host.enabled=true)"); return; } const a = { control: t.control ?? false, requester: e.requester, ..."credentials" in t && t.credentials ? { credentials: t.credentials } : {} }; const o = i ? n.hostDesktopService : void 0; const s = i ? void 0 : getNodeDesktopService(n); const c = t.source.kind === "host" ? o?.observe.bind(o, a) : s?.observe.bind(s, { ...a, nodeId: t.source.nodeId }); if (!c) { respondError(r, ErrorCodes.INVALID_REQUEST, i ? "gateway host desktop is unavailable in this Gateway runtime" : "node desktop service is unavailable; reconnect to the Gateway and retry"); return; } try { r(true, await c(), void 0); } catch (e) { respondDesktopObserveFailure(r, e, i ? "gateway host desktop observe unavailable; verify the VNC server and retry" : "node desktop observe unavailable"); } return; } const { environmentId: i } = t.source; await respondWorkerDesktop(e, "observe", (t) => t.observeDesktop({ environmentId: i, control: e.request.control ?? false, requester: e.requester })); } async function respondDesktopLaunch(e, t, n) { await respondWorkerDesktop(e, "launch", (r) => r.launchDesktopApp({ environmentId: t, app: n }, readGatewayRequestMutationAuthority(e).assertCurrent)); } async function respondWorkerDesktop(e, t, n) { const r = e.context.workerEnvironmentService; if (!r) { respondError(e.respond, ErrorCodes.INVALID_REQUEST, "unknown environmentId"); return; } try { e.respond(true, await n(r), void 0); } catch (n) { const r = n && typeof n === "object" && "code" in n ? n.code : void 0; const i = r === "environment_not_found" || r === "invalid_state" || t === "launch" && (r === "desktop_app_not_found" || r === "unsupported_platform"); const a = i || t === "launch" && r === "launcher_failure"; e.respond(false, void 0, errorShape(i ? ErrorCodes.INVALID_REQUEST : ErrorCodes.UNAVAILABLE, a && n instanceof Error ? n.message : t === "launch" ? "worker desktop app launch unavailable; try again" : "worker desktop observe unavailable")); } } const GATEWAY_ENVIRONMENT = { id: "gateway", type: "local", label: "Gateway local", status: "available", platform: process.platform, sessionHost: true, trust: "persistent", capabilities: [ "agent.run", "sessions", "tools", "workspace" ] }; function uniqueSortedStrings(...e) { return normalizeSortedUniqueTrimmedStringList(e.flatMap((e) => e ?? [])); } function summarizeNodeEnvironment(e, t, n, r) { const i = uniqueSortedStrings(e.caps, e.commands); const a = e.platform?.trim(); const o = e.connected === true ? resolveNodeCommandAllowlist(t, { platform: e.platform, deviceFamily: e.deviceFamily, commands: e.commands, approvedCommands: e.commands }) : void 0; const s = o ? uniqueSortedStrings(e.commands).filter((t) => t.length <= 128 && isNodeCommandAllowed({ command: t, declaredCommands: e.commands, allowlist: o }).ok).slice(0, 128) : []; const c = s.includes(NODE_DESKTOP_STREAM_COMMAND); const l = o && r ? resolveRequiredNodeCommandAuthority({ nodeId: e.nodeId, requiredCommands: n, declaredCommands: r.declaredCommands, effectiveCommands: r.commands, withheldCommands: readNodeSessionWithheldCommands(r), allowlist: o }) : void 0; return { id: `node:${e.nodeId}`, type: "node", label: e.displayName ?? e.nodeId, status: e.connected ? "available" : "unavailable", ...a ? { platform: a } : {}, sessionHost: e.sessionHost === true, ...e.connected && e.workerHost?.deviceFolders === true ? { workerHost: { deviceFolders: true } } : {}, ...e.workerSlots ? { workerSlots: { ...e.workerSlots } } : {}, ...e.workerBundle ? { workerBundle: structuredClone(e.workerBundle) } : {}, ...e.lastConnectedAtMs !== void 0 ? { lastConnectedAtMs: e.lastConnectedAtMs } : {}, ...e.lastDisconnectedAtMs !== void 0 ? { lastDisconnectedAtMs: e.lastDisconnectedAtMs } : {}, ...e.lastSeenAtMs !== void 0 ? { lastSeenAtMs: e.lastSeenAtMs } : {}, ...e.lastSeenReason ? { lastSeenReason: e.lastSeenReason } : {}, trust: "persistent", ...c ? { desktop: true } : {}, ...r?.desktopAvailability ? { desktopAvailability: { ...r.desktopAvailability } } : {}, ...i.length > 0 ? { capabilities: i } : {}, ...s.length > 0 ? { invocableCommands: s } : {}, ...l ? { requiredNodeCommand: l } : {}, ...e.issues?.length ? { issues: [...e.issues] } : {} }; } async function listGatewayEnvironments(e, t = readWorkerInventory(e, false).workers, n, r = false) { const i = n ? resolveWorkerPlacementCapabilities(n) : void 0; const { nodes: a, connectedNodes: o } = await readKnownNodeCatalog(e.nodeRegistry, i?.executionMode === "worker-turn" ? "worker-environments" : "environments"); const s = new Set(t.flatMap((e) => e.providerId !== "device" && e.nodeDeviceId && e.state !== "destroyed" ? [e.nodeDeviceId] : [])); const c = new Map(o.map((e) => [e.nodeId, e])); const l = i?.devicePlacement?.requiredNodeCommands ?? []; const u = e.getRuntimeConfig(); let d = u.desktop?.host?.enabled === true ? { ...GATEWAY_ENVIRONMENT, desktop: true } : GATEWAY_ENVIRONMENT; if (r && u.desktop?.host?.enabled !== true) { const { inspectHostDesktopSetup: e } = await import("./host-source-CwfCPmcO.mjs"); d = { ...d, desktopSetup: await e({ config: u.desktop?.host }) }; } return [d, ...a.filter((e) => !s.has(e.nodeId)).map((e) => summarizeNodeEnvironment(e, u, l, c.get(e.nodeId)))]; } function readWorkerInventory(e, t) { try { return { workers: e.workerEnvironmentService?.list() ?? [], preparedPool: t ? e.workerEnvironmentService?.readPreparedPoolSummary() : void 0 }; } catch { throw new Error("environment inventory unavailable"); } } function defineEnvironmentMutation(e, t, n) { return defineValidatedGatewayHandler(`environments.${e}`, t, async (t) => { const { respond: r, context: i } = t; const a = i.workerEnvironmentService; if (!a) { respondError(r, ErrorCodes.INVALID_REQUEST, e === "destroy" ? "unknown environmentId" : "cloud worker environments are not configured"); return; } try { r(true, await n(t, a), void 0); } catch (t) { const n = t && typeof t === "object" && "code" in t ? t.code : void 0; const i = e === "destroy" ? n === "environment_not_found" || n === "invalid_state" : n === "profile_not_found" || n === "invalid_profile" || e === "prepare" && n === "invalid_project"; const a = i || e === "prepare" && n === "capacity"; const o = { create: "creation", prepare: "preparation", destroy: "destruction" }[e]; r(false, void 0, errorShape(i ? ErrorCodes.INVALID_REQUEST : ErrorCodes.UNAVAILABLE, a && t instanceof Error ? t.message : `worker environment ${o} failed`, e === "prepare" && a ? { details: { code: n } } : void 0)); } }); } const environmentsHandlers = { ...environmentsSessionHandlers, "environments.adoptSuggestedProfile": adoptSuggestedWorkerProfile, ...environmentsSessionExecHandlers, "environments.list": async (e) => { const { params: t, respond: n, client: r, context: i } = e; if (!assertValidParams(t, validateEnvironmentsListParams, "environments.list", n)) return; const a = r?.connect.scopes ?? []; const o = t.includePreparedDetails === true && authorizeOperatorScopesForRequiredScope("operator.admin", a).allowed; const s = readGatewayRequestMutationAuthority(e); if (t.runtimeId) { const e = authorizeOperatorScopesForRequiredScope(WRITE_SCOPE, a); if (!e.allowed) { respondError(n, ErrorCodes.FORBIDDEN, `missing scope: ${e.missingScope}`); return; } } await respondUnavailableOnThrow(n, async () => { let e = []; let a = []; let c; if (t.projection !== "profiles") { const n = readWorkerInventory(i, o); a = n.workers; c = n.preparedPool; e = await listGatewayEnvironments(i, a, t.runtimeId, t.includeDesktopSetup); } const l = await listWorkerProfilesWithMachines(i); const u = await listSuggestedWorkerProfile(i); s.assertCurrent(); const d = resolveOperatorRolePolicy(r ?? null, i.getRuntimeConfig()); const f = r?.connect.scopes ?? []; const p = f.includes("operator.admin") && (!d || d.scopes.includes("operator.admin")); const m = authorizeOperatorScopesForRequiredScope("operator.write", f).allowed && (!d || authorizeOperatorScopesForRequiredScope("operator.write", d.scopes).allowed); const h = l.filter((e) => m && (p || d?.workerProfiles?.includes(e.id))).map((e) => e.id); const g = o && authorizeOperatorScopesForRequiredScope("operator.admin", r?.connect.scopes ?? []).allowed; const _ = Date.now(); e.push(...a.map((e) => summarizeWorkerEnvironment(e, _, { includePreparedDetails: g }))); n(true, { environments: e, ...l.length > 0 ? { dispatchableProfileIds: h } : {}, ...u ? { suggestedProfile: u } : {}, ...i.getRuntimeConfig().cloudWorkers?.requiredProfile ? { requiredProfile: i.getRuntimeConfig().cloudWorkers?.requiredProfile } : {}, ...l.length > 0 ? { profiles: g ? l.map((e) => ({ ...e, readyWorkers: i.workerEnvironmentService?.readReadyWorkerTarget(e.id) })) : l } : {}, ...g && c ? { preparedPool: c } : {} }, void 0); }); }, "environments.status": async (e) => { const { params: t, respond: n, client: r, context: i } = e; if (!assertValidParams(t, validateEnvironmentsStatusParams, "environments.status", n)) return; const a = readGatewayRequestMutationAuthority(e); await respondUnavailableOnThrow(n, async () => { const e = (await listGatewayEnvironments(i)).find((e) => e.id === t.environmentId); a.assertCurrent(); if (e) { n(true, e, void 0); return; } let o; try { o = i.workerEnvironmentService?.get(t.environmentId); } catch { respondError(n, ErrorCodes.UNAVAILABLE, "environment status unavailable"); return; } n(Boolean(o), o ? summarizeWorkerEnvironment(o, Date.now(), { includePreparedDetails: t.includePreparedDetails === true && authorizeOperatorScopesForRequiredScope("operator.admin", r?.connect.scopes ?? []).allowed }) : void 0, o ? void 0 : errorShape(ErrorCodes.INVALID_REQUEST, "unknown environmentId")); }); }, "environments.create": defineEnvironmentMutation("create", validateEnvironmentsCreateParams, async ({ params: e }, t) => summarizeWorkerEnvironment(await t.create(e.profileId, e.idempotencyKey))), "environments.prepare": defineEnvironmentMutation("prepare", validateEnvironmentsPrepareParams, (e, t) => t.prepare(e.params, readGatewayRequestMutationAuthority(e).assertCurrent)), "environments.destroy": defineEnvironmentMutation("destroy", validateEnvironmentsDestroyParams, async (e, t) => { const { params: n, context: r } = e; const { assertCurrent: i } = readGatewayRequestMutationAuthority(e); const a = r.workerPlacementDispatchService; if (n.force && !a?.forceDestroyEnvironment) throw new Error("cloud worker placement control is unavailable"); const o = n.force ? await a.forceDestroyEnvironment(n.environmentId, (e) => r.logGateway.warn(`worker environment forced teardown cleanup failed: ${formatForLog(e)}`), i) : await t.destroyUnattached(n.environmentId, i); try { await a?.reconcileActive?.(n.environmentId); } catch (e) { r.logGateway.warn(`worker placement reconciliation after destroy failed: ${formatForLog(e)}`); } return summarizeWorkerEnvironment(o); }), "worker.desktop.observe": defineValidatedGatewayHandler("worker.desktop.observe", validateWorkerDesktopObserveParams, ({ params: e, respond: t, context: n, client: r, hasCurrentClientAuthority: i }) => respondDesktopObserve({ request: { source: { kind: "environment", environmentId: e.environmentId }, ...e.control === void 0 ? {} : { control: e.control } }, respond: t, context: n, requester: resolveDesktopObserveRequester({ client: r, hasCurrentClientAuthority: i }) })), "worker.desktop.launch": defineValidatedGatewayHandler("worker.desktop.launch", validateWorkerDesktopLaunchParams, (e) => respondDesktopLaunch(e, e.params.environmentId, e.params.app)), "desktop.observe": defineValidatedGatewayHandler("desktop.observe", validateDesktopObserveParams, ({ params: e, respond: t, context: n, client: r, hasCurrentClientAuthority: i }) => respondDesktopObserve({ request: e, respond: t, context: n, requester: resolveDesktopObserveRequester({ client: r, hasCurrentClientAuthority: i }) })), "desktop.launch": defineValidatedGatewayHandler("desktop.launch", validateDesktopLaunchParams, (e) => respondDesktopLaunch(e, e.params.source.environmentId, e.params.app)), "desktop.release": defineValidatedGatewayHandler("desktop.release", validateDesktopReleaseParams, async ({ params: e, respond: t, client: n, hasCurrentClientAuthority: r }) => { const { releaseDesktopObserverToken: i } = await import("./observe-bridge-BNslmUCS.mjs"); await respondUnavailableOnThrow(t, async () => { t(true, { released: await i(e.wsPath, resolveDesktopObserveRequester({ client: n, hasCurrentClientAuthority: r })) }, void 0); }); }) }; //#endregion export { listGatewayEnvironments as n, listWorkerProfiles as r, environmentsHandlers as t };