UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

392 lines (391 loc) • 16.2 kB
import { r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs"; import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { s as raceWithTimeout } from "./src-BPmQBLJp.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import "./crypto-digest-B2m8wIBj.mjs"; import { n as ASK_USER_TOOL_DISPLAY_SUMMARY, x as describeAskUserTool } from "./tool-catalog-C1ALpCJD.mjs"; import { r as textResult } from "./tool-results-CcV0sxnb.mjs"; import { n as ToolInputError } from "./tool-input-error-B1hgavSw.mjs"; import "./common-njQNtpnW.mjs"; import { C as resolveAgentQuestionAnswerAuthority, T as withAgentQuestionAnswerAuthority } from "./host-private-capabilities-DDumj0c_.mjs"; import { a as runWithQuestionChannelDeliveries } from "./question-channel-runtime-9JTnl8rq.mjs"; import { i as isReplyDispatchDeliveryError } from "./reply-dispatch-outcome-C1yqMjJt.mjs"; import { l as resolveAgentQuestionGatewayCall } from "./gateway-question-dispatch-BdJ_mO-C.mjs"; import { a as registerPendingAgentQuestion, g as readQuestionRejection, h as createQuestionPromptLifetime, m as createGatewayQuestionCanceller, s as buildAgentHarnessQuestionPromptPayload } from "./gateway-question-u5Q7erev.mjs"; import { n as QUESTION_RPC_GRACE_MS, r as normalizeAskUserParams, t as AskUserToolSchema } from "./ask-user-tool-normalization-BkE0uL3h.mjs"; import { i as resolveControlUiSessionLinkBase } from "./control-ui-link-base-Drx2Z5zY.mjs"; //#region src/agents/tools/question-prompt-send.ts /** Host-generated capability guidance that is safe to return to the model. */ var QuestionPromptUnavailableError = class extends Error {}; /** * Publishes the prompt for an already-committed gateway question record. * * Rejects when the question cannot become answerable where it was asked, which is * what tells the caller to cancel the pending record instead of waiting it out. */ async function sendQuestionToolPrompt(e) { const { questionId: t, questions: n } = e; const send = (n) => runWithQuestionChannelDeliveries([t], () => e.signal ? e.send(n, { signal: e.signal }) : e.send(n)); if (e.toolName === "secrets") { const r = n[0]?.secretStore; if (!r) return; const i = resolveControlUiSessionLinkBase(e.config); const a = i ? `🔑 Agent requests credential ${r.name} (${r.kind}). Reply is disabled for secrets — open to provide it: ${i}/ask/${encodeURIComponent(t)}` : "Credential request unavailable here: no reachable Control UI link. Open a trusted Control UI or native app and retry, or ask the operator to enable Control UI and configure gateway.publicOrigin. Never send credentials in chat."; await send({ text: a, channelData: { askUser: { questionId: t } } }); if (!i) throw new QuestionPromptUnavailableError(a); return; } await send(buildAgentHarnessQuestionPromptPayload({ questionId: t, questions: n.map(({ questionId: e, ...t }) => Object.assign(t, { id: e })), options: { intro: "Question for you:" } })); } //#endregion //#region src/agents/tools/ask-user-tool.ts const ASK_USER_PROMPT_RECHECK_MS = 50; const askUserQuestions = resolveGlobalMap(Symbol.for("openclaw.askUserQuestions")); /** Stable client-generated gateway question id shared with tool-start delivery. */ function buildAskUserQuestionId(e, t, n, r) { const i = `${n?.trim() || askUserSessionKey(t, r)}\0${e}`; return `ask_${sha256Hex(i).slice(0, 32)}`; } function askUserSessionKey(e, t) { const n = e?.trim(); if (n && parseAgentSessionKey(n)) return n; return `${t?.trim() || "unknown"}\0${n || "session:unknown"}`; } function findAskUserQuestionForSession(e) { for (const t of askUserQuestions.values()) if (t.sessionKey === e) return t; } function transitionAskUserQuestion(e, t) { e.phase = t; for (const t of e.waiters) t(); e.waiters.clear(); } function releaseAskUserQuestion(e) { const t = askUserQuestions.get(e); if (!t) return; askUserQuestions.delete(e); t.claim?.dispose(); for (const e of t.waiters) e(); t.waiters.clear(); } async function waitForQuestionChange(e, t) { t?.throwIfAborted(); await new Promise((n, r) => { const wake = () => { t?.removeEventListener("abort", onAbort); n(); }; const onAbort = () => { e.waiters.delete(wake); r(t?.reason instanceof Error ? t.reason : /* @__PURE__ */ new Error("ask_user aborted")); }; e.waiters.add(wake); t?.addEventListener("abort", onAbort, { once: true }); }); } /** Reserves one visible ask_user prompt slot before subscriber delivery. */ function reserveAskUserPromptDelivery(e) { const t = askUserSessionKey(e.sessionKey, e.agentId); if (findAskUserQuestionForSession(t)) return; const n = buildAskUserQuestionId(e.toolCallId, e.sessionKey, e.runId, e.agentId); if (askUserQuestions.has(n)) return; askUserQuestions.set(n, { questionId: n, sessionKey: t, questions: e.questions, expiresAtMs: Date.now() + (e.timeoutSeconds ?? 900) * 1e3, phase: { kind: "reserved" }, waiters: /* @__PURE__ */ new Set() }); return { questionId: n }; } /** Waits until policy-accepted tool execution has registered the gateway question. */ async function waitForAskUserPromptReady(e, t = resolveAgentQuestionGatewayCall()) { const n = askUserQuestions.get(e); if (!n) return; while (askUserQuestions.get(e) === n) { if (n.phase.kind === "prompting" || n.phase.kind === "answerable" || n.phase.kind === "resolving" || n.phase.kind === "prompt-failed") return n.questions; try { const r = await readAskUserQuestionStatus(e, t); if (r === "pending") return n.questions; if (typeof r === "string") return; } catch {} await sleep(50); } } async function readAskUserQuestionStatus(e, t) { const n = await t("question.list", { timeoutMs: QUESTION_RPC_GRACE_MS }, {}); const r = asNullableRecord(n)?.questions; const i = Array.isArray(r) ? r.find((t) => asNullableRecord(t)?.id === e) : void 0; const a = asNullableRecord(i)?.status; return typeof a === "string" ? a : void 0; } async function readAskUserQuestionStatusBeforeExpiry(e, t, n) { const r = t - Date.now(); if (r <= 0) return { kind: "expired" }; return await raceWithTimeout(() => readAskUserQuestionStatus(e, n).then((e) => ({ kind: "status", status: e }), () => ({ kind: "error" })), r, () => ({ kind: "expired" })); } /** Opens prompt delivery after question.request succeeds. */ function markAskUserPromptReady(e, t) { const n = askUserQuestions.get(e); if (!n || n.phase.kind !== "reserved" && n.phase.kind !== "registering") return; n.questions = t; transitionAskUserQuestion(n, { kind: "prompting" }); } /** Records whether the originating-conversation prompt reached its delivery callback. */ function settleAskUserPromptDelivery(e, t) { const n = askUserQuestions.get(e); if (!n || n.phase.kind !== "prompting") return; transitionAskUserQuestion(n, t === void 0 ? { kind: "answerable" } : { kind: "prompt-failed", error: t }); } /** * Settles the prompt wait from the same run that published the prompt. * * Detached on purpose: the waiter below races prompt delivery against the answer, * so this must not block the tool call that is registering that answer. */ function settleAfterOwnPromptDelivery(e, t) { t.then(() => settleAskUserPromptDelivery(e), (t) => settleAskUserPromptDelivery(e, t)); } /** Rechecks the Gateway immediately before exposing an answerable prompt. */ async function isAskUserPromptPending(e, t = resolveAgentQuestionGatewayCall()) { const n = askUserQuestions.get(e); if (!n) return false; while (askUserQuestions.get(e) === n) { if (n.phase.kind === "resolving" || n.phase.kind === "prompt-failed") return false; const r = await readAskUserQuestionStatusBeforeExpiry(e, n.expiresAtMs, t); if (r.kind === "expired") return false; const i = askUserQuestions.get(e); if (i !== n || i.phase.kind === "resolving" || i.phase.kind === "prompt-failed") return false; if (r.kind === "status" && r.status === "pending") return true; if (r.kind === "status" && typeof r.status === "string") return false; const a = n.expiresAtMs - Date.now(); if (a <= 0) return false; await sleep(Math.min(ASK_USER_PROMPT_RECHECK_MS, a)); } return false; } /** Releases a tool-start reservation when policy rejects execution. */ function cancelAskUserPromptDelivery(e, t, n, r) { releaseAskUserQuestion(buildAskUserQuestionId(e, t, n, r)); } function answeredResult(e, t) { const n = { status: "answered", answers: t }; const r = e.map((e) => { const n = t.answers[e.questionId] ?? []; return `${e.header}: ${n.length > 0 ? n.join(", ") : "(no answer)"}`; }); return textResult(`${r.join("\n")}\n\n${JSON.stringify(n, null, 2)}`, n); } function noAnswerResult(e) { const t = { status: "no_answer" }; return textResult(`${e === "cancelled" ? "The question was cancelled; proceed with best judgment." : "No answer arrived; proceed with best judgment."}\n\n${JSON.stringify(t, null, 2)}`, t); } async function waitForPromptDelivery(e, t) { while (askUserQuestions.get(e.questionId) === e) { if (e.phase.kind === "answerable" || e.phase.kind === "resolving") return {}; if (e.phase.kind === "prompt-failed") return { error: e.phase.error }; await waitForQuestionChange(e, t); } return { error: /* @__PURE__ */ new Error("ask_user prompt is no longer active") }; } /** Shares question ownership and prompt delivery without installing a plaintext answer claim. */ function beginAskUserPromptDelivery(e) { return createAskUserPromptDelivery(buildAskUserQuestionId(e.toolCallId, e.sessionKey, e.runId, e.agentId), askUserSessionKey(e.sessionKey, e.agentId), e.questions, e.timeoutSeconds, "a question is already pending for this session; wait for it to resolve before requesting another", e.deliverPrompt).delivery; } function createAskUserPromptDelivery(e, t, n, r, i, a) { const o = askUserQuestions.get(e); const s = findAskUserQuestionForSession(t); if (o && o.phase.kind !== "reserved" || s && s !== o) throw new ToolInputError(i); const c = o ?? { questionId: e, sessionKey: t, questions: n, expiresAtMs: 0, phase: { kind: "registering" }, waiters: /* @__PURE__ */ new Set() }; Object.assign(c, { sessionKey: t, questions: n }); c.expiresAtMs = Date.now() + r * 1e3; transitionAskUserQuestion(c, { kind: "registering" }); askUserQuestions.set(e, c); return { state: c, delivery: { questionId: e, hasSubscriber: o !== void 0 || a !== void 0, markReady() { if (o || a) markAskUserPromptReady(e, n); else transitionAskUserQuestion(c, { kind: "answerable" }); if (!o && a) settleAfterOwnPromptDelivery(e, a(e)); }, waitForDelivery(e) { return waitForPromptDelivery(c, e); }, release() { if (askUserQuestions.get(e) === c) releaseAskUserQuestion(e); } } }; } /** Creates the main-session-only blocking ask_user tool. */ function createAskUserTool(e) { const t = resolveAgentQuestionAnswerAuthority(); const n = resolveAgentQuestionGatewayCall(e.gatewayCall); return { label: "Ask User", name: "ask_user", displaySummary: ASK_USER_TOOL_DISPLAY_SUMMARY, description: describeAskUserTool(), parameters: AskUserToolSchema, execute: async (r, i, a) => { try { var o = _usingCtx(); const s = buildAskUserQuestionId(r, e.sessionKey, e.runId, e.agentId); let c; try { a?.throwIfAborted(); c = normalizeAskUserParams(i); } catch (e) { releaseAskUserQuestion(s); throw e; } const l = askUserSessionKey(e.sessionKey, e.agentId); const u = c.timeoutSeconds * 1e3; const d = e.questionPrompt?.send; const { state: f, delivery: p } = createAskUserPromptDelivery(s, l, c.questions, c.timeoutSeconds, "ask_user already has a pending question for this session; wait for it to resolve before asking another", d ? (e) => sendQuestionToolPrompt({ toolName: "ask_user", questionId: e, questions: c.questions, send: d, signal: m.signal }) : void 0); const m = o.u(createQuestionPromptLifetime(a)); let h = false; const g = createGatewayQuestionCanceller({ gatewayCall: n, questionId: s, beforeCancel: m.close }); const cancelOnAbort = () => { m.close(); p.release(); g("run-abort"); }; const finishWait = async (e) => { const t = e.status === "pending" ? await g("wait-timeout") ?? e : e; if (t.status === "answered") return answeredResult(c.questions, t.answers); if (t.status === "pending" || t.status === "expired" || t.status === "cancelled") return noAnswerResult(t.status); throw new Error("question.waitAnswer returned an invalid status"); }; try { f.claim = withAgentQuestionAnswerAuthority(t, () => registerPendingAgentQuestion({ questionId: s, sessionKey: l, questions: c.questions.map(({ questionId: e, ...t }) => ({ ...t, id: e })), gatewayCall: e.gatewayCall, onCancel: () => { m.close(); if (askUserQuestions.get(s) === f && f.phase.kind !== "reserved" && f.phase.kind !== "resolving" && f.phase.kind !== "prompt-failed") transitionAskUserQuestion(f, { kind: "resolving" }); } })); const r = Promise.resolve().then(() => n("question.request", {}, { id: s, questions: c.questions, ...e.agentId ? { agentId: e.agentId } : {}, ...e.sessionKey ? { sessionKey: e.sessionKey } : {}, ...e.runId ? { runId: e.runId } : {}, timeoutMs: u }, a ? { signal: a } : void 0)); f.claim.attachRegistration(r); const i = await r; h = true; if (i.id !== s) throw new Error("question.request returned an unexpected question id"); if (f.claim.isCancellationRequested()) { const e = await g("superseded-input"); return e ? answeredResult(c.questions, e.answers) : noAnswerResult("cancelled"); } a?.addEventListener("abort", cancelOnAbort, { once: true }); if (a?.aborted) { cancelOnAbort(); a.throwIfAborted(); } const o = n("question.waitAnswer", { timeoutMs: u + QUESTION_RPC_GRACE_MS }, { id: s, timeoutMs: u, includeResolutionId: true }, a ? { signal: a } : void 0).finally(m.close); f.claim.setAnswer(o); p.markReady(); if (p.hasSubscriber) { const e = p.waitForDelivery(a); const t = await Promise.race([e.then((e) => ({ kind: "delivery", result: e })), o.then((e) => ({ kind: "answer", result: e }))]); a?.throwIfAborted(); if (t.kind === "answer") return await finishWait(t.result); const n = t.result; if (n.error !== void 0) { const e = await g("prompt-delivery-failed"); if (e) return answeredResult(c.questions, e.answers); if (isReplyDispatchDeliveryError(n.error) && n.error.outcome === "failed-deliver") { const e = { status: "delivery_failed" }; return { ...textResult(`The prompt became visible, but its controls failed to deliver. The question was cancelled; no retry/fallback should be sent.\n\n${JSON.stringify(e, null, 2)}`, e), terminate: true }; } throw new Error("ask_user prompt delivery failed", { cause: n.error }); } } const d = await o; a?.throwIfAborted(); return await finishWait(d); } catch (e) { if (h || readQuestionRejection(e)?.reason !== "QUESTION_ID_IN_USE") { const e = await g(a?.aborted ? "run-abort" : h ? "tool-error" : "registration-failed"); if (!a?.aborted && e) return answeredResult(c.questions, e.answers); } throw e; } finally { a?.removeEventListener("abort", cancelOnAbort); p.release(); } } catch (e) { o.e = e; } finally { o.d(); } } }; } //#endregion export { reserveAskUserPromptDelivery as a, QuestionPromptUnavailableError as c, isAskUserPromptPending as i, sendQuestionToolPrompt as l, cancelAskUserPromptDelivery as n, settleAskUserPromptDelivery as o, createAskUserTool as r, waitForAskUserPromptReady as s, beginAskUserPromptDelivery as t };