UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

176 lines (175 loc) • 9.47 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { n as waitForAgentDatabaseWriteAdmission } from "./agent-database-preparation-context-CkVoUMTY.mjs"; import { C as isSubagentSessionKey, j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { A as tryResolveLegacyCompatibilityAgentId } from "./agent-scope-config-DmXgFGKP.mjs"; import { r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { d as hasGatewayAdminScope } from "./operator-scopes-CULmYfyY.mjs"; import { S as readAgentDatabaseAdmissionRefusal, c as createAgentDatabaseAdmissionErrorShape } from "./agent-database-admission-CL6wHJ_N.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { _ as normalizeInputProvenance, b as shouldPreserveUserFacingSessionStateForInputProvenance, f as isExecCompletionInputProvenance, h as isProgressCardRefreshInputProvenance } from "./input-provenance-DupvvURj.mjs"; import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { r as resolveRequestedSessionAgentId, s as tryResolveSessionCompatibilityOwnerAgentId } from "./session-request-agent-tfwWH53J.mjs"; import "./sessions-D5Vvu3AE.mjs"; import { o as withGatewaySessionStoreTarget } from "./session-utils-store-lookup-BrmEKLOy.mjs"; import { n as isSubagentSessionFromEntry } from "./subagent-depth-policy-B6h8hEI1.mjs"; import { C as getSwarmRunExecutionLane } from "./subagent-run-liveness-D7qiCtn0.mjs"; import { n as findAuthorizedSwarmCollectorRequest, r as findSwarmCollectorSession } from "./subagent-registry-memory-lc6LBIFb.mjs"; import { t as readAcpSessionMetaForEntries } from "./session-meta-readonly-B5S0IsZ_.mjs"; import { n as normalizeSpawnedRunMetadata } from "./spawned-context-wZ6NGSBl.mjs"; import { i as resolveExpectedExistingSessionConstraint } from "./agent-expected-session-tLzLj-o-.mjs"; import { t as resolveSwarmConfig } from "./swarm-config-Dp8TTyRG.mjs"; import { a as readGatewayDedupeEntry, s as resolveAgentDedupeKeys } from "./agent-dedupe-DvejJfx2.mjs"; import { a as parseExecApprovalFollowupApprovalId } from "./bash-tools.exec-approval-followup-state-CdzwahWm.mjs"; import { t as validateStructuredOutputSchema } from "./swarm-output-schema-CXql9BEx.mjs"; import path from "node:path"; //#region src/gateway/agent-turn/agent-request-preflight.ts const COLLECTOR_CONTINUATION_REFUSAL = "Collector children (spawned with collect=true) are one-shot: they accept no steering or follow-up input, including after they finish or time out. Collect the result with agents_wait using the run id from the spawn receipt. To continue the work, start a new child with sessions_spawn that includes the context it needs: give it a larger runTimeoutSeconds if the previous child timed out, and omit collect if the work needs follow-up turns."; async function prepareAgentRequestPreflight(e) { const { request: t } = e; const rejectInvalidRequest = (t) => { e.io.emitAcceptance([ false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, t) ]); }; const n = e.context.getRuntimeConfig(); const r = e.client?.connect?.client?.mode === GATEWAY_CLIENT_MODES.BACKEND; const i = t.sessionKey?.trim(); const a = i ? parseAgentSessionKey(i) : void 0; const o = a?.agentId ?? normalizeOptionalString(t.agentId) ?? tryResolveSessionCompatibilityOwnerAgentId(n, i); if (o) await waitForAgentDatabaseWriteAdmission(o, { owner: e.context.resolveGatewayContext?.()?.agentDatabaseStartup }); const s = i && !a ? resolveRequestedSessionAgentId(n, i, t.agentId) : void 0; if (s && !s.ok) { e.io.emitAcceptance([ false, void 0, s.error ]); return; } const c = a?.agentId ?? s?.agentId ?? normalizeOptionalString(t.agentId) ?? tryResolveLegacyCompatibilityAgentId(n); const l = c ? readAgentDatabaseAdmissionRefusal(c) : void 0; if (l) { e.io.emitAcceptance([ false, void 0, createAgentDatabaseAdmissionErrorShape(l) ]); return; } const u = findSwarmCollectorSession(i, c); let d; const f = !u && i && isSubagentSessionKey(i) ? (await readSessionEntryReadOnlyInWorker({ ...c ? { agentId: c } : {}, storePath: resolveSessionStorePathCore(n.session?.store, { agentId: c }), sessionKey: i }))?.swarmCollector === true : false; if (u || f || t.swarmCollector === true || t.swarmOutputSchema !== void 0) { const i = t.swarmOutputSchema ? validateStructuredOutputSchema(t.swarmOutputSchema) : void 0; if (t.swarmCollector !== true || i) return rejectInvalidRequest(i ?? (u || f ? COLLECTOR_CONTINUATION_REFUSAL : "swarm collector output schemas require swarmCollector=true")); const a = findAuthorizedSwarmCollectorRequest({ childSessionKey: t.sessionKey, childAgentId: c, idempotencyKey: t.idempotencyKey, outputSchema: t.swarmOutputSchema }); const o = readGatewayDedupeEntry({ dedupe: e.context.dedupe, keys: resolveAgentDedupeKeys({ idempotencyKey: t.idempotencyKey }) }); const s = a?.swarmRequesterSessionKey ?? a?.requesterSessionKey; const l = resolveSwarmConfig(n, a?.requesterAgentId ?? (s ? parseAgentSessionKey(s)?.agentId ?? c : c)).enabled; const p = a?.swarmLaunchPending === true && !a.collectorCompletion && typeof a.execution.endedAt !== "number"; if (!l && !o || !r || t.lane !== "subagent" || !a || !p && !o) return rejectInvalidRequest("swarm collector fields require an enabled, host-registered collector run"); d = getSwarmRunExecutionLane(a.schedulerSlotId ?? a.runId); } if (t.cwd && !path.isAbsolute(t.cwd)) return rejectInvalidRequest("cwd must be absolute"); if (t.cwd && !normalizeOptionalString(e.client?.internal?.pluginRuntimeOwnerId)) return rejectInvalidRequest("cwd is reserved for plugin-owned subagent runs"); const p = hasGatewayAdminScope(e.client) || e.client?.internal?.allowModelOverride === true; const m = e.client?.internal?.cronRunContinuation === true; const h = resolveExpectedExistingSessionConstraint({ canUseInternalRuntimeHandoff: r, expectedExistingSessionId: t.expectedExistingSessionId, expectedExistingSessionLifecycleRevision: t.expectedExistingSessionLifecycleRevision, internalRuntimeHandoffId: t.internalRuntimeHandoffId }); if (!h.ok) return rejectInvalidRequest(h.error); const g = t.suppressPromptPersistence === true; const _ = t.sessionEffects === "internal"; const v = Boolean(t.provider || t.model); const y = t.modelRun === true; const b = y || t.promptMode === "none"; if (t.promptMode === "none" && !y) return rejectInvalidRequest("promptMode=\"none\" requires modelRun=true so the run cannot mutate a durable session."); if (v && !p) return rejectInvalidRequest("provider/model overrides are not authorized for this caller."); if ((_ || g) && !r) return rejectInvalidRequest("internal session-effect controls are reserved for backend callers."); const x = t.idempotencyKey; const S = parseExecApprovalFollowupApprovalId(x); if (S && !r) return rejectInvalidRequest("exec approval followup idempotency keys are reserved for backend callers."); const C = normalizeInputProvenance(t.inputProvenance); if (isProgressCardRefreshInputProvenance(C) && !r) return rejectInvalidRequest("Progress refresh input is reserved for progressCard.refresh."); if (isExecCompletionInputProvenance(C) && !r) return rejectInvalidRequest("Exec completion input is reserved for background exec owners."); if (C?.kind === "inter_session" && C.sourceTool === "sessions_send") { const e = C.sourceSessionKey; const t = parseAgentSessionKey(e)?.agentId; const r = e && t ? await withGatewaySessionStoreTarget({ cfg: n, key: e, agentId: t, projection: "full" }, (e) => e) : void 0; const i = r ? r.store[r.canonicalKey] : void 0; let a = Boolean(r && isSubagentSessionFromEntry(r.canonicalKey, i)); if (!a && r && i && (i.parentSessionKey || i.spawnedBy)) { const [e] = await readAcpSessionMetaForEntries({ entries: [{ sessionKey: r.canonicalKey, agentId: r.agentId, entry: i }], cfg: n }); a = isSubagentSessionFromEntry(r.canonicalKey, i, e); } if (a) C.sourceRole = "subagent"; else delete C.sourceRole; } const w = y || _ ? "internal" : t.sessionEffects; const T = resolveAgentDedupeKeys({ idempotencyKey: x, execApprovalFollowupApprovalId: S }); return { request: t, bootstrapContextRunKind: t.bootstrapContextRunKind === "heartbeat" ? "cron" : t.bootstrapContextRunKind, cfg: n, runId: x, allowModelOverride: p, canUseInternalRuntimeHandoff: r, canUseCronRunContinuation: m, expectedSession: h.constraint, expectedExistingSessionId: h.constraint?.sessionId, providerOverride: p ? t.provider : void 0, modelOverride: p ? t.model : void 0, execApprovalFollowupApprovalId: S, normalizedSpawned: normalizeSpawnedRunMetadata({ groupId: t.groupId, groupChannel: t.groupChannel, groupSpace: t.groupSpace }), inputProvenance: C, preserveUserFacingSessionModelState: r && shouldPreserveUserFacingSessionStateForInputProvenance(C), sessionEffects: w, suppressVisibleSessionEffects: w === "internal", requestedPromptPersistenceSuppression: g, isOneShotModelRun: y, isRawModelRun: b, agentDedupeKeys: T, swarmExecutionLane: d }; } //#endregion export { prepareAgentRequestPreflight as t };