exoagent 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,383 @@
1
+ import { IncomingMessage, ServerResponse, OutgoingHttpHeaders, OutgoingHttpHeader } from 'node:http';
2
+
3
+ // Copyright (c) 2025 Cloudflare, Inc.
4
+ // Licensed under the MIT license found in the LICENSE.txt file or at:
5
+ // https://opensource.org/license/mit
6
+
7
+ // This file borrows heavily from `types/defines/rpc.d.ts` in workerd.
8
+
9
+ type GlobalRpcSessionOptions = {
10
+ recordReplayMode?: 'map' | 'all';
11
+ }
12
+
13
+ // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
14
+ // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
15
+ // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
16
+ // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)
17
+ declare const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';
18
+ declare const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
19
+ interface RpcTargetBranded {
20
+ [__RPC_TARGET_BRAND]: never;
21
+ }
22
+
23
+ // Types that can be used through `Stub`s
24
+ type Stubable = RpcTargetBranded | ((...args: any[]) => any);
25
+
26
+ // Types that can be passed over RPC
27
+ // The reason for using a generic type here is to build a serializable subset of structured
28
+ // cloneable composite types. This allows types defined with the "interface" keyword to pass the
29
+ // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
30
+ type RpcCompatible<T> =
31
+ // Structured cloneables
32
+ | BaseType
33
+ // Structured cloneable composites
34
+ | Map<
35
+ T extends Map<infer U, unknown> ? RpcCompatible<U> : never,
36
+ T extends Map<unknown, infer U> ? RpcCompatible<U> : never
37
+ >
38
+ | Set<T extends Set<infer U> ? RpcCompatible<U> : never>
39
+ | Array<T extends Array<infer U> ? RpcCompatible<U> : never>
40
+ | ReadonlyArray<T extends ReadonlyArray<infer U> ? RpcCompatible<U> : never>
41
+ | {
42
+ [K in keyof T]: K extends number | string ? RpcCompatible<T[K]> : never;
43
+ }
44
+ | Promise<T extends Promise<infer U> ? RpcCompatible<U> : never>
45
+ // Special types
46
+ | Stub<Stubable>
47
+ // Serialized as stubs, see `Stubify`
48
+ | Stubable;
49
+
50
+ // Base type for all RPC stubs, including common memory management methods.
51
+ // `T` is used as a marker type for unwrapping `Stub`s later.
52
+ interface StubBase<T extends RpcCompatible<T>> extends Disposable {
53
+ [__RPC_STUB_BRAND]: T;
54
+ dup(): this;
55
+ onRpcBroken(callback: (error: any) => void): void;
56
+ }
57
+ type Stub<T extends RpcCompatible<T>> =
58
+ T extends object ? Provider<T> & StubBase<T> : StubBase<T>;
59
+
60
+ type TypedArray =
61
+ | Uint8Array
62
+ | Uint8ClampedArray
63
+ | Uint16Array
64
+ | Uint32Array
65
+ | Int8Array
66
+ | Int16Array
67
+ | Int32Array
68
+ | BigUint64Array
69
+ | BigInt64Array
70
+ | Float32Array
71
+ | Float64Array;
72
+
73
+ // This represents all the types that can be sent as-is over an RPC boundary
74
+ type BaseType =
75
+ | void
76
+ | undefined
77
+ | null
78
+ | boolean
79
+ | number
80
+ | bigint
81
+ | string
82
+ | TypedArray
83
+ | ArrayBuffer
84
+ | DataView
85
+ | Date
86
+ | Error
87
+ | RegExp
88
+ | ReadableStream<Uint8Array>
89
+ | WritableStream<Uint8Array>
90
+ | Request
91
+ | Response
92
+ | Headers;
93
+ // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
94
+ // prettier-ignore
95
+ type Stubify<T> =
96
+ T extends Stubable ? Stub<T>
97
+ : T extends Promise<infer U> ? Stubify<U>
98
+ : T extends StubBase<any> ? T
99
+ : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>>
100
+ : T extends Set<infer V> ? Set<Stubify<V>>
101
+ : T extends [] ? []
102
+ : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>]
103
+ : T extends readonly [] ? readonly []
104
+ : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>]
105
+ : T extends Array<infer V> ? Array<Stubify<V>>
106
+ : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>>
107
+ : T extends BaseType ? T
108
+ // When using "unknown" instead of "any", interfaces are not stubified.
109
+ : T extends { [key: string | number]: any } ? { [K in keyof T]: Stubify<T[K]> }
110
+ : T;
111
+
112
+ // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
113
+ // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
114
+ // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
115
+ // prettier-ignore
116
+ type UnstubifyInner<T> =
117
+ T extends StubBase<infer V> ? (T | V) // can provide either stub or local RpcTarget
118
+ : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>>
119
+ : T extends Set<infer V> ? Set<Unstubify<V>>
120
+ : T extends [] ? []
121
+ : T extends [infer Head, ...infer Tail] ? [Unstubify<Head>, ...Unstubify<Tail>]
122
+ : T extends readonly [] ? readonly []
123
+ : T extends readonly [infer Head, ...infer Tail] ? readonly [Unstubify<Head>, ...Unstubify<Tail>]
124
+ : T extends Array<infer V> ? Array<Unstubify<V>>
125
+ : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>>
126
+ : T extends BaseType ? T
127
+ : T extends { [key: string | number]: unknown } ? { [K in keyof T]: Unstubify<T[K]> }
128
+ : T;
129
+
130
+ // You can put promises anywhere in the params and they'll be resolved before delivery.
131
+ // (This also covers RpcPromise, because it's defined as being a Promise.)
132
+ type Unstubify<T> = UnstubifyInner<T> | Promise<UnstubifyInner<T>>
133
+
134
+ type UnstubifyAll<A extends any[]> = { [I in keyof A]: Unstubify<A[I]> };
135
+
136
+ // Utility type for adding `Disposable`s to `object` types only.
137
+ // Note `unknown & T` is equivalent to `T`.
138
+ type MaybeDisposable<T> = T extends object ? Disposable : unknown;
139
+
140
+ // Type for method return or property on an RPC interface.
141
+ // - Stubable types are replaced by stubs.
142
+ // - RpcCompatible types are passed by value, with stubable types replaced by stubs
143
+ // and a top-level `Disposer`.
144
+ // Everything else can't be passed over RPC.
145
+ // Technically, we use custom thenables here, but they quack like `Promise`s.
146
+ // Intersecting with `(Maybe)Provider` allows pipelining.
147
+ // prettier-ignore
148
+ type Result<R> =
149
+ R extends Stubable ? Promise<Stub<R>> & Provider<R> & StubBase<R>
150
+ : R extends RpcCompatible<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & Provider<R> & StubBase<R>
151
+ : never;
152
+
153
+ // Type for method or property on an RPC interface.
154
+ // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
155
+ // Unwrapping `Stub`s allows calling with `Stubable` arguments.
156
+ // For properties, rewrite types to be `Result`s.
157
+ // In each case, unwrap `Promise`s.
158
+ type MethodOrProperty<V> = V extends (...args: infer P) => infer R
159
+ ? (...args: UnstubifyAll<P>) => Result<Awaited<R>>
160
+ : Result<Awaited<V>>;
161
+
162
+ // Type for the callable part of an `Provider` if `T` is callable.
163
+ // This is intersected with methods/properties.
164
+ type MaybeCallableProvider<T> = T extends (...args: any[]) => any
165
+ ? MethodOrProperty<T>
166
+ : unknown;
167
+
168
+ // Base type for all other types providing RPC-like interfaces.
169
+ // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
170
+ type Provider<T> = MaybeCallableProvider<T> &
171
+ (T extends Array<infer U>
172
+ ? {
173
+ [key: number]: MethodOrProperty<U>;
174
+ } & {
175
+ map<V>(callback: (elem: U) => V): Result<Array<V>>;
176
+ }
177
+ : {
178
+ [K in Exclude<
179
+ keyof T,
180
+ symbol | keyof StubBase<never>
181
+ >]: MethodOrProperty<T[K]>;
182
+ } & {
183
+ map<V>(callback: (value: NonNullable<T>) => V): Result<Array<V>>;
184
+ });
185
+
186
+ declare const setGlobalRpcSessionOptions: (options: (() => GlobalRpcSessionOptions)) => void;
187
+ declare function takeOwnership<T extends Function>(fn: T): T & Disposable;
188
+
189
+ type ExplicitCallback<T extends Function> = T & {
190
+ serializationMode?: 'recordReplay' | 'stub';
191
+ };
192
+ declare const explicitCallback: <T extends Function>(fn: T, serializationMode: "recordReplay" | "stub") => ExplicitCallback<T>;
193
+ /**
194
+ * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
195
+ * RPC stubs, but it will support basic data types.
196
+ */
197
+ declare function serialize(value: unknown): string;
198
+ /**
199
+ * Deserialize a value serialized using serialize().
200
+ */
201
+ declare function deserialize(value: string): unknown;
202
+
203
+ /**
204
+ * Interface for an RPC transport, which is a simple bidirectional message stream. Implement this
205
+ * interface if the built-in transports (e.g. for HTTP batch and WebSocket) don't meet your needs.
206
+ */
207
+ interface RpcTransport {
208
+ /**
209
+ * Sends a message to the other end.
210
+ */
211
+ send(message: string): Promise<void>;
212
+ /**
213
+ * Receives a message sent by the other end.
214
+ *
215
+ * If and when the transport becomes disconnected, this will reject. The thrown error will be
216
+ * propagated to all outstanding calls and future calls on any stubs associated with the session.
217
+ * If there are no outstanding calls (and none are made in the future), then the error does not
218
+ * propagate anywhere -- this is considered a "clean" shutdown.
219
+ */
220
+ receive(): Promise<string>;
221
+ /**
222
+ * Indicates that the RPC system has suffered an error that prevents the session from continuing.
223
+ * The transport should ideally try to send any queued messages if it can, and then close the
224
+ * connection. (It's not strictly necessary to deliver queued messages, but the last message sent
225
+ * before abort() is called is often an "abort" message, which communicates the error to the
226
+ * peer, so if that is dropped, the peer may have less information about what happened.)
227
+ */
228
+ abort?(reason: any): void;
229
+ }
230
+ /**
231
+ * Options to customize behavior of an RPC session. All functions which start a session should
232
+ * optionally accept this.
233
+ */
234
+ type RpcSessionOptions = {
235
+ /**
236
+ * If provided, this function will be called whenever an `Error` object is serialized (for any
237
+ * reason, not just because it was thrown). This can be used to log errors, and also to redact
238
+ * them.
239
+ *
240
+ * If `onSendError` returns an Error object, than object will be substituted in place of the
241
+ * original. If it has a stack property, the stack will be sent to the client.
242
+ *
243
+ * If `onSendError` doesn't return anything (or is not provided at all), the default behavior is
244
+ * to serialize the error with the stack omitted.
245
+ */
246
+ onSendError?: (error: Error) => Error | void;
247
+ };
248
+
249
+ /**
250
+ * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
251
+ * with the given `localMain`.
252
+ */
253
+ declare function newWorkersWebSocketRpcResponse(request: Request, localMain?: any, options?: RpcSessionOptions): Response;
254
+
255
+ /**
256
+ * Implements the server end of an HTTP batch session, using standard Fetch API types to represent
257
+ * HTTP requests and responses.
258
+ *
259
+ * @param request The request received from the client initiating the session.
260
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
261
+ * @param options Optional RPC session options.
262
+ * @returns The HTTP response to return to the client. Note that the returned object has mutable
263
+ * headers, so you can modify them using e.g. `response.headers.set("Foo", "bar")`.
264
+ */
265
+ declare function newHttpBatchRpcResponse(request: Request, localMain: any, options?: RpcSessionOptions): Promise<Response>;
266
+ /**
267
+ * Implements the server end of an HTTP batch session using traditional Node.js HTTP APIs.
268
+ *
269
+ * @param request The request received from the client initiating the session.
270
+ * @param response The response object, to which the response should be written.
271
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
272
+ * @param options Optional RPC session options. You can also pass headers to set on the response.
273
+ */
274
+ declare function nodeHttpBatchRpcResponse(request: IncomingMessage, response: ServerResponse, localMain: any, options?: RpcSessionOptions & {
275
+ headers?: OutgoingHttpHeaders | OutgoingHttpHeader[];
276
+ }): Promise<void>;
277
+
278
+ /**
279
+ * Represents a reference to a remote object, on which methods may be remotely invoked via RPC.
280
+ *
281
+ * `RpcStub` can represent any interface (when using TypeScript, you pass the specific interface
282
+ * type as `T`, but this isn't known at runtime). The way this works is, `RpcStub` is actually a
283
+ * `Proxy`. It makes itself appear as if every possible method / property name is defined. You can
284
+ * invoke any method name, and the invocation will be sent to the server. If it turns out that no
285
+ * such method exists on the remote object, an exception is thrown back. But the client does not
286
+ * actually know, until that point, what methods exist.
287
+ */
288
+ type RpcStub<T extends RpcCompatible<T>> = Stub<T>;
289
+ declare const RpcStub: {
290
+ new <T extends RpcCompatible<T>>(value: T): RpcStub<T>;
291
+ };
292
+ /**
293
+ * Represents the result of an RPC call.
294
+ *
295
+ * Also used to represent properties. That is, `stub.foo` evaluates to an `RpcPromise` for the
296
+ * value of `foo`.
297
+ *
298
+ * This isn't actually a JavaScript `Promise`. It does, however, have `then()`, `catch()`, and
299
+ * `finally()` methods, like `Promise` does, and because it has a `then()` method, JavaScript will
300
+ * allow you to treat it like a promise, e.g. you can `await` it.
301
+ *
302
+ * An `RpcPromise` is also a proxy, just like `RpcStub`, where calling methods or awaiting
303
+ * properties will make a pipelined network request.
304
+ *
305
+ * Note that and `RpcPromise` is "lazy": the actual final result is not requested from the server
306
+ * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
307
+ * if you only intend to use the promise for pipelining and you never await it, then there's no
308
+ * need to transmit the resolution!
309
+ */
310
+ type RpcPromise<T extends RpcCompatible<T>> = Stub<T> & Promise<Stubify<T>>;
311
+ declare const RpcPromise: {};
312
+ /**
313
+ * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
314
+ *
315
+ * Most people won't use this. You only need it if you've implemented your own `RpcTransport`.
316
+ */
317
+ interface RpcSession<T extends RpcCompatible<T> = undefined> {
318
+ getRemoteMain(): RpcStub<T>;
319
+ getStats(): {
320
+ imports: number;
321
+ exports: number;
322
+ };
323
+ drain(): Promise<void>;
324
+ }
325
+ declare const RpcSession: {
326
+ new <T extends RpcCompatible<T> = undefined>(transport: RpcTransport, localMain?: any, options?: RpcSessionOptions): RpcSession<T>;
327
+ };
328
+ /**
329
+ * Classes which are intended to be passed by reference and called over RPC must extend
330
+ * `RpcTarget`. A class which does not extend `RpcTarget` (and which doesn't have built-in support
331
+ * from the RPC system) cannot be passed in an RPC message at all; an exception will be thrown.
332
+ *
333
+ * Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the
334
+ * "cloudflare:workers" module, so they can be used interchangably.
335
+ */
336
+ interface RpcTarget extends RpcTargetBranded {
337
+ }
338
+ declare const RpcTarget: {
339
+ new (): RpcTarget;
340
+ };
341
+ /**
342
+ * Empty interface used as default type parameter for sessions where the other side doesn't
343
+ * necessarily export a main interface.
344
+ */
345
+ interface Empty {
346
+ }
347
+ /**
348
+ * Start a WebSocket session given either an already-open WebSocket or a URL.
349
+ *
350
+ * @param webSocket Either the `wss://` URL to connect to, or an already-open WebSocket object to
351
+ * use.
352
+ * @param localMain The main RPC interface to expose to the peer. Returns a stub for the main
353
+ * interface exposed from the peer.
354
+ */
355
+ declare let newWebSocketRpcSession: <T extends RpcCompatible<T> = Empty>(webSocket: WebSocket | string, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
356
+ /**
357
+ * Initiate an HTTP batch session from the client side.
358
+ *
359
+ * The parameters to this method have exactly the same signature as `fetch()`, but the return
360
+ * value is an RpcStub. You can customize anything about the request except for the method
361
+ * (it will always be set to POST) and the body (which the RPC system will fill in).
362
+ */
363
+ declare let newHttpBatchRpcSession: <T extends RpcCompatible<T>>(urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub<T>;
364
+ /**
365
+ * Initiate an RPC session over a MessagePort, which is particularly useful for communicating
366
+ * between an iframe and its parent frame in a browser context. Each side should call this function
367
+ * on its own end of the MessageChannel.
368
+ */
369
+ declare let newMessagePortRpcSession: <T extends RpcCompatible<T> = Empty>(port: MessagePort, localMain?: any, options?: RpcSessionOptions) => RpcStub<T>;
370
+ /**
371
+ * Implements unified handling of HTTP-batch and WebSocket responses for the Cloudflare Workers
372
+ * Runtime.
373
+ *
374
+ * SECURITY WARNING: This function accepts cross-origin requests. If you do not want this, you
375
+ * should validate the `Origin` header before calling this, or use `newHttpBatchRpcSession()` and
376
+ * `newWebSocketRpcSession()` directly with appropriate security measures for each type of request.
377
+ * But if your API uses in-band authorization (i.e. it has an RPC method that takes the user's
378
+ * credentials as parameters and returns the authorized API), then cross-origin requests should
379
+ * be safe.
380
+ */
381
+ declare function newWorkersRpcResponse(request: Request, localMain: any): Promise<Response>;
382
+
383
+ export { type ExplicitCallback, type RpcCompatible, RpcPromise, RpcSession, type RpcSessionOptions, RpcStub, RpcTarget, type RpcTransport, deserialize, explicitCallback, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize, setGlobalRpcSessionOptions, takeOwnership };