File size: 2,574 Bytes
78d0c37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { ErrorCodes, errorShape } from "../../../packages/gateway-protocol/src/index.js";
import type { GatewayClient, GatewayRequestContext, RespondFn } from "./types.js";

export function hasActiveAgentRuntimeAuthority(
  client: GatewayClient | null,
  context: Pick<GatewayRequestContext, "validateAgentRuntimeApprovalAuthority">,
  assertCallerCurrent?: () => void,
): boolean {
  try {
    assertCallerCurrent?.();
  } catch {
    return false;
  }
  const identity = client?.internal?.agentRuntimeIdentity;
  const validate = context.validateAgentRuntimeApprovalAuthority;
  // Production dispatch always supplies the validator. Lightweight direct-handler
  // contexts have no live authority owner and therefore no identity to invalidate.
  return !identity || !validate || validate(identity);
}

export function assertActiveAgentRuntimeAuthority(
  client: GatewayClient | null,
  context: Pick<GatewayRequestContext, "validateAgentRuntimeApprovalAuthority">,
  assertCallerCurrent?: () => void,
): void {
  if (!hasActiveAgentRuntimeAuthority(client, context, assertCallerCurrent)) {
    throw new TypeError("agent runtime authority is no longer active");
  }
}

function ensureActiveAgentRuntimeAuthority(params: {
  client: GatewayClient | null;
  context: GatewayRequestContext;
  respond: RespondFn;
  assertCallerCurrent?: () => void;
}): boolean {
  if (hasActiveAgentRuntimeAuthority(params.client, params.context, params.assertCallerCurrent)) {
    return true;
  }
  params.respond(
    false,
    undefined,
    errorShape(ErrorCodes.INVALID_REQUEST, "agent runtime authority is no longer active"),
  );
  return false;
}

export function createAgentRuntimeAuthorityGuard(
  client: GatewayClient | null,
  context: GatewayRequestContext,
  respond: RespondFn,
  assertCallerCurrent?: () => void,
) {
  const hasActive = () => hasActiveAgentRuntimeAuthority(client, context, assertCallerCurrent);
  return {
    commitGuard:
      assertCallerCurrent ||
      (client?.internal?.agentRuntimeIdentity && context.validateAgentRuntimeApprovalAuthority)
        ? () => assertActiveAgentRuntimeAuthority(client, context, assertCallerCurrent)
        : undefined,
    ensureActive: () =>
      ensureActiveAgentRuntimeAuthority({ client, context, respond, assertCallerCurrent }),
    handleClosedError(error: unknown): undefined {
      if (error instanceof TypeError && !hasActive()) {
        respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, error.message));
        return undefined;
      }
      throw error;
    },
    hasActive,
  };
}