Repository navigation
Expand file tree
/
Copy pathplugin-discovery.mts
More file actions
574 lines (551 loc) · 18.5 KB
/
Copy pathplugin-discovery.mts
File metadata and controls
574 lines (551 loc) · 18.5 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
import type {
AgentPluginCredentialSlot,
PluginCatalogEntry,
PluginCatalogPage,
} from "@openclaw-enterprise/contracts";
import { type RequestOptions, requestFailure } from "../api-client.mjs";
import {
type CatalogDirection,
type CatalogEntry,
type ManagedToolConnection,
type ManagedToolDiscovery,
type PluginFieldCatalog,
type PluginFieldsOptions,
createPluginFields,
} from "./plugin-fields.mjs";
import { withRequestId } from "../dom.mjs";
import { describeFailure, namespacePath } from "./list.mjs";
export interface PluginDiscoveryContext {
namespaceId: string;
installationAdmin?: boolean | null;
// Discovery is a read-only POST. The view owner uses this flag when deciding whether to retain it.
request(path: string, options?: RequestOptions & { readOnly?: true }): Promise<unknown>;
isCurrent(): boolean;
onExpired(): void;
}
type Message = string | (() => string);
const managedAccessAdvice =
"Tool discovery requires Agent edit access and permission to use the selected credential. Choose Recheck access.";
type CatalogRequest = { cursor?: string; q?: string } | { pluginId: string };
type DiscoveryRetryAction = "Load plugins" | "Load tools" | "Retry tools";
type DiscoveryEntry = CatalogEntry & { retryAfterConflict?: true | undefined };
interface PluginDiscoveryOptions extends Pick<
PluginFieldsOptions,
"input" | "saveHint" | "createApproverField" | "renderAccountConnection" | "savedAgent"
> {
context: PluginDiscoveryContext;
canDiscover(): boolean;
canPrefetch?(): boolean;
isPending(): boolean;
unavailableMessage: Message;
catalogPath?: string;
// Create Agent adds the discovery credential. An existing Agent's path identifies its saved one.
requestBody(body: CatalogRequest): unknown;
onCatalogPage?(page: PluginCatalogPage): void;
applyRecheckedCapabilities?(response: unknown): boolean;
deniedMessage?: Message;
unsupportedMessage?: string;
availableMessage?: Message;
}
function isDiscoveryConflict(error: ReturnType<typeof requestFailure>) {
return error.status === 409 && error.code === "RESOURCE_CONFLICT";
}
function discoveryConflictMessage(action: DiscoveryRetryAction) {
return `Plugin discovery could not finish with the current setup. Choose ${action} to try again.`;
}
function discoveryError(
error: ReturnType<typeof requestFailure>,
deniedMessage: Message,
unsupportedMessage: string,
retryAction: DiscoveryRetryAction,
) {
if (isDiscoveryConflict(error)) {
return withRequestId(discoveryConflictMessage(retryAction), error.requestId);
}
if (error.status === 403) {
return typeof deniedMessage === "function" ? deniedMessage() : deniedMessage;
}
if (error.status === 501) {
return unsupportedMessage;
}
const reasons: Record<string, string> = {
PLUGIN_DISCOVERY_CREDENTIALS_REJECTED:
"The credential was rejected or cannot access plugins. Check its permissions.",
PLUGIN_DISCOVERY_RATE_LIMITED: "The plugin service rate limit was reached. Try again later.",
PLUGIN_DISCOVERY_UNAVAILABLE:
"The plugin service is unavailable. Check the server's plugin service access and retry.",
PLUGIN_DISCOVERY_INVALID_RESPONSE:
"The plugin service returned an unsupported response. Retry or contact your operator.",
};
const reason = error.code ? reasons[error.code] : undefined;
// A rate limit the API itself answered says how long to wait (finding 2538).
const fallback =
error.status === 429
? describeFailure(error)
: "Plugins could not be loaded. Check the credential and retry.";
return withRequestId(reason ?? fallback, error.requestId);
}
export function createPluginDiscovery({
context,
input,
canDiscover,
canPrefetch = () => false,
isPending,
unavailableMessage,
saveHint,
catalogPath = `${namespacePath(context.namespaceId)}/agents/plugins`,
requestBody,
onCatalogPage,
applyRecheckedCapabilities,
deniedMessage = "Plugin discovery requires Agent create permission in this Namespace. Saved selections can still be edited.",
unsupportedMessage = "This Installation's Plugin Driver does not offer catalog browsing. You can edit configured selections or JSON, or ask an operator to select a catalog-capable Driver.",
availableMessage = "Load plugins available to this credential. Your plugin selections stay unchanged.",
createApproverField,
renderAccountConnection,
savedAgent,
}: PluginDiscoveryOptions) {
let generation = 0;
let prefetched = false;
let searchTimer: number | undefined;
let requests = new AbortController();
// Keep the managed recovery path available after clearing the active refusal.
let managedRecovery = false;
let currentRefusal: { requestId: string | undefined } | undefined;
const retryAccessAdvice = () => withRequestId(managedAccessAdvice, currentRefusal?.requestId);
let catalog: Pick<
PluginFieldCatalog,
"status" | "message" | "nextCursor" | "setup" | "reloadRequired" | "access"
> = {
status: "idle",
nextCursor: null,
};
const canLoad = () => !catalog.access && canDiscover();
const entries = new Map<string, DiscoveryEntry>();
let pageIds: string[] = [];
let cursors: (string | null)[] = [null];
let query = "";
let pageIndex = 0;
const fields = createPluginFields({
input,
...(saveHint !== undefined ? { saveHint } : {}),
...(createApproverField ? { createApproverField } : {}),
...(renderAccountConnection ? { renderAccountConnection } : {}),
...(savedAgent ? { savedAgent: true } : {}),
onLoadPlugins: (direction, q) => {
if (direction === "search") {
scheduleSearch(q);
} else {
void loadCatalog(direction, q);
}
},
onCancelDiscovery: cancel,
...(applyRecheckedCapabilities && { onRecheckAccess: (slot) => void recheckAccess(slot) }),
onLoadTools: (id, connection) => void loadTools(id, connection),
});
function render(transition?: "refusal") {
const available = canLoad();
const statusMessage = available ? availableMessage : unavailableMessage;
fields.setCatalog(
{
...catalog,
entries: pageIds.map((id) => entries.get(id)).filter((entry) => entry !== undefined),
knownEntries: [...entries.values()],
pageNumber: pageIndex + 1,
hasPrevious: pageIndex > 0,
canLoad: available,
canRecheck:
managedRecovery &&
(available || catalog.access === "denied" || catalog.access === "checking"),
message:
catalog.message ??
(typeof statusMessage === "function" ? statusMessage() : statusMessage),
},
transition,
);
}
function update() {
render();
if (!prefetched && catalog.status === "idle" && canPrefetch() && canLoad()) {
if (!context.isCurrent() || isPending()) {
return;
}
prefetched = true;
scheduleSearch("");
}
}
function invalidateRequests() {
generation += 1;
clearTimeout(searchTimer);
searchTimer = undefined;
requests.abort();
requests = new AbortController();
for (const [id, entry] of entries) {
if (entry.toolStatus === "loading") {
entries.set(id, { ...entry, toolStatus: undefined });
}
if (entry.managedTools?.status === "loading") {
entries.set(id, { ...entries.get(id)!, managedTools: undefined });
}
}
}
function invalidateHostedDetails(failedId: string, message: string) {
// Hosted details share the catalog binding. Keep row identities for manual retry and
// discard old tool data, including results that were still in flight at the conflict.
invalidateRequests();
for (const { id, name, remoteId, managedTools } of entries.values()) {
if (remoteId) {
const toolError = id === failedId ? message : discoveryConflictMessage("Retry tools");
entries.set(id, {
id,
name,
remoteId,
managedTools,
tools: null,
toolError,
retryAfterConflict: true,
});
}
}
render();
}
function resetCatalogPage(state: typeof catalog = { status: "idle", nextCursor: null }) {
pageIds = [];
cursors = [null];
pageIndex = 0;
catalog = state;
}
function retireSavedDiscovery(error: ReturnType<typeof requestFailure>, managed = false) {
const deleting = error.status === 409 && error.code === "AGENT_DELETING";
if (!applyRecheckedCapabilities || (!deleting && error.status !== 403)) {
return false;
}
if (deleting) {
retireCatalog(
withRequestId(
"Plugin discovery is unavailable while this Agent is being deleted.",
error.requestId,
),
"deleting",
);
} else if (managed || managedRecovery) {
managedRecovery = true;
currentRefusal = { requestId: error.requestId };
retireCatalog(retryAccessAdvice(), "denied");
} else {
const denial = typeof deniedMessage === "function" ? deniedMessage() : deniedMessage;
retireCatalog(withRequestId(`${denial} Choose Load plugins to try again.`, error.requestId));
}
render("refusal");
return true;
}
function retireCatalog(message: string, access?: PluginFieldCatalog["access"]) {
invalidateRequests();
entries.clear();
resetCatalogPage({
status: "error",
nextCursor: null,
reloadRequired: true,
message,
...(access && { access }),
});
}
async function recheckAccess(slot?: AgentPluginCredentialSlot) {
if (!applyRecheckedCapabilities || !managedRecovery || !context.isCurrent() || isPending()) {
return;
}
if (slot ? !fields.canRecheckAccounts(slot) : catalog.access !== "denied") {
return;
}
retireCatalog("Checking plugin access and account eligibility.", "checking");
render();
const current = generation;
const isCurrent = () => context.isCurrent() && current === generation;
try {
const response = await context.request(`${catalogPath}/capabilities`, {
signal: requests.signal,
});
if (!isCurrent()) {
return;
}
if (applyRecheckedCapabilities(response)) {
currentRefusal = undefined;
delete catalog.access;
catalog.message =
"Access rechecked. Choose Load plugins to discover available plugins again.";
} else {
catalog.access = "denied";
catalog.message = `${retryAccessAdvice()} Plugin capabilities could not be confirmed for this setup.`;
}
} catch (cause) {
if (!isCurrent()) {
return;
}
const error = requestFailure(cause);
if (error.status === 401) {
context.onExpired();
} else if (!((error.status === 409 || !currentRefusal) && retireSavedDiscovery(error))) {
catalog.access = "denied";
catalog.message = `${retryAccessAdvice()} ${withRequestId("Access could not be rechecked.", error.requestId)}`;
}
} finally {
if (isCurrent()) {
render();
}
}
}
function cancel() {
const pending = searchTimer !== undefined || catalog.status === "loading";
invalidateRequests();
if (catalog.access === "checking") {
catalog.access = "denied";
catalog.message = retryAccessAdvice();
}
if (pending) {
resetCatalogPage(
catalog.reloadRequired
? { ...catalog, status: "error" }
: { status: "idle", nextCursor: null, setup: catalog.setup },
);
}
render();
}
function scheduleSearch(q: string) {
query = q.trim();
if (catalog.access) {
return;
}
if (catalog.reloadRequired) {
// Keep the recovery action explicit while still retaining the latest query.
cancel();
return;
}
// Invalidate on input, before the delay, so an older response cannot fill this query.
invalidateRequests();
resetCatalogPage({ status: "idle", nextCursor: null, setup: catalog.setup });
if (context.isCurrent() && canLoad() && !isPending()) {
catalog.status = "loading";
searchTimer = setTimeout(() => {
// A form submission or tab change can prevent this deferred read from starting.
// Release the loading state so reopening a retained tab can load its catalog.
if (!context.isCurrent() || isPending()) {
prefetched = false;
cancel();
return;
}
void loadCatalog("refresh", query);
}, 300);
}
render();
}
function reset() {
// A catalog belongs to one entered credential; late responses cannot restore it.
invalidateRequests();
entries.clear();
prefetched = false;
query = "";
fields.resetSearch();
resetCatalogPage();
update();
}
async function loadCatalog(
direction: Exclude<CatalogDirection, "search"> = "refresh",
q = query,
) {
const search = q.trim();
const queryChanged = search !== query;
if (
!context.isCurrent() ||
!canLoad() ||
isPending() ||
(catalog.status === "loading" && searchTimer === undefined && !queryChanged)
) {
return;
}
if (queryChanged) {
query = search;
resetCatalogPage(catalog.reloadRequired ? catalog : undefined);
}
let nextPageIndex = pageIndex;
let cursor = cursors[nextPageIndex];
if (direction === "next") {
if (!catalog.nextCursor) {
return;
}
nextPageIndex += 1;
cursor = catalog.nextCursor;
} else if (direction === "previous") {
if (nextPageIndex === 0) {
return;
}
nextPageIndex -= 1;
cursor = cursors[nextPageIndex];
}
// Every page change invalidates in-flight details; the service owns page boundaries.
invalidateRequests();
const active = generation;
catalog = { ...catalog, status: "loading" };
render();
try {
const page = (await context.request(catalogPath, {
method: "POST",
readOnly: true,
signal: requests.signal,
body: requestBody({
...(cursor ? { cursor } : {}),
...(query ? { q: query } : {}),
}),
})) as PluginCatalogPage;
if (!context.isCurrent() || active !== generation) {
return;
}
for (const entry of page.plugins) {
entries.set(entry.id, entry);
}
onCatalogPage?.(page);
pageIds = page.plugins.map((entry) => entry.id);
cursors = [...cursors.slice(0, nextPageIndex), cursor ?? null];
pageIndex = nextPageIndex;
catalog = { status: "ready", nextCursor: page.nextCursor, setup: page.setup };
} catch (cause) {
if (!context.isCurrent() || active !== generation) {
return;
}
const error = requestFailure(cause);
if (error.status === 401) {
context.onExpired();
return;
}
if (retireSavedDiscovery(error)) {
return;
}
if (isDiscoveryConflict(error)) {
entries.clear();
resetCatalogPage({ status: "error", nextCursor: null, reloadRequired: true });
}
catalog = {
...catalog,
status: "error",
message: discoveryError(error, deniedMessage, unsupportedMessage, "Load plugins"),
};
} finally {
if (context.isCurrent() && active === generation) {
render();
}
}
}
async function loadTools(id: string, connection?: ManagedToolConnection) {
const entry = entries.get(id);
if (
!context.isCurrent() ||
!canLoad() ||
isPending() ||
catalog.status === "loading" ||
!entry
) {
return;
}
const pending: ManagedToolDiscovery | undefined = connection && {
connection,
status: "loading",
};
if (pending) {
entries.set(id, { ...entry, managedTools: pending });
} else {
if (!entry.remoteId || entry.toolStatus === "loading") {
return;
}
entries.set(id, {
...entry,
toolStatus: "loading",
toolError: entry.retryAfterConflict ? entry.toolError : undefined,
});
}
const active = generation;
const currentEntry = () => {
const current = entries.get(id);
return context.isCurrent() &&
active === generation &&
(pending ? current?.managedTools === pending : current?.remoteId === entry.remoteId)
? current
: undefined;
};
render();
try {
const detail = (await context.request(`${catalogPath}/details`, {
method: "POST",
readOnly: true,
signal: requests.signal,
body: connection
? { ...(requestBody({ pluginId: id }) as object), managedConnection: connection }
: requestBody({ pluginId: entry.remoteId! }),
})) as PluginCatalogEntry | null | undefined;
const current = currentEntry();
if (!current) {
return;
}
if (detail?.id !== id) {
throw Object.assign(new Error("Plugin details do not match the selected plugin."), {
code: "PLUGIN_DISCOVERY_INVALID_RESPONSE",
});
}
entries.set(
id,
pending
? {
...current,
managedTools: { ...pending, status: "loaded", tools: detail.tools ?? [] },
}
: {
...current,
...detail,
toolStatus: "loaded",
toolError: undefined,
retryAfterConflict: undefined,
},
);
} catch (cause) {
if (!context.isCurrent() || active !== generation) {
return;
}
const error = requestFailure(cause);
// A newer account replaces the result marker, but the refusal can apply to the Agent.
if (retireSavedDiscovery(error, !!pending)) {
return;
}
const current = currentEntry();
if (!current) {
return;
}
if (error.status === 401) {
context.onExpired();
return;
}
const message = discoveryError(
error,
pending
? "Tool discovery requires Agent edit access and permission to use the selected credential."
: deniedMessage,
pending
? "Authenticated tool discovery is unavailable for this connection."
: unsupportedMessage,
pending ? "Load tools" : "Retry tools",
);
if (!pending && isDiscoveryConflict(error)) {
invalidateHostedDetails(id, message);
return;
}
entries.set(
id,
pending
? { ...current, managedTools: { ...pending, status: "error", message } }
: { ...current, toolStatus: undefined, toolError: message },
);
} finally {
if (context.isCurrent() && active === generation) {
render();
}
}
}
render();
return { fields, reset, update, refreshCatalog: () => loadCatalog("refresh") };
}