objectiveai-api 2.0.5

ObjectiveAI API Server
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
use crate::ctx;
use std::sync::Arc;
use std::time::Duration;

#[derive(Debug, Clone)]
pub struct Client {
    pub http_client: reqwest::Client,
    /// GitHub authorization token.
    pub authorization: Option<String>,
    pub user_agent: String,
    pub x_title: String,
    pub http_referer: String,
    /// If false, require_authorization will reject requests that don't have a per-request BYOK token.
    pub allow_publish_without_byok: bool,
    pub backoff_current_interval: Duration,
    pub backoff_initial_interval: Duration,
    pub backoff_randomization_factor: f64,
    pub backoff_multiplier: f64,
    pub backoff_max_interval: Duration,
    pub backoff_max_elapsed_time: Duration,
}

impl Client {
    pub fn new(
        http_client: reqwest::Client,
        authorization: Option<String>,
        allow_publish_without_byok: bool,
        user_agent: String,
        x_title: String,
        http_referer: String,
        backoff_current_interval: Duration,
        backoff_initial_interval: Duration,
        backoff_randomization_factor: f64,
        backoff_multiplier: f64,
        backoff_max_interval: Duration,
        backoff_max_elapsed_time: Duration,
    ) -> Self {
        Self {
            http_client,
            authorization,
            allow_publish_without_byok,
            user_agent,
            x_title,
            http_referer,
            backoff_current_interval,
            backoff_initial_interval,
            backoff_randomization_factor,
            backoff_multiplier,
            backoff_max_interval,
            backoff_max_elapsed_time,
        }
    }

    fn backoff(&self) -> backoff::ExponentialBackoff {
        backoff::ExponentialBackoff {
            current_interval: self.backoff_current_interval,
            initial_interval: self.backoff_initial_interval,
            randomization_factor: self.backoff_randomization_factor,
            multiplier: self.backoff_multiplier,
            max_interval: self.backoff_max_interval,
            max_elapsed_time: Some(self.backoff_max_elapsed_time),
            ..Default::default()
        }
    }

    /// Resolves the authorization token: per-request header → ext → self.authorization.
    async fn resolve_authorization<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
    ) -> Option<Arc<String>> {
        if let Some(token) = ctx.github_authorization().await {
            return Some(token);
        }
        self.authorization.as_ref().map(|t| Arc::new(t.clone()))
    }

    /// Resolves the authorization token, returning an error if none is available.
    /// If `allow_publish_without_byok` is false, only the per-request ctx token is accepted.
    async fn require_authorization<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
    ) -> Result<Arc<String>, super::Error> {
        if let Some(token) = ctx.github_authorization().await {
            return Ok(token);
        }
        if !self.allow_publish_without_byok {
            return Err(super::Error::MissingPublishToken);
        }
        self.authorization
            .as_ref()
            .map(|t| Arc::new(t.clone()))
            .ok_or(super::Error::MissingPublishToken)
    }

    /// Adds authorization + standard headers to a request.
    fn request_headers(
        &self,
        mut req: reqwest::RequestBuilder,
        token: Option<&str>,
    ) -> reqwest::RequestBuilder {
        if let Some(token) = token {
            req = req.header(
                reqwest::header::AUTHORIZATION,
                ensure_bearer(token),
            );
        }
        req = req.header("user-agent", &self.user_agent);
        req = req.header("x-title", &self.x_title);
        req = req
            .header("referer", &self.http_referer)
            .header("http-referer", &self.http_referer);
        req
    }

    // ── Public fetch methods ───────────────────────────────────────

    /// Fetches the latest commit SHA for a repository.
    pub async fn fetch_latest_commit<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
        owner: &str,
        repository: &str,
    ) -> Result<Option<String>, super::Error> {
        #[derive(serde::Deserialize)]
        struct Commit {
            sha: String,
        }
        let token = self.resolve_authorization(ctx).await;
        let token_str: Option<&str> = token.as_deref().map(|s| s.as_str());
        let http_request = self.request_headers(
            self.http_client
                .get(format!(
                    "https://api.github.com/repos/{}/{}/commits",
                    owner, repository,
                ))
                .header("accept", "application/vnd.github+json"),
            token_str,
        );
        backoff::future::retry(self.backoff(), || async {
            let response = http_request
                .try_clone()
                .unwrap()
                .send()
                .await
                .map_err(super::Error::RequestError)?;
            let code = response.status();
            if code.is_success() {
                let text = response
                    .text()
                    .await
                    .map_err(super::Error::ResponseError)?;
                let mut de = serde_json::Deserializer::from_str(&text);
                match serde_path_to_error::deserialize::<_, Vec<Commit>>(&mut de) {
                    Ok(commits) => Ok(commits.first().map(|c| c.sha.clone())),
                    Err(e) => Err(backoff::Error::transient(
                        super::Error::DeserializationError(e),
                    )),
                }
            } else if code == reqwest::StatusCode::NOT_FOUND {
                Ok(None)
            } else {
                Err(backoff::Error::transient(bad_status(response).await))
            }
        })
        .await
    }

    /// Fetches a file from a GitHub repository and returns the raw text content.
    /// Tries raw.githubusercontent.com first, falls back to the Contents API.
    pub async fn read_file<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
        owner: &str,
        repository: &str,
        commit: &str,
        path: &str,
    ) -> Result<Option<String>, super::Error> {
        let token = self.resolve_authorization(ctx).await;
        let token_str: Option<&str> = token.as_deref().map(|s| s.as_str());
        backoff::future::retry(self.backoff(), || async {
            match self.fetch_file_raw(token_str, owner, repository, commit, path).await {
                Ok(opt) => Ok(opt),
                Err(e1) => match self
                    .fetch_file_api(token_str, owner, repository, commit, path)
                    .await
                {
                    Ok(opt) => Ok(opt),
                    Err(e2) => Err(backoff::Error::transient(
                        super::Error::MultipleErrors(Box::new(e1), Box::new(e2)),
                    )),
                },
            }
        })
        .await
    }

    /// Fetches a JSON file from a GitHub repository and deserializes it.
    pub async fn read_json<T, CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
        owner: &str,
        repository: &str,
        commit: &str,
        path: &str,
    ) -> Result<Option<T>, super::Error>
    where
        T: serde::de::DeserializeOwned,
    {
        match self.read_file(ctx, owner, repository, commit, path).await? {
            Some(text) => {
                let mut de = serde_json::Deserializer::from_str(&text);
                match serde_path_to_error::deserialize::<_, T>(&mut de) {
                    Ok(value) => Ok(Some(value)),
                    Err(e) => Err(super::Error::DeserializationError(e)),
                }
            }
            None => Ok(None),
        }
    }

    // ── Private fetch helpers ──────────────────────────────────────

    async fn fetch_file_raw(
        &self,
        token: Option<&str>,
        owner: &str,
        repository: &str,
        commit: &str,
        path: &str,
    ) -> Result<Option<String>, super::Error> {
        let http_request = self.request_headers(
            self.http_client.get(format!(
                "https://raw.githubusercontent.com/{}/{}/{}/{}",
                owner, repository, commit, path,
            )),
            token,
        );
        let response = http_request
            .send()
            .await
            .map_err(super::Error::RequestError)?;
        let code = response.status();
        if code.is_success() {
            let text = response.text().await.map_err(super::Error::ResponseError)?;
            Ok(Some(text))
        } else if code == reqwest::StatusCode::NOT_FOUND {
            Ok(None)
        } else {
            Err(bad_status(response).await)
        }
    }

    async fn fetch_file_api(
        &self,
        token: Option<&str>,
        owner: &str,
        repository: &str,
        commit: &str,
        path: &str,
    ) -> Result<Option<String>, super::Error> {
        let http_request = self.request_headers(
            self.http_client
                .get(format!(
                    "https://api.github.com/repos/{}/{}/contents/{}?ref={}",
                    owner, repository, path, commit,
                ))
                .header("accept", "application/vnd.github.raw+json"),
            token,
        );
        let response = http_request
            .send()
            .await
            .map_err(super::Error::RequestError)?;
        let code = response.status();
        if code.is_success() {
            let text = response.text().await.map_err(super::Error::ResponseError)?;
            Ok(Some(text))
        } else if code == reqwest::StatusCode::NOT_FOUND {
            Ok(None)
        } else {
            Err(bad_status(response).await)
        }
    }

    // ── Publish methods ────────────────────────────────────────────

    /// Checks whether a GitHub repository exists.
    pub async fn repository_exists<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
        owner: &str,
        repository: &str,
    ) -> Result<bool, super::Error> {
        let token = self.require_authorization(ctx).await?;
        let req = self.request_headers(
            self.http_client
                .get(format!("https://api.github.com/repos/{}/{}", owner, repository))
                .header("accept", "application/vnd.github+json"),
            Some(&token),
        );
        backoff::future::retry(self.backoff(), || async {
            let response = req
                .try_clone()
                .unwrap()
                .send()
                .await
                .map_err(|e| backoff::Error::transient(super::Error::RequestError(e)))?;
            let code = response.status();
            if code.is_success() {
                Ok(true)
            } else if code == reqwest::StatusCode::NOT_FOUND {
                Ok(false)
            } else {
                Err(backoff::Error::transient(bad_status(response).await))
            }
        })
        .await
    }

    /// Validates that a GitHub token is valid. Returns the scopes.
    pub async fn validate_token<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
    ) -> Result<Vec<String>, super::Error> {
        let token = self.require_authorization(ctx).await?;
        let req = self.request_headers(
            self.http_client
                .get("https://api.github.com/user")
                .header("accept", "application/vnd.github+json"),
            Some(&token),
        );
        backoff::future::retry(self.backoff(), || async {
            let response = req
                .try_clone()
                .unwrap()
                .send()
                .await
                .map_err(|e| backoff::Error::transient(super::Error::RequestError(e)))?;
            let code = response.status();
            if code.is_success() {
                let scopes = response
                    .headers()
                    .get("x-oauth-scopes")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("")
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                Ok(scopes)
            } else {
                Err(backoff::Error::permanent(bad_status(response).await))
            }
        })
        .await
    }

    /// Returns the authenticated user's login name.
    pub async fn get_authenticated_user<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
    ) -> Result<String, super::Error> {
        let token = self.require_authorization(ctx).await?;
        let req = self.request_headers(
            self.http_client
                .get("https://api.github.com/user")
                .header("accept", "application/vnd.github+json"),
            Some(&token),
        );
        backoff::future::retry(self.backoff(), || async {
            let response = req
                .try_clone()
                .unwrap()
                .send()
                .await
                .map_err(|e| backoff::Error::transient(super::Error::RequestError(e)))?;
            let code = response.status();
            if code.is_success() {
                let body: serde_json::Value = response
                    .json()
                    .await
                    .map_err(|e| backoff::Error::transient(super::Error::ResponseError(e)))?;
                let login = body["login"]
                    .as_str()
                    .ok_or_else(|| {
                        backoff::Error::permanent(super::Error::BadStatus {
                            code,
                            body: body.clone(),
                        })
                    })?
                    .to_string();
                Ok(login)
            } else {
                Err(backoff::Error::permanent(bad_status(response).await))
            }
        })
        .await
    }

    /// Creates a new GitHub repository under the authenticated user.
    pub async fn create_repository<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
        name: &str,
        description: &str,
    ) -> Result<String, super::Error> {
        let token = self.require_authorization(ctx).await?;
        let req = self.request_headers(
            self.http_client
                .post("https://api.github.com/user/repos")
                .header("accept", "application/vnd.github+json")
                .json(&serde_json::json!({
                    "name": name,
                    "description": description,
                    "auto_init": false,
                })),
            Some(&token),
        );
        backoff::future::retry(self.backoff(), || async {
            let response = req
                .try_clone()
                .unwrap()
                .send()
                .await
                .map_err(|e| backoff::Error::transient(super::Error::RequestError(e)))?;
            let code = response.status();
            if code.is_success() {
                let body: serde_json::Value = response
                    .json()
                    .await
                    .map_err(|e| backoff::Error::transient(super::Error::ResponseError(e)))?;
                Ok(body["clone_url"].as_str().unwrap_or("").to_string())
            } else {
                Err(backoff::Error::transient(bad_status(response).await))
            }
        })
        .await
    }

    /// Updates the description of a GitHub repository.
    pub async fn update_description<CTXEXT: ctx::ContextExt>(
        &self,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
        owner: &str,
        repository: &str,
        description: &str,
    ) -> Result<(), super::Error> {
        let token = self.require_authorization(ctx).await?;
        let req = self.request_headers(
            self.http_client
                .patch(format!("https://api.github.com/repos/{}/{}", owner, repository))
                .header("accept", "application/vnd.github+json")
                .json(&serde_json::json!({ "description": description })),
            Some(&token),
        );
        backoff::future::retry(self.backoff(), || async {
            let response = req
                .try_clone()
                .unwrap()
                .send()
                .await
                .map_err(|e| backoff::Error::transient(super::Error::RequestError(e)))?;
            let code = response.status();
            if code.is_success() {
                Ok(())
            } else {
                Err(backoff::Error::transient(bad_status(response).await))
            }
        })
        .await
    }

    /// Publishes files to a GitHub repository. The owner is resolved
    /// internally from the request's commit-author name (falling back to
    /// the filesystem client's configured commit_author_name), matching
    /// how the local git commit is attributed.
    pub async fn publish<CTXEXT: ctx::ContextExt + Send + Sync>(
        &self,
        filesystem_client: &crate::filesystem::Client,
        ctx: &ctx::Context<CTXEXT, impl crate::ctx::persistent_cache::PersistentCacheClient>,
        repo: &str,
        description: &str,
        files: &[(&str, &str)],
    ) -> Result<objectiveai_sdk::RemotePath, super::Error> {
        // Resolve owner the same way the filesystem client does — from the
        // request context's commit-author name, with the client's own
        // configured commit_author_name as fallback. This guarantees that
        // the local commit author and the GitHub target namespace agree.
        let owner = ctx
            .commit_author_name()
            .await
            .map(|s| (*s).clone())
            .unwrap_or_else(|| filesystem_client.commit_author_name.clone());

        let exists = self.repository_exists(ctx, &owner, repo).await?;
        if !exists {
            self.create_repository(ctx, repo, description).await?;
        }

        let token = self.require_authorization(ctx).await?;
        let bare_token = strip_bearer(&token).to_string();
        let remote_url = format!("https://github.com/{}/{}.git", owner, repo);
        let commit_message = format!("Publish {}", repo);

        let (_commit_owner, commit_sha) = filesystem_client
            .publish_and_push(
                ctx,
                crate::retrieval::Kind::Functions,
                repo,
                files,
                &commit_message,
                &remote_url,
                &bare_token,
            )
            .await
            .map_err(super::Error::Filesystem)?;

        let _ = self.update_description(ctx, &owner, repo, description).await;

        Ok(objectiveai_sdk::RemotePath::Github {
            owner,
            repository: repo.to_string(),
            commit: commit_sha,
        })
    }
}

/// Extracts a bad status error from a response.
async fn bad_status(response: reqwest::Response) -> super::Error {
    let code = response.status();
    match response.text().await {
        Ok(text) => super::Error::BadStatus {
            code,
            body: serde_json::from_str::<serde_json::Value>(&text)
                .unwrap_or(serde_json::Value::String(text)),
        },
        Err(_) => super::Error::BadStatus {
            code,
            body: serde_json::Value::Null,
        },
    }
}

/// Ensures a token has the "Bearer " prefix.
fn ensure_bearer(token: &str) -> String {
    if token.starts_with("Bearer ") {
        token.to_string()
    } else {
        format!("Bearer {}", token)
    }
}

/// Strips the "Bearer " prefix from a token if present.
fn strip_bearer(token: &str) -> &str {
    token.strip_prefix("Bearer ").unwrap_or(token)
}