-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugins.rs
More file actions
6886 lines (6461 loc) · 259 KB
/
Copy pathplugins.rs
File metadata and controls
6886 lines (6461 loc) · 259 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 system: self-bootstrapping hooks loaded from .catalyst-code/plugins/.
// Each plugin is a subdirectory with a plugin.json manifest and hook scripts.
// Hooks are spawned as subprocesses with stdin JSON context, stdout JSON response.
// Broken hooks never crash the core; timeouts and parse failures are handled gracefully.
use crate::config::{ProviderConfig, ProviderKind, ResolvedProvider};
use crate::oauth::{LoginOutcome, OAuthPrompt, PendingOauth};
use crate::tools::{Outcome, ToolKind};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, RwLock};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
use tokio::process::Command;
// ---- constants ----
/// Short plugins pointer injected into the standing system prompt. The full
/// authoring contract lives in the opt-in `plugin-authoring` skill so everyday
/// coding turns do not pay for a ~6k-token manual.
pub const PLUGIN_DOCS: &str = r#"## Plugins
Extend the harness via `.catalyst-code/plugins/` (hooks, custom tools, OAuth,
memory backends, system-prompt injection). Manage with `/plugin-install` /
`/plugin-enable` / `/plugin-disable` / `/plugin-reload` (or the matching
protocol commands). There is no built-in `plugin` tool — use slash/protocol.
When authoring or debugging a plugin, apply the `plugin-authoring` skill
(`/skill:plugin-authoring`) — do not invent schema from memory. Full contract:
hooks (incl. pre_tool/post_tool catch-alls + agent-loop hooks), tools,
overrides, OAuth, and memory providers.
"#;
/// Valid hook point names. Plugins can register for any of these.
pub const HOOK_POINTS: &[&str] = &[
"pre_bash",
"pre_write",
"pre_read",
"post_bash",
"post_write",
"post_read",
"session_start",
"session_stop",
"pre_compact",
"pre_turn",
// Agent-loop hooks (PI parity): input/prompt/context/turn boundaries.
"pre_input",
"pre_agent_start",
"pre_context",
"turn_start",
"turn_end",
"session_shutdown",
// Catch-all hooks that fire for EVERY tool call (in addition to the
// specific pre_bash/pre_write/pre_read). They cover tools with no
// dedicated hook (memory, todo_write, git_*, subagent, plugin tools, …)
// so a plugin can audit/modify/deny ANY tool — the same reach a core edit
// of the dispatch loop has. pre_tool runs after the specific pre-hook;
// post_tool runs after the specific post-hook.
"pre_tool",
"post_tool",
];
/// Per-hook policy: safety rule, default timeout, and which response fields are honored.
#[derive(Debug, Clone, Copy)]
pub struct HookPolicy {
pub default_timeout_ms: u64,
/// What happens when the hook fails (non-zero, timeout, parse fail).
pub fail_mode: HookFailMode,
/// Whether `allow:false` is honored (pre_* style). When false, `allow` is ignored.
pub honor_allow: bool,
/// Whether `modify` keys are applied. Lifecycle hooks that only emit side effects
/// may still honor modify for prompt/context surgery.
pub honor_modify: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookFailMode {
/// Block the operation (pre_* style).
Deny,
/// Silently skip the hook result (post_* and advisory lifecycle hooks).
Skip,
}
/// Policy table for every hook point. This is the single source of truth for
/// how execute_hook reacts to failures and which response fields matter.
///
/// Design intent:
/// - pre_* hooks are BLOCKING: a failure denies the operation (fail-safe).
/// - post_* hooks are BEST-EFFORT: a failure silently skips.
/// - lifecycle/session hooks are advisory: failures are logged but never block.
/// - prompt/context/input surgery hooks are advisory by default so a slow/broken
/// plugin cannot freeze or corrupt the agent loop; callers may still apply
/// safe sub-modifies with their own validation.
pub fn hook_policy(hook_name: &str) -> HookPolicy {
match hook_name {
"pre_bash" | "pre_write" | "pre_read" | "pre_tool" | "pre_input" => HookPolicy {
default_timeout_ms: DEFAULT_PRE_TIMEOUT_MS,
fail_mode: HookFailMode::Deny,
honor_allow: true,
honor_modify: true,
},
"post_bash" | "post_write" | "post_read" | "post_tool" => HookPolicy {
default_timeout_ms: DEFAULT_POST_TIMEOUT_MS,
fail_mode: HookFailMode::Skip,
honor_allow: false,
honor_modify: true,
},
"session_start" | "session_stop" | "pre_compact" | "pre_turn" | "session_shutdown"
| "pre_agent_start" | "pre_context" | "turn_start" | "turn_end" => HookPolicy {
default_timeout_ms: DEFAULT_POST_TIMEOUT_MS,
fail_mode: HookFailMode::Skip,
honor_allow: false,
honor_modify: true,
},
_ => HookPolicy {
default_timeout_ms: DEFAULT_POST_TIMEOUT_MS,
fail_mode: HookFailMode::Skip,
honor_allow: false,
honor_modify: true,
},
}
}
/// Default timeout in milliseconds for pre_* hooks (blocking — keep short).
pub const DEFAULT_PRE_TIMEOUT_MS: u64 = 5_000;
/// Default timeout in milliseconds for post_* and lifecycle hooks.
pub const DEFAULT_POST_TIMEOUT_MS: u64 = 30_000;
pub const MAX_PLUGIN_INPUT_BYTES: usize = 1024 * 1024;
pub const MAX_PLUGIN_OUTPUT_BYTES: usize = 1024 * 1024;
/// Maximum size of a prompt-backed command's template file (and its rendered
/// output). Keeps a misconfigured `prompt_file` from blowing up the agent
/// context. 256 KiB is generous for a research protocol yet bounded.
pub const MAX_PROMPT_COMMAND_BYTES: usize = 256 * 1024;
fn validate_plugin_io(label: &str, input_len: usize) -> Result<(), String> {
if input_len > MAX_PLUGIN_INPUT_BYTES {
Err(format!(
"{label} input exceeds the {} byte limit",
MAX_PLUGIN_INPUT_BYTES
))
} else {
Ok(())
}
}
fn validate_plugin_output(label: &str, stdout: &[u8], stderr: &[u8]) -> Result<(), String> {
if stdout.len() > MAX_PLUGIN_OUTPUT_BYTES || stderr.len() > MAX_PLUGIN_OUTPUT_BYTES {
Err(format!(
"{label} output exceeds the {} byte per-stream limit",
MAX_PLUGIN_OUTPUT_BYTES
))
} else {
Ok(())
}
}
async fn read_plugin_stream_bounded<R: AsyncRead + Unpin>(
mut stream: Option<R>,
label: &'static str,
) -> std::io::Result<Vec<u8>> {
let Some(stream) = stream.as_mut() else {
return Ok(Vec::new());
};
let mut output = Vec::new();
let mut chunk = [0_u8; 16 * 1024];
loop {
let read = stream.read(&mut chunk).await?;
if read == 0 {
return Ok(output);
}
if output.len().saturating_add(read) > MAX_PLUGIN_OUTPUT_BYTES {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("plugin {label} exceeds the {MAX_PLUGIN_OUTPUT_BYTES} byte limit"),
));
}
output.extend_from_slice(&chunk[..read]);
}
}
/// Wait for a plugin while draining stdout/stderr concurrently into bounded
/// buffers. `kill_on_drop(true)` on every caller's child guarantees timeout or
/// overflow tears down the process when the cancelled future drops it.
async fn bounded_plugin_output(
mut child: tokio::process::Child,
timeout: Duration,
) -> Result<std::io::Result<std::process::Output>, tokio::time::error::Elapsed> {
let stdout = child.stdout.take();
let stderr = child.stderr.take();
tokio::time::timeout(timeout, async move {
let (status, stdout, stderr) = tokio::try_join!(
child.wait(),
read_plugin_stream_bounded(stdout, "stdout"),
read_plugin_stream_bounded(stderr, "stderr"),
)?;
Ok(std::process::Output {
status,
stdout,
stderr,
})
})
.await
}
/// Normalized plugin/hook run result (host or microVM). `std::process::Output`
/// Run a plugin/hook/oauth/memory-provider script. When sandboxing is enabled
/// the script executes inside the microVM via the shared execution backend
/// (never directly on the host); the script directory is mounted read-only
/// (workspace plugins live under /workspace, global plugins under
/// /catcode-plugins). Host secrets are never inherited. The context payload
/// travels over stdin; stdout carries the response.
///
/// Returns the SAME shape as [`bounded_plugin_output`] so the existing
/// deny/skip/error match arms in the callers are unchanged.
async fn plugin_run(
script: &std::path::Path,
stdin: Vec<u8>,
timeout: Duration,
extra_env: &[(String, String)],
) -> Result<std::io::Result<std::process::Output>, std::io::Error> {
if crate::sandbox::is_sandbox_enabled() {
return plugin_run_sandboxed(script, stdin, timeout, extra_env).await;
}
// Host path: spawn with the minimal env, write stdin, bound the wait.
let mut child = match hook_command_with_env(script, extra_env)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()
{
Ok(c) => c,
Err(e) => {
return Ok(Err(std::io::Error::other(format!(
"failed to spawn script {:?}: {e}",
script
))))
}
};
if !stdin.is_empty() {
if let Some(mut child_stdin) = child.stdin.take() {
let stdin_timeout = Duration::from_millis(timeout.as_millis().max(1000) as u64);
let write_fut = async {
use tokio::io::AsyncWriteExt;
let _ = child_stdin.write_all(&stdin).await;
let _ = child_stdin.shutdown().await;
};
if tokio::time::timeout(stdin_timeout, write_fut)
.await
.is_err()
{
let _ = child.start_kill();
// Model a stdin timeout as an elapsed timeout so the caller's
// existing `Err(_)` arm (deny/skip/error on timeout) handles it.
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"plugin execution timed out",
));
}
}
}
match bounded_plugin_output(child, timeout).await {
Ok(Ok(o)) => Ok(Ok(o)),
Ok(Err(e)) => Ok(Err(e)),
Err(_) => Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"plugin execution timed out",
)),
}
}
/// Construct a `std::process::Output` from a guest exit code cross-platform.
fn output_from_exit(code: i32, stdout: Vec<u8>, stderr: Vec<u8>) -> std::process::Output {
#[cfg(unix)]
let status = {
use std::os::unix::process::ExitStatusExt;
std::process::ExitStatus::from_raw(code << 8)
};
#[cfg(not(unix))]
let status = {
// On non-Unix the only guest is Linux (sandboxed), so this branch is
// unreachable in practice; fall back to a best-effort status.
std::process::ExitStatus::default()
};
std::process::Output {
status,
stdout,
stderr,
}
}
/// Sandboxed plugin/hook run: translate the script path to its guest location,
/// pick the guest interpreter (Linux guest — no PowerShell), and exec via the
/// shared backend. Never falls back to the host on a backend error.
async fn plugin_run_sandboxed(
script: &std::path::Path,
stdin: Vec<u8>,
timeout: Duration,
extra_env: &[(String, String)],
) -> Result<std::io::Result<std::process::Output>, std::io::Error> {
use crate::sandbox::policy;
let cfg = crate::sandbox::config();
let cfg = cfg.as_ref();
// Translate the host script path to its guest mount point.
let ws = cfg
.workspace
.canonicalize()
.unwrap_or_else(|_| cfg.workspace.clone());
let plugin_dir = cfg
.plugin_dir
.canonicalize()
.unwrap_or_else(|_| cfg.plugin_dir.clone());
let global_dir = crate::config::home_dir()
.map(|home| home.join(".catalyst-code/plugins"))
.and_then(|p| p.canonicalize().ok());
let script_canon = match script.canonicalize() {
Ok(p) => p,
Err(e) => {
return Ok(Err(std::io::Error::other(format!(
"script {:?} not found: {e}",
script
))))
}
};
let guest_path = if let Ok(rel) = script_canon.strip_prefix(&ws) {
std::path::PathBuf::from("/workspace").join(rel)
} else if let Ok(rel) = script_canon.strip_prefix(&plugin_dir) {
std::path::PathBuf::from("/catcode-plugins").join(rel)
} else if let Some(global_dir) = global_dir.as_ref() {
if let Ok(rel) = script_canon.strip_prefix(global_dir) {
std::path::PathBuf::from("/catcode-plugins").join(rel)
} else {
return Ok(Err(std::io::Error::other(format!(
"script {:?} is not under a mounted plugin directory",
script
))));
}
} else {
return Ok(Err(std::io::Error::other(format!(
"script {:?} is not under the workspace and no global plugin dir is mounted",
script
))));
};
let gp = guest_path.display().to_string();
// Pick the guest interpreter from the extension (guest is Linux).
let ext = script
.extension()
.and_then(|e| e.to_str())
.map(|e| e.to_ascii_lowercase())
.unwrap_or_default();
let (program, args): (String, Vec<String>) = match ext.as_str() {
"sh" | "bash" => ("bash".to_string(), vec![gp]),
"py" => ("python3".to_string(), vec![gp]),
"ps1" | "bat" | "cmd" | "exe" | "com" => {
return Ok(Err(std::io::Error::other(format!(
"script {:?} is a Windows-only type (.{ext}); the sandbox guest is Linux. \
Re-implement the plugin as a .sh or .py script.",
script
))));
}
_ => ("sh".to_string(), vec![gp]),
};
let proc_env = policy::build_process_env(cfg, policy::ExecPurpose::Plugin);
let mut env = proc_env.env;
for (k, v) in extra_env {
if !policy::is_secret_var(k) {
env.insert(k.clone(), v.clone());
}
}
let cwd = policy::effective_cwd(cfg, "").unwrap_or_else(|_| cfg.workspace.clone());
let req = crate::sandbox::ExecRequest {
program,
args,
cwd,
env,
inherit_parent_env: false,
stdin: Some(stdin),
timeout,
..Default::default()
};
match crate::sandbox::execution_backend().execute(req).await {
Ok(r) => {
let code = r.exit_code.unwrap_or(127);
Ok(Ok(output_from_exit(code, r.stdout, r.stderr)))
}
Err(crate::sandbox::ExecutionError::Timeout(_)) => Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"plugin execution timed out",
)),
Err(e) => Ok(Err(std::io::Error::other(e.user_message()))),
}
}
/// Slash-command names reserved by the harness. Plugin commands may not reuse
/// these (with or without a leading `/`).
const RESERVED_COMMAND_NAMES: &[&str] = &[
"help",
"new",
"abort",
"login",
"logout",
"models",
"plugin-install",
"plugin-list",
"plugin-enable",
"plugin-disable",
"plugin-remove",
"plugin-reload",
"plugin-config",
"stats",
"sessions",
"clear",
"reset",
"undo",
"compact",
"memory",
"remember",
"forget",
"reflect",
"index",
"goal",
"cancel-goal",
"run",
"parallel",
"chain",
"subagents",
"vision",
"context",
"usage",
"skill",
];
// ---- manifest deserialization (plugin.json) ----
#[derive(Deserialize, Debug, Clone)]
struct PluginManifest {
name: String,
version: String,
#[serde(default)]
protocol_version: Option<u32>,
/// Explicit authority requested by newer plugins. Absent keeps legacy
/// manifests compatible by inferring the minimum set from their features.
#[serde(default)]
capabilities: Option<Vec<String>>,
#[serde(default)]
description: String,
#[serde(default)]
hooks: HashMap<String, HookManifestEntry>,
/// Optional user-declared tools (custom capabilities, no MCP needed).
#[serde(default)]
tools: Vec<ToolManifestEntry>,
/// Built-in/plugin tool names to REMOVE from the model's toolset.
#[serde(default)]
disable_tools: Vec<String>,
/// Static text injected into the system prompt (empty = none).
#[serde(default)]
system_prompt: String,
/// Optional OAuth subscription provider this plugin adds (login flow +
/// token resolution), mirroring the built-in OpenAI/Claude/Gemini OAuth.
#[serde(default)]
oauth: Option<OauthManifestEntry>,
/// Optional memory backend that replaces the built-in markdown store for
/// standing-prompt injection, slash memory commands, compaction extracts,
/// and (when no tool overrides `memory`) the built-in `memory` tool.
#[serde(default)]
memory_provider: Option<MemoryProviderManifestEntry>,
/// Optional slash commands declared by the plugin (`/name` → script).
#[serde(default)]
commands: Vec<CommandManifestEntry>,
}
/// A slash-command declared in a plugin manifest (the `commands` array).
///
/// A command is either **script-backed** (`script` → run an executable, show
/// its output) or **prompt-backed** (`prompt_file` → render a template and
/// submit it as a normal agent turn). Exactly one of `script`/`prompt_file`
/// must be set. `mode` is optional and inferred when absent.
#[derive(Deserialize, Debug, Clone)]
struct CommandManifestEntry {
name: String,
#[serde(default)]
description: String,
/// Executable handler script (script-backed commands). Mutually exclusive
/// with `prompt_file`.
#[serde(default)]
script: Option<String>,
/// Prompt template file (prompt-backed commands) rendered and submitted as
/// an agent turn. Path-confined to the plugin directory (no absolute
/// paths, no `..`). Mutually exclusive with `script`.
#[serde(default)]
prompt_file: Option<String>,
/// Optional explicit mode: `"script"` or `"agent_turn"`. Inferred from
/// which of `script`/`prompt_file` is set when absent.
#[serde(default)]
mode: Option<String>,
#[serde(default)]
timeout_ms: Option<u64>,
}
/// A memory-provider declaration in `plugin.json` (`memory_provider` block).
#[derive(Deserialize, Debug, Clone)]
struct MemoryProviderManifestEntry {
script: String,
#[serde(default)]
timeout_ms: Option<u64>,
}
#[derive(Deserialize, Debug, Clone)]
struct HookManifestEntry {
script: String,
#[serde(default)]
timeout_ms: Option<u64>,
#[serde(default)]
pass_args: bool,
}
/// A tool declared in a plugin manifest (the `tools` array). Each entry becomes
/// a tool the model can call; the `script` handler is spawned per call.
#[derive(Deserialize, Debug, Clone)]
struct ToolManifestEntry {
name: String,
#[serde(default)]
description: String,
/// JSON Schema for the tool's parameters (sent to the model as-is).
#[serde(default)]
parameters: Value,
script: String,
/// "readonly" (skip the approval gate) or "destructive" (prompt; default).
#[serde(default)]
kind: Option<String>,
#[serde(default)]
timeout_ms: Option<u64>,
/// When true AND `name` matches a built-in tool, this plugin's handler
/// REPLACES the built-in's implementation: the model still sees a tool of
/// that name (the plugin's declared schema), but calls route to the plugin
/// script instead of the core handler. Lets a plugin fully override a
/// core tool (a sandboxed bash, a redacting read_file, …) without
/// recompiling. Default false: a name collision stays built-in (unchanged).
#[serde(default, rename = "override")]
override_builtin: bool,
}
/// An OAuth provider declared by a plugin manifest's `oauth` block. Lets a
/// plugin add a subscription-OAuth provider (login flow + token resolution)
/// the same way the built-in OpenAI/Claude/Gemini providers work — no
/// recompile. The plugin supplies ONE script that handles four actions
/// (`login`, `complete`, `token`, `clear`) dispatched by an `action` field in
/// the stdin context; per-action script overrides are optional. See the `plugin-authoring` skill
/// (`.catalyst-code/skills/plugin-authoring/SKILL.md`) for the full contract.
#[derive(Deserialize, Debug, Clone)]
struct OauthManifestEntry {
/// The provider identity. Must match the provider-config `name` created on
/// `/login` (the harness creates the config with this name). Also the key
/// `/oauth-code` and `/logout` dispatch on.
provider_id: String,
/// Human label shown in the `/login` picker (defaults to provider_id).
#[serde(default)]
label: Option<String>,
/// Wire protocol: "openai" (default) or "anthropic".
#[serde(default)]
kind: Option<String>,
/// The endpoint base URL (include `/v1`; paths appended directly).
base_url: String,
#[serde(default)]
description: Option<String>,
/// Extra HTTP headers appended to every request, `[[key,val],…]`.
#[serde(default)]
headers: Vec<(String, String)>,
/// Token-file name, relative to `~/.config/catalyst-code/oauth/`. Defaults
/// to `<provider_id>.json`. The harness passes the ABSOLUTE resolved path to
/// every script invocation, so the plugin owns the token's on-disk format.
#[serde(default)]
token_path: Option<String>,
/// Optional external credential file to detect and import. The supported
/// `$CODEX_HOME/auth.json` form follows the official Codex CLI store; the
/// harness uses it only as a cheap credential-presence hint and leaves the
/// actual format/import logic to the provider script.
#[serde(default)]
detect_path: Option<String>,
/// The script handling ALL actions (login/complete/token/clear). Required
/// unless every action has an explicit override.
#[serde(default)]
script: Option<String>,
#[serde(default)]
login_script: Option<String>,
#[serde(default)]
complete_script: Option<String>,
#[serde(default)]
token_script: Option<String>,
/// Timeout for the login + complete actions (default 120s).
#[serde(default)]
login_timeout_ms: Option<u64>,
/// Timeout for the token (resolve/refresh) action (default 30s).
#[serde(default)]
token_timeout_ms: Option<u64>,
/// Non-secret env var names the harness forwards to this provider's
/// scripts (e.g. `ACME_OAUTH_HOST` for a self-hosted auth server). The
/// harness otherwise scrubs the environment, so plugin-specific config
/// knobs must be declared here. Names containing KEY/TOKEN/SECRET/
/// PASSWORD are rejected — passthrough must never defeat env scrubbing.
#[serde(default)]
env_passthrough: Vec<String>,
}
// ---- public types ----
/// A loaded plugin with its registered hooks and declared tools.
#[derive(Clone, Debug)]
pub struct Plugin {
pub name: String,
pub version: String,
pub protocol_version: u32,
pub capabilities: Vec<String>,
pub description: String,
pub enabled: bool,
/// Absolute path to the plugin directory on disk.
pub source_path: PathBuf,
/// Hook name → config map.
pub hooks: HashMap<String, HookConfig>,
/// Tools this plugin declares (custom capabilities; no MCP needed).
pub tools: Vec<ToolConfig>,
/// Slash commands this plugin declares (`/name` handlers).
pub commands: Vec<CommandConfig>,
/// Built-in/plugin tool names to REMOVE from the model's toolset.
pub disable_tools: Vec<String>,
/// Static text injected into the system prompt (empty = none).
pub system_prompt: String,
/// OAuth subscription provider this plugin declares, if any.
pub oauth: Option<PluginOauthConfig>,
/// Memory backend that replaces the built-in markdown store, if any.
pub memory_provider: Option<PluginMemoryProviderConfig>,
}
/// A loaded memory-provider declaration (`memory_provider` block with the
/// script resolved to an absolute, path-confined, executable file).
#[derive(Clone, Debug)]
pub struct PluginMemoryProviderConfig {
/// Plugin that owns this provider (for logging / framing).
pub plugin_name: String,
/// Absolute path to the provider script.
pub script: PathBuf,
/// Hard timeout in milliseconds per action.
pub timeout_ms: u64,
}
/// Configuration for one hook within a plugin.
#[derive(Clone, Debug)]
pub struct HookConfig {
/// Absolute path to the executable hook script.
pub script: PathBuf,
/// Hard timeout in milliseconds for this hook.
pub timeout_ms: u64,
/// Whether to include tool args in the hook context JSON.
pub pass_args: bool,
}
/// Configuration for one user-declared tool within a plugin.
#[derive(Clone, Debug)]
pub struct ToolConfig {
pub name: String,
pub description: String,
/// JSON Schema for the tool's parameters (sent to the model verbatim).
pub parameters: Value,
/// Absolute path to the executable handler script.
pub script: PathBuf,
/// Hard timeout in milliseconds for a single tool call.
pub timeout_ms: u64,
/// Approval classification: ReadOnly skips the gate, Destructive prompts.
pub kind: ToolKind,
/// True → this tool's handler replaces the built-in of the same name.
pub override_builtin: bool,
/// Plugin that owns this tool (for UI side-effect framing).
pub plugin_name: String,
/// Declared plugin capabilities (enforced at execute time — CORE_REVIEW).
pub capabilities: Vec<String>,
}
/// How a plugin slash command is executed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandMode {
/// Run an executable handler script; its `output` is shown to the user.
Script,
/// Render a prompt template and submit it as a normal agent turn (the same
/// path as a user `send`). Lets a command like `/deep-research` drive a
/// full agent loop without a script or recompile.
AgentTurn,
}
impl CommandMode {
pub fn as_str(&self) -> &'static str {
match self {
CommandMode::Script => "script",
CommandMode::AgentTurn => "agent_turn",
}
}
}
/// Configuration for one plugin-declared slash command.
#[derive(Clone, Debug)]
pub struct CommandConfig {
pub name: String,
pub description: String,
/// How the command is executed (script vs. agent-turn prompt).
pub mode: CommandMode,
/// Absolute path to the executable handler script (script-backed commands).
pub script: Option<PathBuf>,
/// Absolute path to the prompt template file (prompt-backed commands).
pub prompt_file: Option<PathBuf>,
/// Hard timeout in milliseconds for a single command invocation.
pub timeout_ms: u64,
/// Plugin that owns this command.
pub plugin_name: String,
}
/// A loaded OAuth-provider declaration (manifest `oauth` block with script
/// paths resolved to absolute, path-confined, executable files). The plugin
/// owns the token's on-disk format; the harness owns the loopback redirect
/// server (web flow), optional automatic completion, and the `/oauth-code`
/// paste path (manual flow).
#[derive(Clone, Debug)]
pub struct PluginOauthConfig {
pub provider_id: String,
pub label: String,
pub kind: ProviderKind,
pub base_url: String,
pub description: String,
pub headers: Vec<(String, String)>,
/// Absolute path the plugin reads/writes its token at.
pub token_path: PathBuf,
/// Optional external credential path used for cheap login detection.
pub detect_path: Option<PathBuf>,
/// Resolved absolute script paths per action (override else the default).
pub scripts: HashMap<String, PathBuf>,
pub login_timeout_ms: u64,
pub token_timeout_ms: u64,
/// Non-secret env var names forwarded to this provider's scripts
/// (validated in `load_oauth_entry`; values taken from the harness env).
pub env_passthrough: Vec<String>,
}
impl PluginOauthConfig {
/// Resolve which script runs `action` (the action-specific override, else
/// the shared `script` fallback).
pub fn script_for(&self, action: &str) -> Option<&Path> {
self.scripts
.get(action)
.or_else(|| self.scripts.get("*"))
.map(|p| p.as_path())
}
}
/// A cached OAuth access token + optional request headers + absolute-seconds
/// expiry, keyed by provider_id in the PluginManager. Keeps the per-turn hot
/// path (enrich_oauth) from spawning the token script on every request.
/// `headers` come from the plugin `token` action (e.g. `chatgpt-account-id`).
#[derive(Clone)]
struct CachedToken {
token: String,
expires_at: u64,
headers: Vec<(String, String)>,
}
/// Fresh OAuth credentials resolved from a plugin `token` action (or cache).
#[derive(Clone, Debug)]
pub struct ResolvedOauthCreds {
pub access_token: String,
/// Extra HTTP headers to merge onto the resolved provider for this turn
/// (e.g. `chatgpt-account-id`). Empty when the script omits them.
pub headers: Vec<(String, String)>,
}
/// Result returned from executing a hook.
#[derive(Clone, Debug)]
pub struct HookResult {
/// Whether the operation is allowed to proceed.
pub allow: bool,
/// Human-readable explanation from the hook.
pub reason: String,
/// Optional modified arguments (pre hooks only; ignored for post hooks).
pub modify: Option<Value>,
/// Optional UI notification text from the hook response.
pub notify: Option<String>,
/// Optional status-bar text (`Some("")` means clear).
pub status: Option<String>,
}
pub const PLUGIN_PROTOCOL_VERSION: u32 = 1;
const PLUGIN_CAPABILITIES: &[&str] = &[
"read_workspace",
"write_workspace",
"execute_subprocess",
"access_network",
"receive_prompts",
"receive_tool_arguments",
"receive_model_responses",
"access_secrets",
"register_tools",
"register_commands",
"register_providers",
"register_memory_backend",
];
fn validate_manifest_capabilities(manifest: &PluginManifest) -> Result<Vec<String>, String> {
let protocol_version = manifest.protocol_version.unwrap_or(1);
if protocol_version > PLUGIN_PROTOCOL_VERSION {
return Err(format!(
"plugin protocol version {protocol_version} is newer than supported ({PLUGIN_PROTOCOL_VERSION})"
));
}
let mut required = HashSet::<&str>::new();
let uses_subprocess = !manifest.hooks.is_empty()
|| !manifest.tools.is_empty()
|| manifest.commands.iter().any(|c| {
c.script
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.is_some()
})
|| manifest.oauth.is_some()
|| manifest.memory_provider.is_some();
if uses_subprocess {
required.insert("execute_subprocess");
}
for (name, hook) in &manifest.hooks {
if hook.pass_args {
required.insert("receive_tool_arguments");
}
if matches!(
name.as_str(),
"pre_input" | "pre_context" | "pre_turn" | "turn_start"
) {
required.insert("receive_prompts");
}
if matches!(name.as_str(), "post_tool" | "turn_end" | "session_stop") {
required.insert("receive_model_responses");
}
}
if !manifest.tools.is_empty() {
required.insert("register_tools");
for tool in &manifest.tools {
if tool.kind.as_deref() == Some("readonly") {
required.insert("read_workspace");
} else {
required.insert("write_workspace");
}
}
}
if !manifest.commands.is_empty() {
required.insert("register_commands");
}
if manifest.oauth.is_some() {
required.extend(["register_providers", "access_network", "access_secrets"]);
}
if manifest.memory_provider.is_some() {
required.insert("register_memory_backend");
}
let Some(declared) = manifest.capabilities.as_ref() else {
let mut inferred: Vec<String> = required.into_iter().map(str::to_string).collect();
inferred.sort();
return Ok(inferred);
};
let declared_set: HashSet<&str> = declared.iter().map(String::as_str).collect();
let unknown: Vec<&str> = declared_set
.iter()
.copied()
.filter(|capability| !PLUGIN_CAPABILITIES.contains(capability))
.collect();
if !unknown.is_empty() {
return Err(format!(
"plugin declares unknown capabilities: {}",
unknown.join(", ")
));
}
let mut missing: Vec<&str> = required.difference(&declared_set).copied().collect();
missing.sort_unstable();
if !missing.is_empty() {
return Err(format!(
"plugin is denied because its manifest is missing required capabilities: {}",
missing.join(", ")
));
}
let mut validated = declared.clone();
validated.sort();
validated.dedup();
Ok(validated)
}
// ---- PluginManager ----
/// Where `/plugin-install` copies a plugin on disk.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PluginInstallScope {
/// `~/.catalyst-code/plugins` — available in every workspace.
Global,
/// `<workspace>/.catalyst-code/plugins` — this repo only.
Workspace,
}
impl PluginInstallScope {
pub fn parse(s: &str) -> Result<Self, String> {
match s.trim().to_lowercase().as_str() {
"" | "global" | "user" | "g" | "-g" | "--global" => Ok(Self::Global),
"workspace" | "project" | "local" | "w" | "-w" | "--workspace" => Ok(Self::Workspace),
other => Err(format!(
"unknown plugin scope '{other}' (use 'global' or 'workspace')"
)),
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Global => "global",
Self::Workspace => "workspace",
}
}
}
/// A project-scoped plugin that was NOT loaded because it is not trusted
/// (or its trust decision is still pending). Carries enough manifest metadata
/// for the trust prompt UI plus the recorded decision.
#[derive(Clone, Debug)]
pub struct SkippedProjectPlugin {
pub name: String,
pub version: String,
pub description: String,
pub path: PathBuf,
/// Stable key for the project plugin directory, independent of the
/// manifest's mutable display name.
pub decision_key: String,
/// Recorded user decision: `Some("trust")` → would load; `Some("deny")`
/// → stays skipped; `None` → undecided (drives the auto trust prompt).
pub decision: Option<String>,
}
/// Manages the lifecycle of all installed plugins.
/// Holds an in-memory registry behind a `RwLock`.
pub struct PluginManager {
plugins_dir: PathBuf,
/// Optional **global, user-owned** plugins dir (`~/.catalyst-code/plugins`)
/// scanned before the project dir so globally-staged plugins load across
/// every project. `None` for the isolated `new()` constructor (used by
/// tests); `Some` for `new_with_global_plugins()` (used by the core at
/// startup). A project plugin with the same name overrides the global one.
user_plugins_dir: Option<PathBuf>,
/// Workspace root — used to decide whether a plugin dir is project-scoped
/// (inside the workspace) vs user-installed (outside it).
workspace: PathBuf,
/// When false (the secure default), project-scoped plugins under the
/// workspace's `.catalyst-code/plugins` are NOT auto-loaded — a repo you
/// `cd` into must not run hook scripts with your privileges without opt-in.
trust_project: bool,
/// Canonical workspace root used as the trust-store key.
trust_key: PathBuf,
/// Per-project trust decisions (canonical plugin directory key →
/// "trust" | "deny") loaded from the user-owned store; consulted when
/// gating project plugins.
trust_decisions: RwLock<HashMap<String, String>>,
/// Where decisions are persisted (`~/.config/catalyst-code/plugin-trust.json`);
/// None for isolated test constructors so tests never touch the real store.
trust_store_path: Option<PathBuf>,
plugins: RwLock<HashMap<String, Plugin>>,
/// Project-scoped plugins skipped because they are not trusted (or the
/// trust decision is still pending). Carries manifest metadata + decision
/// so the UI can render the trust prompt.
skipped_project: Mutex<Vec<SkippedProjectPlugin>>,
/// In-memory cache of resolved OAuth access tokens (provider_id → token),
/// so the per-turn hot path (`enrich_oauth`) doesn't spawn the token script
/// on every request. Refreshed when near expiry.
token_cache: Mutex<HashMap<String, CachedToken>>,
}
impl PluginManager {
/// Resolve a possibly-relative project plugins dir against `workspace`.
/// Keeps install + scan on the same absolute path regardless of process cwd
/// (the TUI passes `--workspace .` but cwd can still drift across restarts).
fn resolve_plugins_dir(plugins_dir: PathBuf, workspace: &Path) -> PathBuf {
if plugins_dir.is_absolute() {
plugins_dir
} else {
workspace.join(plugins_dir)
}
}
}
/// Canonical (symlink-resolved) form of `workspace`, used as the trust-store
/// key so the same project always maps to the same decisions regardless of how
/// it was opened.
fn canonical_workspace(workspace: &Path) -> PathBuf {
std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf())
}
/// Stable trust-store key for one project plugin directory. Decisions are
/// intentionally bound to the directory, not only the mutable manifest name.
fn canonical_plugin_key(path: &Path) -> String {