返回 CodeWhale
extension_toml.rs
根目录 / crates / config / src / extension_toml.rs
1 use serde::{Deserialize, Serialize};
2 use std::collections::BTreeMap;
3 use std::path::PathBuf;
4
5 /// On-disk schema for the `[hook_sinks]` table.
6 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
7 pub struct HookSinksToml {
8 #[serde(default)]
9 pub unix_socket_path: Option<PathBuf>,
10 }
11
12 /// On-disk schema for the `[lifecycle_outbox]` table.
13 ///
14 /// Opt-in lifecycle event outbox: every emitted event is appended as one
15 /// JSONL line to `path` in the `RuntimeEventEnvelope` shape
16 /// (`schema_version, seq, event, kind, thread_id, turn_id, item_id,
17 /// timestamp, payload`), and optionally POSTed to `webhook_url`. An unset or
18 /// empty `path` disables the feature entirely — behavior is unchanged from a
19 /// release without the table.
20 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
21 pub struct LifecycleOutboxToml {
22 /// Path to the JSONL outbox file. Parent directories are created lazily
23 /// on the first event. Unset or empty = feature OFF.
24 #[serde(default)]
25 pub path: Option<PathBuf>,
26 /// Optional webhook URL. Events are POSTed as `{"at", "event"}` JSON
27 /// only when this is set (in addition to, never instead of, `path`).
28 /// Delivery is best-effort: failures are logged and dropped.
29 #[serde(default)]
30 pub webhook_url: Option<String>,
31 /// Optional bearer token sent as `Authorization: Bearer <token>` on
32 /// webhook POSTs. Ignored when `webhook_url` is unset.
33 #[serde(default)]
34 pub webhook_token: Option<String>,
35 }
36
37 /// On-disk schema for the `[control_socket]` table.
38 ///
39 /// Opt-in per-session control surface: when `enabled`, the interactive TUI
40 /// binds a unix domain socket at `<sessions-dir>/<session-id>/control.sock`
41 /// for the running session. The socket speaks newline-framed JSON-RPC with
42 /// the verbs `message`, `interrupt`, and `status`. An absent
43 /// table, or `enabled = false` (the default), disables the feature entirely —
44 /// behavior is unchanged from a release without the table.
45 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
46 pub struct ControlSocketToml {
47 /// Bind the per-session control socket. Default: false (OFF).
48 #[serde(default)]
49 pub enabled: bool,
50 }
51
52 /// On-disk schema for the `[skills]` table (#140). See `config.example.toml`
53 /// for documentation.
54 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
55 pub struct SkillsToml {
56 /// Curated registry index URL. When unset, the TUI falls back to the
57 /// bundled default (community-curated GitHub raw).
58 #[serde(default)]
59 pub registry_url: Option<String>,
60 /// Per-skill maximum *uncompressed* size in bytes. When unset, the TUI
61 /// uses 5 MiB.
62 #[serde(default)]
63 pub max_install_size_bytes: Option<u64>,
64 /// Keys owned by the TUI runtime (for example `scan_codewhale_only`) or
65 /// added by newer releases must survive dispatcher reads and typed saves.
66 #[serde(flatten)]
67 pub extras: BTreeMap<String, toml::Value>,
68 }
69
70 /// On-disk schema for the `[tools]` table (#2076).
71 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
72 pub struct ToolsToml {
73 /// Native tool names to keep loaded outside the default core catalog.
74 #[serde(default)]
75 pub always_load: Vec<String>,
76 /// Runtime-owned tool settings must survive dispatcher reads and saves.
77 /// Their validation belongs to the runtime's ToolsConfig, not this facade.
78 #[serde(flatten)]
79 pub extras: BTreeMap<String, toml::Value>,
80 }
81
82 /// Existing `[workshop]` threshold configuration, retained for compatibility.
83 #[derive(Debug, Clone, Deserialize, Default)]
84 pub struct WorkshopConfig {
85 /// Token threshold above which results become handle-only evidence.
86 #[serde(default)]
87 pub large_output_threshold_tokens: Option<usize>,
88
89 /// Per-tool threshold overrides (tool name → token limit). A tool whose
90 /// name appears here uses this limit instead of
91 /// `large_output_threshold_tokens`.
92 #[serde(default)]
93 pub per_tool_thresholds: Option<std::collections::HashMap<String, usize>>,
94
95 /// Optional model-visible byte budget for a single `read` / `read_file`
96 /// result. Absent keeps the compile-time default (#5367).
97 #[serde(default)]
98 pub read_result_max_bytes: Option<usize>,
99
100 /// Optional model-visible byte budget for a generic tool result after
101 /// spillover. Absent keeps the compile-time default (#5367).
102 #[serde(default)]
103 pub tool_result_max_bytes: Option<usize>,
104 }
105
106 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
107 #[serde(transparent)]
108 pub struct PluginId(pub String);
109
110 impl PluginId {
111 #[must_use]
112 pub fn as_str(&self) -> &str {
113 &self.0
114 }
115 }
116
117 /// Persistable proof of the exact reviewed plugin authority attached to a
118 /// Skill or MCP server. Runtime contexts keep this receipt instead of a
119 /// pointer to mutable process-global discovery state, and revalidate it at
120 /// every side-effect boundary.
121 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122 #[serde(deny_unknown_fields)]
123 pub struct PluginAuthority {
124 pub plugin_id: PluginId,
125 pub plugin_name: String,
126 pub workspace: std::path::PathBuf,
127 pub state_path: std::path::PathBuf,
128 #[serde(default)]
129 pub managed_policy_path: Option<std::path::PathBuf>,
130 #[serde(skip)]
131 pub managed_policy_source: Option<std::path::PathBuf>,
132 pub source_manifest: std::path::PathBuf,
133 pub staged_manifest: std::path::PathBuf,
134 pub content_hash: String,
135 pub capability_hash: String,
136 /// Monotonic generation of this plugin's persisted authority. Any trust,
137 /// enablement, disablement, or revocation transition invalidates receipts
138 /// held by another process immediately, even when hashes are unchanged.
139 pub state_generation: u64,
140 }
141
142 #[derive(Debug, Clone, PartialEq, Eq)]
143 pub struct ProjectHookAuthority {
144 pub workspace: PathBuf,
145 pub digest: String,
146 }
147
148 /// Identity of one activation. `generation` bumps on every (re)activation;
149 /// `owner_token` is 128+ random bits minted by the core and handed over only
150 /// in `ext/activate`. It catches bugs and stale fibers; it is not a boundary
151 /// against a malicious plugin in the same process (see the design, §4.4).
152 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
153 #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
154 #[serde(deny_unknown_fields)]
155 pub struct OwnerRef {
156 pub plugin_id: String,
157 pub generation: u64,
158 pub owner_token: String,
159 }
160
161 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
162 #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
163 pub struct EntryRef {
164 pub path: String,
165 pub sha256: String,
166 }
167
168 impl std::fmt::Display for PluginId {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 f.write_str(&self.0)
171 }
172 }
173
174 /// Host uses the SDK by default; explicit Rust selection remains available.
175 /// A Host refusal never falls back to Rust.
176 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
177 #[serde(rename_all = "lowercase")]
178 pub enum McpBackend {
179 Rust,
180 #[default]
181 Host,
182 }
183
184 /// Return only the non-secret network authority of a configured URL.
185 ///
186 /// Userinfo, path, query keys and values, and fragments are all omitted because
187 /// every one of those components can carry credentials. Parse failures also
188 /// omit the original input rather than echoing an attacker-controlled value.
189 #[must_use]
190 pub fn structural_url_authority(url: &str) -> String {
191 let Some(parsed) = url::Url::parse(url).ok() else {
192 return "unparseable (configured value omitted)".to_string();
193 };
194 let Some(host) = parsed.host_str() else {
195 return "unparseable (configured value omitted)".to_string();
196 };
197 // Url::host_str already includes the brackets around an IPv6 address.
198 let mut authority = format!("{}://{host}", parsed.scheme());
199 if let Some(port) = parsed.port() {
200 authority.push(':');
201 authority.push_str(&port.to_string());
202 }
203 authority
204 }
205
206 /// Default snapshot retention window: 7 days.
207 pub const DEFAULT_SNAPSHOT_MAX_AGE: std::time::Duration =
208 std::time::Duration::from_secs(7 * 24 * 60 * 60);
209
210 /// Default workspace-size ceiling above which snapshots self-disable
211 /// on first use (2 GB of non-excluded content). Reports from users with
212 /// multi-hundred-GB project directories — datasets, model weights,
213 /// docker image dumps that fall outside the built-in excludes —
214 /// surfaced that `git add -A` on first init would hang the TUI for
215 /// minutes-to-hours while indexing the workspace. Snapshots are a
216 /// rollback safety net, not a backup tool; bailing out on workspaces
217 /// that big is the right tradeoff. Users with legitimate large
218 /// monorepos can raise `[snapshots] max_workspace_gb` (or set it to
219 /// `0` to disable the cap entirely).
220 pub const DEFAULT_MAX_WORKSPACE_BYTES_FOR_SNAPSHOT: u64 = 2 * 1024 * 1024 * 1024;
221
222 /// On-disk schema for the `[snapshots]` table (#137). See
223 /// `config.example.toml` for documentation.
224 #[derive(Debug, Clone, Serialize, Deserialize)]
225 pub struct SnapshotsToml {
226 #[serde(default = "default_snapshots_enabled")]
227 pub enabled: bool,
228 #[serde(default = "default_snapshot_max_age_days")]
229 pub max_age_days: u64,
230 /// Keys owned by the TUI runtime (for example `max_workspace_gb`) or
231 /// added by newer releases must survive dispatcher reads and typed saves.
232 #[serde(flatten)]
233 pub extras: BTreeMap<String, toml::Value>,
234 }
235
236 pub fn default_snapshots_enabled() -> bool {
237 true
238 }
239
240 pub(crate) fn default_snapshot_max_age_days() -> u64 {
241 DEFAULT_SNAPSHOT_MAX_AGE.as_secs() / (24 * 60 * 60)
242 }
243
244 impl Default for SnapshotsToml {
245 fn default() -> Self {
246 Self {
247 enabled: default_snapshots_enabled(),
248 max_age_days: default_snapshot_max_age_days(),
249 extras: BTreeMap::new(),
250 }
251 }
252 }
253
253 lines RUST