|
| 1 | +import { E } from '@endo/eventual-send'; |
| 2 | +import type { DiscoverableExo, MethodSchema } from '@metamask/kernel-utils'; |
| 3 | + |
| 4 | +import type { CapabilityRecord, CapabilitySpec } from '../types.ts'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Discover the capabilities of a discoverable exo. Intended for use from inside a vat. |
| 8 | + * This function fetches the schema from the discoverable exo and creates capabilities that can be used by kernel agents. |
| 9 | + * |
| 10 | + * @param exo - The discoverable exo to convert to a capability record. |
| 11 | + * @returns A promise for a capability record. |
| 12 | + */ |
| 13 | +export const discover = async ( |
| 14 | + exo: DiscoverableExo, |
| 15 | +): Promise<CapabilityRecord> => { |
| 16 | + // @ts-expect-error - E type doesn't remember method names |
| 17 | + const description = (await E(exo).describe()) as Record<string, MethodSchema>; |
| 18 | + |
| 19 | + const capabilities: CapabilityRecord = Object.fromEntries( |
| 20 | + Object.entries(description).map(([name, schema]) => { |
| 21 | + // Get argument names in order from the schema. |
| 22 | + // IMPORTANT: This relies on the schema's args object having keys in the same |
| 23 | + // order as the method's parameters. The schema must be defined with argument |
| 24 | + // names matching the method parameter order (e.g., for method `add(a, b)`, |
| 25 | + // the schema must have `args: { a: ..., b: ... }` in that order). |
| 26 | + // JavaScript objects preserve insertion order for string keys, so Object.keys() |
| 27 | + // will return keys in the order they were defined in the schema. |
| 28 | + const argNames = Object.keys(schema.args); |
| 29 | + |
| 30 | + // Create a capability function that accepts an args object |
| 31 | + // and maps it to positional arguments for the exo method |
| 32 | + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type |
| 33 | + const func = async (args: Record<string, unknown>) => { |
| 34 | + // Map object arguments to positional arguments in schema order. |
| 35 | + // The order of argNames matches the method parameter order by convention. |
| 36 | + const positionalArgs = argNames.map((argName) => args[argName]); |
| 37 | + // @ts-expect-error - E type doesn't remember method names |
| 38 | + return E(exo)[name](...positionalArgs); |
| 39 | + }; |
| 40 | + |
| 41 | + return [name, { func, schema }] as [ |
| 42 | + string, |
| 43 | + CapabilitySpec<never, unknown>, |
| 44 | + ]; |
| 45 | + }), |
| 46 | + ); |
| 47 | + |
| 48 | + return capabilities; |
| 49 | +}; |
0 commit comments