File size: 21,948 Bytes
4440aec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 | // Approval shared helpers normalize pending exec/plugin approval lookups,
// decision payloads, turn-source routing, and gateway error responses.
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import { ErrorCodes, errorShape } from "../../../packages/gateway-protocol/src/index.js";
import type {
ApprovalChannelReviewer,
ValidationError,
} from "../../../packages/gateway-protocol/src/index.js";
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import { hasApprovalTurnSourceRoute } from "../../infra/approval-turn-source.js";
import type { ChannelApprovalKind } from "../../infra/approval-types.js";
import type {
ExecApprovalDecision,
ExecApprovalRequestPayload,
} from "../../infra/exec-approvals.js";
import type { PluginApprovalRequestPayload } from "../../infra/plugin-approvals.js";
import { createDeferredCore } from "../../shared/deferred.js";
import { prepareApprovalChannelCustody } from "../approval-channel-custody.js";
import type { ExecApprovalManager, ExecApprovalRecord } from "../exec-approval-manager.js";
import {
type ApprovalRecordLookupResult,
isApprovalRecordVisibleToClient,
normalizeApprovalIdentities,
resolvePendingApprovalRecord,
resolveResolvedApprovalRecord,
respondPendingApprovalLookupError,
respondUnknownOrExpiredApproval,
} from "./approval-record-lookup.js";
import { buildWaitResponse, type WaitReasonResolver } from "./approval-wait-response.js";
import type { GatewayClient, GatewayRequestContext, RespondFn } from "./types.js";
import { assertValidParams } from "./validation.js";
export {
isApprovalRecordVisibleToClient,
listVisiblePendingApprovalRequests,
resolvePendingApprovalRecord,
respondPendingApprovalLookupError,
} from "./approval-record-lookup.js";
const APPROVAL_ALREADY_RESOLVED_DETAILS = {
reason: "APPROVAL_ALREADY_RESOLVED",
} as const;
function resolveRecordedApprovalDecision<TPayload>(
record: ExecApprovalRecord<TPayload>,
): ExecApprovalDecision | undefined {
return record.decision ?? record.consumedDecision;
}
type ApprovalTurnSourceFields = {
turnSourceChannel?: string | null;
turnSourceAccountId?: string | null;
};
type RequestedApprovalEvent<
TPayload extends ApprovalTurnSourceFields,
TKind extends ChannelApprovalKind = ChannelApprovalKind,
> = {
approvalKind?: TKind;
id: string;
request: TPayload;
createdAtMs: number;
expiresAtMs: number;
};
type ResolvedApprovalEvent<TPayload> = {
id: string;
decision: ExecApprovalDecision;
resolvedBy: string | null;
ts: number;
request: TPayload;
};
type ApprovalRequestDeliveryRoute = "approval-client" | "forwarder" | "turn-source" | "none";
type ApprovalResolveParams = {
id: string;
decision: string;
reviewer?: ApprovalChannelReviewer;
};
type ApprovalResolveParamsValidator<TParams extends ApprovalResolveParams> = ((
params: unknown,
) => params is TParams) & {
errors?: ValidationError[] | null;
};
function isApprovalDecision(value: string): value is ExecApprovalDecision {
return value === "allow-once" || value === "allow-always" || value === "deny";
}
/** Binds the current gateway client identity onto a newly-created approval record. */
export function bindApprovalRequesterMetadata<TPayload>(params: {
record: ExecApprovalRecord<TPayload>;
client?: GatewayClient | null;
}): void {
params.record.requestedByConnId = params.client?.connId ?? null;
params.record.requestedByDeviceId = params.client?.connect?.device?.id ?? null;
params.record.requestedByClientId = params.client?.connect?.client?.id ?? null;
params.record.requestedByDeviceTokenAuth = params.client?.isDeviceTokenAuth === true;
}
export function bindApprovalReviewerDeviceIds<TPayload>(params: {
record: ExecApprovalRecord<TPayload>;
deviceIds?: readonly string[] | null;
}): void {
const deviceIds = normalizeApprovalIdentities(params.deviceIds);
if (deviceIds.length > 0) {
params.record.approvalReviewerDeviceIds = deviceIds;
}
}
export function respondApprovalStorageUnavailable(params: {
context: GatewayRequestContext;
respond: RespondFn;
operation: "request" | "resolve" | "history" | "lookup";
error: unknown;
}): void {
params.context.logGateway?.error?.(
`approval ${params.operation} storage failure: ${String(params.error)}`,
);
params.respond(
false,
undefined,
errorShape(ErrorCodes.UNAVAILABLE, `approval ${params.operation} unavailable`),
);
}
/** Registers an approval record and converts manager registration errors to gateway errors. */
export function registerPendingApprovalRecord<TPayload>(params: {
manager: ExecApprovalManager<TPayload>;
record: ExecApprovalRecord<TPayload>;
timeoutMs: number;
respond: RespondFn;
context: GatewayRequestContext;
}): Promise<ExecApprovalDecision | null> | undefined {
try {
return params.manager.register(params.record, params.timeoutMs);
} catch (err) {
respondApprovalStorageUnavailable({ ...params, operation: "request", error: err });
return undefined;
}
}
/** Builds the gateway event payload broadcast when an approval starts waiting. */
export function buildRequestedApprovalEvent<
TPayload extends ApprovalTurnSourceFields,
TKind extends ChannelApprovalKind,
>(
record: ExecApprovalRecord<TPayload>,
approvalKind?: TKind,
): RequestedApprovalEvent<TPayload, TKind> {
return {
...(approvalKind ? { approvalKind } : {}),
id: record.id,
request: record.request,
createdAtMs: record.createdAtMs,
expiresAtMs: record.expiresAtMs,
};
}
/** Validates approval resolve params and narrows the decision to the supported enum. */
export function resolveApprovalDecisionParams<TParams extends ApprovalResolveParams>(params: {
rawParams: unknown;
validate: ApprovalResolveParamsValidator<TParams>;
methodName: string;
respond: RespondFn;
}): {
inputId: string;
decision: ExecApprovalDecision;
reviewer?: ApprovalChannelReviewer;
} | null {
const rawParams = params.rawParams;
if (!assertValidParams(rawParams, params.validate, params.methodName, params.respond)) {
return null;
}
if (!isApprovalDecision(rawParams.decision)) {
params.respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "invalid decision"));
return null;
}
return {
inputId: rawParams.id,
decision: rawParams.decision,
...(rawParams.reviewer ? { reviewer: rawParams.reviewer } : {}),
};
}
/** Resolves the approval clients that should receive request or resolution events. */
function resolveApprovalRequestRecipientConnIds<TPayload>(params: {
approvalKind: "exec" | "plugin" | "system-agent";
context: GatewayRequestContext;
record: ExecApprovalRecord<TPayload>;
excludeConnId?: string;
}): ReadonlySet<string> | null {
return (
params.context.getApprovalClientConnIds?.({
approvalKind: params.approvalKind,
excludeConnId: params.excludeConnId,
record: params.record,
filter: (client) =>
isApprovalRecordVisibleToClient({
record: params.record,
client,
}),
}) ?? null
);
}
/** Sends a resolved approval only to clients authorized for its live binding. */
export function broadcastApprovalResolvedEvent<TPayload>(params: {
approvalKind: "exec" | "plugin" | "system-agent";
context: GatewayRequestContext;
record: ExecApprovalRecord<TPayload>;
event: ResolvedApprovalEvent<TPayload>;
}): void {
const eventName =
params.approvalKind === "system-agent"
? "openclaw.approval.resolved"
: `${params.approvalKind}.approval.resolved`;
const recipientConnIds = resolveApprovalRequestRecipientConnIds({
approvalKind: params.approvalKind,
context: params.context,
record: params.record,
});
if (recipientConnIds) {
params.context.broadcastToConnIds(eventName, params.event, recipientConnIds, {
dropIfSlow: true,
});
return;
}
params.context.broadcast(eventName, params.event, { dropIfSlow: true });
}
export async function handleApprovalWaitDecision<TPayload>(params: {
manager: ExecApprovalManager<TPayload>;
inputId: unknown;
client?: GatewayClient | null;
cfg?: OpenClawConfig;
respond: RespondFn;
resolveTerminalReason?: WaitReasonResolver<TPayload>;
}): Promise<void> {
const id = normalizeOptionalString(params.inputId) ?? "";
if (!id) {
params.respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "id is required"));
return;
}
const snapshot = params.manager.getSnapshot(id);
if (
!snapshot ||
!isApprovalRecordVisibleToClient({
record: snapshot,
client: params.client ?? null,
...(params.cfg ? { cfg: params.cfg } : {}),
})
) {
params.respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "approval expired or not found"),
);
return;
}
const decisionPromise = params.manager.awaitDecision(id);
if (!decisionPromise) {
params.respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "approval expired or not found"),
);
return;
}
const decision = params.manager.projectDecisionIfActive(id, await decisionPromise);
const terminalSnapshot = params.manager.getSnapshot(id) ?? snapshot;
const terminalReason = params.resolveTerminalReason?.(terminalSnapshot);
params.respond(
true,
buildWaitResponse(id, decision, terminalSnapshot, terminalReason),
undefined,
);
}
/** Broadcasts or routes a pending approval request, then responds after acceptance/decision. */
export async function handlePendingApprovalRequest<
TPayload extends ApprovalTurnSourceFields,
>(params: {
manager: ExecApprovalManager<TPayload>;
record: ExecApprovalRecord<TPayload>;
respond: RespondFn;
context: GatewayRequestContext;
clientConnId?: string;
requestEventName: string;
requestEvent: RequestedApprovalEvent<TPayload>;
twoPhase: boolean;
approvalKind?: ChannelApprovalKind;
deliverRequest: () => boolean | Promise<boolean>;
afterDecision?: (
decision: ExecApprovalDecision | null,
requestEvent: RequestedApprovalEvent<TPayload>,
) => Promise<void> | void;
afterDecisionErrorLabel?: string;
keepPendingWithoutRoute?: boolean;
requireDeliveryRoute?: boolean;
suppressDelivery?: boolean;
deliverToApprovalClientsOnly?: boolean;
}): Promise<void> {
const deliveryReady = createDeferredCore<boolean>();
let noRouteWon = false;
const handoff = params.manager.registerDecisionHandoff(params.record.id, async (decision) => {
if (!(await deliveryReady.promise)) {
return;
}
let projectedDecision = params.manager.projectDecisionIfActive(params.record.id, decision);
if (!noRouteWon && params.afterDecision) {
try {
await params.afterDecision(projectedDecision, params.requestEvent);
} catch (err) {
params.context.logGateway?.error?.(
`${params.afterDecisionErrorLabel ?? "approval follow-up failed"}: ${String(err)}`,
);
}
}
projectedDecision = params.manager.projectDecisionIfActive(params.record.id, projectedDecision);
params.respond(
true,
{
id: params.record.id,
decision: projectedDecision,
createdAtMs: params.record.createdAtMs,
expiresAtMs: params.record.expiresAtMs,
},
undefined,
);
});
// Observation can close while delivery is preparing; the registered genuine
// handoff remains manager-owned and is joined independently of this observer.
void handoff.observation.catch(() => {});
try {
const suppressDelivery = params.suppressDelivery === true;
// Cron/automation cards go only to connected approval surfaces (Control
// UI, TUI): chat runtimes and turn-source routes would recreate the
// per-occurrence spam #128031 removed, while an approval client can end
// the recurrence with one allow-always (standing grant).
const approvalClientsOnly = !suppressDelivery && params.deliverToApprovalClientsOnly === true;
const approvalClientConnIds = suppressDelivery
? null
: resolveApprovalRequestRecipientConnIds({
approvalKind: params.approvalKind ?? "exec",
context: params.context,
record: params.record,
excludeConnId: params.clientConnId,
});
if (!suppressDelivery) {
if (approvalClientConnIds) {
params.context.broadcastToConnIds(
params.requestEventName,
params.requestEvent,
approvalClientConnIds,
{
dropIfSlow: true,
},
);
} else {
params.context.broadcast(params.requestEventName, params.requestEvent, {
dropIfSlow: true,
});
}
}
const internalApprovalSubscriberCount =
suppressDelivery || approvalClientsOnly
? 0
: (params.context.approvalEvents?.publishRequested(
params.approvalKind ?? "exec",
params.requestEvent,
) ?? 0);
const hasApprovalClients = suppressDelivery
? false
: approvalClientConnIds !== null
? approvalClientConnIds.size > 0 || internalApprovalSubscriberCount > 0
: (params.context.hasExecApprovalClients?.(params.clientConnId) ?? false) ||
internalApprovalSubscriberCount > 0;
const delivered =
suppressDelivery || approvalClientsOnly
? false
: await params.manager.trackActiveWork(params.deliverRequest);
// A turn-source route can approve without an active approval client, so keep
// the record alive when the originating channel/account can still receive it.
const hasTurnSourceRoute =
!suppressDelivery &&
!approvalClientsOnly &&
!hasApprovalClients &&
!delivered &&
hasApprovalTurnSourceRoute({
turnSourceChannel: params.record.request.turnSourceChannel,
turnSourceAccountId: params.record.request.turnSourceAccountId,
approvalKind: params.approvalKind ?? "exec",
});
const deliveryRoute: ApprovalRequestDeliveryRoute = delivered
? "forwarder"
: hasApprovalClients
? "approval-client"
: hasTurnSourceRoute
? "turn-source"
: "none";
if (
params.requireDeliveryRoute !== false &&
!params.keepPendingWithoutRoute &&
!hasApprovalClients &&
!hasTurnSourceRoute &&
!delivered
) {
try {
noRouteWon = params.manager.expire(params.record.id, "no-approval-route");
} catch (err) {
deliveryReady.resolve(false);
handoff.abandon();
respondApprovalStorageUnavailable({ ...params, operation: "request", error: err });
return;
}
} else if (params.twoPhase) {
params.respond(
true,
{
status: "accepted",
id: params.record.id,
// Agent-side timeouts use this to distinguish delivered prompts from
// requests kept pending only because manual /approve routing may work.
deliveryRoute,
createdAtMs: params.record.createdAtMs,
expiresAtMs: params.record.expiresAtMs,
},
undefined,
);
}
} catch (error) {
deliveryReady.resolve(false);
handoff.abandon();
throw error;
}
deliveryReady.resolve(true);
await handoff.observation;
}
function respondRepeatedApprovalResolution<TPayload>(
record: ExecApprovalRecord<TPayload>,
decision: ExecApprovalDecision,
respond: RespondFn,
): void {
// Identical retries are idempotent; a conflicting retry must never replace
// or obscure the first durable operator decision.
if (resolveRecordedApprovalDecision(record) === decision) {
respond(true, { ok: true }, undefined);
return;
}
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, "approval already resolved", {
details: APPROVAL_ALREADY_RESOLVED_DETAILS,
}),
);
}
/** Resolves a pending approval and broadcasts the final decision exactly once. */
export async function handleApprovalResolve<
TPayload extends ExecApprovalRequestPayload | PluginApprovalRequestPayload,
>(params: {
approvalKind: ChannelApprovalKind;
manager: ExecApprovalManager<TPayload>;
inputId: string;
decision: ExecApprovalDecision;
respond: RespondFn;
context: GatewayRequestContext;
client: GatewayClient | null;
reviewer?: ApprovalChannelReviewer;
exposeAmbiguousPrefixError?: boolean;
validateDecision?: (snapshot: ExecApprovalRecord<TPayload>) =>
| {
message: string;
details?: Record<string, unknown>;
}
| null
| undefined;
resolveRecord?: (params: {
approvalId: string;
decision: ExecApprovalDecision;
resolvedBy: string | null;
snapshot: ExecApprovalRecord<TPayload>;
resolver?: { kind: "channel"; id: string };
}) => boolean;
forwardResolved?: (event: ResolvedApprovalEvent<TPayload>) => Promise<void> | void;
forwardResolvedErrorLabel?: string;
extraResolvedHandlers?: Array<{
run: (event: ResolvedApprovalEvent<TPayload>) => Promise<void> | void;
errorLabel: string;
}>;
}): Promise<void> {
const custody = params.reviewer
? prepareApprovalChannelCustody({
cfg: params.context.getRuntimeConfig(),
approvalKind: params.approvalKind,
reviewer: params.reviewer,
})
: null;
if (params.reviewer && !custody) {
respondUnknownOrExpiredApproval(params.respond);
return;
}
const recordFilter = custody
? (record: ExecApprovalRecord<TPayload>) => custody.authorizes(record)
: undefined;
let resolved: ApprovalRecordLookupResult<TPayload>;
try {
resolved = resolvePendingApprovalRecord({
manager: params.manager,
inputId: params.inputId,
client: params.client,
exposeAmbiguousPrefixError: params.exposeAmbiguousPrefixError,
recordFilter,
});
} catch (err) {
respondApprovalStorageUnavailable({ ...params, operation: "resolve", error: err });
return;
}
if (!resolved.ok) {
let resolvedRepeat: ApprovalRecordLookupResult<TPayload>;
try {
resolvedRepeat = resolveResolvedApprovalRecord({
manager: params.manager,
inputId: params.inputId,
client: params.client,
exposeAmbiguousPrefixError: params.exposeAmbiguousPrefixError,
recordFilter,
});
} catch (err) {
respondApprovalStorageUnavailable({ ...params, operation: "resolve", error: err });
return;
}
if (resolvedRepeat.ok) {
respondRepeatedApprovalResolution(resolvedRepeat.snapshot, params.decision, params.respond);
return;
}
respondPendingApprovalLookupError({ respond: params.respond, response: resolved.response });
return;
}
const validationError = params.validateDecision?.(resolved.snapshot);
if (validationError) {
params.respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
validationError.message,
validationError.details ? { details: validationError.details } : undefined,
),
);
return;
}
const resolvedBy =
params.client?.connect?.client?.displayName ?? params.client?.connect?.client?.id ?? null;
const resolver = custody ? ({ kind: "channel", id: custody.resolverId } as const) : undefined;
let ok: boolean;
try {
ok = params.resolveRecord
? params.resolveRecord({
approvalId: resolved.approvalId,
decision: params.decision,
resolvedBy,
snapshot: resolved.snapshot,
resolver,
})
: resolver
? params.manager.resolveDetailed(resolved.approvalId, params.decision, resolver, resolvedBy)
.outcome === "resolved"
: params.manager.resolve(resolved.approvalId, params.decision, resolvedBy);
} catch (err) {
respondApprovalStorageUnavailable({ ...params, operation: "resolve", error: err });
return;
}
if (!ok) {
// A concurrent surface can win between the pending lookup and this
// resolve; report the recorded conflict, not a missing approval.
const raced = params.manager.getSnapshot(resolved.approvalId);
if (raced && raced.resolvedAtMs !== undefined) {
respondRepeatedApprovalResolution(raced, params.decision, params.respond);
return;
}
respondUnknownOrExpiredApproval(params.respond);
return;
}
const resolvedEvent: ResolvedApprovalEvent<TPayload> = {
id: resolved.approvalId,
decision: params.decision,
resolvedBy,
ts: Date.now(),
request: resolved.snapshot.request,
};
broadcastApprovalResolvedEvent({
approvalKind: params.approvalKind,
context: params.context,
record: resolved.snapshot,
event: resolvedEvent,
});
if (params.approvalKind !== "system-agent") {
params.context.approvalEvents?.publishResolved(params.approvalKind, resolvedEvent as never);
}
const followUps = [
params.forwardResolved
? {
run: params.forwardResolved,
errorLabel: params.forwardResolvedErrorLabel ?? "approval resolve follow-up failed",
}
: null,
...(params.extraResolvedHandlers ?? []),
params.context.approvalWebPushDelivery
? {
run: params.context.approvalWebPushDelivery.handleResolved,
errorLabel: `${params.approvalKind} approvals: Web Push resolve failed`,
}
: null,
].filter(
(
entry,
): entry is {
run: (event: ResolvedApprovalEvent<TPayload>) => Promise<void> | void;
errorLabel: string;
} => Boolean(entry),
);
// Resolution has already been recorded and broadcast; follow-up hooks are
// best-effort so a plugin/channel forwarding failure cannot reopen it.
for (const followUp of followUps) {
try {
await followUp.run(resolvedEvent);
} catch (err) {
params.context.logGateway?.error?.(`${followUp.errorLabel}: ${String(err)}`);
}
}
params.respond(true, { ok: true }, undefined);
}
|