-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathsession.rs
More file actions
720 lines (665 loc) · 22.6 KB
/
session.rs
File metadata and controls
720 lines (665 loc) · 22.6 KB
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
use crate::routes::errors::ErrorResponse;
use crate::routes::recipe_utils::{apply_recipe_to_agent, build_recipe_with_parameter_values};
use crate::state::AppState;
use axum::extract::{DefaultBodyLimit, State};
use axum::routing::post;
use axum::{
extract::Path,
http::StatusCode,
routing::{delete, get, put},
Json, Router,
};
use goose::agents::ExtensionConfig;
use goose::recipe::Recipe;
use goose::session::nostr_share;
use goose::session::session_manager::{SessionInsights, SessionType};
use goose::session::{EnabledExtensionsState, Session};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use utoipa::ToSchema;
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct SessionListResponse {
/// List of available session information objects
sessions: Vec<Session>,
}
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct UpdateSessionNameRequest {
/// Updated name for the session (max 200 characters)
name: String,
}
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct UpdateSessionUserRecipeValuesRequest {
/// Recipe parameter values entered by the user
user_recipe_values: HashMap<String, String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct UpdateSessionUserRecipeValuesResponse {
recipe: Recipe,
}
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ImportSessionRequest {
json: String,
}
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ShareSessionNostrRequest {
relays: Option<Vec<String>>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ShareSessionNostrResponse {
deeplink: String,
nevent: String,
event_id: String,
relays: Vec<String>,
}
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ImportSessionNostrRequest {
deeplink: String,
}
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ForkRequest {
timestamp: Option<i64>,
truncate: bool,
copy: bool,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ForkResponse {
session_id: String,
}
const MAX_NAME_LENGTH: usize = 200;
#[utoipa::path(
get,
path = "/sessions",
responses(
(status = 200, description = "List of available sessions retrieved successfully", body = SessionListResponse),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn list_sessions(
State(state): State<Arc<AppState>>,
) -> Result<Json<SessionListResponse>, StatusCode> {
let sessions = state
.session_manager()
.list_sessions()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(SessionListResponse { sessions }))
}
#[utoipa::path(
get,
path = "/sessions/{session_id}",
params(
("session_id" = String, Path, description = "Unique identifier for the session")
),
responses(
(status = 200, description = "Session history retrieved successfully", body = Session),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 404, description = "Session not found"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn get_session(
State(state): State<Arc<AppState>>,
Path(session_id): Path<String>,
) -> Result<Json<Session>, StatusCode> {
let session = state
.session_manager()
.get_session(&session_id, true)
.await
.map_err(|_| StatusCode::NOT_FOUND)?;
Ok(Json(session))
}
#[utoipa::path(
get,
path = "/sessions/insights",
responses(
(status = 200, description = "Session insights retrieved successfully", body = SessionInsights),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn get_session_insights(
State(state): State<Arc<AppState>>,
) -> Result<Json<SessionInsights>, StatusCode> {
let insights = state
.session_manager()
.get_insights()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(insights))
}
#[utoipa::path(
put,
path = "/sessions/{session_id}/name",
request_body = UpdateSessionNameRequest,
params(
("session_id" = String, Path, description = "Unique identifier for the session")
),
responses(
(status = 200, description = "Session name updated successfully"),
(status = 400, description = "Bad request - Name too long (max 200 characters)"),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 404, description = "Session not found"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn update_session_name(
State(state): State<Arc<AppState>>,
Path(session_id): Path<String>,
Json(request): Json<UpdateSessionNameRequest>,
) -> Result<StatusCode, StatusCode> {
let name = request.name.trim();
if name.is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
if name.len() > MAX_NAME_LENGTH {
return Err(StatusCode::BAD_REQUEST);
}
state
.session_manager()
.update(&session_id)
.user_provided_name(name.to_string())
.apply()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(StatusCode::OK)
}
#[utoipa::path(
put,
path = "/sessions/{session_id}/user_recipe_values",
request_body = UpdateSessionUserRecipeValuesRequest,
params(
("session_id" = String, Path, description = "Unique identifier for the session")
),
responses(
(status = 200, description = "Session user recipe values updated successfully", body = UpdateSessionUserRecipeValuesResponse),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 404, description = "Session not found", body = ErrorResponse),
(status = 500, description = "Internal server error", body = ErrorResponse)
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
// Update session user recipe parameter values
async fn update_session_user_recipe_values(
State(state): State<Arc<AppState>>,
Path(session_id): Path<String>,
Json(request): Json<UpdateSessionUserRecipeValuesRequest>,
) -> Result<Json<UpdateSessionUserRecipeValuesResponse>, ErrorResponse> {
state
.session_manager()
.update(&session_id)
.user_recipe_values(Some(request.user_recipe_values))
.apply()
.await
.map_err(|err| ErrorResponse {
message: err.to_string(),
status: StatusCode::INTERNAL_SERVER_ERROR,
})?;
let session = state
.session_manager()
.get_session(&session_id, false)
.await
.map_err(|err| ErrorResponse {
message: err.to_string(),
status: StatusCode::INTERNAL_SERVER_ERROR,
})?;
let recipe = session.recipe.ok_or_else(|| ErrorResponse {
message: "Recipe not found".to_string(),
status: StatusCode::NOT_FOUND,
})?;
let user_recipe_values = session.user_recipe_values.unwrap_or_default();
match build_recipe_with_parameter_values(&recipe, user_recipe_values).await {
Ok(Some(recipe)) => {
let agent = state
.get_agent_for_route(session_id.clone())
.await
.map_err(|status| ErrorResponse {
message: format!("Failed to get agent: {}", status),
status,
})?;
if let Some(prompt) = apply_recipe_to_agent(&agent, &recipe, false).await {
agent
.extend_system_prompt("recipe".to_string(), prompt)
.await;
}
Ok(Json(UpdateSessionUserRecipeValuesResponse { recipe }))
}
Ok(None) => Err(ErrorResponse {
message: "Missing required parameters".to_string(),
status: StatusCode::BAD_REQUEST,
}),
Err(e) => Err(ErrorResponse {
message: e.to_string(),
status: StatusCode::INTERNAL_SERVER_ERROR,
}),
}
}
#[utoipa::path(
delete,
path = "/sessions/{session_id}",
params(
("session_id" = String, Path, description = "Unique identifier for the session")
),
responses(
(status = 200, description = "Session deleted successfully"),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 404, description = "Session not found"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn delete_session(
State(state): State<Arc<AppState>>,
Path(session_id): Path<String>,
) -> Result<StatusCode, StatusCode> {
state
.session_manager()
.delete_session(&session_id)
.await
.map_err(|e| {
if e.to_string().contains("not found") {
StatusCode::NOT_FOUND
} else {
StatusCode::INTERNAL_SERVER_ERROR
}
})?;
// Cancel any in-flight replies before dropping the bus, so spawned
// agent tasks stop consuming tokens for a deleted session.
if let Some(bus) = state.get_event_bus(&session_id).await {
bus.cancel_all_requests().await;
}
state.remove_event_bus(&session_id).await;
Ok(StatusCode::OK)
}
#[utoipa::path(
get,
path = "/sessions/{session_id}/export",
params(
("session_id" = String, Path, description = "Unique identifier for the session")
),
responses(
(status = 200, description = "Session exported successfully", body = String),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 404, description = "Session not found"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn export_session(
State(state): State<Arc<AppState>>,
Path(session_id): Path<String>,
) -> Result<Json<String>, StatusCode> {
let exported = state
.session_manager()
.export_session(&session_id)
.await
.map_err(|_| StatusCode::NOT_FOUND)?;
Ok(Json(exported))
}
#[utoipa::path(
post,
path = "/sessions/import",
request_body = ImportSessionRequest,
responses(
(status = 200, description = "Session imported successfully", body = Session),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 400, description = "Bad request - Invalid JSON"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn import_session(
State(state): State<Arc<AppState>>,
Json(request): Json<ImportSessionRequest>,
) -> Result<Json<Session>, StatusCode> {
let session = state
.session_manager()
.import_session(&request.json, Some(SessionType::User))
.await
.map_err(|_| StatusCode::BAD_REQUEST)?;
Ok(Json(session))
}
#[utoipa::path(
post,
path = "/sessions/{session_id}/share/nostr",
request_body = ShareSessionNostrRequest,
params(
("session_id" = String, Path, description = "Unique identifier for the session")
),
responses(
(status = 200, description = "Session shared to Nostr successfully", body = ShareSessionNostrResponse),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 404, description = "Session not found"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn share_session_nostr(
State(state): State<Arc<AppState>>,
Path(session_id): Path<String>,
Json(request): Json<ShareSessionNostrRequest>,
) -> Result<Json<ShareSessionNostrResponse>, StatusCode> {
let exported = state
.session_manager()
.export_session(&session_id)
.await
.map_err(|_| StatusCode::NOT_FOUND)?;
let relays = request.relays.unwrap_or_default();
let relays = nostr_share::resolve_relays(relays, goose::config::Config::global());
let share = nostr_share::publish_session_json(&exported, relays)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ShareSessionNostrResponse {
deeplink: share.deeplink,
nevent: share.nevent,
event_id: share.event_id,
relays: share.relays,
}))
}
#[utoipa::path(
post,
path = "/sessions/import/nostr",
request_body = ImportSessionNostrRequest,
responses(
(status = 200, description = "Nostr shared session imported successfully", body = Session),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 400, description = "Bad request - Invalid Nostr share link"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn import_session_nostr(
State(state): State<Arc<AppState>>,
Json(request): Json<ImportSessionNostrRequest>,
) -> Result<Json<Session>, StatusCode> {
let json = nostr_share::import_session_json_from_deeplink(&request.deeplink)
.await
.map_err(|_| StatusCode::BAD_REQUEST)?;
let session = state
.session_manager()
.import_session(&json, Some(SessionType::User))
.await
.map_err(|_| StatusCode::BAD_REQUEST)?;
Ok(Json(session))
}
#[utoipa::path(
post,
path = "/sessions/{session_id}/fork",
request_body = ForkRequest,
params(
("session_id" = String, Path, description = "Unique identifier for the session")
),
responses(
(status = 200, description = "Session forked successfully", body = ForkResponse),
(status = 400, description = "Bad request - truncate=true requires timestamp"),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 404, description = "Session not found"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn fork_session(
State(state): State<Arc<AppState>>,
Path(session_id): Path<String>,
Json(request): Json<ForkRequest>,
) -> Result<Json<ForkResponse>, ErrorResponse> {
if request.truncate && request.timestamp.is_none() {
return Err(ErrorResponse {
message: "truncate=true requires a timestamp".to_string(),
status: StatusCode::BAD_REQUEST,
});
}
let session_manager = state.session_manager();
let target_session_id = if request.copy {
let original = session_manager
.get_session(&session_id, false)
.await
.map_err(|e| {
tracing::error!("Failed to get session: {}", e);
#[cfg(feature = "telemetry")]
goose::posthog::emit_error("session_get_failed", &e.to_string());
ErrorResponse {
message: if e.to_string().contains("not found") {
format!("Session {} not found", session_id)
} else {
format!("Failed to get session: {}", e)
},
status: if e.to_string().contains("not found") {
StatusCode::NOT_FOUND
} else {
StatusCode::INTERNAL_SERVER_ERROR
},
}
})?;
let copied = session_manager
.copy_session(&session_id, original.name)
.await
.map_err(|e| {
tracing::error!("Failed to copy session: {}", e);
#[cfg(feature = "telemetry")]
goose::posthog::emit_error("session_copy_failed", &e.to_string());
ErrorResponse {
message: format!("Failed to copy session: {}", e),
status: StatusCode::INTERNAL_SERVER_ERROR,
}
})?;
copied.id
} else {
session_id.clone()
};
if request.truncate {
session_manager
.truncate_conversation(&target_session_id, request.timestamp.unwrap_or(0))
.await
.map_err(|e| {
tracing::error!("Failed to truncate conversation: {}", e);
#[cfg(feature = "telemetry")]
goose::posthog::emit_error("session_truncate_failed", &e.to_string());
ErrorResponse {
message: format!("Failed to truncate conversation: {}", e),
status: StatusCode::INTERNAL_SERVER_ERROR,
}
})?;
}
Ok(Json(ForkResponse {
session_id: target_session_id,
}))
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct SessionExtensionsResponse {
extensions: Vec<ExtensionConfig>,
}
#[utoipa::path(
get,
path = "/sessions/{session_id}/extensions",
params(
("session_id" = String, Path, description = "Unique identifier for the session")
),
responses(
(status = 200, description = "Session extensions retrieved successfully", body = SessionExtensionsResponse),
(status = 401, description = "Unauthorized - Invalid or missing API key"),
(status = 404, description = "Session not found"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn get_session_extensions(
State(state): State<Arc<AppState>>,
Path(session_id): Path<String>,
) -> Result<Json<SessionExtensionsResponse>, StatusCode> {
let session = state
.session_manager()
.get_session(&session_id, false)
.await
.map_err(|_| StatusCode::NOT_FOUND)?;
let extensions = EnabledExtensionsState::extensions_or_default(
Some(&session.extension_data),
goose::config::Config::global(),
);
Ok(Json(SessionExtensionsResponse { extensions }))
}
pub fn routes(state: Arc<AppState>) -> Router {
Router::new()
.route("/sessions", get(list_sessions))
.route("/sessions/search", get(search_sessions))
.route("/sessions/{session_id}", get(get_session))
.route("/sessions/{session_id}", delete(delete_session))
.route("/sessions/{session_id}/export", get(export_session))
.route(
"/sessions/{session_id}/share/nostr",
post(share_session_nostr).layer(DefaultBodyLimit::max(25 * 1024 * 1024)),
)
.route(
"/sessions/import",
post(import_session).layer(DefaultBodyLimit::max(25 * 1024 * 1024)),
)
.route(
"/sessions/import/nostr",
post(import_session_nostr).layer(DefaultBodyLimit::max(25 * 1024 * 1024)),
)
.route("/sessions/insights", get(get_session_insights))
.route("/sessions/{session_id}/name", put(update_session_name))
.route(
"/sessions/{session_id}/user_recipe_values",
put(update_session_user_recipe_values),
)
.route("/sessions/{session_id}/fork", post(fork_session))
.route(
"/sessions/{session_id}/extensions",
get(get_session_extensions),
)
.with_state(state)
}
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct SearchSessionsQuery {
/// Search query string (keywords separated by spaces)
query: String,
/// Maximum number of results to return (default: 10, max: 50)
#[serde(default = "default_limit")]
limit: usize,
/// Filter results to sessions after this date (ISO 8601 format)
after_date: Option<String>,
/// Filter results to sessions before this date (ISO 8601 format)
before_date: Option<String>,
}
fn default_limit() -> usize {
10
}
#[utoipa::path(
get,
path = "/sessions/search",
params(
("query" = String, Query, description = "Search query string"),
("limit" = Option<usize>, Query, description = "Maximum results (default: 10, max: 50)"),
("after_date" = Option<String>, Query, description = "Filter after date (ISO 8601)"),
("before_date" = Option<String>, Query, description = "Filter before date (ISO 8601)")
),
responses(
(status = 200, description = "Matching sessions", body = Vec<Session>),
(status = 400, description = "Bad request - Invalid query"),
(status = 401, description = "Unauthorized"),
(status = 500, description = "Internal server error")
),
security(
("api_key" = [])
),
tag = "Session Management"
)]
async fn search_sessions(
State(state): State<Arc<AppState>>,
axum::extract::Query(params): axum::extract::Query<SearchSessionsQuery>,
) -> Result<Json<Vec<Session>>, StatusCode> {
let query = params.query.trim();
if query.is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
let limit = params.limit.min(50);
let after_date = params
.after_date
.and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())
.map(|dt| dt.with_timezone(&chrono::Utc));
let before_date = params
.before_date
.and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())
.map(|dt| dt.with_timezone(&chrono::Utc));
let search_results = state
.session_manager()
.search_chat_history(
query,
Some(limit),
after_date,
before_date,
None,
vec![SessionType::User, SessionType::Scheduled],
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Get full Session objects for matching session IDs
let session_ids: Vec<String> = search_results
.results
.into_iter()
.map(|r| r.session_id)
.collect();
let all_sessions = state
.session_manager()
.list_sessions()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let matching_sessions: Vec<Session> = all_sessions
.into_iter()
.filter(|s| session_ids.contains(&s.id))
.collect();
Ok(Json(matching_sessions))
}