Repository navigation
Expand file tree
/
Copy pathregistry.ts
More file actions
338 lines (320 loc) · 11.2 KB
/
Copy pathregistry.ts
File metadata and controls
338 lines (320 loc) · 11.2 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { AppError } from '@agent-device/kernel/errors';
import { isRecord } from '@agent-device/kernel/record';
import type { ProviderDeviceRuntime } from '@agent-device/contracts/device';
import type { PlatformRuntimeProviderModule } from '@agent-device/contracts/platform-runtime-operations';
import type {
AgentDevicePlugin,
PluginConnection,
PluginSetupResult,
PluginWebDriverSetup,
WebDriverDescriptor,
} from './contract.ts';
import type { RegisteredConnection } from './connection.ts';
import { createPluginHost } from './host.ts';
import {
NO_PLUGIN_CREDENTIALS,
type PluginInventoryEntry,
type PluginSource,
} from '@agent-device/contracts/plugin-inventory';
import { describePluginFailure } from './inventory.ts';
import { isProviderId, ROUTING_PROVIDER_IDENTITIES } from './manifest.ts';
import { assertProviderRuntime, invalidPlugin, validateAgentDevicePlugin } from './validate.ts';
/**
* One plugin a source offers the registry. Sources differ only in how a candidate loads; the
* registry validates, claims and sets up every candidate the same way.
*/
export type PluginCandidate = Readonly<{
source: PluginSource;
package?: string;
version?: string;
/** Known before the plugin loads, such as a v1 manifest; a load failure still claims it. */
provider?: string;
/** Claims `provider` without registering or listing: a built-in that is not configured. */
dormant?: boolean;
/** The `options` the store passes to the host, which a v1 plugin reads. */
hostOptions?: Record<string, unknown>;
/** Returns the unvalidated plugin, or throws the reason it cannot load. */
load(): Promise<unknown> | unknown;
}>;
/** Claims provider ids without loading anything, as the built-in sources do for their own. */
export function claimProviderIds(providers: readonly string[]): PluginCandidate[] {
return providers.map((provider) => ({
source: 'builtin',
provider,
dormant: true,
load: () => undefined,
}));
}
/**
* What the composing root decides for every registry, so this package names no provider: how a
* plugin's `{ webDriver }` descriptor becomes a runtime.
*/
export type PluginRegistryPolicy = Readonly<{
adaptWebDriver(
descriptor: WebDriverDescriptor,
context: Readonly<{ clientVersion: string }>,
): Promise<Pick<ProviderRegistration, 'runtime' | 'platformModule'>>;
}>;
export type ProviderRegistration = Readonly<{
provider: string;
runtime: ProviderDeviceRuntime;
platformModule: PlatformRuntimeProviderModule;
}>;
type Slot = {
candidate: PluginCandidate;
provider?: string;
plugin?: AgentDevicePlugin;
failure?: unknown;
registration?: ProviderRegistration;
};
/** Candidates whose plugins loaded and validated, with duplicate providers already settled. */
export type ResolvedProviderPlugins = Readonly<{
/** The connection callbacks of every loaded plugin, by provider. */
connections: ReadonlyMap<string, RegisteredConnection>;
/** Every provider id claimed, including failed and dormant plugins. */
claimedProviders: readonly string[];
inventory(): readonly PluginInventoryEntry[];
/** @internal Consumed by {@link startProviderRegistry}. */
slots: readonly Slot[];
}>;
export type ProviderRegistry = Readonly<{
registrations: readonly ProviderRegistration[];
claimedProviders: readonly string[];
inventory: readonly PluginInventoryEntry[];
/** Shuts down every registered runtime, then disposes its plugin; never throws. */
close(): Promise<void>;
}>;
/**
* Loads and validates the candidates in order. The first candidate to name a provider claims it,
* even when that candidate later fails; a later one with the same id is recorded as failed. A
* plugin that cannot load never stops the others.
*/
export async function resolveProviderPlugins(
candidates: readonly PluginCandidate[],
): Promise<ResolvedProviderPlugins> {
const slots: Slot[] = [];
const claimed = new Set<string>();
for (const candidate of candidates) {
const slot: Slot = { candidate, provider: candidate.provider };
slots.push(slot);
if (candidate.dormant) {
if (candidate.provider !== undefined) claimed.add(candidate.provider);
continue;
}
try {
const raw = await candidate.load();
slot.provider = readProviderId(raw) ?? candidate.provider;
slot.plugin = validateAgentDevicePlugin(raw);
} catch (error) {
slot.failure = asPluginFailure(error, 'plugin_load_failed');
}
if (slot.provider === undefined || ROUTING_PROVIDER_IDENTITIES.includes(slot.provider))
continue;
if (claimed.has(slot.provider)) {
slot.plugin = undefined;
slot.failure ??= new AppError('INVALID_ARGS', `Duplicate provider plugin: ${slot.provider}`, {
reason: 'duplicate_provider',
provider: slot.provider,
});
} else claimed.add(slot.provider);
}
return Object.freeze({
connections: new Map(
slots.flatMap(({ plugin, candidate }) =>
plugin?.connection
? [
[
plugin.provider,
withConnectionHost(plugin.connection, candidate.hostOptions),
] as const,
]
: [],
),
),
claimedProviders: [...claimed],
inventory: () => slots.flatMap(describeSlot),
slots,
});
}
/**
* Sets up every loaded plugin in order. A plugin whose setup throws, or returns a runtime the
* registry refuses, is cleaned up and recorded as failed; the remaining plugins still register.
*/
export async function startProviderRegistry(
resolved: ResolvedProviderPlugins,
env: NodeJS.ProcessEnv,
policy: PluginRegistryPolicy,
): Promise<ProviderRegistry> {
for (const slot of resolved.slots) {
if (!slot.plugin || slot.failure !== undefined) continue;
try {
await setUpSlot(slot, slot.plugin, env, policy);
} catch (error) {
slot.failure = asPluginFailure(error, 'plugin_setup_failed');
slot.registration = undefined;
}
}
const registrations = resolved.slots.flatMap(({ registration }) =>
registration ? [registration] : [],
);
return Object.freeze({
registrations,
claimedProviders: resolved.claimedProviders,
inventory: resolved.inventory(),
close: async () => {
await Promise.allSettled(registrations.map(async ({ runtime }) => await runtime.shutdown()));
},
});
}
function withConnectionHost(
connection: PluginConnection,
hostOptions: Record<string, unknown> | undefined,
): RegisteredConnection {
return {
capabilities: connection.capabilities,
resolve: (context) =>
connection.resolve({ ...context, host: createPluginHost(context.env, hostOptions) }),
verify: (context) =>
connection.verify({ ...context, host: createPluginHost(context.env, hostOptions) }),
};
}
async function setUpSlot(
slot: Slot,
plugin: AgentDevicePlugin,
env: NodeJS.ProcessEnv,
policy: PluginRegistryPolicy,
): Promise<void> {
const host = createPluginHost(env, slot.candidate.hostOptions);
const result = await plugin.setup(host);
try {
const { runtime, platformModule } = await buildRegistration(
plugin,
result,
host.clientVersion,
policy,
);
const dispose = result.dispose?.bind(result);
slot.registration = {
provider: plugin.provider,
runtime: dispose ? withDisposal(runtime, dispose) : runtime,
platformModule,
};
} catch (error) {
await cleanUpRejectedSetup(result);
throw error;
}
}
async function buildRegistration(
plugin: AgentDevicePlugin,
result: PluginSetupResult,
clientVersion: string,
policy: PluginRegistryPolicy,
): Promise<Pick<ProviderRegistration, 'runtime' | 'platformModule'>> {
if (!isRecord(result))
throw invalidPlugin(`Plugin setup must return a runtime: ${plugin.provider}`);
if (isWebDriverSetup(result)) {
if (result.webDriver?.provider !== plugin.provider) {
throw invalidPlugin(
`WebDriver plugin provider does not match its declaration: ${plugin.provider}`,
);
}
return await policy.adaptWebDriver(result.webDriver, { clientVersion });
}
// The public contract names only what registration reads; the host checks the facets it calls.
const { runtime, platformModule } = result as unknown as {
runtime: ProviderDeviceRuntime;
platformModule: PlatformRuntimeProviderModule;
};
assertProviderRuntime(plugin.provider, runtime, platformModule);
return { runtime, platformModule };
}
function isWebDriverSetup(result: PluginSetupResult): result is PluginWebDriverSetup {
return 'webDriver' in result;
}
async function cleanUpRejectedSetup(result: unknown): Promise<void> {
if (!isRecord(result)) return;
const runtime = result.runtime as ProviderDeviceRuntime | undefined;
// The same order a registered plugin shuts down in: the runtime first, then `dispose`.
try {
if (typeof runtime?.shutdown === 'function') await runtime.shutdown();
} catch {}
try {
if (typeof result.dispose === 'function') await (result.dispose as () => unknown)();
} catch {}
}
/** A thrown value that is not already typed becomes a typed failure the inventory can key on. */
function asPluginFailure(error: unknown, reason: 'plugin_load_failed' | 'plugin_setup_failed') {
if (error instanceof AppError) {
return typeof error.details?.reason === 'string'
? error
: new AppError(error.code, error.message, { ...error.details, reason }, error);
}
return new AppError(
'COMMAND_FAILED',
error instanceof Error ? error.message : String(error),
{ reason },
error,
);
}
/**
* The daemon shuts providers down through their runtime, so a plugin's own `dispose` rides on
* `shutdown` and runs after it, whether or not the runtime's shutdown succeeds.
*/
function withDisposal<T extends ProviderDeviceRuntime>(
runtime: T,
dispose: () => Promise<void> | void,
): T {
return new Proxy(runtime, {
get(target, property) {
if (property === 'shutdown') {
return async () => {
try {
await target.shutdown();
} finally {
await dispose();
}
};
}
const value = Reflect.get(target, property, target);
return typeof value === 'function' ? value.bind(target) : value;
},
});
}
function describeSlot(slot: Slot): PluginInventoryEntry[] {
const { candidate, plugin } = slot;
if (candidate.dormant) return [];
const base = {
...(slot.provider !== undefined ? { provider: slot.provider } : {}),
source: candidate.source,
...(candidate.package !== undefined ? { package: candidate.package } : {}),
...(candidate.version !== undefined ? { version: candidate.version } : {}),
};
if (slot.failure !== undefined || !plugin) {
return [
{
...base,
state: 'failed',
error: describePluginFailure(slot.failure),
credentials: NO_PLUGIN_CREDENTIALS,
},
];
}
return [
{
...base,
state: 'active',
credentials: {
variables: [...plugin.credentials.variables],
byBackend: Object.fromEntries(
Object.entries(plugin.credentials.byBackend ?? {}).map(([backend, names]) => [
backend,
[...names],
]),
),
},
},
];
}
function readProviderId(raw: unknown): string | undefined {
return isRecord(raw) && isProviderId(raw.provider) ? raw.provider : undefined;
}