Python
feat(sdk): support image, PDF and text attachments
Rohit P9ac4f832674a
diff --git a/.github/workflows/rust-sdk.yml b/.github/workflows/rust-sdk.ymlindex c3bbea90..10cb191f 100644--- a/.github/workflows/rust-sdk.yml+++ b/.github/workflows/rust-sdk.yml@@ -62,7 +62,7 @@ jobs:timeout-minutes: 25run: |rustup show active-toolchain- cargo test --locked -p openworker-sdk --features test-support --lib --test desktop_api --test agent_team -- --test-threads=1+ cargo test --locked -p openworker-sdk --features test-support --lib --test desktop_api --test agent_team --test attachments -- --test-threads=1cargo test --locked -p openworker-runtime --lib direct::windows::tests -- --test-threads=1cargo test --locked -p openworker-runtime --test windows --test connections --test model_endpoints --test direct_macos --test coding --test coding_extended --test assistantcargo test --locked -p openworker-sdk --features test-support --test coding --test assistant -- --test-threads=1@@ -230,7 +230,7 @@ jobs:node ../harness/trace-viewer/sync.mjs --checknpm --prefix typescript-sdk run test:integrationnpm --prefix typescript-sdk run test:dynamic-agents- node --test --test-concurrency=2 --test-reporter=tap typescript-sdk/test/chat-usage.test.mjs typescript-sdk/test/openrouter-streaming.test.mjs typescript-sdk/test/anthropic-caching.test.mjs typescript-sdk/test/gemini-compat.test.mjs typescript-sdk/test/session-options.test.mjs typescript-sdk/test/stream-events.test.mjs+ node --test --test-concurrency=2 --test-reporter=tap typescript-sdk/test/chat-usage.test.mjs typescript-sdk/test/openrouter-streaming.test.mjs typescript-sdk/test/anthropic-caching.test.mjs typescript-sdk/test/gemini-compat.test.mjs typescript-sdk/test/session-options.test.mjs typescript-sdk/test/stream-events.test.mjs typescript-sdk/test/attachments.test.mjsnode --test --test-reporter=tap typescript-sdk/test/desktop-api.test.mjs typescript-sdk/test/agent-team.test.mjs typescript-sdk/test/standalone-subagents.test.mjsnode --test --test-reporter=tap typescript-sdk/test/coding.test.mjs typescript-sdk/test/assistant.test.mjs- name: Starter and partner packaging@@ -286,6 +286,8 @@ jobs:- name: Runtime and telemetry regressionsrun: |cargo test --locked -p openworker-runtime -- --test-threads=1+ cargo test --locked -p openworker-runtime --no-default-features --test attachment_features+ cargo test --locked -p openworker-server-reference --test input_attachments -- --ignored --test-threads=1cargo test --locked -p openworker-telemetry --features otlpOW_OBSERVABILITY_TEST_URL="$OW_PG_TEST_URL" cargo test --locked -p openworker-observability --features postgres,evaluations -- --include-ignored --test-threads=1cargo test --locked -p openworker-store-postgres --features test-support --test environments terminal_team_save_ -- --ignored --test-threads=1diff --git a/docs/harness/guides/attachments.md b/docs/harness/guides/attachments.mdnew file mode 100644index 00000000..867d6045--- /dev/null+++ b/docs/harness/guides/attachments.md@@ -0,0 +1,174 @@+# Attach images, PDFs and text files++**Source preview.** These APIs require the SDK and runtime from this branch;+they are not included in the published `0.1.0-beta.2` packages. The host advertises+`capabilities.attachments`; a remote service advertises `features.attachments`.+An older host returns a setup error rather than dropping a file.++Attach a screenshot, a PDF report or a UTF-8 text file to a user message. Files+are model inputs: attaching a file does not place it in a sandbox, grant a tool+permission or share it with a child agent. Choose a model that accepts the formats+you use. Provider request/context limits still apply.++## Add files after a message++```typescript+import { Attachment } from '@openworkerai/harness-sdk';++const screen = await Attachment.fromFile('./screen.png');+const report = await Attachment.fromFile('./report.pdf');+const result = await session.run('Compare this screen with the report.', [screen, report]);+```++A single attachment works too: `session.run('Explain this.', report)`. Existing+`session.run(text, options)` calls keep their meaning. Pass turn options as the+third argument when using the attachment convenience form.++`Attachment.fromFile` reads on the caller's machine. For a browser upload, send+bytes through your authenticated application backend, check the user's ownership+and size limits there, then construct an attachment in the backend:++```typescript+const report = Attachment.fromBytes({+ name: 'report.pdf', mediaType: 'application/pdf', data: uploadedBytes,+});+```++The Node SDK runs in your server or desktop application's trusted process.+Browser and renderer code use your application's upload/API boundary.++## Interleave text and files++An ordered `content` array represents one user message. Text can appear between+files; order is preserved in storage and provider requests.++```typescript+const input = { content: [+ { type: 'text' as const, text: 'Look at this screen.' }, screen,+ { type: 'text' as const, text: 'Compare it with this report.' }, report,+ { type: 'document' as const, name: 'notes.md', source: {+ type: 'text' as const, mediaType: 'text/plain' as const,+ data: 'The report covers the previous release.',+ } },+] };+const run = await session.send(input, { submissionId: 'review-42' });+for await (const event of run.events()) { /* update your UI */ }+const result = await run.result();+```++`run`, `send`, `runWith` and `runStreamed` accept structured input. `runStreamed`+also accepts the text-plus-attachments convenience form. An explicit image or+document block can use a base64 source:++```typescript+{ type: 'image', name: 'screen.png', source: {+ type: 'base64', mediaType: 'image/png', data: imageBase64,+} }+```++Use `{type: 'attachment', id}` as the source only for an already committed+OpenWorker attachment **in this session**. These are not OpenAI or Anthropic file+IDs. The harness rechecks ownership and type at admission; a label cannot change+the stored file. URLs and provider-owned file IDs are outside this initial API.++## Rust++```rust+use openworker_sdk::{Attachment, InputContent, UserInput};++let report = Attachment::from_file("./report.pdf")?;+let input = UserInput::new(vec![+ InputContent::text("Read this report."),+ report.clone().into(),+ InputContent::text("Explain the main changes."),+]);+let result = session.run_input(input).await?;+// Convenience form:+let result = session.run_with_attachments("Explain this.", vec![report]).await?;+```++Use `send_input(input, TurnOptions)` for submission IDs and turn options, or+`run_input_streamed(input)` for journal events followed by `finish()`.++## Connect to a service++The same TypeScript input works with a connected service session:++```typescript+const run = await serviceSession.send(input, { idempotencyKey: 'review-42' });+```++Rust service sessions expose `send_input(input, limits, idempotency_key)`.+The SDK stages bounded chunks over authenticated HTTP, then submits references.+Each chunk is checked against the caller's session permissions. API replicas and+replacement workers share immutable bytes through the execution PostgreSQL+store; the observability database does not store those bytes.++## Formats, limits and recovery++| Input | Model representation |+| --- | --- |+| PNG, JPEG, static GIF, static WebP | Native image part |+| PDF | Original PDF document, without text extraction |+| UTF-8 text (`.txt`, `.md`, `.json`, `.csv`, source files) | Named text at the same content position |++The initial SDK limits are **8 MiB per file**, **16 MiB of files per message**,+**32 content blocks** and **32,000 bytes of inline text**. A session reserves at+most **128 files / 64 MiB** of stored files, including uploads awaiting acceptance. The host+checks media headers, UTF-8 and hashes; this is not malware scanning or a full+image/PDF decoder. Unsupported formats and animation are rejected. Provider/model+limits can be smaller; the SDK does not promise that every model supports PDF or+vision input. Gemini-native input is not part of this qualification.++The stdio frame limit remains 1 MiB. The SDK hides 256 KiB raw-byte upload chunks,+checksum validation and commit. Uploads can be repeated with identical bytes;+conflicting bytes or metadata are rejected. Reuse the same submission ID and+content to reconcile a lost turn receipt. Changing a file, its label, order or+text requires a new submission ID.++Accepted history stores immutable references. Bytes remain in the session's+private execution store for restart/recovery and provider switching. Compaction+retains text and reference descriptions in its summary input while preserving+the complete original history and bytes. It may omit older file bodies from the+current model context. The existing `initialHistory` import remains text and+completed tool calls/results; it does not copy another session's files.++Unaccepted uploads, including sealed files, expire after 24 hours and are cleaned+on the next upload in that session. Accepted references remain for the session's+retention lifetime. Retrying an expired upload stages the same bytes again.+Cancellation while staging prevents turn submission; it can leave an expiring+upload. After turn acceptance, stopping a wait does not cancel agent execution.++## Guardrails and privacy++User-input checks cover each inline text block and decoded text file. A redaction+creates a new immutable file reference; the accepted message points to the checked+text. Model-input checks also see decoded text documents. Existing guardrail size+limits apply (currently 128,000 bytes per inspected input); oversized required+checks fail closed. Large text attachments without those checks are still subject+to the selected model's context limit.++Text-only guardrails cannot inspect pixels or PDF pages. Binary attachments are+rejected when a configured user-input or model-input policy requires inspection.+A model-input policy added on a later turn also covers binary files still present+in that turn's model context.+There is no implicit OCR, extraction or multimodal safety scanner. Scan those+files in your application or use text inputs when that policy is required.++Ordinary journal events and snapshots contain references, not file bodies or+base64. Binary content is withheld even from full-content model telemetry. Text+files become model text, so explicit full-content capture can include checked+text; keep capture disabled or redacted for sensitive documents.++## Upgrade an existing store++Use matching SDK, service and worker builds. SQLite upgrades compatible versions+7/8 to **9** while preserving records; older binaries refuse version 9. PostgreSQL+requires an explicit migration to schema **7**. Drain API/worker processes and+release or expire execution leases before running the migration. The database+rejects writes from older workers so a queued file input cannot silently become+a text-only turn. Back up persistent stores before an upgrade.++For a lightweight Rust build, disable default features and enable only what you+need. Attachment admission/upload can be excluded with the `attachments` feature;+no PDF renderer, OCR engine or office converter is linked by this feature.diff --git a/docs/harness/guides/sessions.md b/docs/harness/guides/sessions.mdindex 0616d6c1..36837a8b 100644--- a/docs/harness/guides/sessions.md+++ b/docs/harness/guides/sessions.md@@ -40,6 +40,12 @@ limit does not increase that total. Set limits on the agent for defaults or onReusing a submission ID requires the same message, context, limits and safetyoptions; a changed addendum is a new turn with a new submission ID.+## Attach a file++The source preview supports images, PDFs and UTF-8 files as ordered user-message+content. See [Attachments](attachments.md) for the convenience and interleaved+forms, storage limits and guardrail behavior.+## Import a conversationUse `initialHistory` only when creating a new session. Ordinary recovery shoulddiff --git a/harness/Cargo.lock b/harness/Cargo.lockindex 355f3eee..87924aa4 100644--- a/harness/Cargo.lock+++ b/harness/Cargo.lock@@ -1941,6 +1941,7 @@ version = "0.1.0-beta.2"dependencies = ["anyhow","async-stream",+ "base64 0.22.1","chrono","fs2","futures-util",diff --git a/harness/harness-sdk/Cargo.toml b/harness/harness-sdk/Cargo.tomlindex 1c27fd64..a40b8382 100644--- a/harness/harness-sdk/Cargo.toml+++ b/harness/harness-sdk/Cargo.toml@@ -10,7 +10,8 @@ license.workspace = truepublish = ["crates-io"][features]-default = ["guardrails", "compliance", "otlp"]+default = ["guardrails", "compliance", "otlp", "attachments"]+attachments = ["openworker-runtime/attachments", "openworker-store-postgres/attachments"]otlp = ["openworker-telemetry/otlp"]recording = ["dep:openworker-observability"]evaluations = ["recording", "openworker-observability/evaluations"]@@ -32,6 +33,7 @@ openworker-observability = { path = "../observability", version = "=0.1.0-beta.2openworker-security-adapters = { version = "=0.1.0-beta.2", path = "../security-adapters", optional = true }reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }anyhow = "1"+base64 = "0.22"fs2 = "0.4"rusqlite = { version = "0.32", features = ["bundled"] }openworker-store-postgres = { version = "=0.1.0-beta.2", path = "../store-postgres" }diff --git a/harness/harness-sdk/README.md b/harness/harness-sdk/README.mdindex 1e946cd9..39f8717f 100644--- a/harness/harness-sdk/README.md+++ b/harness/harness-sdk/README.md@@ -354,3 +354,10 @@ See the [observability guide](../../docs/harness/guides/observability.md) for loSQLite/PostgreSQL, Langfuse export, content selection and audit references. Thesenew APIs require matching local candidate builds and are not in the published0.1.0-beta.2 packages yet.++## User attachments (source preview)++Attach images, PDFs and UTF-8 text files to a session with ordered content and+immutable recovery references. See [Attachments](../../docs/harness/guides/attachments.md)+for the Rust/TypeScript APIs, service uploads, limits and upgrade instructions.+This API requires matching source builds; it is not in npm `0.1.0-beta.2`.diff --git a/harness/harness-sdk/src/agents/session.rs b/harness/harness-sdk/src/agents/session.rsindex 5cc8e54a..158c8243 100644--- a/harness/harness-sdk/src/agents/session.rs+++ b/harness/harness-sdk/src/agents/session.rs@@ -709,6 +709,59 @@ impl Session {let cursors = started["cursors"].as_object().cloned().unwrap_or_default();Ok(self.spawn(Some(submission), cursors))}+ /// Submit an ordered user message, staging immutable attachments first.+ pub async fn send_input(+ &self,+ input: crate::UserInput,+ options: crate::TurnOptions,+ ) -> Result<Run> {+ let parts = input.upload(&self.client, self.id()).await?;+ let id = options+ .submission_id+ .unwrap_or_else(|| openworker_runtime::id("sub"));+ let value=self.client.request("session/send",json!({"session_id":self.id(),"submission_id":id,"input":{"content":parts},"limits":options.limits,"safety":options.safety,"instruction_addendum":options.instruction_addendum,"output":options.output})).await?;+ Ok(Run {+ session: self.clone(),+ submission: id,+ cursors: value["cursors"].as_object().cloned().unwrap_or_default(),+ })+ }+ pub async fn run_input(&self, input: crate::UserInput) -> Result<RunResult> {+ let parts = input.upload(&self.client, self.id()).await?;+ let id = openworker_runtime::id("sub");+ self.client+ .request(+ "run/start",+ json!({"session_id":self.id(),"submission_id":id,"content":parts}),+ )+ .await?;+ self.wait(Some(&id)).await+ }+ pub async fn run_with_attachments(+ &self,+ text: &str,+ attachments: Vec<crate::Attachment>,+ ) -> Result<RunResult> {+ let mut content = vec![crate::InputContent::text(text)];+ content.extend(attachments.into_iter().map(crate::InputContent::from));+ self.run_input(crate::UserInput::new(content)).await+ }+ pub async fn run_input_streamed(&self, input: crate::UserInput) -> Result<RunStream> {+ let parts = input.upload(&self.client, self.id()).await?;+ let id = openworker_runtime::id("sub");+ let started = self+ .client+ .request(+ "run/start",+ json!({"session_id":self.id(),"submission_id":id,"content":parts}),+ )+ .await?;+ Ok(self.spawn(+ Some(id),+ started["cursors"].as_object().cloned().unwrap_or_default(),+ ))+ }+/// Keep waiting after responding to interruptions (or after reattaching).pub async fn resume(&self) -> Result<RunResult> {self.wait(None).awaitdiff --git a/harness/harness-sdk/src/attachments.rs b/harness/harness-sdk/src/attachments.rsnew file mode 100644index 00000000..bf4436ab--- /dev/null+++ b/harness/harness-sdk/src/attachments.rs@@ -0,0 +1,245 @@+//! User attachments are uploaded in bounded chunks; accepted messages store references.+use crate::{Error, HarnessClient, Result};+use base64::{engine::general_purpose::STANDARD, Engine};+use serde_json::{json, Value};+use std::{io::Read, path::Path};+#[derive(Clone)]+pub struct Attachment {+ name: String,+ media_type: String,+ bytes: Vec<u8>,+}+impl Attachment {+ pub fn from_bytes(+ name: impl Into<String>,+ media_type: impl Into<String>,+ bytes: Vec<u8>,+ ) -> Result<Self> {+ let a = Self {+ name: name.into(),+ media_type: media_type.into(),+ bytes,+ };+ a.metadata()?+ .validate()+ .map_err(|e| Error::InvalidInput(e.to_string()))?;+ openworker_runtime::attachments::validate_bytes(&a.media_type, &a.bytes)+ .map_err(|e| Error::InvalidInput(e.to_string()))?;+ Ok(a)+ }+ pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {+ let path = path.as_ref();+ let name = path+ .file_name()+ .and_then(|s| s.to_str())+ .ok_or_else(|| Error::InvalidInput("Invalid attachment filename".into()))?;+ let ext = path+ .extension()+ .and_then(|s| s.to_str())+ .unwrap_or("")+ .to_lowercase();+ let mime = match ext.as_str() {+ "png" => "image/png",+ "jpg" | "jpeg" => "image/jpeg",+ "gif" => "image/gif",+ "webp" => "image/webp",+ "pdf" => "application/pdf",+ _ => "text/plain",+ };+ let metadata = std::fs::metadata(path)+ .map_err(|_| Error::InvalidInput("Cannot read attachment".into()))?;+ if !metadata.is_file() || metadata.len() > openworker_runtime::attachments::MAX_FILE as u64+ {+ return Err(Error::InvalidInput(+ "Attachment must be a bounded regular file".into(),+ ));+ }+ let mut bytes = vec![];+ std::fs::File::open(path)+ .map_err(|_| Error::InvalidInput("Cannot read attachment".into()))?+ .take((openworker_runtime::attachments::MAX_FILE + 1) as u64)+ .read_to_end(&mut bytes)+ .map_err(|_| Error::InvalidInput("Cannot read attachment".into()))?;+ Self::from_bytes(name, mime, bytes)+ }+ fn metadata(&self) -> Result<openworker_runtime::attachments::Metadata> {+ let sha256 = openworker_runtime::bundle::digest(&self.bytes);+ let id = openworker_runtime::bundle::digest(+ &serde_json::to_vec(&json!([self.name, self.media_type, sha256])).unwrap(),+ );+ Ok(openworker_runtime::attachments::Metadata {+ id: format!("att_{id}"),+ name: self.name.clone(),+ media_type: self.media_type.clone(),+ size: self.bytes.len(),+ sha256,+ })+ }+ async fn stage(+ &self,+ destination: &Destination<'_>,+ sid: &str,+ ) -> Result<openworker_runtime::attachments::Part> {+ let m = self.metadata()?;+ destination.check()?;+ let call = |upload: Value| json!({"session_id":sid,"id":m.id,"upload":upload});+ let receipt = destination+ .request(call(json!({"operation":"begin","metadata":m})))+ .await?;+ if receipt["sealed"] != true {+ for (i, chunk) in self+ .bytes+ .chunks(openworker_runtime::attachments::CHUNK)+ .enumerate()+ {+ destination.request(call(json!({"operation":"chunk","offset":i*openworker_runtime::attachments::CHUNK,"data":STANDARD.encode(chunk)}))).await?;+ }+ destination+ .request(call(json!({"operation":"commit"})))+ .await?;+ }+ Ok(if self.media_type.starts_with("image/") {+ openworker_runtime::attachments::Part::Image {+ attachment_id: m.id,+ }+ } else {+ openworker_runtime::attachments::Part::Document {+ attachment_id: m.id,+ }+ })+ }+}+#[derive(Clone)]+pub enum InputContent {+ Text(String),+ Attachment(Attachment),+ Reference(openworker_runtime::attachments::Part),+}+impl InputContent {+ pub fn text(text: impl Into<String>) -> Self {+ Self::Text(text.into())+ }+}+impl From<Attachment> for InputContent {+ fn from(a: Attachment) -> Self {+ Self::Attachment(a)+ }+}+#[derive(Clone)]+pub struct UserInput {+ pub content: Vec<InputContent>,+}+impl UserInput {+ pub fn new(content: Vec<InputContent>) -> Self {+ Self { content }+ }+ pub(crate) async fn upload(+ &self,+ client: &HarnessClient,+ sid: &str,+ ) -> Result<Vec<openworker_runtime::attachments::Part>> {+ self.stage(Destination::Managed(client), sid).await+ }+ pub(crate) async fn upload_service(+ &self,+ service: &crate::service::Service,+ sid: &str,+ ) -> Result<Vec<openworker_runtime::attachments::Part>> {+ self.stage(Destination::Service(service), sid).await+ }+ async fn stage(+ &self,+ destination: Destination<'_>,+ sid: &str,+ ) -> Result<Vec<openworker_runtime::attachments::Part>> {+ if self.content.is_empty() || self.content.len() > 32 {+ return Err(Error::InvalidInput(+ "Input content must have 1..32 blocks".into(),+ ));+ }+ let mut total = 0usize;+ let mut preview = vec![];+ for p in &self.content {+ preview.push(match p {+ InputContent::Text(text) => {+ openworker_runtime::attachments::Part::Text { text: text.clone() }+ }+ InputContent::Attachment(a) => {+ total = total.saturating_add(a.bytes.len());+ if a.media_type.starts_with("image/") {+ openworker_runtime::attachments::Part::Image {+ attachment_id: a.metadata()?.id,+ }+ } else {+ openworker_runtime::attachments::Part::Document {+ attachment_id: a.metadata()?.id,+ }+ }+ }+ InputContent::Reference(p) => p.clone(),+ });+ }+ if total > openworker_runtime::attachments::MAX_TURN {+ return Err(Error::InvalidInput(+ "Turn attachment byte limit exceeded".into(),+ ));+ }+ openworker_runtime::attachments::validate_parts(&preview)+ .map_err(|e| Error::InvalidInput(e.to_string()))?;+ let mut parts = vec![];+ for p in &self.content {+ parts.push(match p {+ InputContent::Text(text) => {+ openworker_runtime::attachments::Part::Text { text: text.clone() }+ }+ InputContent::Attachment(a) => a.stage(&destination, sid).await?,+ InputContent::Reference(p) => p.clone(),+ });+ }+ openworker_runtime::attachments::validate_parts(&parts)+ .map_err(|e| Error::InvalidInput(e.to_string()))?;+ Ok(parts)+ }+}++enum Destination<'a> {+ Managed(&'a HarnessClient),+ Service(&'a crate::service::Service),+}+impl Destination<'_> {+ fn check(&self) -> Result<()> {+ let supported = match self {+ Self::Managed(c) => c.info()["capabilities"]["attachments"] == true,+ Self::Service(c) => c.capabilities()["features"]["attachments"] == true,+ };+ if supported {+ Ok(())+ } else {+ Err(Error::Setup("Host does not support attachments".into()))+ }+ }+ async fn request(&self, p: Value) -> Result<Value> {+ match self {+ Self::Managed(c) => c.request("attachment/upload", p).await,+ Self::Service(s) => s+ .json(+ "POST",+ &format!(+ "/v1/sessions/{}/attachments/{}",+ p["session_id"].as_str().unwrap(),+ p["id"].as_str().unwrap()+ ),+ Some(p["upload"].clone()),+ None,+ )+ .await+ .map_err(|e| {+ if e.code == "outcome_unknown" {+ Error::OutcomeUnknown+ } else {+ Error::Remote(e.to_string())+ }+ }),+ }+ }+}diff --git a/harness/harness-sdk/src/host.rs b/harness/harness-sdk/src/host.rsindex e2f5283e..25933538 100644--- a/harness/harness-sdk/src/host.rs+++ b/harness/harness-sdk/src/host.rs@@ -1131,6 +1131,13 @@ impl Host {c.insert("telemetry_export".into(), json!(cfg!(feature = "otlp")));c.insert("turn_limits".into(), json!(true));c.insert("turn_context".into(), json!(true));+ c.insert(+ "attachments".into(),+ json!(+ cfg!(feature = "attachments")+ && self.store.lock().unwrap().supports_input_attachments()+ ),+ );c.insert("initial_history".into(), json!(true));c.insert("builtin_tools".into(), json!(true));c.insert("per_call_output_limit".into(), json!(true));diff --git a/harness/harness-sdk/src/host_runs.rs b/harness/harness-sdk/src/host_runs.rsindex 58f496a9..0a78409e 100644--- a/harness/harness-sdk/src/host_runs.rs+++ b/harness/harness-sdk/src/host_runs.rs@@ -93,19 +93,31 @@ impl Host {let _run_admission = self.run_admission.lock().await;let sid = text(p, "session_id")?;let submission = text(p, "submission_id")?;- let context = openworker_runtime::turn_options::Context::from_request(p)?;- let context_digest = context.digest()?;- let raw_input = openworker_runtime::runtime::text(p, "text", 32000)?;+ let mut context = openworker_runtime::turn_options::Context::from_request(p)?;let coworker = self.store.lock().unwrap().metadata(sid)?.coworker;let safety = p.get("safety").filter(|v| !v.is_null()).map(|v| serde_json::from_value::<openworker_runtime::safety::Config>(v.clone())).transpose()?;- let input = self- .runtime(&coworker)?- .check_user_input_with(sid, raw_input, safety.as_ref())- .await?;+ let runtime = self.runtime(&coworker)?;+ let input = if let Some(parts) = &context.content {+ let parts = runtime+ .prepare_input_content(sid, parts, safety.as_ref())+ .await?;+ let text = openworker_runtime::attachments::summary(&parts);+ context.content = Some(parts);+ text+ } else {+ runtime+ .check_user_input_with(+ sid,+ openworker_runtime::runtime::text(p, "text", 32000)?,+ safety.as_ref(),+ )+ .await?+ };+ let context_digest = context.digest()?;if let Some(value) = p.get("limits").filter(|v| !v.is_null()) {let limits: openworker_runtime::budget::Limits = serde_json::from_value(value.clone())?;limits.validate()?;@@ -164,7 +176,7 @@ impl Host {let started = self.retry_busy("turn/start",- json!({"session_id":sid,"submission_id":submission,"text":input,"limits":p["limits"],"safety":p["safety"],"instruction_addendum":context.instruction_addendum,"output":context.output}),+ json!({"session_id":sid,"submission_id":submission,"text":input,"limits":p["limits"],"safety":p["safety"],"instruction_addendum":context.instruction_addendum,"output":context.output,"content":context.content}),).await;match started {@@ -300,7 +312,7 @@ impl Host {.transpose()?.unwrap_or("message");let allowed: &[&str] = match kind {- "message" => &["type", "text"],+ "message" => &["type", "text", "content"],"answer" => &["type", "text", "interaction_id", "target_session_id"],"approval" => &["type", "decision", "interaction_id", "target_session_id"],"steer" => bail!("Steering is not supported by this host"),@@ -319,7 +331,7 @@ impl Host {"Safety overrides apply only to new turns");if kind == "message" {- return self.run_start(&json!({"session_id":sid,"text":input["text"],"submission_id":text(p,"submission_id")?,"limits":p["limits"],"safety":p["safety"],"instruction_addendum":p["instruction_addendum"],"output":p["output"]})).await;+ return self.run_start(&json!({"session_id":sid,"text":input["text"],"submission_id":text(p,"submission_id")?,"limits":p["limits"],"safety":p["safety"],"instruction_addendum":p["instruction_addendum"],"output":p["output"],"content":input["content"]})).await;}ensure!(p.get("instruction_addendum").is_none_or(Value::is_null)diff --git a/harness/harness-sdk/src/lib.rs b/harness/harness-sdk/src/lib.rsindex 5bdd7705..f3ee9f3e 100644--- a/harness/harness-sdk/src/lib.rs+++ b/harness/harness-sdk/src/lib.rs@@ -526,3 +526,6 @@ pub use openworker_runtime::compliance_export::Sink as ComplianceSink;#[cfg(feature = "evaluations")]pub use openworker_observability::evaluations;++mod attachments;+pub use attachments::{Attachment, InputContent, UserInput};diff --git a/harness/harness-sdk/src/service.rs b/harness/harness-sdk/src/service.rsindex b81adfb4..642588ea 100644--- a/harness/harness-sdk/src/service.rs+++ b/harness/harness-sdk/src/service.rs@@ -681,6 +681,52 @@ impl Session {.into(),})}+ /// Upload immutable inputs over the authenticated service boundary, then+ /// submit their ordered references using the caller's idempotency key.+ pub async fn send_input(+ &self,+ input: crate::UserInput,+ limits: Option<openworker_runtime::budget::Limits>,+ key: Option<&str>,+ ) -> Result<Run> {+ let _ = id(self.id())?;+ let content = input+ .upload_service(&self.service, self.id())+ .await+ .map_err(|e| {+ error(if matches!(e, crate::Error::OutcomeUnknown) {+ "outcome_unknown"+ } else {+ "attachment_upload_failed"+ })+ })?;+ if let Some(limits) = &limits {+ limits+ .validate()+ .map_err(|_| error("invalid_turn_limits"))?;+ }+ let generated = openworker_runtime::id("idem");+ let r = self+ .service+ .json(+ "POST",+ &format!("/v1/sessions/{}/turns", id(self.id())?),+ Some(json!({"content":content,"limits":limits})),+ Some(key.unwrap_or(&generated)),+ )+ .await?;+ Ok(Run {+ session: self.clone(),+ id: r["runId"]+ .as_str()+ .ok_or_else(|| error("invalid_receipt"))?+ .into(),+ submission_id: r["submissionId"]+ .as_str()+ .ok_or_else(|| error("invalid_receipt"))?+ .into(),+ })+ }pub async fn resume_run(&self, submission: &str) -> Result<Run> {let r = self.servicediff --git a/harness/harness-sdk/tests/attachments.rs b/harness/harness-sdk/tests/attachments.rsnew file mode 100644index 00000000..cbaf9993--- /dev/null+++ b/harness/harness-sdk/tests/attachments.rs@@ -0,0 +1,184 @@+#![cfg(all(feature = "test-support", feature = "attachments"))]+use openworker_sdk::{agents::*, *};+use serde_json::Value;+use std::{+ path::PathBuf,+ sync::{Arc, Mutex},+ time::Duration,+};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+async fn exercise(managed: bool) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}/v1", listener.local_addr().unwrap());+ let requests = Arc::new(Mutex::new(vec![]));+ let captured = requests.clone();+ let server = tokio::spawn(async move {+ for _ in 0..3 {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut raw = vec![];+ let mut buffer = [0; 8192];+ let end = loop {+ let n = socket.read(&mut buffer).await.unwrap();+ assert!(n > 0);+ raw.extend_from_slice(&buffer[..n]);+ if let Some(i) = raw.windows(4).position(|b| b == b"\r\n\r\n") {+ break i + 4;+ }+ };+ let len = String::from_utf8_lossy(&raw[..end])+ .lines()+ .find_map(|l| {+ l.to_lowercase()+ .strip_prefix("content-length:")+ .map(|v| v.trim().parse::<usize>().unwrap())+ })+ .unwrap();+ assert!(len < 2_000_000);+ while raw.len() < end + len {+ let n = socket.read(&mut buffer).await.unwrap();+ assert!(n > 0);+ raw.extend_from_slice(&buffer[..n]);+ }+ let body: Value = serde_json::from_slice(&raw[end..end + len]).unwrap();+ captured.lock().unwrap().push(body);+ let response="data: {\"id\":\"fixture\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Read.\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n";+ socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",response.len(),response).as_bytes()).await.unwrap();+ }+ });+ let root = tempfile::tempdir().unwrap();+ let binary = PathBuf::from(env!("CARGO_BIN_EXE_sdk-test-host"));+ let builder = || {+ Harness::builder()+ .state_dir(root.path())+ .executable(&binary)+ .sandbox(Sandbox::Off)+ };+ let harness = if managed {+ builder()+ .managed(binary.clone(), RestartPolicy::default())+ .await+ } else {+ builder().start().await+ }+ .unwrap();+ harness+ .set_model_provider(ModelProvider::chat_completions("Fixture").base_url(url.clone()))+ .await+ .unwrap();+ let definition = || {+ Agent::new("reader")+ .instructions("Read attached files.")+ .tools([] as [&str; 0])+ .memory(false)+ .planning(false)+ .scheduling(false)+ .default_model(Model::new("Fixture", "fixture"))+ };+ let session = harness+ .create_agent(definition())+ .await+ .unwrap()+ .new_session()+ .await+ .unwrap();+ let document = Attachment::from_bytes("notes.md", "text/plain", vec![65; 300000]).unwrap();+ let input = UserInput::new(vec![+ InputContent::text("Before"),+ document.clone().into(),+ InputContent::text("After"),+ ]);+ let stream = session.run_input_streamed(input.clone()).await.unwrap();+ let mut stream = stream;+ let mut deltas = String::new();+ while let Some(e) = stream.next().await {+ if let RunEvent::TextDelta { text, .. } = e {+ deltas.push_str(&text);+ }+ }+ assert_eq!(stream.finish().await.unwrap().status, RunStatus::Completed);+ assert_eq!(deltas, "Read.");+ let request = requests.lock().unwrap()[0].clone();+ let parts = &request["messages"][1]["content"];+ assert_eq!(parts[0]["text"], "Before");+ assert!(parts[1]["text"]+ .as_str()+ .unwrap()+ .starts_with("Attached text file: notes.md\n"));+ assert_eq!(parts[2]["text"], "After");+ let run = session+ .send_input(+ input.clone(),+ TurnOptions {+ submission_id: Some("same".into()),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(run.result().await.unwrap().status, RunStatus::Completed);+ assert_eq!(+ session+ .send_input(+ input,+ TurnOptions {+ submission_id: Some("same".into()),+ ..Default::default()+ }+ )+ .await+ .unwrap()+ .result()+ .await+ .unwrap()+ .status,+ RunStatus::Completed+ );+ assert_eq!(requests.lock().unwrap().len(), 2);+ assert!(session+ .send_input(+ UserInput::new(vec![InputContent::text("different")]),+ TurnOptions {+ submission_id: Some("same".into()),+ ..Default::default()+ }+ )+ .await+ .is_err());+ let reference = session.reference().clone();+ harness.shutdown().await.unwrap();+ drop(session);+ drop(harness);+ let harness = if managed {+ builder()+ .managed(binary.clone(), RestartPolicy::default())+ .await+ } else {+ builder().start().await+ }+ .unwrap();+ harness+ .set_model_provider(ModelProvider::chat_completions("Fixture").base_url(url))+ .await+ .unwrap();+ harness.create_agent(definition()).await.unwrap();+ let resumed = harness.resume(reference).await.unwrap();+ assert_eq!(+ resumed.run("Continue").await.unwrap().status,+ RunStatus::Completed+ );+ assert_eq!(+ requests.lock().unwrap()[2]["messages"][1]["content"],+ *parts+ );+ harness.shutdown().await.unwrap();+ server.await.unwrap();+}+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn attachments_work_in_process_and_managed_subprocess() {+ tokio::time::timeout(Duration::from_secs(120), async {+ exercise(false).await;+ exercise(true).await+ })+ .await+ .unwrap();+}diff --git a/harness/runtime/Cargo.toml b/harness/runtime/Cargo.tomlindex ef4d2f2e..909814c4 100644--- a/harness/runtime/Cargo.toml+++ b/harness/runtime/Cargo.toml@@ -15,7 +15,8 @@ path = "src/main.rs"# Fault-injection fixtures are opt-in and excluded from shipped builds.[features]-default = ["guardrails", "compliance"]+default = ["guardrails", "compliance", "attachments"]+attachments = []guardrails = ["openworker-guardrails/engine"]compliance = []compliance-export = ["compliance"]diff --git a/harness/runtime/src/anthropic.rs b/harness/runtime/src/anthropic.rsindex 37e86be4..95a939d9 100644--- a/harness/runtime/src/anthropic.rs+++ b/harness/runtime/src/anthropic.rs@@ -78,6 +78,7 @@ fn content(value: &Value) -> Result<Vec<Value>, Error> {Some("text" | "input_text" | "output_text") => {Ok(json!({"type":"text","text":v["text"].as_str().ok_or_else(config)?}))}+ Some("input_file") => {let url=v["file_data"].as_str().ok_or_else(config)?;let data=url.strip_prefix("data:application/pdf;base64,").ok_or_else(config)?;Ok(json!({"type":"document","title":v["filename"],"source":{"type":"base64","media_type":"application/pdf","data":data}}))}Some("input_image") => {let url = v["image_url"].as_str().ok_or_else(config)?;let (header, data) = url.split_once(",").ok_or_else(config)?;diff --git a/harness/runtime/src/attachments.rs b/harness/runtime/src/attachments.rsnew file mode 100644index 00000000..998362f3--- /dev/null+++ b/harness/runtime/src/attachments.rs@@ -0,0 +1,518 @@+//! Immutable session-owned model inputs. Bytes never enter journals or RPC replies.+use anyhow::{ensure, Context, Result};+use base64::{engine::general_purpose::STANDARD, Engine};+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+pub const CHUNK: usize = 256 * 1024;+pub const MAX_FILE: usize = 8 * 1024 * 1024;+pub const MAX_SESSION: usize = 64 * 1024 * 1024;+pub const MAX_SESSION_FILES: usize = 128;+pub const MAX_TURN: usize = 16 * 1024 * 1024;+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Metadata {+ pub id: String,+ pub name: String,+ pub media_type: String,+ pub size: usize,+ pub sha256: String,+}+impl Metadata {+ pub fn validate(&self) -> Result<()> {+ ensure!(+ cfg!(feature = "attachments"),+ "Attachments are not included in this build"+ );+ component(&self.id)?;+ ensure!(+ !self.name.is_empty()+ && self.name.len() <= 240+ && !self.name.chars().any(char::is_control)+ && !self.name.contains(['/', '\\']),+ "Invalid attachment name"+ );+ ensure!(+ self.size > 0 && self.size <= MAX_FILE,+ "Attachment size limit exceeded"+ );+ ensure!(+ self.sha256.len() == 64+ && self+ .sha256+ .bytes()+ .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)),+ "Invalid attachment checksum"+ );+ ensure!(+ [+ "image/png",+ "image/jpeg",+ "image/webp",+ "image/gif",+ "application/pdf",+ "text/plain"+ ]+ .contains(&self.media_type.as_str()),+ "Unsupported attachment media type"+ );+ Ok(())+ }+}+#[derive(Clone, Deserialize)]+#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]+pub enum Upload {+ Begin { metadata: Metadata },+ Chunk { offset: usize, data: String },+ Commit,+ Stat,+}+#[derive(Clone)]+pub struct Blob {+ pub metadata: Metadata,+ pub bytes: Vec<u8>,+ pub sealed: bool,+}+impl Blob {+ pub fn reply(&self) -> Value {+ json!({"metadata":self.metadata,"received":self.bytes.len(),"sealed":self.sealed})+ }+}+pub fn apply(id: &str, old: Option<Blob>, request: Upload) -> Result<Blob> {+ ensure!(+ cfg!(feature = "attachments"),+ "Attachments are not included in this build"+ );+ match request {+ Upload::Begin { metadata } => {+ metadata.validate()?;+ ensure!(metadata.id == id, "Attachment ID mismatch");+ if let Some(old) = old {+ ensure!(old.metadata == metadata, "Attachment ID conflict");+ Ok(old)+ } else {+ Ok(Blob {+ metadata,+ bytes: vec![],+ sealed: false,+ })+ }+ }+ other => {+ let mut blob = old.context("Attachment not found in this session")?;+ match other {+ Upload::Chunk { offset, data } => {+ ensure!(+ data.len() <= CHUNK.div_ceil(3) * 4,+ "Attachment chunk too large"+ );+ let bytes = STANDARD+ .decode(&data)+ .context("Invalid attachment base64")?;+ ensure!(+ !bytes.is_empty() && bytes.len() <= CHUNK,+ "Invalid attachment chunk"+ );+ ensure!(+ offset <= blob.bytes.len()+ && offset.saturating_add(bytes.len()) <= blob.metadata.size,+ "Attachment offset or size conflict"+ );+ if offset < blob.bytes.len() {+ ensure!(+ blob.bytes.get(offset..offset + bytes.len()) == Some(bytes.as_slice()),+ "Attachment chunk conflict"+ );+ } else {+ ensure!(!blob.sealed, "Attachment is immutable");+ blob.bytes.extend(bytes);+ }+ }+ Upload::Commit => {+ ensure!(+ blob.bytes.len() == blob.metadata.size+ && crate::bundle::digest(&blob.bytes) == blob.metadata.sha256,+ "Attachment checksum or size mismatch"+ );+ validate_bytes(&blob.metadata.media_type, &blob.bytes)?;+ blob.sealed = true;+ }+ Upload::Stat => {}+ Upload::Begin { .. } => unreachable!(),+ };+ Ok(blob)+ }+ }+}+pub fn validate_bytes(mime: &str, b: &[u8]) -> Result<()> {+ let valid = match mime {+ "image/png" => {+ png_static(b)?;+ true+ }+ "image/jpeg" => b.starts_with(&[255, 216, 255]),+ "image/webp" => {+ b.len() >= 12+ && &b[..4] == b"RIFF"+ && &b[8..12] == b"WEBP"+ && !(b.len() > 20 && &b[12..16] == b"VP8X" && b[20] & 2 != 0)+ }+ "image/gif" => {+ gif_static(b)?;+ true+ }+ "application/pdf" => b.starts_with(b"%PDF-"),+ "text/plain" => std::str::from_utf8(b).is_ok() && !b.contains(&0),+ _ => false,+ };+ ensure!(+ valid,+ "Attachment content does not match its media type or encoding"+ );+ Ok(())+}+fn gif_static(b: &[u8]) -> Result<()> {+ ensure!(+ b.len() >= 13 && (b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a")),+ "Invalid GIF"+ );+ let mut i = 13;+ if b[10] & 128 != 0 {+ i += 3 * (1usize << ((b[10] & 7) + 1));+ }+ let mut frames = 0;+ while i < b.len() {+ let tag = b[i];+ i += 1;+ match tag {+ 0x3b => break,+ 0x21 => {+ i += 1;+ skip_blocks(b, &mut i)?;+ }+ 0x2c => {+ frames += 1;+ ensure!(frames == 1, "Animated images are unsupported");+ ensure!(i + 9 <= b.len(), "Invalid GIF");+ let packed = b[i + 8];+ i += 9;+ if packed & 128 != 0 {+ i += 3 * (1usize << ((packed & 7) + 1));+ }+ i += 1;+ skip_blocks(b, &mut i)?;+ }+ _ => anyhow::bail!("Invalid GIF"),+ }+ }+ ensure!(frames == 1, "Invalid GIF");+ Ok(())+}+fn skip_blocks(b: &[u8], i: &mut usize) -> Result<()> {+ loop {+ let n = *b.get(*i).context("Invalid GIF")? as usize;+ *i += 1;+ if n == 0 {+ return Ok(());+ }+ *i += n;+ ensure!(*i <= b.len(), "Invalid GIF");+ }+}+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]+pub enum Part {+ Text { text: String },+ Image { attachment_id: String },+ Document { attachment_id: String },+}+pub fn validate_parts(parts: &[Part]) -> Result<()> {+ ensure!(+ cfg!(feature = "attachments"),+ "Attachments are not included in this build"+ );+ ensure!(+ !parts.is_empty() && parts.len() <= 32,+ "Input content must have 1..32 blocks"+ );+ let mut n = 0;+ for p in parts {+ match p {+ Part::Text { text } => {+ n += text.len();+ ensure!(!text.contains('\0'), "Invalid input text");+ }+ Part::Image { attachment_id } | Part::Document { attachment_id } => {+ component(attachment_id)?+ }+ }+ }+ ensure!(n <= 32000, "Input text exceeds 32,000 bytes");+ Ok(())+}+pub fn history(parts: &[Part]) -> Value {+ json!(parts+ .iter()+ .map(|p| match p {+ Part::Text { text } => json!({"type":"input_text","text":text}),+ Part::Image { attachment_id } =>+ json!({"type":"input_attachment","kind":"image","id":attachment_id}),+ Part::Document { attachment_id } =>+ json!({"type":"input_attachment","kind":"document","id":attachment_id}),+ })+ .collect::<Vec<_>>())+}++fn component(s: &str) -> Result<()> {+ ensure!(+ !s.is_empty()+ && s.len() <= 100+ && s.bytes()+ .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-'),+ "Invalid attachment ID"+ );+ Ok(())+}++/// Resolve immutable references only at the provider boundary, never into events.+pub fn hydrate(+ store: &mut dyn crate::store::StateStore,+ sid: &str,+ history: &[Value],+) -> Result<Vec<Value>> {+ if !cfg!(feature = "attachments") {+ ensure!(+ !history.iter().any(|item| item["content"]+ .as_array()+ .is_some_and(|blocks| blocks.iter().any(|b| b["type"] == "input_attachment"))),+ "Attachments are not included in this build"+ );+ return Ok(history.to_vec());+ }+ let mut out = history.to_vec();+ for item in &mut out {+ if item["role"] != "user" {+ continue;+ }+ let Some(blocks) = item["content"].as_array_mut() else {+ continue;+ };+ for block in blocks {+ if block["type"] != "input_attachment" {+ continue;+ }+ let id = block["id"].as_str().context("Missing attachment ID")?;+ let blob = store.input_attachment(sid, id, Upload::Stat)?;+ ensure!(blob.sealed, "Attachment not committed");+ let m = &blob.metadata;+ m.validate()?;+ ensure!(+ m.id == id+ && blob.bytes.len() == m.size+ && crate::bundle::digest(&blob.bytes) == m.sha256,+ "Stored attachment integrity check failed"+ );+ *block = if block["kind"] == "image" {+ ensure!(+ m.media_type.starts_with("image/"),+ "Attachment type mismatch"+ );+ json!({"type":"input_image","image_url":format!("data:{};base64,{}",m.media_type,STANDARD.encode(&blob.bytes))})+ } else if m.media_type == "text/plain" {+ json!({"type":"input_text","text":format!("Attached text file: {}\n{}",m.name,std::str::from_utf8(&blob.bytes)? )})+ } else {+ ensure!(+ m.media_type == "application/pdf",+ "Attachment type mismatch"+ );+ json!({"type":"input_file","filename":m.name,"file_data":format!("data:application/pdf;base64,{}",STANDARD.encode(&blob.bytes))})+ };+ }+ }+ Ok(out)+}+impl crate::runtime::Runtime {+ /// Inspect text blocks independently without changing their relative positions.+ /// Binary scanning is never implied by a successful text guardrail.+ pub async fn prepare_input_content(+ &self,+ sid: &str,+ parts: &[Part],+ safety: Option<&crate::safety::Config>,+ ) -> Result<Vec<Part>> {+ validate_parts(parts)?;+ let session = self.store.lock().unwrap().metadata(sid)?;+ let policy = self+ .safety_defaults+ .merge(&session.safety)?+ .merge(&safety.cloned().unwrap_or_default())?;+ let mut checked = vec![];+ let mut total = 0usize;+ for part in parts {+ checked.push(match part {+ Part::Text { text } => Part::Text {+ text: self.check_user_input_with(sid, text, safety).await?,+ },+ Part::Image { attachment_id } | Part::Document { attachment_id } => {+ let blob = self.store.lock().unwrap().input_attachment(+ sid,+ attachment_id,+ Upload::Stat,+ )?;+ ensure!(blob.sealed, "Attachment upload is incomplete");+ total = total.saturating_add(blob.metadata.size);+ ensure!(total <= MAX_TURN, "Turn attachment byte limit exceeded");+ let image = matches!(part, Part::Image { .. });+ ensure!(+ if image {+ blob.metadata.media_type.starts_with("image/")+ } else {+ ["application/pdf", "text/plain"]+ .contains(&blob.metadata.media_type.as_str())+ },+ "Attachment type mismatch"+ );+ let id = if blob.metadata.media_type == "text/plain" {+ let text = std::str::from_utf8(&blob.bytes)?;+ let replacement = self.check_user_input_with(sid, text, safety).await?;+ if replacement.as_bytes() != blob.bytes {+ let bytes = replacement.into_bytes();+ let hash = crate::bundle::digest(&bytes);+ let identity = crate::bundle::digest(&serde_json::to_vec(&json!([+ blob.metadata.name,+ blob.metadata.media_type,+ hash+ ]))?);+ let m = Metadata {+ id: format!("att_{}", identity),+ sha256: hash,+ size: bytes.len(),+ ..blob.metadata.clone()+ };+ let mut store = self.store.lock().unwrap();+ store.input_attachment(+ sid,+ &m.id,+ Upload::Begin {+ metadata: m.clone(),+ },+ )?;+ for (i, b) in bytes.chunks(CHUNK).enumerate() {+ store.input_attachment(+ sid,+ &m.id,+ Upload::Chunk {+ offset: i * CHUNK,+ data: STANDARD.encode(b),+ },+ )?;+ }+ store.input_attachment(sid, &m.id, Upload::Commit)?;+ m.id+ } else {+ attachment_id.clone()+ }+ } else {+ if policy.protects(crate::safety::Phase::UserInput, None)+ || policy.protects(crate::safety::Phase::ModelInput, None)+ {+ return Err(InspectionUnsupported.into());+ }+ attachment_id.clone()+ };+ if image {+ Part::Image { attachment_id: id }+ } else {+ Part::Document { attachment_id: id }+ }+ }+ });+ }+ Ok(checked)+ }+}++/// Admission validates ownership and committed state before appending history.+pub fn validate_references(+ parts: &[Part],+ mut lookup: impl FnMut(&str) -> Result<Metadata>,+) -> Result<()> {+ validate_parts(parts)?;+ let mut size = 0usize;+ for p in parts {+ let (id, image) = match p {+ Part::Text { .. } => continue,+ Part::Image { attachment_id } => (attachment_id, true),+ Part::Document { attachment_id } => (attachment_id, false),+ };+ let m = lookup(id)?;+ ensure!(+ if image {+ m.media_type.starts_with("image/")+ } else {+ ["application/pdf", "text/plain"].contains(&m.media_type.as_str())+ },+ "Attachment type mismatch"+ );+ size = size.saturating_add(m.size);+ ensure!(size <= MAX_TURN, "Turn attachment byte limit exceeded");+ }+ Ok(())+}++/// Short text projection for durable run status. Content order lives in history.+pub fn summary(parts: &[Part]) -> String {+ let mut text = parts+ .iter()+ .filter_map(|p| {+ if let Part::Text { text } = p {+ Some(text.as_str())+ } else {+ None+ }+ })+ .collect::<Vec<_>>()+ .join("\n");+ if text.len() > 32000 {+ let mut end = 32000;+ while !text.is_char_boundary(end) {+ end -= 1;+ }+ text.truncate(end);+ }+ if text.trim().is_empty() {+ "Attached content".into()+ } else {+ text+ }+}++#[derive(Debug)]+pub struct InspectionUnsupported;+impl std::fmt::Display for InspectionUnsupported {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(+ "Binary attachments cannot be inspected by configured text-only input guardrails",+ )+ }+}+impl std::error::Error for InspectionUnsupported {}++fn png_static(bytes: &[u8]) -> Result<()> {+ ensure!(bytes.starts_with(b"\x89PNG\r\n\x1a\n"), "Invalid PNG");+ let mut offset = 8;+ while offset + 12 <= bytes.len() {+ let length = u32::from_be_bytes(bytes[offset..offset + 4].try_into()?) as usize;+ let end = offset+ .checked_add(12)+ .and_then(|n| n.checked_add(length))+ .context("Invalid PNG")?;+ ensure!(end <= bytes.len(), "Invalid PNG");+ let kind = &bytes[offset + 4..offset + 8];+ ensure!(kind != b"acTL", "Animated images are unsupported");+ if kind == b"IEND" {+ return Ok(());+ }+ offset = end;+ }+ anyhow::bail!("Invalid PNG")+}diff --git a/harness/runtime/src/chat_completions.rs b/harness/runtime/src/chat_completions.rsindex f73823af..00fc155f 100644--- a/harness/runtime/src/chat_completions.rs+++ b/harness/runtime/src/chat_completions.rs@@ -67,6 +67,7 @@ fn content(value: &Value) -> Result<Value, Error> {let blocks = value.as_array().ok_or_else(config)?.iter().map(|p| {match p["type"].as_str() {Some("text" | "input_text" | "output_text") => Ok(json!({"type":"text","text":p["text"].as_str().ok_or_else(config)?})),+ Some("input_file") => Ok(json!({"type":"file","file":{"filename":p["filename"],"file_data":p["file_data"]}})),Some("input_image") => Ok(json!({"type":"image_url","image_url":{"url":p["image_url"].as_str().ok_or_else(config)?}})),_ => Err(config()),}diff --git a/harness/runtime/src/compaction.rs b/harness/runtime/src/compaction.rsindex 05e32f23..a2c5d89b 100644--- a/harness/runtime/src/compaction.rs+++ b/harness/runtime/src/compaction.rs@@ -284,7 +284,30 @@ pub fn candidate(let mut lines = vec![];for msg in span {let role = msg["role"].as_str().unwrap_or("");- let text = msg["content"].as_str().unwrap_or("");+ let text = msg["content"]+ .as_str()+ .map(str::to_owned)+ .unwrap_or_else(|| {+ msg["content"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|block| {+ if let Some(text) = block["text"].as_str() {+ Some(text.to_owned())+ } else if block["type"] == "input_attachment" {+ Some(format!(+ "[attached {}: {}; original retained in session]",+ block["kind"].as_str().unwrap_or("file"),+ block["id"].as_str().unwrap_or("")+ ))+ } else {+ None+ }+ })+ .collect::<Vec<_>>()+ .join("\n")+ });if role == "user" && msg["_runtime_notice"].is_null() {let text = text.split_whitespace().collect::<Vec<_>>().join(" ");if !text.is_empty() {@@ -318,9 +341,9 @@ pub fn candidate(lines.push(format!("[{role}] {}",if role == "tool" {- clip(text, 100)+ clip(&text, 100)} else {- text.into()+ text}));}diff --git a/harness/runtime/src/lib.rs b/harness/runtime/src/lib.rsindex d8894a41..14c960bf 100644--- a/harness/runtime/src/lib.rs+++ b/harness/runtime/src/lib.rs@@ -73,3 +73,5 @@ pub mod compliance_export;pub mod subagents;pub mod observation_links;++pub mod attachments;diff --git a/harness/runtime/src/model.rs b/harness/runtime/src/model.rsindex 966e8bd9..e02d0322 100644--- a/harness/runtime/src/model.rs+++ b/harness/runtime/src/model.rs@@ -998,7 +998,19 @@ pub fn public_items(items: &[Value]) -> Vec<Value> {items.iter().filter(|item| item["type"] != "reasoning")- .cloned()+ .map(|item| {+ let mut item = item.clone();+ if let Some(blocks) = item["content"].as_array_mut() {+ for block in blocks {+ if block["type"] == "input_image" {+ *block = json!({"type":"input_image","content_withheld":true});+ } else if block["type"] == "input_file" {+ *block = json!({"type":"input_file","filename":block["filename"],"content_withheld":true});+ }+ }+ }+ item+ }).collect()}diff --git a/harness/runtime/src/protocol.rs b/harness/runtime/src/protocol.rsindex 1d6b3e2a..dc5e12b9 100644--- a/harness/runtime/src/protocol.rs+++ b/harness/runtime/src/protocol.rs@@ -132,7 +132,7 @@ pub async fn serve_endpoint(rt: impl Endpoint + 'static) -> Result<()> {if method=="session/attach"{subscribed.insert(p["session_id"].as_str().unwrap().to_owned());}Ok::<_,anyhow::Error>(result)}.await;- match result{Ok(result)=>json!({"jsonrpc":"2.0","id":id,"result":result}),Err(e)=>json!({"jsonrpc":"2.0","id":id,"error":{"code":-32000,"message":e.to_string(),"provider_error":e.downcast_ref::<crate::provider::Error>().map(|e|e.diagnostic())}})}+ match result{Ok(result)=>json!({"jsonrpc":"2.0","id":id,"result":result}),Err(e)=>json!({"jsonrpc":"2.0","id":id,"error":{"code":-32000,"message":e.to_string(),"attachment_inspection_unsupported":e.is::<crate::attachments::InspectionUnsupported>(),"provider_error":e.downcast_ref::<crate::provider::Error>().map(|e|e.diagnostic())}})}}}},diff --git a/harness/runtime/src/runtime.rs b/harness/runtime/src/runtime.rsindex 4f93b727..a8d8e255 100644--- a/harness/runtime/src/runtime.rs+++ b/harness/runtime/src/runtime.rs@@ -64,7 +64,7 @@ pub struct Runtime {observers_started: AtomicBool,observers_stop: CancellationToken,compliance_defaults: Option<crate::compliance::Config>,- safety_defaults: crate::safety::Config,+ pub(crate) safety_defaults: crate::safety::Config,pub safety_handlers: Arc<crate::safety::Registry>,pub telemetry: Telemetry,pub store: crate::store::SharedStore,@@ -665,8 +665,24 @@ impl Runtime {} else if summary {instructions.push_str("\nThe configured turn budget is exhausted. No tools may execute. Return a short plain-language response (at most 120 words) telling the user the configured limit was reached, what was actually completed, and what is incomplete. Do not claim failed/unknown tools succeeded. Do not request tools or continue the task.");}+ // Text documents participate in model-input checks. Binary blocks+ // are withheld from text checks and exports; admission rejects them+ // when an input policy requires inspection we cannot perform.+ let attachment_history =+ crate::attachments::hydrate(self.store.lock().unwrap().as_mut(), sid, history)?;+ if safety.protects(crate::safety::Phase::ModelInput, None)+ && attachment_history.iter().any(|item| {+ item["content"].as_array().is_some_and(|blocks| {+ blocks+ .iter()+ .any(|b| b["type"] == "input_image" || b["type"] == "input_file")+ })+ })+ {+ return Err(crate::attachments::InspectionUnsupported.into());+ }let request_text = serde_json::to_string(- &json!({"instructions":instructions,"history":crate::model::public_items(history)}),+ &json!({"instructions":instructions,"history":crate::model::public_items(&attachment_history)}),)?;let (_, blocked) = self.check_content(@@ -771,7 +787,7 @@ impl Runtime {}) {images.clear(sid);}- images.hydrate(sid, history)+ images.hydrate(sid, &attachment_history)};tokio::time::timeout(std::time::Duration::from_secs(240).saturating_sub(started.elapsed()),@@ -1550,6 +1566,10 @@ impl Runtime {json!(self.store.lock().unwrap().supports_teams());info["capabilities"]["session_tool_grants"] = json!(true);info["capabilities"]["native_tool_controls"] = json!(true);+ info["capabilities"]["attachments"] = json!(+ cfg!(feature = "attachments")+ && self.store.lock().unwrap().supports_input_attachments()+ );info["capabilities"]["ephemeral_native_images"] = json!(true);info["capabilities"]["model_connections"] = json!(true);info["capabilities"]["model_providers"] = json!(["openai", "anthropic"]);@@ -1600,6 +1620,16 @@ impl Runtime {_ => {}}let sid = text(&p, "session_id", 80)?.to_owned();+ if method == "attachment/upload" {+ let id = text(&p, "id", 100)?;+ let request: crate::attachments::Upload = serde_json::from_value(p["upload"].clone())?;+ let blob = self+ .store+ .lock()+ .unwrap()+ .input_attachment(&sid, id, request)?;+ return Ok(blob.reply());+ }match method {"session/attach" => self.snapshot(&sid),"compliance/delivery-health" => {@@ -1693,7 +1723,7 @@ impl Runtime {Ok(json!({"resumed":true}))}"turn/start" => {- let context = crate::turn_options::Context::from_request(&p)?;+ let mut context = crate::turn_options::Context::from_request(&p)?;self.check_backend(&sid)?;if self.store@@ -1739,9 +1769,17 @@ impl Runtime {.filter(|v| !v.is_null()).map(|v| serde_json::from_value::<crate::safety::Config>(v.clone())).transpose()?;- let checked_input = self- .check_user_input_with(&sid, text(&p, "text", 32000)?, safety.as_ref())- .await?;+ let checked_input = if let Some(parts) = &context.content {+ let parts = self+ .prepare_input_content(&sid, parts, safety.as_ref())+ .await?;+ let text = crate::attachments::summary(&parts);+ context.content = Some(parts);+ text+ } else {+ self.check_user_input_with(&sid, text(&p, "text", 32000)?, safety.as_ref())+ .await?+ };let (s, fresh, e) = self.store.lock().unwrap().accept_with_context(&sid,text(&p, "submission_id", 100)?,@@ -1907,7 +1945,7 @@ impl Runtime {let provider_error = e.downcast_ref::<crate::provider::Error>().map(|e| e.diagnostic());let status = if e.is::<safety::Unavailable>() {"waiting_safety"- } else if e.is::<safety::Blocked>() {+ } else if e.is::<safety::Blocked>() || e.is::<crate::attachments::InspectionUnsupported>() {"blocked"} else if e.downcast_ref::<crate::provider::Error>()diff --git a/harness/runtime/src/scoped_store.rs b/harness/runtime/src/scoped_store.rsindex 89819174..24d8b78a 100644--- a/harness/runtime/src/scoped_store.rs+++ b/harness/runtime/src/scoped_store.rs@@ -6,6 +6,23 @@ pub struct ScopedStore {pub coworker: String,}impl StateStore for ScopedStore {+ fn supports_input_attachments(&self) -> bool {+ self.inner.lock().unwrap().supports_input_attachments()+ }++ fn input_attachment(+ &mut self,+ sid: &str,+ id: &str,+ request: crate::attachments::Upload,+ ) -> Result<crate::attachments::Blob> {+ self.metadata(sid)?;+ self.inner+ .lock()+ .unwrap()+ .input_attachment(sid, id, request)+ }+fn claim_compliance_export(&mut self,sid: &str,diff --git a/harness/runtime/src/store.rs b/harness/runtime/src/store.rsindex 42a29e72..d3ad20b2 100644--- a/harness/runtime/src/store.rs+++ b/harness/runtime/src/store.rs@@ -213,6 +213,19 @@ pub struct Event {/// the runtime safe for shared workers. `recover` may only touch sessions owned/// exclusively by this store instance. No automatic replay of tool effects.pub trait StateStore: Send {+ fn supports_input_attachments(&self) -> bool {+ false+ }++ fn input_attachment(+ &mut self,+ _sid: &str,+ _id: &str,+ _request: crate::attachments::Upload,+ ) -> Result<crate::attachments::Blob> {+ bail!("Input attachments unsupported by this store")+ }+fn has_turn(&self, sid: &str, tid: &str) -> Result<bool> {Ok(self.metadata(sid)?.turn.is_some_and(|t| t.id == tid))}@@ -475,7 +488,7 @@ impl Store {[],|r| r.get(0),)?;- if !(matches!(version, 7 | 8) || version == 0 && tables == 0) {+ if !(matches!(version, 7..=9) || version == 0 && tables == 0) {bail!("Incompatible runtime state schema {version}; use a fresh state directory. M1 migration is intentionally unsupported; existing data was not reset.");}}@@ -504,8 +517,11 @@ impl Store {CREATE TABLE IF NOT EXISTS submissions(session_id TEXT, submission_id TEXT, text TEXT, turn_id TEXT, PRIMARY KEY(session_id,submission_id));CREATE TABLE IF NOT EXISTS events(id INTEGER PRIMARY KEY AUTOINCREMENT,session_id TEXT NOT NULL, turn_id TEXT,kind TEXT NOT NULL,data TEXT NOT NULL);CREATE INDEX IF NOT EXISTS session_events ON events(session_id,id);- PRAGMA user_version=8;+ PRAGMA user_version=9;COMMIT;")?;+ if cfg!(feature = "attachments") {+ db.execute_batch("CREATE TABLE IF NOT EXISTS input_attachments(session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,id TEXT NOT NULL,metadata TEXT NOT NULL,data BLOB NOT NULL,sealed INTEGER NOT NULL DEFAULT 0,created INTEGER NOT NULL,referenced INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(session_id,id))")?;+ }sqlite_teams::migrate(&db)?;sqlite_assistant::migrate(&db)?;sqlite_agent_team::migrate(&db)?;@@ -837,6 +853,13 @@ impl Store {context: crate::turn_options::Context,) -> Result<(Session, bool, Option<Event>)> {context.validate()?;+ if let Some(parts) = &context.content {+ crate::attachments::validate_references(parts, |id| {+ let blob = self.input_blob(sid, id, crate::attachments::Upload::Stat)?;+ anyhow::ensure!(blob.sealed, "Attachment upload is incomplete");+ Ok(blob.metadata)+ })?;+ }let context_digest = context.digest()?;if let Some(config) = &safety {config.validate()?;@@ -911,7 +934,7 @@ impl Store {s.history.push(json!({"type":"function_call_output","call_id":c["call_id"],"output":"Previous turn interrupted; action outcome unknown, do not assume success."}));}}- let mut input = json!({"role":"user","content":text});+ let mut input = json!({"role":"user","content":context.content.as_ref().map(|p|crate::attachments::history(p)).unwrap_or_else(||json!(text))});if crate::assistant_tools::admit(&mut s, key, text, crate::assistant_tools::now())? {input["_runtime_notice"] = json!("scheduled_task");}@@ -953,6 +976,18 @@ impl Store {});let tx = self.db.transaction()?;sqlite_agent_team::ensure_admission(&tx, &s)?;+ if let Some(parts) = &context.content {+ for part in parts {+ if let crate::attachments::Part::Image { attachment_id }+ | crate::attachments::Part::Document { attachment_id } = part+ {+ tx.execute(+ "UPDATE input_attachments SET referenced=1 WHERE session_id=? AND id=?",+ params![sid, attachment_id],+ )?;+ }+ }+ }Self::append_history(&tx, &s)?;tx.execute("UPDATE team_queue SET status='accepted' WHERE session_id=? AND id=? AND status='queued'", params![sid,key])?;tx.execute(@@ -1079,6 +1114,19 @@ impl Store {}impl StateStore for Store {+ fn supports_input_attachments(&self) -> bool {+ cfg!(feature = "attachments")+ }++ fn input_attachment(+ &mut self,+ sid: &str,+ id: &str,+ request: crate::attachments::Upload,+ ) -> Result<crate::attachments::Blob> {+ self.input_blob(sid, id, request)+ }+fn has_turn(&self, sid: &str, tid: &str) -> Result<bool> {self.metadata(sid)?;Ok(self.db.query_row(@@ -1306,3 +1354,78 @@ impl StateStore for Store {Store::recover(self)}}++impl Store {+ fn input_blob(+ &mut self,+ sid: &str,+ id: &str,+ request: crate::attachments::Upload,+ ) -> Result<crate::attachments::Blob> {+ use crate::attachments::*;+ anyhow::ensure!(cfg!(feature = "attachments"), "Attachments disabled");+ let session = self.metadata(sid)?;+ let stat = matches!(&request, Upload::Stat);+ let writable = !stat && !session.closed;+ let tx = self+ .db+ .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;+ if writable {+ tx.execute(+ "DELETE FROM input_attachments WHERE session_id=? AND referenced=0 AND created<?",+ params![sid, now_ms().saturating_sub(86400000)],+ )?;+ }+ let old = tx+ .query_row(+ "SELECT metadata,data,sealed FROM input_attachments WHERE session_id=? AND id=?",+ params![sid, id],+ |r| {+ Ok((+ r.get::<_, String>(0)?,+ r.get::<_, Vec<u8>>(1)?,+ r.get::<_, bool>(2)?,+ ))+ },+ )+ .optional()?+ .map(|(m, bytes, sealed)| -> Result<_> {+ Ok(Blob {+ metadata: serde_json::from_str(&m)?,+ bytes,+ sealed,+ })+ })+ .transpose()?;+ if session.closed && !stat {+ anyhow::ensure!(+ matches!(&request, Upload::Begin { .. }) && old.as_ref().is_some_and(|b| b.sealed),+ "Session closed"+ );+ }+ if old.is_none() {+ if let Upload::Begin { metadata } = &request {+ let count: usize = tx.query_row(+ "SELECT count(*) FROM input_attachments WHERE session_id=?",+ [sid],+ |r| r.get(0),+ )?;+ anyhow::ensure!(+ count < MAX_SESSION_FILES,+ "Session attachment count limit exceeded"+ );+ let total:usize=tx.query_row("SELECT COALESCE(SUM(json_extract(metadata,'$.size')),0) FROM input_attachments WHERE session_id=?",[sid],|r|r.get(0))?;+ anyhow::ensure!(+ total.saturating_add(metadata.size) <= MAX_SESSION,+ "Session attachment quota exceeded"+ );+ }+ }+ let blob = apply(id, old, request)?;+ if writable {+ tx.execute("INSERT INTO input_attachments(session_id,id,metadata,data,sealed,created) VALUES(?,?,?,?,?,?) ON CONFLICT(session_id,id) DO UPDATE SET data=excluded.data,sealed=excluded.sealed",params![sid,id,serde_json::to_string(&blob.metadata)?,blob.bytes,blob.sealed,now_ms()])?;+ }+ tx.commit()?;+ Ok(blob)+ }+}diff --git a/harness/runtime/src/turn_options.rs b/harness/runtime/src/turn_options.rsindex 9f8b3fef..be7cfdd4 100644--- a/harness/runtime/src/turn_options.rs+++ b/harness/runtime/src/turn_options.rs@@ -13,6 +13,8 @@ pub struct OutputOptions {#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(default, deny_unknown_fields)]pub struct Context {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub content: Option<Vec<crate::attachments::Part>>,pub instruction_addendum: Option<String>,pub output: OutputOptions,}@@ -22,6 +24,9 @@ impl Context {Ok(crate::bundle::digest(&serde_json::to_vec(self)?))}pub fn validate(&self) -> Result<()> {+ if let Some(parts) = &self.content {+ crate::attachments::validate_parts(parts)?;+ }if let Some(text) = &self.instruction_addendum {ensure!(text.len() <= 32000,@@ -36,6 +41,11 @@ impl Context {}pub fn from_request(p: &serde_json::Value) -> Result<Self> {let value = Self {+ content: p+ .get("content")+ .filter(|v| !v.is_null())+ .map(|v| serde_json::from_value(v.clone()))+ .transpose()?,instruction_addendum: p.get("instruction_addendum").filter(|v| !v.is_null())diff --git a/harness/runtime/tests/attachment_features.rs b/harness/runtime/tests/attachment_features.rsnew file mode 100644index 00000000..c5406484--- /dev/null+++ b/harness/runtime/tests/attachment_features.rs@@ -0,0 +1,33 @@+use openworker_runtime::{+ attachments::*,+ store::{StateStore, Store},+ turn_options::Context,+};+#[test]+fn attachment_capability_tracks_the_build_feature() {+ let mut store = Store::memory().unwrap();+ assert_eq!(+ store.supports_input_attachments(),+ cfg!(feature = "attachments")+ );+ let metadata = Metadata {+ id: "a".into(),+ name: "a.txt".into(),+ media_type: "text/plain".into(),+ size: 1,+ sha256: openworker_runtime::bundle::digest(b"a"),+ };+ assert_eq!(metadata.validate().is_ok(), cfg!(feature = "attachments"));+ let context = Context {+ content: Some(vec![Part::Text {+ text: "hello".into(),+ }]),+ ..Default::default()+ };+ assert_eq!(context.validate().is_ok(), cfg!(feature = "attachments"));+ if !cfg!(feature = "attachments") {+ assert!(store+ .input_attachment("missing", "a", Upload::Begin { metadata })+ .is_err());+ }+}diff --git a/harness/runtime/tests/attachments.rs b/harness/runtime/tests/attachments.rsnew file mode 100644index 00000000..0652c7fc--- /dev/null+++ b/harness/runtime/tests/attachments.rs@@ -0,0 +1,354 @@+#![cfg(feature = "attachments")]+use base64::{engine::general_purpose::STANDARD, Engine};+use openworker_runtime::{+ attachments::*,+ store::{Session, StateStore, Store},+ turn_options::Context,+};+use serde_json::json;+fn session(id: &str) -> Session {+ serde_json::from_value(json!({"id":id,"name":"Reader","workspace":"/work","coworker":"reader","bundle_digest":"bundle","schema_digest":null,"interactions":[],"turn":null,"sandbox":null,"closed":false,"resource_policy":openworker_runtime::resource_policy::Resolved::default()})).unwrap()+}+fn meta(id: &str, data: &[u8]) -> Metadata {+ Metadata {+ id: id.into(),+ name: "notes.txt".into(),+ media_type: "text/plain".into(),+ size: data.len(),+ sha256: openworker_runtime::bundle::digest(data),+ }+}+fn upload(store: &mut dyn StateStore, sid: &str, id: &str, data: &[u8]) {+ store+ .input_attachment(+ sid,+ id,+ Upload::Begin {+ metadata: meta(id, data),+ },+ )+ .unwrap();+ for (i, b) in data.chunks(CHUNK).enumerate() {+ let r = Upload::Chunk {+ offset: i * CHUNK,+ data: STANDARD.encode(b),+ };+ store.input_attachment(sid, id, r.clone()).unwrap();+ store.input_attachment(sid, id, r).unwrap();+ }+ store.input_attachment(sid, id, Upload::Commit).unwrap();+}+#[test]+fn sqlite_references_are_owned_immutable_recoverable_and_atomic() {+ let root = tempfile::tempdir().unwrap();+ let mut s = Store::open(root.path()).unwrap();+ for id in ["owner", "other"] {+ s.save(&session(id), "session_created", json!({})).unwrap();+ }+ let bytes = vec![65; CHUNK + 32];+ upload(&mut s, "owner", "att_text", &bytes);+ assert!(s+ .input_attachment("other", "att_text", Upload::Stat)+ .is_err());+ assert!(s+ .input_attachment(+ "owner",+ "att_text",+ Upload::Chunk {+ offset: 0,+ data: STANDARD.encode(b"changed")+ }+ )+ .is_err());+ assert!(s+ .input_attachment(+ "owner",+ "att_text",+ Upload::Begin {+ metadata: meta("att_text", b"changed")+ }+ )+ .is_err());+ let parts = vec![+ Part::Text {+ text: "Before".into(),+ },+ Part::Document {+ attachment_id: "att_text".into(),+ },+ Part::Text {+ text: "After".into(),+ },+ ];+ let context = Context {+ content: Some(parts.clone()),+ ..Default::default()+ };+ let c = s.cursor("other").unwrap();+ assert!(s+ .accept_with_context("other", "s", "Read", None, None, context.clone())+ .is_err());+ assert_eq!(s.cursor("other").unwrap(), c);+ let (mut original, fresh, _) = s+ .accept_with_context("owner", "s", "Read", None, None, context.clone())+ .unwrap();+ assert!(fresh);+ let (_, fresh, _) = s+ .accept_with_context("owner", "s", "Read", None, None, context)+ .unwrap();+ assert!(!fresh);+ assert!(s+ .accept_with_context(+ "owner",+ "s",+ "Read",+ None,+ None,+ Context {+ content: Some(vec![parts[1].clone()]),+ ..Default::default()+ }+ )+ .is_err());+ assert_eq!(original.history[0]["content"], history(&parts));+ assert!(!serde_json::to_string(&s.get("owner").unwrap())+ .unwrap()+ .contains(&STANDARD.encode(&bytes)));+ // Compaction context may drop old inputs; the append-only original remains available.+ original+ .history+ .push(json!({"role":"assistant","content":"done"}));+ original.turn.as_mut().unwrap().status = "completed".into();+ s.save(&original, "turn_completed", json!({"status":"completed"}))+ .unwrap();+ drop(s);+ let mut s = Store::open(root.path()).unwrap();+ upload(&mut s, "owner", "orphan", b"orphan");+ let sql = rusqlite::Connection::open(root.path().join("runtime.sqlite3")).unwrap();+ sql.execute("UPDATE input_attachments SET created=0", [])+ .unwrap();+ drop(sql);+ upload(&mut s, "owner", "fresh", b"new upload triggers expiry");+ assert!(s.input_attachment("owner", "orphan", Upload::Stat).is_err());+ assert!(+ s.input_attachment("owner", "att_text", Upload::Stat)+ .unwrap()+ .sealed+ );+ let restored = s.get("owner").unwrap();+ let hydrated = hydrate(&mut s, "owner", &restored.history).unwrap();+ assert_eq!(hydrated[0]["content"][0]["text"], "Before");+ assert!(hydrated[0]["content"][1]["text"]+ .as_str()+ .unwrap()+ .ends_with(&String::from_utf8(bytes.clone()).unwrap()));+ assert_eq!(hydrated[0]["content"][2]["text"], "After");+ assert!(!s+ .events("owner", 0)+ .unwrap()+ .iter()+ .any(|e| e.data.to_string().contains(&STANDARD.encode(&bytes))));+}+#[test]+fn reservations_are_bounded_and_failed_commits_do_not_seal() {+ let root = tempfile::tempdir().unwrap();+ let mut s = Store::open(root.path()).unwrap();+ s.save(&session("s"), "session_created", json!({})).unwrap();+ for i in 0..8 {+ s.input_attachment(+ "s",+ &format!("a{i}"),+ Upload::Begin {+ metadata: Metadata {+ size: MAX_FILE,+ ..meta(&format!("a{i}"), b"x")+ },+ },+ )+ .unwrap();+ }+ assert!(s+ .input_attachment(+ "s",+ "overflow",+ Upload::Begin {+ metadata: meta("overflow", b"x")+ }+ )+ .is_err());+ assert!(s.input_attachment("s", "a0", Upload::Commit).is_err());+ assert!(!s.input_attachment("s", "a0", Upload::Stat).unwrap().sealed);+ assert!(s+ .input_attachment(+ "s",+ "a0",+ Upload::Chunk {+ offset: 1,+ data: STANDARD.encode(b"x")+ }+ )+ .is_err());+ assert!(s+ .input_attachment(+ "s",+ "a0",+ Upload::Chunk {+ offset: 0,+ data: STANDARD.encode(vec![65; CHUNK + 1])+ }+ )+ .is_err());+ assert!(s+ .input_attachment(+ "s",+ "a0",+ Upload::Chunk {+ offset: 0,+ data: "%%%".into()+ }+ )+ .is_err());+}+#[test]+fn encoding_and_public_projection_do_not_leak_binary_inputs() {+ assert!(validate_bytes("text/plain", &[0xff]).is_err());+ assert!(validate_bytes("text/plain", b"a\0b").is_err());+ assert!(validate_bytes("application/pdf", b"not a PDF").is_err());+ assert!(meta("a", b"x").validate().is_ok());+ assert!(Metadata {+ name: "../secret".into(),+ ..meta("a", b"x")+ }+ .validate()+ .is_err());+ let private = json!({"role":"user","content":[{"type":"input_text","text":"hello"},{"type":"input_image","image_url":"data:SECRET"},{"type":"input_file","filename":"a.pdf","file_data":"data:PRIVATE"}]});+ let projected = openworker_runtime::model::public_items(&[private]);+ let text = serde_json::to_string(&projected).unwrap();+ assert!(!text.contains("SECRET"));+ assert!(!text.contains("PRIVATE"));+ assert!(text.contains("hello"));+ assert!(text.contains("content_withheld"));+}++#[test]+fn compaction_retains_interleaved_text_and_reference_context() {+ let parts = vec![+ Part::Text {+ text: "Before the image".into(),+ },+ Part::Image {+ attachment_id: "image_reference".into(),+ },+ Part::Text {+ text: "After the image".into(),+ },+ ];+ let raw = vec![+ json!({"role":"user","content":history(&parts)}),+ json!({"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}),+ json!({"role":"user","content":"next"}),+ json!({"type":"message","role":"assistant","content":[{"type":"output_text","text":"more"}]}),+ ];+ let candidate =+ openworker_runtime::compaction::candidate(&raw, None, &Default::default(), true).unwrap();+ assert!(candidate.prompt.contains("Before the image"));+ assert!(candidate.prompt.contains("image_reference"));+ assert!(candidate.prompt.contains("After the image"));+ assert_eq!(raw[0]["content"], history(&parts));+}++#[test]+fn small_uploads_are_count_bounded_and_animation_is_rejected() {+ let root = tempfile::tempdir().unwrap();+ let mut s = Store::open(root.path()).unwrap();+ s.save(&session("s"), "session_created", json!({})).unwrap();+ for i in 0..MAX_SESSION_FILES {+ let id = format!("a{i}");+ s.input_attachment(+ "s",+ &id,+ Upload::Begin {+ metadata: meta(&id, b"x"),+ },+ )+ .unwrap();+ }+ assert!(s+ .input_attachment(+ "s",+ "overflow",+ Upload::Begin {+ metadata: meta("overflow", b"x")+ }+ )+ .is_err());+ let mut apng = b"\x89PNG\r\n\x1a\n".to_vec();+ apng.extend(8u32.to_be_bytes());+ apng.extend(b"acTL");+ apng.extend([0; 12]);+ assert!(validate_bytes("image/png", &apng).is_err());+ let mut webp = b"RIFF\0\0\0\0WEBPVP8X\0\0\0\0\x02".to_vec();+ assert!(validate_bytes("image/webp", &webp).is_err());+ webp[20] = 0;+ assert!(validate_bytes("image/webp", &webp).is_ok());+}++#[test]+fn status_summary_is_bounded_without_changing_canonical_content() {+ let parts = vec![+ Part::Text {+ text: "é".repeat(8000),+ },+ Part::Text {+ text: "é".repeat(8000),+ },+ ];+ validate_parts(&parts).unwrap();+ let text = summary(&parts);+ assert!(text.len() <= 32000);+ assert!(text.contains('\n'));+ assert_eq!(history(&parts)[1]["text"].as_str().unwrap().len(), 16000);+}++#[test]+fn closed_sessions_allow_only_sealed_begin_reconciliation() {+ let mut store = Store::memory().unwrap();+ store+ .save(&session("s"), "session_created", json!({}))+ .unwrap();+ upload(&mut store, "s", "notes", b"immutable");+ let mut closed = store.get("s").unwrap();+ closed.closed = true;+ store.save(&closed, "session_closed", json!({})).unwrap();+ assert!(+ store+ .input_attachment(+ "s",+ "notes",+ Upload::Begin {+ metadata: meta("notes", b"immutable")+ }+ )+ .unwrap()+ .sealed+ );+ assert!(store+ .input_attachment(+ "s",+ "new",+ Upload::Begin {+ metadata: meta("new", b"new")+ }+ )+ .is_err());+ assert!(store+ .input_attachment(+ "s",+ "notes",+ Upload::Chunk {+ offset: 0,+ data: STANDARD.encode(b"immutable")+ }+ )+ .is_err());+}diff --git a/harness/runtime/tests/core.rs b/harness/runtime/tests/core.rsindex fcac4706..0d0f4393 100644--- a/harness/runtime/tests/core.rs+++ b/harness/runtime/tests/core.rs@@ -88,6 +88,7 @@ fn imported_history_and_turn_context_are_atomic_and_durable() {db.save(&s, "session_created", json!({})).unwrap();assert!(db.get(&s.id).unwrap().turn.is_none());let context = Context {+ content: None,instruction_addendum: Some("TURN_PRIVATE_CONTEXT".into()),output: OutputOptions {reasoning: true,@@ -142,6 +143,7 @@ fn imported_history_and_turn_context_are_atomic_and_durable() {None,None,Context {+ content: None,output: OutputOptions::default(),..context}@@ -601,6 +603,6 @@ fn safety_schema_upgrade_preserves_existing_sessions_and_fences_old_readers() {let version: i64 = db.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();- assert_eq!(version, 8); // The old runtime accepts only 7.+ assert_eq!(version, 9); // Older runtimes accept only 7/8.assert_eq!(store.events(&s.id, 0).unwrap().len(), 1);}diff --git a/harness/server-reference/Cargo.toml b/harness/server-reference/Cargo.tomlindex b2643ae8..65bbe643 100644--- a/harness/server-reference/Cargo.toml+++ b/harness/server-reference/Cargo.toml@@ -7,7 +7,8 @@ license.workspace = truepublish = false[features]-default = ["compliance", "guardrails"]+default = ["compliance", "guardrails", "attachments"]+attachments = ["openworker-runtime/attachments", "openworker-store-postgres/attachments"]compliance = ["openworker-runtime/compliance", "openworker-store-postgres/compliance"]security-adapters = ["guardrails", "dep:openworker-security-adapters"]compliance-export = ["compliance", "openworker-runtime/compliance-export"]diff --git a/harness/server-reference/src/http.rs b/harness/server-reference/src/http.rsindex df7a9e31..3ab1b12c 100644--- a/harness/server-reference/src/http.rs+++ b/harness/server-reference/src/http.rs@@ -272,6 +272,16 @@ impl From<anyhow::Error> for ApiError {}impl IntoResponse for ApiError {fn into_response(self) -> Response {+ if self+ .0+ .is::<openworker_runtime::attachments::InspectionUnsupported>()+ {+ return (+ StatusCode::UNPROCESSABLE_ENTITY,+ Json(json!({"error":"attachment_inspection_unsupported"})),+ )+ .into_response();+ }if let Some(error) = self.0.downcast_ref::<crate::service_safety::InputError>() {return match error {crate::service_safety::InputError::Blocked => (diff --git a/harness/server-reference/src/input_attachments.rs b/harness/server-reference/src/input_attachments.rsnew file mode 100644index 00000000..ec9145c5--- /dev/null+++ b/harness/server-reference/src/input_attachments.rs@@ -0,0 +1,34 @@+//! Authenticated bounded uploads; model inputs are independent of sandbox files.+use crate::http::{ApiError, App};+use axum::{extract::Path, Extension, Json};+use openworker_runtime::{+ attachments::{Part, Upload},+ store::StateStore,+};+use serde_json::Value;+pub(crate) async fn upload(+ Extension(app): Extension<App>,+ Path((sid, id)): Path<(String, String)>,+ Json(request): Json<Upload>,+) -> Result<Json<Value>, ApiError> {+ // The scoped store rechecks the principal and session on every chunk.+ let blob = app.store.clone().input_attachment(&sid, &id, request)?;+ Ok(Json(blob.reply()))+}+pub(crate) async fn inspect(app: &App, sid: &str, parts: &[Part]) -> Result<Vec<Part>, ApiError> {+ app.store.input_safety_policy(sid)?;+ openworker_runtime::attachments::validate_parts(parts)?;+ // Check ownership using the request-scoped store before trusted runtime+ // inspection. Never allow an ID to cross a project/principal boundary.+ for part in parts {+ if let Part::Image { attachment_id } | Part::Document { attachment_id } = part {+ app.store+ .clone()+ .input_attachment(sid, attachment_id, Upload::Stat)?;+ }+ }+ Ok(app+ .runtime+ .prepare_input_content(sid, parts, Some(&app.config.safety))+ .await?)+}diff --git a/harness/server-reference/src/lib.rs b/harness/server-reference/src/lib.rsindex a7e8adbb..5df12be9 100644--- a/harness/server-reference/src/lib.rs+++ b/harness/server-reference/src/lib.rs@@ -386,3 +386,5 @@ impl Config {Ok(())}}++mod input_attachments;diff --git a/harness/server-reference/src/service.rs b/harness/server-reference/src/service.rsindex 2bf54077..48ba1244 100644--- a/harness/server-reference/src/service.rs+++ b/harness/server-reference/src/service.rs@@ -72,7 +72,8 @@ pub(crate) fn authority(method: &str, path: &str) -> Option<Action> {("POST", ["", "v1", "sessions", _, "artifacts"])| ("POST", ["", "v1", "sessions", _, "artifacts", _, "reconcile"])| ("PUT", ["", "v1", "sessions", _, "artifacts", _, "content"]) => Some(Action::Artifact),- ("POST", ["", "v1", "sessions", _, "turns"]) => Some(Action::Submit),+ ("POST", ["", "v1", "sessions", _, "turns"])+ | ("POST", ["", "v1", "sessions", _, "attachments", _]) => Some(Action::Submit),("GET", ["", "v1", "sessions", _, "team"])| ("GET", ["", "v1", "sessions", _, "team", "messages"]) => Some(Action::Read),("POST", ["", "v1", "sessions", _, "team"])@@ -182,6 +183,10 @@ pub(crate) fn router() -> Router<App> {.route("/v1/sessions/:sid/runs/:id", get(run_result)).route("/v1/sessions/:sid", get(snapshot)).route("/v1/sessions/:sid/events", get(crate::http::events))+ .route(+ "/v1/sessions/:sid/attachments/:id",+ post(crate::input_attachments::upload).layer(DefaultBodyLimit::max(1_048_576)),+ ).route("/v1/sessions/:sid/turns", post(send)).route("/v1/sessions/:sid/turns/:id", get(result)).route("/v1/sessions/:sid/controls", post(control))@@ -212,7 +217,7 @@ fn cfg(app: &App) -> &ServiceConfig {}async fn capabilities(Extension(app): Extension<App>) -> Json<Value> {Json(- json!({"apiVersion":"1","serviceId":cfg(&app).id,"namespace":cfg(&app).namespace,"agent":cfg(&app).agent,"features":{"compliance":cfg!(feature="compliance"),"turnLimits":true,"toolArgumentRecovery":true,"environmentProcesses":cfg!(target_os="linux"),"sessions":true,"events":"sse","controls":true,"artifacts":app.artifacts.is_some(),"combinedSubmission":true,"runtimeProfiles":true,"agentDeployment":true,"credentialExpiry":true,"configuration":true,"workerPools":true,"humanLogin":"token-file","approvedReleasesOnly":!cfg(&app).legacy_compatibility,"teams":true,"standaloneSubagents":true,"singleNamespace":true},"limits":{"jsonBytes":160000,"textBytes":32000,"idempotencyKeyBytes":100,"catalogEntries":64,"pendingOperations":128,"environments":64,"environmentsPerPrincipal":16}}),+ json!({"apiVersion":"1","serviceId":cfg(&app).id,"namespace":cfg(&app).namespace,"agent":cfg(&app).agent,"features":{"attachments":cfg!(feature="attachments"),"compliance":cfg!(feature="compliance"),"turnLimits":true,"toolArgumentRecovery":true,"environmentProcesses":cfg!(target_os="linux"),"sessions":true,"events":"sse","controls":true,"artifacts":app.artifacts.is_some(),"combinedSubmission":true,"runtimeProfiles":true,"agentDeployment":true,"credentialExpiry":true,"configuration":true,"workerPools":true,"humanLogin":"token-file","approvedReleasesOnly":!cfg(&app).legacy_compatibility,"teams":true,"standaloneSubagents":true,"singleNamespace":true},"limits":{"jsonBytes":160000,"textBytes":32000,"idempotencyKeyBytes":100,"catalogEntries":64,"pendingOperations":128,"environments":64,"environmentsPerPrincipal":16}}),)}async fn agent(@@ -300,7 +305,8 @@ async fn snapshot(#[derive(Deserialize)]#[serde(deny_unknown_fields)]struct Send {- text: String,+ text: Option<String>,+ content: Option<Vec<openworker_runtime::attachments::Part>>,#[serde(default)]limits: Option<openworker_runtime::budget::Limits>,}@@ -311,13 +317,29 @@ async fn send(Json(body): Json<Send>,) -> Result<(StatusCode, Json<Value>), ApiError> {let submission_id = key(&app, &headers, &format!("turn:{sid}"))?;- let text = crate::service_safety::inspect(&app, Some(&sid), &submission_id, &body.text).await?;- let r = app.store.submit_service_turn(TurnSubmission {+ let (text, content) = match (body.text, body.content) {+ (Some(text), None) => (+ crate::service_safety::inspect(&app, Some(&sid), &submission_id, &text).await?,+ None,+ ),+ (None, Some(parts)) => {+ let parts = crate::input_attachments::inspect(&app, &sid, &parts).await?;+ let text = openworker_runtime::attachments::summary(&parts);+ (text, Some(parts))+ }+ _ => return Err(ApiError(SubmissionError::InvalidRequest.into())),+ };+ let request = TurnSubmission {session_id: sid.clone(),submission_id,text,limits: body.limits,- })?;+ };+ let r = if let Some(content) = content {+ app.store.submit_service_input(request, content)?+ } else {+ app.store.submit_service_turn(request)?+ };Ok((StatusCode::ACCEPTED,Json(diff --git a/harness/server-reference/tests/input_attachments.rs b/harness/server-reference/tests/input_attachments.rsnew file mode 100644index 00000000..cc0549b6--- /dev/null+++ b/harness/server-reference/tests/input_attachments.rs@@ -0,0 +1,304 @@+//! Real PostgreSQL + two authenticated HTTP API replicas, no cloud or model keys.+#![cfg(all(feature = "attachments", feature = "guardrails", not(windows)))]+use base64::{engine::general_purpose::STANDARD, Engine};+use openworker_runtime::{+ attachments::{Metadata, Part, Upload},+ execution::Backend,+ model::Model,+ runtime::Runtime,+ store::{Session, StateStore},+ turn_options::Context,+};+use openworker_server_reference::{http::App, Config};+use openworker_store_postgres::{+ auth::{Role, Scope, Spec},+ PostgresStore,+};+use serde_json::{json, Value};+use tokio_util::sync::CancellationToken;+const ADMIN: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";+const ALICE: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";+const BOB: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";+const READER: &str = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+#[ignore = "requires disposable OW_PG_TEST_URL"]+async fn uploads_cross_api_replicas_are_scoped_and_recoverable() {+ let root = tempfile::tempdir().unwrap();+ let id = uuid::Uuid::new_v4().simple().to_string();+ let key = format!("OW_ATTACH_DB_{}", id.to_uppercase());+ std::env::set_var(&key, std::env::var("OW_PG_TEST_URL").unwrap());+ let config:Config=serde_json::from_value(json!({"database_env":key,"schema":format!("ow_att_{}",&id[..20]),"database_loopback_plaintext":true,"state_root":root.path().join("state"),"bundle":"unused","runner":"unused","model":"fixture","scripted":true,"api_token_file":"unused","actor":"admin","openshell":{"identity":"fixture","endpoint":"https://127.0.0.1:1","certificates":"unused","workspace":"unused","image":"unused"},"service":{"id":"attachment-test","namespace":"test","agent":"test","legacy_compatibility":true}})).unwrap();+ let db = config.database().unwrap();+ PostgresStore::migrate(&db).unwrap();+ let mut store = PostgresStore::open(db.clone()).unwrap();+ store.auth_bootstrap(ADMIN, "admin").unwrap();+ let admin = store.authorized(ADMIN).unwrap();+ for sid in ["s_one", "s_two"] {+ let mut session:Session=serde_json::from_value(json!({"id":sid,"name":"Input","workspace":"/work","coworker":"test","bundle_digest":"bundle","schema_digest":null,"interactions":[],"turn":null,"sandbox":null,"closed":false,"resource_policy":openworker_runtime::resource_policy::Resolved::default()})).unwrap();+ if sid == "s_two" {+ session+ .safety+ .guardrails+ .user_input+ .push(openworker_runtime::safety::Rule::regex(+ "secret",+ "SECRET_",+ openworker_runtime::safety::Action::Block,+ ));+ }+ store.save(&session, "session_created", json!({})).unwrap();+ }+ for (token, principal, sid, role) in [+ (ALICE, "alice", "s_one", Role::Operator),+ (BOB, "bob", "s_two", Role::Operator),+ (READER, "reader", "s_one", Role::Observer),+ ] {+ admin+ .auth_issue(+ principal,+ Spec {+ principal: principal.into(),+ role,+ scope: Scope::Sessions {+ ids: vec![sid.into()],+ },+ environments: vec![],+ expires_at: None,+ },+ token,+ )+ .unwrap();+ }+ let bundle = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/assistant");+ let runner = std::env::current_exe().unwrap();+ let runtime = Runtime::open_with_store(+ &root.path().join("runtime"),+ &bundle,+ &runner,+ Model::new("fixture".into(), true),+ Backend::Off,+ None,+ None,+ Default::default(),+ Some(Box::new(store.clone())),+ )+ .unwrap();+ let mut urls = vec![];+ let mut servers = vec![];+ for _ in 0..2 {+ let app = App::new(+ &config,+ runtime.clone(),+ store.clone(),+ CancellationToken::new(),+ )+ .unwrap();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ urls.push(format!("http://{}", listener.local_addr().unwrap()));+ servers.push(tokio::spawn(async move {+ axum::serve(listener, app.router()).await.unwrap();+ }));+ }+ let client = reqwest::Client::builder().no_proxy().build().unwrap();+ let post = |node: usize, token: &'static str, path: String, body: Value, idem: &'static str| {+ let url = format!("{}{path}", urls[node]);+ client+ .post(url)+ .header("x-openworker-namespace", "test")+ .header("idempotency-key", idem)+ .bearer_auth(token)+ .json(&body)+ .send()+ };+ let data = vec![65u8; 600000];+ let m = Metadata {+ id: "notes".into(),+ name: "notes.txt".into(),+ media_type: "text/plain".into(),+ size: data.len(),+ sha256: openworker_runtime::bundle::digest(&data),+ };+ let path = "/v1/sessions/s_one/attachments/notes";+ let begin = json!({"operation":"begin","metadata":m});+ for token in [BOB, READER] {+ assert_eq!(+ post(0, token, path.into(), begin.clone(), "unused")+ .await+ .unwrap()+ .status(),+ 403+ );+ }+ assert_eq!(+ post(0, ALICE, path.into(), begin.clone(), "unused")+ .await+ .unwrap()+ .status(),+ 200+ );+ for (i, chunk) in data.chunks(262144).enumerate() {+ let body = json!({"operation":"chunk","offset":i*262144,"data":STANDARD.encode(chunk)});+ for _ in 0..2 {+ assert_eq!(+ post(i % 2, ALICE, path.into(), body.clone(), "unused")+ .await+ .unwrap()+ .status(),+ 200+ );+ }+ }+ assert_eq!(+ post(+ 1,+ ALICE,+ path.into(),+ json!({"operation":"commit"}),+ "unused"+ )+ .await+ .unwrap()+ .status(),+ 200+ );+ let receipt: Value = post(0, ALICE, path.into(), json!({"operation":"stat"}), "unused")+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ assert_eq!(receipt["sealed"], true);+ assert!(!receipt.to_string().contains(&STANDARD.encode(&data)));+ let parts = vec![+ Part::Text {+ text: "Before".into(),+ },+ Part::Document {+ attachment_id: "notes".into(),+ },+ Part::Text {+ text: "After".into(),+ },+ ];+ let body = json!({"content":parts});+ let turn_path = "/v1/sessions/s_one/turns";+ let response = post(0, ALICE, turn_path.into(), body.clone(), "ordered")+ .await+ .unwrap();+ let status = response.status();+ let receipt: Value = response.json().await.unwrap();+ assert_eq!(status, 202, "{receipt}");+ let submission = receipt["submissionId"].as_str().unwrap();+ let replay = post(1, ALICE, turn_path.into(), body.clone(), "ordered")+ .await+ .unwrap();+ assert_eq!(replay.status(), 202);+ assert_eq!(+ store.submission_input("s_one", submission).unwrap(),+ Some(parts.clone())+ );+ let changed = post(+ 1,+ ALICE,+ turn_path.into(),+ json!({"content":[parts[1].clone(),parts[0].clone()]}),+ "ordered",+ )+ .await+ .unwrap();+ assert_eq!(changed.status(), 409);+ let next = store.next_turn("s_one").unwrap().unwrap();+ let (s, _, _) = store+ .accept_with_context(+ "s_one",+ &next.submission_id,+ &next.text,+ next.limits,+ None,+ Context {+ content: Some(parts),+ ..Default::default()+ },+ )+ .unwrap();+ assert_eq!(s.history[0]["content"][1]["id"], "notes");+ let mut reopened = PostgresStore::open(db.clone()).unwrap();+ let hydrated = openworker_runtime::attachments::hydrate(+ &mut reopened,+ "s_one",+ &store.get("s_one").unwrap().history,+ )+ .unwrap();+ assert_eq!(hydrated[0]["content"][0]["text"], "Before");+ assert!(hydrated[0]["content"][1]["text"]+ .as_str()+ .unwrap()+ .ends_with(&"A".repeat(data.len())));+ // No bypass through a reference: binary input policies fail closed on ingress.+ let pdf = b"%PDF-1.4\n%%EOF";+ let meta = Metadata {+ id: "pdf".into(),+ name: "a.pdf".into(),+ media_type: "application/pdf".into(),+ size: pdf.len(),+ sha256: openworker_runtime::bundle::digest(pdf),+ };+ for upload in [+ Upload::Begin { metadata: meta },+ Upload::Chunk {+ offset: 0,+ data: STANDARD.encode(pdf),+ },+ Upload::Commit,+ ] {+ store.input_attachment("s_two", "pdf", upload).unwrap();+ }+ let denied = post(+ 0,+ BOB,+ "/v1/sessions/s_two/turns".into(),+ json!({"content":[{"type":"document","attachment_id":"pdf"}]}),+ "binary",+ )+ .await+ .unwrap();+ assert_eq!(denied.status(), 422);+ assert_eq!(+ denied.json::<Value>().await.unwrap()["error"],+ "attachment_inspection_unsupported"+ );+ assert!(store+ .authorized(BOB)+ .unwrap()+ .input_attachment("s_one", "notes", Upload::Stat)+ .is_err());+ for server in servers {+ server.abort();+ let _ = server.await;+ }+ runtime.shutdown().await.unwrap();+ drop(runtime);+ drop(reopened);+ drop(admin);+ drop(store);+ tokio::task::spawn_blocking(move || {+ let mut sql = postgres::Client::connect(&db.connection, postgres::NoTls).unwrap();+ sql.batch_execute(&format!(+ "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ db.schema+ ))+ .unwrap();+ assert!(+ sql.execute(+ "UPDATE submissions SET text=text WHERE session_id='s_one'",+ &[]+ )+ .is_err(),+ "An older worker must not consume an attachment submission"+ );+ sql.batch_execute(&format!("DROP SCHEMA {} CASCADE", db.schema))+ .unwrap();+ })+ .await+ .unwrap();+}diff --git a/harness/store-postgres/Cargo.toml b/harness/store-postgres/Cargo.tomlindex 1a812f88..2df61de7 100644--- a/harness/store-postgres/Cargo.toml+++ b/harness/store-postgres/Cargo.toml@@ -10,6 +10,7 @@ license.workspace = truepublish = ["crates-io"][features]+attachments = ["openworker-runtime/attachments"]compliance = ["openworker-runtime/compliance"]guardrails = ["openworker-runtime/guardrails"]test-support = ["dep:openworker-tools", "openworker-runtime/test-fixtures"]diff --git a/harness/store-postgres/src/compatibility.sql b/harness/store-postgres/src/compatibility.sqlindex 53efd14f..f08215f1 100644--- a/harness/store-postgres/src/compatibility.sql+++ b/harness/store-postgres/src/compatibility.sql@@ -1,9 +1,9 @@--- Old clients ignore safety fields. Fence their writes even if they raced an+-- Old clients ignore safety fields and queued attachment inputs. Fence their writes even if they raced an-- upgrade startup check. This is a compatibility boundary, not DB-user auth.CREATE OR REPLACE FUNCTION ow_require_safety_runtime() RETURNS trigger LANGUAGE plpgsql AS $$BEGIN- IF current_setting('ow.runtime_schema',true) IS DISTINCT FROM '6' THEN- RAISE EXCEPTION 'Runtime schema 6 required; upgrade the client before writing';+ IF current_setting('ow.runtime_schema',true) IS DISTINCT FROM '7' THEN+ RAISE EXCEPTION 'Runtime schema 7 required; upgrade the client before writing';END IF;RETURN NULL;END $$;diff --git a/harness/store-postgres/src/db.rs b/harness/store-postgres/src/db.rsindex badeae80..48803f65 100644--- a/harness/store-postgres/src/db.rs+++ b/harness/store-postgres/src/db.rs@@ -71,7 +71,7 @@ fn connect(config: &Config) -> Result<Client> {}};let millis = config.timeout.as_millis().saturating_mul(3) / 4;- client.batch_execute(&format!("SET statement_timeout={millis}; SET lock_timeout={millis}; SET idle_in_transaction_session_timeout={millis}; SET ow.runtime_schema='6'; SET search_path={},pg_catalog",config.schema))?;+ client.batch_execute(&format!("SET statement_timeout={millis}; SET lock_timeout={millis}; SET idle_in_transaction_session_timeout={millis}; SET ow.runtime_schema='7'; SET search_path={},pg_catalog",config.schema))?;Ok(client)}pub(crate) fn migrate(config: &Config) -> Result<()> {@@ -87,10 +87,10 @@ pub(crate) fn migrate(config: &Config) -> Result<()> {.get(0);if exists {let rows = tx.query("SELECT version FROM version WHERE singleton", &[])?;- if rows.len() != 1 || !matches!(rows[0].get::<_, i32>(0), 5 | 6) {+ if rows.len() != 1 || !matches!(rows[0].get::<_, i32>(0), 5..=7) {bail!("Unsupported PostgreSQL schema version; migration required");}- if rows[0].get::<_, i32>(0) == 5 {+ if rows[0].get::<_, i32>(0) != 7 {// Stop/drain all old API and worker processes before this upgrade. Never// revoke live execution ownership while an external action may be running.let active: bool = tx@@ -100,9 +100,9 @@ pub(crate) fn migrate(config: &Config) -> Result<()> {)?.get(0);if active {- bail!("Stop old API/worker/SDK processes and release or expire their leases before upgrading schema 5 to 6");+ bail!("Stop old API/worker/SDK processes and release or expire their leases before upgrading schema 5/6 to 7");}- tx.execute("UPDATE version SET version=6 WHERE singleton", &[])?;+ tx.execute("UPDATE version SET version=7 WHERE singleton", &[])?;}} else {// Do not adopt/reset an unrelated partially populated schema.@@ -116,12 +116,12 @@ pub(crate) fn migrate(config: &Config) -> Result<()> {bail!("Refusing to initialize a nonempty unversioned PostgreSQL schema");}tx.batch_execute(include_str!("schema.sql"))?;- tx.execute("INSERT INTO version VALUES(TRUE,6)", &[])?;+ tx.execute("INSERT INTO version VALUES(TRUE,7)", &[])?;}// Optional query accelerators; explicit migration only.tx.batch_execute("CREATE INDEX IF NOT EXISTS submissions_recent ON submissions(created DESC,session_id DESC,sequence DESC); CREATE INDEX IF NOT EXISTS submissions_session_recent ON submissions(session_id,created DESC,sequence DESC)")?;// Nullable for existing submissions; queued overrides require explicit migration.- tx.batch_execute("ALTER TABLE submissions ADD COLUMN IF NOT EXISTS limits JSONB")?;+ tx.batch_execute("ALTER TABLE submissions ADD COLUMN IF NOT EXISTS limits JSONB; ALTER TABLE submissions ADD COLUMN IF NOT EXISTS input_content JSONB")?;crate::artifacts::migrate(&mut tx)?;crate::auth::migrate(&mut tx)?;crate::compliance::migrate(&mut tx)?;@@ -138,6 +138,7 @@ pub(crate) fn migrate(config: &Config) -> Result<()> {crate::service_team_submissions::migrate(&mut tx)?;crate::service_team_publications::migrate(&mut tx)?;tx.batch_execute("CREATE TABLE IF NOT EXISTS sdk_host_mode(singleton BOOLEAN PRIMARY KEY CHECK(singleton), mode TEXT NOT NULL CHECK(mode='sdk'))")?;+ tx.batch_execute("CREATE TABLE IF NOT EXISTS input_attachments(session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,id TEXT NOT NULL,metadata JSONB NOT NULL,data BYTEA NOT NULL,sealed BOOLEAN NOT NULL DEFAULT false,created TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),referenced BOOLEAN NOT NULL DEFAULT false,PRIMARY KEY(session_id,id))")?;tx.batch_execute(include_str!("compatibility.sql"))?;tx.commit()?;Ok(())@@ -325,7 +326,7 @@ impl Database {pub fn open(config: Config) -> Result<Self> {let mut client = connect(&config)?;let rows = client.query("SELECT version FROM version WHERE singleton", &[])?;- if rows.len() != 1 || rows[0].get::<_, i32>(0) != 6 {+ if rows.len() != 1 || rows[0].get::<_, i32>(0) != 7 {bail!("Unsupported PostgreSQL schema; run explicit migration");}let owner = uuid::Uuid::new_v4().to_string();@@ -835,10 +836,13 @@ impl Database {let epoch = self.epoch(sid)?;let mut tx = self.client.transaction()?;let mut s = locked(&mut tx, sid, Some((&self.owner, epoch)))?;+ if let Some(parts) = &context.content {+ crate::input_attachments::validate_references(&mut tx, sid, parts)?;+ }crate::submissions::verify(&mut tx, sid)?;read_history(&mut tx, &mut s)?;let existing = tx.query_opt(- "SELECT text,turn_id,status,limits FROM submissions WHERE session_id=$1 AND id=$2",+ "SELECT text,turn_id,status,limits,input_content FROM submissions WHERE session_id=$1 AND id=$2",&[&sid, &key],)?;if let Some(row) = &existing {@@ -850,6 +854,17 @@ impl Database {{return Err(crate::SubmissionError::Conflict.into());}+ if row.get::<_, String>(2) == "queued" {+ anyhow::ensure!(+ row.get::<_, Option<Value>>(4)+ == context+ .content+ .as_ref()+ .map(serde_json::to_value)+ .transpose()?,+ "Queued input content conflict"+ );+ }if row.get::<_, String>(2) != "queued" {let old_context_digest = tx.query_opt("SELECT data->>'context_digest' FROM events WHERE session_id=$1 AND turn_id=$2 AND kind='turn_accepted' ORDER BY cursor LIMIT 1", &[&sid,&tid])?.and_then(|r|r.get::<_,Option<String>>(0)).unwrap_or(openworker_runtime::turn_options::Context::default().digest()?);anyhow::ensure!(@@ -930,7 +945,10 @@ impl Database {s.history.push(json!({"type":"function_call_output","call_id":c["call_id"],"output":"Previous turn interrupted; action outcome unknown, do not assume success."}));}}- let mut input = json!({"role":"user","content":text});+ if let Some(parts) = &context.content {+ crate::input_attachments::retain(&mut tx, sid, parts)?;+ }+ let mut input = json!({"role":"user","content":context.content.as_ref().map(|p|openworker_runtime::attachments::history(p)).unwrap_or_else(||json!(text))});if openworker_runtime::assistant_tools::admit(&mut s,key,diff --git a/harness/store-postgres/src/input_attachments.rs b/harness/store-postgres/src/input_attachments.rsnew file mode 100644index 00000000..be25ea3f--- /dev/null+++ b/harness/store-postgres/src/input_attachments.rs@@ -0,0 +1,100 @@+use crate::{+ auth::{self, Action},+ db::Database,+};+use anyhow::{ensure, Result};+use openworker_runtime::attachments::*;+impl Database {+ pub(crate) fn input_blob(&mut self, sid: &str, id: &str, request: Upload) -> Result<Blob> {+ let stat = matches!(&request, Upload::Stat);+ let mut tx = self.client.transaction()?;+ auth::guard(+ &mut tx,+ self.auth.as_ref(),+ if stat { Action::Read } else { Action::Submit },+ Some(sid),+ None,+ )?;+ let session = tx+ .query_opt("SELECT data FROM sessions WHERE id=$1 FOR UPDATE", &[&sid])?+ .ok_or_else(|| anyhow::anyhow!("Session unavailable"))?;+ let closed = session.get::<_, serde_json::Value>(0)["closed"] == true;+ let writable = !stat && !closed;+ if writable {+ tx.execute("DELETE FROM input_attachments WHERE session_id=$1 AND NOT referenced AND created<clock_timestamp()-interval '24 hours'",&[&sid])?;+ }+ let old = tx+ .query_opt(+ "SELECT metadata,data,sealed FROM input_attachments WHERE session_id=$1 AND id=$2",+ &[&sid, &id],+ )?+ .map(|r| -> Result<_> {+ Ok(Blob {+ metadata: serde_json::from_value(r.get(0))?,+ bytes: r.get(1),+ sealed: r.get(2),+ })+ })+ .transpose()?;+ if closed && !stat {+ ensure!(+ matches!(&request, Upload::Begin { .. }) && old.as_ref().is_some_and(|b| b.sealed),+ "Session closed"+ );+ }+ if old.is_none() {+ if let Upload::Begin { metadata } = &request {+ let count: i64 = tx+ .query_one(+ "SELECT count(*) FROM input_attachments WHERE session_id=$1",+ &[&sid],+ )?+ .get(0);+ ensure!(+ count < MAX_SESSION_FILES as i64,+ "Session attachment count limit exceeded"+ );+ let total:i64=tx.query_one("SELECT COALESCE(SUM((metadata->>'size')::bigint),0)::bigint FROM input_attachments WHERE session_id=$1",&[&sid])?.get(0);+ ensure!(+ total.saturating_add(metadata.size.try_into()?) <= MAX_SESSION as i64,+ "Session attachment quota exceeded"+ );+ }+ }+ let blob = apply(id, old, request)?;+ if writable {+ tx.execute("INSERT INTO input_attachments(session_id,id,metadata,data,sealed) VALUES($1,$2,$3,$4,$5) ON CONFLICT(session_id,id) DO UPDATE SET data=excluded.data,sealed=excluded.sealed",&[&sid,&id,&serde_json::to_value(&blob.metadata)?,&blob.bytes,&blob.sealed])?;+ }+ tx.commit()?;+ Ok(blob)+ }+}++pub(crate) fn validate_references(+ tx: &mut postgres::Transaction<'_>,+ sid: &str,+ parts: &[Part],+) -> Result<()> {+ openworker_runtime::attachments::validate_references(parts, |id| {+ let row = tx+ .query_opt(+ "SELECT metadata,sealed FROM input_attachments WHERE session_id=$1 AND id=$2",+ &[&sid, &id],+ )?+ .ok_or_else(|| anyhow::anyhow!("Attachment not found in this session"))?;+ ensure!(row.get::<_, bool>(1), "Attachment upload is incomplete");+ Ok(serde_json::from_value(row.get(0))?)+ })+}++pub(crate) fn retain(tx: &mut postgres::Transaction<'_>, sid: &str, parts: &[Part]) -> Result<()> {+ for part in parts {+ if let Part::Image { attachment_id } | Part::Document { attachment_id } = part {+ tx.execute(+ "UPDATE input_attachments SET referenced=true WHERE session_id=$1 AND id=$2",+ &[&sid, &attachment_id],+ )?;+ }+ }+ Ok(())+}diff --git a/harness/store-postgres/src/lib.rs b/harness/store-postgres/src/lib.rsindex 7e216238..e8820b14 100644--- a/harness/store-postgres/src/lib.rs+++ b/harness/store-postgres/src/lib.rs@@ -9,6 +9,7 @@ mod controls;mod db;mod environments;mod ingress;+mod input_attachments;mod input_safety;mod observers;mod operations;@@ -535,6 +536,21 @@ fn sanitize(e: anyhow::Error) -> anyhow::Error {}impl StateStore for PostgresStore {+ fn supports_input_attachments(&self) -> bool {+ cfg!(feature = "attachments")+ }++ fn input_attachment(+ &mut self,+ sid: &str,+ id: &str,+ request: openworker_runtime::attachments::Upload,+ ) -> Result<openworker_runtime::attachments::Blob> {+ let sid = sid.to_owned();+ let id = id.to_owned();+ self.call(move |db| db.input_blob(&sid, &id, request))+ }+fn pending_observers(&self, sid: &str) -> Result<Vec<Value>> {let sid = sid.to_owned();self.call(move |db| db.pending_observers(&sid))diff --git a/harness/store-postgres/src/service.rs b/harness/store-postgres/src/service.rsindex 93f6cc60..14f67a92 100644--- a/harness/store-postgres/src/service.rs+++ b/harness/store-postgres/src/service.rs@@ -19,6 +19,43 @@ impl PostgresStore {request.validate()?;self.call(move |db| db.submit_turn_with_mode(request, true))}+ pub fn submit_service_input(+ &self,+ request: crate::TurnSubmission,+ content: Vec<openworker_runtime::attachments::Part>,+ ) -> Result<crate::SubmissionReceipt> {+ self.call(move |db| db.submit_turn_with_input(request, true, Some(content)))+ }+ /// References only; scoped read, never attachment bytes.+ pub fn submission_input(+ &self,+ sid: &str,+ key: &str,+ ) -> Result<Option<Vec<openworker_runtime::attachments::Part>>> {+ let (sid, key) = (sid.to_owned(), key.to_owned());+ self.call(move |db| {+ let mut tx = db.client.transaction()?;+ auth::guard(+ &mut tx,+ db.auth.as_ref(),+ auth::Action::Read,+ Some(&sid),+ None,+ )?;+ let value = tx+ .query_opt(+ "SELECT input_content FROM submissions WHERE session_id=$1 AND id=$2",+ &[&sid, &key],+ )?+ .ok_or(SubmissionError::NotFound)?+ .get::<_, Option<Value>>(0);+ tx.commit()?;+ value+ .map(serde_json::from_value)+ .transpose()+ .map_err(Into::into)+ })+ }/// Trusted installation/startup only. Never changes an established binding.pub fn bind_service(&self, id: &str, namespace: &str) -> Result<()> {ensure!(self.auth.is_none(), auth::Error::Forbidden);diff --git a/harness/store-postgres/src/submissions.rs b/harness/store-postgres/src/submissions.rsindex e6bf560f..0c4ec400 100644--- a/harness/store-postgres/src/submissions.rs+++ b/harness/store-postgres/src/submissions.rs@@ -195,8 +195,20 @@ impl Database {&mut self,request: TurnSubmission,single: bool,+ ) -> Result<SubmissionReceipt> {+ self.submit_turn_with_input(request, single, None)+ }+ pub(crate) fn submit_turn_with_input(+ &mut self,+ request: TurnSubmission,+ single: bool,+ content: Option<Vec<openworker_runtime::attachments::Part>>,) -> Result<SubmissionReceipt> {request.validate()?;+ if let Some(parts) = &content {+ openworker_runtime::attachments::validate_parts(parts)?;+ }+ let content_value = content.as_ref().map(serde_json::to_value).transpose()?;let mut tx = self.client.transaction()?;let p = crate::auth::guard(&mut tx,@@ -206,6 +218,9 @@ impl Database {None,)?;let session = locked(&mut tx, &request.session_id, None)?;+ if let Some(parts) = &content {+ crate::input_attachments::validate_references(&mut tx, &request.session_id, parts)?;+ }verify(&mut tx, &request.session_id)?;// Deduplicate before lifecycle/capacity checks: lost receipts remain// reconcilable when the queue fills or the session later closes.@@ -213,7 +228,8 @@ impl Database {"SELECT * FROM submissions WHERE session_id=$1 AND id=$2",&[&request.session_id, &request.submission_id],)? {- if row.get::<_, String>("text") != request.text+ if row.get::<_, Option<Value>>("input_content") != content_value+ || row.get::<_, String>("text") != request.text|| row.get::<_, Option<Value>>("limits")!= request.limits@@ -274,6 +290,15 @@ impl Database {SubmissionError::QueueFull);let result = insert(&mut tx, &request, "queued", None)?;+ if let Some(parts) = &content {+ crate::input_attachments::retain(&mut tx, &request.session_id, parts)?;+ }+ if content_value.is_some() {+ tx.execute(+ "UPDATE submissions SET input_content=$3 WHERE session_id=$1 AND id=$2",+ &[&request.session_id, &request.submission_id, &content_value],+ )?;+ }journal_acceptance(&mut tx, &result, p.as_ref().map(|p| p.principal.as_str()))?;crate::auth::audit(&mut tx,diff --git a/harness/store-postgres/src/worker.rs b/harness/store-postgres/src/worker.rsindex d3e41288..485ad309 100644--- a/harness/store-postgres/src/worker.rs+++ b/harness/store-postgres/src/worker.rs@@ -599,10 +599,12 @@ async fn execute_inner(Err(e) => return Err(e),};if let Some(next) = next {- if let Err(error) = runtime- .dispatch("turn/start", serde_json::to_value(next)?)- .await- {+ let content = store.submission_input(sid, &next.submission_id)?;+ let mut request = serde_json::to_value(next)?;+ if let Some(content) = content {+ request["content"] = serde_json::to_value(content)?;+ }+ if let Err(error) = runtime.dispatch("turn/start", request).await {// A control can arrive after the peek. Acceptance has// committed nothing: re-read the priority path next tick,// without restarting this worker or changing task IDs.diff --git a/harness/store-postgres/tests/artifacts.rs b/harness/store-postgres/tests/artifacts.rsindex fae74cd3..fa205ce0 100644--- a/harness/store-postgres/tests/artifacts.rs+++ b/harness/store-postgres/tests/artifacts.rs@@ -46,7 +46,7 @@ fn binding() -> Binding {fn admin(c: &Config) -> postgres::Client {let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/assistant.rs b/harness/store-postgres/tests/assistant.rsindex dc7eaa81..80730866 100644--- a/harness/store-postgres/tests/assistant.rs+++ b/harness/store-postgres/tests/assistant.rs@@ -33,7 +33,7 @@ fn postgres_atomic_memory_rollback() {let (tid, call) = contract::prepare(&mut s, "a", "memory_remember", &args);let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();@@ -117,7 +117,7 @@ fn fenced_owner_cannot_mutate_memory() {let args = json!({"summary":"fenced","content":"must not commit"});let (tid, call) = contract::prepare(&mut old, "a", "memory_remember", &args);let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();- db.batch_execute(&format!("SET ow.runtime_schema='6'; SET search_path={},pg_catalog; UPDATE sessions SET expires=clock_timestamp()-interval '1 second' WHERE id='a'", c.schema)).unwrap();+ db.batch_execute(&format!("SET ow.runtime_schema='7'; SET search_path={},pg_catalog; UPDATE sessions SET expires=clock_timestamp()-interval '1 second' WHERE id='a'", c.schema)).unwrap();let mut next = PostgresStore::open(c).unwrap();next.claim("a").unwrap();assert!(old.assistant_call("a", &tid, &call, &args).is_err());diff --git a/harness/store-postgres/tests/authorization.rs b/harness/store-postgres/tests/authorization.rsindex cd610205..998bba28 100644--- a/harness/store-postgres/tests/authorization.rs+++ b/harness/store-postgres/tests/authorization.rs@@ -29,7 +29,7 @@ fn fixture() -> (Config, PostgresStore, PostgresStore) {fn sql(c: &Config) -> postgres::Client {let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/compliance.rs b/harness/store-postgres/tests/compliance.rsindex c4b93f70..3421f899 100644--- a/harness/store-postgres/tests/compliance.rs+++ b/harness/store-postgres/tests/compliance.rs@@ -203,7 +203,7 @@ fn schema_fence_blocks_old_clients_and_preserves_existing_records() {PostgresStore::migrate(&c).is_err(),"Do not upgrade under a live owner");- db.batch_execute("UPDATE version SET version=6 WHERE singleton")+ db.batch_execute("UPDATE version SET version=7 WHERE singleton").unwrap();// Emulate a drained old schema without altering its session payload.store.release("upgrade").unwrap();@@ -215,7 +215,7 @@ fn schema_fence_blocks_old_clients_and_preserves_existing_records() {db.query_one("SELECT version FROM version", &[]).unwrap().get::<_, i32>(0),- 6+ 7);let store = PostgresStore::open(c.clone()).unwrap();assert_eq!(diff --git a/harness/store-postgres/tests/controls.rs b/harness/store-postgres/tests/controls.rsindex 0a10ce56..54bc1bdc 100644--- a/harness/store-postgres/tests/controls.rs+++ b/harness/store-postgres/tests/controls.rs@@ -54,7 +54,7 @@ fn fixture() -> (Config, PostgresStore, Command) {fn admin(c: &Config) -> postgres::Client {let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/environments.rs b/harness/store-postgres/tests/environments.rsindex fc7fb7e2..e60dc4b4 100644--- a/harness/store-postgres/tests/environments.rs+++ b/harness/store-postgres/tests/environments.rs@@ -60,7 +60,7 @@ fn close(store: &mut PostgresStore, id: &str) {fn admin(c: &Config) -> postgres::Client {let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/ingress.rs b/harness/store-postgres/tests/ingress.rsindex c7918e7c..2713a366 100644--- a/harness/store-postgres/tests/ingress.rs+++ b/harness/store-postgres/tests/ingress.rs@@ -68,7 +68,7 @@ fn creation_audit_failure_rolls_back_and_missing_receipt_never_recreates() {let api = PostgresStore::open(c.clone()).unwrap();let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/operations.rs b/harness/store-postgres/tests/operations.rsindex ec15e2da..39f089f9 100644--- a/harness/store-postgres/tests/operations.rs+++ b/harness/store-postgres/tests/operations.rs@@ -61,7 +61,7 @@ fn operational_counts_are_current_content_free_and_host_only() {}).unwrap();let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();- db.batch_execute(&format!("SET ow.runtime_schema='6'; SET search_path={},pg_catalog; UPDATE audit SET created=now()-interval '60 seconds'; UPDATE submissions SET created=now()-interval '60 seconds'",c.schema)).unwrap();+ db.batch_execute(&format!("SET ow.runtime_schema='7'; SET search_path={},pg_catalog; UPDATE audit SET created=now()-interval '60 seconds'; UPDATE submissions SET created=now()-interval '60 seconds'",c.schema)).unwrap();let snapshot = store.operational_snapshot(30, 30).unwrap();assert_eq!((diff --git a/harness/store-postgres/tests/pools.rs b/harness/store-postgres/tests/pools.rsindex cc7a580d..5afc72f6 100644--- a/harness/store-postgres/tests/pools.rs+++ b/harness/store-postgres/tests/pools.rs@@ -103,7 +103,7 @@ fn version_catalog_preserves_identity_counts_idle_sessions_and_expires_presence(.advertise_worker("old-pool", selector.clone(), 2, false).unwrap();let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();- db.batch_execute(&format!("SET ow.runtime_schema='6'; SET search_path={},pg_catalog; UPDATE worker_presence SET expires=now()-interval '1 second'",c.schema)).unwrap();+ db.batch_execute(&format!("SET ow.runtime_schema='7'; SET search_path={},pg_catalog; UPDATE worker_presence SET expires=now()-interval '1 second'",c.schema)).unwrap();assert_eq!(store.worker_pools(None, 1).unwrap()["pools"][0]["workers"],json!([])diff --git a/harness/store-postgres/tests/service_catalog.rs b/harness/store-postgres/tests/service_catalog.rsindex 8ef0fa27..4c6c413f 100644--- a/harness/store-postgres/tests/service_catalog.rs+++ b/harness/store-postgres/tests/service_catalog.rs@@ -131,7 +131,7 @@ fn immutable_catalog_admission_ownership_and_one_dispatch() {assert!(store.service_claim().unwrap().is_none());let mut pg = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();pg.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();@@ -206,7 +206,7 @@ fn admission_failure_rolls_back_environment_and_receipt() {let (r, p) = catalog(&a);let mut pg = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();pg.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();@@ -316,7 +316,7 @@ fn combined_submission_commits_once_and_rolls_back_as_one_unit() {.unwrap();let mut pg = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();pg.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();@@ -563,7 +563,7 @@ fn credential_expiring_during_provisioning_cannot_commit_a_session() {.unwrap();let mut pg = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();pg.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/service_identity.rs b/harness/store-postgres/tests/service_identity.rsindex 359760e5..cd993d49 100644--- a/harness/store-postgres/tests/service_identity.rs+++ b/harness/store-postgres/tests/service_identity.rs@@ -17,7 +17,7 @@ fn persisted_binding_cannot_change_and_restore_verification_does_not_write() {assert!(store.bind_service("cluster", "other").is_err());let mut db = postgres::Client::connect(&config.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",config.schema)).unwrap();diff --git a/harness/store-postgres/tests/store.rs b/harness/store-postgres/tests/store.rsindex 4774c85c..c5f4cb01 100644--- a/harness/store-postgres/tests/store.rs+++ b/harness/store-postgres/tests/store.rs@@ -23,7 +23,7 @@ fn session(id: &str) -> Session {fn admin(c: &Config) -> postgres::Client {let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();@@ -135,6 +135,7 @@ fn imported_history_and_turn_context_survive_postgres_atomicity_and_takeover() {owner.save(&s, "session_created", json!({})).unwrap();assert!(owner.get(&s.id).unwrap().turn.is_none());let context = Context {+ content: None,instruction_addendum: Some("TURN_PRIVATE_CONTEXT".into()),output: OutputOptions {reasoning: true,@@ -195,6 +196,7 @@ fn imported_history_and_turn_context_survive_postgres_atomicity_and_takeover() {None,None,Context {+ content: None,output: OutputOptions::default(),..context}diff --git a/harness/store-postgres/tests/submissions.rs b/harness/store-postgres/tests/submissions.rsindex 73fefb66..7dcc2a1c 100644--- a/harness/store-postgres/tests/submissions.rs+++ b/harness/store-postgres/tests/submissions.rs@@ -21,7 +21,7 @@ fn fixture(limit: u16) -> (Config, PostgresStore) {fn admin(c: &Config) -> postgres::Client {let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/support/load.rs b/harness/store-postgres/tests/support/load.rsindex c051a388..942db6b1 100644--- a/harness/store-postgres/tests/support/load.rs+++ b/harness/store-postgres/tests/support/load.rs@@ -117,7 +117,7 @@ async fn sample(let (queue, end_to_end) = tokio::task::block_in_place(|| {let mut db = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/teams.rs b/harness/store-postgres/tests/teams.rsindex f2b9ad0d..377bd856 100644--- a/harness/store-postgres/tests/teams.rs+++ b/harness/store-postgres/tests/teams.rs@@ -348,7 +348,7 @@ fn concurrent_assignment_has_one_winner_and_failed_commit_enqueues_nothing() {let before = db.team_snapshot(&team).unwrap();let mut sql = postgres::Client::connect(&c.connection, postgres::NoTls).unwrap();sql.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",c.schema)).unwrap();diff --git a/harness/store-postgres/tests/worker_recovery.rs b/harness/store-postgres/tests/worker_recovery.rsindex 0576a042..a2934876 100644--- a/harness/store-postgres/tests/worker_recovery.rs+++ b/harness/store-postgres/tests/worker_recovery.rs@@ -282,7 +282,7 @@ async fn production_worker_loses_database_and_replacement_recovers_unknown_once(tokio::task::block_in_place(|| {let mut db = postgres::Client::connect(&config.connection, postgres::NoTls).unwrap();db.batch_execute(&format!(- "SET ow.runtime_schema='6'; SET search_path={},pg_catalog",+ "SET ow.runtime_schema='7'; SET search_path={},pg_catalog",config.schema)).unwrap();diff --git a/harness/typescript-sdk/README.md b/harness/typescript-sdk/README.mdindex 95df5efd..bcf20326 100644--- a/harness/typescript-sdk/README.md+++ b/harness/typescript-sdk/README.md@@ -529,3 +529,10 @@ See the [observability guide](../../docs/harness/guides/observability.md) for loSQLite/PostgreSQL, Langfuse export, content selection and audit references. Thesenew APIs require matching local candidate builds and are not in the published0.1.0-beta.2 packages yet.++## User attachments (source preview)++Attach images, PDFs and UTF-8 text files to a session with ordered content and+immutable recovery references. See [Attachments](../../docs/harness/guides/attachments.md)+for the Rust/TypeScript APIs, service uploads, limits and upgrade instructions.+This API requires matching source builds; it is not in npm `0.1.0-beta.2`.diff --git a/harness/typescript-sdk/package.json b/harness/typescript-sdk/package.jsonindex 0e7d61d8..33c56ce2 100644--- a/harness/typescript-sdk/package.json+++ b/harness/typescript-sdk/package.json@@ -43,7 +43,8 @@"test:service": "npm run build && node --test test/service.test.mjs","test:team-types": "npm run build && node --test --test-concurrency=1 test/team-types.test.mjs","test:observability": "npm run build && node --test test/observability.test.mjs test/evaluation-export.test.mjs",- "test:observability:integration": "npm run build && node --test test/observability-live.test.mjs"+ "test:observability:integration": "npm run build && node --test test/observability-live.test.mjs",+ "test:attachments": "npm run build && node --test --test-concurrency=1 test/attachments.test.mjs"},"devDependencies": {"@types/node": "^22.0.0",diff --git a/harness/typescript-sdk/src/attachments.ts b/harness/typescript-sdk/src/attachments.tsnew file mode 100644index 00000000..536aa3ad--- /dev/null+++ b/harness/typescript-sdk/src/attachments.ts@@ -0,0 +1,258 @@+/** Ordered user inputs; file bytes are staged, never packed into a giant RPC. */+import { createHash } from "node:crypto";+import { open } from "node:fs/promises";+import { basename, extname } from "node:path";+import { HarnessError } from "./types.js";+const MAX_FILE = 8 * 1024 * 1024,+ CHUNK = 256 * 1024;+const mimes = [+ "image/png",+ "image/jpeg",+ "image/gif",+ "image/webp",+ "application/pdf",+ "text/plain",+];+const invalid = (message: string): never => {+ throw new HarnessError("InvalidInput", message);+};+export type AttachmentSource =+ | { type: "base64"; mediaType: string; data: string }+ | { type: "text"; mediaType: "text/plain"; data: string }+ | { type: "attachment"; id: string };+export type InputContent =+ | { type: "text"; text: string }+ | Attachment+ | { type: "image" | "document"; name?: string; source: AttachmentSource };+export interface UserInput {+ type?: "message";+ content: InputContent[];+}+export class Attachment {+ readonly type: "image" | "document";+ readonly name: string;+ readonly mediaType: string;+ #bytes: Buffer;+ private constructor(name: string, mediaType: string, bytes: Uint8Array) {+ if (+ !name ||+ Buffer.byteLength(name) > 240 ||+ /[\x00-\x1f\x7f/\\]/.test(name)+ )+ invalid("Invalid attachment name");+ if (!mimes.includes(mediaType))+ invalid("Unsupported attachment media type");+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_FILE)+ invalid("Attachment size limit exceeded");+ if (mediaType === "text/plain") {+ try {+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);+ } catch {+ invalid("Text attachment must be UTF-8");+ }+ if (bytes.includes(0)) invalid("Text attachment contains null bytes");+ }+ this.name = name;+ this.mediaType = mediaType;+ this.type = mediaType.startsWith("image/") ? "image" : "document";+ this.#bytes = Buffer.from(bytes);+ Object.freeze(this);+ }+ static fromBytes(options: {+ name: string;+ mediaType: string;+ data: Uint8Array;+ }): Attachment {+ return new Attachment(options.name, options.mediaType, options.data);+ }+ static async fromFile(+ path: string,+ options: { mediaType?: string } = {},+ ): Promise<Attachment> {+ const file = await open(path, "r");+ try {+ const stat = await file.stat();+ if (!stat.isFile() || stat.size > MAX_FILE)+ invalid("Attachment must be a bounded regular file");+ const bytes = Buffer.alloc(stat.size + 1);+ let used = 0;+ while (used < bytes.length) {+ const n = await file.read(bytes, used, bytes.length - used, null);+ if (!n.bytesRead) break;+ used += n.bytesRead;+ }+ if (used > MAX_FILE || used !== stat.size)+ invalid("Attachment changed while reading");+ const ext = extname(path).toLowerCase();+ const mime =+ options.mediaType ??+ (+ {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".pdf": "application/pdf",+ } as Record<string, string>+ )[ext] ??+ "text/plain";+ return new Attachment(basename(path), mime, bytes.subarray(0, used));+ } finally {+ await file.close();+ }+ }+ /** Return a copy so caller changes cannot mutate an in-flight upload. */+ bytes(): Buffer {+ return Buffer.from(this.#bytes);+ }+}+function asAttachment(+ part: Exclude<InputContent, { type: "text"; text: string }>,+): Attachment | { reference: string; type: "image" | "document" } {+ if (part instanceof Attachment) return part;+ if (+ !part ||+ !["image", "document"].includes(part.type) ||+ !part.source ||+ Object.keys(part).some((k) => !["type", "name", "source"].includes(k))+ )+ invalid("Invalid attachment content");+ if (part.source.type === "attachment") {+ if (Object.keys(part.source).some((k) => !["type", "id"].includes(k)))+ invalid("Invalid attachment source fields");+ if (!/^[A-Za-z0-9_-]{1,100}$/.test(part.source.id))+ invalid("Invalid attachment reference");+ return { reference: part.source.id, type: part.type };+ }+ let bytes: Buffer;+ const source = part.source;+ if (+ Object.keys(source).some((k) => !["type", "mediaType", "data"].includes(k))+ )+ invalid("Invalid attachment source fields");+ if (source.type === "text") {+ if (typeof source.data !== "string" || source.mediaType !== "text/plain")+ invalid("Invalid text attachment source");+ bytes = Buffer.from(source.data, "utf8");+ } else if (source.type === "base64") {+ if (+ typeof source.data !== "string" ||+ source.data.length > Math.ceil(MAX_FILE / 3) * 4 ||+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(+ source.data,+ )+ )+ invalid("Invalid attachment base64");+ bytes = Buffer.from(source.data, "base64");+ } else return invalid("Unsupported attachment source");+ const a = Attachment.fromBytes({+ name: part.name ?? "attachment",+ mediaType: source.mediaType,+ data: bytes,+ });+ if (a.type !== part.type) invalid("Attachment type mismatch");+ return a;+}+export function userInput(+ text: string,+ attachments: Attachment | Attachment[],+): UserInput {+ return {+ content: [+ { type: "text", text },+ ...(Array.isArray(attachments) ? attachments : [attachments]),+ ],+ };+}+export function attachmentArgument(+ value: unknown,+): value is Attachment | Attachment[] {+ return value instanceof Attachment || Array.isArray(value);+}+export async function stageInput(+ input: UserInput,+ sessionId: string,+ request: (method: string, args: Record<string, unknown>) => Promise<unknown>,+ signal?: AbortSignal,+): Promise<Record<string, unknown>[]> {+ if (+ !input ||+ (input.type !== undefined && input.type !== "message") ||+ Object.keys(input).some((k) => k !== "content" && k !== "type") ||+ !Array.isArray(input.content) ||+ input.content.length < 1 ||+ input.content.length > 32+ )+ invalid("Input content must have 1..32 blocks");+ // Snapshot all bytes before the first await; validate total size before staging.+ let size = 0,+ textSize = 0;+ const parts = input.content.map((part) => {+ if (!part || typeof part !== "object")+ invalid("Invalid input content block");+ if (part.type === "text") {+ if (Object.keys(part).some((k) => !["type", "text"].includes(k)))+ invalid("Invalid text block fields");+ if (typeof part.text !== "string" || part.text.includes("\0"))+ invalid("Invalid input text");+ textSize += Buffer.byteLength(part.text);+ return { text: part.text };+ }+ const value = asAttachment(part);+ if ("reference" in value) return value;+ const bytes = value.bytes();+ size += bytes.length;+ if (size > 16 * 1024 * 1024) invalid("User input exceeds turn limits");+ return { attachment: value, bytes };+ });+ if (size > 16 * 1024 * 1024 || textSize > 32000)+ invalid("User input exceeds turn limits");+ const result: Record<string, unknown>[] = [];+ for (const part of parts) {+ if (signal?.aborted)+ throw new HarnessError("Aborted", "Attachment upload cancelled");+ if ("text" in part) {+ result.push({ type: "text", text: part.text });+ continue;+ }+ if ("reference" in part) {+ result.push({ type: part.type, attachment_id: part.reference });+ continue;+ }+ const { attachment: a, bytes } = part;+ const sha256 = createHash("sha256").update(bytes).digest("hex");+ const identity = createHash("sha256")+ .update(JSON.stringify([a.name, a.mediaType, sha256]))+ .digest("hex");+ const id = "att_" + identity;+ const send = (upload: Record<string, unknown>) =>+ request("attachment/upload", { session_id: sessionId, id, upload });+ const receipt = await send({+ operation: "begin",+ metadata: {+ id,+ name: a.name,+ media_type: a.mediaType,+ size: bytes.length,+ sha256,+ },+ });+ if ((receipt as { sealed?: boolean } | null)?.sealed !== true) {+ for (let offset = 0; offset < bytes.length; offset += CHUNK) {+ if (signal?.aborted)+ throw new HarnessError("Aborted", "Attachment upload cancelled");+ await send({+ operation: "chunk",+ offset,+ data: bytes.subarray(offset, offset + CHUNK).toString("base64"),+ });+ }+ await send({ operation: "commit" });+ }+ result.push({ type: a.type, attachment_id: id });+ }+ if (signal?.aborted)+ throw new HarnessError("Aborted", "Attachment upload cancelled");+ return result;+}diff --git a/harness/typescript-sdk/src/index.ts b/harness/typescript-sdk/src/index.tsindex 630a9f7c..bb6beed2 100644--- a/harness/typescript-sdk/src/index.ts+++ b/harness/typescript-sdk/src/index.ts@@ -1,3 +1,6 @@+import {Attachment,attachmentArgument,stageInput,userInput,type UserInput} from "./attachments.js";+export { Attachment } from "./attachments.js";+export type { UserInput, InputContent, AttachmentSource } from "./attachments.js";import { Observability } from "./observability.js";export * from "./observability.js";import { normalizeSafety, type SafetyOptions, type SafetyHandler, type SafetyContext, type SafetyDecision } from "./safety.js";@@ -800,7 +803,11 @@ export class Session {if (options.limits && this.harness.capabilities.turn_limits !== true) {throw new HarnessError("Setup", "Host does not support turn limits");}- const value = typeof input === "string" ? { text: input } : input;+ let value = typeof input === "string" ? { text: input } : input;+ if ("content" in value) {+ if(this.harness.capabilities.attachments!==true)throw new HarnessError("Setup","Host does not support attachments");+ value={content:await stageInput(value as UserInput,this.id,(m,p)=>this.harness.request(m,p),options.signal)} as unknown as typeof value;+ }const control = value.type === "approval" || value.type === "answer";if (control && (options.limits !== undefined||options.guardrails||options.hooks||options.blockedOutputOptions||options.instructionAddendum !== undefined||options.output !== undefined)) {throw new HarnessError(@@ -812,14 +819,14 @@ export class Session {? value.type === "approval"? ["type", "interactionId", "targetSessionId", "decision"]: ["type", "interactionId", "targetSessionId", "text"]- : ["type", "text"];+ : ["type", "text", "content"];if (Object.keys(value).some((key) => !allowed.includes(key)))throw new HarnessError("InvalidInput","Mixed or unknown session input fields",);const submissionId = options.submissionId ?? randomUUID();- const wire = control+ const wire = (value.type === "approval" || value.type === "answer")? {...value,interaction_id: value.interactionId,@@ -851,10 +858,14 @@ export class Session {options,);}- async run(input: string, options: RunOptions = {}): Promise<RunResult> {+ async run(input:string|UserInput,options?:RunOptions):Promise<RunResult>;+ async run(input:string,attachments:Attachment|Attachment[],options?:RunOptions):Promise<RunResult>;+ async run(input: string|UserInput, second:RunOptions|Attachment|Attachment[] = {}, third:RunOptions = {}): Promise<RunResult> {+ const options=attachmentArgument(second)?third:second;+ if(attachmentArgument(second)){if(typeof input!=="string")throw new HarnessError("InvalidInput","Attachments convenience form requires text");input=userInput(input,second);}const submissionId = options.submissionId ?? randomUUID();try {- await this.start(input, submissionId, options.signal);+ await this.start(input, submissionId, options);return await this.resume({ ...options, submissionId });} catch (e) {if (e instanceof HarnessError) {@@ -868,7 +879,7 @@ export class Session {}}async runWith(- input: string,+ input: string|UserInput,handler: (i: Interruption) => Response | Promise<Response>,options: RunOptions = {},): Promise<RunResult> {@@ -888,12 +899,13 @@ export class Session {}return result;}- async runStreamed(- input: string,- options: RunOptions = {},- ): Promise<RunStream> {+ async runStreamed(input:string|UserInput,options?:RunOptions):Promise<RunStream>;+ async runStreamed(input:string,attachments:Attachment|Attachment[],options?:RunOptions):Promise<RunStream>;+ async runStreamed(input:string|UserInput,second:RunOptions|Attachment|Attachment[]={},third:RunOptions={}):Promise<RunStream>{+ const options=attachmentArgument(second)?third:second;+ if(attachmentArgument(second)){if(typeof input!=="string")throw new HarnessError("InvalidInput","Attachments convenience form requires text");input=userInput(input,second);}const submissionId = options.submissionId ?? randomUUID();- const started = await this.start(input, submissionId, options.signal);+ const started = await this.start(input, submissionId, options);return new RunStream(this.harness, this.id, started.cursors as Cursors, {...options,submissionId,@@ -932,17 +944,28 @@ export class Session {return new RunStream(this.harness, this.id, cursors, options);}private async start(- input: string,+ input: string|UserInput,submissionId: string,- signal?: AbortSignal,+ options:RunOptions = {},): Promise<Record<string, unknown>> {- aborted(signal);+ aborted(options.signal);+ let content:Record<string,unknown>[]|undefined;+ if(typeof input!=="string"){+ if(this.harness.capabilities.attachments!==true)throw new HarnessError("Setup","Host does not support attachments");+ content=await stageInput(input,this.id,(m,p)=>this.harness.request(m,p),options.signal);+ }+ aborted(options.signal);try {return record(await this.harness.request("run/start", {session_id: this.id,submission_id: submissionId,- text: input,+ text: typeof input==="string"?input:undefined,+ content,+ limits:options.limits,+ instruction_addendum:options.instructionAddendum,+ output:options.output,+ safety:await this.harness.safetyOptions(options),}),);} catch (e) {diff --git a/harness/typescript-sdk/src/service.ts b/harness/typescript-sdk/src/service.tsindex 0ed6fc6f..eeb236af 100644--- a/harness/typescript-sdk/src/service.ts+++ b/harness/typescript-sdk/src/service.ts@@ -1,3 +1,5 @@+import {stageInput,type UserInput} from "./attachments.js";+import {HarnessError} from "./types.js";import { ServiceObservability } from "./observability.js";/** Authenticated remote service handles. The service owns all execution and policy. */import { randomUUID } from "node:crypto";@@ -712,14 +714,19 @@ export class ServiceSession {return this.service.json("GET", `/v1/sessions/${segment(this.id)}`);}async send(- text: string,+ text: string | UserInput,options: { idempotencyKey?: string; limits?: TurnLimits } = {},): Promise<ServiceRun> {const key = options.idempotencyKey ?? randomUUID();+ let content:Record<string,unknown>[]|undefined;+ if(typeof text!=="string"){+ if(this.service.capabilities.features?.attachments!==true)throw new HarnessError("Setup","Service does not support attachments");+ content=await stageInput(text,this.id,(_method,args)=>this.service.json("POST",`/v1/sessions/${segment(this.id)}/attachments/${segment(String(args.id))}`,args.upload));+ }const r = await this.service.json("POST",`/v1/sessions/${segment(this.id)}/turns`,- { text, limits: options.limits },+ { text:typeof text==="string"?text:undefined, content, limits: options.limits },key,);return new ServiceRun(this.service, this.ref, r.submissionId, r.runId);diff --git a/harness/typescript-sdk/src/transport.ts b/harness/typescript-sdk/src/transport.tsindex c2a089de..ed53712e 100644--- a/harness/typescript-sdk/src/transport.ts+++ b/harness/typescript-sdk/src/transport.ts@@ -331,7 +331,7 @@ export class Transport {p.reject(new HarnessError("Remote",- diagnostic ? `Provider ${diagnostic.category}${diagnostic.httpStatus ? ` (HTTP ${diagnostic.httpStatus})` : ""}` : "Harness rejected the request; inspect its configuration or durable session state",+ typeof frame.error === "object" && "attachment_inspection_unsupported" in frame.error && frame.error.attachment_inspection_unsupported === true ? "Binary attachments cannot be inspected by configured text-only input guardrails" : diagnostic ? `Provider ${diagnostic.category}${diagnostic.httpStatus ? ` (HTTP ${diagnostic.httpStatus})` : ""}` : "Harness rejected the request; inspect its configuration or durable session state",diagnostic ? { providerError: diagnostic } : undefined,),);diff --git a/harness/typescript-sdk/src/types.ts b/harness/typescript-sdk/src/types.tsindex 2295394a..8b7f49ca 100644--- a/harness/typescript-sdk/src/types.ts+++ b/harness/typescript-sdk/src/types.ts@@ -264,7 +264,7 @@ export interface RunOptions extends SafetyOptions {/** Stops waiting only. Call session.cancel() to cancel agent execution. */signal?: AbortSignal;}-export type MessageInput = string | { type?: "message"; text: string };+export type MessageInput = string | { type?: "message"; text: string } | import("./attachments.js").UserInput;export interface OutputOptions {reasoning?: boolean;bufferAttempts?: boolean;diff --git a/harness/typescript-sdk/test/attachments.test.mjs b/harness/typescript-sdk/test/attachments.test.mjsnew file mode 100644index 00000000..724a9421--- /dev/null+++ b/harness/typescript-sdk/test/attachments.test.mjs@@ -0,0 +1,444 @@+// Actual managed Rust process + deterministic streaming provider fixtures.+import test from "node:test";+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Harness, Attachment, guard, hook } from "../dist/index.js";+import { stageInput } from "../dist/attachments.js";+const png = Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aM9sAAAAASUVORK5CYII=",+ "base64",+);+const pdf = Buffer.from("%PDF-1.4\n1 0 obj<</Type/Catalog>>endobj\n%%EOF");+const image = () =>+ Attachment.fromBytes({+ name: "screen.png",+ mediaType: "image/png",+ data: png,+ });+const report = () =>+ Attachment.fromBytes({+ name: "report.pdf",+ mediaType: "application/pdf",+ data: pdf,+ });+const opts = { skip: !process.env.OW_TS_TEST_HOST, timeout: 120000 };+function frames(api) {+ const f = (v) => `data: ${JSON.stringify(v)}\n\n`;+ if (api === "responses")+ return (+ f({ type: "response.output_text.delta", delta: "Understood." }) ++ f({+ type: "response.completed",+ response: {+ status: "completed",+ output: [+ {+ type: "message",+ role: "assistant",+ content: [{ type: "output_text", text: "Understood." }],+ },+ ],+ usage: { input_tokens: 20, output_tokens: 4 },+ },+ })+ );+ if (api === "chat-completions")+ return (+ f({+ id: "fixture",+ choices: [+ {+ index: 0,+ delta: { content: "Understood." },+ finish_reason: "stop",+ },+ ],+ }) + "data: [DONE]\n\n"+ );+ return (+ f({+ type: "message_start",+ message: {+ role: "assistant",+ content: [],+ usage: { input_tokens: 20, output_tokens: 0 },+ },+ }) ++ f({+ type: "content_block_start",+ index: 0,+ content_block: { type: "text", text: "" },+ }) ++ f({+ type: "content_block_delta",+ index: 0,+ delta: { type: "text_delta", text: "Understood." },+ }) ++ f({ type: "content_block_stop", index: 0 }) ++ f({+ type: "message_delta",+ delta: { stop_reason: "end_turn" },+ usage: { output_tokens: 4 },+ }) ++ f({ type: "message_stop" })+ );+}+async function fixture(t, api, extra = {}) {+ const root = await mkdtemp(join(tmpdir(), "ow-inputs-"));+ let harness;+ const requests = [];+ const server = createServer(async (req, res) => {+ try {+ let raw = "";+ for await (const c of req) raw += c;+ requests.push(JSON.parse(raw));+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.end(frames(api));+ } catch (e) {+ res.writeHead(500);+ res.end();+ }+ });+ await new Promise((r) => server.listen(0, "127.0.0.1", r));+ t.after(async () => {+ await harness?.shutdown();+ server.closeAllConnections();+ await new Promise((r) => server.close(r));+ await rm(root, { recursive: true, force: true });+ });+ async function start() {+ harness = await Harness.start({+ executable: process.env.OW_TS_TEST_HOST,+ stateDir: root,+ sandbox: "off",+ ...extra,+ });+ await harness.setModelProvider({+ name: "Fixture",+ api,+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`,+ credentials: { apiKey: "fixture-only", storage: "memory" },+ });+ return harness;+ }+ await start();+ const agent = () =>+ harness.createAgent({+ name: "reader",+ instructions: "Explain attached content.",+ tools: [],+ builtinTools: { askUser: false, readHistory: false },+ planning: false,+ memory: false,+ scheduling: false,+ defaultModel: { provider: "Fixture", name: "fixture" },+ });+ return {+ requests,+ root,+ agent,+ start,+ get harness() {+ return harness;+ },+ };+}+for (const api of ["responses", "chat-completions", "anthropic"])+ test(+ `${api}: ordered images, PDFs and text survive replay and restart`,+ opts,+ async (t) => {+ const f = await fixture(t, api);+ const session = await f.agent().newSession();+ const notes = Attachment.fromBytes({+ name: "notes.md",+ mediaType: "text/plain",+ data: Buffer.from("notes-unique-sentinel"),+ });+ const input = {+ content: [+ { type: "text", text: "First" },+ image(),+ { type: "text", text: "Second" },+ report(),+ notes,+ { type: "text", text: "Last" },+ ],+ };+ const stream = await session.runStreamed(input, {+ submissionId: "ordered",+ });+ const events = [];+ for await (const e of stream) events.push(e);+ assert.equal((await stream.result()).status, "completed");+ const messages = () =>+ api === "responses"+ ? f.requests.at(-1).input+ : f.requests.at(-1).messages;+ const blocks = messages().find((m) => m.role === "user").content;+ assert.deepEqual(+ blocks.map((p) => p.type),+ api === "responses"+ ? [+ "input_text",+ "input_image",+ "input_text",+ "input_file",+ "input_text",+ "input_text",+ ]+ : api === "anthropic"+ ? ["text", "image", "text", "document", "text", "text"]+ : ["text", "image_url", "text", "file", "text", "text"],+ );+ assert.equal(blocks[0].text, "First");+ assert.equal(blocks[2].text, "Second");+ assert.match(blocks[4].text, /notes.md\nnotes-unique-sentinel/);+ assert.equal(blocks[5].text, "Last");+ const data =+ api === "responses"+ ? blocks[3].file_data+ : api === "anthropic"+ ? blocks[3].source.data+ : blocks[3].file.file_data;+ assert.ok(data.endsWith(pdf.toString("base64")), "PDF bytes preserved");+ const snapshot = await f.harness.request("session/attach", {+ session_id: session.id,+ });+ const journal = JSON.stringify(events);+ const raw = JSON.stringify(snapshot);+ for (const serialized of [journal, raw]) {+ assert.ok(!serialized.includes(png.toString("base64")));+ assert.ok(!serialized.includes(pdf.toString("base64")));+ assert.ok(!serialized.includes("notes-unique-sentinel"));+ }+ assert.ok(raw.includes("input_attachment"));+ const before = f.requests.length;+ assert.equal(+ (await session.run(input, { submissionId: "ordered" })).status,+ "completed",+ );+ assert.equal(+ f.requests.length,+ before,+ "Identical retry does not call model",+ );+ await assert.rejects(() =>+ session.run(+ { content: [...input.content, { type: "text", text: "changed" }] },+ { submissionId: "ordered" },+ ),+ );+ const ref = session.reference();+ await f.harness.shutdown();+ await f.start();+ const resumed = await f.harness.resume(ref);+ assert.equal(+ (await resumed.run("Continue after restart.")).status,+ "completed",+ );+ assert.deepEqual(+ messages().find((m) => m.role === "user").content,+ blocks,+ );+ const foreign = await f.agent().newSession();+ const history = snapshot.history ?? snapshot.session?.history;+ const id = raw.match(/att_[a-f0-9]{64}/)?.[0];+ assert.ok(id);+ await assert.rejects(() =>+ foreign.run({+ content: [{ type: "image", source: { type: "attachment", id } }],+ }),+ );+ assert.equal(+ (await resumed.run("One attachment appended.", image())).status,+ "completed",+ );+ },+ );++test(+ "bounded chunks, sealed replay, failed staging and text guardrails",+ opts,+ async (t) => {+ const f = await fixture(t, "chat-completions");+ const session = await f.agent().newSession();+ const big = Buffer.from("bounded-chunk ".repeat(100000));+ const file = join(f.root, "large.txt");+ await writeFile(file, big);+ const a = await Attachment.fromFile(file);+ const run = await session.send({+ content: [{ type: "text", text: "Read" }, a],+ });+ assert.equal((await run.result()).status, "completed");+ assert.ok(JSON.stringify(f.requests.at(-1)).includes("bounded-chunk "));+ const bad = Attachment.fromBytes({+ name: "bad.pdf",+ mediaType: "application/pdf",+ data: Buffer.from("not a PDF"),+ });+ const count = f.requests.length;+ await assert.rejects(() => session.run("Read", bad));+ assert.equal(f.requests.length, count);+ const text = Attachment.fromBytes({+ name: "secret.txt",+ mediaType: "text/plain",+ data: Buffer.from("SECRET_12345"),+ });+ await assert.rejects(() =>+ session.run(+ { content: [text] },+ {+ guardrails: {+ userInput: [guard.regex({ name: "deny", pattern: "SECRET_" })],+ },+ },+ ),+ );+ assert.equal(f.requests.length, count);+ const otherText = Attachment.fromBytes({+ name: "other.txt",+ mediaType: "text/plain",+ data: Buffer.from("SECRET_12345"),+ });+ const safe = await session.run(+ { content: [text, otherText] },+ {+ guardrails: {+ userInput: [+ guard.regex({+ name: "hide",+ pattern: "SECRET_[0-9]+",+ action: "redact",+ }),+ ],+ },+ },+ );+ assert.equal(safe.status, "completed");+ assert.ok(+ !JSON.stringify(f.requests.at(-1).messages.at(-1)).includes(+ "SECRET_12345",+ ),+ );+ await assert.rejects(+ () =>+ session.run("Inspect", image(), {+ guardrails: {+ userInput: [guard.regex({ name: "required", pattern: "DENY" })],+ },+ }),+ /Binary attachments/,+ );+ const priorImage = await f.agent().newSession();+ assert.equal(+ (await priorImage.run("Inspect", image())).status,+ "completed",+ );+ const priorCount = f.requests.length;+ const blockedReplay = await priorImage.run("Inspect previous input again", {+ hooks: [+ hook.beforeModel({+ name: "required-model-input",+ run: () => ({ action: "allow" }),+ }),+ ],+ });+ assert.notEqual(blockedReplay.status, "completed");+ assert.equal(+ f.requests.length,+ priorCount,+ "A new model-input policy also covers binary history from earlier turns",+ );+ const aborted = new AbortController();+ aborted.abort();+ await assert.rejects(+ () => session.run("Stop", image(), { signal: aborted.signal }),+ (e) => e.code === "Aborted",+ );+ },+);++test("input validation is local and uploads never exceed the frame bound", async () => {+ const send = [];+ const req = async (m, p) => {+ send.push([m, p]);+ return {};+ };+ await stageInput(+ {+ content: [+ Attachment.fromBytes({+ name: "large.txt",+ mediaType: "text/plain",+ data: Buffer.alloc(1200000, 65),+ }),+ ],+ },+ "s",+ req,+ );+ assert.ok(send.length > 4);+ for (const [, p] of send)+ assert.ok(Buffer.byteLength(JSON.stringify(p)) < 400000);+ for (const input of [+ { content: [] },+ { content: [{ type: "text", text: "ok" }], text: "mixed" },+ {+ content: [+ {+ type: "document",+ source: { type: "base64", mediaType: "text/plain", data: "!!!" },+ },+ ],+ },+ { content: [{ type: "text", text: "x".repeat(32001) }] },+ ])+ await assert.rejects(() => stageInput(input, "s", req));+ assert.throws(() =>+ Attachment.fromBytes({+ name: "../escape",+ mediaType: "text/plain",+ data: Buffer.from("x"),+ }),+ );+ assert.throws(() =>+ Attachment.fromBytes({+ name: "bad.txt",+ mediaType: "text/plain",+ data: Buffer.from([0xff]),+ }),+ );+ assert.throws(() =>+ Attachment.fromBytes({+ name: "bad.zip",+ mediaType: "application/zip",+ data: Buffer.from("x"),+ }),+ );+});++test("cancelling during the final upload commit prevents turn submission", async () => {+ const controller = new AbortController();+ let commits = 0;+ await assert.rejects(+ () =>+ stageInput(+ { content: [image()] },+ "s",+ async (_m, p) => {+ if (p.upload.operation === "commit") {+ commits++;+ controller.abort();+ }+ return {};+ },+ controller.signal,+ ),+ (e) => e.code === "Aborted",+ );+ assert.equal(commits, 1);+});diff --git a/harness/typescript-sdk/test/service.test.mjs b/harness/typescript-sdk/test/service.test.mjsindex 7ba66987..9bece7bf 100644--- a/harness/typescript-sdk/test/service.test.mjs+++ b/harness/typescript-sdk/test/service.test.mjs@@ -289,3 +289,26 @@ test("coding defaults and submitted-source selection preserve independent checkoawait team.submissions({after:"hs_original",limit:5});assert.deepEqual(requests[2],{operation:"team_list_submissions",arguments:{after:"hs_original",limit:5}});}finally{service.disconnect();}});++test("service attachments use bounded authenticated uploads before submitting references",async t=>{+ const {Attachment}=await import("../dist/index.js");const uploads=[];let submitted;+ const url=await server(t,(req,res)=>{+ headers(res);+ if(req.url==="/v1/capabilities"){res.end(JSON.stringify({apiVersion:"1",namespace:"test",serviceId:"service-one",agent:"reader",features:{attachments:true}}));return;}+ if(handshake(req,res))return;+ if(req.url==="/v1/agents/reader"){res.end('{"id":"reader"}');return;}+ if(req.url==="/v1/sessions/s_one"&&req.method==="GET"){res.end('{"session":{"environment":{"environment_id":"env"}}}');return;}+ assert.equal(req.headers.authorization,`Bearer ${token}`);+ let raw="";req.on("data",c=>raw+=c);req.on("end",()=>{+ const body=JSON.parse(raw);assert.ok(Buffer.byteLength(raw)<400000);+ if(req.url.startsWith("/v1/sessions/s_one/attachments/")){uploads.push(body);res.end('{}');}+ else {assert.equal(req.url,"/v1/sessions/s_one/turns");assert.equal(req.headers["idempotency-key"],"original-input");submitted=body;res.end('{"runId":"run-one","submissionId":"receipt-one"}');}+ });+ });+ const service=await Harness.connect(options(url));+ try{+ const session=await service.resume({serviceId:"service-one",namespace:"test",sessionId:"s_one",agent:"reader",environmentId:"env"});+ const run=await session.send({content:[{type:"text",text:"Before"},Attachment.fromBytes({name:"notes.txt",mediaType:"text/plain",data:Buffer.from("hello")}),{type:"text",text:"After"}]},{idempotencyKey:"original-input"});+ assert.equal(run.id,"run-one");assert.deepEqual(uploads.map(v=>v.operation),["begin","chunk","commit"]);assert.deepEqual(submitted.content.map(v=>v.type),["text","document","text"]);assert.ok(submitted.content[1].attachment_id.startsWith("att_"));assert.ok(!JSON.stringify(submitted).includes("aGVsbG8="));+ }finally{service.disconnect();}+});