openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
686 lines (685 loc) • 24.7 kB
JavaScript
import { r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs";
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { i as createAbortError } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { Eu as QuestionWaitAnswerResultSchema } from "./src-BX8OAe1J.mjs";
import { C as markReplyPayloadForSourceSuppressionDelivery } from "./reply-payload-k5WsQWxi.mjs";
import { o as getGatewayToolCallerIdentity, t as captureGatewayToolCallerAssertion } from "./gateway-caller-context-BNidAW8G.mjs";
import { C as resolveAgentQuestionAnswerAuthority, T as withAgentQuestionAnswerAuthority, a as captureAgentQuestionAnswerAuthority, t as bindQuestionDispatchGuard, u as prepareQuestionCallerAuthority } from "./host-private-capabilities-DDumj0c_.mjs";
import { f as withQuestionInputAssertion, i as MessageInjectionRequesterMismatchError } from "./message-injection-authority-B9SdalrV.mjs";
import { a as runWithQuestionChannelDeliveries } from "./question-channel-runtime-9JTnl8rq.mjs";
import { a as buildAgentQuestionAnswers, c as refuseQuestionDispatch, i as QuestionDispatchUnsupportedError, l as resolveAgentQuestionGatewayCall, n as QuestionAnswerUnconfirmedError, o as buildAgentQuestionRequestQuestions, r as QuestionDispatchRefusedError, s as prepareQuestionDispatchAuthority, t as PreparedQuestionAnswerRefusedError, u as withQuestionDispatchAuthority } from "./gateway-question-dispatch-BdJ_mO-C.mjs";
import { t as log } from "./logger-DgCpB-Fs.mjs";
import { i as reserveMcpFormQuestion } from "./mcp-form-resource-context-CZnlvKdp.mjs";
import { randomBytes } from "node:crypto";
import { Value } from "typebox/value";
//#region src/agents/tools/gateway-question-lifecycle.ts
/** Shared registration, wait, and cancellation for blocking Gateway questions. */
/** Grace added to Gateway RPC deadlines so the question's own timeout wins. */
const QUESTION_RPC_GRACE_MS$1 = 1e4;
/** Publication ends with the answer, before cancellation or post-answer work. */
function createQuestionPromptLifetime(e) {
const t = new AbortController();
const close = () => t.abort(createAbortError("Question publication ended"));
return {
signal: e ? AbortSignal.any([e, t.signal]) : t.signal,
close,
[Symbol.dispose]: close
};
}
const TERMINAL_QUESTION_ERROR_REASONS = /* @__PURE__ */ new Set(["QUESTION_ALREADY_TERMINAL", "QUESTION_NOT_FOUND"]);
function readQuestionRejection(e) {
const t = asNullableRecord(e);
if (t?.name !== "GatewayClientRequestError") return;
const n = asNullableRecord(t.details)?.reason;
return {
code: t.gatewayCode,
reason: typeof n === "string" ? n : void 0
};
}
function isTerminalQuestionResolveError(e) {
const t = readQuestionRejection(e)?.reason;
return t !== void 0 && TERMINAL_QUESTION_ERROR_REASONS.has(t);
}
async function awaitGatewayQuestionAnswer(e) {
const t = await e.gatewayCall("question.waitAnswer", { timeoutMs: e.timeoutMs + QUESTION_RPC_GRACE_MS$1 }, {
id: e.questionId,
timeoutMs: e.timeoutMs
}, e.signal ? { signal: e.signal } : void 0);
if (!Value.Check(QuestionWaitAnswerResultSchema, t)) throw new Error("question.waitAnswer returned an invalid status");
return t;
}
/**
* Cancels a pending question at most once. An answer that lands between the
* caller's timeout and this cancel makes the Gateway reject it as terminal; the
* recovery read returns that answer so a submitted response is never discarded.
*/
function createGatewayQuestionCanceller(e) {
let t;
return (n) => {
e.beforeCancel?.();
return t ??= (async () => {
try {
await e.gatewayCall("question.resolve", { timeoutMs: QUESTION_RPC_GRACE_MS$1 }, {
id: e.questionId,
cancel: true,
resolvedBy: n
});
return;
} catch (t) {
if (!isTerminalQuestionResolveError(t)) return;
try {
const t = await awaitGatewayQuestionAnswer({
gatewayCall: e.gatewayCall,
questionId: e.questionId,
timeoutMs: 1e3
});
return t.status === "answered" ? t : void 0;
} catch {
return;
}
}
})();
};
}
//#endregion
//#region src/agents/harness/user-input-bridge.ts
function emptyAgentHarnessUserInputAnswers() {
return { answers: {} };
}
function formatAgentHarnessUserInputPrompt(e, t = {}) {
const n = t.formatText ?? ((e) => e);
const r = [t.intro ?? "Agent needs input:"];
e.forEach((i, a) => {
const o = e.length > 1 ? `${a + 1}. ` : "";
r.push("", `${o}${n(i.header)}`, n(i.question));
if (i.isSecret) r.push(t.secretWarning ?? "This channel may show your reply to other participants.");
i.options?.forEach((e, t) => {
r.push(`${t + 1}. ${n(e.label)}${e.description ? ` - ${n(e.description)}` : ""}`);
});
if (i.isOther) r.push(t.otherLabel ?? "Other: reply with your own answer.");
});
return r.join("\n");
}
async function deliverAgentHarnessUserInputPrompt(e, t, n = {}) {
const r = formatAgentHarnessUserInputPrompt(t, n);
if (e.onBlockReply) {
await e.onBlockReply(markReplyPayloadForSourceSuppressionDelivery({
text: r,
presentation: n.presentation
}));
return;
}
await e.onPartialReply?.({ text: r });
}
/** Builds the portable one-question presentation shared by tools and harnesses. */
function buildAgentHarnessQuestionPresentation(e) {
if (e.questions.length !== 1) return;
const [t] = e.questions;
const n = t?.options ?? [];
const r = e.formatText ?? ((e) => e);
if (!t || t.multiSelect || t.isSecret || n.length === 0) return;
const i = [
...n.map((e) => `- ${r(e.label)}${e.description ? `: ${r(e.description)}` : ""}`),
"",
questionReplyGuidance(e.questions)
].join("\n");
return { blocks: [
{
type: "text",
text: r(t.question)
},
{
type: "text",
text: i
},
{
type: "buttons",
buttons: [
...t.url ? [{
label: "Open link",
action: {
type: "url",
url: t.url
}
}] : [],
...n.map((t) => ({
label: r(t.label),
action: {
type: "question",
questionId: e.questionId,
optionValue: t.value ?? t.label
}
})),
...t.isOther ? [{
label: "Other…",
action: {
type: "question",
questionId: e.questionId,
intent: "custom-input"
}
}] : []
]
}
] };
}
/** Builds the exact question payload consumed by web chat and native channels. */
function buildAgentHarnessQuestionPromptPayload(e) {
const t = formatAgentHarnessUserInputPrompt(e.questions, e.options);
const n = e.options?.presentation ?? buildAgentHarnessQuestionPresentation({
...e,
formatText: e.options?.formatText
});
const [r] = e.questions;
const i = e.questions.length === 1 && r && !r.multiSelect && !r.isSecret ? r.options?.map((e) => e.value ?? e.label) ?? [] : [];
const a = i.map((e) => e.trim().toLowerCase());
const o = i.length >= 2 && i.length <= 4 && a.every(Boolean) && new Set(a).size === i.length ? i : void 0;
return markReplyPayloadForSourceSuppressionDelivery({
text: `${t}\n\n${questionReplyGuidance(e.questions)}`,
...n ? {
presentation: n,
presentationTextMode: "fallback"
} : {},
channelData: { askUser: {
questionId: e.questionId,
...o ? { optionValues: o } : {}
} }
});
}
function questionReplyGuidance(e) {
if (e.length !== 1) return "Reply by number or question id. Use a declared option where choices are fixed.";
const [t] = e;
if (!t || (t.options?.length ?? 0) === 0) return "Reply with your answer.";
if (t.multiSelect) return "Reply with comma-separated option numbers or text, or your own answer.";
return t.isOther ? "Reply with the number, the option text, or your own answer." : "Reply with the number or option text.";
}
/** Delivers a gateway-backed question through the harness block-reply surface. */
async function deliverAgentHarnessQuestionPrompt(e, t, n, r, i) {
i?.throwIfAborted();
const a = buildAgentHarnessQuestionPromptPayload({
questionId: t,
questions: n,
options: r
});
if (e.onBlockReply) {
await runWithQuestionChannelDeliveries([t], () => e.onBlockReply?.(a, {
...i ? { abortSignal: i } : {},
deliveryIntentId: `block-reply:v1:agent-question:${t}`
}));
return;
}
i?.throwIfAborted();
await e.onPartialReply?.({ text: a.text });
}
function buildAgentHarnessUserInputAnswers(e, t) {
const n = {};
if (e.length === 1) {
const r = e[0];
if (r) n[r.id] = { answers: normalizeAgentHarnessUserInputAnswers(t, r) };
return { answers: n };
}
const r = parseKeyedAnswers(t);
const i = t.split(/\r?\n/).map((e) => e.trim());
e.forEach((e, t) => {
const a = r.get(e.id.toLowerCase()) ?? r.get(e.header.toLowerCase()) ?? r.get(e.question.toLowerCase()) ?? r.get(String(t + 1)) ?? i[t] ?? "";
n[e.id] = { answers: a ? normalizeAgentHarnessUserInputAnswers(a, e) : [] };
});
return { answers: n };
}
function normalizeAgentHarnessUserInputAnswers(e, t) {
if (!t.multiSelect) {
const n = normalizeAgentHarnessUserInputAnswer(e, t);
return n ? [n] : [];
}
const n = normalizeAgentHarnessUserInputOption(e, t);
if (n) return [n];
const r = e.split(t.answerFormat === "lines" ? /\r?\n/u : /[,;\n]/u).map((e) => normalizeAgentHarnessUserInputAnswer(e, t)).filter((e) => Boolean(e));
return t.presentation === "form" ? r : [...new Set(r)];
}
function normalizeAgentHarnessUserInputAnswer(e, t) {
const n = t.presentation === "form" ? e : e.trim();
const r = normalizeAgentHarnessUserInputOption(n, t);
if (r) return r;
if ((t.options?.length ?? 0) > 0 && !t.isOther) return;
return n || void 0;
}
function normalizeAgentHarnessUserInputOption(e, t) {
const n = e.trim();
const r = t.options ?? [];
const i = /^\d+$/.test(n) ? Number(n) - 1 : -1;
const a = (i >= 0 ? r[i] : void 0) || r.find((r) => r.value === e || (!t.isOther || r.value === void 0) && r.label.toLowerCase() === n.toLowerCase());
return a ? a.value ?? a.label : void 0;
}
function parseKeyedAnswers(e) {
const t = /* @__PURE__ */ new Map();
for (const n of e.split(/\r?\n/)) {
const e = n.match(/^\s*([^:=-]+?)\s*[:=-]\s*(.+?)\s*$/);
if (!e) continue;
const r = e[1]?.trim().toLowerCase();
const i = e[2]?.trim();
if (r && i) t.set(r, i);
}
return t;
}
//#endregion
//#region src/agents/harness/gateway-question.ts
const QUESTION_RPC_GRACE_MS = 1e4;
const pendingAgentQuestions = resolveGlobalMap(Symbol.for("openclaw.pendingAgentQuestions"), (e) => {
const t = /* @__PURE__ */ new Error("gateway lifecycle ended before question registration completed");
for (const n of e.values()) if (n.kind === "gateway") n.rejectRegistration(t);
else n.settle();
e.clear();
});
/** One reservation owns dispatch refusal while input is being resolved. */
function reserveQuestionInput(e, t) {
let n = false;
const refuse = (e) => {
n = true;
return refuseQuestionDispatch(e);
};
const assertCurrent = () => {
try {
withQuestionInputAssertion(() => t?.assertCurrent());
e.answerAuthority?.assertActive();
if (pendingAgentQuestions.get(e.sessionKey) !== e) throw new Error("pending question is no longer current");
} catch (e) {
refuse(e);
}
};
assertCurrent();
if (e.kind === "gateway" && t?.kind === "source-bound" && !e.supportsSourceBound) throw new QuestionDispatchUnsupportedError("source-bound question input requires the default or a version 2 dispatcher");
e.resolving = true;
const r = bindQuestionDispatchGuard(assertCurrent, t, refuse);
return {
assertCurrent,
prepareCurrent: r,
wasRefused: () => n,
extra: e.kind === "gateway" ? { dispatchAuthority: {
version: 2,
kind: t?.kind ?? "run",
assertCurrent,
prepareCurrent: r
} } : void 0,
finish: (t) => {
e.resolving = t;
if (e.kind === "gateway" && !t) e.cancelRequested = false;
}
};
}
/** Registers one gateway question as the next plain-text claim target for its session. */
function registerPendingAgentQuestion(e) {
const t = e.sessionKey.trim();
const n = captureAgentQuestionAnswerAuthority(t);
if (pendingAgentQuestions.get(t)) throw new Error(`session already has a pending agent input request: ${t}`);
const { promise: r, resolve: i, reject: a } = createDeferredCore();
r.catch(() => void 0);
const o = {
kind: "gateway",
...e,
sessionKey: t,
answerAuthority: n,
gatewayCall: resolveAgentQuestionGatewayCall(e.gatewayCall),
supportsSourceBound: typeof e.gatewayCall !== "function",
registration: r,
rejectRegistration: a,
attachRegistration: (e) => {
e.then(i, a);
},
cancelRequested: false,
resolving: false
};
const s = reserveMcpFormQuestion({
...e,
sessionKey: t
});
pendingAgentQuestions.set(t, o);
return {
attachRegistration: o.attachRegistration,
setAnswer: (e) => {
o.answer = e;
},
isCancellationRequested: () => o.cancelRequested,
dispose: () => {
s();
if (pendingAgentQuestions.get(t) === o) pendingAgentQuestions.delete(t);
}
};
}
/** Core ingress claims require the question creator's policy, not an answering-turn owner. */
async function claimPendingAgentQuestionAnswerFromCaller(e) {
const t = e.sessionKey ? pendingAgentQuestions.get(e.sessionKey.trim()) : void 0;
if (!t || t.resolving) return false;
const assertActive = () => {
e.assertSourceCurrent();
t.answerAuthority?.assertActive();
if (!t.answerAuthority) throw new QuestionDispatchRefusedError("pending question has no prepared creator authority");
if (pendingAgentQuestions.get(t.sessionKey) !== t) throw new QuestionDispatchRefusedError("pending question is no longer current");
};
let n;
try {
n = await prepareQuestionCallerAuthority(t.answerAuthority, e.caller, assertActive);
} catch (e) {
if (e instanceof MessageInjectionRequesterMismatchError) {
try {
assertActive();
} catch (e) {
return refuseQuestionDispatch(e);
}
return "requester-mismatch";
}
return refuseQuestionDispatch(e);
}
return claimQuestionAnswer({
sessionKey: e.sessionKey,
text: e.text,
persist: e.persist,
sourceRecorder: e.sourceRecorder,
authority: n
}, e.onAnswerProcessed);
}
/** Owns reservation and persistence; absent questions return before checking caller authority. */
async function claimPendingAgentQuestionAnswer(e) {
return claimQuestionAnswer(e);
}
/** Core ingress revalidates its prepared route after question and source preparation. */
async function claimPreparedPendingAgentQuestionAnswer(e, t) {
return claimQuestionAnswer(e, void 0, t);
}
async function claimQuestionAnswer(e, t, n) {
const r = e.sessionKey?.trim();
const i = r ? pendingAgentQuestions.get(r) : void 0;
if (!i || i.resolving || i.kind === "gateway" && i.cancelRequested) return false;
let a = e.authority;
if (a?.toolAuthorityPreparation || a?.prepareCurrent) a = await prepareQuestionDispatchAuthority(a);
if (pendingAgentQuestions.get(r) !== i || i.resolving || i.kind === "gateway" && i.cancelRequested) return false;
withQuestionInputAssertion(() => a?.assertCurrent());
const o = e.sourceRecorder;
const s = o?.getPendingInputMessage?.() !== void 0;
const c = reserveQuestionInput(i, a);
let l = false;
let u = false;
try {
if (i.kind === "gateway" && !i.answer) {
try {
await i.registration;
} catch {
return false;
}
if (pendingAgentQuestions.get(i.sessionKey) !== i) return false;
}
if (c.prepareCurrent) await c.prepareCurrent();
c.assertCurrent();
if (i.kind !== "secret" || s) {
if (o) try {
await o.persistApproved();
if (s && !o.hasPersisted()) throw new Error("staged question source was not committed");
} catch (e) {
if (s) throw new QuestionDispatchRefusedError("Question answer source was not persisted", { cause: e });
throw e;
}
else await e.persist?.();
}
if (n) try {
await n();
c.assertCurrent();
} catch (e) {
throw new PreparedQuestionAnswerRefusedError(e);
}
c.assertCurrent();
if (i.kind === "secret") {
l = await withQuestionDispatchAuthority(c, () => i.settle(e.text));
return l;
}
i.answerAuthority?.admitTranscriptAnswer?.(o);
const r = buildAgentHarnessUserInputAnswers(i.questions, e.text);
const a = buildAgentQuestionAnswers(r);
const d = randomBytes(16).toString("hex");
try {
await i.gatewayCall("question.resolve", {}, {
id: i.questionId,
answers: a,
resolvedBy: "plain-text",
resolutionId: d
}, ...c.extra ? [c.extra] : []);
l = true;
} catch (e) {
if (c.wasRefused()) throw e;
if (isTerminalQuestionResolveError(e)) {
u = true;
return false;
}
const n = readQuestionRejection(e);
if (n?.code === "INVALID_REQUEST" || n?.code === "FORBIDDEN") {
if (n.code === "INVALID_REQUEST" && n.reason === "QUESTION_INVALID_ANSWER") t?.();
throw e;
}
const r = await i.answer?.catch(() => void 0);
u = true;
if (!r || r.status === "pending" || r.status === "answered" && r.resolutionId === void 0) throw new QuestionAnswerUnconfirmedError(e);
l = r.status === "answered" && r.resolutionId === d;
}
if (l) t?.();
return l;
} finally {
c.finish(l || u);
}
}
/** Cancels a question before the same inbound message takes another route. */
async function cancelPendingAgentQuestionForSession(e) {
const t = e.sessionKey?.trim();
const n = t ? pendingAgentQuestions.get(t) : void 0;
if (!n || n.resolving) return false;
let r = e.authority;
if (r?.toolAuthorityPreparation || r?.prepareCurrent) r = await prepareQuestionDispatchAuthority(r);
if (pendingAgentQuestions.get(n.sessionKey) !== n || n.resolving) return false;
const i = reserveQuestionInput(n, r);
const a = e.authority?.kind === "source-bound";
let o = false;
try {
if (n.kind === "secret") {
o = await withQuestionDispatchAuthority(i, () => n.settle());
return o;
}
n.cancelRequested = !a;
if (a && !n.answer) try {
await n.registration;
} catch {
return false;
}
if (i.prepareCurrent) await i.prepareCurrent();
i.assertCurrent();
try {
await n.gatewayCall("question.resolve", { timeoutMs: QUESTION_RPC_GRACE_MS }, {
id: n.questionId,
cancel: true,
resolvedBy: e.resolvedBy
}, ...i.extra ? [i.extra] : []);
} catch (e) {
if (i.wasRefused() || !isTerminalQuestionResolveError(e)) throw e;
}
o = true;
n.onCancel?.(e.resolvedBy);
return true;
} finally {
i.finish(o);
}
}
/** Presents one warned secret prompt and keeps its answer out of durable question records. */
function runAgentHarnessSecretInput(e) {
e.signal?.throwIfAborted();
const t = e.sessionKey.trim();
const n = captureAgentQuestionAnswerAuthority(t);
if (!t) throw new Error("secret input requires a session key");
if (pendingAgentQuestions.has(t)) throw new Error(`session already has a pending agent input request: ${t}`);
return new Promise((r) => {
const finish = (n) => {
if (pendingAgentQuestions.get(t) !== a) return false;
pendingAgentQuestions.delete(t);
clearTimeout(i);
e.signal?.removeEventListener("abort", onAbort);
r(n);
return true;
};
const onAbort = () => finish();
const i = setTimeout(onAbort, e.timeoutMs);
i.unref();
const a = {
kind: "secret",
sessionKey: t,
answerAuthority: n,
resolving: false,
settle: finish
};
pendingAgentQuestions.set(t, a);
e.signal?.addEventListener("abort", onAbort, { once: true });
if (e.signal?.aborted) {
onAbort();
return;
}
deliverAgentHarnessUserInputPrompt(e.delivery, e.questions, e.promptOptions).catch(() => {
if (finish()) log.warn("Secret input prompt delivery failed; the pending input request was cancelled.");
});
});
}
/** Registers, presents, and waits for one harness-owned gateway question record. */
async function runAgentHarnessGatewayQuestion(e) {
const t = resolveAgentQuestionAnswerAuthority(e.delivery.hostCapabilities);
return await withAgentQuestionAnswerAuthority(t, () => runScopedAgentHarnessQuestion(e));
}
async function runScopedAgentHarnessQuestion(e) {
try {
var t = _usingCtx();
if (e.questions.some((e) => e.isSecret)) {
const t = await runAgentHarnessSecretInput(e);
if (t === void 0) return { status: "cancelled" };
const n = buildAgentHarnessUserInputAnswers(e.questions, t);
return {
status: "answered",
answers: buildAgentQuestionAnswers(n)
};
}
const n = resolveAgentQuestionGatewayCall(e.gatewayCall);
const r = e.questionId ?? `ask_${randomBytes(16).toString("hex")}`;
const i = buildAgentQuestionRequestQuestions(e.questions);
const a = getGatewayToolCallerIdentity()?.watchdogAttempt;
const o = captureGatewayToolCallerAssertion();
let s;
e.signal?.throwIfAborted();
const c = t.u(createQuestionPromptLifetime(e.signal));
const l = registerPendingAgentQuestion({
questionId: r,
sessionKey: e.sessionKey,
agentId: e.agentId,
questions: e.questions,
gatewayCall: e.gatewayCall,
onCancel: c.close
});
const u = Promise.resolve().then(() => n("question.request", {}, {
id: r,
questions: i,
sessionKey: e.sessionKey,
...e.agentId ? { agentId: e.agentId } : {},
...e.runId ? { runId: e.runId } : {},
timeoutMs: e.timeoutMs
}, e.signal ? { signal: e.signal } : void 0));
l.attachRegistration(u);
const cancel = async (e) => {
c.close();
try {
return await n("question.resolve", { timeoutMs: QUESTION_RPC_GRACE_MS }, {
id: r,
cancel: true,
resolvedBy: e
});
} catch (e) {
if (!isTerminalQuestionResolveError(e)) throw e;
try {
const e = await n("question.waitAnswer", { timeoutMs: QUESTION_RPC_GRACE_MS }, {
id: r,
timeoutMs: 1e3
});
return e.status === "answered" ? e : void 0;
} catch {
return;
}
}
};
const onAbort = () => {
c.close();
l.dispose();
cancel("run-abort").catch(() => void 0);
};
try {
e.signal?.addEventListener("abort", onAbort, { once: true });
if (e.signal?.aborted) {
onAbort();
e.signal.throwIfAborted();
}
const t = await u;
if (t.id !== r) throw new Error("question.request returned an unexpected question id");
if (l.isCancellationRequested() || e.signal?.aborted) {
const t = await cancel(e.signal?.aborted ? "run-abort" : "superseded-input");
if (t?.status === "answered") return t;
return { status: "cancelled" };
}
s = a?.beginWait({
kind: "human_question",
deadlineAtMs: t.expiresAtMs,
isCurrent: () => {
e.signal?.throwIfAborted();
o?.();
return !l.isCancellationRequested();
}
});
const i = n("question.waitAnswer", { timeoutMs: e.timeoutMs + QUESTION_RPC_GRACE_MS }, {
id: r,
timeoutMs: e.timeoutMs,
includeResolutionId: true
}, e.signal ? { signal: e.signal } : void 0).finally(c.close);
l.setAnswer(i);
const d = i.then((e) => ({
kind: "answer",
result: e
}));
const finishAnswer = async (e) => {
const t = e.status === "pending" ? await cancel("wait-timeout") ?? { status: "cancelled" } : e;
if (t.status === "answered") a?.progress("semantic", "human_input:resolved");
return t.status === "answered" ? {
status: t.status,
answers: t.answers
} : t;
};
const f = deliverAgentHarnessQuestionPrompt(e.delivery, r, e.questions, e.promptOptions, c.signal).then(() => ({ kind: "delivery" }), (e) => ({
kind: "delivery-error",
error: e
}));
const p = await Promise.race([d, f]);
if (p.kind === "answer") return await finishAnswer(p.result);
if (p.kind === "delivery-error") {
const e = await cancel("prompt-delivery-failed");
if (e?.status === "answered") return e;
throw new Error("harness question prompt delivery failed", { cause: p.error });
}
return await finishAnswer(await i);
} catch (t) {
try {
const t = await cancel(e.signal?.aborted ? "run-abort" : "harness-error");
if (t?.status === "answered") return t;
} catch {}
if (e.signal?.aborted) return { status: "cancelled" };
throw t;
} finally {
s?.close();
e.signal?.removeEventListener("abort", onAbort);
l.dispose();
}
} catch (e) {
t.e = e;
} finally {
t.d();
}
}
//#endregion
export { registerPendingAgentQuestion as a, buildAgentHarnessUserInputAnswers as c, formatAgentHarnessUserInputPrompt as d, normalizeAgentHarnessUserInputAnswer as f, readQuestionRejection as g, createQuestionPromptLifetime as h, claimPreparedPendingAgentQuestionAnswer as i, deliverAgentHarnessUserInputPrompt as l, createGatewayQuestionCanceller as m, claimPendingAgentQuestionAnswer as n, runAgentHarnessGatewayQuestion as o, awaitGatewayQuestionAnswer as p, claimPendingAgentQuestionAnswerFromCaller as r, buildAgentHarnessQuestionPromptPayload as s, cancelPendingAgentQuestionForSession as t, emptyAgentHarnessUserInputAnswers as u };