1use super::*;
8
9fn remote_request(name: &str, arguments: &Value) -> Result<(&'static str, Value)> {
11 match name {
12 "IdentityAccounts" => Ok(("identity.accounts", json!({}))),
13 "IdentitySignin" => {
14 let Some(session) = str_arg(arguments, "session") else {
16 let mut params = json!({});
17 for key in ["provider", "account"] {
18 if let Some(v) = str_arg(arguments, key) {
19 params[key] = json!(v);
20 }
21 }
22 return Ok(("identity.signin.start", params));
23 };
24 let mut params = json!({ "session": session });
25 if let Some(code) = str_arg(arguments, "code") {
26 params["code"] = json!(code);
27 }
28 Ok(("identity.signin.finish", params))
29 }
30 _ => {
31 let account = str_arg(arguments, "account").ok_or_else(|| anyhow::anyhow!("missing required parameter: account"))?;
32 let agent = str_arg(arguments, "agent")
33 .ok_or_else(|| anyhow::anyhow!("with a host, name the agent on that machine (or \"all limited\"): there is no \"yourself\" across machines"))?;
34 let mut params = json!({ "agent_id": agent, "account": account });
35 if let Some(when) = str_arg(arguments, "when") {
36 params["when"] = json!(when);
37 }
38 Ok(("identity.switch", params))
39 }
40 }
41}
42
43async fn remote(name: &str, arguments: &Value, cx: &ToolCtx<'_>, host: &str) -> Result<String> {
45 let (op, params) = remote_request(name, arguments)?;
46 let reason = str_arg(arguments, "reason").unwrap_or_else(|| format!("Identity {}", op.trim_start_matches("identity.")));
47 let answer = remote_op::remote_op_call(cx, host, op, params, &reason).await?;
48 if let Some(problem) = remote_op::explain_not_done(host, op, &answer) {
49 anyhow::bail!("{problem}");
50 }
51 let mut text = remote_op::pretty(host, &answer);
52 if op == "identity.signin.start" {
53 text.push_str(&signin_notice(cx, host, arguments, &answer).await);
54 }
55 Ok(text)
56}
57
58async fn signin_notice(cx: &ToolCtx<'_>, host: &str, arguments: &Value, answer: &Value) -> String {
61 let Some(url) = answer["result"]["url"].as_str() else { return String::new() };
62 let provider = str_arg(arguments, "provider").unwrap_or_else(|| "claude".to_string());
63 let Ok(agent_id) = agent_slug() else { return String::new() };
64 let endpoint = format!("{}/api/v1/agent/identity/signin/notice", cx.local_url.trim_end_matches('/'));
65 let body = json!({ "agent_id": agent_id, "provider": provider, "machine": host, "url": url, "code": answer["result"]["device_code"] });
66 let sent = cx.client.post(&endpoint).header(AUTH_KEY_HEADER, cx.auth_key).json(&body).send().await;
67 let shown = match sent {
68 Ok(resp) if resp.status().is_success() => resp.json::<Value>().await.ok(),
69 _ => None,
70 };
71 match shown.as_ref().and_then(|v| v["shown_on"].as_str()) {
72 Some(machine) => format!("
73
74The link is also on {machine} as a notice with an Open button."),
75 None => String::new(),
76 }
77}
78
79pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
80 if matches!(name, "IdentityAccounts" | "IdentitySwitch" | "IdentitySignin") {
81 if let Some(host) = remote_op::host_arg(arguments) {
82 return remote(name, arguments, cx, &host).await;
83 }
84 }
85 if name == "IdentitySignin" {
86 anyhow::bail!("signin needs a host: it signs an account in on another machine. To add an account here, use the Connectors pane");
87 }
88 match name {
89 "IdentityAccounts" => run_identity_accounts(arguments, cx).await,
90 "IdentityValidate" => run_identity_validate(arguments, cx).await,
91 "IdentitySwitch" => run_identity_switch(arguments, cx).await,
92 "IdentityCheckLimits" => run_identity_check_limits(arguments, cx).await,
93 _ => Err(not_in_family()),
94 }
95}
96
97async fn run_identity_accounts(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
98 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
99 require_agent_env(local_url, auth_key, block_id)?;
100 let agent_id = agent_slug()?;
101 let result = cx.get_json("/api/v1/agent/identity/accounts", &[("agent_id", agent_id.as_str()), ("scope", arguments.get("scope").and_then(|v| v.as_str()).unwrap_or(""))], "identity/accounts").await?;
102 Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
103}
104
105async fn run_identity_validate(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
106 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
107 let account_id = arguments
108 .get("account_id")
109 .and_then(|v| v.as_str())
110 .filter(|s| !s.is_empty())
111 .ok_or_else(|| anyhow::anyhow!("missing required parameter: account_id"))?;
112 require_agent_env(local_url, auth_key, block_id)?;
113 let agent_id = agent_slug()?;
114 let body = json!({
115 "agent_id": agent_id,
116 "account_id": account_id,
117 });
118 let result = cx.post_json("/api/v1/agent/identity/validate", &body, "identity/validate").await?;
119 Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
120}
121
122async fn run_identity_check_limits(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
126 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
127 require_agent_env(local_url, auth_key, block_id)?;
128 let agent_id = agent_slug()?;
129 let account = arguments.get("account").and_then(|v| v.as_str()).filter(|s| !s.trim().is_empty());
130 let result = cx.post_json("/api/v1/agent/identity/check-limits", &json!({ "agent_id": agent_id, "account": account }), Named::with_hyphen("identity/check-limits")).await?;
131 Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
132}
133
134async fn run_identity_switch(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
135 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
136 let account = arguments
137 .get("account")
138 .and_then(|v| v.as_str())
139 .filter(|s| !s.is_empty())
140 .ok_or_else(|| anyhow::anyhow!("missing required parameter: account"))?;
141 require_agent_env(local_url, auth_key, block_id)?;
142 let agent_id = agent_slug()?;
143 let mut body = json!({ "agent_id": agent_id, "account": account });
144 if let Some(target) = arguments.get("agent").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
145 body["target"] = json!(target);
146 }
147 if let Some(when) = arguments.get("when").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
148 body["when"] = json!(when);
149 }
150 let result = cx.post_json("/api/v1/agent/identity/switch", &body, "identity/switch").await?;
151 Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
152}
153
154#[cfg(test)]
155mod call_tests;
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160
161 #[test]
162 fn accounts_on_a_host_asks_for_the_listing() {
163 let (op, params) = remote_request("IdentityAccounts", &json!({ "host": "charlie" })).unwrap();
164 assert_eq!((op, params), ("identity.accounts", json!({})));
165 }
166
167 #[test]
168 fn signin_starts_without_a_session_and_waits_with_one() {
169 let (op, params) = remote_request("IdentitySignin", &json!({ "host": "charlie", "provider": "claude" })).unwrap();
170 assert_eq!((op, params), ("identity.signin.start", json!({ "provider": "claude" })));
171 let args = json!({ "host": "charlie", "session": "s1", "code": "abc" });
172 let (op, params) = remote_request("IdentitySignin", &args).unwrap();
173 assert_eq!((op, params), ("identity.signin.finish", json!({ "session": "s1", "code": "abc" })));
174 let (op, params) = remote_request("IdentitySignin", &json!({ "host": "charlie", "session": "s1" })).unwrap();
175 assert_eq!((op, params), ("identity.signin.finish", json!({ "session": "s1" })));
176 }
177
178 #[test]
179 fn a_switch_on_a_host_names_the_agent_and_the_account() {
180 let args = json!({ "host": "charlie", "agent": "Opaz", "account": "any with quota", "when": "now" });
181 let (op, params) = remote_request("IdentitySwitch", &args).unwrap();
182 assert_eq!(op, "identity.switch");
183 assert_eq!(params, json!({ "agent_id": "Opaz", "account": "any with quota", "when": "now" }));
184 let e = remote_request("IdentitySwitch", &json!({ "host": "charlie", "account": "x" })).unwrap_err().to_string();
185 assert!(e.contains("name the agent"), "{e}");
186 assert!(remote_request("IdentitySwitch", &json!({ "host": "charlie", "agent": "Opaz" })).is_err());
187 }
188}