File size: 6,053 Bytes
fcd8223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  buildCloudflareAccessHeaders,
  type CloudflareAccessCredentials,
} from "../../packages/gateway-client/src/cloudflare-access.js";
import {
  GatewayClient,
  type GatewayClientCloseInfo,
  type GatewayClientOptions,
  type GatewayClientRequestOptions,
  type GatewayReconnectPausedInfo,
} from "../gateway/client.js";
import type { ComputerUseCapabilityDescriptor } from "../plugins/computer-use-contract.js";
import type { NodeHostGatewayConfig } from "./config.js";

type GatewayCandidateEvent = Parameters<NonNullable<GatewayClientOptions["onEvent"]>>[0];
type GatewayCandidateHello = Parameters<NonNullable<GatewayClientOptions["onHelloOk"]>>[0];

type CandidateConnectionOptions = Omit<
  GatewayClientOptions,
  | "url"
  | "tlsFingerprint"
  | "edgeAuthHeaders"
  | "onEvent"
  | "onHelloOk"
  | "onConnectError"
  | "onReconnectPaused"
  | "onClose"
>;

type GatewayCandidateConnectionParams = {
  candidates: readonly NodeHostGatewayConfig[];
  cloudflareAccessByCandidate?: ReadonlyMap<NodeHostGatewayConfig, CloudflareAccessCredentials>;
  clientOptions: CandidateConnectionOptions;
  onEvent: (event: GatewayCandidateEvent) => void;
  onHelloOk: (
    hello: GatewayCandidateHello,
    url: string,
    tlsFingerprint?: string,
    cloudflareAccess?: CloudflareAccessCredentials,
  ) => void;
  onConnectError: (error: Error) => void;
  onReconnectPaused: (info: GatewayReconnectPausedInfo) => void;
  onClose: (code: number, reason: string, info?: GatewayClientCloseInfo) => void;
  onWinningCandidate: (candidate: NodeHostGatewayConfig) => void;
};

export function formatGatewayCandidateUrl(gateway: NodeHostGatewayConfig): string {
  const host = gateway.host ?? "127.0.0.1";
  const urlHost =
    host.includes(":") && !(host.startsWith("[") && host.endsWith("]")) ? `[${host}]` : host;
  const port = gateway.port ?? 18789;
  const scheme = gateway.tls ? "wss" : "ws";
  const contextPath = gateway.contextPath
    ? gateway.contextPath.startsWith("/")
      ? gateway.contextPath
      : `/${gateway.contextPath}`
    : "";
  return `${scheme}://${urlHost}:${port}${contextPath}`;
}

function canTryNextGatewayCandidate(info: GatewayClientCloseInfo | undefined): boolean {
  return info?.phase === "pre-hello" && info.connectRequestSent === false;
}

export function createNodeHostGatewayCandidateConnection(params: GatewayCandidateConnectionParams) {
  if (params.candidates.length === 0) {
    throw new Error("node host gateway candidate list cannot be empty");
  }

  let currentCandidateIndex = 0;
  let stopped = false;
  let winnerSelected = params.candidates.length === 1;
  let latestManifest:
    | { caps: string[]; commands: string[]; computerUse?: ComputerUseCapabilityDescriptor }
    | undefined;
  let currentClient = createCandidateClient(currentCandidateIndex);

  function createCandidateClient(candidateIndex: number): GatewayClient {
    const candidate = params.candidates[candidateIndex];
    if (!candidate) {
      throw new Error(`node host gateway candidate ${candidateIndex} is unavailable`);
    }
    const url = formatGatewayCandidateUrl(candidate);
    const cloudflareAccess = params.cloudflareAccessByCandidate?.get(candidate);
    const candidateClient = new GatewayClient({
      ...params.clientOptions,
      url,
      tlsFingerprint: candidate.tlsFingerprint,
      ...(cloudflareAccess
        ? { edgeAuthHeaders: buildCloudflareAccessHeaders(cloudflareAccess) }
        : {}),
      onEvent: (event) => {
        if (currentCandidateIndex === candidateIndex) {
          params.onEvent(event);
        }
      },
      onHelloOk: (hello) => {
        if (currentCandidateIndex !== candidateIndex) {
          return;
        }
        if (!winnerSelected) {
          winnerSelected = true;
          params.onWinningCandidate(candidate);
        }
        params.onHelloOk(hello, url, candidate.tlsFingerprint, cloudflareAccess);
      },
      onConnectError: (error) => {
        if (currentCandidateIndex === candidateIndex) {
          params.onConnectError(error);
        }
      },
      onReconnectPaused: (info) => {
        if (currentCandidateIndex === candidateIndex) {
          params.onReconnectPaused(info);
        }
      },
      onClose: (code, reason, info) => {
        if (currentCandidateIndex !== candidateIndex) {
          return;
        }
        params.onClose(code, reason, info);
        const nextCandidateIndex = candidateIndex + 1;
        if (
          stopped ||
          // A successful hello redeems setup credentials and promotes this
          // endpoint. Its own reconnect path owns durable device auth from here.
          winnerSelected ||
          nextCandidateIndex >= params.candidates.length ||
          !canTryNextGatewayCandidate(info)
        ) {
          return;
        }
        currentCandidateIndex = nextCandidateIndex;
        candidateClient.stop();
        queueMicrotask(() => {
          if (stopped || currentCandidateIndex !== nextCandidateIndex) {
            return;
          }
          currentClient = createCandidateClient(nextCandidateIndex);
          currentClient.start();
        });
      },
    });
    if (latestManifest) {
      candidateClient.updateNodeManifest(latestManifest);
    }
    return candidateClient;
  }

  return {
    start(): void {
      currentClient.start();
    },
    stop(): void {
      stopped = true;
      currentClient.stop();
    },
    request<T = Record<string, unknown>>(
      ...requestArgs: [method: string, params?: unknown, options?: GatewayClientRequestOptions]
    ): Promise<T> {
      return currentClient.request<T>(...requestArgs);
    },
    updateNodeManifest(manifest: {
      caps: string[];
      commands: string[];
      computerUse?: ComputerUseCapabilityDescriptor;
    }): void {
      // Availability may change before the first hello. Every later candidate
      // must start with the newest manifest rather than the constructor snapshot.
      latestManifest = manifest;
      currentClient.updateNodeManifest(manifest);
    },
  };
}