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
//! # Cortex SDK
//!
//! The official Rust SDK for Cortex's trusted native plugin boundary.
//!
//! This crate defines the public plugin surface with **zero dependency on
//! Cortex internals**. The runtime loads trusted native plugins through a
//! stable C-compatible ABI and bridges these traits to its own turn runtime,
//! command surface, and transport layer.
//!
//! Process-isolated JSON plugins do **not** need this crate. They are defined
//! through `manifest.toml` plus a child-process command. Use `cortex-sdk` when
//! you are building a trusted in-process native plugin that exports
//! `cortex_plugin_init`.
//!
//! SDK release cadence is independent from Cortex runtime releases. Choose the
//! SDK version by the native ABI/DTO surface your plugin needs, not by the
//! latest Cortex runtime patch. Runtime compatibility is declared in the
//! plugin `manifest.toml` `cortex_version` field, which is the minimum Cortex
//! runtime version the plugin supports.
//!
//! ## Architecture
//!
//! ```text
//! ┌──────────────┐ dlopen ┌──────────────────┐
//! │ cortex-runtime│ ──────────────▶ │ your plugin.so │
//! │ (daemon) │ │ cortex-sdk only │
//! └──────┬───────┘ FFI call └────────┬─────────┘
//! │ cortex_plugin_init() │
//! ▼ ▼
//! ToolRegistry ◀─── register ─── MultiToolPlugin
//! ├─ plugin_info()
//! └─ create_tools()
//! ├─ Tool A
//! └─ Tool B
//! ```
//!
//! Plugins are compiled as `cdylib` shared libraries. The runtime calls
//! `cortex_plugin_init`, receives a C-compatible function table, then asks that
//! table for plugin metadata, tool descriptors, and tool execution results.
//! Rust trait objects stay inside the plugin; they never cross the
//! dynamic-library boundary.
//!
//! The SDK exposes a runtime-aware execution surface:
//!
//! - [`InvocationContext`] gives tools stable metadata such as session id,
//! canonical actor, transport/source, and foreground/background scope
//! - [`ToolRuntime`] lets tools emit progress updates and observer text back
//! to the parent turn
//! - [`ToolCapabilities`] lets tools declare whether they emit runtime signals
//! and whether they are background-safe
//! - [`Attachment`] and [`ToolResult::with_media`] let tools return structured
//! image, audio, video, or file outputs without depending on Cortex internals
//! ## Native Plugin Quick Start
//!
//! **Cargo.toml:**
//!
//! ```toml
//! [package]
//! name = "cortex-plugin-native-hello"
//! version = "0.1.0"
//! edition = "2024"
//! publish = false
//!
//! [lib]
//! crate-type = ["cdylib", "rlib"]
//!
//! [dependencies]
//! cortex-sdk = "1.6.10"
//! serde_json = "1"
//! ```
//!
//! **src/lib.rs:**
//!
//! ```text
//! use cortex_sdk::prelude::*;
//!
//! #[derive(Default)]
//! struct MyPlugin;
//!
//! impl MultiToolPlugin for MyPlugin {
//! fn plugin_info(&self) -> PluginInfo {
//! PluginInfo {
//! name: "my-plugin".into(),
//! version: env!("CARGO_PKG_VERSION").into(),
//! description: "My custom tools for Cortex".into(),
//! }
//! }
//!
//! fn create_tools(&self) -> Vec<Box<dyn Tool>> {
//! vec![Box::new(WordCountTool)]
//! }
//! }
//!
//! struct WordCountTool;
//!
//! impl Tool for WordCountTool {
//! fn name(&self) -> &'static str { "word_count" }
//!
//! fn description(&self) -> &'static str {
//! "Count words in a text string. Use when the user asks for word \
//! counts, statistics, or text length metrics."
//! }
//!
//! fn input_schema(&self) -> serde_json::Value {
//! serde_json::json!({
//! "type": "object",
//! "properties": {
//! "text": {
//! "type": "string",
//! "description": "The text to count words in"
//! }
//! },
//! "required": ["text"]
//! })
//! }
//!
//! fn execute(&self, input: serde_json::Value) -> Result<ToolResult, ToolError> {
//! let text = input["text"]
//! .as_str()
//! .ok_or_else(|| ToolError::InvalidInput("missing 'text' field".into()))?;
//! let count = text.split_whitespace().count();
//! Ok(ToolResult::success(format!("{count} words")))
//! }
//! }
//!
//! cortex_sdk::export_plugin!(MyPlugin);
//! ```
//!
//! Tools that need runtime context can override
//! [`Tool::execute_with_runtime`] instead of only [`Tool::execute`].
//!
//! **manifest.toml:**
//!
//! ```toml
//! name = "native-hello"
//! version = "0.1.0"
//! description = "Example trusted native Cortex plugin"
//! cortex_version = "1.6.10"
//! trust = "trusted_native"
//!
//! [capabilities]
//! provides = ["tools"]
//! secrets = false
//!
//! [sandbox]
//! level = "trusted_in_process"
//!
//! [native]
//! library = "lib/libcortex_plugin_native_hello.so"
//! isolation = "trusted_in_process"
//! abi_version = 1
//! ```
//!
//! ## Build, Sign, Pack, Publish
//!
//! ```bash
//! cargo build --release
//! cortex plugin review .
//! cortex plugin test .
//! cortex plugin keygen ~/.config/cortex/plugin-signing/example-dev.ed25519
//! cortex plugin sign . --key ~/.config/cortex/plugin-signing/example-dev.ed25519 --publisher example.dev
//! cortex plugin pack .
//! sha256sum cortex-plugin-native-hello-v0.1.0-linux-amd64.cpx > cortex-plugin-native-hello-v0.1.0-linux-amd64.cpx.sha256
//! ```
//!
//! Upload the `.cpx` and `.sha256` files to a GitHub Release. Users install the
//! package by repository name and restart the daemon so the native library is
//! loaded:
//!
//! ```bash
//! cortex plugin install owner/cortex-plugin-native-hello@0.1.0
//! cortex restart
//! ```
//!
//! Installing or replacing a trusted native shared library still requires a
//! daemon restart so the new code is loaded. Process-isolated plugin manifest
//! changes hot-apply without that restart.
//!
//! ## Plugin Lifecycle
//!
//! 1. **Load** — `dlopen` at daemon startup
//! 2. **Create** — runtime calls `export_plugin!`-generated stable ABI init
//! 3. **Register** — [`MultiToolPlugin::create_tools`] is called once; each
//! [`Tool`] is registered in the global tool registry
//! 4. **Execute** — the LLM invokes tools by name during turns; the runtime
//! calls [`Tool::execute`] with JSON parameters
//! 5. **Retain** — the library handle is held for the daemon's lifetime;
//! `Drop` runs only at shutdown
//!
//! ## Tool Design Guidelines
//!
//! - **`name`**: lowercase with underscores (`word_count`, not `WordCount`).
//! Must be unique across all tools in the registry.
//! - **`description`**: written for the LLM — explain what the tool does,
//! when to use it, and when *not* to use it. The LLM reads this to decide
//! whether to call the tool.
//! - **`input_schema`**: a [JSON Schema](https://json-schema.org/) object
//! describing the parameters. The LLM generates JSON matching this schema.
//! - **`execute`**: receives the LLM-generated JSON. Return
//! [`ToolResult::success`] for normal output or [`ToolResult::error`] for
//! recoverable errors the LLM should see. Return [`ToolError`] only for
//! unrecoverable failures (invalid input, missing deps).
//! - **Media output**: attach files with [`ToolResult::with_media`]. Cortex
//! delivers attachments through the active transport; plugins should not call
//! channel-specific APIs directly.
//! - **`execute_with_runtime`**: use this when the tool needs invocation
//! metadata or wants to emit progress / observer updates during execution.
//! - **`timeout_secs`**: optional per-tool timeout override. If `None`, the
//! global `[turn].tool_timeout_secs` applies.
use ;
pub use serde_json;
pub use ;
pub use ;
pub use ;
/// Version of the SDK crate used by native plugin builds.
pub const SDK_VERSION: &str = env!;
/// Stable native ABI version for trusted in-process plugins.
///
/// The runtime never exchanges Rust trait objects across the dynamic-library
/// boundary. It loads a C-compatible function table through `cortex_plugin_init`
/// and moves structured values as UTF-8 JSON buffers.
pub const NATIVE_ABI_VERSION: u32 = 1;
/// Stable multimedia attachment DTO exposed to plugins.
///
/// This type intentionally lives in `cortex-sdk` instead of depending on
/// Cortex internal crates, so plugin authors only need the SDK.
/// Whether a tool invocation belongs to a user-visible foreground turn or a
/// background maintenance execution.
/// Stable runtime metadata exposed to plugin tools during execution.
///
/// This intentionally exposes the execution surface, not Cortex internals.
// ── Export Macro ────────────────────────────────────────────
/// Generate the stable native ABI entry point for a [`MultiToolPlugin`].
///
/// This macro expands to an `extern "C"` function named `cortex_plugin_init`
/// that fills a C-compatible function table. The plugin type must implement
/// [`Default`].
///
/// # Usage
///
/// `cortex_sdk::export_plugin!(MyPlugin);`
///
/// # Expansion
///
/// The macro constructs the Rust plugin internally and exposes it through the
/// stable native ABI table. Rust trait objects never cross the dynamic-library
/// boundary.