@srobroek/pi-find-tools 0.0.0-stage → 0.6.1

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,1552 @@
1
+ // @bun
2
+ // Generated by scripts/build.ts. Do not edit.
3
+ // plugins/find-tools/pi-src/find-tools.ts
4
+ import { readdir, readFile } from "fs/promises";
5
+ import { join } from "path";
6
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+
9
+ // lib/src/shell-tokenizer.ts
10
+ var SEPARATORS = new Set([";", "&", "|", "(", ")", `
11
+ `]);
12
+ function token(value, startsQuoted = false, sawQuote = false) {
13
+ return { value, startsQuoted, sawQuote };
14
+ }
15
+ function tokenizeShell(command, options = {}) {
16
+ if (typeof command !== "string")
17
+ return [];
18
+ const out = [];
19
+ let current = "";
20
+ let started = false;
21
+ let startsQuoted = false;
22
+ let sawQuote = false;
23
+ let quote = null;
24
+ const pending = [];
25
+ const flush = () => {
26
+ if (!started)
27
+ return;
28
+ out.push(token(current, startsQuoted, sawQuote));
29
+ current = "";
30
+ started = false;
31
+ startsQuoted = false;
32
+ sawQuote = false;
33
+ };
34
+ for (let i = 0;i < command.length; i++) {
35
+ const ch = command[i];
36
+ if (quote !== null) {
37
+ if (ch === quote) {
38
+ quote = null;
39
+ continue;
40
+ }
41
+ current += ch;
42
+ started = true;
43
+ continue;
44
+ }
45
+ if (ch === '"' || ch === "'") {
46
+ if (!started)
47
+ startsQuoted = true;
48
+ started = true;
49
+ sawQuote = true;
50
+ quote = ch;
51
+ continue;
52
+ }
53
+ if (ch === "\\" && i + 1 < command.length) {
54
+ if (options.preserveBackslashes)
55
+ current += ch;
56
+ current += command[++i];
57
+ started = true;
58
+ continue;
59
+ }
60
+ if (ch === "$" && command[i + 1] === "(") {
61
+ flush();
62
+ out.push(token("$("));
63
+ i++;
64
+ continue;
65
+ }
66
+ if (ch === "<" && command[i + 1] === "<" && command[i + 2] === "<") {
67
+ flush();
68
+ out.push(token("<<<"));
69
+ i += 2;
70
+ continue;
71
+ }
72
+ if (ch === "<" && command[i + 1] === "<") {
73
+ const operator = hereDocumentOperator(command, i);
74
+ if (operator !== null) {
75
+ flush();
76
+ pending.push(operator);
77
+ i = operator.end - 1;
78
+ continue;
79
+ }
80
+ }
81
+ if (ch === `
82
+ `) {
83
+ flush();
84
+ out.push(token(ch));
85
+ let bodyStart = i + 1;
86
+ while (pending.length > 0) {
87
+ const document = pending.shift();
88
+ if (document === undefined)
89
+ break;
90
+ const body = hereDocumentBody(command, bodyStart, document);
91
+ if (!document.quoted) {
92
+ const source = command.slice(bodyStart, body.bodyEnd);
93
+ if (options.hereDocumentSubstitutionsOnly)
94
+ out.push(...substitutions(source, options));
95
+ else
96
+ out.push(...tokenizeShell(source, options));
97
+ }
98
+ i = body.terminatorEnd;
99
+ bodyStart = i + 1;
100
+ }
101
+ continue;
102
+ }
103
+ if (/\s/.test(ch)) {
104
+ flush();
105
+ continue;
106
+ }
107
+ if (SEPARATORS.has(ch)) {
108
+ flush();
109
+ out.push(token(ch));
110
+ continue;
111
+ }
112
+ current += ch;
113
+ started = true;
114
+ }
115
+ flush();
116
+ return out;
117
+ }
118
+ function hereDocumentOperator(command, start) {
119
+ let i = start + 2;
120
+ const stripTabs = command[i] === "-";
121
+ if (stripTabs)
122
+ i++;
123
+ while (command[i] === " " || command[i] === "\t")
124
+ i++;
125
+ let delimiter = "";
126
+ let quoted = false;
127
+ let quote = null;
128
+ while (i < command.length) {
129
+ const ch = command[i];
130
+ if (quote !== null) {
131
+ if (ch === quote) {
132
+ quote = null;
133
+ i++;
134
+ continue;
135
+ }
136
+ delimiter += ch;
137
+ i++;
138
+ continue;
139
+ }
140
+ if (ch === '"' || ch === "'") {
141
+ quoted = true;
142
+ quote = ch;
143
+ i++;
144
+ continue;
145
+ }
146
+ if (ch === "\\" && i + 1 < command.length) {
147
+ quoted = true;
148
+ delimiter += command[i + 1];
149
+ i += 2;
150
+ continue;
151
+ }
152
+ if (/\s|[;&|<>()]/.test(ch))
153
+ break;
154
+ delimiter += ch;
155
+ i++;
156
+ }
157
+ if (quote !== null || delimiter.length === 0)
158
+ return null;
159
+ return { delimiter, stripTabs, quoted, end: i };
160
+ }
161
+ function hereDocumentBody(command, from, document) {
162
+ let cursor = from;
163
+ while (cursor < command.length) {
164
+ let next = command.indexOf(`
165
+ `, cursor);
166
+ if (next === -1)
167
+ next = command.length;
168
+ let line = command.slice(cursor, next);
169
+ if (document.stripTabs)
170
+ line = line.replace(/^\t+/, "");
171
+ if (line === document.delimiter)
172
+ return { bodyEnd: cursor, terminatorEnd: next };
173
+ if (next === command.length)
174
+ break;
175
+ cursor = next + 1;
176
+ }
177
+ return { bodyEnd: command.length, terminatorEnd: command.length };
178
+ }
179
+ function substitutions(body, options) {
180
+ const out = [];
181
+ for (let i = 0;i < body.length; i++) {
182
+ const ch = body[i];
183
+ if (ch === "\\") {
184
+ i++;
185
+ continue;
186
+ }
187
+ let inner;
188
+ if (ch === "$" && body[i + 1] === "(") {
189
+ const end = substitutionEnd(body, i + 2);
190
+ inner = body.slice(i + 2, end);
191
+ i = end;
192
+ if (inner.startsWith("("))
193
+ continue;
194
+ } else if (ch === "`") {
195
+ let end = i + 1;
196
+ while (end < body.length && body[end] !== "`")
197
+ end += body[end] === "\\" ? 2 : 1;
198
+ inner = body.slice(i + 1, end);
199
+ i = end;
200
+ } else {
201
+ continue;
202
+ }
203
+ out.push(token("$("), ...tokenizeShell(inner, options), token(")"));
204
+ }
205
+ return out;
206
+ }
207
+ function substitutionEnd(body, from) {
208
+ let depth = 1;
209
+ let quote = null;
210
+ for (let i = from;i < body.length; i++) {
211
+ const ch = body[i];
212
+ if (quote !== null) {
213
+ if (ch === quote)
214
+ quote = null;
215
+ else if (ch === "\\" && quote === '"')
216
+ i++;
217
+ continue;
218
+ }
219
+ if (ch === "\\")
220
+ i++;
221
+ else if (ch === '"' || ch === "'")
222
+ quote = ch;
223
+ else if (ch === "(")
224
+ depth++;
225
+ else if (ch === ")" && --depth === 0)
226
+ return i;
227
+ }
228
+ return body.length;
229
+ }
230
+
231
+ // lib/src/command-words.ts
232
+ var NONE = new Set;
233
+ var WRAPPERS = new Map([
234
+ [
235
+ "sudo",
236
+ {
237
+ valued: new Set([
238
+ "-C",
239
+ "-D",
240
+ "-g",
241
+ "-h",
242
+ "-p",
243
+ "-R",
244
+ "-r",
245
+ "-T",
246
+ "-t",
247
+ "-U",
248
+ "-u",
249
+ "--chdir",
250
+ "--chroot",
251
+ "--close-from",
252
+ "--command-timeout",
253
+ "--group",
254
+ "--host",
255
+ "--other-user",
256
+ "--prompt",
257
+ "--role",
258
+ "--type",
259
+ "--user"
260
+ ]),
261
+ chdir: new Set(["-D", "--chdir"])
262
+ }
263
+ ],
264
+ ["doas", { valued: new Set(["-C", "-u"]) }],
265
+ [
266
+ "env",
267
+ {
268
+ valued: new Set(["-C", "-L", "-P", "-S", "-U", "-u", "--chdir", "--split-string", "--unset"]),
269
+ chdir: new Set(["-C", "--chdir"]),
270
+ split: new Set(["-S", "--split-string"]),
271
+ assignments: true
272
+ }
273
+ ],
274
+ ["nice", { valued: new Set(["-n", "--adjustment"]) }],
275
+ ["timeout", { valued: new Set(["-k", "-s", "--kill-after", "--signal"]), operands: 1 }],
276
+ ["stdbuf", { valued: new Set(["-e", "-i", "-o", "--error", "--input", "--output"]) }],
277
+ ["exec", { valued: new Set(["-a"]) }],
278
+ ["command", { valued: NONE, lookup: new Set(["-V", "-v"]) }],
279
+ ["time", { valued: new Set(["-f", "-o", "--format", "--output"]) }],
280
+ ["nohup", { valued: NONE }]
281
+ ]);
282
+ var ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
283
+ function readOption(words, at, wrapper) {
284
+ const word = words[at];
285
+ if (word.startsWith("--")) {
286
+ const eq = word.indexOf("=");
287
+ const name = eq === -1 ? word : word.slice(0, eq);
288
+ if (!wrapper.valued.has(name))
289
+ return null;
290
+ return eq === -1 ? { name, value: words[at + 1], span: 2 } : { name, value: word.slice(eq + 1), span: 1 };
291
+ }
292
+ for (let j = 1;j < word.length; j++) {
293
+ const name = `-${word[j]}`;
294
+ if (wrapper.lookup?.has(name))
295
+ return "lookup";
296
+ if (!wrapper.valued.has(name))
297
+ continue;
298
+ const attached = word.slice(j + 1);
299
+ return attached ? { name, value: attached, span: 1 } : { name, value: words[at + 1], span: 2 };
300
+ }
301
+ return null;
302
+ }
303
+ function commandWords(input) {
304
+ const { argv, directories } = stripWrappers(input);
305
+ return { argv, directories };
306
+ }
307
+ function stripWrappers(input) {
308
+ const words = [...input];
309
+ const directories = [];
310
+ const wrappers = [];
311
+ let i = 0;
312
+ while (i < words.length) {
313
+ const word = words[i];
314
+ if (ASSIGNMENT.test(word) || word === "--") {
315
+ i++;
316
+ continue;
317
+ }
318
+ const wrapper = WRAPPERS.get(word.slice(word.lastIndexOf("/") + 1));
319
+ if (wrapper === undefined)
320
+ break;
321
+ wrappers.push(word.slice(word.lastIndexOf("/") + 1));
322
+ i++;
323
+ while (i < words.length) {
324
+ const option = words[i];
325
+ if (option === "--") {
326
+ i++;
327
+ break;
328
+ }
329
+ if (wrapper.assignments && ASSIGNMENT.test(option)) {
330
+ i++;
331
+ continue;
332
+ }
333
+ if (!option.startsWith("-"))
334
+ break;
335
+ const read = readOption(words, i, wrapper);
336
+ if (read === "lookup")
337
+ return { argv: [], directories, wrappers };
338
+ if (read === null) {
339
+ i++;
340
+ continue;
341
+ }
342
+ if (read.value === undefined)
343
+ return { argv: [], directories, wrappers };
344
+ if (wrapper.split?.has(read.name)) {
345
+ words.splice(i, read.span, ...tokenizeShell(read.value).map((token) => token.value));
346
+ continue;
347
+ }
348
+ if (wrapper.chdir?.has(read.name))
349
+ directories.push(read.value);
350
+ i += read.span;
351
+ }
352
+ i += Math.min(wrapper.operands ?? 0, words.length - i);
353
+ }
354
+ return { argv: words.slice(i), directories, wrappers };
355
+ }
356
+
357
+ // plugins/find-tools/shared/install-gate.ts
358
+ var SEPARATORS2 = new Set([";", "&", "|", `
359
+ `, "(", ")", "$("]);
360
+ var SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh", "fish"]);
361
+ var FETCHERS = new Set(["curl", "wget", "fetch", "http", "https", "xh", "aria2c"]);
362
+ var RUNNERS = new Set(["npx", "bunx", "pnpx"]);
363
+ var RUNNER_SUBCOMMANDS = new Map([
364
+ ["pnpm", new Set(["dlx", "exec"])],
365
+ ["yarn", new Set(["dlx"])],
366
+ ["bun", new Set(["x"])],
367
+ ["npm", new Set(["exec", "x"])]
368
+ ]);
369
+ var RUNNER_VALUE_FLAGS = new Set(["-p", "--package", "--registry", "--cache"]);
370
+ var SKILLS_PACKAGES = new Set(["skills", "add-skill"]);
371
+ var SKILLS_VERBS = new Set(["add", "install", "i", "update", "upgrade"]);
372
+ var SMITHERY_PACKAGES = new Set(["smithery", "@smithery/cli"]);
373
+ var SMITHERY_VERBS = new Set(["add", "install"]);
374
+ var MAX_DEPTH = 4;
375
+ var MESSAGES = {
376
+ "skills-cli": "find-tools: this runs the skills CLI to install a skill, which downloads and runs package code. Confirm the skill was vetted and the scope (project by default, user-wide only if asked).",
377
+ smithery: "find-tools: this runs the Smithery CLI to add an MCP server, which downloads package code and edits client configuration. Confirm the server was vetted and the scope.",
378
+ "pipe-to-shell": "find-tools: this pipes a downloaded script into a shell, which runs unreviewed code. Confirm the script was read and its source vetted."
379
+ };
380
+ var base = (word) => word.slice(word.lastIndexOf("/") + 1);
381
+ function packageName(spec) {
382
+ const at = spec.indexOf("@", 1);
383
+ return at > 0 ? spec.slice(0, at) : spec;
384
+ }
385
+ function runnerPackage(words) {
386
+ const exe = base(words[0] ?? "");
387
+ let i = 1;
388
+ if (!RUNNERS.has(exe)) {
389
+ const subs = RUNNER_SUBCOMMANDS.get(exe);
390
+ if (!subs)
391
+ return;
392
+ while (i < words.length && words[i].startsWith("-"))
393
+ i++;
394
+ if (!subs.has(words[i] ?? ""))
395
+ return;
396
+ i++;
397
+ }
398
+ let pkg;
399
+ for (;i < words.length; i++) {
400
+ const word = words[i];
401
+ if (word === "--")
402
+ continue;
403
+ if (RUNNER_VALUE_FLAGS.has(word)) {
404
+ pkg ??= words[i + 1];
405
+ i++;
406
+ continue;
407
+ }
408
+ if (word.startsWith("--package=")) {
409
+ pkg ??= word.slice("--package=".length);
410
+ continue;
411
+ }
412
+ if (word.startsWith("-"))
413
+ continue;
414
+ return { pkg: packageName(pkg ?? word), args: words.slice(pkg ? i : i + 1) };
415
+ }
416
+ return;
417
+ }
418
+ function positionals(args) {
419
+ return args.filter((arg) => !arg.startsWith("-"));
420
+ }
421
+ function simpleKind(argv) {
422
+ const words = commandWords(argv).argv;
423
+ const exe = base(words[0] ?? "");
424
+ if (!exe)
425
+ return;
426
+ const run = runnerPackage(words);
427
+ const pkg = run?.pkg ?? exe;
428
+ const args = run?.args ?? words.slice(1);
429
+ const verbs = positionals(args).slice(0, 2);
430
+ if (SKILLS_PACKAGES.has(pkg) && (pkg === "add-skill" || SKILLS_VERBS.has(verbs[0] ?? "")))
431
+ return "skills-cli";
432
+ if (SMITHERY_PACKAGES.has(pkg) && verbs.some((verb) => SMITHERY_VERBS.has(verb)))
433
+ return "smithery";
434
+ return;
435
+ }
436
+ function isFetcher(argv) {
437
+ return FETCHERS.has(base(commandWords(argv).argv[0] ?? ""));
438
+ }
439
+ function shellArgs(argv) {
440
+ const words = commandWords(argv).argv;
441
+ return SHELLS.has(base(words[0] ?? "")) ? words.slice(1) : undefined;
442
+ }
443
+ function readsStdin(argv) {
444
+ const args = shellArgs(argv);
445
+ if (!args)
446
+ return false;
447
+ if (args.includes("-s") || args.includes("-"))
448
+ return true;
449
+ return !args.some((arg) => !arg.startsWith("-")) && !args.includes("-c");
450
+ }
451
+ function segments(command) {
452
+ const out = [];
453
+ let words = [];
454
+ let pipe = false;
455
+ const tokens = tokenizeShell(command, { hereDocumentSubstitutionsOnly: true });
456
+ const flush = (next) => {
457
+ const segment = { words, ...next ? { next } : {} };
458
+ if (pipe && out.length)
459
+ segment.pipedFrom = out[out.length - 1];
460
+ if (words.length)
461
+ out.push(segment);
462
+ words = [];
463
+ };
464
+ for (let i = 0;i < tokens.length; i++) {
465
+ const token = tokens[i];
466
+ if (!token)
467
+ continue;
468
+ if (token.sawQuote || !SEPARATORS2.has(token.value)) {
469
+ words.push(token.value);
470
+ continue;
471
+ }
472
+ if (token.value === "|" && tokens[i + 1]?.value === "|" && !tokens[i + 1]?.sawQuote) {
473
+ flush("||");
474
+ pipe = false;
475
+ i++;
476
+ continue;
477
+ }
478
+ flush(token.value);
479
+ pipe = token.value === "|";
480
+ }
481
+ flush();
482
+ return out;
483
+ }
484
+ function installKind(command, depth = 0) {
485
+ if (depth > MAX_DEPTH || !command.trim())
486
+ return;
487
+ const parts = segments(command);
488
+ for (const [index, part] of parts.entries()) {
489
+ const kind = simpleKind(part.words);
490
+ if (kind)
491
+ return kind;
492
+ if (part.pipedFrom && readsStdin(part.words)) {
493
+ for (let up = part.pipedFrom;up; up = up.pipedFrom) {
494
+ if (isFetcher(up.words))
495
+ return "pipe-to-shell";
496
+ }
497
+ }
498
+ const args = shellArgs(part.words);
499
+ const substituted = part.next === "$(" || part.next === "(" && args?.at(-1) === "<";
500
+ if (args && substituted && isFetcher(parts[index + 1]?.words ?? []))
501
+ return "pipe-to-shell";
502
+ const script = args && args.indexOf("-c") >= 0 ? args[args.indexOf("-c") + 1] : undefined;
503
+ if (script !== undefined) {
504
+ if (/^\s*(?:\$\(|`)\s*(?:\S*\/)?(?:curl|wget)\b/.test(script))
505
+ return "pipe-to-shell";
506
+ const inner = installKind(script, depth + 1);
507
+ if (inner)
508
+ return inner;
509
+ }
510
+ }
511
+ for (const match of command.matchAll(/`([^`]*)`|\$\(([^()]*)\)/g)) {
512
+ const inner = installKind(match[1] ?? match[2] ?? "", depth + 1);
513
+ if (inner)
514
+ return inner;
515
+ }
516
+ return;
517
+ }
518
+ function evaluationKind(resources, metadata) {
519
+ const commands = [...resources];
520
+ if (typeof metadata?.command === "string")
521
+ commands.push(metadata.command);
522
+ for (const command of commands) {
523
+ const kind = installKind(command);
524
+ if (kind)
525
+ return kind;
526
+ }
527
+ if (resources.length > 1) {
528
+ const parsed = resources.map((resource) => segments(resource));
529
+ const fetches = parsed.some((parts) => parts.some((part) => isFetcher(part.words)));
530
+ const shell = parsed.some((parts) => parts.some((part) => readsStdin(part.words)));
531
+ if (fetches && shell)
532
+ return "pipe-to-shell";
533
+ }
534
+ return;
535
+ }
536
+
537
+ // plugins/find-tools/shared/query.ts
538
+ var STOPWORDS = new Set([
539
+ "a",
540
+ "an",
541
+ "and",
542
+ "any",
543
+ "for",
544
+ "from",
545
+ "in",
546
+ "into",
547
+ "is",
548
+ "it",
549
+ "of",
550
+ "on",
551
+ "or",
552
+ "that",
553
+ "the",
554
+ "to",
555
+ "with",
556
+ "find",
557
+ "need",
558
+ "want",
559
+ "some",
560
+ "something",
561
+ "tool",
562
+ "tools",
563
+ "plugin",
564
+ "plugins",
565
+ "skill",
566
+ "skills",
567
+ "server",
568
+ "servers",
569
+ "mcp",
570
+ "opencode",
571
+ "agent",
572
+ "agents",
573
+ "reusable",
574
+ "capability"
575
+ ]);
576
+ function queryTerms(query) {
577
+ const seen = new Set;
578
+ for (const word of query.toLowerCase().split(/[^a-z0-9@._/+-]+/)) {
579
+ const term = word.replace(/^[._/-]+|[._/-]+$/g, "");
580
+ if (term.length < 2 || STOPWORDS.has(term))
581
+ continue;
582
+ seen.add(term);
583
+ }
584
+ return [...seen];
585
+ }
586
+ function keyTerms(query, count) {
587
+ const terms = queryTerms(query);
588
+ if (terms.length === 0) {
589
+ const trimmed = query.trim();
590
+ return trimmed ? [trimmed] : [];
591
+ }
592
+ return [...terms].sort((a, b) => b.length - a.length || terms.indexOf(a) - terms.indexOf(b)).slice(0, count);
593
+ }
594
+ function relevance(terms, name, detail = "") {
595
+ const n = name.toLowerCase();
596
+ const d = detail.toLowerCase();
597
+ let score = 0;
598
+ for (const term of terms) {
599
+ if (n.includes(term))
600
+ score += 2;
601
+ else if (d.includes(term))
602
+ score += 1;
603
+ }
604
+ return score;
605
+ }
606
+ var NPM_TEXT_MAX = 64;
607
+ function npmSearchText(keyword, query) {
608
+ const text = `keywords:${keyword}`;
609
+ if (text.length > NPM_TEXT_MAX)
610
+ return null;
611
+ const terms = queryTerms(query);
612
+ let used = 0;
613
+ let joined = text;
614
+ for (const term of terms) {
615
+ if (joined.length + 1 + term.length > NPM_TEXT_MAX)
616
+ break;
617
+ joined = `${joined} ${term}`;
618
+ used++;
619
+ }
620
+ return { text: joined, dropped: terms.length - used };
621
+ }
622
+
623
+ // plugins/find-tools/shared/run.ts
624
+ import { spawn } from "child_process";
625
+
626
+ // lib/src/subprocess.ts
627
+ var EXIT_GRACE_MS = 2000;
628
+ var EXIT_POLL_MS = 100;
629
+ function goneWatch(graceMs, pollMs) {
630
+ const polls = Math.max(1, Math.ceil(graceMs / Math.max(1, pollMs)));
631
+ let since = null;
632
+ let seen = 0;
633
+ return (alive) => {
634
+ if (alive) {
635
+ since = null;
636
+ seen = 0;
637
+ return false;
638
+ }
639
+ since ??= Date.now();
640
+ seen++;
641
+ return seen > polls && Date.now() - since >= graceMs;
642
+ };
643
+ }
644
+ function processAlive(pid) {
645
+ try {
646
+ process.kill(pid, 0);
647
+ return true;
648
+ } catch (error) {
649
+ return error.code === "EPERM";
650
+ }
651
+ }
652
+
653
+ // plugins/find-tools/shared/run.ts
654
+ var DEFAULT_MS = 1e4;
655
+ var OUTPUT_LIMIT = 1048576;
656
+ function defaultRun(argv, timeoutMs, signal) {
657
+ if (signal?.aborted)
658
+ return Promise.resolve({ ok: false, stdout: "", stderr: "Cancelled before spawn" });
659
+ const command = argv[0];
660
+ if (!command)
661
+ return Promise.resolve({ ok: false, stdout: "", stderr: "No command provided" });
662
+ return new Promise((resolve) => {
663
+ try {
664
+ const proc = spawn(command, argv.slice(1), {
665
+ stdio: ["ignore", "pipe", "pipe"],
666
+ detached: process.platform !== "win32"
667
+ });
668
+ const stdout = [];
669
+ const stderr = [];
670
+ let bytes = 0;
671
+ let stopped = "";
672
+ let settled = false;
673
+ let cleanup;
674
+ const finish = (code) => {
675
+ if (settled)
676
+ return;
677
+ settled = true;
678
+ clearTimeout(deadline);
679
+ clearInterval(poll);
680
+ if (cleanup)
681
+ clearTimeout(cleanup);
682
+ signal?.removeEventListener("abort", abort);
683
+ proc.stdout?.destroy();
684
+ proc.stderr?.destroy();
685
+ resolve({
686
+ ok: !stopped && code === 0,
687
+ stdout: Buffer.concat(stdout).toString("utf8"),
688
+ stderr: [Buffer.concat(stderr).toString("utf8"), stopped].filter(Boolean).join(`
689
+ `)
690
+ });
691
+ };
692
+ const stop = (reason) => {
693
+ if (stopped || settled)
694
+ return;
695
+ stopped = reason;
696
+ try {
697
+ if (process.platform !== "win32" && proc.pid)
698
+ process.kill(-proc.pid, "SIGKILL");
699
+ else
700
+ proc.kill("SIGKILL");
701
+ } catch {}
702
+ cleanup = setTimeout(() => finish(1), 1000);
703
+ };
704
+ const abort = () => stop("Cancelled");
705
+ const ms = Number.isFinite(timeoutMs) ? Math.max(1, Math.min(timeoutMs, DEFAULT_MS)) : DEFAULT_MS;
706
+ const deadline = setTimeout(() => stop("Discovery command deadline exceeded"), ms);
707
+ const gone = goneWatch(EXIT_GRACE_MS, EXIT_POLL_MS);
708
+ let exitSeen = false;
709
+ const poll = setInterval(() => {
710
+ if (gone(exitSeen || !proc.pid || processAlive(proc.pid)))
711
+ stop("Discovery command ended without reporting an exit status");
712
+ }, EXIT_POLL_MS);
713
+ poll.unref?.();
714
+ const collect = (target, chunk) => {
715
+ if (stopped || settled)
716
+ return;
717
+ const remaining = OUTPUT_LIMIT - bytes;
718
+ if (remaining > 0) {
719
+ const kept = chunk.subarray(0, remaining);
720
+ target.push(Buffer.from(kept));
721
+ bytes += kept.length;
722
+ }
723
+ if (chunk.length > remaining)
724
+ stop("Discovery command output limit exceeded");
725
+ };
726
+ proc.stdout?.on("data", (chunk) => collect(stdout, chunk));
727
+ proc.stderr?.on("data", (chunk) => collect(stderr, chunk));
728
+ proc.on("error", (error) => {
729
+ stopped = `Discovery command failed to start: ${error.message}`;
730
+ finish(1);
731
+ });
732
+ proc.on("exit", () => {
733
+ exitSeen = true;
734
+ });
735
+ proc.on("close", (code) => finish(code ?? 1));
736
+ signal?.addEventListener("abort", abort, { once: true });
737
+ if (signal?.aborted)
738
+ abort();
739
+ } catch (error) {
740
+ resolve({ ok: false, stdout: "", stderr: error instanceof Error ? error.message : String(error) });
741
+ }
742
+ });
743
+ }
744
+
745
+ // plugins/find-tools/shared/scan.ts
746
+ var SOURCES = [
747
+ "local",
748
+ "catalog",
749
+ "mcp_registry",
750
+ "npm",
751
+ "github",
752
+ "awesome_opencode",
753
+ "smithery",
754
+ "skills_cli"
755
+ ];
756
+ var SOURCE_TIMEOUT_MS = 1e4;
757
+ var REPOSITORY = "srobroek/harness-plugins";
758
+ var REPO_SPEC = `github:${REPOSITORY}::path:plugins`;
759
+ var INVENTORY_URL = `https://raw.githubusercontent.com/${REPOSITORY}/main/inventory.json`;
760
+ var CATALOG_URLS = {
761
+ claude: `https://raw.githubusercontent.com/${REPOSITORY}/main/.claude-plugin/marketplace.json`,
762
+ opencode: INVENTORY_URL,
763
+ omp: `https://raw.githubusercontent.com/${REPOSITORY}/main/.omp-plugin/marketplace.json`,
764
+ pi: INVENTORY_URL
765
+ };
766
+ var DEFAULT_CATALOG_URL = CATALOG_URLS.opencode;
767
+ function catalogUrlFor(harness) {
768
+ return CATALOG_URLS[harness];
769
+ }
770
+ function piPackage(name, piName) {
771
+ return `@srobroek/${piName ?? `pi-${name}`}`;
772
+ }
773
+ function installHint(harness, name, piName) {
774
+ switch (harness) {
775
+ case "claude":
776
+ return `/plugin install ${name}@harness-plugins`;
777
+ case "omp":
778
+ return `omp plugin install --scope project ${name}@harness-plugins`;
779
+ case "pi":
780
+ return `pi install npm:${piPackage(name, piName)}`;
781
+ case "opencode":
782
+ return `opencode plugin add 'github:${REPOSITORY}::path:plugins/${name}/opencode'`;
783
+ }
784
+ }
785
+ var AWESOME_OPENCODE_URL = "https://raw.githubusercontent.com/awesome-opencode/awesome-opencode/main/README.md";
786
+ var MCP_REGISTRY_URL = "https://registry.modelcontextprotocol.io/v0.1/servers";
787
+ var NPM_SEARCH_URL = "https://registry.npmjs.org/-/v1/search";
788
+ var SMITHERY_URL = "https://registry.smithery.ai/servers";
789
+ var NPM_KEYWORDS = ["opencode-plugin", "mcp-server", "agent-skill", "claude-skill"];
790
+ var SEARCH_CAP = 20;
791
+ var DETAIL_CHARS = 300;
792
+ function classify(result) {
793
+ if (result.skipped)
794
+ return "skipped";
795
+ if (!result.ok)
796
+ return "failed";
797
+ if (result.failures?.length)
798
+ return "partial";
799
+ return result.hits.length > 0 ? "ok" : "empty";
800
+ }
801
+ var failed = (source, reason, extra = {}) => ({
802
+ source,
803
+ ok: false,
804
+ reason,
805
+ hits: [],
806
+ ...extra
807
+ });
808
+ var message = (error) => error instanceof Error ? error.message : String(error);
809
+ async function getText(fetchFn, url, signal, init) {
810
+ try {
811
+ const res = await fetchFn(url, { ...init, signal });
812
+ return { ok: res.ok, status: res.status, text: await res.text() };
813
+ } catch (error) {
814
+ return { ok: false, status: 0, text: message(error) };
815
+ }
816
+ }
817
+ function httpReason(res) {
818
+ return res.status ? `HTTP ${res.status}: ${res.text.slice(0, 200)}` : res.text.slice(0, 200) || "request failed";
819
+ }
820
+ function parseJson(text) {
821
+ try {
822
+ return JSON.parse(text);
823
+ } catch {
824
+ return;
825
+ }
826
+ }
827
+ var record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
828
+ var str = (value) => typeof value === "string" && value ? value : undefined;
829
+ function listOf(value) {
830
+ if (Array.isArray(value))
831
+ return value;
832
+ const data = record(value)?.data;
833
+ return Array.isArray(data) ? data : [];
834
+ }
835
+ function pluginHit(plugin) {
836
+ const source = plugin.source;
837
+ let origin = source?.type ?? "unknown";
838
+ if (source?.type === "package") {
839
+ origin = `package ${source.target ?? "?"}${source.version ? `@${source.version}` : ""}${source.outdated ? " (outdated)" : ""}`;
840
+ } else if (source?.version) {
841
+ origin = `${source.type} ${source.version}`;
842
+ }
843
+ const failedState = plugin.state?.status === "failed" ? "; failed to load" : "";
844
+ const name = plugin.id ?? (source?.type === "package" ? source.target : undefined) ?? "unnamed";
845
+ return { name: `plugin:${name}`, detail: `${origin}${failedState}` };
846
+ }
847
+ function mcpCounts(servers) {
848
+ const counts = { configured: 0 };
849
+ for (const server of servers) {
850
+ counts.configured = (counts.configured ?? 0) + 1;
851
+ const status = server?.status?.status;
852
+ const key = status && /^[a-z_]{1,20}$/.test(status) ? status : "unknown";
853
+ counts[key] = (counts[key] ?? 0) + 1;
854
+ }
855
+ return counts;
856
+ }
857
+ async function scanLocal(local) {
858
+ if (!local)
859
+ return { source: "local", ok: true, skipped: true, reason: "host inventory unavailable", hits: [] };
860
+ if (local.pi) {
861
+ const inventory = await local.pi();
862
+ const hits = [];
863
+ for (const item of listOf(inventory.packages)) {
864
+ const source = typeof item === "string" ? item : record(item)?.source;
865
+ if (typeof source === "string" && /^(?:npm:|git:|https?:|builtin:)/u.test(source)) {
866
+ const packageName = source.startsWith("npm:") ? source.slice(4).replace(/@[^/@]+$/u, "") : source;
867
+ hits.push({ name: `pi-package:${packageName}` });
868
+ }
869
+ }
870
+ for (const value of listOf(inventory.skills)) {
871
+ const skill = record(value);
872
+ const name = str(skill?.name) ?? str(skill?.id);
873
+ if (name)
874
+ hits.push({ name: `pi-skill:${name}`, ...str(skill?.description) ? { detail: str(skill?.description) } : {} });
875
+ }
876
+ if (inventory.mcp !== undefined) {
877
+ const servers = record(inventory.mcp);
878
+ const entries = servers ? Object.values(servers) : listOf(inventory.mcp);
879
+ hits.push({ name: "pi-mcp", detail: JSON.stringify({ configured: entries.length }) });
880
+ }
881
+ return { source: "local", ok: true, hits };
882
+ }
883
+ const [plugins, skills, mcp] = await Promise.allSettled([
884
+ local.plugins?.() ?? Promise.resolve([]),
885
+ local.skills?.() ?? Promise.resolve([]),
886
+ local.mcp?.() ?? Promise.resolve([])
887
+ ]);
888
+ const hits = [];
889
+ const failures = [];
890
+ if (plugins.status === "fulfilled") {
891
+ const entries = listOf(plugins.value);
892
+ hits.push(...entries.map((plugin) => pluginHit(plugin)));
893
+ } else
894
+ failures.push(`plugin list failed: ${message(plugins.reason).slice(0, 200)}`);
895
+ if (skills.status === "fulfilled") {
896
+ for (const skill of listOf(skills.value)) {
897
+ const name = skill.name ?? skill.id;
898
+ if (name)
899
+ hits.push(skill.description ? { name: `skill:${name}`, detail: skill.description } : { name: `skill:${name}` });
900
+ }
901
+ } else
902
+ failures.push(`skill list failed: ${message(skills.reason).slice(0, 200)}`);
903
+ if (mcp.status === "fulfilled")
904
+ hits.push({ name: "mcp", detail: JSON.stringify(mcpCounts(listOf(mcp.value))) });
905
+ else
906
+ failures.push("mcp list failed");
907
+ if (failures.length === 3)
908
+ return failed("local", failures.join("; "), { failures });
909
+ return { source: "local", ok: true, hits, ...failures.length ? { failures } : {} };
910
+ }
911
+ function catalogEntries(json, harness = "opencode") {
912
+ const obj = record(json);
913
+ const list = Array.isArray(json) ? json : Array.isArray(obj?.plugins) ? obj.plugins : obj?.skills;
914
+ if (!Array.isArray(list))
915
+ return;
916
+ const inventory = Array.isArray(obj?.plugins) && obj.plugins.some((item) => record(record(item)?.harnesses) !== undefined);
917
+ const kind = inventory ? "inventory" : Array.isArray(obj?.plugins) ? "marketplace" : "skills";
918
+ const entries = [];
919
+ for (const item of list) {
920
+ const entry = record(item);
921
+ const name = str(entry?.name);
922
+ if (!name)
923
+ continue;
924
+ if (inventory && record(record(entry?.harnesses)?.[harness]) === undefined)
925
+ continue;
926
+ const description = str(entry?.description);
927
+ const source = str(entry?.source) ?? str(record(entry?.source)?.url) ?? str(record(entry?.source)?.repo);
928
+ const piName = inventory ? str(entry?.piName) : undefined;
929
+ entries.push({ name, ...description ? { description } : {}, ...source ? { source } : {}, ...piName ? { piName } : {} });
930
+ }
931
+ return { kind, entries };
932
+ }
933
+ function catalogIndexUrl(url) {
934
+ return url.endsWith("/") ? `${url}index.json` : url;
935
+ }
936
+ function catalogHits(url, own, json, terms, harness = "opencode") {
937
+ const parsed = catalogEntries(json, harness);
938
+ if (!parsed)
939
+ return;
940
+ const ranked = parsed.entries.map((entry) => ({ entry, score: terms.length ? relevance(terms, entry.name, entry.description) : 1 })).filter(({ score }) => score > 0).sort((a, b) => b.score - a.score).slice(0, SEARCH_CAP);
941
+ return ranked.map(({ entry }) => {
942
+ const install = own ? installHint(harness, entry.name, entry.piName) : parsed.kind === "skills" ? `project: add "${url}" to "skills" in opencode.json` : `Claude Code marketplace entry${entry.source ? ` (source ${entry.source})` : ""}; inspect it before adapting`;
943
+ return {
944
+ name: own ? entry.name : `${entry.name} (${new URL(url).host})`,
945
+ ...entry.description ? { detail: entry.description } : {},
946
+ url: own ? `https://github.com/${REPOSITORY}/tree/main/plugins/${entry.name}/${harness}` : url,
947
+ install
948
+ };
949
+ });
950
+ }
951
+ async function scanCatalog(fetchFn, signal, query, catalogUrl, extra, harness) {
952
+ const terms = queryTerms(query);
953
+ const urls = [catalogUrl, ...extra.filter((u) => u !== catalogUrl)];
954
+ const answers = await Promise.all(urls.map(async (url, index) => {
955
+ let target;
956
+ try {
957
+ target = new URL(catalogIndexUrl(url)).href;
958
+ } catch {
959
+ return { url, error: "invalid URL" };
960
+ }
961
+ if (!/^https?:$/.test(new URL(target).protocol))
962
+ return { url, error: "not an http(s) URL" };
963
+ const res = await getText(fetchFn, target, signal);
964
+ if (!res.ok)
965
+ return { url, error: httpReason(res) };
966
+ const hits = catalogHits(url, index === 0 && url === catalogUrl, parseJson(res.text), terms, harness);
967
+ return hits ? { url, hits } : { url, error: "not a recognised catalog" };
968
+ }));
969
+ const hits = [];
970
+ const failures = [];
971
+ for (const answer of answers) {
972
+ if ("hits" in answer && answer.hits)
973
+ hits.push(...answer.hits);
974
+ else
975
+ failures.push(`${answer.url}: ${answer.error}`);
976
+ }
977
+ if (failures.length === urls.length)
978
+ return failed("catalog", failures.join("; "), { failures });
979
+ return { source: "catalog", ok: true, hits, ...failures.length ? { failures } : {} };
980
+ }
981
+ var shortName = (name) => (name.split("/").pop() ?? name).replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "server";
982
+ function registryInstall(server) {
983
+ const name = shortName(server.name ?? "server");
984
+ const remote = server.remotes?.find((r) => r.url && !r.url.includes("{"));
985
+ if (remote?.url)
986
+ return { install: `opencode mcp add ${name} --url ${remote.url}` };
987
+ const pkg = server.packages?.find((p) => p.identifier);
988
+ if (pkg?.identifier) {
989
+ const versioned = pkg.version ? `${pkg.identifier}@${pkg.version}` : pkg.identifier;
990
+ const runner = pkg.registryType === "npm" ? `npx -y ${versioned}` : pkg.registryType === "pypi" ? `uvx ${pkg.version ? `${pkg.identifier}==${pkg.version}` : pkg.identifier}` : pkg.registryType === "oci" ? `docker run -i --rm ${pkg.identifier}${pkg.version ? `:${pkg.version}` : ""}` : undefined;
991
+ if (runner)
992
+ return { install: `opencode mcp add ${name} -- ${runner}`, runsCode: true };
993
+ }
994
+ if (server.remotes?.length)
995
+ return { install: "remote URL needs template variables; see the registry entry" };
996
+ return {};
997
+ }
998
+ async function scanMcpRegistry(fetchFn, signal, query) {
999
+ const searches = keyTerms(query, 3);
1000
+ if (searches.length === 0)
1001
+ return { source: "mcp_registry", ok: true, reason: "empty query", hits: [] };
1002
+ const terms = queryTerms(query);
1003
+ const answers = await Promise.all(searches.map(async (search) => {
1004
+ const url = `${MCP_REGISTRY_URL}?search=${encodeURIComponent(search)}&version=latest&limit=30`;
1005
+ return { search, res: await getText(fetchFn, url, signal) };
1006
+ }));
1007
+ const seen = new Map;
1008
+ const failures = [];
1009
+ for (const { search, res } of answers) {
1010
+ if (!res.ok) {
1011
+ failures.push(`${search}: ${httpReason(res)}`);
1012
+ continue;
1013
+ }
1014
+ const servers = record(parseJson(res.text))?.servers;
1015
+ if (!Array.isArray(servers)) {
1016
+ failures.push(`${search}: invalid registry response`);
1017
+ continue;
1018
+ }
1019
+ for (const entry of servers) {
1020
+ const server = record(record(entry)?.server) ?? record(entry);
1021
+ const name = str(server?.name);
1022
+ if (!server || !name || seen.has(name))
1023
+ continue;
1024
+ const detail = str(server.description) ?? str(server.title);
1025
+ const url = str(server.repository?.url) ?? str(server.websiteUrl);
1026
+ const hit = { name, ...detail ? { detail } : {}, ...url ? { url } : {}, ...registryInstall(server) };
1027
+ seen.set(name, { hit, score: relevance(terms, name, `${server.title ?? ""} ${detail ?? ""}`) });
1028
+ }
1029
+ }
1030
+ if (failures.length === searches.length)
1031
+ return failed("mcp_registry", failures.join("; "), { failures });
1032
+ const hits = [...seen.values()].sort((a, b) => b.score - a.score).slice(0, SEARCH_CAP).map(({ hit }) => hit);
1033
+ return {
1034
+ source: "mcp_registry",
1035
+ ok: true,
1036
+ reason: `searched name substrings: ${searches.join(", ")}`,
1037
+ hits,
1038
+ ...failures.length ? { failures } : {}
1039
+ };
1040
+ }
1041
+ function npmInstall(name, keywords) {
1042
+ if (keywords.has("opencode-plugin")) {
1043
+ return { install: `project: add "${name}" to "plugins" in opencode.json; user-wide: opencode plugin add ${name}` };
1044
+ }
1045
+ if (keywords.has("mcp-server"))
1046
+ return { install: `opencode mcp add ${shortName(name)} -- npx -y ${name}`, runsCode: true };
1047
+ return { install: "skill package: vet its SKILL.md, then copy the skill directory into .opencode/skills/" };
1048
+ }
1049
+ async function scanNpm(fetchFn, signal, query) {
1050
+ const terms = queryTerms(query);
1051
+ const searches = await Promise.all(NPM_KEYWORDS.map(async (keyword) => {
1052
+ const search = npmSearchText(keyword, query);
1053
+ if (!search)
1054
+ return { keyword, search, res: undefined };
1055
+ const url = `${NPM_SEARCH_URL}?text=${encodeURIComponent(search.text)}&size=10`;
1056
+ return { keyword, search, res: await getText(fetchFn, url, signal) };
1057
+ }));
1058
+ const found = new Map;
1059
+ const failures = [];
1060
+ let answered = 0;
1061
+ let dropped = 0;
1062
+ for (const { keyword, search, res } of searches) {
1063
+ if (!search || !res) {
1064
+ failures.push(`${keyword}: keyword alone exceeds npm's ${NPM_TEXT_MAX}-character search text limit`);
1065
+ continue;
1066
+ }
1067
+ dropped = Math.max(dropped, search.dropped);
1068
+ if (!res.ok) {
1069
+ failures.push(`${keyword}: ${res.status ? `HTTP ${res.status}` : res.text.slice(0, 120)}`);
1070
+ continue;
1071
+ }
1072
+ const objects = record(parseJson(res.text))?.objects;
1073
+ if (!Array.isArray(objects)) {
1074
+ failures.push(`${keyword}: invalid search response`);
1075
+ continue;
1076
+ }
1077
+ answered++;
1078
+ for (const object of objects) {
1079
+ const p = object?.package;
1080
+ if (!p?.name)
1081
+ continue;
1082
+ const entry = found.get(p.name) ?? {
1083
+ name: p.name,
1084
+ ...p.description ? { detail: p.description } : {},
1085
+ ...p.links?.npm ? { url: p.links.npm } : {},
1086
+ keywords: new Set,
1087
+ monthly: object.downloads?.monthly ?? 0
1088
+ };
1089
+ entry.keywords.add(keyword);
1090
+ for (const kw of p.keywords ?? [])
1091
+ if (NPM_KEYWORDS.includes(kw))
1092
+ entry.keywords.add(kw);
1093
+ found.set(p.name, entry);
1094
+ }
1095
+ }
1096
+ if (answered === 0)
1097
+ return failed("npm", failures.join("; ") || "no npm searches ran", { failures });
1098
+ const hits = [...found.values()].map((entry) => ({ entry, score: relevance(terms, entry.name, entry.detail) })).sort((a, b) => b.score - a.score || b.entry.monthly - a.entry.monthly).slice(0, SEARCH_CAP).map(({ entry }) => {
1099
+ const downloads = entry.monthly ? ` [${entry.monthly.toLocaleString("en-US")}/month]` : "";
1100
+ return {
1101
+ name: entry.name,
1102
+ detail: `${entry.detail ?? ""}${downloads} (${[...entry.keywords].join(", ")})`.trim(),
1103
+ ...entry.url ? { url: entry.url } : {},
1104
+ ...npmInstall(entry.name, entry.keywords)
1105
+ };
1106
+ });
1107
+ const notes = [
1108
+ failures.length ? `${answered}/${NPM_KEYWORDS.length} keyword searches answered` : "",
1109
+ dropped ? `query trimmed to npm's ${NPM_TEXT_MAX}-character search text (${dropped} term(s) dropped)` : "",
1110
+ found.size > SEARCH_CAP ? `top ${SEARCH_CAP} of ${found.size} packages` : ""
1111
+ ].filter(Boolean);
1112
+ return {
1113
+ source: "npm",
1114
+ ok: true,
1115
+ hits,
1116
+ ...failures.length ? { failures } : {},
1117
+ ...notes.length ? { reason: notes.join("; ") } : {}
1118
+ };
1119
+ }
1120
+ function githubSearches(query) {
1121
+ const q = keyTerms(query, 3).join(" ");
1122
+ return [
1123
+ {
1124
+ label: "code .claude-plugin/marketplace.json",
1125
+ path: `search/code?q=${encodeURIComponent(`${q} filename:marketplace.json path:.claude-plugin`)}&per_page=10`,
1126
+ kind: "marketplace"
1127
+ },
1128
+ {
1129
+ label: "code SKILL.md",
1130
+ path: `search/code?q=${encodeURIComponent(`${q} filename:SKILL.md`)}&per_page=10`,
1131
+ kind: "skill"
1132
+ },
1133
+ {
1134
+ label: "repos topic:opencode-plugin",
1135
+ path: `search/repositories?q=${encodeURIComponent(`${q} topic:opencode-plugin`)}&sort=stars&per_page=10`,
1136
+ kind: "repo"
1137
+ }
1138
+ ];
1139
+ }
1140
+ function githubHits(kind, json) {
1141
+ const items = record(json)?.items;
1142
+ if (!Array.isArray(items))
1143
+ return;
1144
+ const hits = [];
1145
+ for (const raw of items) {
1146
+ const item = record(raw);
1147
+ if (!item)
1148
+ continue;
1149
+ if (kind === "repo") {
1150
+ const name = str(item.full_name);
1151
+ if (!name)
1152
+ continue;
1153
+ const stars = typeof item.stargazers_count === "number" ? ` [${item.stargazers_count} stars]` : "";
1154
+ const license = str(record(item.license)?.spdx_id);
1155
+ const pushed = str(item.pushed_at)?.slice(0, 10);
1156
+ const meta = [license, pushed ? `pushed ${pushed}` : ""].filter(Boolean).join(", ");
1157
+ hits.push({
1158
+ name,
1159
+ detail: `${str(item.description) ?? ""}${stars}${meta ? ` (${meta})` : ""}`.trim(),
1160
+ ...str(item.html_url) ? { url: str(item.html_url) } : {},
1161
+ install: `project: add "github:${name}" to "plugins" in opencode.json, after checking it is a V2 plugin`
1162
+ });
1163
+ continue;
1164
+ }
1165
+ const repo = str(record(item.repository)?.full_name);
1166
+ const path = str(item.path);
1167
+ if (!repo)
1168
+ continue;
1169
+ const install = kind === "skill" ? `copy the skill directory${path ? ` ${path.replace(/\/?SKILL\.md$/, "") || "."}` : ""} into .opencode/skills/` : "Claude Code marketplace: read its entries; OpenCode does not install from it";
1170
+ hits.push({
1171
+ name: path ? `${repo}/${path}` : repo,
1172
+ ...str(item.html_url) ? { url: str(item.html_url) } : {},
1173
+ install
1174
+ });
1175
+ }
1176
+ return hits;
1177
+ }
1178
+ async function scanGithub(run, which, signal, timeoutMs, query) {
1179
+ if (!which("gh"))
1180
+ return { source: "github", ok: true, skipped: true, reason: "gh not found", hits: [] };
1181
+ const searches = githubSearches(query);
1182
+ const answers = await Promise.all(searches.map(async (search) => ({ search, res: await run(["gh", "api", search.path], timeoutMs, signal) })));
1183
+ const hits = [];
1184
+ const failures = [];
1185
+ const seen = new Set;
1186
+ for (const { search, res } of answers) {
1187
+ if (!res.ok) {
1188
+ failures.push(`${search.label}: ${res.stderr.trim().slice(0, 200) || "gh api failed"}`);
1189
+ continue;
1190
+ }
1191
+ const found = githubHits(search.kind, parseJson(res.stdout));
1192
+ if (!found) {
1193
+ failures.push(`${search.label}: invalid GitHub search response`);
1194
+ continue;
1195
+ }
1196
+ for (const hit of found) {
1197
+ if (seen.has(hit.name))
1198
+ continue;
1199
+ seen.add(hit.name);
1200
+ hits.push(hit);
1201
+ }
1202
+ }
1203
+ if (failures.length === searches.length)
1204
+ return failed("github", failures.join("; "), { failures });
1205
+ return { source: "github", ok: true, hits, ...failures.length ? { failures } : {} };
1206
+ }
1207
+ var stripTags = (html) => html.replace(/<br\s*\/?>/gi, " ").replace(/<[^>]+>/g, "").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\s+/g, " ").trim();
1208
+ function awesomeEntries(markdown) {
1209
+ const entries = [];
1210
+ let section;
1211
+ const cards = /<summary><strong>([^<]*)<\/strong><\/summary>|<details>\s*<summary>([\s\S]*?)<\/summary>([\s\S]*?)<\/details>|^\s*[-*] \[([^\]]+)\]\(([^)\s]+)\)\s*[-\u2013\u2014:]?\s*(.*)$/gm;
1212
+ for (const match of markdown.matchAll(cards)) {
1213
+ if (match[1] !== undefined) {
1214
+ section = stripTags(match[1]).replace(/^[^A-Za-z]+/, "") || undefined;
1215
+ continue;
1216
+ }
1217
+ if (match[2] !== undefined) {
1218
+ const name = stripTags(/<b>([\s\S]*?)<\/b>/.exec(match[2])?.[1] ?? "");
1219
+ if (!name)
1220
+ continue;
1221
+ const tagline = stripTags(/<i>([\s\S]*?)<\/i>/.exec(match[2])?.[1] ?? "");
1222
+ const body = stripTags(match[3] ?? "").replace(/\uD83D\uDD17\s*View Repository/g, "").trim();
1223
+ const url = /href="([^"]+)"/.exec(match[3] ?? "")?.[1];
1224
+ entries.push({ name, detail: [tagline, body].filter(Boolean).join(" \u2014 "), ...url ? { url } : {}, ...section ? { section } : {} });
1225
+ continue;
1226
+ }
1227
+ if (match[4] !== undefined) {
1228
+ entries.push({ name: match[4], detail: stripTags(match[6] ?? ""), url: match[5], ...section ? { section } : {} });
1229
+ }
1230
+ }
1231
+ return entries;
1232
+ }
1233
+ async function scanAwesome(fetchFn, signal, query) {
1234
+ const res = await getText(fetchFn, AWESOME_OPENCODE_URL, signal);
1235
+ if (!res.ok)
1236
+ return failed("awesome_opencode", httpReason(res));
1237
+ const entries = awesomeEntries(res.text);
1238
+ if (entries.length === 0)
1239
+ return failed("awesome_opencode", "README had no recognisable entries");
1240
+ const terms = queryTerms(query);
1241
+ const hits = entries.map((entry) => ({ entry, score: relevance(terms, entry.name, entry.detail) })).filter(({ score }) => score > 0).sort((a, b) => b.score - a.score).slice(0, SEARCH_CAP).map(({ entry }) => ({
1242
+ name: entry.name,
1243
+ detail: entry.section ? `[${entry.section}] ${entry.detail}` : entry.detail,
1244
+ ...entry.url ? { url: entry.url } : {},
1245
+ unvetted: true
1246
+ }));
1247
+ return {
1248
+ source: "awesome_opencode",
1249
+ ok: true,
1250
+ reason: `community list, unvetted: ${hits.length} of ${entries.length} entries matched`,
1251
+ hits
1252
+ };
1253
+ }
1254
+ async function scanSmithery(fetchFn, signal, env, query) {
1255
+ const key = env.SMITHERY_API_KEY;
1256
+ if (!key)
1257
+ return { source: "smithery", ok: true, skipped: true, reason: "SMITHERY_API_KEY unset", hits: [] };
1258
+ const url = `${SMITHERY_URL}?q=${encodeURIComponent(query)}&pageSize=${SEARCH_CAP}`;
1259
+ const res = await getText(fetchFn, url, signal, { headers: { Authorization: `Bearer ${key}` } });
1260
+ if (!res.ok)
1261
+ return failed("smithery", httpReason(res));
1262
+ const servers = record(parseJson(res.text))?.servers;
1263
+ if (!Array.isArray(servers)) {
1264
+ return {
1265
+ source: "smithery",
1266
+ ok: true,
1267
+ failures: ["unparseable Smithery response; raw text kept"],
1268
+ hits: [{ name: "raw", detail: res.text.slice(0, 1000) }]
1269
+ };
1270
+ }
1271
+ const hits = [];
1272
+ for (const raw of servers.slice(0, SEARCH_CAP)) {
1273
+ const server = record(raw);
1274
+ const name = str(server?.qualifiedName) ?? str(server?.displayName);
1275
+ if (!server || !name)
1276
+ continue;
1277
+ const uses = typeof server.useCount === "number" ? ` [${server.useCount} uses]` : "";
1278
+ const verified = server.verified === true ? " (verified)" : "";
1279
+ const description = str(server.description);
1280
+ hits.push({
1281
+ name,
1282
+ ...description || uses || verified ? { detail: `${description ?? ""}${uses}${verified}`.trim() } : {},
1283
+ url: `https://smithery.ai/server/${name}`,
1284
+ install: server.remote === true ? `opencode mcp add ${shortName(name)} --url https://server.smithery.ai/${name}/mcp` : "local server: read its Smithery page for the package and run command"
1285
+ });
1286
+ }
1287
+ return { source: "smithery", ok: true, hits };
1288
+ }
1289
+ async function scanSkillsCli() {
1290
+ return {
1291
+ source: "skills_cli",
1292
+ ok: true,
1293
+ skipped: true,
1294
+ hits: [],
1295
+ reason: "not run: the skills CLI (`npx skills find`) downloads and runs package code. Discovery never runs it; " + "vet the package and ask the user before any `skills` command."
1296
+ };
1297
+ }
1298
+ async function bounded(source, ms, outer, job) {
1299
+ const own = new AbortController;
1300
+ const signal = outer ? AbortSignal.any([outer, own.signal]) : own.signal;
1301
+ let timer;
1302
+ let onAbort;
1303
+ const deadline = new Promise((resolve) => {
1304
+ timer = setTimeout(() => {
1305
+ own.abort();
1306
+ resolve(failed(source, `timed out after ${ms / 1000} s`));
1307
+ }, ms);
1308
+ });
1309
+ const cancelled = new Promise((resolve) => {
1310
+ if (!outer)
1311
+ return;
1312
+ onAbort = () => resolve(failed(source, "cancelled"));
1313
+ if (outer.aborted)
1314
+ onAbort();
1315
+ else
1316
+ outer.addEventListener("abort", onAbort, { once: true });
1317
+ });
1318
+ try {
1319
+ return await Promise.race([job(signal).catch((error) => failed(source, message(error))), deadline, cancelled]);
1320
+ } finally {
1321
+ clearTimeout(timer);
1322
+ if (onAbort)
1323
+ outer?.removeEventListener("abort", onAbort);
1324
+ }
1325
+ }
1326
+ async function scanSources(params, deps = {}) {
1327
+ const fetchFn = deps.fetchFn ?? fetch;
1328
+ const run = deps.run ?? defaultRun;
1329
+ const which = deps.which ?? ((bin) => Bun.which(bin) !== null);
1330
+ const env = deps.env ?? process.env;
1331
+ const ms = deps.timeoutMs ?? SOURCE_TIMEOUT_MS;
1332
+ const query = params.query.trim();
1333
+ const requested = params.sources?.map((s) => s.trim()).filter(Boolean) ?? [];
1334
+ const invalid = requested.filter((name) => !SOURCES.includes(name));
1335
+ if (invalid.length > 0) {
1336
+ throw new Error(`Unknown source${invalid.length === 1 ? "" : "s"}: ${invalid.join(", ")}. Valid sources: ${SOURCES.join(", ")}`);
1337
+ }
1338
+ const selected = requested.length > 0 ? new Set(requested) : null;
1339
+ const jobs = {
1340
+ local: () => scanLocal(deps.local),
1341
+ catalog: (signal) => scanCatalog(fetchFn, signal, query, deps.catalogUrl ?? catalogUrlFor(deps.harness ?? "opencode"), deps.skillCatalogs ?? [], deps.harness ?? "opencode"),
1342
+ mcp_registry: (signal) => scanMcpRegistry(fetchFn, signal, query),
1343
+ npm: (signal) => scanNpm(fetchFn, signal, query),
1344
+ github: (signal) => scanGithub(run, which, signal, ms, query),
1345
+ awesome_opencode: (signal) => scanAwesome(fetchFn, signal, query),
1346
+ smithery: (signal) => scanSmithery(fetchFn, signal, env, query),
1347
+ skills_cli: scanSkillsCli
1348
+ };
1349
+ const completed = new Set;
1350
+ const results = await Promise.all(SOURCES.map(async (source) => {
1351
+ if (selected && !selected.has(source)) {
1352
+ return { source, ok: true, skipped: true, reason: "not requested", hits: [] };
1353
+ }
1354
+ if (deps.signal?.aborted)
1355
+ return failed(source, "cancelled");
1356
+ const result = await bounded(source, ms, deps.signal, jobs[source]);
1357
+ if (result.reason !== "cancelled")
1358
+ completed.add(source);
1359
+ return result;
1360
+ }));
1361
+ const classified = results.map((r) => ({ ...r, status: classify(r) }));
1362
+ const gaps = [];
1363
+ const coverage = { answered: 0, empty: 0, partial: 0, unavailable: 0, failed: 0 };
1364
+ for (const r of classified) {
1365
+ if (r.status === "ok")
1366
+ coverage.answered++;
1367
+ else if (r.status === "empty")
1368
+ coverage.empty++;
1369
+ else if (r.status === "partial") {
1370
+ coverage.partial++;
1371
+ gaps.push({ source: r.source, kind: "partial", reason: r.failures?.join("; ") ?? r.reason ?? "partial coverage" });
1372
+ } else if (r.status === "skipped") {
1373
+ coverage.unavailable++;
1374
+ gaps.push({ source: r.source, kind: "unavailable", reason: r.reason ?? "skipped" });
1375
+ } else {
1376
+ coverage.failed++;
1377
+ gaps.push({ source: r.source, kind: "failed", reason: r.reason ?? "failed" });
1378
+ }
1379
+ }
1380
+ const started = SOURCES.filter((s) => !selected || selected.has(s));
1381
+ const cancellation = deps.signal?.aborted ? { completed: started.filter((s) => completed.has(s)), timedOut: started.filter((s) => !completed.has(s)) } : undefined;
1382
+ return { results: classified, gaps, coverage, ...cancellation ? { cancellation } : {} };
1383
+ }
1384
+ var SEARCH_HITS_SHOWN = 8;
1385
+ function clip(text, max) {
1386
+ if (!text)
1387
+ return text;
1388
+ const flat = text.replace(/\s+/g, " ").trim();
1389
+ return flat.length > max ? `${flat.slice(0, max)}\u2026` : flat;
1390
+ }
1391
+ function renderScan({ results, gaps, coverage, cancellation }) {
1392
+ const lines = [];
1393
+ for (const r of results) {
1394
+ lines.push(`[${r.status}] ${r.source}${r.reason ? ` \u2014 ${r.reason}` : ""} (${r.hits.length} hits)`);
1395
+ const shown = r.source === "local" ? r.hits : r.hits.slice(0, SEARCH_HITS_SHOWN);
1396
+ for (const h of shown) {
1397
+ const detail = clip(h.detail, r.source === "local" ? 120 : DETAIL_CHARS);
1398
+ const label = h.unvetted ? " [unvetted]" : "";
1399
+ lines.push(` - ${h.name}${label}${detail ? `: ${detail}` : ""}${h.url ? ` <${h.url}>` : ""}`);
1400
+ if (h.install)
1401
+ lines.push(` install hint${h.runsCode ? " (runs package code)" : ""}: ${h.install}`);
1402
+ }
1403
+ if (shown.length < r.hits.length)
1404
+ lines.push(` - \u2026 ${r.hits.length - shown.length} more in metadata.results`);
1405
+ }
1406
+ lines.push(`coverage: ${coverage.answered} answered, ${coverage.empty} empty, ${coverage.partial} partial, ${coverage.unavailable} unavailable, ${coverage.failed} failed`);
1407
+ if (cancellation) {
1408
+ lines.push(`cancelled: completed [${cancellation.completed.join(", ") || "none"}], not finished [${cancellation.timedOut.join(", ") || "none"}]`);
1409
+ }
1410
+ if (gaps.length) {
1411
+ lines.push("gaps:");
1412
+ for (const g of gaps)
1413
+ lines.push(` - ${g.source} (${g.kind}): ${g.reason}`);
1414
+ }
1415
+ lines.push("Install hints are suggestions for the user. find_tools_scan never installs or runs anything it found.");
1416
+ return lines.join(`
1417
+ `);
1418
+ }
1419
+
1420
+ // plugins/find-tools/pi-src/find-tools.ts
1421
+ async function readPiInventory(agentDirOverride) {
1422
+ const agentDir = agentDirOverride ?? getAgentDir();
1423
+ let packages = [];
1424
+ try {
1425
+ const settings = JSON.parse(await readFile(join(agentDir, "settings.json"), "utf8"));
1426
+ if (Array.isArray(settings.packages))
1427
+ packages = settings.packages;
1428
+ } catch {}
1429
+ const skills = [];
1430
+ const root = join(agentDir, "skills");
1431
+ const visit = async (dir) => {
1432
+ let entries;
1433
+ try {
1434
+ entries = await readdir(dir, { withFileTypes: true });
1435
+ } catch {
1436
+ return;
1437
+ }
1438
+ for (const entry of entries) {
1439
+ if (entry.isDirectory()) {
1440
+ await visit(join(dir, entry.name));
1441
+ continue;
1442
+ }
1443
+ if (entry.name !== "SKILL.md")
1444
+ continue;
1445
+ try {
1446
+ const text = await readFile(join(dir, entry.name), "utf8");
1447
+ const frontmatter = /^---\s*\n([\s\S]*?)\n---/u.exec(text)?.[1] ?? "";
1448
+ const name = /^name:\s*(.+)$/mu.exec(frontmatter)?.[1]?.trim();
1449
+ if (!name)
1450
+ continue;
1451
+ const description = /^description:\s*(.+)$/mu.exec(frontmatter)?.[1]?.trim();
1452
+ skills.push({ name, ...description ? { description } : {} });
1453
+ } catch {}
1454
+ }
1455
+ };
1456
+ await visit(root);
1457
+ let mcp = [];
1458
+ try {
1459
+ const config = JSON.parse(await readFile(join(agentDir, "mcp.json"), "utf8"));
1460
+ const rawServers = config && typeof config === "object" && !Array.isArray(config) ? config.mcpServers ?? config.servers ?? config.mcp : undefined;
1461
+ if (rawServers && typeof rawServers === "object" && !Array.isArray(rawServers))
1462
+ mcp = Object.values(rawServers);
1463
+ } catch {}
1464
+ return { packages, skills, mcp };
1465
+ }
1466
+ async function readOmpInventory(exec) {
1467
+ const result = await exec("omp", ["plugin", "list", "--json"]);
1468
+ if (result.code !== 0)
1469
+ throw new Error("omp plugin list failed");
1470
+ const data = JSON.parse(result.stdout);
1471
+ const marketplace = Array.isArray(data.marketplace) ? data.marketplace.flatMap((group) => {
1472
+ if (!group || typeof group !== "object")
1473
+ return [];
1474
+ const value = group;
1475
+ const entries = Array.isArray(value.entries) ? value.entries : [];
1476
+ const active = entries.find((entry) => entry && typeof entry === "object" && entry.enabled !== false);
1477
+ if (!active || typeof value.id !== "string")
1478
+ return [];
1479
+ const version = typeof active.version === "string" ? active.version : undefined;
1480
+ const scope = typeof active.scope === "string" ? active.scope : undefined;
1481
+ return [{ id: value.id, source: { type: scope ? `marketplace, ${scope} scope` : "marketplace", ...version ? { version } : {} } }];
1482
+ }) : [];
1483
+ const npm = Array.isArray(data.npm) ? data.npm.flatMap((item) => {
1484
+ if (!item || typeof item !== "object")
1485
+ return [];
1486
+ const plugin = item;
1487
+ if (plugin.enabled === false || typeof plugin.name !== "string")
1488
+ return [];
1489
+ return [{ id: plugin.name, source: { type: "npm", ...typeof plugin.version === "string" ? { version: plugin.version } : {} } }];
1490
+ }) : [];
1491
+ return { plugins: [...marketplace, ...npm] };
1492
+ }
1493
+ function isOmpHost(pi) {
1494
+ return pi.runtime !== undefined;
1495
+ }
1496
+ function ompInventory(exec) {
1497
+ return { plugins: async () => (await readOmpInventory(exec)).plugins };
1498
+ }
1499
+ var piInventory = (agentDir) => ({
1500
+ pi: () => readPiInventory(agentDir)
1501
+ });
1502
+ function find_tools_default(pi) {
1503
+ pi.registerTool({
1504
+ name: "find_tools_scan",
1505
+ label: "Find tools",
1506
+ description: "Read-only discovery of plugins, skills and MCP servers for a capability. Sources run in parallel, 10 s each: local (installed host plugins and skills; MCP as counts only), catalog (harness-plugins marketplace and configured skill catalogs), mcp_registry, npm, github (gh api), awesome_opencode (unvetted), smithery (needs SMITHERY_API_KEY), skills_cli (reported gap, never run). Each source reports ok, empty, partial, skipped or failed, with gaps and coverage. Install hints are shown, never run.",
1507
+ parameters: Type.Object({
1508
+ query: Type.String({ description: "The capability to find, in a few words" }),
1509
+ sources: Type.Optional(Type.Array(Type.String({ enum: [...SOURCES] }), {
1510
+ description: "Optional subset of sources; all by default"
1511
+ }))
1512
+ }, { additionalProperties: false }),
1513
+ async execute(_toolCallId, params, signal) {
1514
+ try {
1515
+ const ompHost = isOmpHost(pi);
1516
+ const inventory = ompHost ? ompInventory(async (command, args) => pi.exec(command, args, { signal, timeout: 1e4, maxBuffer: 1e6 })) : piInventory(getAgentDir());
1517
+ const report = await scanSources(params, {
1518
+ signal,
1519
+ local: inventory,
1520
+ harness: ompHost ? "omp" : "pi"
1521
+ });
1522
+ return { content: [{ type: "text", text: renderScan(report) }], details: report };
1523
+ } catch (error) {
1524
+ const message = error instanceof Error ? error.message : String(error);
1525
+ return {
1526
+ content: [{ type: "text", text: `find_tools_scan error: ${message}` }],
1527
+ details: { results: [], gaps: [], coverage: { answered: 0, empty: 0, partial: 0, unavailable: 0, failed: 0 }, error: message },
1528
+ isError: true
1529
+ };
1530
+ }
1531
+ }
1532
+ });
1533
+ pi.on("tool_call", async (event, ctx) => {
1534
+ if (event.toolName !== "bash" || typeof event.input.command !== "string")
1535
+ return;
1536
+ const kind = evaluationKind([event.input.command], { command: event.input.command });
1537
+ if (!kind)
1538
+ return;
1539
+ if (!ctx.hasUI)
1540
+ return { block: true, reason: `find-tools blocked guarded install without UI: ${MESSAGES[kind]}` };
1541
+ const confirmed = await ctx.ui.confirm("find-tools: guarded install", MESSAGES[kind]);
1542
+ if (!confirmed)
1543
+ return { block: true, reason: `find-tools blocked guarded install: ${MESSAGES[kind]}` };
1544
+ });
1545
+ }
1546
+ export {
1547
+ find_tools_default as default,
1548
+ isOmpHost,
1549
+ ompInventory,
1550
+ readOmpInventory,
1551
+ readPiInventory
1552
+ };