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
use tonic::{Response, Status};
use tracing::{info, warn};
use dk_engine::workspace::session_workspace::WorkspaceMode;
use crate::server::ProtocolServer;
use crate::{
ActiveSessionSummary, CodebaseSummary, ConnectRequest, ConnectResponse,
WorkspaceConcurrencyInfo,
};
/// Handle a CONNECT RPC.
///
/// 1. Validates the bearer token.
/// 2. Looks up the repository by name.
/// 3. Retrieves a high-level codebase summary (languages, symbol count, file count).
/// 4. Reads the HEAD commit hash as the current codebase version.
/// 5. Creates a stateful session and returns the session ID.
/// 6. Creates a session workspace (isolated overlay for file changes).
/// 7. Returns workspace ID and concurrency info.
pub async fn handle_connect(
server: &ProtocolServer,
req: ConnectRequest,
) -> Result<Response<ConnectResponse>, Status> {
// 1. Auth
let _authed_agent_id = server.validate_auth(&req.auth_token)?;
// Check for session resume.
//
// `take_snapshot` consumes the snapshot so it cannot be reused by a stale
// reconnect. When a valid snapshot is found, its `codebase_version` is
// used as the default base_commit so the resumed session starts from the
// same commit the old session was on.
let mut resumed_snapshot: Option<crate::session::SessionSnapshot> = None;
if let Some(ref ws_config) = req.workspace_config {
if let Some(ref resume_id_str) = ws_config.resume_session_id {
match resume_id_str.parse::<uuid::Uuid>() {
Ok(resume_id) => {
match server.session_mgr().take_snapshot(&resume_id) {
Some(snapshot) => {
if snapshot.codebase != req.codebase {
return Err(Status::invalid_argument(format!(
"Cannot resume session from codebase '{}' into '{}'",
snapshot.codebase, req.codebase
)));
}
info!(
resume_from = %resume_id,
agent_id = %snapshot.agent_id,
base_version = %snapshot.codebase_version,
"CONNECT: resuming from previous session snapshot"
);
resumed_snapshot = Some(snapshot);
}
None => {
warn!(
resume_session_id = %resume_id,
"CONNECT: resume requested but no snapshot found \
(session may have expired beyond snapshot TTL)"
);
}
}
}
Err(_) => {
return Err(Status::invalid_argument(format!(
"resume_session_id '{}' is not a valid UUID",
resume_id_str
)));
}
}
}
}
// Extract the requested base_commit early so it can be validated during
// the initial repo lookup (avoids a redundant `get_repo` call later).
// If resuming, default to the snapshot's codebase_version so the
// workspace starts from the same commit the old session was on.
let requested_base_commit = req
.workspace_config
.as_ref()
.and_then(|c| c.base_commit.clone())
.or_else(|| resumed_snapshot.as_ref().map(|s| s.codebase_version.clone()));
// 2-4. Resolve repo, get summary, read HEAD version, and validate
// base_commit if one was provided. Everything involving
// `GitRepository` (which is !Sync) is scoped inside a block so
// the future remains Send.
let engine = server.engine();
let (repo_id, version, summary) = {
let (repo_id, git_repo) = engine
.get_repo(&req.codebase)
.await
.map_err(|e| match e {
dk_core::Error::AmbiguousRepoName(_) => Status::invalid_argument(
format!("Ambiguous repository name: use the full 'owner/repo' form ({e})"),
),
_ => Status::not_found(format!("Repository not found: {e}")),
})?;
// HEAD commit hash (or "initial" for empty repos).
let version = git_repo
.head_hash()
.map_err(|e| Status::internal(format!("Failed to read HEAD: {e}")))?
.unwrap_or_else(|| "initial".to_string());
// Validate custom base_commit while we still hold git_repo, avoiding
// a second `get_repo` call.
if let Some(ref base) = requested_base_commit {
if base != &version && base != "initial" {
git_repo
.list_tree_files(base)
.map_err(|_| {
Status::invalid_argument(format!(
"base_commit '{base}' does not resolve to a valid commit"
))
})?;
}
}
// Drop git_repo before the next .await to keep the future Send.
drop(git_repo);
let summary = engine
.codebase_summary(repo_id)
.await
.map_err(|e| Status::internal(format!("Failed to get summary: {e}")))?;
(repo_id, version, summary)
};
// 5. Create session (session_mgr is lock-free / DashMap-based).
let session_id = server.session_mgr().create_session(
req.agent_id.clone(),
req.codebase.clone(),
req.intent.clone(),
version.clone(),
);
// 5a. Resolve agent name: use provided name or auto-assign.
let agent_name = if req.agent_name.is_empty() {
engine.workspace_manager().next_agent_name(&repo_id)
} else {
req.agent_name.clone()
};
// 5b. Create a changeset (staging area for file changes).
let changeset = engine
.changeset_store()
.create(repo_id, Some(session_id), &req.agent_id, &req.intent, Some(&version), &agent_name)
.await
.map_err(|e| Status::internal(format!("failed to create changeset: {e}")))?;
// 6. Determine workspace mode from request config
let ws_mode = match req.workspace_config.as_ref().map(|c| c.mode()) {
Some(crate::WorkspaceMode::Persistent) => WorkspaceMode::Persistent { expires_at: None },
_ => WorkspaceMode::Ephemeral,
};
// Use the provided base_commit or default to current HEAD version
let base_commit = requested_base_commit.unwrap_or_else(|| version.clone());
// Create the session workspace
let workspace_id = engine
.workspace_manager()
.create_workspace(
session_id,
repo_id,
req.agent_id.clone(),
changeset.id,
req.intent.clone(),
base_commit,
ws_mode,
agent_name.clone(),
)
.await
.map_err(|e| Status::internal(format!("failed to create workspace: {e}")))?;
// 7. Build concurrency info
let other_session_ids = engine
.workspace_manager()
.active_sessions_for_repo(repo_id, Some(session_id));
let mut other_sessions = Vec::new();
for other_sid in &other_session_ids {
if let Some(other_ws) = engine.workspace_manager().get_workspace(other_sid) {
// Gather just the paths (avoids cloning file content)
let active_files: Vec<String> = other_ws.overlay.list_paths();
other_sessions.push(ActiveSessionSummary {
agent_id: other_ws.agent_id.clone(),
intent: other_ws.intent.clone(),
active_files,
});
}
}
let concurrency = WorkspaceConcurrencyInfo {
active_sessions: (other_session_ids.len() + 1) as u32, // include this session
other_sessions,
};
info!(
session_id = %session_id,
changeset_id = %changeset.id,
workspace_id = %workspace_id,
agent_id = %req.agent_id,
agent_name = %agent_name,
codebase = %req.codebase,
active_sessions = concurrency.active_sessions,
"CONNECT: session, changeset, and workspace created"
);
Ok(Response::new(ConnectResponse {
session_id: session_id.to_string(),
codebase_version: version,
summary: Some(CodebaseSummary {
languages: summary.languages,
total_symbols: summary.total_symbols,
total_files: summary.total_files,
}),
changeset_id: changeset.id.to_string(),
workspace_id: workspace_id.to_string(),
concurrency: Some(concurrency),
}))
}