openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
338 lines (337 loc) • 11.6 kB
JavaScript
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { Dc as validateAgentWaitParams, Ec as validateAgentParams } from "./src-BX8OAe1J.mjs";
import { d as getAgentEventLifecycleGeneration } from "./agent-events-BdfWYmot.mjs";
import { a as getRpcSourceIdentity, g as isRpcSourceRegistered, h as isRpcSourceQueued, m as isRpcSourceExecuting, o as getRpcSourceLifecycleGeneration, r as getRpcSourceForGateway } from "./session-controller.rpc-sources-CTFbRW2t.mjs";
import { a as removedPluginCapabilityDescriptor } from "./registry-ClBzy_np.mjs";
import { i as validateGatewayMethodParams } from "./validation-DwNk6A-B.mjs";
import { a as waitForGatewayDispatch, i as unwrapGatewayMethodDispatchResponse, r as throwIfGatewayDispatchAborted } from "./server-in-process-dispatch-9g3SxRny.mjs";
import { t as abortChatRunById } from "./chat-abort-DHc0iNFP.mjs";
import { t as authorizeGatewayRequestPreDispatch } from "./request-authorization-DBy_jA62.mjs";
import { i as runWithGatewayObservationScope, r as runWithGatewayRequestEnvelope, t as createRequestGatewayMethodRegistry } from "./server-methods-BODN_2Ja.mjs";
//#region src/gateway/agent-turn/internal-facade.ts
const REMOVED_START_OWNER_EXPIRY = removedPluginCapabilityDescriptor("startOwner.observe().expiresAtMs", "Use startOwner.observe().startDeadlineAtMs for the admission-to-execution-start deadline; it does not limit an already executing turn.");
function throwEnvelopeRejection(e, t) {
return unwrapGatewayMethodDispatchResponse(e, {
ok: false,
error: t
});
}
/** Typed, frame-free access to agent turns owned by the running Gateway instance. */
function createInternalAgentTurnFacade(e) {
const t = e.isWebchatConnect ?? (() => false);
const n = e.getMethodRegistry ?? createRequestGatewayMethodRegistry;
const dispatchRaw = async (r, i = {}) => {
const a = "agent";
throwIfGatewayDispatchAborted(a, i.signal);
i.assertAdmissionCurrent?.();
e.assertContextCurrent?.();
const o = e.getContext();
const s = getAgentEventLifecycleGeneration();
const { agentId: c, expectedExistingSessionId: l, idempotencyKey: u, sessionKey: d } = r;
const f = o.requestEntryLifetime?.enter({
req: {
method: a,
params: r
},
client: e.client,
context: o
});
let p = false;
try {
const m = n();
const h = await authorizeGatewayRequestPreDispatch({
method: a,
requestParams: r,
client: e.client,
context: o,
methodRegistry: m,
controllerInput: i.controllerInput,
assertPreparationCurrent: i.assertAdmissionCurrent
});
h.sessionMutationAuthorization?.release?.();
h.sessionAccessAuthority?.release();
throwIfGatewayDispatchAborted(a, i.signal);
f?.assertOpen();
if (h.error) return {
ok: false,
error: h.error
};
const g = validateGatewayMethodParams(r, validateAgentParams, a);
if (g) return {
ok: false,
error: g
};
e.assertContextCurrent?.();
i.assertAdmissionCurrent?.();
let _;
let v;
const y = createDeferredCore();
let b;
let x;
let S;
let C;
let w;
let T = false;
let E = false;
const isSourceIdentityCurrent = (t) => {
try {
e.assertContextCurrent?.();
const n = getRpcSourceIdentity(t);
E ||= e.getContext() !== o || !isRpcSourceRegistered(t) || t.input.protocolRunId !== u || getAgentEventLifecycleGeneration() !== s || getRpcSourceLifecycleGeneration(t) !== s || c !== void 0 && n.agentId !== c || !isRpcSourceExecuting(t) && n.sessionId !== l || n.sessionKey !== d;
} catch {
E = true;
}
return !E;
};
const publishStartOwner = (e, t) => {
const n = getRpcSourceIdentity(t);
if (T || !i.onStartOwner || e !== u || c !== void 0 && n.agentId !== c || n.sessionKey !== d || n.sessionId !== l || getRpcSourceLifecycleGeneration(t) !== s || !isRpcSourceRegistered(t)) return;
T = true;
const observe = () => {
if (!isSourceIdentityCurrent(t)) return;
const e = isRpcSourceExecuting(t);
if (t.input.abortSignal.aborted || t.input.retirementRequested === true) return;
const n = e ? void 0 : t.input.claim?.operation?.watchdog;
const r = n?.snapshot();
const i = r?.current ? n?.decide() : void 0;
const a = i ? i.action === "observe" || i.action === "warn" ? Math.min(r?.executionDeadlineAtMs ?? Infinity, i.deadlineAtMs ?? Infinity) : Date.now() : void 0;
return Object.defineProperty({
executionStarted: e,
startDeadlineAtMs: a !== void 0 ? Number.isFinite(a) ? a : null : isRpcSourceQueued(t) && t.input.phase === "waiting" ? null : void 0
}, "expiresAtMs", REMOVED_START_OWNER_EXPIRY);
};
i.onStartOwner({
observe,
abort: () => observe()?.executionStarted === false && abortChatRunById(o, {
runId: e,
expectedEntry: t,
sessionKey: getRpcSourceIdentity(t).sessionKey,
stopReason: "timeout"
}).aborted
});
};
let D;
const cancelAcceptedRun = (e) => {
D ??= e;
const t = C;
if (!t || !isRpcSourceRegistered(t.entry)) return;
abortChatRunById(o, {
runId: t.runId,
sessionKey: getRpcSourceIdentity(t.entry).sessionKey,
expectedEntry: t.entry,
stopReason: D
});
};
const O = {
emitStartOwner: (e, t) => {
w = {
runId: e,
entry: t
};
if (i.privateCompletion) S = t.input.settlement.promise;
publishStartOwner(e, t);
},
emitAcceptance: (e, t) => {
if (!_) {
_ = {
ok: e[0],
payload: e[1],
error: e[2],
...t ? { meta: t } : {}
};
y.resolve(_);
const n = typeof t?.runId === "string" && t.runId.length ? t.runId : void 0;
const r = w && w.runId === n && isRpcSourceRegistered(w.entry) ? w.entry : n ? getRpcSourceForGateway(n, o.resolveGatewayContext) : void 0;
if (n && r) {
C = {
entry: r,
runId: n
};
if (D) cancelAcceptedRun(D);
if (t?.cached === true) publishStartOwner(n, r);
}
if (t?.cached === true && r && isRpcSourceExecuting(r)) i.onExecutionStarted?.();
}
},
emitFinal: (e, t) => {
if (!v) {
v = {
ok: e[0],
payload: e[1],
error: e[2],
...t ? { meta: t } : {}
};
b?.resolve(v);
}
},
...i.onExecutionStarted ? { emitExecutionStarted: i.onExecutionStarted } : {}
};
o.trackExecution(async () => {
p = true;
let n;
try {
n = i.executionSource?.retain?.();
return await runWithGatewayRequestEnvelope(a, e.client, async () => {
const [{ prepareAgentRequestPreflight: n }, { createAgentTurnService: s }, { captureAgentTurnPrincipal: c, resolveAgentTurnRunObserver: l }] = await Promise.all([
import("./agent-request-preflight-C0sOUV7J.mjs"),
import("./agent-turn-service-WGn5PZpN.mjs"),
import("./principal-DZb7tInZ.mjs")
]);
if (i.prepareDispatchCurrent) await i.prepareDispatchCurrent();
throwIfGatewayDispatchAborted(a, i.signal);
f?.assertOpen();
e.assertContextCurrent?.();
i.assertAdmissionCurrent?.();
f?.release();
const d = c(e.client);
const p = await n({
request: r,
context: o,
client: d,
io: O
});
if (!p) return;
const m = l({
principal: d,
registerToolEventRecipient: o.registerToolEventRecipient
});
await s({
context: o,
isWebchatConnect: t
}, e.assertContextCurrent).startTurn({
controllerInput: i.controllerInput,
preflight: p,
principal: d,
io: O,
onRunObserved: m,
assertAdmissionCurrent: i.assertAdmissionCurrent,
assertCancellationCurrent: i.assertCancellationCurrent ? () => {
const e = w?.entry;
if (!e || w?.runId !== u || !e.input.abortSignal.aborted || !isSourceIdentityCurrent(e)) throw new Error("Canceled agent request no longer owns its RPC source");
i.assertCancellationCurrent?.();
} : void 0,
executionSource: i.executionSource,
privateCompletion: i.privateCompletion,
replyExpectation: i.replyExpectation,
settleWakeReplay: i.settleWakeReplay
});
}, {
context: o,
isWebchatConnect: t,
methodRegistry: m,
reject: (e) => O.emitAcceptance([
false,
void 0,
e
])
});
} finally {
n?.();
f?.release();
}
}).then(() => {
if (!_) y.reject(/* @__PURE__ */ new Error(`Gateway method "${a}" completed without a response.`));
}, (e) => {
const t = e instanceof Error ? e : new Error(String(e));
if (_) {
x = t;
b?.reject(t);
return;
}
y.reject(t);
});
const k = (async () => {
const e = _ ?? await y.promise;
if (i.expectFinal !== true || e.payload?.status !== "accepted") return e;
i.onAccepted?.(e.payload);
if (x) throw x;
return v ?? await (b = createDeferredCore()).promise;
})();
return await waitForGatewayDispatch(a, i.privateCompletion ? k.then(async (t) => {
await S;
e.assertContextCurrent?.();
return t;
}) : k, i.timeoutMs, i.signal, i.cancelOnDeadline || i.onSignalAbort ? async () => {
if (i.cancelOnDeadline) cancelAcceptedRun("rpc");
await i.onSignalAbort?.();
} : void 0, i.cancelOnDeadline ? () => cancelAcceptedRun("timeout") : void 0);
} finally {
if (!p) f?.release();
}
};
const dispatch = async (e, t = {}) => {
return unwrapGatewayMethodDispatchResponse("agent", await dispatchRaw(e, typeof t === "number" ? { timeoutMs: t } : t));
};
const wait = async (r, i, a, o, s) => {
const c = "agent.wait";
throwIfGatewayDispatchAborted(c, a);
e.assertContextCurrent?.();
const l = e.getContext();
const u = l.requestEntryLifetime?.enter({
req: {
method: c,
params: r
},
client: e.client,
context: l
});
let d = false;
try {
const f = n();
const p = l.trackExecution(async () => {
d = true;
try {
const observe = async (n) => {
const i = await authorizeGatewayRequestPreDispatch({
method: c,
requestParams: r,
client: e.client,
context: l,
methodRegistry: f
});
i.sessionMutationAuthorization?.release?.();
i.sessionAccessAuthority?.release();
throwIfGatewayDispatchAborted(c, a);
u?.assertOpen();
if (i.error) return throwEnvelopeRejection(c, i.error);
const o = validateGatewayMethodParams(r, validateAgentWaitParams, c);
if (o) return throwEnvelopeRejection(c, o);
e.assertContextCurrent?.();
return await runWithGatewayRequestEnvelope(c, e.client, async () => {
n?.();
const { createAgentTurnService: i } = await import("./agent-turn-service-WGn5PZpN.mjs");
if (s) await s();
throwIfGatewayDispatchAborted(c, a);
u?.assertOpen();
e.assertContextCurrent?.();
u?.release();
return (await i({
context: l,
isWebchatConnect: t
}).waitForTurn(r)).result;
}, {
context: l,
isWebchatConnect: t,
methodRegistry: f,
reject: (e) => throwEnvelopeRejection(c, e),
signal: a
});
};
return await (f.isObservation(c) ? runWithGatewayObservationScope(c, observe, [a, e.client?.connectionSignal], (e) => throwEnvelopeRejection(c, e)) : observe());
} finally {
u?.release();
}
});
return await waitForGatewayDispatch(c, p, i, a, o);
} finally {
if (!d) u?.release();
}
};
return {
dispatch,
dispatchRaw,
wait
};
}
//#endregion
export { createInternalAgentTurnFacade as t };