[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7529GA0MJE8WC0AABMQGVM0":3,"skill-same:01M7529GA0MJE8WC0AABMQGVM0":53},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7529GA0MJE8WC0AABMQGVM0","rust-coding-skill",null,"Use this skill whenever editing `*.rs` files in the `rust\u002F` SDK in order to write idiomatic, efficient, well-structured Rust code","review-bench\u002Fgithub_copilot-sdk","review-bench","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F286778065?v=4","01M7517F9NTEPDZDAXJBR30FWT","ReviewBench","01M7528XAPJMCHT2F9YHNWHYXT",0,"MIT","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Fgithub_copilot-sdk\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Frust-coding-skill\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: rust-coding-skill\ndescription: \"Use this skill whenever editing `*.rs` files in the `rust\u002F` SDK in order to write idiomatic, efficient, well-structured Rust code\"\n---\n\n# Rust Coding Skill\n\nOpinionated Rust rules for the Copilot Rust SDK (`rust\u002F`). Priority order:\n\n1. **Readable code** — every line should earn its place\n2. **Correct code** — especially in concurrent\u002Fasync contexts\n3. **Performant code** — think about allocations, data structures, hot paths\n\n## Error handling\n\nThe SDK's public error type is `crate::Error` (`rust\u002Fsrc\u002Ferror.rs`). Add new\nvariants there rather than introducing parallel error enums per module — every\npublic failure mode is part of the API contract and should be expressible in one\ntype. Internal modules can use `thiserror` enums when a richer local taxonomy\nhelps; convert at the boundary.\n\n`anyhow` is reserved for binaries and example code. Library code never returns\n`anyhow::Result` — callers can't pattern-match on `anyhow::Error`, so it would\nprevent them from handling specific failures.\n\nIn production code, prefer `?`, `let-else`, and `if let`. Reach for `expect(\"…\")`\nwhen an invariant cannot fail and the message would help debug a future\nregression. `unwrap()` belongs in tests only — Clippy enforces this in the SDK\nvia `#![cfg_attr(test, allow(clippy::unwrap_used))]` in `lib.rs`.\n\nWhen you need to log on the way through, prefer\n`.inspect_err(|e| warn!(error = ?e, \"context\"))?` over a `match` that logs and\nre-wraps. It reads top-to-bottom and keeps the happy path uncluttered.\n\n## Async and concurrency\n\nThe default for request-scoped I\u002FO is `async fn` plus `.await` — futures\ninherit cancellation from their parent task and can borrow local references.\nReach for `tokio::spawn` only when you genuinely need background work (an event\nloop, a long-lived watcher) and track the `JoinHandle` so you can cancel or join\nit on shutdown. Fire-and-forget spawns silently swallow panics and outlive the\nsession; don't.\n\nBlocking calls (filesystem, subprocess wait) belong in\n`tokio::task::spawn_blocking`, *not* on the async runtime. The blocking pool is\nbounded, so for genuinely long-lived workers (think: file watchers that run for\nthe lifetime of a session) prefer `std::thread::spawn` with a channel back into\nasync land.\n\nLock choice matters. `tokio::sync::Mutex` is correct when you must hold the\nguard across `.await`; `parking_lot::Mutex` (or `RwLock`) is faster on hot\nsynchronous paths and is what `session.rs` uses for capability state.\n`std::sync::Mutex` is rarely the right answer in this crate — its poisoning\nsemantics buy us nothing and it's slower than `parking_lot`. Never hold a\n`std::sync::Mutex` guard across an `.await`; Clippy will catch this, but the\nfix is to move the await out, not silence the lint.\n\nFor lazy statics use `std::sync::LazyLock`. The `once_cell` crate is no longer\nneeded.\n\n## Traits and conversions\n\nPlain functions on a type beat traits for navigability. Use them as the default.\n\n**Trait-based extension points are different.** When a consumer must plug behaviour into the SDK, prefer one trait with one default-impl method per event over per-event `Box\u003Cdyn Fn>` callback fields. This is what `tower_lsp::LanguageServer`, `rmcp::ServerHandler`, and `notify::EventHandler` do — the dominant idiom in async Rust for \"wire-protocol handler\" traits. Callback fields fight `Send + Sync + 'static`, fragment consumer state across closures, and skip exhaustiveness checks.\n\nThe four extension-point traits in this crate:\n\n- **`SessionHandler`** (`rust\u002Fsrc\u002Fhandler.rs`) — per-event methods (`on_permission_request`, `on_user_input`, `on_external_tool`, `on_elicitation`, `on_exit_plan_mode`, `on_auto_mode_switch`, `on_session_event`) each with a default impl. The dispatcher `on_event(HandlerEvent)` is itself a default method that fans out to them; override per-event methods in normal use, override `on_event` only when you want a single exhaustive match. Concurrent invocations are possible (notification-triggered events run on spawned tasks), so `Send + Sync + 'static` is required on the trait.\n- **`SessionHooks`** (`rust\u002Fsrc\u002Fhooks.rs`) — optional lifecycle callbacks. The SDK auto-enables hooks when an impl is supplied to `create_session` \u002F `resume_session`.\n- **`SystemMessageTransform`** (`rust\u002Fsrc\u002Fsystem_message.rs`) — declare `section_ids()` and return content from `transform_section()`.\n- **`ToolHandler`** (`rust\u002Fsrc\u002Ftool.rs`) — client-side tool implementations, dispatched by name via `ToolHandlerRouter`.\n\n`ApproveAllHandler` is the standard test handler for `SessionHandler`.\n\n**Don't add traits without a clear extension story.** Don't implement `From`\u002F`Into` for SDK-internal conversions: they can't take extra parameters, can't return `Result`, and hide which conversion is happening at call sites. Prefer named methods like `to_info(&self)` or `MyType::from_record(record, ctx)`.\n\nTrivial field re-shaping is best inlined. Closures should stay short (under ~10 lines); extract to named functions when they grow. Visitor patterns are a closure-fest — expose `iter()` and let the consumer drive.\n\n## Concurrency primitives\n\n**Channels, not callback closures, for event flow.** Closures fight `Send + Sync + 'static` and don't compose with `select!`. Channel choice by semantics:\n\n| Use case | Primitive |\n|---|---|\n| One producer → one consumer with backpressure | `tokio::sync::mpsc` (cap 1) or `tokio::sync::oneshot` for single value |\n| Many producers → one consumer | `tokio::sync::mpsc` |\n| One producer → many consumers, every event delivered (pub\u002Fsub) | `tokio::sync::broadcast` |\n| One producer → many consumers, only the latest value matters | `tokio::sync::watch` |\n\nFor the **public** API, prefer returning `impl Stream\u003CItem = Event>` (wrap a `broadcast::Receiver` in `tokio_stream::wrappers::BroadcastStream`). `Stream` composes with `select!`, `take`, `map`, `filter`, `timeout`. See `EventSubscription` and `LifecycleSubscription`.\n\n**Cancellation: drop is the primitive; `tokio_util::sync::CancellationToken` for SDK-internal task coordination.**\n\n- **Caller-owned futures** (`send_message`, subscription streams): drop \u002F `select!` \u002F `tokio::time::timeout`. Don't accept a token parameter — it duplicates what `select!` already provides. Document cancel-safety on every `.await` in the hot path.\n- **SDK-internal tasks** (event loops, subprocess readers, anything `tokio::spawn`ed by the SDK): use `CancellationToken` stored on the long-lived handle. `Drop` calls `cancel()`. `Session::cancellation_token()` exposes a child token so callers can bind external work to the session lifetime.\n\nRefs: [`CancellationToken`][ctoken] · [`tonic` example][tonic-cancel] · [withoutboats: async clean-up][wb-cleanup] · [Cybernetist: cancellation patterns][cybernetist].\n\n[ctoken]: https:\u002F\u002Fdocs.rs\u002Ftokio-util\u002Flatest\u002Ftokio_util\u002Fsync\u002Fstruct.CancellationToken.html\n[tonic-cancel]: https:\u002F\u002Fgithub.com\u002Fhyperium\u002Ftonic\u002Fblob\u002Fmaster\u002Fexamples\u002Fsrc\u002Fcancellation\u002Fserver.rs\n[wb-cleanup]: https:\u002F\u002Fwithout.boats\u002Fblog\u002Fasynchronous-clean-up\u002F\n[cybernetist]: https:\u002F\u002Fcybernetist.com\u002F2024\u002F04\u002F19\u002Frust-tokio-task-cancellation-patterns\u002F\n\n## Optional fields and serde\n\nUse `Option\u003CT>` for optional fields, not nullable references or sentinel values. Defaults come from `Default` impls. Pair with `#[non_exhaustive]` on public config structs and a builder so adding fields stays non-breaking.\n\nFor required builder fields: prefer `build() -> Result\u003CSelf, BuildError>` over typestate unless required-field count is tiny (1-2).\n\nJSON: `#[serde(rename_all = \"camelCase\")]` at the type level, per-field `#[serde(rename = \"…\")]` for outliers, `#[serde(skip_serializing_if = \"Option::is_none\")]` for output, `#[serde(default)]` for input tolerance. Reach for `serde_with` only for non-trivial transforms (durations, base64, numeric-as-string keys).\n\n## Tracing — `#[tracing::instrument]` is banned\n\nBanned via `clippy.toml`. Use manual spans with `error_span!`:\n\n- **Almost always use `error_span!`**, not `info_span!`. Span level controls\n  the *minimum* filter at which the span appears. An `info_span` disappears when\n  the filter is `warn` or `error` — taking all child events with it, even\n  errors. `error_span!` ensures the span is always present.\n- **Spawned tasks lose parent context.** Attach a span with `.instrument()` or\n  events inside won't correlate.\n- **Never hold `span.enter()` guards across `.await`** — use `.instrument(span)`\n  instead (also enforced by Clippy).\n\n```rust\nuse tracing::Instrument;\n\nasync fn send_message(&self, session_id: &str, prompt: &str) -> Result\u003C(), Error> {\n    let span = tracing::error_span!(\"send_message\", session_id = %session_id);\n    async { \u002F* body *\u002F }.instrument(span).await\n}\n\nlet span = tracing::error_span!(\"event_loop\", session_id = %id);\ntokio::spawn(async move { run_loop().await }.instrument(span));\n```\n\nLog with structured fields: `info!(session_id = %id, \"Session created\")`.\nStatic messages stay greppable; dynamic data goes in named fields, not\ninterpolated into the message string.\n\n## Idioms that don't port from other languages\n\nWhen porting from Node, Python, Go, or .NET: see the **Concurrency primitives** and **Traits and conversions** sections above. The two patterns that most reliably translate poorly are (1) per-event `Box\u003Cdyn Fn>` callback fields — use a trait with default-impl methods (the `tower_lsp::LanguageServer` \u002F `rmcp::ServerHandler` \u002F `notify::EventHandler` shape) — and (2) plumbing `context.Context` \u002F `CancellationToken` through every call site — drop-cancel for caller-owned futures, `tokio_util::sync::CancellationToken` for SDK-internal tasks.\n\n## Code organization\n\n- **Public API:** every `pub` item in the crate is part of the SDK's contract.\n  Adding a field to a `pub struct` is a breaking change unless the struct is\n  `#[non_exhaustive]` or constructors hide field-by-field literals. Prefer\n  `Default + ..Default::default()` patterns and document new fields with\n  rustdoc.\n- **Generated code lives in `rust\u002Fsrc\u002Fgenerated\u002F`** and must not be\n  hand-edited. Regenerate with `cd scripts\u002Fcodegen && npm run generate:rust`.\n  When a generated type lacks a field the schema doesn't yet describe (e.g.\n  `Tool::overrides_built_in_tool`), hand-author the user-facing type in\n  `rust\u002Fsrc\u002Ftypes.rs` and stop re-exporting the generated one.\n- **`#[expect(dead_code)]`** instead of `#[allow(dead_code)]` on individual\n  fields — it forces a cleanup once the field gets used.\n- **`..Default::default()`** — avoid in production code (be explicit about\n  which fields you're setting); prefer it in tests and doc examples to keep\n  the focus on the values that matter for the test.\n- **Import grouping** — three blocks separated by blank lines:\n  (1) `std`\u002F`core`\u002F`alloc`, (2) external crates, (3)\n  `crate::`\u002F`super::`\u002F`self::`. Enforced by nightly `cargo fmt` via\n  `rust\u002F.rustfmt.nightly.toml`.\n- **`pub(crate)` vs `pub`** — most modules in `lib.rs` are private (`mod`), so\n  `pub` items inside them are already crate-private. Use `pub(crate)` only when\n  you want to be explicit that an item must not become part of the public API.\n\n## Testing\n\n- **No mock testing.** Depend on real implementations, spin up lightweight\n  versions (e.g. `MockServer` in tests), or restructure code so the logic\n  under test takes its dependency's output as input.\n- `assert_eq!(actual, expected)` — actual first, for readable diffs.\n- Tests at end of file: `#[cfg(test)] mod tests`. Never place production code\n  after the test module.\n- Keep tests concurrent-safe — unique temp dirs (`tempfile::tempdir()`),\n  unique data, no global state.\n- `ApproveAllHandler` is the standard test handler for sessions that don't\n  exercise permission logic — see `rust\u002Fsrc\u002Fhandler.rs:174`.\n\n## Cross-platform\n\nThe SDK ships on macOS, Windows, and Linux; CI exercises all three. Construct\npaths with `Path::join` rather than string concatenation — `\u002F` and `\\` are not\ninterchangeable, and string equality breaks on Windows UNC paths. Log paths\nwith `path.display()`; serialize with `to_string_lossy()` only when you need a\n`String`.\n\nProcess spawning needs care. The SDK applies `CREATE_NO_WINDOW` on Windows\nwhen launching the CLI (see `Client::build_command`); preserve that if you\ntouch process spawning. Subprocess stdout often contains `\\r` on Windows — strip\nor split on `\\r?\\n` rather than assuming `\\n`.\n\nTests must use `tempfile::tempdir()`, never hardcoded `\u002Ftmp\u002F`, and any test\nthat asserts on a path string needs to normalize separators or use\n`std::path::MAIN_SEPARATOR`.\n\n## Build speed\n\nSpecify Tokio features explicitly — never `features = [\"full\"]`. Iterate with\n`cargo check`; reach for `cargo build` only when you need the binary. Audit\nnew dependency feature flags with `cargo tree` before committing.\n\n## Comments\n\nExplain **why**, never **what**. No comments that restate code. No decorative\nbanners (`\u002F\u002F ── Section ────────`).\n\n**Never compare to other SDKs in code comments or rustdoc.** Don't write\n\"Mirrors Node's `Foo`\", \"Like Go's `Bar`\", \"Unlike Python's `Baz`\", or include\nfile\u002Fline citations into other SDKs (`nodejs\u002Fsrc\u002Ftypes.ts:1592`, `go\u002Ftypes.go:14`).\nThe Rust SDK seeks parity with the Node, Python, Go, and .NET SDKs, and that\nfact is stated once at the top of `rust\u002FREADME.md`. Intentional divergences\nlive in the README's \"Differences From Other SDKs\" section. Repeating the\nrelationship per-symbol is unscalable, drifts as the other SDKs evolve, and\nadds noise to consumer-facing rustdoc — Rust users care about the Rust API,\nnot its lineage. Self-references within the Rust crate (e.g. \"Mirrors\n[`from_streams`] but adds…\") are fine.\n\n## Toolchain\n\nThe SDK is pinned to `rust 1.94.0` via `rust\u002Frust-toolchain.toml`. Formatting\nuses nightly (`nightly-2026-04-14`) so unstable rustfmt options like grouped\nimports work — see `rust\u002F.rustfmt.nightly.toml`. CI runs:\n\n```bash\ncd rust\ncargo +nightly-2026-04-14 fmt --check\ncargo clippy --all-features --all-targets -- -D warnings\ncargo test --all-features\n```\n\nMatch those exact commands locally before pushing.\n\n## Codegen\n\nJSON-RPC and session-event types are generated from the Copilot CLI schema:\n\n| Source | Output |\n|---|---|\n| `nodejs\u002Fnode_modules\u002F@github\u002Fcopilot\u002Fschemas\u002Fapi.schema.json` | `rust\u002Fsrc\u002Fgenerated\u002Fapi_types.rs` |\n| `nodejs\u002Fnode_modules\u002F@github\u002Fcopilot\u002Fschemas\u002Fsession-events.schema.json` | `rust\u002Fsrc\u002Fgenerated\u002Fsession_events.rs` |\n\nRegenerate with:\n\n```bash\ncd scripts\u002Fcodegen && npm run generate:rust\n```\n\nNever hand-edit files under `rust\u002Fsrc\u002Fgenerated\u002F`. If a generated type needs a\nfield the schema lacks, hand-author the user-facing type in `rust\u002Fsrc\u002Ftypes.rs`\nand stop re-exporting the generated one.\n","# Rust Coding Skill\n\nOpinionated Rust rules for the Copilot Rust SDK (`rust\u002F`). Priority order:\n\n1. **Readable code** — every line should earn its place\n2. **Correct code** — especially in concurrent\u002Fasync contexts\n3. **Performant code** — think about allocations, data structures, hot paths\n\n## Error handling\n\nThe SDK's public error type is `crate::Error` (`rust\u002Fsrc\u002Ferror.rs`). Add new\nvariants there rather than introducing parallel error enums per module — every\npublic failure mode is part of the API contract and should be expressible in one\ntype. Internal modules can use `thiserror` enums when a richer local taxonomy\nhelps; convert at the boundary.\n\n`anyhow` is reserved for binaries and example code. Library code never returns\n`anyhow::Result` — callers can't pattern-match on `anyhow::Error`, so it would\nprevent them from handling specific failures.\n\nIn production code, prefer `?`, `let-else`, and `if let`. Reach for `expect(\"…\")`\nwhen an invariant cannot fail and the message would help debug a future\nregression. `unwrap()` belongs in tests only — Clippy enforces this in the SDK\nvia `#![cfg_attr(test, allow(clippy::unwrap_used))]` in `lib.rs`.\n\nWhen you need to log on the way through, prefer\n`.inspect_err(|e| warn!(error = ?e, \"context\"))?` over a `match` that logs and\nre-wraps. It reads top-to-bottom and keeps the happy path uncluttered.\n\n## Async and concurrency\n\nThe default for request-scoped I\u002FO is `async fn` plus `.await` — futures\ninherit cancellation from their parent task and can borrow local references.\nReach for `tokio::spawn` only when you genuinely need background work (an event\nloop, a long-lived watcher) and track the `JoinHandle` so you can cancel or join\nit on shutdown. Fire-and-forget spawns silently swallow panics and outlive the\nsession; don't.\n\nBlocking calls (filesystem, subprocess wait) belong in\n`tokio::task::spawn_blocking`, *not* on the async runtime. The blocking pool is\nbounded, so for genuinely long-lived workers (think: file watchers that run for\nthe lifetime of a session) prefer `std::thread::spawn` with a channel back into\nasync land.\n\nLock choice matters. `tokio::sync::Mutex` is correct when you must hold the\nguard across `.await`; `parking_lot::Mutex` (or `RwLock`) is faster on hot\nsynchronous paths and is what `session.rs` uses for capability state.\n`std::sync::Mutex` is rarely the right answer in this crate — its poisoning\nsemantics buy us nothing and it's slower than `parking_lot`. Never hold a\n`std::sync::Mutex` guard across an `.await`; Clippy will catch this, but the\nfix is to move the await out, not silence the lint.\n\nFor lazy statics use `std::sync::LazyLock`. The `once_cell` crate is no longer\nneeded.\n\n## Traits and conversions\n\nPlain functions on a type beat traits for navigability. Use them as the default.\n\n**Trait-based extension points are different.** When a consumer must plug behaviour into the SDK, prefer one trait with one default-impl method per event over per-event `Box\u003Cdyn Fn>` callback fields. This is what `tower_lsp::LanguageServer`, `rmcp::ServerHandler`, and `notify::EventHandler` do — the dominant idiom in async Rust for \"wire-protocol handler\" traits. Callback fields fight `Send + Sync + 'static`, fragment consumer state across closures, and skip exhaustiveness checks.\n\nThe four extension-point traits in this crate:\n\n- **`SessionHandler`** (`rust\u002Fsrc\u002Fhandler.rs`) — per-event methods (`on_permission_request`, `on_user_input`, `on_external_tool`, `on_elicitation`, `on_exit_plan_mode`, `on_auto_mode_switch`, `on_session_event`) each with a default impl. The dispatcher `on_event(HandlerEvent)` is itself a default method that fans out to them; override per-event methods in normal use, override `on_event` only when you want a single exhaustive match. Concurrent invocations are possible (notification-triggered events run on spawned tasks), so `Send + Sync + 'static` is required on the trait.\n- **`SessionHooks`** (`rust\u002Fsrc\u002Fhooks.rs`) — optional lifecycle callbacks. The SDK auto-enables hooks when an impl is supplied to `create_session` \u002F `resume_session`.\n- **`SystemMessageTransform`** (`rust\u002Fsrc\u002Fsystem_message.rs`) — declare `section_ids()` and return content from `transform_section()`.\n- **`ToolHandler`** (`rust\u002Fsrc\u002Ftool.rs`) — client-side tool implementations, dispatched by name via `ToolHandlerRouter`.\n\n`ApproveAllHandler` is the standard test handler for `SessionHandler`.\n\n**Don't add traits without a clear extension story.** Don't implement `From`\u002F`Into` for SDK-internal conversions: they can't take extra parameters, can't return `Result`, and hide which conversion is happening at call sites. Prefer named methods like `to_info(&self)` or `MyType::from_record(record, ctx)`.\n\nTrivial field re-shaping is best inlined. Closures should stay short (under ~10 lines); extract to named functions when they grow. Visitor patterns are a closure-fest — expose `iter()` and let the consumer drive.\n\n## Concurrency primitives\n\n**Channels, not callback closures, for event flow.** Closures fight `Send + Sync + 'static` and don't compose with `select!`. Channel choice by semantics:\n\n| Use case | Primitive |\n|---|---|\n| One producer → one consumer with backpressure | `tokio::sync::mpsc` (cap 1) or `tokio::sync::oneshot` for single value |\n| Many producers → one consumer | `tokio::sync::mpsc` |\n| One producer → many consumers, every event delivered (pub\u002Fsub) | `tokio::sync::broadcast` |\n| One producer → many consumers, only the latest value matters | `tokio::sync::watch` |\n\nFor the **public** API, prefer returning `impl Stream\u003CItem = Event>` (wrap a `broadcast::Receiver` in `tokio_stream::wrappers::BroadcastStream`). `Stream` composes with `select!`, `take`, `map`, `filter`, `timeout`. See `EventSubscription` and `LifecycleSubscription`.\n\n**Cancellation: drop is the primitive; `tokio_util::sync::CancellationToken` for SDK-internal task coordination.**\n\n- **Caller-owned futures** (`send_message`, subscription streams): drop \u002F `select!` \u002F `tokio::time::timeout`. Don't accept a token parameter — it duplicates what `select!` already provides. Document cancel-safety on every `.await` in the hot path.\n- **SDK-internal tasks** (event loops, subprocess readers, anything `tokio::spawn`ed by the SDK): use `CancellationToken` stored on the long-lived handle. `Drop` calls `cancel()`. `Session::cancellation_token()` exposes a child token so callers can bind external work to the session lifetime.\n\nRefs: [`CancellationToken`][ctoken] · [`tonic` example][tonic-cancel] · [withoutboats: async clean-up][wb-cleanup] · [Cybernetist: cancellation patterns][cybernetist].\n\n[ctoken]: https:\u002F\u002Fdocs.rs\u002Ftokio-util\u002Flatest\u002Ftokio_util\u002Fsync\u002Fstruct.CancellationToken.html\n[tonic-cancel]: https:\u002F\u002Fgithub.com\u002Fhyperium\u002Ftonic\u002Fblob\u002Fmaster\u002Fexamples\u002Fsrc\u002Fcancellation\u002Fserver.rs\n[wb-cleanup]: https:\u002F\u002Fwithout.boats\u002Fblog\u002Fasynchronous-clean-up\u002F\n[cybernetist]: https:\u002F\u002Fcybernetist.com\u002F2024\u002F04\u002F19\u002Frust-tokio-task-cancellation-patterns\u002F\n\n## Optional fields and serde\n\nUse `Option\u003CT>` for optional fields, not nullable references or sentinel values. Defaults come from `Default` impls. Pair with `#[non_exhaustive]` on public config structs and a builder so adding fields stays non-breaking.\n\nFor required builder fields: prefer `build() -> Result\u003CSelf, BuildError>` over typestate unless required-field count is tiny (1-2).\n\nJSON: `#[serde(rename_all = \"camelCase\")]` at the type level, per-field `#[serde(rename = \"…\")]` for outliers, `#[serde(skip_serializing_if = \"Option::is_none\")]` for output, `#[serde(default)]` for input tolerance. Reach for `serde_with` only for non-trivial transforms (durations, base64, numeric-as-string keys).\n\n## Tracing — `#[tracing::instrument]` is banned\n\nBanned via `clippy.toml`. Use manual spans with `error_span!`:\n\n- **Almost always use `error_span!`**, not `info_span!`. Span level controls\n  the *minimum* filter at which the span appears. An `info_span` disappears when\n  the filter is `warn` or `error` — taking all child events with it, even\n  errors. `error_span!` ensures the span is always present.\n- **Spawned tasks lose parent context.** Attach a span with `.instrument()` or\n  events inside won't correlate.\n- **Never hold `span.enter()` guards across `.await`** — use `.instrument(span)`\n  instead (also enforced by Clippy).\n\n```rust\nuse tracing::Instrument;\n\nasync fn send_message(&self, session_id: &str, prompt: &str) -> Result\u003C(), Error> {\n    let span = tracing::error_span!(\"send_message\", session_id = %session_id);\n    async { \u002F* body *\u002F }.instrument(span).await\n}\n\nlet span = tracing::error_span!(\"event_loop\", session_id = %id);\ntokio::spawn(async move { run_loop().await }.instrument(span));\n```\n\nLog with structured fields: `info!(session_id = %id, \"Session created\")`.\nStatic messages stay greppable; dynamic data goes in named fields, not\ninterpolated into the message string.\n\n## Idioms that don't port from other languages\n\nWhen porting from Node, Python, Go, or .NET: see the **Concurrency primitives** and **Traits and conversions** sections above. The two patterns that most reliably translate poorly are (1) per-event `Box\u003Cdyn Fn>` callback fields — use a trait with default-impl methods (the `tower_lsp::LanguageServer` \u002F `rmcp::ServerHandler` \u002F `notify::EventHandler` shape) — and (2) plumbing `context.Context` \u002F `CancellationToken` through every call site — drop-cancel for caller-owned futures, `tokio_util::sync::CancellationToken` for SDK-internal tasks.\n\n## Code organization\n\n- **Public API:** every `pub` item in the crate is part of the SDK's contract.\n  Adding a field to a `pub struct` is a breaking change unless the struct is\n  `#[non_exhaustive]` or constructors hide field-by-field literals. Prefer\n  `Default + ..Default::default()` patterns and document new fields with\n  rustdoc.\n- **Generated code lives in `rust\u002Fsrc\u002Fgenerated\u002F`** and must not be\n  hand-edited. Regenerate with `cd scripts\u002Fcodegen && npm run generate:rust`.\n  When a generated type lacks a field the schema doesn't yet describe (e.g.\n  `Tool::overrides_built_in_tool`), hand-author the user-facing type in\n  `rust\u002Fsrc\u002Ftypes.rs` and stop re-exporting the generated one.\n- **`#[expect(dead_code)]`** instead of `#[allow(dead_code)]` on individual\n  fields — it forces a cleanup once the field gets used.\n- **`..Default::default()`** — avoid in production code (be explicit about\n  which fields you're setting); prefer it in tests and doc examples to keep\n  the focus on the values that matter for the test.\n- **Import grouping** — three blocks separated by blank lines:\n  (1) `std`\u002F`core`\u002F`alloc`, (2) external crates, (3)\n  `crate::`\u002F`super::`\u002F`self::`. Enforced by nightly `cargo fmt` via\n  `rust\u002F.rustfmt.nightly.toml`.\n- **`pub(crate)` vs `pub`** — most modules in `lib.rs` are private (`mod`), so\n  `pub` items inside them are already crate-private. Use `pub(crate)` only when\n  you want to be explicit that an item must not become part of the public API.\n\n## Testing\n\n- **No mock testing.** Depend on real implementations, spin up lightweight\n  versions (e.g. `MockServer` in tests), or restructure code so the logic\n  under test takes its dependency's output as input.\n- `assert_eq!(actual, expected)` — actual first, for readable diffs.\n- Tests at end of file: `#[cfg(test)] mod tests`. Never place production code\n  after the test module.\n- Keep tests concurrent-safe — unique temp dirs (`tempfile::tempdir()`),\n  unique data, no global state.\n- `ApproveAllHandler` is the standard test handler for sessions that don't\n  exercise permission logic — see `rust\u002Fsrc\u002Fhandler.rs:174`.\n\n## Cross-platform\n\nThe SDK ships on macOS, Windows, and Linux; CI exercises all three. Construct\npaths with `Path::join` rather than string concatenation — `\u002F` and `\\` are not\ninterchangeable, and string equality breaks on Windows UNC paths. Log paths\nwith `path.display()`; serialize with `to_string_lossy()` only when you need a\n`String`.\n\nProcess spawning needs care. The SDK applies `CREATE_NO_WINDOW` on Windows\nwhen launching the CLI (see `Client::build_command`); preserve that if you\ntouch process spawning. Subprocess stdout often contains `\\r` on Windows — strip\nor split on `\\r?\\n` rather than assuming `\\n`.\n\nTests must use `tempfile::tempdir()`, never hardcoded `\u002Ftmp\u002F`, and any test\nthat asserts on a path string needs to normalize separators or use\n`std::path::MAIN_SEPARATOR`.\n\n## Build speed\n\nSpecify Tokio features explicitly — never `features = [\"full\"]`. Iterate with\n`cargo check`; reach for `cargo build` only when you need the binary. Audit\nnew dependency feature flags with `cargo tree` before committing.\n\n## Comments\n\nExplain **why**, never **what**. No comments that restate code. No decorative\nbanners (`\u002F\u002F ── Section ────────`).\n\n**Never compare to other SDKs in code comments or rustdoc.** Don't write\n\"Mirrors Node's `Foo`\", \"Like Go's `Bar`\", \"Unlike Python's `Baz`\", or include\nfile\u002Fline citations into other SDKs (`nodejs\u002Fsrc\u002Ftypes.ts:1592`, `go\u002Ftypes.go:14`).\nThe Rust SDK seeks parity with the Node, Python, Go, and .NET SDKs, and that\nfact is stated once at the top of `rust\u002FREADME.md`. Intentional divergences\nlive in the README's \"Differences From Other SDKs\" section. Repeating the\nrelationship per-symbol is unscalable, drifts as the other SDKs evolve, and\nadds noise to consumer-facing rustdoc — Rust users care about the Rust API,\nnot its lineage. Self-references within the Rust crate (e.g. \"Mirrors\n[`from_streams`] but adds…\") are fine.\n\n## Toolchain\n\nThe SDK is pinned to `rust 1.94.0` via `rust\u002Frust-toolchain.toml`. Formatting\nuses nightly (`nightly-2026-04-14`) so unstable rustfmt options like grouped\nimports work — see `rust\u002F.rustfmt.nightly.toml`. CI runs:\n\n```bash\ncd rust\ncargo +nightly-2026-04-14 fmt --check\ncargo clippy --all-features --all-targets -- -D warnings\ncargo test --all-features\n```\n\nMatch those exact commands locally before pushing.\n\n## Codegen\n\nJSON-RPC and session-event types are generated from the Copilot CLI schema:\n\n| Source | Output |\n|---|---|\n| `nodejs\u002Fnode_modules\u002F@github\u002Fcopilot\u002Fschemas\u002Fapi.schema.json` | `rust\u002Fsrc\u002Fgenerated\u002Fapi_types.rs` |\n| `nodejs\u002Fnode_modules\u002F@github\u002Fcopilot\u002Fschemas\u002Fsession-events.schema.json` | `rust\u002Fsrc\u002Fgenerated\u002Fsession_events.rs` |\n\nRegenerate with:\n\n```bash\ncd scripts\u002Fcodegen && npm run generate:rust\n```\n\nNever hand-edit files under `rust\u002Fsrc\u002Fgenerated\u002F`. If a generated type needs a\nfield the schema lacks, hand-author the user-facing type in `rust\u002Fsrc\u002Ftypes.rs`\nand stop re-exporting the generated one.\n",{"name":5,"description":7},"main","36d1906c0f5e8cbdc4c3b5cc88236b6d68628299",".github\u002Fskills\u002Frust-coding-skill",1,"https:\u002F\u002Fgithub.com\u002Freview-bench\u002Fgithub_copilot-sdk","https:\u002F\u002Fgithub.com\u002Freview-bench","https:\u002F\u002Freview-bench.ai","An open benchmark for AI code review.","2026-10-27 07:02:57",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add review-bench\u002Fgithub_copilot-sdk --skill rust-coding-skill",{"tool":39,"command":40},"bunx","bunx skills add review-bench\u002Fgithub_copilot-sdk --skill rust-coding-skill",{"tool":42,"command":43},"pnpm","pnpm dlx skills add review-bench\u002Fgithub_copilot-sdk --skill rust-coding-skill","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Freview-bench\u002Fgithub_copilot-sdk\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Frust-coding-skill\u002FSKILL.md",true,[47],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"examples.md","REFERENCE","参考文档",4937,"https:\u002F\u002Fgithub.com\u002Freview-bench\u002Fgithub_copilot-sdk\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Frust-coding-skill\u002Fexamples.md",[54,60],{"skillNo":55,"name":56,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7529JCBRR1WB00VK5CWKMJS","greeting","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Fgithub_copilot-sdk\u002Fblob\u002Fmain\u002Ftest\u002Fscenarios\u002Ftools\u002Fskills\u002Fsample-skills\u002Fgreeting\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7529C4KXMCY39SYA2HGMDTH","java-coding-skill","Use this skill whenever editing `*.java` files in the `java\u002F` SDK in order to write idiomatic, well-structured Java code for the Copilot SDK","https:\u002F\u002Fgithub.com\u002Freview-bench\u002Fgithub_copilot-sdk\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fjava-coding-skill\u002FSKILL.md",[],[]]