-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.zig
More file actions
3190 lines (2898 loc) · 130 KB
/
Copy pathmanager.zig
File metadata and controls
3190 lines (2898 loc) · 130 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
//! Plugin orchestration.
//!
//! Loads plugin directories under `~/.stem/plugins/`, dispatches to
//! the appropriate runtime (wasm or exec), enforces manifest
//! permissions, and populates the command palette eagerly from each
//! manifest before the plugin starts.
//!
//! Two runtimes:
//!
//! * **wasm** — `bundled/plugins/<name>/{plugin.json, <name>.wasm}`.
//! A WebAssembly module executed by the wick interpreter
//! (github.com/ooyeku/wick) and bound to a small set of
//! `env.stem_*` host imports. See `wasm/loader.zig`.
//! * **exec** — `~/.stem/plugins/<name>/{plugin.json, <entry>}`.
//! A child process speaking JSON-RPC 2.0 over stdio with LSP
//! framing. See `process_loader.zig`. Nothing bundled uses this
//! path today; it's available for third-party plugins.
const std = @import("std");
const log = std.log.scoped(.PluginManager);
const protocol = @import("../kernel/protocol.zig");
const CommandRegistry = @import("../kernel/command.zig").CommandRegistry;
const MessageBus = @import("../kernel/message_bus.zig").MessageBus;
const manifest_mod = @import("manifest.zig");
const process_loader = @import("process_loader.zig");
const ProcessPlugin = process_loader.ProcessPlugin;
const wasm_loader = @import("wasm/loader.zig");
const WasmPlugin = wasm_loader.WasmPlugin;
const jsonrpc = @import("jsonrpc.zig");
const logger_service = @import("../services/logger.zig");
const telemetry = @import("../services/telemetry.zig");
const event_topics = @import("../services/event_topics.zig");
const vigil_api = @import("../services/vigil_adapters.zig");
const vigil_supervision = @import("../services/vigil_supervision.zig");
/// Wire-protocol version handed to exec plugins on `plugin/initialize`.
/// Bumped only when the JSON-RPC envelope semantics change.
const PROC_ABI_VERSION: u32 = 1;
pub const PluginManager = struct {
allocator: std.mem.Allocator,
io: std.Io,
environ_block: std.process.Environ.Block,
/// Guards every mutable field on the manager. Process plugin reader
/// threads call into the manager off the main loop (notifications,
/// request forwarding, exit reporting), so map mutations and
/// permission lookups must be serialised. Core's main thread takes
/// the same lock when it mutates plugin state on tick / load /
/// unload, which gives both sides a single ordering.
state_mu: vigil_api.Mutex = .{},
/// Plugins whose reader thread observed EOF/error. Populated from
/// the reader thread (off-loop); drained by core on tick via
/// `drainPendingExits`. The strings are owned copies — freed after
/// the unload completes. This is what keeps `on_exit` from
/// destroying the very plugin still unwinding its callback stack.
pending_exits: std.ArrayListUnmanaged([]u8) = .empty,
/// Per-plugin restart policy lifted from each manifest at load
/// time. The manifest's arena is freed right after parsing, so
/// we copy. Looked up by `drainPendingExits` to decide whether
/// a crashed plugin should respawn.
restart_policies: std.StringHashMapUnmanaged(manifest_mod.Restart) = .empty,
/// Backoff state for crashed-and-being-restarted plugins. Wiped
/// for a plugin once it survives long enough to be considered
/// healthy (currently: when it's still alive at the next drain
/// after restart). Keys are owned dupes of plugin names.
restart_state: std.StringHashMapUnmanaged(RestartState) = .empty,
/// Plugins waiting to be respawned by `drainPendingRestarts`.
/// Pending list rather than spawning inline so the restart runs
/// on the main loop, after the deinit of the previous instance
/// has fully unwound.
pending_restarts: std.ArrayListUnmanaged(PendingRestart) = .empty,
/// Out-of-process plugins.
process_plugins: std.StringHashMapUnmanaged(*ProcessPlugin) = .empty,
/// WebAssembly plugins.
wasm_plugins: std.StringHashMapUnmanaged(*WasmPlugin) = .empty,
/// `correlation_id → plugin name` for in-flight process plugin
/// requests. Lets `replyToProcessPlugin` route a reply back to the
/// exact plugin that asked, rather than broadcasting to every
/// running exec plugin. Populated when a process plugin's reader
/// thread forwards a request to core's inbox; drained when the
/// reply (or error) is dispatched back.
pending_requests: std.AutoHashMapUnmanaged(u64, []u8) = .empty,
core_inbox: ?*vigil_api.Inbox = null,
event_broker: ?*vigil_api.PubSubBroker = null,
lifecycle_supervisor: ?*vigil_supervision.ComponentSupervisor = null,
ui_bus: *MessageBus,
command_registry: *CommandRegistry,
/// Owned `PluginCommandContext`s registered with `command_registry`.
/// Freed in `deinit`.
allocated_contexts: std.ArrayListUnmanaged(*PluginCommandContext) = .empty,
/// Per-plugin permission grants, lifted from the manifest at load
/// time. Host accessors consult this table before granting
/// capability requests (event subscription, spawn, filesystem).
plugin_permissions: std.StringHashMapUnmanaged(StoredPermissions) = .empty,
/// Capability denials keyed by `<plugin>:<capability>:<target>`.
/// This is the plugin audit trail surfaced in the dashboard.
capability_denials: std.StringHashMapUnmanaged(StoredCapabilityDenial) = .empty,
/// Map of editor event → list of plugins subscribed to it.
/// Populated by `plugin/subscribeEvent` (exec) and
/// `stem_subscribe_event` (wasm); drained on plugin unload.
event_subscribers: std.AutoHashMapUnmanaged(protocol.PluginEvent, std.ArrayListUnmanaged(EventSub)) = .empty,
/// Flow control for high-frequency event fanout. Delivery is synchronous
/// on the calling (core) thread, so a held arrow key with a slow plugin
/// subscribed to cursor events would otherwise stall the editor. Vigil's
/// lock-free GCRA limiter caps deliveries; only drop-safe events
/// (`cursor_moved` — positional, latest-wins) are ever throttled.
cursor_event_limiter: vigil_api.raw.RateLimiter,
events_rate_limited: std.atomic.Value(u64) = .init(0),
/// Plugin status-bar widgets, keyed by `"<plugin_id>:<item_id>"`.
status_items: std.StringHashMapUnmanaged(StoredStatusItem) = .empty,
/// Plugin side panels, keyed by `"<plugin_id>:<panel_id>"`.
panels: std.StringHashMapUnmanaged(StoredPanel) = .empty,
/// Manifest-declared keybinding sequences. Key is the
/// space-separated key sequence (e.g. `"Space g s"`); value is the
/// command id to execute. The core input handler consults this
/// after its own leader chord chain when `leader_pending` is set.
plugin_keybindings: std.StringHashMapUnmanaged(PluginKeybinding) = .empty,
/// Editor-side hooks set by Core after construction. Lets the
/// plugin manager pull data that lives on Core (active buffer
/// content, file path) without taking a circular import on the
/// `Core` type. Wasm `stem_get_buffer_*` host imports route
/// through these.
host_hooks: HostHooks = .{},
/// Monotonic counter for assigning new widget ids on each
/// status-item / panel registration. Stable across the lifetime
/// of the plugin manager.
next_widget_id: u32 = 1,
pub const RestartState = struct {
attempts: u8 = 0,
last_attempt_ms: i64 = 0,
};
pub const PendingRestart = struct {
/// Owned dupe of the plugin name.
name: []u8,
due_ms: i64,
};
pub const HealthSnapshot = struct {
loaded_plugins: usize = 0,
process_plugins: usize = 0,
wasm_plugins: usize = 0,
pending_exits: usize = 0,
pending_restarts: usize = 0,
pending_requests: usize = 0,
restart_policies: usize = 0,
event_subscribers: usize = 0,
status_items: usize = 0,
panels: usize = 0,
keybindings: usize = 0,
/// Cursor events dropped by the fanout rate limiter.
events_rate_limited: u64 = 0,
vigil_broker_attached: bool = false,
vigil_supervisor_attached: bool = false,
lifecycle: vigil_supervision.Snapshot = .{},
};
const PluginKeybinding = struct {
command_id: []u8,
plugin_id: []u8,
fn deinit(self: PluginKeybinding, allocator: std.mem.Allocator) void {
allocator.free(self.command_id);
allocator.free(self.plugin_id);
}
};
/// Backoff schedule: 1 s, 5 s, 30 s, then give up. Index is the
/// attempt count (0 = first restart). Returning null means we've
/// exhausted retries; the plugin stays down until the user
/// reloads explicitly.
fn restartDelayMs(attempts: u8) ?i64 {
return switch (attempts) {
0 => 1_000,
1 => 5_000,
2 => 30_000,
else => null,
};
}
pub fn init(
allocator: std.mem.Allocator,
io: std.Io,
environ_block: std.process.Environ.Block,
ui_bus: *MessageBus,
command_registry: *CommandRegistry,
) PluginManager {
return .{
.allocator = allocator,
.io = io,
.environ_block = environ_block,
.ui_bus = ui_bus,
.command_registry = command_registry,
// Runtime init: the GCRA limiter samples the monotonic clock.
.cursor_event_limiter = vigil_api.raw.RateLimiter.initBurst(30, 60),
};
}
pub fn setVigilServices(
self: *PluginManager,
event_broker: *vigil_api.PubSubBroker,
lifecycle_supervisor: *vigil_supervision.ComponentSupervisor,
) void {
self.event_broker = event_broker;
self.lifecycle_supervisor = lifecycle_supervisor;
}
pub fn healthSnapshot(self: *PluginManager) HealthSnapshot {
self.state_mu.lock();
var snapshot = HealthSnapshot{
.process_plugins = self.process_plugins.count(),
.wasm_plugins = self.wasm_plugins.count(),
.pending_exits = self.pending_exits.items.len,
.pending_restarts = self.pending_restarts.items.len,
.pending_requests = self.pending_requests.count(),
.restart_policies = self.restart_policies.count(),
.status_items = self.status_items.count(),
.panels = self.panels.count(),
.keybindings = self.plugin_keybindings.count(),
.vigil_broker_attached = self.event_broker != null,
.vigil_supervisor_attached = self.lifecycle_supervisor != null,
.events_rate_limited = self.events_rate_limited.load(.monotonic),
};
snapshot.loaded_plugins = snapshot.process_plugins + snapshot.wasm_plugins;
var ev_it = self.event_subscribers.valueIterator();
while (ev_it.next()) |subs| {
snapshot.event_subscribers += subs.items.len;
}
const supervisor = self.lifecycle_supervisor;
self.state_mu.unlock();
if (supervisor) |s| {
snapshot.lifecycle = s.snapshot();
}
return snapshot;
}
pub fn deinit(self: *PluginManager) void {
// Process plugins — shut down children, then free per-plugin state.
var p_it = self.process_plugins.valueIterator();
while (p_it.next()) |pp_ptr| {
const pp = pp_ptr.*;
self.cleanupPluginResources(pp.name);
pp.deinit();
self.allocator.destroy(pp);
}
self.process_plugins.deinit(self.allocator);
// Wasm plugins — tear down instances + decoded modules.
var w_it = self.wasm_plugins.valueIterator();
while (w_it.next()) |wp_ptr| {
const wp = wp_ptr.*;
self.cleanupPluginResources(wp.plugin_id);
wp.deinit();
self.allocator.destroy(wp);
}
self.wasm_plugins.deinit(self.allocator);
self.allocated_contexts.deinit(self.allocator);
// Event subscriptions: each list owns its plugin_id duplicates.
var ev_it = self.event_subscribers.valueIterator();
while (ev_it.next()) |list| {
for (list.items) |s| self.allocator.free(s.plugin_id);
list.deinit(self.allocator);
}
self.event_subscribers.deinit(self.allocator);
// Plugin keybindings.
var kb_it = self.plugin_keybindings.iterator();
while (kb_it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
entry.value_ptr.*.deinit(self.allocator);
}
self.plugin_keybindings.deinit(self.allocator);
// Status items / panels.
var si_it = self.status_items.iterator();
while (si_it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
entry.value_ptr.deinit(self.allocator);
}
self.status_items.deinit(self.allocator);
var pn_it = self.panels.iterator();
while (pn_it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
entry.value_ptr.deinit(self.allocator);
}
self.panels.deinit(self.allocator);
var perm_it = self.plugin_permissions.iterator();
while (perm_it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
entry.value_ptr.deinit(self.allocator);
}
self.plugin_permissions.deinit(self.allocator);
var denial_it = self.capability_denials.iterator();
while (denial_it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
entry.value_ptr.deinit(self.allocator);
}
self.capability_denials.deinit(self.allocator);
for (self.pending_exits.items) |name| self.allocator.free(name);
self.pending_exits.deinit(self.allocator);
var pr_it = self.pending_requests.iterator();
while (pr_it.next()) |entry| self.allocator.free(entry.value_ptr.*);
self.pending_requests.deinit(self.allocator);
var pol_it = self.restart_policies.iterator();
while (pol_it.next()) |entry| self.allocator.free(entry.key_ptr.*);
self.restart_policies.deinit(self.allocator);
var rs_it = self.restart_state.iterator();
while (rs_it.next()) |entry| self.allocator.free(entry.key_ptr.*);
self.restart_state.deinit(self.allocator);
for (self.pending_restarts.items) |pr| self.allocator.free(pr.name);
self.pending_restarts.deinit(self.allocator);
}
pub fn loadUserPlugins(self: *PluginManager) !void {
// Walk every configured plugin root in priority order. The
// first occurrence of a plugin name wins, so `~/.stem/plugins`
// (per-user) shadows the system path, which shadows anything
// injected via `STEM_PLUGIN_PATH`. That keeps `stem plugin
// install <path>` (which lands in `~/.stem/plugins`) doing
// what its UX implies: overriding the bundled copy.
var seen: std.StringHashMapUnmanaged(void) = .empty;
defer {
var it = seen.keyIterator();
while (it.next()) |k| self.allocator.free(k.*);
seen.deinit(self.allocator);
}
var roots = try self.collectPluginRoots();
defer {
for (roots.items) |p| self.allocator.free(p);
roots.deinit(self.allocator);
}
for (roots.items) |root| {
try self.loadFromRoot(root, &seen);
}
}
/// Ordered list of directories to scan for plugins. Each entry is
/// an owned absolute path; caller frees.
fn collectPluginRoots(self: *PluginManager) !std.ArrayListUnmanaged([]u8) {
// Cross-platform env access (env.getPosix is POSIX-only in
// Zig 0.16; we route through platform.getEnv instead).
const platform = @import("../kernel/platform.zig");
var out: std.ArrayListUnmanaged([]u8) = .empty;
errdefer {
for (out.items) |p| self.allocator.free(p);
out.deinit(self.allocator);
}
// 1. Per-user dir under HOME (or USERPROFILE on Windows).
const home_owned: ?[]u8 = (try platform.getEnv(self.allocator, self.environ_block, "HOME")) orelse
(try platform.getEnv(self.allocator, self.environ_block, "USERPROFILE"));
defer if (home_owned) |h| self.allocator.free(h);
if (home_owned) |home| {
const user_dir = try std.fs.path.join(self.allocator, &.{ home, ".stem", "plugins" });
try out.append(self.allocator, user_dir);
} else {
log.warn("Could not determine HOME — skipping ~/.stem/plugins", .{});
}
// 2. Common system install dirs. `install.sh` writes to
// `~/.local/lib/stem/plugins` (no /usr/local access) or
// `/usr/local/lib/stem/plugins`; the Nix derivation lands in
// `<store>/lib/stem/plugins`; `install.ps1` writes to
// `%LOCALAPPDATA%\Programs\stem\lib\stem\plugins`. We can't
// ask the binary where it lives in Zig 0.16, so we just probe
// the well-known paths and silently skip anything that
// doesn't exist.
if (home_owned) |home| {
const local_dir = try std.fs.path.join(self.allocator, &.{ home, ".local", "lib", "stem", "plugins" });
try out.append(self.allocator, local_dir);
}
if (@import("builtin").os.tag == .windows) {
// Per-user install (no admin) — what install.ps1 uses by default.
if (try platform.getEnv(self.allocator, self.environ_block, "LOCALAPPDATA")) |lad| {
defer self.allocator.free(lad);
const dir = try std.fs.path.join(self.allocator, &.{ lad, "Programs", "stem", "lib", "stem", "plugins" });
try out.append(self.allocator, dir);
}
// System-wide install (admin) — Program Files.
if (try platform.getEnv(self.allocator, self.environ_block, "ProgramFiles")) |pf| {
defer self.allocator.free(pf);
const dir = try std.fs.path.join(self.allocator, &.{ pf, "stem", "lib", "stem", "plugins" });
try out.append(self.allocator, dir);
}
} else {
const system_dirs = [_][]const u8{
"/usr/local/lib/stem/plugins",
"/usr/lib/stem/plugins",
"/opt/stem/plugins",
};
for (system_dirs) |sd| {
const dup = try self.allocator.dupe(u8, sd);
try out.append(self.allocator, dup);
}
}
// 3. Anything on `STEM_PLUGIN_PATH`. Split on `:` on POSIX,
// `;` on Windows. Empty segments are ignored.
const sep: u8 = if (@import("builtin").os.tag == .windows) ';' else ':';
if (try platform.getEnv(self.allocator, self.environ_block, "STEM_PLUGIN_PATH")) |raw_owned| {
defer self.allocator.free(raw_owned);
const raw = raw_owned;
var it = std.mem.tokenizeScalar(u8, raw, sep);
while (it.next()) |seg| {
if (seg.len == 0) continue;
const dup = try self.allocator.dupe(u8, seg);
try out.append(self.allocator, dup);
}
}
return out;
}
fn loadFromRoot(
self: *PluginManager,
root: []const u8,
seen: *std.StringHashMapUnmanaged(void),
) !void {
var dir = std.Io.Dir.openDirAbsolute(self.io, root, .{ .iterate = true }) catch |err| {
if (err == error.FileNotFound) return;
log.warn("Failed to open plugin dir {s}: {}", .{ root, err });
return;
};
defer dir.close(self.io);
var it = dir.iterate();
while (it.next(self.io) catch null) |entry| {
if (entry.kind != .directory) continue;
if (seen.contains(entry.name)) {
log.debug("plugin '{s}' already loaded from a higher-priority root; skipping {s}", .{ entry.name, root });
continue;
}
const full_path = try std.fs.path.join(self.allocator, &.{ root, entry.name });
defer self.allocator.free(full_path);
self.tryLoadPluginDir(full_path) catch |err| {
log.warn("Plugin dir {s} failed to load: {s}", .{ entry.name, @errorName(err) });
continue;
};
const dup = try self.allocator.dupe(u8, entry.name);
seen.put(self.allocator, dup, {}) catch {
self.allocator.free(dup);
};
}
}
/// Resolve a plugin name into its `~/.stem/plugins/<name>/` dir
/// and (re)load it via `tryLoadPluginDir`. Used by the runtime
/// `:plugin.reload` command and the `load_plugin` plugin message.
pub fn loadPluginByName(self: *PluginManager, name: []const u8) !void {
const platform = @import("../kernel/platform.zig");
const home = (try platform.getEnv(self.allocator, self.environ_block, "HOME")) orelse
(try platform.getEnv(self.allocator, self.environ_block, "USERPROFILE")) orelse
return error.NoHome;
defer self.allocator.free(home);
const plugin_dir = try std.fs.path.join(self.allocator, &.{ home, ".stem", "plugins", name });
defer self.allocator.free(plugin_dir);
try self.tryLoadPluginDir(plugin_dir);
}
/// Tear down a wasm or exec plugin by name. Drops every command,
/// status item, panel, event subscription, and permission grant
/// the plugin owned.
pub fn unloadPlugin(self: *PluginManager, name: []const u8) !void {
if (self.wasm_plugins.fetchRemove(name)) |kv| {
self.cleanupPluginResources(kv.value.plugin_id);
kv.value.deinit();
self.allocator.destroy(kv.value);
self.dropStoredPermissions(name);
self.dropRestartPolicy(name);
log.info("Unloaded wasm plugin: {s}", .{name});
return;
}
if (self.process_plugins.fetchRemove(name)) |kv| {
self.cleanupPluginResources(kv.value.name);
kv.value.deinit();
self.allocator.destroy(kv.value);
self.dropStoredPermissions(name);
self.dropRestartPolicy(name);
log.info("Unloaded process plugin: {s}", .{name});
return;
}
return error.PluginNotFound;
}
fn dropStoredPermissions(self: *PluginManager, plugin_id: []const u8) void {
if (self.plugin_permissions.fetchRemove(plugin_id)) |kv| {
self.allocator.free(kv.key);
var v = kv.value;
v.deinit(self.allocator);
}
}
fn dropRestartPolicy(self: *PluginManager, plugin_id: []const u8) void {
if (self.restart_policies.fetchRemove(plugin_id)) |kv| {
self.allocator.free(kv.key);
}
if (self.restart_state.fetchRemove(plugin_id)) |kv| {
self.allocator.free(kv.key);
}
var i: usize = 0;
while (i < self.pending_restarts.items.len) {
if (std.mem.eql(u8, self.pending_restarts.items[i].name, plugin_id)) {
self.allocator.free(self.pending_restarts.items[i].name);
_ = self.pending_restarts.swapRemove(i);
} else {
i += 1;
}
}
}
/// Read `<plugin_dir>/plugin.json` and dispatch to the runtime
/// declared in the manifest. Silently no-ops if the manifest is
/// missing (stray directory). Returns an error on the wasm /
/// exec load path so callers can log.
pub fn tryLoadPluginDir(self: *PluginManager, plugin_dir: []const u8) !void {
const manifest_path = try std.fs.path.join(self.allocator, &.{ plugin_dir, "plugin.json" });
defer self.allocator.free(manifest_path);
const file = std.Io.Dir.openFileAbsolute(self.io, manifest_path, .{}) catch |err| {
if (err == error.FileNotFound) return; // not a plugin dir
return err;
};
defer file.close(self.io);
const size = try file.length(self.io);
if (size > 1 * 1024 * 1024) return error.ManifestTooLarge;
const bytes = try self.allocator.alloc(u8, @intCast(size));
defer self.allocator.free(bytes);
const read_n = try file.readPositionalAll(self.io, bytes, 0);
var m = try manifest_mod.parse(self.allocator, bytes[0..read_n]);
defer m.deinit();
switch (m.runtime) {
.exec => try self.loadProcessPluginFromManifest(plugin_dir, &m),
.wasm => try self.loadWasmPluginFromManifest(plugin_dir, &m),
}
}
// -------------------------------------------------------------------
// Out-of-process plugins (JSON-RPC over stdio).
// -------------------------------------------------------------------
pub fn loadProcessPluginFromManifest(
self: *PluginManager,
plugin_dir: []const u8,
m: *const manifest_mod.Manifest,
) !void {
if (self.process_plugins.contains(m.name)) return error.DuplicatePluginId;
if (self.wasm_plugins.contains(m.name)) return error.DuplicatePluginId;
const entry_path = try std.fs.path.join(self.allocator, &.{ plugin_dir, m.entry });
errdefer self.allocator.free(entry_path);
const name_dup = try self.allocator.dupe(u8, m.name);
errdefer self.allocator.free(name_dup);
const pp = try self.allocator.create(ProcessPlugin);
errdefer self.allocator.destroy(pp);
pp.* = ProcessPlugin.init(self.allocator, self.io, name_dup, entry_path, .{
.user_data = @ptrCast(self),
.on_notification = handleProcessNotification,
.on_request = handleProcessRequest,
.on_exit = handleProcessExit,
});
errdefer pp.deinit();
var manifest_resources_installed = false;
errdefer if (manifest_resources_installed) {
self.cleanupPluginResources(m.name);
self.dropStoredPermissions(m.name);
self.dropRestartPolicy(m.name);
};
// Manifest-driven palette registration runs BEFORE the plugin
// starts so commands remain discoverable even if the child
// fails to come up. The dispatcher no-ops when the
// `process_plugins` map doesn't yet hold an entry.
for (m.commands) |cmd| {
self.registerManifestCommand(m.name, .exec, cmd) catch |err| {
log.warn("manifest commands for '{s}': {s}", .{ m.name, @errorName(err) });
};
}
try self.installPluginPermissions(m.name, m.permissions);
try self.installRestartPolicy(m.name, m.restart);
manifest_resources_installed = true;
try pp.start();
var inserted_in_map = false;
errdefer if (inserted_in_map) {
_ = self.process_plugins.fetchRemove(m.name);
};
try self.process_plugins.put(self.allocator, name_dup, pp);
inserted_in_map = true;
// Successful load — reset any prior crash backoff for this plugin.
self.clearRestartState(m.name);
// Synchronous `initialize` handshake: tell the plugin which
// ABI version it's talking to, and its assigned id. Plugins
// use this to bind any local state before the first command.
const init_params = try std.fmt.allocPrint(
self.allocator,
"{{\"abi_version\":{d},\"plugin_id\":\"{s}\"}}",
.{ PROC_ABI_VERSION, m.name },
);
defer self.allocator.free(init_params);
try pp.sendNotification("plugin/initialize", init_params);
manifest_resources_installed = false;
inserted_in_map = false;
log.info("Loaded process plugin: {s} ({s})", .{ m.name, entry_path });
}
/// JSON-RPC notification handler — runs on the ProcessPlugin's
/// reader thread. Mutations to manager state (command registry,
/// event subscribers, status items, panels) all happen inside this
/// call, so we serialise the whole dispatch under `state_mu`. The
/// lock is short-lived: every branch is O(1) or O(N small) work.
fn handleProcessNotification(
user_data: *anyopaque,
plugin_id: []const u8,
method: []const u8,
params: std.json.Value,
) void {
_ = plugin_id;
const self: *PluginManager = @ptrCast(@alignCast(user_data));
self.state_mu.lock();
defer self.state_mu.unlock();
if (std.mem.eql(u8, method, "plugin/log")) {
// params: { "level": int, "message": string }
if (params != .object) return;
const obj = params.object;
const message = if (obj.get("message")) |v| (if (v == .string) v.string else return) else return;
const level: u8 = if (obj.get("level")) |v| (if (v == .integer) @intCast(v.integer) else 1) else 1;
if (logger_service.getGlobal()) |g| {
const lvl: logger_service.LogLevel = switch (level) {
0 => .debug,
2 => .warn,
3 => .err,
else => .info,
};
g.log(lvl, "Plugin", "{s}", .{message});
}
return;
}
if (std.mem.eql(u8, method, "plugin/registerCommand")) {
self.registerProcessCommand(params) catch |err| {
log.warn("registerCommand failed: {s}", .{@errorName(err)});
};
return;
}
if (std.mem.eql(u8, method, "plugin/subscribeEvent")) {
self.subscribeProcessEvent(params) catch {};
return;
}
if (std.mem.eql(u8, method, "editor/showNotification")) {
if (params != .object) return;
const obj = params.object;
const msg_v = obj.get("message") orelse return;
if (msg_v != .string) return;
const level: u8 = if (obj.get("level")) |v| (if (v == .integer) @intCast(v.integer) else 0) else 0;
self.dispatchNotification("process-plugin", level, msg_v.string);
return;
}
log.info("process plugin: unhandled notification '{s}'", .{method});
}
fn handleProcessRequest(
user_data: *anyopaque,
plugin_id: []const u8,
id: u64,
method: []const u8,
_: std.json.Value,
) void {
const self: *PluginManager = @ptrCast(@alignCast(user_data));
// Forward the request onto core's inbox as a PluginMessage
// carrying the JSON-RPC id in `correlation_id`; core handles
// it on its own thread and calls `replyToProcessPlugin` once
// it has the answer. Record `(id → plugin_id)` here so the
// reply lands on the exact plugin that asked.
const core_inbox = self.core_inbox orelse {
self.replyProcessPluginByName(plugin_id, id, null, -32603, "core inbox unavailable");
return;
};
const which: protocol.PluginMessage.PluginMessageType = blk: {
if (std.mem.eql(u8, method, "editor/getState")) break :blk .get_state;
if (std.mem.eql(u8, method, "editor/getBufferContent")) break :blk .get_buffer_content;
if (std.mem.eql(u8, method, "editor/getPluginList")) break :blk .get_plugin_list;
self.replyProcessPluginByName(plugin_id, id, null, -32601, "Method not found");
return;
};
if (!self.recordPendingRequest(id, plugin_id)) {
self.replyProcessPluginByName(plugin_id, id, null, -32603, "request tracking failed");
return;
}
const pm = protocol.PluginMessage{
.plugin_id = plugin_id,
.message_type = which,
.payload = switch (which) {
.get_state => .{ .state_request = {} },
.get_buffer_content => .{ .buffer_content_request = {} },
.get_plugin_list => .{ .plugin_list_request = {} },
else => unreachable,
},
.correlation_id = id,
};
const outer = protocol.Message{ .plugin_message = pm };
const encoded = outer.encode(self.allocator) catch {
if (self.takePendingRequest(id)) |stale| self.allocator.free(stale);
self.replyProcessPluginByName(plugin_id, id, null, -32603, "encode failed");
return;
};
defer self.allocator.free(encoded);
core_inbox.send(encoded) catch {
if (self.takePendingRequest(id)) |stale| self.allocator.free(stale);
self.replyProcessPluginByName(plugin_id, id, null, -32603, "core inbox closed");
};
}
/// Record an in-flight `(correlation_id → plugin_id)` mapping
/// under the state lock. Returns `false` if allocation fails so
/// the caller can surface an error reply immediately rather than
/// silently drop the reply when it arrives.
fn recordPendingRequest(self: *PluginManager, id: u64, plugin_id: []const u8) bool {
self.state_mu.lock();
defer self.state_mu.unlock();
const copy = self.allocator.dupe(u8, plugin_id) catch return false;
self.pending_requests.put(self.allocator, id, copy) catch {
self.allocator.free(copy);
return false;
};
return true;
}
fn takePendingRequest(self: *PluginManager, id: u64) ?[]u8 {
self.state_mu.lock();
defer self.state_mu.unlock();
if (self.pending_requests.fetchRemove(id)) |kv| return kv.value;
return null;
}
/// Dispatch a JSON-RPC reply built by core back to the originating
/// process plugin. Looks up the plugin by name (saved when the
/// request was forwarded); if the plugin has since been unloaded
/// or crashed the reply is silently dropped — better than waking
/// every other plugin with a stale correlation id.
pub fn replyToProcessPlugin(
self: *PluginManager,
correlation_id: u64,
result_json: []const u8,
) void {
const plugin_name_opt = self.takePendingRequest(correlation_id);
const plugin_name = plugin_name_opt orelse {
log.warn("dropping reply for unknown correlation_id={d}", .{correlation_id});
return;
};
defer self.allocator.free(plugin_name);
self.state_mu.lock();
const pp_opt = self.process_plugins.get(plugin_name);
self.state_mu.unlock();
const pp = pp_opt orelse {
log.warn("dropping reply id={d}: plugin '{s}' is gone", .{ correlation_id, plugin_name });
return;
};
pp.sendReply(correlation_id, result_json) catch |err| {
log.warn("reply to '{s}' id={d} failed: {s}", .{ plugin_name, correlation_id, @errorName(err) });
};
}
/// Send a JSON-RPC error to a specific process plugin. If the
/// correlation id was already recorded (`takePendingRequest`
/// returned a name) the caller passes it as `recorded_name`;
/// otherwise we fall back to the `plugin_id` argument the request
/// handler observed.
fn replyProcessPluginByName(
self: *PluginManager,
plugin_id: []const u8,
correlation_id: u64,
recorded_name: ?[]u8,
code: i32,
message: []const u8,
) void {
defer if (recorded_name) |n| self.allocator.free(n);
self.state_mu.lock();
const pp_opt = self.process_plugins.get(plugin_id);
self.state_mu.unlock();
if (pp_opt) |pp| {
pp.sendError(correlation_id, code, message) catch {};
}
log.warn("process plugin '{s}' request id={d} error {d}: {s}", .{ plugin_id, correlation_id, code, message });
}
fn handleProcessExit(user_data: *anyopaque, plugin_id: []const u8) void {
// Runs on the ProcessPlugin's reader thread when the child
// closes stdout. We MUST NOT call `unloadPlugin` here —
// doing so would destroy the very `ProcessPlugin` whose
// reader thread is still unwinding through this callback,
// and the manager's maps may be in use on the main loop.
// Instead, hand the name to `pending_exits` for the main
// loop to drain on its next tick via `drainPendingExits`.
const self: *PluginManager = @ptrCast(@alignCast(user_data));
self.state_mu.lock();
const copy = self.allocator.dupe(u8, plugin_id) catch {
self.state_mu.unlock();
return;
};
self.pending_exits.append(self.allocator, copy) catch {
self.allocator.free(copy);
self.state_mu.unlock();
return;
};
self.state_mu.unlock();
// Wake core so it drains promptly. The render flag is set in
// `drainPendingExits` once the work actually runs.
if (self.core_inbox) |inbox| {
const tick_bytes = (protocol.Message{ .tick = {} }).encode(self.allocator) catch return;
defer self.allocator.free(tick_bytes);
inbox.send(tick_bytes) catch {};
}
}
/// Drain any process plugins flagged by their reader thread.
/// Called by core on tick, on the main loop, so it's safe to
/// destroy the plugin and tear down its commands/widgets here.
/// Returns the number of plugins actually unloaded — non-zero
/// means the UI should re-render to drop stale palette entries.
pub fn drainPendingExits(self: *PluginManager) usize {
// Move the pending list out under the lock, then process
// outside it so the unload path (which also takes the lock
// via the public API) doesn't deadlock against itself.
self.state_mu.lock();
const names = self.pending_exits.toOwnedSlice(self.allocator) catch &[_][]u8{};
self.state_mu.unlock();
defer self.allocator.free(names);
for (names) |name| {
telemetry.recordPluginCrash(name);
if (self.lifecycle_supervisor) |supervisor| {
supervisor.recordCrash(name);
}
const policy: manifest_mod.Restart = blk: {
self.state_mu.lock();
defer self.state_mu.unlock();
break :blk self.restart_policies.get(name) orelse .never;
};
self.unloadPlugin(name) catch |err| {
log.warn("unload of failed process plugin '{s}' failed: {s}", .{ name, @errorName(err) });
};
switch (policy) {
.never => {
log.warn("process plugin '{s}' exited; resources pruned (no restart — manifest opted out)", .{name});
self.allocator.free(name);
},
.on_crash, .always => {
self.scheduleRestart(name) catch |err| {
log.warn("schedule restart for '{s}' failed: {s}; resources pruned", .{ name, @errorName(err) });
self.allocator.free(name);
};
},
}
}
return names.len;
}
/// Insert (or refresh) the backoff entry for a crashed plugin and
/// append it to `pending_restarts`. Ownership of `name_owned`
/// transfers to the manager — either into the pending list (if
/// queued) or freed immediately (if we've exhausted retries).
fn scheduleRestart(self: *PluginManager, name_owned: []u8) !void {
// Snapshot a stable handle for the post-unlock inbox poke so
// we never call into another subsystem with `state_mu` held.
var inbox_snapshot: ?*vigil_api.Inbox = null;
var restart_delay_ms: i64 = 0;
var restart_attempt: u32 = 0;
{
self.state_mu.lock();
defer self.state_mu.unlock();
// Look up the existing backoff state, or initialise a fresh
// one. Cloning the key into a separate string for the
// restart_state map keeps lifetimes straight: the pending
// list owns its `name`, and restart_state owns its key.
const gop = try self.restart_state.getOrPut(self.allocator, name_owned);
if (!gop.found_existing) {
const key_dup = try self.allocator.dupe(u8, name_owned);
gop.key_ptr.* = key_dup;
gop.value_ptr.* = .{};
}
const delay = restartDelayMs(gop.value_ptr.attempts) orelse {
log.warn("process plugin '{s}' crashed too many times; giving up (re-load manually with `:Plugin Manager Reload All`)", .{name_owned});
// Drop the give-up entry so the bookkeeping doesn't
// hang around until manager deinit. The next manual
// reload will start fresh.
if (self.restart_state.fetchRemove(name_owned)) |kv| {
self.allocator.free(kv.key);
}
self.allocator.free(name_owned);
return;
};
gop.value_ptr.attempts += 1;
gop.value_ptr.last_attempt_ms = std.Io.Clock.real.now(self.io).toMilliseconds();
const due = gop.value_ptr.last_attempt_ms + delay;
restart_delay_ms = delay;
restart_attempt = gop.value_ptr.attempts;
log.info("process plugin '{s}' crashed; restart scheduled in {d}ms (attempt {d})", .{
name_owned, delay, gop.value_ptr.attempts,
});
try self.pending_restarts.append(self.allocator, .{ .name = name_owned, .due_ms = due });
inbox_snapshot = self.core_inbox;
}
if (self.lifecycle_supervisor) |supervisor| {
supervisor.recordRestartScheduled(name_owned, restart_delay_ms, restart_attempt);
}
// Wake core promptly so it ticks soon and notices the pending
// restart — otherwise the restart only fires when something
// unrelated wakes the loop. Run *outside* `state_mu` so we
// never block the lock on inbox-side bookkeeping.
if (inbox_snapshot) |inbox| {
const tick_bytes = (protocol.Message{ .tick = {} }).encode(self.allocator) catch return;
defer self.allocator.free(tick_bytes);
inbox.send(tick_bytes) catch {};
}
}
/// Try to respawn any plugins whose backoff window has elapsed.
/// Called by core on tick. Same pattern as `drainPendingExits`:
/// move under the lock, process outside it.
pub fn drainPendingRestarts(self: *PluginManager) usize {
const now = std.Io.Clock.real.now(self.io).toMilliseconds();
self.state_mu.lock();
// Pre-reserve both partitions for the worst case (everything
// ready OR everything still pending). If reservation fails
// we'd otherwise be forced into a silent-drop fallback where
// `name` allocations leak; better to bail out and leave the
// queue intact so the next tick retries.
const total = self.pending_restarts.items.len;
var ready: std.ArrayListUnmanaged(PendingRestart) = .empty;
ready.ensureTotalCapacity(self.allocator, total) catch {
self.state_mu.unlock();
return 0;
};
errdefer ready.deinit(self.allocator);
var still_pending: std.ArrayListUnmanaged(PendingRestart) = .empty;
still_pending.ensureTotalCapacity(self.allocator, total) catch {
ready.deinit(self.allocator);
self.state_mu.unlock();
return 0;
};
for (self.pending_restarts.items) |pr| {