Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47a6e54660 | ||
|
|
206ca784f7 | ||
|
|
a438c1df42 | ||
|
|
aed83268a0 | ||
|
|
12d8a3d490 | ||
|
|
e57ab47c05 | ||
|
|
1baeefe889 | ||
|
|
9567bbf3aa | ||
|
|
54ce770682 |
No files matched your search
@@ -145,50 +145,15 @@ jobs:
|
|||||||
docker --version
|
docker --version
|
||||||
|
|
||||||
|
|
||||||
- name: Detect UI changes
|
|
||||||
id: ui-diff
|
|
||||||
env:
|
|
||||||
FEATURE_VALIDATION: ${{ inputs.validation_level == 'feature' || contains(gitea.event.pull_request.labels.*.name, 'feature-ready') }}
|
|
||||||
BASE_SHA: ${{ gitea.event.pull_request.base.sha || gitea.event.before }}
|
|
||||||
run: |
|
|
||||||
run_ui=true
|
|
||||||
reason="no reliable base revision; checking UI conservatively"
|
|
||||||
|
|
||||||
if [ "$FEATURE_VALIDATION" = "true" ]; then
|
|
||||||
reason="feature validation requested"
|
|
||||||
elif [[ ! "$BASE_SHA" =~ ^([0-9a-fA-F]{40}|[0-9a-fA-F]{64})$ ]] || [[ "$BASE_SHA" =~ ^0+$ ]]; then
|
|
||||||
: # Keep the conservative default when the event has no usable base.
|
|
||||||
else
|
|
||||||
if ! git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null; then
|
|
||||||
git fetch --no-tags --depth=1 origin "$BASE_SHA" >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
if git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null && git diff --quiet "$BASE_SHA" HEAD -- apps/ui/ crank-community.png; then
|
|
||||||
run_ui=false
|
|
||||||
reason="UI inputs are unchanged from the event base"
|
|
||||||
else
|
|
||||||
reason="apps/ui changed or the base comparison was unavailable"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "run_ui=$run_ui" >> "$GITHUB_OUTPUT"
|
|
||||||
if [ "$run_ui" = "false" ]; then
|
|
||||||
echo "UI checks not applicable: $reason."
|
|
||||||
else
|
|
||||||
echo "Running UI checks: $reason."
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Install UI dependencies
|
- name: Install UI dependencies
|
||||||
if: steps.ui-diff.outputs.run_ui == 'true'
|
|
||||||
working-directory: apps/ui
|
working-directory: apps/ui
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
||||||
- name: Audit UI dependencies
|
- name: Audit UI dependencies
|
||||||
if: steps.ui-diff.outputs.run_ui == 'true'
|
|
||||||
working-directory: apps/ui
|
working-directory: apps/ui
|
||||||
run: npm audit --audit-level=high
|
run: npm audit --audit-level=high
|
||||||
|
|
||||||
- name: Build UI bundle
|
- name: Build UI bundle
|
||||||
if: steps.ui-diff.outputs.run_ui == 'true'
|
|
||||||
working-directory: apps/ui
|
working-directory: apps/ui
|
||||||
run: npm run build
|
run: npm run build
|
||||||
|
|
||||||
|
|||||||
@@ -212,7 +212,9 @@ jobs:
|
|||||||
- name: Publish release bundles, checksums, evidence, and SBOM to Gitea
|
- name: Publish release bundles, checksums, evidence, and SBOM to Gitea
|
||||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||||
env:
|
env:
|
||||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
# gitea.server_url inside the job container is the internal http://gitea:3000 origin;
|
||||||
|
# the publisher only forwards its token to the public HTTPS origin.
|
||||||
|
GITEA_SERVER_URL: https://git.itexp.me
|
||||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||||
RELEASE_TAG: ${{ gitea.ref_name }}
|
RELEASE_TAG: ${{ gitea.ref_name }}
|
||||||
|
|||||||
@@ -241,6 +241,11 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
triples,
|
triples,
|
||||||
vec![
|
vec![
|
||||||
|
(
|
||||||
|
"server".to_owned(),
|
||||||
|
"capability".to_owned(),
|
||||||
|
"logging".to_owned()
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"server".to_owned(),
|
"server".to_owned(),
|
||||||
"capability".to_owned(),
|
"capability".to_owned(),
|
||||||
@@ -262,7 +267,7 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio
|
|||||||
"tools".to_owned()
|
"tools".to_owned()
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
"the advertised server capabilities of the current scope are `completions`, `prompts`, `resources` and `tools`"
|
"the advertised server capabilities of the current scope are `logging`, `completions`, `prompts`, `resources` and `tools`"
|
||||||
);
|
);
|
||||||
|
|
||||||
// The sidecar is not the payload: byte comparison is against the frozen file only.
|
// The sidecar is not the payload: byte comparison is against the frozen file only.
|
||||||
|
|||||||
@@ -454,6 +454,18 @@ async fn a_request_value_can_never_reach_a_notification() {
|
|||||||
"the positive control must reflect the canary in the error message, got {message:?}"
|
"the positive control must reflect the canary in the error message, got {message:?}"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Positive control on delivery: the event is really delivered and its body is exactly the
|
||||||
|
// closed one for a rejected request, so the canary assertions below cannot pass vacuously.
|
||||||
|
assert_eq!(
|
||||||
|
reply.notifications,
|
||||||
|
vec![expected_notification(
|
||||||
|
"warning",
|
||||||
|
"mcp.request.rejected",
|
||||||
|
"invalid_params"
|
||||||
|
)],
|
||||||
|
"a rejected request must deliver exactly one safe warning event"
|
||||||
|
);
|
||||||
|
|
||||||
// The delivered notification is exactly the closed safe body: no canary, no argument value.
|
// The delivered notification is exactly the closed safe body: no canary, no argument value.
|
||||||
for notification in &reply.notifications {
|
for notification in &reply.notifications {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -724,6 +736,45 @@ async fn the_modern_era_has_no_set_level_method() {
|
|||||||
assert!(after.notifications.is_empty());
|
assert!(after.notifications.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// AT-3.18-01/03: a method this era does not implement is a pinned client error, so the safe event
|
||||||
|
/// of an opted-in client describes a client-side rejection, never an internal server failure.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_unknown_method_is_a_rejection_not_an_internal_failure() {
|
||||||
|
let endpoint = logging_endpoint().await;
|
||||||
|
let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await;
|
||||||
|
endpoint.set_level(&session, json!("info")).await;
|
||||||
|
|
||||||
|
// `server/discover` is a modern-era method, so the legacy adapter answers it with -32601.
|
||||||
|
let reply = endpoint
|
||||||
|
.legacy_post(
|
||||||
|
AGENT_SLUG,
|
||||||
|
&endpoint.api_key,
|
||||||
|
&session,
|
||||||
|
json!({
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 71,
|
||||||
|
"method": "server/discover",
|
||||||
|
"params": {}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
reply.error().0,
|
||||||
|
-32601,
|
||||||
|
"an unimplemented method is a pinned client error: {}",
|
||||||
|
reply.response
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
reply.notifications,
|
||||||
|
vec![expected_notification(
|
||||||
|
"warning",
|
||||||
|
"mcp.request.rejected",
|
||||||
|
"invalid_params"
|
||||||
|
)],
|
||||||
|
"a pinned client error must not be reported as an internal failure"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// AT-3.18-01/03 (independence): a level belongs to one client context, so a second session and a
|
/// AT-3.18-01/03 (independence): a level belongs to one client context, so a second session and a
|
||||||
/// second Agent keep their own (or no) level.
|
/// second Agent keep their own (or no) level.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -114,8 +114,8 @@ fn now_rfc3339() -> String {
|
|||||||
.unwrap_or_else(|error| format!("unformatted-utc ({error})"))
|
.unwrap_or_else(|error| format!("unformatted-utc ({error})"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A single timed `resources/list`, built directly on `reqwest` so transport/timeout/HTTP failures are
|
/// A single timed `resources/list` call, built directly on `reqwest` so transport/timeout/HTTP
|
||||||
/// recorded as outcomes instead of aborting the run.
|
/// failures are recorded as outcomes instead of aborting the run.
|
||||||
async fn timed_list(
|
async fn timed_list(
|
||||||
endpoint: &ResourceEndpoint,
|
endpoint: &ResourceEndpoint,
|
||||||
revision: &'static str,
|
revision: &'static str,
|
||||||
|
|||||||
+94
-25
@@ -1,18 +1,56 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use std::process::Command;
|
use std::{
|
||||||
|
env,
|
||||||
|
io::{Read, Write},
|
||||||
|
net::{TcpListener, TcpStream, ToSocketAddrs},
|
||||||
|
process::Command,
|
||||||
|
thread,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
pub(super) struct TestValkey(String);
|
pub(super) struct TestValkey(String);
|
||||||
|
|
||||||
impl TestValkey {
|
impl TestValkey {
|
||||||
pub(super) fn start() -> (Self, u16) {
|
pub(super) fn start() -> (Self, u16) {
|
||||||
let output = Command::new("docker")
|
let in_docker_job = if std::path::Path::new("/.dockerenv").exists() {
|
||||||
.args([
|
let hostname = env::var("HOSTNAME").unwrap_or_default();
|
||||||
"run",
|
assert!(
|
||||||
"--detach",
|
matches!(hostname.len(), 12 | 64)
|
||||||
"--publish",
|
&& hostname.bytes().all(|byte| byte.is_ascii_hexdigit()),
|
||||||
"127.0.0.1::6379",
|
"Docker job hostname must be a full 12- or 64-character container ID"
|
||||||
"valkey/valkey:8-alpine",
|
);
|
||||||
])
|
Some(hostname)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let port = if in_docker_job.is_some() {
|
||||||
|
let listener = TcpListener::bind(("127.0.0.1", 0))
|
||||||
|
.expect("test-owned Valkey loopback port must be available");
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
drop(listener);
|
||||||
|
Some(port)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut docker = Command::new("docker");
|
||||||
|
docker.args([
|
||||||
|
"run",
|
||||||
|
"--detach",
|
||||||
|
"--label",
|
||||||
|
"crank.test.fixture=static-resources-valkey",
|
||||||
|
]);
|
||||||
|
if let (Some(hostname), Some(port)) = (&in_docker_job, port) {
|
||||||
|
docker
|
||||||
|
.arg("--network")
|
||||||
|
.arg(format!("container:{hostname}"))
|
||||||
|
.arg("valkey/valkey:8-alpine")
|
||||||
|
.args(["valkey-server", "--port", &port.to_string()]);
|
||||||
|
} else {
|
||||||
|
docker.args(["--publish", "127.0.0.1::6379", "valkey/valkey:8-alpine"]);
|
||||||
|
}
|
||||||
|
let output = docker
|
||||||
.output()
|
.output()
|
||||||
.expect("Docker CLI must start the test-owned Valkey container");
|
.expect("Docker CLI must start the test-owned Valkey container");
|
||||||
assert!(
|
assert!(
|
||||||
@@ -25,22 +63,29 @@ impl TestValkey {
|
|||||||
.trim()
|
.trim()
|
||||||
.to_owned();
|
.to_owned();
|
||||||
let valkey = Self(id);
|
let valkey = Self(id);
|
||||||
let port_output = Command::new("docker")
|
let port = match port {
|
||||||
.args(["port", &valkey.0, "6379/tcp"])
|
Some(port) => port,
|
||||||
.output()
|
None => {
|
||||||
.expect("Docker CLI must report the test-owned port");
|
let port_output = Command::new("docker")
|
||||||
assert!(
|
.args(["port", &valkey.0, "6379/tcp"])
|
||||||
port_output.status.success(),
|
.output()
|
||||||
"test-owned Valkey port must be available"
|
.expect("Docker CLI must report the test-owned port");
|
||||||
);
|
assert!(
|
||||||
let address = String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
|
port_output.status.success(),
|
||||||
let port = address
|
"test-owned Valkey port must be available"
|
||||||
.trim()
|
);
|
||||||
.rsplit(':')
|
let address =
|
||||||
.next()
|
String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
|
||||||
.unwrap()
|
address
|
||||||
.parse()
|
.trim()
|
||||||
.expect("Docker mapped port must be numeric");
|
.rsplit(':')
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.parse()
|
||||||
|
.expect("Docker mapped port must be numeric")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
wait_for_valkey(port);
|
||||||
(valkey, port)
|
(valkey, port)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,6 +98,30 @@ impl TestValkey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn wait_for_valkey(port: u16) {
|
||||||
|
let address = ("127.0.0.1", port)
|
||||||
|
.to_socket_addrs()
|
||||||
|
.expect("test-owned Valkey loopback address must resolve")
|
||||||
|
.next()
|
||||||
|
.unwrap();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
if let Ok(mut stream) = TcpStream::connect_timeout(&address, Duration::from_millis(250)) {
|
||||||
|
let _ = stream.set_read_timeout(Some(Duration::from_millis(250)));
|
||||||
|
let _ = stream.set_write_timeout(Some(Duration::from_millis(250)));
|
||||||
|
let mut reply = [0_u8; 7];
|
||||||
|
if stream.write_all(b"*1\r\n$4\r\nPING\r\n").is_ok()
|
||||||
|
&& stream.read_exact(&mut reply).is_ok()
|
||||||
|
&& &reply == b"+PONG\r\n"
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
thread::sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
panic!("test-owned Valkey did not answer PING on 127.0.0.1:{port} within 10 seconds");
|
||||||
|
}
|
||||||
|
|
||||||
impl Drop for TestValkey {
|
impl Drop for TestValkey {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
|
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@ COPY crank-community.png ./crank-community.png
|
|||||||
|
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM nginx:1.30.4-alpine3.24-slim
|
FROM nginx:1.30.6-alpine3.24-slim
|
||||||
|
|
||||||
RUN apk add --no-cache --upgrade \
|
RUN apk add --no-cache --upgrade \
|
||||||
'pcre2>=10.49-r0' \
|
'pcre2>=10.49-r0' \
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ mod approvals;
|
|||||||
mod auth_resolution;
|
mod auth_resolution;
|
||||||
mod dispatch;
|
mod dispatch;
|
||||||
mod endpoint;
|
mod endpoint;
|
||||||
|
mod legacy_dispatch;
|
||||||
|
|
||||||
use self::approvals::{
|
use self::approvals::{
|
||||||
approve_request, deny_request, get_approval_request, list_pending_approvals,
|
approve_request, deny_request, get_approval_request, list_pending_approvals,
|
||||||
|
|||||||
@@ -3,29 +3,19 @@
|
|||||||
//!
|
//!
|
||||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); `mcp_post_response` is reached from
|
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); `mcp_post_response` is reached from
|
||||||
//! `build_app_inner` via `mcp_post`, hence `pub(super)`. No behaviour changed.
|
//! `build_app_inner` via `mcp_post`, hence `pub(super)`. No behaviour changed.
|
||||||
|
//!
|
||||||
|
//! The legacy-era dispatch itself lives in `super::legacy_dispatch` (Story 3.18 code-health, kanban
|
||||||
|
//! t_d1b45ddc) to keep this transport entry file inside the 1000-line limit.
|
||||||
|
|
||||||
use super::metrics::{ActiveStreamGuard, McpRequestMetrics};
|
use super::metrics::{ActiveStreamGuard, McpRequestMetrics};
|
||||||
use super::request::ToolCallParams;
|
|
||||||
use super::response::take_confirmation_token;
|
|
||||||
use super::stages::{enforce_traced_rate_limit, require_traced_machine_access};
|
use super::stages::{enforce_traced_rate_limit, require_traced_machine_access};
|
||||||
use crate::{
|
use crate::{
|
||||||
jsonrpc::{
|
jsonrpc::{jsonrpc_error, method_name, request_id},
|
||||||
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
|
|
||||||
method_name, params, request_id,
|
|
||||||
},
|
|
||||||
protocol::{
|
protocol::{
|
||||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
|
EnvelopeKind, RequestEra, ambiguous_session_carrier_response, resolve_request_identity,
|
||||||
EVENT_LEVEL_APPLIED, EnvelopeKind, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler,
|
|
||||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestEra,
|
|
||||||
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
|
||||||
ServiceContext, SetLevelCommand, ToolCallCommand, ToolsCommand, ToolsListCommand,
|
|
||||||
ToolsOutcome, ambiguous_session_carrier_response, handle_completion_command,
|
|
||||||
handle_logging_command, handle_prompts_command, handle_resources_command,
|
|
||||||
handle_tools_command, resolve_request_identity,
|
|
||||||
},
|
},
|
||||||
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
|
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
|
||||||
request_context::RequestContext,
|
request_context::RequestContext,
|
||||||
tool_error::execution_locale,
|
|
||||||
transport::{
|
transport::{
|
||||||
accepts_event_stream, negotiate_post_response_mode, session_id_from_headers, sse_response,
|
accepts_event_stream, negotiate_post_response_mode, session_id_from_headers, sse_response,
|
||||||
transport_response, validate_get_accept_header, validate_origin,
|
transport_response, validate_get_accept_header, validate_origin,
|
||||||
@@ -40,20 +30,11 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use crank_core::{CorrelationContext, PlatformApiKeyScope};
|
use crank_core::{CorrelationContext, PlatformApiKeyScope};
|
||||||
use futures_util::stream;
|
use futures_util::stream;
|
||||||
use serde_json::{Value, json};
|
use serde_json::Value;
|
||||||
use std::{convert::Infallible, sync::Arc, time::Duration};
|
use std::{convert::Infallible, sync::Arc, time::Duration};
|
||||||
use tracing::info;
|
use tracing::info;
|
||||||
|
|
||||||
use super::dispatch::{
|
use super::dispatch::handle_modern_request;
|
||||||
handle_initialize, handle_initialized_notification, handle_modern_request,
|
|
||||||
require_initialized_session,
|
|
||||||
};
|
|
||||||
use super::response::{
|
|
||||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
|
||||||
prompts_list_result, resource_error_response, resource_read_result,
|
|
||||||
resource_templates_list_result, resources_list_result, tool_command_response,
|
|
||||||
tools_list_result,
|
|
||||||
};
|
|
||||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||||
pub(super) async fn mcp_get(
|
pub(super) async fn mcp_get(
|
||||||
Path(path): Path<AgentRoutePath>,
|
Path(path): Path<AgentRoutePath>,
|
||||||
@@ -384,675 +365,17 @@ async fn mcp_post_response(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
crate::app::dispatch_observer::era_legacy_enter();
|
crate::app::dispatch_observer::era_legacy_enter();
|
||||||
|
|
||||||
// R5/F5: the owning registration decides *which handler* serves this method in the request's
|
// R5/F5: the owning registration decides which handler serves this method in the request's
|
||||||
// revision. The adapter holds no method list of its own — the method-to-handler mapping lives in
|
// revision; that legacy dispatch lives in `super::legacy_dispatch`.
|
||||||
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
|
super::legacy_dispatch::handle_legacy_request(
|
||||||
// really reaches its handler and removing a descriptor removes the dispatch.
|
state,
|
||||||
let registration_revision = protocol_version
|
path,
|
||||||
.as_deref()
|
headers,
|
||||||
.unwrap_or(LEGACY_PROTOCOL_VERSION);
|
message,
|
||||||
let dispatch = crate::protocol::dispatch_decision(
|
response_mode,
|
||||||
method_name(message).unwrap_or_default(),
|
&identity,
|
||||||
registration_revision,
|
&credential,
|
||||||
);
|
transport_correlation,
|
||||||
match dispatch {
|
)
|
||||||
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
|
.await
|
||||||
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
|
|
||||||
// notification: the two share one handler but are not interchangeable, so an `initialize`
|
|
||||||
// notification may not initialize an existing session and a `notifications/initialized`
|
|
||||||
// request may not create one.
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::Lifecycle,
|
|
||||||
kind: Kind::Method,
|
|
||||||
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::Lifecycle,
|
|
||||||
kind: Kind::Notification,
|
|
||||||
} if is_notification(message) => {
|
|
||||||
handle_initialized_notification(state, path, headers).await
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::Ping,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
|
|
||||||
transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
json!({ "protocolVersion": session.protocol_version }),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ToolList,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
|
|
||||||
// The adapter parses the wire form and maps the neutral outcome back; the shared Tools
|
|
||||||
// service never sees the envelope, the response mode or the protocol revision.
|
|
||||||
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(value) => value,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_tools_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
ToolsCommand::List(list_command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, message_text),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ToolsOutcome::CatalogUnavailable => {
|
|
||||||
internal_jsonrpc_error(message, "published catalog is unavailable")
|
|
||||||
}
|
|
||||||
// A list command never produces a call outcome; it is answered with the adapter's
|
|
||||||
// internal error instead of being silently ignored.
|
|
||||||
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
|
||||||
message,
|
|
||||||
"unexpected shared tools outcome for a tools/list",
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ToolCall,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(value) => value,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// The adapter owns the wire form: it parses the call parameters, removes the reserved
|
|
||||||
// confirmation marker and the shared Tools service never sees the envelope, the
|
|
||||||
// response mode or the protocol revision (spec section 6.2).
|
|
||||||
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
|
||||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
|
||||||
let outcome = handle_tools_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
ToolsCommand::Call(ToolCallCommand {
|
|
||||||
tool_name: tool_call_params.name,
|
|
||||||
arguments,
|
|
||||||
confirmation_token,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
tool_command_response(
|
|
||||||
message,
|
|
||||||
response_mode,
|
|
||||||
&session.protocol_version,
|
|
||||||
transport_correlation,
|
|
||||||
outcome,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ResourceList,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(value) => value,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid resources/list parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_resources_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
ResourcesCommand::List(list_command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
ResourcesOutcome::Listed {
|
|
||||||
resources,
|
|
||||||
next_cursor,
|
|
||||||
} => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
resources_list_result(resources, next_cursor),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ResourceRead,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(value) => value,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid resources/read parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_resources_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
ResourcesCommand::Read(read_command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
ResourcesOutcome::Read { contents } => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ResourcesOutcome::NotAvailable => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"the requested resource is not available",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
ResourcesOutcome::ExecutionError(contract) => resource_error_response(
|
|
||||||
message,
|
|
||||||
response_mode,
|
|
||||||
&session.protocol_version,
|
|
||||||
contract,
|
|
||||||
),
|
|
||||||
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Story 3.11: the shared service returns exact bound Published templates; the legacy adapter
|
|
||||||
// retains its earlier result shape and still requires the initialized session.
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::ResourceTemplateList,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
|
|
||||||
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid resources/templates/list parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
|
||||||
&state,
|
|
||||||
&path.workspace_slug,
|
|
||||||
&path.agent_slug,
|
|
||||||
&session.protocol_version,
|
|
||||||
command,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(page) => page,
|
|
||||||
Err(crate::protocol::ResourceTemplatesListError::InvalidCursor) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid resources/templates/list cursor",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(crate::protocol::ResourceTemplatesListError::Unavailable) => {
|
|
||||||
return internal_jsonrpc_error(message, "published templates are unavailable");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
resource_templates_list_result(templates, next_cursor),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
// Story 3.14: `prompts/list` / `prompts/get` of the initialized legacy session, served from
|
|
||||||
// the same exact bound Published Prompt Versions as the modern era.
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::PromptList,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid prompts/list parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_prompts_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
PromptsCommand::List(command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
PromptsOutcome::Listed {
|
|
||||||
prompts,
|
|
||||||
next_cursor,
|
|
||||||
} => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
prompts_list_result(prompts, next_cursor),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::PromptGet,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid prompts/get parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_prompts_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
PromptsCommand::Get(command),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
PromptsOutcome::Got {
|
|
||||||
description,
|
|
||||||
messages,
|
|
||||||
} => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
prompt_get_result(description, messages),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
PromptsOutcome::NotAvailable => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"the requested prompt is not available",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
|
||||||
prompt_arguments_error_response(
|
|
||||||
message,
|
|
||||||
response_mode,
|
|
||||||
&session.protocol_version,
|
|
||||||
reason,
|
|
||||||
argument,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
PromptsOutcome::DependencyUnavailable { position } => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32603,
|
|
||||||
format!("the pinned dependency at dependencies[{position}] is unavailable"),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
PromptsOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Story 3.17: `completion/complete` of the initialized legacy session. The shared service is
|
|
||||||
// the same one the modern era uses; only the result envelope differs (no `resultType`).
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::Completion,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let command: CompletionCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"invalid completion/complete parameters",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let outcome = handle_completion_command(
|
|
||||||
&state,
|
|
||||||
ServiceContext {
|
|
||||||
workspace_slug: &session.workspace_slug,
|
|
||||||
agent_slug: &session.agent_slug,
|
|
||||||
credential: &credential,
|
|
||||||
correlation: transport_correlation,
|
|
||||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
|
||||||
locale: execution_locale(message),
|
|
||||||
},
|
|
||||||
&session.protocol_version,
|
|
||||||
command,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
match outcome {
|
|
||||||
CompletionOutcome::Completed {
|
|
||||||
values,
|
|
||||||
total,
|
|
||||||
has_more,
|
|
||||||
} => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(
|
|
||||||
request_id(message),
|
|
||||||
completion_result(values, total, has_more),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
CompletionOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
CompletionOutcome::NotAvailable => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32602,
|
|
||||||
"the completion reference is not available",
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
CompletionOutcome::CatalogUnavailable => {
|
|
||||||
internal_jsonrpc_error(message, "published completion sources are unavailable")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Story 3.18: the pinned legacy `logging/setLevel`. The level belongs to the initialized
|
|
||||||
// session of this request, so setting it can never change another client's level. The request
|
|
||||||
// answers an empty result; the acknowledgment event is filtered by the level it just set.
|
|
||||||
DispatchDecision::Allowed {
|
|
||||||
handler: MethodHandler::LoggingSetLevel,
|
|
||||||
..
|
|
||||||
} if is_request(message) => {
|
|
||||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
|
||||||
Ok(session) => session,
|
|
||||||
Err(response) => return response,
|
|
||||||
};
|
|
||||||
let command: SetLevelCommand = match serde_json::from_value(params(message)) {
|
|
||||||
Ok(command) => command,
|
|
||||||
// A non-string, missing or otherwise unparsable level shares the one safe detail of a
|
|
||||||
// value outside the pinned union: nothing the client sent is echoed back.
|
|
||||||
Err(_) => {
|
|
||||||
return transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, INVALID_LEVEL),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
match handle_logging_command(&state.logging_levels, &session.id, command) {
|
|
||||||
LoggingOutcome::Applied(level) => {
|
|
||||||
crate::protocol::set_active_level(Some(level));
|
|
||||||
crate::protocol::note(
|
|
||||||
crate::protocol::LogLevel::Notice,
|
|
||||||
EVENT_LEVEL_APPLIED,
|
|
||||||
"applied",
|
|
||||||
);
|
|
||||||
transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_result(request_id(message), json!({})),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
LoggingOutcome::InvalidParams(detail) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(request_id(message), -32602, detail),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
Some(&session.protocol_version),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A notification whose method the registration does not map to this adapter's handlers is
|
|
||||||
// acknowledged without being dispatched, exactly as before.
|
|
||||||
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
|
||||||
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
|
|
||||||
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
|
|
||||||
_ => match method_name(message) {
|
|
||||||
Some(method) => transport_response(
|
|
||||||
StatusCode::OK,
|
|
||||||
jsonrpc_error(
|
|
||||||
request_id(message),
|
|
||||||
-32601,
|
|
||||||
format!("method {method} is not supported"),
|
|
||||||
),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
protocol_version.as_deref(),
|
|
||||||
),
|
|
||||||
None => transport_response(
|
|
||||||
StatusCode::BAD_REQUEST,
|
|
||||||
jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC message"),
|
|
||||||
response_mode,
|
|
||||||
None,
|
|
||||||
protocol_version.as_deref(),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,731 @@
|
|||||||
|
//! Legacy-era JSON-RPC dispatch: the registered method-to-handler mapping, the
|
||||||
|
//! initialized-session guard and every legacy envelope the transport endpoint answers.
|
||||||
|
//!
|
||||||
|
//! Moved verbatim out of `app/endpoint.rs` (Story 3.18 code-health, kanban t_d1b45ddc) so the
|
||||||
|
//! transport entry file stays inside the 1000-line limit; the entry point is `pub(super)`.
|
||||||
|
//! No behaviour changed.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
http::{HeaderMap, StatusCode},
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use crank_core::CorrelationContext;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use super::dispatch::{
|
||||||
|
handle_initialize, handle_initialized_notification, require_initialized_session,
|
||||||
|
};
|
||||||
|
use super::request::ToolCallParams;
|
||||||
|
use super::response::{
|
||||||
|
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||||
|
prompts_list_result, resource_error_response, resource_read_result,
|
||||||
|
resource_templates_list_result, resources_list_result, take_confirmation_token,
|
||||||
|
tool_command_response, tools_list_result,
|
||||||
|
};
|
||||||
|
use super::{AgentRoutePath, AppState};
|
||||||
|
use crate::{
|
||||||
|
auth::VerifiedMachineCredential,
|
||||||
|
jsonrpc::{
|
||||||
|
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
|
||||||
|
method_name, params, request_id,
|
||||||
|
},
|
||||||
|
protocol::{
|
||||||
|
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
|
||||||
|
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
|
||||||
|
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
|
||||||
|
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
|
||||||
|
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_completion_command,
|
||||||
|
handle_logging_command, handle_prompts_command, handle_resources_command,
|
||||||
|
handle_tools_command,
|
||||||
|
},
|
||||||
|
tool_error::execution_locale,
|
||||||
|
transport::{ResponseMode, transport_response},
|
||||||
|
};
|
||||||
|
|
||||||
|
// The transport invariants of one request travel together here; a parameter struct would only
|
||||||
|
// duplicate them (the same shape every other dispatch entry point in this crate uses).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub(super) async fn handle_legacy_request(
|
||||||
|
state: Arc<AppState>,
|
||||||
|
path: &AgentRoutePath,
|
||||||
|
headers: &HeaderMap,
|
||||||
|
message: &Value,
|
||||||
|
response_mode: ResponseMode,
|
||||||
|
identity: &RequestIdentity,
|
||||||
|
credential: &VerifiedMachineCredential,
|
||||||
|
transport_correlation: &CorrelationContext,
|
||||||
|
) -> Response {
|
||||||
|
let protocol_version = identity.version.as_deref();
|
||||||
|
|
||||||
|
// R5/F5: the owning registration decides *which handler* serves this method in the request's
|
||||||
|
// revision. The adapter holds no method list of its own — the method-to-handler mapping lives in
|
||||||
|
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
|
||||||
|
// really reaches its handler and removing a descriptor removes the dispatch.
|
||||||
|
let registration_revision = protocol_version.unwrap_or(LEGACY_PROTOCOL_VERSION);
|
||||||
|
let dispatch = crate::protocol::dispatch_decision(
|
||||||
|
method_name(message).unwrap_or_default(),
|
||||||
|
registration_revision,
|
||||||
|
);
|
||||||
|
match dispatch {
|
||||||
|
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
|
||||||
|
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
|
||||||
|
// notification: the two share one handler but are not interchangeable, so an `initialize`
|
||||||
|
// notification may not initialize an existing session and a `notifications/initialized`
|
||||||
|
// request may not create one.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Lifecycle,
|
||||||
|
kind: Kind::Method,
|
||||||
|
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Lifecycle,
|
||||||
|
kind: Kind::Notification,
|
||||||
|
} if is_notification(message) => {
|
||||||
|
handle_initialized_notification(state, path, headers).await
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Ping,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
|
||||||
|
transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
json!({ "protocolVersion": session.protocol_version }),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ToolList,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
|
||||||
|
// The adapter parses the wire form and maps the neutral outcome back; the shared Tools
|
||||||
|
// service never sees the envelope, the response mode or the protocol revision.
|
||||||
|
let list_command: ToolsListCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, "invalid tools/list parameters"),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_tools_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
ToolsCommand::List(list_command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, message_text),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ToolsOutcome::CatalogUnavailable => {
|
||||||
|
internal_jsonrpc_error(message, "published catalog is unavailable")
|
||||||
|
}
|
||||||
|
// A list command never produces a call outcome; it is answered with the adapter's
|
||||||
|
// internal error instead of being silently ignored.
|
||||||
|
ToolsOutcome::Call(_) => internal_jsonrpc_error(
|
||||||
|
message,
|
||||||
|
"unexpected shared tools outcome for a tools/list",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ToolCall,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// The adapter owns the wire form: it parses the call parameters, removes the reserved
|
||||||
|
// confirmation marker and the shared Tools service never sees the envelope, the
|
||||||
|
// response mode or the protocol revision (spec section 6.2).
|
||||||
|
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
||||||
|
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||||
|
let outcome = handle_tools_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
ToolsCommand::Call(ToolCallCommand {
|
||||||
|
tool_name: tool_call_params.name,
|
||||||
|
arguments,
|
||||||
|
confirmation_token,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
tool_command_response(
|
||||||
|
message,
|
||||||
|
response_mode,
|
||||||
|
&session.protocol_version,
|
||||||
|
transport_correlation,
|
||||||
|
outcome,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ResourceList,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let list_command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid resources/list parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_resources_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
ResourcesCommand::List(list_command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
ResourcesOutcome::Listed {
|
||||||
|
resources,
|
||||||
|
next_cursor,
|
||||||
|
} => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
resources_list_result(resources, next_cursor),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ResourceRead,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let read_command: ResourceReadCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid resources/read parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_resources_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
ResourcesCommand::Read(read_command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
ResourcesOutcome::Read { contents } => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ResourcesOutcome::NotAvailable => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"the requested resource is not available",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ResourcesOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
ResourcesOutcome::ExecutionError(contract) => resource_error_response(
|
||||||
|
message,
|
||||||
|
response_mode,
|
||||||
|
&session.protocol_version,
|
||||||
|
contract,
|
||||||
|
),
|
||||||
|
_ => internal_jsonrpc_error(message, "published resources are unavailable"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Story 3.11: the shared service returns exact bound Published templates; the legacy adapter
|
||||||
|
// retains its earlier result shape and still requires the initialized session.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::ResourceTemplateList,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
|
||||||
|
let command: ResourcesListCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid resources/templates/list parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
||||||
|
&state,
|
||||||
|
&path.workspace_slug,
|
||||||
|
&path.agent_slug,
|
||||||
|
&session.protocol_version,
|
||||||
|
command,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(page) => page,
|
||||||
|
Err(crate::protocol::ResourceTemplatesListError::InvalidCursor) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid resources/templates/list cursor",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(crate::protocol::ResourceTemplatesListError::Unavailable) => {
|
||||||
|
return internal_jsonrpc_error(message, "published templates are unavailable");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
resource_templates_list_result(templates, next_cursor),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// Story 3.14: `prompts/list` / `prompts/get` of the initialized legacy session, served from
|
||||||
|
// the same exact bound Published Prompt Versions as the modern era.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::PromptList,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let command: PromptsListCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid prompts/list parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_prompts_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
PromptsCommand::List(command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
PromptsOutcome::Listed {
|
||||||
|
prompts,
|
||||||
|
next_cursor,
|
||||||
|
} => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
prompts_list_result(prompts, next_cursor),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::PromptGet,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let command: PromptGetCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid prompts/get parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_prompts_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
PromptsCommand::Get(command),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
PromptsOutcome::Got {
|
||||||
|
description,
|
||||||
|
messages,
|
||||||
|
} => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
prompt_get_result(description, messages),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
PromptsOutcome::NotAvailable => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"the requested prompt is not available",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
PromptsOutcome::ArgumentsRejected { reason, argument } => {
|
||||||
|
prompt_arguments_error_response(
|
||||||
|
message,
|
||||||
|
response_mode,
|
||||||
|
&session.protocol_version,
|
||||||
|
reason,
|
||||||
|
argument,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
PromptsOutcome::DependencyUnavailable { position } => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32603,
|
||||||
|
format!("the pinned dependency at dependencies[{position}] is unavailable"),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
PromptsOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
_ => internal_jsonrpc_error(message, "published prompts are unavailable"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Story 3.17: `completion/complete` of the initialized legacy session. The shared service is
|
||||||
|
// the same one the modern era uses; only the result envelope differs (no `resultType`).
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::Completion,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let command: CompletionCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"invalid completion/complete parameters",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let outcome = handle_completion_command(
|
||||||
|
&state,
|
||||||
|
ServiceContext {
|
||||||
|
workspace_slug: &session.workspace_slug,
|
||||||
|
agent_slug: &session.agent_slug,
|
||||||
|
credential,
|
||||||
|
correlation: transport_correlation,
|
||||||
|
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||||
|
locale: execution_locale(message),
|
||||||
|
},
|
||||||
|
&session.protocol_version,
|
||||||
|
command,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match outcome {
|
||||||
|
CompletionOutcome::Completed {
|
||||||
|
values,
|
||||||
|
total,
|
||||||
|
has_more,
|
||||||
|
} => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(
|
||||||
|
request_id(message),
|
||||||
|
completion_result(values, total, has_more),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
CompletionOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
CompletionOutcome::NotAvailable => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32602,
|
||||||
|
"the completion reference is not available",
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
CompletionOutcome::CatalogUnavailable => {
|
||||||
|
internal_jsonrpc_error(message, "published completion sources are unavailable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Story 3.18: the pinned legacy `logging/setLevel`. The level belongs to the initialized
|
||||||
|
// session of this request, so setting it can never change another client's level. The request
|
||||||
|
// answers an empty result; the acknowledgment event is filtered by the level it just set.
|
||||||
|
DispatchDecision::Allowed {
|
||||||
|
handler: MethodHandler::LoggingSetLevel,
|
||||||
|
..
|
||||||
|
} if is_request(message) => {
|
||||||
|
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||||
|
Ok(session) => session,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let command: SetLevelCommand = match serde_json::from_value(params(message)) {
|
||||||
|
Ok(command) => command,
|
||||||
|
// A non-string, missing or otherwise unparsable level shares the one safe detail of a
|
||||||
|
// value outside the pinned union: nothing the client sent is echoed back.
|
||||||
|
Err(_) => {
|
||||||
|
return transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, INVALID_LEVEL),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match handle_logging_command(&state.logging_levels, &session.id, command) {
|
||||||
|
LoggingOutcome::Applied(level) => {
|
||||||
|
crate::protocol::set_active_level(Some(level));
|
||||||
|
crate::protocol::note(
|
||||||
|
crate::protocol::LogLevel::Notice,
|
||||||
|
EVENT_LEVEL_APPLIED,
|
||||||
|
"applied",
|
||||||
|
);
|
||||||
|
transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_result(request_id(message), json!({})),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
LoggingOutcome::InvalidParams(detail) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(request_id(message), -32602, detail),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
Some(&session.protocol_version),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A notification whose method the registration does not map to this adapter's handlers is
|
||||||
|
// acknowledged without being dispatched, exactly as before.
|
||||||
|
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
||||||
|
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
|
||||||
|
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
|
||||||
|
_ => match method_name(message) {
|
||||||
|
Some(method) => transport_response(
|
||||||
|
StatusCode::OK,
|
||||||
|
jsonrpc_error(
|
||||||
|
request_id(message),
|
||||||
|
-32601,
|
||||||
|
format!("method {method} is not supported"),
|
||||||
|
),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
protocol_version,
|
||||||
|
),
|
||||||
|
None => transport_response(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC message"),
|
||||||
|
response_mode,
|
||||||
|
None,
|
||||||
|
protocol_version,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -317,8 +317,11 @@ fn note_logging_outcome(payload: &Value) {
|
|||||||
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
|
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
|
||||||
if payload.get("error").is_some() {
|
if payload.get("error").is_some() {
|
||||||
match payload.pointer("/error/code").and_then(Value::as_i64) {
|
match payload.pointer("/error/code").and_then(Value::as_i64) {
|
||||||
// The pinned client-error codes of a malformed request.
|
// The pinned client-error codes: a malformed request, a method that this era does not
|
||||||
Some(-32600 | -32602) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
|
// implement, and invalid params. The client can correct all three, so they are a
|
||||||
|
// rejection rather than a server failure; the closed label stays the one client-error
|
||||||
|
// label of the vocabulary instead of growing a new one.
|
||||||
|
Some(-32602..=-32600) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
|
||||||
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
|
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -29,7 +29,13 @@ run_atdd() {
|
|||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# Initial accepted recovery scope for Crank Story 3.17. Update with the story
|
# Keep Story 3.16 prompt ATDD with Story 3.17 completion and its bound-template regression.
|
||||||
# being published and add only AC-required affected security/contract cases.
|
run_atdd "MCP prompt composition" -p mcp-server --test integration mcp_prompts::composition -- --test-threads=1
|
||||||
run_atdd "MCP completion" -p mcp-server --test integration mcp_completion -- --test-threads=1
|
run_atdd "MCP completion" -p mcp-server --test integration mcp_completion -- --test-threads=1
|
||||||
run_atdd "static resource list" -p mcp-server --test integration static_resources::list -- --test-threads=1
|
run_atdd "bound template resources/list regression" -p mcp-server --test integration static_resources::list::list_stays_available_when_a_published_template_is_bound -- --test-threads=1
|
||||||
|
|
||||||
|
# Story 3.18: safe structured logging — the closed level vocabulary, the endpoint ATDD, and the
|
||||||
|
# capability projection the `logging` surface changes.
|
||||||
|
run_atdd "MCP log level vocabulary" -p crank-community-mcp --lib protocol::logging -- --test-threads=1
|
||||||
|
run_atdd "MCP safe logging" -p mcp-server --test integration mcp_logging -- --test-threads=1
|
||||||
|
run_atdd "capability inventory projection" -p mcp-server --test integration inventory_projection -- --test-threads=1
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Attach the packaged release artifacts to the Gitea release of one tag.
|
||||||
|
|
||||||
|
The release workflow builds the archives, the checksums file and the SBOM into `dist/`; this script
|
||||||
|
is what makes them durable: it upserts the release entry of the tag and uploads every artifact to it,
|
||||||
|
so a published version keeps its artifacts and checksums after the runner workspace is gone.
|
||||||
|
|
||||||
|
The token is read from `GITEA_TOKEN` only; it is never printed, logged or written to disk.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import mimetypes
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
TIMEOUT_SECONDS = 120
|
||||||
|
|
||||||
|
|
||||||
|
def _json(url: str, token: str, method: str = "GET", payload: dict | None = None) -> dict:
|
||||||
|
headers = {"Authorization": f"token {token}", "Accept": "application/json"}
|
||||||
|
data = None
|
||||||
|
if payload is not None:
|
||||||
|
data = json.dumps(payload).encode("utf-8")
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||||
|
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
||||||
|
return json.loads(response.read() or b"{}")
|
||||||
|
|
||||||
|
|
||||||
|
def _upload(url: str, token: str, path: Path) -> dict:
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"token {token}",
|
||||||
|
"Content-Type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
|
||||||
|
}
|
||||||
|
request = urllib.request.Request(url, data=path.read_bytes(), headers=headers, method="POST")
|
||||||
|
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
||||||
|
return json.loads(response.read() or b"{}")
|
||||||
|
|
||||||
|
|
||||||
|
def release_artifacts(dist: Path) -> list[Path]:
|
||||||
|
"""Every regular file directly in `dist/`, in a stable order; nested build dirs are ignored."""
|
||||||
|
return sorted(path for path in dist.iterdir() if path.is_file() and not path.name.startswith("."))
|
||||||
|
|
||||||
|
|
||||||
|
def publish(api: str, repo: str, tag: str, title: str, notes: Path, dist: Path, prerelease: bool, token: str) -> int:
|
||||||
|
base = f"{api.rstrip('/')}/repos/{repo}"
|
||||||
|
# The notes file is the release body, not an artifact of the release.
|
||||||
|
artifacts = [path for path in release_artifacts(dist) if path.name != notes.name]
|
||||||
|
if not artifacts:
|
||||||
|
print(f"no release artifacts in {dist}", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
release = _json(f"{base}/releases/tags/{tag}", token)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
if error.code != 404:
|
||||||
|
raise
|
||||||
|
release = _json(
|
||||||
|
f"{base}/releases",
|
||||||
|
token,
|
||||||
|
"POST",
|
||||||
|
{
|
||||||
|
"tag_name": tag,
|
||||||
|
"name": title,
|
||||||
|
"body": notes.read_text(encoding="utf-8"),
|
||||||
|
"draft": False,
|
||||||
|
"prerelease": prerelease,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
existing = {asset["name"] for asset in release.get("assets") or []}
|
||||||
|
for path in artifacts:
|
||||||
|
if path.name in existing:
|
||||||
|
print(f"skip existing asset {path.name}")
|
||||||
|
continue
|
||||||
|
uploaded = _upload(f"{base}/releases/{release['id']}/assets?name={path.name}", token, path)
|
||||||
|
print(f"uploaded {path.name} -> {uploaded.get('browser_download_url', 'ok')}")
|
||||||
|
print(f"release {tag} id={release['id']} artifacts={len(artifacts)}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--api", required=True, help="API root, e.g. https://git.itexp.me/api/v1")
|
||||||
|
parser.add_argument("--repo", required=True, help="owner/name")
|
||||||
|
parser.add_argument("--tag", required=True)
|
||||||
|
parser.add_argument("--title", required=True)
|
||||||
|
parser.add_argument("--notes-file", type=Path, required=True)
|
||||||
|
parser.add_argument("--dist", type=Path, required=True)
|
||||||
|
parser.add_argument("--prerelease", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
token = os.environ.get("GITEA_TOKEN", "")
|
||||||
|
if not token:
|
||||||
|
print("GITEA_TOKEN is required to publish release artifacts", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
return publish(args.api, args.repo, args.tag, args.title, args.notes_file, args.dist, args.prerelease, token)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""AT-3 (release durability): the artifacts of a tag land on the Gitea release, idempotently."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import importlib.util
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
SCRIPT = ROOT / "scripts" / "publish-gitea-release.py"
|
||||||
|
|
||||||
|
|
||||||
|
def load_module():
|
||||||
|
spec = importlib.util.spec_from_file_location("publish_gitea_release", SCRIPT)
|
||||||
|
assert spec is not None and spec.loader is not None
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules[spec.name] = module
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
class Stub:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.release_assets: list[dict] = []
|
||||||
|
self.created = False
|
||||||
|
self.uploaded: list[str] = []
|
||||||
|
self.created_payload: dict = {}
|
||||||
|
|
||||||
|
def handler(self):
|
||||||
|
stub = self
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, format, *args): # noqa: A002 - base class signature
|
||||||
|
return
|
||||||
|
|
||||||
|
def _reply(self, status: int, payload: dict) -> None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
self.send_response(status)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
if self.path.endswith("/releases/tags/v1.2.3") and stub.created:
|
||||||
|
self._reply(200, {"id": 7, "assets": stub.release_assets})
|
||||||
|
else:
|
||||||
|
self._reply(404, {"message": "not found"})
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
body = self.rfile.read(length)
|
||||||
|
if self.path.endswith("/releases"):
|
||||||
|
stub.created = True
|
||||||
|
stub.created_payload = json.loads(body)
|
||||||
|
self._reply(201, {"id": 7, "assets": []})
|
||||||
|
return
|
||||||
|
if "/releases/7/assets?name=" in self.path:
|
||||||
|
name = self.path.rsplit("name=", 1)[1]
|
||||||
|
stub.uploaded.append(name)
|
||||||
|
stub.release_assets.append(
|
||||||
|
{"name": name, "browser_download_url": f"http://stub/assets/{name}"}
|
||||||
|
)
|
||||||
|
self._reply(201, {"name": name, "browser_download_url": f"http://stub/assets/{name}"})
|
||||||
|
return
|
||||||
|
self._reply(404, {"message": "not found"})
|
||||||
|
|
||||||
|
return Handler
|
||||||
|
|
||||||
|
|
||||||
|
class PublishGiteaReleaseTests(unittest.TestCase):
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.module = load_module()
|
||||||
|
self.stub = Stub()
|
||||||
|
self.server = ThreadingHTTPServer(("127.0.0.1", 0), self.stub.handler())
|
||||||
|
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||||
|
self.thread.start()
|
||||||
|
self.api = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.dist = Path(self.tmp.name)
|
||||||
|
(self.dist / "crank-community-admin-api-v1.2.3.tar.gz").write_bytes(b"admin")
|
||||||
|
(self.dist / "crank-community-v1.2.3-checksums.txt").write_text("deadbeef admin.tar.gz\n")
|
||||||
|
(self.dist / "nested").mkdir()
|
||||||
|
(self.dist / "nested" / "admin-api").write_bytes(b"raw")
|
||||||
|
self.notes = self.dist / "RELEASE-NOTES.md"
|
||||||
|
self.notes.write_text("## v1.2.3\n", encoding="utf-8")
|
||||||
|
|
||||||
|
def tearDown(self) -> None:
|
||||||
|
self.server.shutdown()
|
||||||
|
self.server.server_close()
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def publish(self) -> tuple[int, str]:
|
||||||
|
output = io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output):
|
||||||
|
code = self.module.publish(
|
||||||
|
self.api,
|
||||||
|
"bsodfather/crank",
|
||||||
|
"v1.2.3",
|
||||||
|
"Crank Community v1.2.3",
|
||||||
|
self.notes,
|
||||||
|
self.dist,
|
||||||
|
True,
|
||||||
|
"stub-token-never-printed",
|
||||||
|
)
|
||||||
|
return code, output.getvalue()
|
||||||
|
|
||||||
|
def test_release_is_created_with_notes_and_every_top_level_artifact(self) -> None:
|
||||||
|
code, output = self.publish()
|
||||||
|
self.assertEqual(code, 0, output)
|
||||||
|
self.assertEqual(self.stub.created_payload["tag_name"], "v1.2.3")
|
||||||
|
self.assertTrue(self.stub.created_payload["prerelease"])
|
||||||
|
self.assertEqual(self.stub.created_payload["body"], "## v1.2.3\n")
|
||||||
|
self.assertEqual(
|
||||||
|
self.stub.uploaded,
|
||||||
|
["crank-community-admin-api-v1.2.3.tar.gz", "crank-community-v1.2.3-checksums.txt"],
|
||||||
|
"every top-level artifact and nothing from the nested build dir",
|
||||||
|
)
|
||||||
|
self.assertNotIn("stub-token-never-printed", output, "the token must never reach the log")
|
||||||
|
|
||||||
|
def test_second_run_reuses_the_release_and_skips_existing_assets(self) -> None:
|
||||||
|
self.assertEqual(self.publish()[0], 0)
|
||||||
|
uploaded_first = list(self.stub.uploaded)
|
||||||
|
code, output = self.publish()
|
||||||
|
self.assertEqual(code, 0, output)
|
||||||
|
self.assertEqual(self.stub.uploaded, uploaded_first, "a rerun must not upload duplicates")
|
||||||
|
self.assertEqual(output.count("skip existing asset"), 2, output)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user