MCPcopy Create free account
hub / github.com/MoonshotAI/kimi-code / createRPC

Function createRPC

packages/agent-core/src/rpc/client.ts:31–105  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

29) => Promise<RPCMethods<Other>>;
30
31export function createRPC<Left extends Record<string, any>, Right extends Record<string, any>>(): [
32 RPCClient<Left, Right>,
33 RPCClient<Right, Left>,
34] {
35 const left = createControlledPromise<PromisableMethods<Left>>();
36 const right = createControlledPromise<PromisableMethods<Right>>();
37
38 function simulateNetwork<T>(data: T): Promise<T> {
39 return new Promise((resolve) => {
40 setTimeout(() => {
41 const serialized = JSON.stringify(data);
42 resolve(serialized === undefined ? (undefined as T) : JSON.parse(serialized));
43 }, 0);
44 });
45 }
46
47 function abortableRpc<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
48 return signal === undefined ? promise : abortable(promise, signal);
49 }
50
51 function mapRpcFunction(fn: Function): Function {
52 return async (payload: any, options?: RPCCallOptions) => {
53 const signal = options?.signal;
54 const rpcPayload = await simulateNetwork(payload);
55 signal?.throwIfAborted();
56 let response: RpcResponse;
57 try {
58 const handlerResult =
59 signal === undefined ? fn(rpcPayload) : fn(rpcPayload, { signal });
60 const value = await abortableRpc(Promise.resolve(handlerResult), signal);
61 response = { ok: true, value };
62 } catch (error) {
63 signal?.throwIfAborted();
64 response = { ok: false, error: toKimiErrorPayload(error) };
65 }
66 const remoteResponse = await simulateNetwork(response);
67 if (remoteResponse.ok) return remoteResponse.value;
68 throw fromKimiErrorPayload(remoteResponse.error);
69 };
70 }
71
72 function bindAllFunctions<T extends Record<string, any>>(obj: T): T {
73 const bound: Record<string, unknown> = {};
74 let current: object | null = obj;
75
76 while (current !== null && current !== Object.prototype) {
77 for (const key of Object.getOwnPropertyNames(current)) {
78 if (key === 'constructor' || Object.hasOwn(bound, key)) {
79 continue;
80 }
81
82 const descriptor = Object.getOwnPropertyDescriptor(current, key);
83 if (typeof descriptor?.value === 'function') {
84 bound[key] = descriptor.value.bind(obj);
85 }
86 }
87
88 current = Object.getPrototypeOf(current);

Callers 8

constructorMethod · 0.90
constructorMethod · 0.90
createTestRpcFunction · 0.90
createTestRpcFunction · 0.90
runtime.test.tsFile · 0.90
createTestRpcFunction · 0.90
create-rpc.test.tsFile · 0.90
constructorMethod · 0.90

Calls

no outgoing calls

Tested by 3

createTestRpcFunction · 0.72
createTestRpcFunction · 0.72
createTestRpcFunction · 0.72