mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 09:05:15 +01:00
Preserve schema-bounded ACP display activity through durable projection
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
4a278e2740
commit
94724d1414
9 files changed
+605
-11
No files matched your search
@@ -31,6 +31,7 @@
|
||||
"eventType": {
|
||||
"enum": [
|
||||
"runtime.event",
|
||||
"runtime.rich_event",
|
||||
"runtime.permission_requested",
|
||||
"runtime.input_requested",
|
||||
"runtime.tool_called",
|
||||
@@ -108,6 +109,67 @@
|
||||
"turnId": { "type": ["string", "null"], "maxLength": 240, "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" },
|
||||
"payload": { "type": "object" }
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"allOf": [
|
||||
{
|
||||
"if": { "properties": { "eventType": { "const": "runtime.rich_event" } } },
|
||||
"then": {
|
||||
"properties": {
|
||||
"runId": { "type": "string" },
|
||||
"turnId": { "type": "string" },
|
||||
"payload": { "$ref": "#/$defs/richEvent" }
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"richEvent": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"eventType",
|
||||
"itemId",
|
||||
"payload"
|
||||
],
|
||||
"properties": {
|
||||
"eventType": {
|
||||
"enum": [
|
||||
"plan.updated",
|
||||
"tool.execution.started",
|
||||
"tool.execution.progressed",
|
||||
"tool.execution.completed",
|
||||
"research.started",
|
||||
"research.progressed",
|
||||
"research.completed",
|
||||
"delegation.started",
|
||||
"delegation.updated",
|
||||
"delegation.completed",
|
||||
"model.route.changed",
|
||||
"model.verification.updated",
|
||||
"context.compacted",
|
||||
"artifact.viewed",
|
||||
"artifact.generated",
|
||||
"review.mode.changed",
|
||||
"hook.started",
|
||||
"hook.completed",
|
||||
"memory.citation.referenced",
|
||||
"safety.review.started",
|
||||
"safety.review.completed",
|
||||
"terminal.input.sent",
|
||||
"wait.started",
|
||||
"wait.completed",
|
||||
"provider.notice.recorded"
|
||||
]
|
||||
},
|
||||
"itemId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 160,
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
|
||||
},
|
||||
"payload": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::acpx_event_scope::AcpxEventScope;
|
||||
use crate::acpx_sidecar_transport::AcpxSidecarEvent;
|
||||
use crate::durable::{redact_text, sanitize_semantic_tool_input, sanitize_value};
|
||||
use crate::durable::{
|
||||
redact_sensitive_text_values, redact_text, sanitize_semantic_tool_input, sanitize_value,
|
||||
};
|
||||
use crate::generated_acpx_sidecar_contract::{
|
||||
classify_generated_acpx_tool_operation, GeneratedAcpxSidecarEventType,
|
||||
};
|
||||
use crate::local_runner::LocalRunnerError;
|
||||
use crate::provider_bridge::semantic_value_digest;
|
||||
use crate::stable_identity::{is_stable_id, SHORT_STABLE_ID_CHARS};
|
||||
|
||||
const MAX_EVENT_PAYLOAD_BYTES: usize = 256 * 1024;
|
||||
const MAX_ID_CHARS: usize = 160;
|
||||
@@ -40,6 +44,10 @@ pub enum AcpxTurnStatus {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AcpxEventPayload {
|
||||
RichActivity {
|
||||
event_type: String,
|
||||
payload: Value,
|
||||
},
|
||||
Runtime {
|
||||
kind: AcpxRuntimeEventKind,
|
||||
tool_operation: Option<&'static str>,
|
||||
@@ -95,6 +103,7 @@ pub fn decode_acpx_event(
|
||||
}
|
||||
|
||||
match event.event_type {
|
||||
GeneratedAcpxSidecarEventType::RuntimeRichEvent => decode_rich_event(&event.payload),
|
||||
GeneratedAcpxSidecarEventType::RuntimeEvent => decode_runtime_event(&event.payload),
|
||||
GeneratedAcpxSidecarEventType::RuntimePermissionRequested => {
|
||||
Ok(AcpxEventPayload::PermissionRequested {
|
||||
@@ -113,7 +122,7 @@ pub fn decode_acpx_event(
|
||||
LocalRunnerError::invalid("ACPX input request omitted its question set")
|
||||
})?;
|
||||
validate_question_set(&question_set)?;
|
||||
let question_set = sanitize_question_set(question_set);
|
||||
let question_set = sanitize_question_set(question_set)?;
|
||||
let origin = optional_object(&event.payload, "origin", "input request origin")?;
|
||||
Ok(AcpxEventPayload::InputRequested {
|
||||
request_id: required_id_with_limit(
|
||||
@@ -192,9 +201,173 @@ pub fn decode_acpx_event(
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize_question_set(mut value: Value) -> Value {
|
||||
// This boundary accepts display activity only. Terminal outcomes, tool dispatch,
|
||||
// runtime requests and source references retain their separate authority paths.
|
||||
fn rich_event_schema(event_type: &str) -> Option<&'static str> {
|
||||
Some(match event_type {
|
||||
"plan.updated" => "plan",
|
||||
"tool.execution.started" | "tool.execution.progressed" | "tool.execution.completed" => {
|
||||
"toolExecution"
|
||||
}
|
||||
"research.started" | "research.progressed" | "research.completed" => "research",
|
||||
"delegation.started" | "delegation.updated" | "delegation.completed" => "delegation",
|
||||
"model.route.changed" => "modelRoute",
|
||||
"model.verification.updated" => "modelVerification",
|
||||
"context.compacted" => "contextCompacted",
|
||||
"artifact.viewed" => "artifactViewed",
|
||||
"artifact.generated" => "artifactGenerated",
|
||||
"review.mode.changed" => "reviewMode",
|
||||
"hook.started" | "hook.completed" => "hook",
|
||||
"memory.citation.referenced" => "memoryCitation",
|
||||
"safety.review.started" | "safety.review.completed" => "safetyReview",
|
||||
"terminal.input.sent" => "terminalInput",
|
||||
"wait.started" | "wait.completed" => "wait",
|
||||
"provider.notice.recorded" => "providerNotice",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn rich_event_validators(
|
||||
) -> Result<&'static BTreeMap<String, jsonschema::Validator>, LocalRunnerError> {
|
||||
static VALIDATORS: OnceLock<Result<BTreeMap<String, jsonschema::Validator>, String>> =
|
||||
OnceLock::new();
|
||||
VALIDATORS.get_or_init(|| {
|
||||
let schema: Value = serde_json::from_str(include_str!("../../../../protocol/schemas/provider-event.schema.json"))
|
||||
.map_err(|_| "embedded provider-event schema is invalid".to_owned())?;
|
||||
fn internal_refs(value: &Value) -> bool {
|
||||
match value {
|
||||
Value::Object(object) => object.iter().all(|(key, value)| {
|
||||
(key != "$ref" || value.as_str().is_some_and(|reference| reference.starts_with("#/"))) && internal_refs(value)
|
||||
}),
|
||||
Value::Array(values) => values.iter().all(internal_refs),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
if !internal_refs(&schema) { return Err("provider-event schema may use only internal references".to_owned()); }
|
||||
let definitions = schema.get("$defs").and_then(Value::as_object).ok_or_else(|| "provider-event schema has no definitions".to_owned())?;
|
||||
let mut validators = BTreeMap::new();
|
||||
for name in ["plan", "toolExecution", "research", "delegation", "modelRoute", "modelVerification", "contextCompacted", "artifactViewed", "artifactGenerated", "reviewMode", "hook", "memoryCitation", "safetyReview", "terminalInput", "wait", "providerNotice"] {
|
||||
if !definitions.contains_key(name) { return Err("provider-event schema is missing an admitted definition".to_owned()); }
|
||||
let selected = serde_json::json!({"$schema":"https://json-schema.org/draft/2020-12/schema", "$ref":format!("#/$defs/{name}"), "$defs":definitions});
|
||||
let validator = jsonschema::validator_for(&selected).map_err(|_| "embedded provider-event schema cannot compile".to_owned())?;
|
||||
validators.insert(name.to_owned(), validator);
|
||||
}
|
||||
Ok(validators)
|
||||
}).as_ref().map_err(|message| LocalRunnerError::invalid(message.clone()))
|
||||
}
|
||||
|
||||
fn decode_rich_event(value: &Value) -> Result<AcpxEventPayload, LocalRunnerError> {
|
||||
let wrapper = value
|
||||
.as_object()
|
||||
.ok_or_else(|| LocalRunnerError::invalid("ACPX rich event must be an object"))?;
|
||||
if wrapper
|
||||
.keys()
|
||||
.any(|key| !matches!(key.as_str(), "eventType" | "itemId" | "payload"))
|
||||
{
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX rich event cannot supply source references or authority fields",
|
||||
));
|
||||
}
|
||||
let item_id = wrapper
|
||||
.get("itemId")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| LocalRunnerError::invalid("ACPX rich event omitted its display identity"))?;
|
||||
if !is_stable_id(item_id, SHORT_STABLE_ID_CHARS) {
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX rich event display identity is invalid",
|
||||
));
|
||||
}
|
||||
let event_type = wrapper
|
||||
.get("eventType")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| LocalRunnerError::invalid("ACPX rich event omitted its type"))?;
|
||||
let schema = rich_event_schema(event_type).ok_or_else(|| {
|
||||
LocalRunnerError::invalid("ACPX rich event type is not admitted display activity")
|
||||
})?;
|
||||
let payload = wrapper
|
||||
.get("payload")
|
||||
.ok_or_else(|| LocalRunnerError::invalid("ACPX rich event omitted its payload"))?;
|
||||
let validators = rich_event_validators()?;
|
||||
let validator = validators
|
||||
.get(schema)
|
||||
.ok_or_else(|| LocalRunnerError::invalid("ACPX rich event schema is unavailable"))?;
|
||||
if !validator.is_valid(payload) {
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX rich event failed its exact provider-event schema",
|
||||
));
|
||||
}
|
||||
if event_type == "artifact.generated" && payload.get("registered") != Some(&Value::Bool(false))
|
||||
{
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX display activity cannot register an artifact",
|
||||
));
|
||||
}
|
||||
if event_type == "plan.updated"
|
||||
&& (payload.get("syncStatus").and_then(Value::as_str) != Some("not_applicable")
|
||||
|| payload
|
||||
.get("documentRevision")
|
||||
.is_some_and(|revision| !revision.is_null()))
|
||||
{
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX display activity cannot synchronize a durable plan",
|
||||
));
|
||||
}
|
||||
for field in ["reference", "target"] {
|
||||
if payload
|
||||
.get(field)
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|path| {
|
||||
path.contains('\\') || path.contains(':') || path.chars().any(char::is_control)
|
||||
})
|
||||
{
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX activity reference must be a workspace-relative path",
|
||||
));
|
||||
}
|
||||
}
|
||||
fn sanitize_display(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::String(text) => Value::String(redact_sensitive_text_values(text)),
|
||||
Value::Array(values) => Value::Array(values.iter().map(sanitize_display).collect()),
|
||||
Value::Object(object) => Value::Object(
|
||||
object
|
||||
.iter()
|
||||
.map(|(key, value)| (key.clone(), sanitize_display(value)))
|
||||
.collect(),
|
||||
),
|
||||
value => value.clone(),
|
||||
}
|
||||
}
|
||||
let payload = sanitize_display(payload);
|
||||
if !validator.is_valid(&payload) {
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX rich event redaction exceeded its schema bounds",
|
||||
));
|
||||
}
|
||||
Ok(AcpxEventPayload::RichActivity {
|
||||
event_type: event_type.to_owned(),
|
||||
payload,
|
||||
})
|
||||
}
|
||||
|
||||
// Durable storage uses this same exact schema gate before lifting diagnostic
|
||||
// preview limits. This does not admit an event or grant mutation authority.
|
||||
pub(crate) fn has_bounded_rich_display_shape(event_type: &str, payload: &Value) -> bool {
|
||||
let Some(schema) = rich_event_schema(event_type) else {
|
||||
return false;
|
||||
};
|
||||
serde_json::to_vec(payload).is_ok_and(|bytes| bytes.len() <= MAX_EVENT_PAYLOAD_BYTES)
|
||||
&& rich_event_validators().is_ok_and(|validators| {
|
||||
validators
|
||||
.get(schema)
|
||||
.is_some_and(|validator| validator.is_valid(payload))
|
||||
})
|
||||
}
|
||||
|
||||
fn sanitize_question_set(mut value: Value) -> Result<Value, LocalRunnerError> {
|
||||
let original = value.clone();
|
||||
let Some(question_set) = value.as_object_mut() else {
|
||||
return value;
|
||||
return Ok(value);
|
||||
};
|
||||
redact_object_text(question_set, &["title", "description", "submitLabel"]);
|
||||
if let Some(questions) = question_set
|
||||
@@ -223,7 +396,17 @@ fn sanitize_question_set(mut value: Value) -> Value {
|
||||
}
|
||||
}
|
||||
}
|
||||
value
|
||||
if value != original {
|
||||
let description = value
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
value["description"] = Value::String(format!(
|
||||
"Sensitive values were redacted from this request.\n\n{description}"
|
||||
));
|
||||
}
|
||||
validate_question_set(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn redact_object_text(object: &mut serde_json::Map<String, Value>, keys: &[&str]) {
|
||||
@@ -231,7 +414,7 @@ fn redact_object_text(object: &mut serde_json::Map<String, Value>, keys: &[&str]
|
||||
let Some(text) = object.get(*key).and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let redacted = redact_text(text);
|
||||
let redacted = redact_sensitive_text_values(text);
|
||||
object.insert((*key).to_owned(), Value::String(redacted));
|
||||
}
|
||||
}
|
||||
@@ -397,7 +580,16 @@ fn validate_plan(payload: &Value) -> Result<(), LocalRunnerError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_question_set(value: &Value) -> Result<(), LocalRunnerError> {
|
||||
pub(crate) fn validate_question_set(value: &Value) -> Result<(), LocalRunnerError> {
|
||||
if serde_json::to_vec(value)
|
||||
.map_err(|_| LocalRunnerError::invalid("ACPX question set is invalid"))?
|
||||
.len()
|
||||
> 196 * 1024
|
||||
{
|
||||
return Err(LocalRunnerError::invalid(
|
||||
"ACPX question set exceeds its 196 KiB durable byte bound",
|
||||
));
|
||||
}
|
||||
let schema: Value = serde_json::from_str(include_str!(
|
||||
"../../../../protocol/schemas/question-set.schema.json"
|
||||
))
|
||||
|
||||
@@ -194,6 +194,16 @@ impl AcpxProviderState {
|
||||
) -> Result<Vec<AcpxProviderStateEvent>, LocalRunnerError> {
|
||||
let payload = decode_acpx_event(&self.scope, event)?;
|
||||
match payload {
|
||||
AcpxEventPayload::RichActivity {
|
||||
event_type,
|
||||
payload,
|
||||
} => Ok(vec![AcpxProviderStateEvent::Activity(
|
||||
NormalizedProviderEvent {
|
||||
event_type,
|
||||
priority: crate::durable::EventPriority::P1,
|
||||
payload,
|
||||
},
|
||||
)]),
|
||||
AcpxEventPayload::Runtime {
|
||||
kind,
|
||||
tool_operation,
|
||||
|
||||
@@ -16,8 +16,8 @@ pub use runner::{
|
||||
TerminalDeliveryReconciliation,
|
||||
};
|
||||
pub(crate) use state::{
|
||||
create_private_temporary_file, open_private_regular_file, redact_text,
|
||||
sanitize_semantic_tool_input, sanitize_value, verify_private_directory,
|
||||
create_private_temporary_file, open_private_regular_file, redact_sensitive_text_values,
|
||||
redact_text, sanitize_semantic_tool_input, sanitize_value, verify_private_directory,
|
||||
};
|
||||
pub use state::{
|
||||
Command, CommandDisposition, DurableState, DurableStateStore, EventPriority,
|
||||
|
||||
@@ -532,6 +532,8 @@ impl DurableState {
|
||||
"durable identity or validation semantics contain credential-shaped material",
|
||||
));
|
||||
}
|
||||
let sanitized_payload =
|
||||
preserve_bounded_display_content(event_type.as_str(), &payload, sanitized_payload)?;
|
||||
let sanitized_payload =
|
||||
finalize_semantic_tool_input_payload(event_type.as_str(), &payload, sanitized_payload)?;
|
||||
|
||||
@@ -1592,6 +1594,76 @@ pub(crate) fn sanitize_value(value: &Value) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize_bounded_display_value(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::Object(object) => Value::Object(
|
||||
object
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
let value = if protocol_authorization_boundary(key, value) {
|
||||
value.clone()
|
||||
} else if sensitive_key(key, value) {
|
||||
Value::String("[REDACTED]".to_owned())
|
||||
} else {
|
||||
sanitize_bounded_display_value(value)
|
||||
};
|
||||
(key.clone(), value)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
Value::Array(values) => {
|
||||
Value::Array(values.iter().map(sanitize_bounded_display_value).collect())
|
||||
}
|
||||
Value::String(text) => Value::String(redact_sensitive_text_values(text)),
|
||||
value => value.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn preserve_bounded_display_content(
|
||||
event_type: &str,
|
||||
original: &Value,
|
||||
mut sanitized: Value,
|
||||
) -> Result<Value, DurableRunnerError> {
|
||||
use crate::acpx_event_payload::{has_bounded_rich_display_shape, validate_question_set};
|
||||
|
||||
// Rich display payloads are already closed and byte-bounded by their exact
|
||||
// protocol schemas. Applying a diagnostic preview cap again would silently
|
||||
// change complete output into a truncated artifact without its metadata.
|
||||
if has_bounded_rich_display_shape(event_type, original) {
|
||||
let preserved = sanitize_bounded_display_value(original);
|
||||
if !has_bounded_rich_display_shape(event_type, &preserved) {
|
||||
return Err(DurableRunnerError::invalid(
|
||||
"redacted display activity exceeds its schema bounds",
|
||||
));
|
||||
}
|
||||
return Ok(preserved);
|
||||
}
|
||||
if event_type == "runtime_request.created" {
|
||||
if let Some(input) = original.pointer("/request/input") {
|
||||
if input.get("schema").and_then(Value::as_str) == Some("paperclip.question_set.v1") {
|
||||
validate_question_set(input)
|
||||
.map_err(|error| DurableRunnerError::invalid(error.to_string()))?;
|
||||
let mut preserved = sanitize_bounded_display_value(input);
|
||||
if &preserved != input {
|
||||
let description = preserved
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
preserved["description"] = Value::String(format!(
|
||||
"Sensitive values were redacted from this request.\n\n{description}"
|
||||
));
|
||||
}
|
||||
validate_question_set(&preserved)
|
||||
.map_err(|error| DurableRunnerError::invalid(error.to_string()))?;
|
||||
if let Some(target) = sanitized.pointer_mut("/request/input") {
|
||||
*target = preserved;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(sanitized)
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_semantic_tool_input(
|
||||
operation_id: &str,
|
||||
input: &Value,
|
||||
@@ -1741,7 +1813,7 @@ pub(crate) fn redact_text(input: &str) -> String {
|
||||
redacted
|
||||
}
|
||||
|
||||
fn redact_sensitive_text_values(input: &str) -> String {
|
||||
pub(crate) fn redact_sensitive_text_values(input: &str) -> String {
|
||||
redact_sensitive_text_values_with_context(input, false)
|
||||
}
|
||||
|
||||
@@ -3146,6 +3218,62 @@ mod tests {
|
||||
assert_eq!(payload["diagnostic"], json!("token=[REDACTED]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn durable_display_content_preserves_complete_utf8_plans_and_tool_output() {
|
||||
let mut config = config(PathBuf::from("unused"));
|
||||
config.max_outbox_bytes = 512 * 1024;
|
||||
config.max_frame_bytes = 256 * 1024;
|
||||
let mut state = DurableState::new(&config);
|
||||
let text = "Review 漢字\n".repeat(2_000);
|
||||
let input = json!({
|
||||
"schema":"paperclip.question_set.v1",
|
||||
"description":text,
|
||||
"questions":[{"id":"revision-123","prompt":"Approve?","required":true,"answerMode":"single_select","options":[{"id":"accept","label":"Accept"},{"id":"reject","label":"Reject"}]}]
|
||||
});
|
||||
state.enqueue_event(&config, "runtime_request.created", EventPriority::P0, json!({
|
||||
"request":{"schema":"paperclip.runtime_request.v2","requestId":"request-1","type":"input","status":"pending","input":input},
|
||||
"diagnostic":text
|
||||
})).unwrap();
|
||||
let stored = state.outbox[0]
|
||||
.envelope
|
||||
.pointer("/payload/payload")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.pointer("/request/input/description"),
|
||||
Some(&json!(text))
|
||||
);
|
||||
assert!(stored["diagnostic"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.ends_with("…[truncated]"));
|
||||
|
||||
state.enqueue_event(&config, "tool.execution.completed", EventPriority::P1, json!({
|
||||
"schema":"paperclip.tool.execution.v1","executionId":"tool-1","transport":"builtin","operation":"read","status":"completed",
|
||||
"output":text,"outputBytes":text.len(),"outputTruncated":false,"outputDigest":null
|
||||
})).unwrap();
|
||||
let stored = state.outbox[1]
|
||||
.envelope
|
||||
.pointer("/payload/payload")
|
||||
.unwrap();
|
||||
assert_eq!(stored["output"], text);
|
||||
assert_eq!(stored["outputTruncated"], false);
|
||||
|
||||
let mut oversized = input;
|
||||
oversized["description"] = json!("漢".repeat(70_000));
|
||||
assert!(state
|
||||
.enqueue_event(
|
||||
&config,
|
||||
"runtime_request.created",
|
||||
EventPriority::P0,
|
||||
json!({
|
||||
"request":{"input":oversized}
|
||||
})
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("196 KiB"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_shaped_question_identity_and_validation_fail_closed() {
|
||||
let config = config(PathBuf::from("unused"));
|
||||
|
||||
+2
@@ -70,6 +70,8 @@ impl GeneratedAcpxSidecarCommand {
|
||||
pub enum GeneratedAcpxSidecarEventType {
|
||||
#[serde(rename = "runtime.event")]
|
||||
RuntimeEvent,
|
||||
#[serde(rename = "runtime.rich_event")]
|
||||
RuntimeRichEvent,
|
||||
#[serde(rename = "runtime.permission_requested")]
|
||||
RuntimePermissionRequested,
|
||||
#[serde(rename = "runtime.input_requested")]
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
use paperclip_runner_core::acpx_event_payload::{decode_acpx_event, AcpxEventPayload};
|
||||
use paperclip_runner_core::acpx_event_scope::AcpxEventScope;
|
||||
use paperclip_runner_core::acpx_provider_state::{AcpxProviderState, AcpxProviderStateEvent};
|
||||
use paperclip_runner_core::acpx_sidecar_transport::AcpxSidecarEvent;
|
||||
use paperclip_runner_core::durable::EventPriority;
|
||||
use paperclip_runner_core::generated_acpx_sidecar_contract::GeneratedAcpxSidecarEventType;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn scope() -> AcpxEventScope {
|
||||
let mut scope = AcpxEventScope::new("run-1").unwrap();
|
||||
scope.bind_turn("turn-1").unwrap();
|
||||
scope
|
||||
}
|
||||
fn event(event_type: &str, payload: Value) -> AcpxSidecarEvent {
|
||||
AcpxSidecarEvent {
|
||||
sequence: 1,
|
||||
event_type: GeneratedAcpxSidecarEventType::RuntimeRichEvent,
|
||||
run_id: Some("run-1".to_owned()),
|
||||
turn_id: Some("turn-1".to_owned()),
|
||||
payload: json!({"eventType":event_type,"itemId":"display-1","payload":payload}),
|
||||
}
|
||||
}
|
||||
fn plan() -> Value {
|
||||
json!({"schema":"paperclip.plan.updated.v1","planId":"plan-1","revision":2,"explanation":"Changed order","steps":[{"stepId":"step-1","body":"Inspect","status":"completed"},{"stepId":"step-2","body":"Build","status":"in_progress"}],"complete":false,"syncStatus":"not_applicable","documentRevision":null})
|
||||
}
|
||||
fn artifact() -> Value {
|
||||
json!({"schema":"paperclip.artifact.generated.v1","artifactId":"image-1","status":"completed","reference":"outputs/diagram.png","mediaType":"image/png","registered":false,"failure":null})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rich_activity_preserves_plans_children_and_artifact_metadata_without_mutation_authority() {
|
||||
let mut state = AcpxProviderState::new("run-1").unwrap();
|
||||
state.begin_turn("turn-1").unwrap();
|
||||
for (event_type, payload) in [
|
||||
("plan.updated", plan()),
|
||||
("artifact.generated", artifact()),
|
||||
(
|
||||
"delegation.completed",
|
||||
json!({"schema":"paperclip.delegation.v1","delegationId":"task-1","action":"spawn","status":"completed","children":[{"childId":"child-1","role":"explore","model":"small-model","status":"completed","summary":"Found the implementation","activitySummary":"Searched src; duration 310 ms"}]}),
|
||||
),
|
||||
] {
|
||||
let projected = state
|
||||
.accept_event(&event(event_type, payload.clone()))
|
||||
.unwrap();
|
||||
assert_eq!(projected.len(), 1);
|
||||
let AcpxProviderStateEvent::Activity(activity) = &projected[0] else {
|
||||
panic!("rich event became an authority-bearing event");
|
||||
};
|
||||
assert_eq!(activity.event_type, event_type);
|
||||
assert_eq!(activity.priority, EventPriority::P1);
|
||||
assert_eq!(activity.payload, payload);
|
||||
assert!(!state.has_pending_requests());
|
||||
assert_eq!(state.active_turn_id(), Some("turn-1"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rich_activity_rejects_terminal_semantic_source_and_schema_injection() {
|
||||
for event_type in [
|
||||
"turn.completed",
|
||||
"run.result",
|
||||
"run.completed",
|
||||
"semantic_tool.input",
|
||||
"semantic_tool.result",
|
||||
"runtime.input_requested",
|
||||
"workspace.changed",
|
||||
"harness.diagnostic",
|
||||
"unknown.event",
|
||||
] {
|
||||
assert!(
|
||||
decode_acpx_event(&scope(), &event(event_type, plan())).is_err(),
|
||||
"{event_type}"
|
||||
);
|
||||
}
|
||||
assert!(decode_acpx_event(&scope(), &event("artifact.generated", plan())).is_err());
|
||||
for field in ["source", "sourceRef", "runId", "priority"] {
|
||||
let mut injected = event("plan.updated", plan());
|
||||
injected.payload[field] = json!("forged");
|
||||
assert!(decode_acpx_event(&scope(), &injected).is_err());
|
||||
}
|
||||
let mut extra = plan();
|
||||
extra["sourceRef"] = json!("file:///private/key");
|
||||
assert!(decode_acpx_event(&scope(), &event("plan.updated", extra)).is_err());
|
||||
let mut registered = artifact();
|
||||
registered["registered"] = json!(true);
|
||||
assert!(decode_acpx_event(&scope(), &event("artifact.generated", registered)).is_err());
|
||||
let mut synchronized = plan();
|
||||
synchronized["syncStatus"] = json!("synchronized");
|
||||
synchronized["documentRevision"] = json!(1);
|
||||
assert!(decode_acpx_event(&scope(), &event("plan.updated", synchronized)).is_err());
|
||||
for path in [
|
||||
"/private/key",
|
||||
"../outside",
|
||||
"file:///private/key",
|
||||
"C:\\private\\key",
|
||||
"outputs/evil\u{0000}.png",
|
||||
] {
|
||||
let mut escaped = artifact();
|
||||
escaped["reference"] = json!(path);
|
||||
assert!(
|
||||
decode_acpx_event(&scope(), &event("artifact.generated", escaped)).is_err(),
|
||||
"{path}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rich_activity_requires_the_current_run_and_active_turn() {
|
||||
let mut event = event("plan.updated", plan());
|
||||
event.run_id = Some("old-run".to_owned());
|
||||
assert!(decode_acpx_event(&scope(), &event).is_err());
|
||||
event.run_id = None;
|
||||
assert!(decode_acpx_event(&scope(), &event).is_err());
|
||||
event.run_id = Some("run-1".to_owned());
|
||||
event.turn_id = Some("old-turn".to_owned());
|
||||
assert!(decode_acpx_event(&scope(), &event).is_err());
|
||||
event.turn_id = None;
|
||||
assert!(decode_acpx_event(&scope(), &event).is_err());
|
||||
event.turn_id = Some("turn-1".to_owned());
|
||||
let mut settled = scope();
|
||||
settled.clear_turn("turn-1").unwrap();
|
||||
assert!(decode_acpx_event(&settled, &event).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rich_activity_is_byte_bounded_and_preserves_long_schema_bounded_output() {
|
||||
let text = "Unicode 漢字\n".repeat(1_000);
|
||||
let payload = json!({"schema":"paperclip.tool.execution.v1","executionId":"tool-1","transport":"builtin","operation":"read","status":"completed","output":text,"outputBytes":text.len(),"outputTruncated":false,"outputDigest":null});
|
||||
let AcpxEventPayload::RichActivity { payload, .. } =
|
||||
decode_acpx_event(&scope(), &event("tool.execution.completed", payload)).unwrap()
|
||||
else {
|
||||
panic!("not rich activity");
|
||||
};
|
||||
assert_eq!(payload["output"], text);
|
||||
let mut oversized = plan();
|
||||
oversized["steps"] = json!((0..100).map(|index|json!({"stepId":format!("step-{index}"),"body":"漢".repeat(3_000),"status":"pending"})).collect::<Vec<_>>());
|
||||
assert!(
|
||||
decode_acpx_event(&scope(), &event("plan.updated", oversized))
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("256 KiB")
|
||||
);
|
||||
}
|
||||
|
||||
fn question_event(description: String) -> AcpxSidecarEvent {
|
||||
AcpxSidecarEvent {
|
||||
sequence: 1,
|
||||
event_type: GeneratedAcpxSidecarEventType::RuntimeInputRequested,
|
||||
run_id: Some("run-1".to_owned()),
|
||||
turn_id: Some("turn-1".to_owned()),
|
||||
payload: json!({"requestId":"plan-request","questionSet":{"schema":"paperclip.question_set.v1","description":description,"questions":[{"id":"revision-123","prompt":"Approve?","required":true,"answerMode":"single_select","options":[{"id":"accept","label":"Accept"},{"id":"reject","label":"Reject"}]}]}}),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_plan_presentation_survives_utf8_redaction_without_diagnostic_truncation() {
|
||||
let description = "Review 漢字\n".repeat(2_000);
|
||||
let AcpxEventPayload::InputRequested { question_set, .. } =
|
||||
decode_acpx_event(&scope(), &question_event(description.clone())).unwrap()
|
||||
else {
|
||||
panic!("not input");
|
||||
};
|
||||
assert_eq!(question_set["description"], description);
|
||||
let secret = format!("{description}\napi_key=topsecret\nFinal action");
|
||||
let AcpxEventPayload::InputRequested { question_set, .. } =
|
||||
decode_acpx_event(&scope(), &question_event(secret)).unwrap()
|
||||
else {
|
||||
panic!("not input");
|
||||
};
|
||||
let displayed = question_set["description"].as_str().unwrap();
|
||||
assert!(displayed.starts_with("Sensitive values were redacted"));
|
||||
assert!(displayed.ends_with("Final action"));
|
||||
assert!(!displayed.contains("topsecret"));
|
||||
assert!(!displayed.contains("[truncated]"));
|
||||
assert!(
|
||||
decode_acpx_event(&scope(), &question_event("漢".repeat(70_000)))
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("196 KiB")
|
||||
);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ export type GeneratedAcpxSidecarCommand =
|
||||
|
||||
export const GENERATED_ACPX_SIDECAR_EVENT_TYPES = [
|
||||
"runtime.event",
|
||||
"runtime.rich_event",
|
||||
"runtime.permission_requested",
|
||||
"runtime.input_requested",
|
||||
"runtime.tool_called",
|
||||
|
||||
@@ -60,6 +60,24 @@ test("the ACPX sidecar schema shares the durable stable-identity boundary", () =
|
||||
}
|
||||
});
|
||||
|
||||
test("rich activity has a closed display-only envelope and explicit run/turn scope", () => {
|
||||
const message = {
|
||||
...messages[2],
|
||||
eventType: "runtime.rich_event",
|
||||
payload: { eventType: "plan.updated", itemId: "display-1", payload: {} },
|
||||
};
|
||||
assert.equal(validate(message), true, JSON.stringify(validate.errors));
|
||||
for (const field of ["runId", "turnId"]) {
|
||||
assert.equal(validate({ ...message, [field]: null }), false);
|
||||
}
|
||||
for (const eventType of ["turn.completed", "run.result.proposed", "semantic_tool.input", "unknown"]) {
|
||||
assert.equal(validate({ ...message, payload: { ...message.payload, eventType } }), false);
|
||||
}
|
||||
for (const field of ["sourceRef", "priority", "runId"]) {
|
||||
assert.equal(validate({ ...message, payload: { ...message.payload, [field]: "forged" } }), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("the ACPX sidecar schema fails closed on drift", () => {
|
||||
for (const message of [
|
||||
{ ...messages[0], protocolVersion: protocolVersion + 1 },
|
||||
|
||||
Reference in new issue
Block a user