-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdiscovery.rs
More file actions
2291 lines (2036 loc) · 102 KB
/
Copy pathdiscovery.rs
File metadata and controls
2291 lines (2036 loc) · 102 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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::time::Duration;
use animus_plugin_protocol::PluginManifest;
use anyhow::{Context, Result};
use serde::Deserialize;
use tokio::io::AsyncReadExt;
use crate::host::PLUGIN_BASE_ENV_ALLOWLIST;
use crate::lockfile::PluginLockfile;
use crate::manifest_cache::ManifestCache;
use crate::scope::PluginScope;
/// Hard ceiling on how long a plugin gets to print its manifest before the
/// host kills the child and surfaces a discovery warning. Manifests are
/// static metadata — anything beyond a second is pathological.
const MANIFEST_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
/// Hard ceiling on bytes the host will buffer from a plugin's stdout during
/// the `--manifest` probe. A manifest is JSON in the kilobytes; anything
/// over 1 MiB is either a bug or an attack.
const MANIFEST_PROBE_MAX_STDOUT: usize = 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscoverySource {
ExplicitConfig,
ProjectLocal,
PluginPath,
SystemPath,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DiscoveredPlugin {
pub name: String,
pub path: PathBuf,
pub manifest: PluginManifest,
pub source: DiscoverySource,
}
/// A plugin that was located on disk but could not be loaded — typically because
/// its `--manifest` probe failed. Surfaced alongside successful discoveries so
/// callers can tell users *why* an installed plugin disappeared instead of
/// silently dropping it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveryWarning {
pub name: String,
pub path: PathBuf,
pub source: DiscoverySource,
pub reason: String,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct PluginConfigEntry {
pub binary: String,
#[serde(default)]
pub name: Option<String>,
/// Install-time `--name <NAME>` override recorded in `plugins.yaml`.
/// When set, discovery uses this as the canonical [`DiscoveredPlugin::name`]
/// instead of the manifest-declared name or the table key. Keeps the
/// lockfile entry, discovery, and the daemon's SubjectRouter alias map
/// agreed on the same logical name when the operator installed the
/// plugin with `--name`. v0.5.8+.
#[serde(default)]
pub name_override: Option<String>,
/// Persisted audit trail: `true` when the plugin was installed with the
/// `--skip-manifest-check` flag. Discovery emits a `warn!` on every probe
/// for plugins flagged this way so operators don't lose track of a plugin
/// whose manifest health is intentionally untrusted.
#[serde(default)]
pub skip_manifest_check_at_install: bool,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
struct PluginsConfig {
// BTreeMap so iteration order is deterministic: duplicate logical names
// across `plugins:` / `providers:` always resolve to the same winner
// (first in key order within `plugins:`, then `providers:`) instead of
// varying with HashMap iteration order run to run.
#[serde(default)]
plugins: BTreeMap<String, PluginConfigEntry>,
#[serde(default)]
providers: BTreeMap<String, PluginConfigEntry>,
}
#[derive(Debug, Clone, Default)]
pub struct PluginDiscovery {
project_root: Option<PathBuf>,
config_path: Option<PathBuf>,
include_system_path: bool,
scope: Option<PluginScope>,
}
/// A binary the discovery walker found and now needs a manifest for.
struct ProbeCandidate {
name: String,
path: PathBuf,
source: DiscoverySource,
}
enum ProbeOutcome {
Hit(PluginManifest),
Probed(Result<PluginManifest>),
}
fn cap_parallelism() -> usize {
let available = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
available.clamp(1, 8)
}
/// Resolve a sha256 hint for `path` so the manifest cache can be consulted
/// without spawning a `--manifest` probe.
///
/// We always hash the actual file on disk rather than trusting the
/// lockfile-recorded sha. Hashing a typical 5-20 MB plugin binary in
/// release mode costs a few milliseconds; trusting a possibly-stale
/// lockfile sha would let an out-of-band binary swap (e.g. `cp -p`, tar
/// restore) serve the wrong cached manifest under the old key. The
/// `lockfile` argument is retained so callers don't break and so future
/// versions can opportunistically skip the hash when the lockfile records
/// a path-bound integrity claim. Codex rounds 2 + 4 P2.
fn resolve_sha_for_binary(_lockfile: Option<&PluginLockfile>, _lock_name: &str, path: &Path) -> Option<String> {
ManifestCache::hash_binary(path).ok()
}
/// Return `true` when `path` looks plausibly executable so the cache-hit
/// fast path doesn't mask a `chmod -x` regression that the previous
/// per-call `--manifest` probe would have caught. On Unix we require at
/// least one execute bit. TODO(codex-p3): this can still hand back a
/// cached manifest when only "other" or "group" exec bits remain set but
/// the current process is the owner without exec — a narrower
/// `access(path, X_OK)` check would also surface that case. The probe
/// will still fail at spawn time today and the operator can clear the
/// cache to recover.
fn is_executable(path: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
match std::fs::metadata(path) {
Ok(meta) => meta.permissions().mode() & 0o111 != 0,
Err(_) => false,
}
}
#[cfg(not(unix))]
{
path.exists()
}
}
/// Pick the sha256 key to insert under after a live `--manifest` probe.
///
/// We hash before AND after the probe and only return a key when the two
/// digests agree. A binary swap concurrent with the probe (e.g. another
/// shell racing an `animus plugin install` or `animus plugin update`)
/// would otherwise let us insert the OLD manifest under the NEW binary's
/// sha key, poisoning future cache hits. When the pre/post hashes don't
/// match we skip caching this round — the next discovery run will see a
/// stable binary and repopulate the cache cleanly. Codex round 6 P2.
fn insert_key_for(path: &Path, pre_probe_sha: Option<&str>) -> Option<String> {
let post_probe_sha = ManifestCache::hash_binary(path).ok()?;
match pre_probe_sha {
Some(pre) if pre == post_probe_sha => Some(post_probe_sha),
Some(_) => None,
None => Some(post_probe_sha),
}
}
/// Drive a batch of probe candidates against the cache + (when warranted)
/// a parallel `--manifest` probe pool. Returns results in the same order
/// as `candidates`.
fn resolve_manifests(
candidates: &[ProbeCandidate],
cache: &ManifestCache,
lockfile: Option<&PluginLockfile>,
) -> Vec<ProbeOutcome> {
let mut outcomes: Vec<Option<ProbeOutcome>> = (0..candidates.len()).map(|_| None).collect();
let cache_enabled = cache.is_enabled();
// When the cache is disabled (kill switch), skip every hash — we
// cannot use the digest for lookup OR insert, so paying the I/O is
// pure waste. Codex round 8 P2.
let mut shas: Vec<Option<String>> = vec![None; candidates.len()];
if cache_enabled {
for (idx, cand) in candidates.iter().enumerate() {
shas[idx] = resolve_sha_for_binary(lockfile, &cand.name, &cand.path);
}
}
let mut probe_indices: Vec<usize> = Vec::new();
for (idx, cand) in candidates.iter().enumerate() {
if !cache_enabled || !is_executable(&cand.path) {
probe_indices.push(idx);
continue;
}
if let Some(sha) = shas[idx].as_deref() {
if let Some(manifest) = cache.lookup_for_path(sha, &cand.path) {
outcomes[idx] = Some(ProbeOutcome::Hit(manifest));
continue;
}
}
probe_indices.push(idx);
}
if probe_indices.is_empty() {
return outcomes.into_iter().map(|o| o.expect("every candidate must have an outcome")).collect();
}
let parallelism = cap_parallelism().min(probe_indices.len()).max(1);
if parallelism <= 1 || probe_indices.len() == 1 {
for idx in probe_indices {
// Reuse the lookup-side sha we already paid for as the
// pre-probe hash so the TOCTOU detection costs one hash, not
// two. When the cache was disabled or sha resolution failed
// earlier, fall back to hashing here. Codex round 8 P2.
let pre_sha = shas[idx].clone().or_else(|| {
if cache_enabled {
ManifestCache::hash_binary(&candidates[idx].path).ok()
} else {
None
}
});
let result = fetch_manifest(&candidates[idx].path);
if cache_enabled {
if let Ok(ref manifest) = result {
if let Some(sha) = insert_key_for(&candidates[idx].path, pre_sha.as_deref()) {
let _ = cache.insert(&sha, manifest);
}
}
}
outcomes[idx] = Some(ProbeOutcome::Probed(result));
}
} else {
let (tx, rx) = mpsc::channel::<(usize, Option<String>, Result<PluginManifest>)>();
let queue: std::sync::Arc<std::sync::Mutex<std::vec::IntoIter<usize>>> =
std::sync::Arc::new(std::sync::Mutex::new(probe_indices.clone().into_iter()));
let paths: std::sync::Arc<Vec<PathBuf>> =
std::sync::Arc::new(candidates.iter().map(|c| c.path.clone()).collect());
let pre_shas: std::sync::Arc<Vec<Option<String>>> = std::sync::Arc::new(shas.clone());
let mut handles = Vec::with_capacity(parallelism);
for _ in 0..parallelism {
let queue = std::sync::Arc::clone(&queue);
let paths = std::sync::Arc::clone(&paths);
let pre_shas = std::sync::Arc::clone(&pre_shas);
let tx = tx.clone();
handles.push(std::thread::spawn(move || loop {
let next_idx = {
let mut guard = queue.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
guard.next()
};
let Some(idx) = next_idx else {
break;
};
let pre_sha = pre_shas[idx].clone().or_else(|| {
if cache_enabled {
ManifestCache::hash_binary(&paths[idx]).ok()
} else {
None
}
});
let result = fetch_manifest(&paths[idx]);
if tx.send((idx, pre_sha, result)).is_err() {
break;
}
}));
}
drop(tx);
for (idx, pre_sha, result) in rx {
if cache_enabled {
if let Ok(ref manifest) = result {
if let Some(sha) = insert_key_for(&candidates[idx].path, pre_sha.as_deref()) {
let _ = cache.insert(&sha, manifest);
}
}
}
outcomes[idx] = Some(ProbeOutcome::Probed(result));
}
for handle in handles {
let _ = handle.join();
}
}
outcomes.into_iter().map(|o| o.expect("every candidate must have an outcome")).collect()
}
impl PluginDiscovery {
pub fn new() -> Self {
Self::default()
}
pub fn with_project_root(mut self, project_root: impl Into<PathBuf>) -> Self {
self.project_root = Some(project_root.into());
self
}
pub fn with_config_path(mut self, config_path: impl Into<PathBuf>) -> Self {
self.config_path = Some(config_path.into());
self
}
/// Opt in to scanning `$PATH` for `animus-plugin-*` / `animus-provider-*` binaries.
///
/// Defaults to `false`. When enabled, [`PluginDiscovery::discover`] will
/// execute every matching binary on `$PATH` with `--manifest` to fetch its
/// manifest. This runs arbitrary executables found on the user's `$PATH`
/// during discovery, so only enable when the caller explicitly trusts that
/// surface.
pub fn include_system_path(mut self, include_system_path: bool) -> Self {
self.include_system_path = include_system_path;
self
}
/// Apply a [`PluginScope`] filter to the discovered set. Plugins
/// outside the scope are removed from the returned `discovered`
/// list AFTER the manifest probe completes — warnings for failed
/// probes still surface so operators retain diagnostic info on
/// out-of-scope plugins whose manifest is broken.
///
/// When this builder method is not called, [`PluginScopeMode::All`]
/// semantics apply (the v0.5.8 behavior).
pub fn with_scope(mut self, scope: PluginScope) -> Self {
self.scope = Some(scope);
self
}
pub fn discover(&self) -> Result<Vec<DiscoveredPlugin>> {
Ok(self.discover_with_warnings()?.0)
}
/// Like [`PluginDiscovery::discover`], but also returns a list of
/// [`DiscoveryWarning`]s for plugins that were located but could not be
/// loaded (e.g. their `--manifest` probe failed). Warnings are also emitted
/// at `warn` level via `tracing`.
///
/// # Precedence
///
/// Discovery walks the following sources in order, and a plugin name (or
/// binary file name when scanning directories) is locked in by the first
/// source that yields it. Later sources can never override an earlier one
/// — duplicates from lower-precedence sources are silently skipped:
///
/// 1. Project-local tier: the install dir scan
/// (`<project_root>/.animus/plugins/`) followed by the project
/// registry (`<project_root>/.animus/plugins.yaml`) — the
/// highest-priority tier so a project-scoped install
/// (`animus plugin install --project`) shadows BOTH a hand-pinned
/// global registry entry and a global install of the same name.
/// 2. Explicit registry config (`~/.animus/plugins.yaml`, or the path
/// supplied to [`PluginDiscovery::with_config_path`]). Every global
/// `animus plugin install` records its entry here, so this tier is
/// where registry-recorded global installs resolve.
/// 3. Global install dir (`$ANIMUS_PLUGIN_DIR` when set, otherwise
/// `~/.animus/plugins/`) — the canonical destination for
/// `animus plugin install`. Scanned unconditionally so a binary
/// dropped into this directory by hand is still discovered even when
/// the registry yaml is missing or stale.
/// 4. `$ANIMUS_PLUGIN_PATH` (PATH-style, colon-separated additional
/// directories, appended after the global install dir).
/// 5. Operating-system `$PATH` (only when
/// [`PluginDiscovery::include_system_path`] is opted in).
///
/// Entries are deduplicated by name to keep the precedence chain
/// deterministic regardless of underlying file-system iteration order.
pub fn discover_with_warnings(&self) -> Result<(Vec<DiscoveredPlugin>, Vec<DiscoveryWarning>)> {
let mut discovered = Vec::new();
let mut warnings = Vec::new();
let mut seen = HashSet::new();
let cache = ManifestCache::from_default();
let lockfile = PluginLockfile::load_default(self.project_root.as_deref()).ok();
// Project-local installs scan FIRST: the explicit registry yaml is
// written by every global `animus plugin install`, so letting it win
// would silently invert the documented "project shadows global" rule
// for any name that was ever installed globally.
if let Some(project_root) = &self.project_root {
scan_dir(
&project_root.join(".animus/plugins"),
DiscoverySource::ProjectLocal,
&mut discovered,
&mut warnings,
&mut seen,
&cache,
lockfile.as_ref(),
);
// The dir scan only matches `animus-plugin-*` /
// `animus-provider-*` file names; the project registry tier
// resolves project-scoped installs of every other official
// plugin name (`animus-subject-*`, `animus-queue-*`, ...).
self.discover_project_registry(
project_root,
&mut discovered,
&mut warnings,
&mut seen,
&cache,
lockfile.as_ref(),
);
}
self.discover_configured(&mut discovered, &mut warnings, &mut seen, &cache, lockfile.as_ref())?;
// Scan the global plugin install dir unconditionally. This is the
// canonical destination for `animus plugin install` and the
// historical "user dropped a binary here by hand" location. When
// `$ANIMUS_PLUGIN_DIR` is set, [`plugin_install_dir`] returns that
// override; otherwise it resolves to `~/.animus/plugins/`
// (honoring `$ANIMUS_CONFIG_DIR` for hermetic tests).
scan_dir(
&plugin_install_dir(),
DiscoverySource::PluginPath,
&mut discovered,
&mut warnings,
&mut seen,
&cache,
lockfile.as_ref(),
);
if let Ok(plugin_path) = std::env::var("ANIMUS_PLUGIN_PATH") {
for raw_dir in plugin_path.split(':') {
if !raw_dir.trim().is_empty() {
scan_dir(
Path::new(raw_dir),
DiscoverySource::PluginPath,
&mut discovered,
&mut warnings,
&mut seen,
&cache,
lockfile.as_ref(),
);
}
}
}
if self.include_system_path {
if let Some(path_var) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&path_var) {
scan_dir(
&dir,
DiscoverySource::SystemPath,
&mut discovered,
&mut warnings,
&mut seen,
&cache,
lockfile.as_ref(),
);
}
}
}
// Auto-load the project scope when a `project_root` is set but
// no explicit `with_scope(...)` override has been supplied. This
// keeps the dozen-or-so direct PluginDiscovery callers in the
// workspace honoring `.animus/plugin-scope.yaml` without each
// having to wire the scope loader manually. Builders that want
// unrestricted discovery can still pass
// `PluginScope::unrestricted()` explicitly.
let scope_owned;
let effective_scope: Option<&PluginScope> = match &self.scope {
Some(s) => Some(s),
None => match &self.project_root {
Some(root) => {
scope_owned = PluginScope::load_for_project(root).unwrap_or_else(|err| {
tracing::warn!(
error = %err,
"failed to auto-load plugin scope; falling back to unrestricted discovery"
);
PluginScope::unrestricted()
});
Some(&scope_owned)
}
None => None,
},
};
if let Some(scope) = effective_scope {
// A flavor manifest that exists but failed to parse leaves the
// scope fail-closed (flavor-only with an EMPTY admit set).
// Surface that as a DiscoveryWarning so `animus plugin list`
// shows the real cause instead of every plugin silently
// disappearing behind a "plugin not installed" symptom. When an
// explicit `.animus/plugin-scope.yaml` overrides the mode, the
// broken manifest does not gate discovery — say so instead of
// claiming plugins were filtered out.
if let Some((manifest_path, reason)) = scope.flavor_manifest_error.as_ref() {
let consequence = if matches!(scope.mode, crate::scope::PluginScopeMode::FlavorOnly) {
"flavor-only scope admits NO plugins until it is fixed"
} else {
"discovery is unaffected because the project's plugin-scope file overrides the mode"
};
warnings.push(DiscoveryWarning {
name: manifest_path
.file_name()
.and_then(|value| value.to_str())
.unwrap_or("flavor-manifest")
.to_string(),
path: manifest_path.clone(),
source: DiscoverySource::ProjectLocal,
reason: format!("flavor manifest failed to load; {consequence}: {reason}"),
});
}
if !scope.admits_everything() {
let before = discovered.len();
discovered.retain(|plugin| scope.admits(plugin));
let removed = before.saturating_sub(discovered.len());
if removed > 0 && scope.effective_admit_set().is_empty() {
tracing::info!(
scope_mode = scope.mode.as_wire(),
removed,
"plugin scope filter removed every discovered plugin: the effective admit set is empty \
(broken or empty flavor manifest?)"
);
} else if removed > 0 {
tracing::debug!(
scope_mode = scope.mode.as_wire(),
removed,
kept = discovered.len(),
"plugin scope filter applied"
);
}
}
}
Ok((discovered, warnings))
}
fn discover_configured(
&self,
discovered: &mut Vec<DiscoveredPlugin>,
warnings: &mut Vec<DiscoveryWarning>,
seen: &mut HashSet<String>,
cache: &ManifestCache,
lockfile: Option<&PluginLockfile>,
) -> Result<()> {
let config_path = self.config_path.clone().unwrap_or_else(default_config_path);
if !config_path.exists() {
return Ok(());
}
let config = load_plugins_config(&config_path)
.with_context(|| format!("failed to read plugin config at {}", config_path.display()))?;
self.discover_from_config(config, DiscoverySource::ExplicitConfig, discovered, warnings, seen, cache, lockfile);
Ok(())
}
/// Project-registry tier: `<project_root>/.animus/plugins.yaml`,
/// written by `animus plugin install --project`. Needed because the
/// project dir scan only picks up `animus-plugin-*` /
/// `animus-provider-*` file names — official plugins like
/// `animus-subject-default` or `animus-queue-default` are only
/// discoverable through their registry entry, exactly like their
/// global counterparts resolve through `~/.animus/plugins.yaml`.
/// A corrupt project registry degrades to a warning (the daemon must
/// not lose every plugin because one project file is broken).
fn discover_project_registry(
&self,
project_root: &Path,
discovered: &mut Vec<DiscoveredPlugin>,
warnings: &mut Vec<DiscoveryWarning>,
seen: &mut HashSet<String>,
cache: &ManifestCache,
lockfile: Option<&PluginLockfile>,
) {
let config_path = project_plugins_registry_path(project_root);
if !config_path.exists() {
return;
}
let config = match load_plugins_config(&config_path) {
Ok(config) => config,
Err(err) => {
warnings.push(DiscoveryWarning {
name: config_path
.file_name()
.and_then(|value| value.to_str())
.unwrap_or("plugins.yaml")
.to_string(),
path: config_path.clone(),
source: DiscoverySource::ProjectLocal,
reason: format!("failed to read project plugin registry: {err:#}"),
});
return;
}
};
self.discover_from_config(config, DiscoverySource::ProjectLocal, discovered, warnings, seen, cache, lockfile);
}
#[allow(clippy::too_many_arguments)]
fn discover_from_config(
&self,
config: PluginsConfig,
source: DiscoverySource,
discovered: &mut Vec<DiscoveredPlugin>,
warnings: &mut Vec<DiscoveryWarning>,
seen: &mut HashSet<String>,
cache: &ManifestCache,
lockfile: Option<&PluginLockfile>,
) {
let mut candidates: Vec<ProbeCandidate> = Vec::new();
for (logical_name, entry) in config.plugins.iter().chain(config.providers.iter()) {
// v0.5.8+: `name_override` records the install-time `--name <NAME>`
// override so discovery, the lockfile entry, and the daemon
// SubjectRouter all agree on the same logical plugin name. Falls
// back to the manifest-name field, then the table key, for
// pre-v0.5.8 entries that never recorded the override.
let effective_name =
entry.name_override.clone().or_else(|| entry.name.clone()).unwrap_or_else(|| logical_name.clone());
if seen.contains(&effective_name) {
continue;
}
let Some(path) = resolve_configured_binary(&entry.binary) else {
// Reserve the name even when the configured binary is gone so
// a lower-precedence directory scan can't silently shadow a
// stale explicit config entry. The warning still surfaces so
// operators fix the entry instead of being routed to an
// unintended copy.
seen.insert(effective_name.clone());
let reason = format!("configured binary not found: {}", entry.binary);
tracing::warn!(
plugin = %logical_name,
binary = %entry.binary,
source = ?source,
"plugin manifest probe skipped: {reason}"
);
warnings.push(DiscoveryWarning {
name: effective_name.clone(),
path: PathBuf::from(&entry.binary),
source,
reason,
});
continue;
};
let name = effective_name;
if entry.skip_manifest_check_at_install {
tracing::warn!(
plugin = %name,
path = %path.display(),
"plugin {name} installed with --skip-manifest-check; manifest probe failures will be tolerated."
);
}
// Reserve the name immediately so a duplicate row in the same
// config (e.g. `plugins:` and `providers:` keying the same
// effective name) doesn't enqueue a second probe candidate for
// the same logical plugin. Codex round 1 P2.
seen.insert(name.clone());
candidates.push(ProbeCandidate { name, path, source });
}
let outcomes = resolve_manifests(&candidates, cache, lockfile);
for (cand, outcome) in candidates.into_iter().zip(outcomes) {
let ProbeCandidate { name, path, source } = cand;
match outcome {
ProbeOutcome::Hit(manifest) | ProbeOutcome::Probed(Ok(manifest)) => {
seen.insert(name.clone());
discovered.push(DiscoveredPlugin { name, path, manifest, source });
}
ProbeOutcome::Probed(Err(error)) => {
// Reserve the name even on probe failure so a lower-precedence
// directory scan can't silently shadow a broken explicit config
// entry. The warning still surfaces so operators can fix the
// broken plugin instead of being routed to an unintended copy.
seen.insert(name.clone());
let reason = format!("{error:#}");
tracing::warn!(
plugin = %name,
path = %path.display(),
source = ?source,
"plugin manifest probe failed: {reason}"
);
warnings.push(DiscoveryWarning { name, path, source, reason });
}
}
}
}
}
pub fn discover_plugins(project_root: impl Into<PathBuf>) -> Result<Vec<DiscoveredPlugin>> {
let root: PathBuf = project_root.into();
let scope = PluginScope::load_for_project(&root).unwrap_or_else(|err| {
tracing::warn!(
error = %err,
"failed to load plugin scope; falling back to unrestricted discovery"
);
PluginScope::unrestricted()
});
PluginDiscovery::new().with_project_root(root).with_scope(scope).discover()
}
/// Discover all installed plugins whose manifest `plugin_kind` equals
/// `kind` (case-sensitive — match the wire constants exactly:
/// `"workflow_runner"`, `"subject_backend"`, `"provider"`, `"transport"`,
/// etc.). Skips plugins whose `--manifest` probe failed (those surface as
/// [`DiscoveryWarning`]s on a full [`discover_plugins`] call).
///
/// Errors only when discovery itself fails (config read, registry parse).
/// An empty `Vec` means "no plugins of that kind installed".
pub fn discover_by_kind(project_root: impl Into<PathBuf>, kind: &str) -> Result<Vec<DiscoveredPlugin>> {
let plugins = discover_plugins(project_root)?;
Ok(plugins.into_iter().filter(|p| p.manifest.plugin_kind == kind).collect())
}
/// Probe a plugin binary's `--manifest` output.
///
/// This is the security-sensitive entry point for plugin discovery: it
/// executes an arbitrary binary on the user's machine. The probe is
/// sandboxed to defend against three classes of misbehavior:
///
/// 1. **Hangs.** Wrapped in a [`MANIFEST_PROBE_TIMEOUT`] (5s) — if the
/// plugin blocks on stdin or sleeps, the child is killed via
/// `kill_on_drop(true)` and the caller sees a clear timeout error.
/// 2. **Memory bombs.** Stdout is capped at
/// [`MANIFEST_PROBE_MAX_STDOUT`] (1 MiB) — manifests are small JSON,
/// anything bigger is rejected before the host allocates more memory.
/// 3. **Env leakage.** The child's environment is scrubbed via
/// `env_clear()` and only [`PLUGIN_BASE_ENV_ALLOWLIST`] is forwarded
/// — the manifest probe never needs API credentials, and any plugin
/// that asks for them during `--manifest` has a bug.
///
/// The function is sync (its callers are sync); internally it spawns a
/// dedicated single-threaded tokio runtime on a worker thread so it
/// remains safe to call from inside an outer tokio runtime as well as
/// from plain sync code.
pub fn fetch_manifest(path: &Path) -> Result<PluginManifest> {
let owned_path = path.to_path_buf();
let join_result = std::thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time()
.build()
.context("failed to build manifest-probe runtime")?;
runtime.block_on(fetch_manifest_inner(&owned_path))
})
.join();
match join_result {
Ok(result) => result,
Err(_) => anyhow::bail!("manifest probe worker thread panicked for {}", path.display()),
}
}
async fn fetch_manifest_inner(path: &Path) -> Result<PluginManifest> {
let mut command = tokio::process::Command::new(path);
command
.arg("--manifest")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
// Scrub the daemon's environment before invoking the plugin. The same
// allowlist used by full plugin spawns (host.rs) — manifest probes
// never legitimately need plugin-declared env_required, since they
// only print static metadata. A plugin that needs API credentials to
// emit its manifest is a plugin bug, not a host concern.
let allow: BTreeSet<&str> = PLUGIN_BASE_ENV_ALLOWLIST.iter().copied().collect();
command.env_clear();
for var in &allow {
if let Some(value) = std::env::var_os(var) {
command.env(var, value);
}
}
let mut child = command.spawn().with_context(|| format!("failed to run {}", path.display()))?;
let mut stdout = child.stdout.take().ok_or_else(|| anyhow::anyhow!("failed to capture plugin stdout"))?;
let mut stderr = child.stderr.take().ok_or_else(|| anyhow::anyhow!("failed to capture plugin stderr"))?;
let probe = async {
let mut stdout_buf: Vec<u8> = Vec::with_capacity(8 * 1024);
let mut stderr_buf: Vec<u8> = Vec::with_capacity(4 * 1024);
let mut stdout_done = false;
let mut stderr_done = false;
let mut stdout_chunk = [0u8; 8 * 1024];
let mut stderr_chunk = [0u8; 4 * 1024];
// Interleave stdout/stderr reads so a plugin can't deadlock us by
// filling one pipe while we wait on the other. Bail the moment
// stdout exceeds the cap so the child can be killed before it
// produces more data.
while !stdout_done || !stderr_done {
tokio::select! {
read = stdout.read(&mut stdout_chunk), if !stdout_done => {
let n = read.with_context(|| format!("failed to read stdout from {}", path.display()))?;
if n == 0 {
stdout_done = true;
} else if stdout_buf.len() + n > MANIFEST_PROBE_MAX_STDOUT {
anyhow::bail!(
"plugin produced >1MiB on stdout for --manifest probe at {}; refusing to load",
path.display()
);
} else {
stdout_buf.extend_from_slice(&stdout_chunk[..n]);
}
}
read = stderr.read(&mut stderr_chunk), if !stderr_done => {
let n = read.with_context(|| format!("failed to read stderr from {}", path.display()))?;
if n == 0 {
stderr_done = true;
} else if stderr_buf.len() + n > MANIFEST_PROBE_MAX_STDOUT {
// Stderr cap mirrors stdout's — a plugin spewing
// GBs of stderr would wedge discovery too.
anyhow::bail!(
"plugin produced >1MiB on stderr for --manifest probe at {}; refusing to load",
path.display()
);
} else {
stderr_buf.extend_from_slice(&stderr_chunk[..n]);
}
}
}
}
let status = child.wait().await.with_context(|| format!("failed to wait on {}", path.display()))?;
if !status.success() {
let stderr_text = String::from_utf8_lossy(&stderr_buf);
let trimmed = stderr_text.trim();
if trimmed.is_empty() {
anyhow::bail!("plugin manifest command failed for {} (exit={:?})", path.display(), status.code());
}
anyhow::bail!(
"plugin manifest command failed for {} (exit={:?}): {}",
path.display(),
status.code(),
trimmed
);
}
serde_json::from_slice::<PluginManifest>(&stdout_buf)
.with_context(|| format!("plugin {} returned malformed --manifest JSON", path.display()))
};
// Drive the probe under an overall deadline. When the timeout fires
// (or when probe returns Err early), `child` is dropped and
// `kill_on_drop` reaps the still-running process so we don't leak it.
match tokio::time::timeout(MANIFEST_PROBE_TIMEOUT, probe).await {
Ok(result) => result,
Err(_) => {
// Explicitly kill before drop so the reap is synchronous —
// `kill_on_drop` schedules the reap async, and we want the
// child gone before this function returns.
let _ = child.start_kill();
anyhow::bail!(
"plugin manifest probe timed out after {}s for {}",
MANIFEST_PROBE_TIMEOUT.as_secs(),
path.display()
)
}
}
}
fn scan_dir(
dir: &Path,
source: DiscoverySource,
discovered: &mut Vec<DiscoveredPlugin>,
warnings: &mut Vec<DiscoveryWarning>,
seen: &mut HashSet<String>,
cache: &ManifestCache,
lockfile: Option<&PluginLockfile>,
) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
let mut candidates: Vec<ProbeCandidate> = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
let Some(file_name) = path.file_name().and_then(|value| value.to_str()) else {
continue;
};
if !is_scanned_plugin_name(file_name) || seen.contains(file_name) {
continue;
}
// Reserve the name immediately so a duplicate file_name within the
// same scan dir cannot enqueue a second probe candidate. Codex
// round 1 P2.
seen.insert(file_name.to_string());
candidates.push(ProbeCandidate { name: file_name.to_string(), path, source });
}
let outcomes = resolve_manifests(&candidates, cache, lockfile);
for (cand, outcome) in candidates.into_iter().zip(outcomes) {
let ProbeCandidate { name, path, source } = cand;
match outcome {
ProbeOutcome::Hit(manifest) | ProbeOutcome::Probed(Ok(manifest)) => {
seen.insert(name.clone());
discovered.push(DiscoveredPlugin { name, path, manifest, source });
}
ProbeOutcome::Probed(Err(error)) => {
// Reserve the name even on probe failure so a lower-precedence
// source (e.g. global install dir) can't silently shadow a
// broken higher-precedence override (e.g. project-local).
// The warning still surfaces so operators can fix the
// broken plugin instead of being routed to the wrong copy.
seen.insert(name.clone());
let reason = format!("{error:#}");
tracing::warn!(
plugin = %name,
path = %path.display(),
source = ?source,
"plugin manifest probe failed: {reason}"
);
warnings.push(DiscoveryWarning { name, path, source, reason });
}
}
}
}
/// Whether a binary file name is picked up by the directory-scan discovery
/// tiers (project-local dir, global install dir, `$ANIMUS_PLUGIN_PATH`,
/// `$PATH`). Names outside these prefixes are only discoverable via a
/// registry entry (`~/.animus/plugins.yaml` for global installs,
/// `<project>/.animus/plugins.yaml` for project-scoped ones).
pub fn is_scanned_plugin_name(name: &str) -> bool {
name.starts_with("animus-plugin-") || name.starts_with("animus-provider-")
}
fn load_plugins_config(path: &Path) -> Result<PluginsConfig> {
let content = std::fs::read_to_string(path)?;
Ok(serde_yaml::from_str(&content)?)
}
/// Canonical home for Animus state. Mirrors `protocol::Config::global_config_dir()`
/// but duplicated here to avoid a crate-level dep on `protocol`. Honors
/// `ANIMUS_CONFIG_DIR` for tests and overrides.
fn animus_home() -> PathBuf {
if let Ok(value) = std::env::var("ANIMUS_CONFIG_DIR") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return PathBuf::from(trimmed);
}
}
std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".animus")).unwrap_or_else(|| PathBuf::from(".animus"))
}
/// Returns the canonical plugin install directory.
///
/// Resolution order:
/// 1. `$ANIMUS_PLUGIN_DIR` (when set and non-empty)
/// 2. `<animus_home>/plugins`
pub fn plugin_install_dir() -> PathBuf {
if let Ok(value) = std::env::var("ANIMUS_PLUGIN_DIR") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return PathBuf::from(trimmed);
}
}
animus_home().join("plugins")
}
/// Returns the project-local plugin install directory
/// (`<project_root>/.animus/plugins/`). Discovery scans this directory at a
/// HIGHER precedence than the global install dir, so a project-local install
/// shadows a global install of the same name.
pub fn project_plugin_install_dir(project_root: &Path) -> PathBuf {
project_root.join(".animus").join("plugins")
}
/// Returns the project-local plugin registry yaml path
/// (`<project_root>/.animus/plugins.yaml`). Mirrors the global
/// [`plugins_registry_path`] shape; written by `animus plugin install
/// --project`.
pub fn project_plugins_registry_path(project_root: &Path) -> PathBuf {
project_root.join(".animus").join("plugins.yaml")
}
/// Returns the canonical plugin registry yaml path.
///
/// The new location is `<animus_home>/plugins.yaml`. The legacy location
/// (`~/.config/animus/plugins.yaml`) is consulted automatically by
/// [`default_config_path`] when the new file does not yet exist, and is
/// migrated to the new path on the next write performed by the installer.
pub fn plugins_registry_path() -> PathBuf {
animus_home().join("plugins.yaml")
}
/// Legacy registry location used before consolidation under `~/.animus/`.
/// Kept for one-shot migration on first read.
pub fn legacy_plugins_registry_path() -> PathBuf {
std::env::var_os("HOME")
.map(|home| PathBuf::from(home).join(".config/animus/plugins.yaml"))
.unwrap_or_else(|| PathBuf::from(".config/animus/plugins.yaml"))
}
/// Read the registered `skip_manifest_check_at_install` flag for the named
/// plugin (or its provider counterpart) from the canonical registry.
///
/// Returns `false` when the registry is missing, the plugin is not listed, or
/// the flag is unset. Errors during registry read are swallowed and treated as
/// "flag absent" — the audit field is informational and must never block
/// discovery or `plugin info`.
pub fn registered_skip_manifest_check_at_install(plugin_name: &str) -> bool {
registered_skip_manifest_check_at_install_scoped(None, plugin_name)
}
/// Like [`registered_skip_manifest_check_at_install`], but consults the
/// project-local registry (`<project_root>/.animus/plugins.yaml`) FIRST so
/// the audit flag of an `animus plugin install --project
/// --skip-manifest-check` install is reported correctly. Falls back to the
/// global registry when the project registry is absent or has no matching
/// entry.
pub fn registered_skip_manifest_check_at_install_scoped(project_root: Option<&Path>, plugin_name: &str) -> bool {