返回 CodeWhale
identity.rs
根目录 / crates / tui / src / integrations / dsh / identity.rs
1 //! Exact Codewhale route identity → DeepSeek Harness overlay mapping.
2 //!
3 //! The mapping carries *identity only*: provider id, model id, endpoint,
4 //! reasoning tier, permission posture, and the *name* of the credential
5 //! environment variable. It never carries a credential value, an OAuth
6 //! document, or a base URL that embeds userinfo/query material.
7
8 use serde::{Deserialize, Serialize};
9 use sha2::{Digest, Sha256};
10
11 /// Non-secret facts about the route Codewhale is currently configured to use.
12 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13 pub(crate) struct CodewhaleRouteIdentity {
14 /// Exact configured provider id (e.g. `deepseek`, `ollama`, `zai`, or a
15 /// named custom table key).
16 pub(crate) provider_id: String,
17 /// Human label for the provider.
18 pub(crate) provider_label: String,
19 /// Exact model id put on the wire.
20 pub(crate) model: String,
21 /// Resolved base URL (structural; must not carry credentials).
22 pub(crate) base_url: String,
23 /// Wire protocol Codewhale speaks to this endpoint.
24 pub(crate) protocol: WireProtocol,
25 /// Canonical credential env var name for the provider, if it has one.
26 pub(crate) api_key_env: Option<String>,
27 /// True when the route is a keyless self-hosted endpoint (loopback
28 /// Ollama/LM Studio/vLLM/SGLang): no credential reference is written.
29 pub(crate) keyless_local: bool,
30 /// Codewhale reasoning tier as configured (`off|low|medium|high|xhigh|max|ultra`).
31 pub(crate) reasoning_effort: Option<String>,
32 /// Codewhale sandbox mode (`read-only|workspace-write|danger-full-access|external-sandbox`).
33 pub(crate) sandbox_mode: Option<String>,
34 /// Codewhale approval policy (`suggest|auto|never`).
35 pub(crate) approval_policy: Option<String>,
36 pub(crate) yolo: bool,
37 /// Workspace the launch is bound to.
38 pub(crate) workspace: String,
39 }
40
41 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42 #[serde(rename_all = "kebab-case")]
43 pub(crate) enum WireProtocol {
44 ChatCompletions,
45 Responses,
46 AnthropicMessages,
47 GenerateContent,
48 }
49
50 /// DSH permission mode mirrored from the Codewhale posture.
51 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52 #[serde(rename_all = "kebab-case")]
53 pub(crate) enum DshPermissionMode {
54 ReadOnly,
55 WorkspaceWrite,
56 DangerFullAccess,
57 }
58
59 impl DshPermissionMode {
60 pub(crate) fn as_str(self) -> &'static str {
61 match self {
62 Self::ReadOnly => "read-only",
63 Self::WorkspaceWrite => "workspace-write",
64 Self::DangerFullAccess => "danger-full-access",
65 }
66 }
67 }
68
69 /// Which DSH adapter carries the route.
70 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71 #[serde(tag = "kind", rename_all = "snake_case")]
72 pub(crate) enum DshAdapter {
73 /// `@deepseek-ai/dsh-llm-deepseek`, route id `deepseek-official`.
74 DeepseekNative,
75 /// `@deepseek-ai/dsh-llm-pi-ai` hand-declared route. The route names the
76 /// provider's own wire dialect (`openai-completions`, `openai-responses`,
77 /// or `anthropic-messages`); see [`pi_ai_api_for`].
78 PiAiOpenAiCompatible { route_id: String },
79 /// DSH cannot carry this route; nothing is written for it.
80 Unsupported { reason: String },
81 }
82
83 /// The identity as it will be written into the overlay, plus disclosures.
84 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85 pub(crate) struct MappedIdentity {
86 pub(crate) source: CodewhaleRouteIdentity,
87 pub(crate) adapter: DshAdapter,
88 /// DSH `reasoningEffort` (`off|high|max`) for the native adapter; `None`
89 /// when Codewhale has no explicit tier or the adapter cannot express it.
90 pub(crate) dsh_reasoning_effort: Option<String>,
91 pub(crate) permission_mode: DshPermissionMode,
92 /// Facts the user must know that the overlay cannot enforce.
93 pub(crate) disclosures: Vec<String>,
94 }
95
96 impl MappedIdentity {
97 pub(crate) fn mappable(&self) -> bool {
98 !matches!(self.adapter, DshAdapter::Unsupported { .. })
99 }
100
101 /// The `provider` value DSH sees for this route.
102 pub(crate) fn dsh_provider(&self) -> Option<&str> {
103 match &self.adapter {
104 DshAdapter::DeepseekNative => Some("deepseek-official"),
105 DshAdapter::PiAiOpenAiCompatible { route_id } => Some(route_id),
106 DshAdapter::Unsupported { .. } => None,
107 }
108 }
109 }
110
111 /// Map a Codewhale reasoning tier onto DSH's `off | high | max`.
112 pub(crate) fn dsh_reasoning_effort(effort: Option<&str>) -> Option<&'static str> {
113 match effort.map(|e| e.trim().to_ascii_lowercase()).as_deref() {
114 None | Some("") => None,
115 Some("off" | "none" | "disabled" | "false") => Some("off"),
116 Some("minimal" | "low" | "medium" | "mid" | "high" | "auto") => Some("high"),
117 Some("xhigh" | "max" | "maximum" | "highest" | "ultra" | "ultracode") => Some("max"),
118 Some(_) => None,
119 }
120 }
121
122 /// Mirror the Codewhale posture. Full access is only granted when Codewhale
123 /// itself runs with full access *and* the caller confirmed it explicitly.
124 pub(crate) fn permission_mode_for(
125 identity: &CodewhaleRouteIdentity,
126 allow_full_access: bool,
127 ) -> (DshPermissionMode, Option<String>) {
128 let sandbox = identity
129 .sandbox_mode
130 .as_deref()
131 .map(|s| s.trim().to_ascii_lowercase());
132 let approval = identity
133 .approval_policy
134 .as_deref()
135 .map(|s| s.trim().to_ascii_lowercase());
136 let codewhale_full = identity.yolo
137 || matches!(
138 sandbox.as_deref(),
139 Some("danger-full-access" | "external-sandbox")
140 );
141 if matches!(sandbox.as_deref(), Some("read-only")) {
142 return (DshPermissionMode::ReadOnly, None);
143 }
144 if codewhale_full {
145 if allow_full_access {
146 return (
147 DshPermissionMode::DangerFullAccess,
148 Some(
149 "DSH danger-full-access mirrors Codewhale full access; DSH will not ask before file effects."
150 .to_string(),
151 ),
152 );
153 }
154 return (
155 DshPermissionMode::WorkspaceWrite,
156 Some(
157 "Codewhale runs with full access, but the DSH overlay stays at workspace-write; pass --allow-full-access to mirror it."
158 .to_string(),
159 ),
160 );
161 }
162 let note = match approval.as_deref() {
163 Some("never" | "deny" | "denied") => Some(
164 "Codewhale approval policy is `never`; DSH keeps its own ask-before-effects policy at workspace-write."
165 .to_string(),
166 ),
167 _ => None,
168 };
169 (DshPermissionMode::WorkspaceWrite, note)
170 }
171
172 fn base_url_is_structural(url: &str) -> Result<(), String> {
173 let trimmed = url.trim();
174 if trimmed.is_empty() {
175 return Err("empty base URL".to_string());
176 }
177 let Some((scheme, rest)) = trimmed.split_once("://") else {
178 return Err("base URL has no scheme".to_string());
179 };
180 if !matches!(scheme, "http" | "https") {
181 return Err(format!("unsupported base URL scheme `{scheme}`"));
182 }
183 let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
184 if authority.contains('@') {
185 return Err("base URL embeds userinfo; refusing to copy it".to_string());
186 }
187 if rest.contains('?') || rest.contains('#') {
188 return Err("base URL carries a query/fragment; refusing to copy it".to_string());
189 }
190 Ok(())
191 }
192
193 /// The `api:` dialect a hand-declared `dsh-llm-pi-ai` route names for a
194 /// Codewhale wire protocol — identity-preserving, never an approximation.
195 ///
196 /// Verified against the installed `@deepseek-ai/dsh@0.1.0-rc.6`:
197 /// `@deepseek-ai/dsh-llm-pi-ai`'s exported profile schema accepts exactly
198 /// `openai-completions | openai-responses | anthropic-messages` for `api:`
199 /// (`lib/index.js`: `const PROTOCOLS = { "openai-completions": …,
200 /// "openai-responses": openAIResponsesApi, "anthropic-messages": … }`),
201 /// while `@deepseek-ai/dsh-llm-deepseek` (the `deepseek-official` route)
202 /// speaks chat completions only — its single wire call posts to
203 /// `<baseURL>/chat/completions` with no protocol switch — so
204 /// Responses-dialect DeepSeek routes (e.g. `deepseek-v4-flash`) ride the
205 /// pi-ai hand-declared route instead.
206 pub(crate) fn pi_ai_api_for(protocol: WireProtocol) -> &'static str {
207 match protocol {
208 WireProtocol::ChatCompletions => "openai-completions",
209 WireProtocol::Responses => "openai-responses",
210 WireProtocol::AnthropicMessages => "anthropic-messages",
211 WireProtocol::GenerateContent => "google-generative-ai",
212 }
213 }
214
215 fn route_id_for(provider_id: &str) -> String {
216 let mut out = String::from("codewhale-");
217 for ch in provider_id.chars() {
218 if ch.is_ascii_alphanumeric() {
219 out.push(ch.to_ascii_lowercase());
220 } else if !out.ends_with('-') {
221 out.push('-');
222 }
223 }
224 out.trim_end_matches('-').to_string()
225 }
226
227 pub(crate) fn map_identity(
228 identity: &CodewhaleRouteIdentity,
229 allow_full_access: bool,
230 ) -> MappedIdentity {
231 let mut disclosures = Vec::new();
232 let (permission_mode, note) = permission_mode_for(identity, allow_full_access);
233 if let Some(note) = note {
234 disclosures.push(note);
235 }
236 let dsh_effort = dsh_reasoning_effort(identity.reasoning_effort.as_deref()).map(str::to_string);
237
238 if let Err(reason) = base_url_is_structural(&identity.base_url) {
239 return MappedIdentity {
240 source: identity.clone(),
241 adapter: DshAdapter::Unsupported { reason },
242 dsh_reasoning_effort: None,
243 permission_mode,
244 disclosures,
245 };
246 }
247
248 let is_deepseek = matches!(identity.provider_id.as_str(), "deepseek" | "deepseek-cn");
249 if is_deepseek && identity.protocol == WireProtocol::ChatCompletions {
250 if identity.reasoning_effort.is_some() && dsh_effort.is_none() {
251 disclosures.push(format!(
252 "Codewhale reasoning tier `{}` has no DSH equivalent; DSH keeps its default (high).",
253 identity.reasoning_effort.as_deref().unwrap_or("")
254 ));
255 }
256 disclosures.push(
257 "DSH resolves DEEPSEEK_API_KEY from its own environment or $DSH_HOME/.credentials.yaml; Codewhale does not hand over a key."
258 .to_string(),
259 );
260 return MappedIdentity {
261 source: identity.clone(),
262 adapter: DshAdapter::DeepseekNative,
263 dsh_reasoning_effort: dsh_effort,
264 permission_mode,
265 disclosures,
266 };
267 }
268
269 // Every wire dialect Codewhale can speak, `dsh-llm-pi-ai` declares a
270 // hand-declared route for (see `pi_ai_api_for`), so the route is carried
271 // in its own dialect rather than refused or approximated as completions.
272 if identity.protocol != WireProtocol::ChatCompletions {
273 disclosures.push(format!(
274 "Route speaks the {} dialect; DSH carries it through the `@deepseek-ai/dsh-llm-pi-ai` hand-declared route (`api: {}`) — the wire dialect is preserved, never approximated as chat completions.",
275 dialect_label(identity.protocol),
276 pi_ai_api_for(identity.protocol)
277 ));
278 }
279
280 if identity.reasoning_effort.is_some() {
281 disclosures.push(
282 "Reasoning tier is not mapped for hand-declared DSH routes (per-provider wire spellings are not verified); DSH sends no effort parameter."
283 .to_string(),
284 );
285 }
286 if identity.keyless_local {
287 disclosures.push(
288 "Keyless local route: no credential reference is written; DSH talks to the endpoint without a key."
289 .to_string(),
290 );
291 } else if let Some(env) = identity.api_key_env.as_deref() {
292 disclosures.push(format!(
293 "DSH resolves {env} from its own environment or $DSH_HOME/.credentials.yaml; Codewhale does not hand over a key."
294 ));
295 } else {
296 disclosures.push(
297 "No credential env var is known for this provider; DSH will defer to its ambient credential discovery."
298 .to_string(),
299 );
300 }
301 MappedIdentity {
302 source: identity.clone(),
303 adapter: DshAdapter::PiAiOpenAiCompatible {
304 route_id: route_id_for(&identity.provider_id),
305 },
306 dsh_reasoning_effort: None,
307 permission_mode,
308 disclosures,
309 }
310 }
311
312 fn dialect_label(protocol: WireProtocol) -> &'static str {
313 match protocol {
314 WireProtocol::ChatCompletions => "OpenAI Chat Completions",
315 WireProtocol::Responses => "OpenAI Responses",
316 WireProtocol::AnthropicMessages => "Anthropic Messages",
317 WireProtocol::GenerateContent => "Gemini Generate Content",
318 }
319 }
320
321 fn yaml_str(value: &str) -> String {
322 // Single-quoted YAML scalar: only `'` needs escaping.
323 format!("'{}'", value.replace('\'', "''"))
324 }
325
326 /// Render the DSH `--patch` overlay for a mapped identity. Deterministic for
327 /// a given identity so its SHA-256 can detect drift.
328 pub(crate) fn render_overlay(mapped: &MappedIdentity) -> Option<String> {
329 let src = &mapped.source;
330 let mut out = String::new();
331 out.push_str("# DeepSeek Harness connected through Codewhale.\n");
332 out.push_str("# Generated by `codewhale integrations dsh connect`; do not edit by hand.\n");
333 out.push_str("# Identity only: no API key, token, or credential document is written here.\n");
334 out.push_str(&format!(
335 "# codewhale.provider={} codewhale.model={} codewhale.workspace={}\n",
336 src.provider_id, src.model, src.workspace
337 ));
338 match &mapped.adapter {
339 DshAdapter::DeepseekNative => {
340 out.push_str("- id: agent-default-model\n");
341 out.push_str(" name: '@deepseek-ai/dsh-agent-default-model'\n");
342 out.push_str(" config:\n");
343 out.push_str(" provider: deepseek-official\n");
344 out.push_str(&format!(" model: {}\n", yaml_str(&src.model)));
345 out.push_str("- id: llm-deepseek\n");
346 out.push_str(" name: '@deepseek-ai/dsh-llm-deepseek'\n");
347 out.push_str(" config:\n");
348 out.push_str(&format!(" baseURL: {}\n", yaml_str(&src.base_url)));
349 if let Some(effort) = mapped.dsh_reasoning_effort.as_deref() {
350 out.push_str(&format!(" reasoningEffort: {effort}\n"));
351 }
352 out.push_str(" models:\n");
353 out.push_str(&format!(" - id: {}\n", yaml_str(&src.model)));
354 out.push_str(&format!(" name: {}\n", yaml_str(&src.model)));
355 }
356 DshAdapter::PiAiOpenAiCompatible { route_id } => {
357 out.push_str("- id: agent-default-model\n");
358 out.push_str(" name: '@deepseek-ai/dsh-agent-default-model'\n");
359 out.push_str(" config:\n");
360 out.push_str(&format!(" provider: {}\n", yaml_str(route_id)));
361 out.push_str(&format!(" model: {}\n", yaml_str(&src.model)));
362 out.push_str("- id: llm-pi-ai\n");
363 out.push_str(" name: '@deepseek-ai/dsh-llm-pi-ai'\n");
364 out.push_str(" config:\n");
365 out.push_str(" providers:\n");
366 out.push_str(&format!(" {}:\n", yaml_str(route_id)));
367 out.push_str(&format!(
368 " displayName: {}\n",
369 yaml_str(&format!("{} (via Codewhale)", src.provider_label))
370 ));
371 if !src.keyless_local
372 && let Some(env) = src.api_key_env.as_deref()
373 {
374 out.push_str(&format!(" apiKeyEnv: {}\n", yaml_str(env)));
375 }
376 out.push_str(&format!(" api: {}\n", pi_ai_api_for(src.protocol)));
377 out.push_str(&format!(" baseURL: {}\n", yaml_str(&src.base_url)));
378 out.push_str(" models:\n");
379 out.push_str(&format!(" - id: {}\n", yaml_str(&src.model)));
380 out.push_str(&format!(" name: {}\n", yaml_str(&src.model)));
381 }
382 DshAdapter::Unsupported { .. } => return None,
383 }
384 Some(out)
385 }
386
387 pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
388 let mut hasher = Sha256::new();
389 hasher.update(bytes);
390 hex_lower(&hasher.finalize())
391 }
392
393 fn hex_lower(bytes: &[u8]) -> String {
394 let mut out = String::with_capacity(bytes.len() * 2);
395 for byte in bytes {
396 out.push_str(&format!("{byte:02x}"));
397 }
398 out
399 }
400
400 lines RUST