diff --git a/apps/albedo/src/albedo/http/http_wire.gleam b/apps/albedo/src/albedo/http/http_wire.gleam index caa9cb740..a58fbc304 100644 --- a/apps/albedo/src/albedo/http/http_wire.gleam +++ b/apps/albedo/src/albedo/http/http_wire.gleam @@ -479,6 +479,7 @@ pub fn context(snapshot: context_snapshot.Snapshot) -> json.Json { compacted, sections, _, + _, ) -> json.object([ #("state", json.string("ready")), diff --git a/apps/albedo/src/albedo/kernel.gleam b/apps/albedo/src/albedo/kernel.gleam index c9c4882b5..4360fd326 100644 --- a/apps/albedo/src/albedo/kernel.gleam +++ b/apps/albedo/src/albedo/kernel.gleam @@ -136,14 +136,25 @@ pub fn execute( code: String, timeout_ms: Int, ) -> Result(Outcome, Error) { - run(kernel, id, code, timeout_ms, False, types.any_images, False, None) + run( + kernel, + id, + code, + timeout_ms, + False, + types.any_images, + types.request_clip_budget, + False, + None, + ) |> result.map(fn(ran) { ran.0 }) } /// `images` are the session provider's limits: `show_image` refuses an image /// over them, or any image for a model that reads text only, and `show_media` /// a clip of a type the model does not read, at the call, so the cell fails -/// where the model can see why. +/// where the model can see why. `show_media` also refuses clips past +/// `clip_room`, the base64 bytes the session's next request has room for. /// A failed cell also names the saved cell the error came from, which is a /// `cells.run` copy when the failure was nested. With `save`, the cell row is /// written in the commit that saves the frame executing it instead of before. @@ -153,6 +164,7 @@ pub fn execute_saved( code: String, timeout_ms: Int, images: types.ImageLimits, + clip_room: Int, snapshots: Bool, save: Bool, ) -> Result(#(Outcome, Option(String)), Error) { @@ -160,7 +172,7 @@ pub fn execute_saved( True -> Some(code) False -> None } - run(kernel, id, code, timeout_ms, True, images, snapshots, save) + run(kernel, id, code, timeout_ms, True, images, clip_room, snapshots, save) } fn run( @@ -170,6 +182,7 @@ fn run( timeout_ms: Int, durable: Bool, images: types.ImageLimits, + clip_room: Int, snapshots: Bool, save: Option(String), ) -> Result(#(Outcome, Option(String)), Error) { @@ -188,6 +201,7 @@ fn run( #("text_only", json.bool(images.max_images == Some(0))), #("media", json.array(images.media, json.string)), #("max_fps", json.nullable(images.fidelity.max_fps, json.float)), + #("clip_room", json.int(int.max(clip_room, 0))), #("snapshots", json.bool(snapshots)), #("timeout_ms", json.int(timeout_ms)), ]) diff --git a/apps/albedo/src/albedo/kernel/python_tool.gleam b/apps/albedo/src/albedo/kernel/python_tool.gleam index 8cfaa33c4..a25b97085 100644 --- a/apps/albedo/src/albedo/kernel/python_tool.gleam +++ b/apps/albedo/src/albedo/kernel/python_tool.gleam @@ -135,6 +135,7 @@ fn invoke( code, timeout_ms, context.images, + context.clip_room, case conversation.acp_marker(context.storage, context.session) { Ok(Some(_)) -> True _ -> False @@ -186,8 +187,9 @@ fn invoke( } /// The cell's JSON result with its images beside it. An image or clip the -/// provider would refuse stays back and is reported with the unreadable ones, -/// so the model can show a smaller one, or one it reads, instead. +/// provider would refuse, or a clip past the room the session's requests have +/// left, stays back and is reported with the unreadable ones, so the model +/// can show a smaller one, or one it reads, instead. fn outcome_output( context: extension.Context, id: String, @@ -204,10 +206,11 @@ fn outcome_output( None -> #([image, ..kept.0], kept.1) } }) + let #(images, over) = within_room(images, context.clip_room) python.Outcome( ..outcome, images: images, - image_errors: list.append(outcome.image_errors, refusals), + image_errors: list.flatten([outcome.image_errors, refusals, over]), ) }) let images = case outcome { @@ -241,6 +244,36 @@ fn outcome_output( ) } +/// The images whose clips, in order, fit in `room` base64 bytes, and why +/// each clip past it stays back. +pub fn within_room( + images: List(types.Image), + room: Int, +) -> #(List(types.Image), List(String)) { + let held = types.request_clip_budget - room + let #(_, kept, over) = + list.fold(images, #(0, [], []), fn(acc, image) { + let #(adding, kept, over) = acc + let size = types.image_size(image) + let #(mime_type, _, _, _) = types.image_meta(image) + case types.media_kind(image) { + types.Picture -> #(adding, [image, ..kept], over) + _ -> + case types.clip_budget_refusal(held, adding + size) { + None -> #(adding + size, [image, ..kept], over) + Some(reason) -> #(adding, kept, [ + mime_type + <> " clip not attached: " + <> reason + <> "; await commands.shake() lists the session's media and drops what it no longer needs", + ..over + ]) + } + } + }) + #(list.reverse(kept), list.reverse(over)) +} + fn outcome_json( id: String, outcome: Result(python.Outcome, python.Error), diff --git a/apps/albedo/src/albedo/model_loop/loop.gleam b/apps/albedo/src/albedo/model_loop/loop.gleam index 78f519ffb..bbca9f817 100644 --- a/apps/albedo/src/albedo/model_loop/loop.gleam +++ b/apps/albedo/src/albedo/model_loop/loop.gleam @@ -629,18 +629,37 @@ fn converse( )) } calls -> { - use ran <- result.try( + let limits = state.upstream.images + let held = runtime.clips_held(state.host, limits, history) + use #(ran, _) <- result.try( plain( - list.try_map(calls, fn(call) { + list.try_fold(calls, #([], held), fn(acc, call) { + let #(ran, held) = acc let output_index = list.find(turn.call_indices, fn(binding) { binding.0 == call.id }) case output_index { - Ok(binding) -> run_tool(state, id, step, attempt, binding.1, call) + Ok(binding) -> { + let room = types.request_clip_budget - held + use item <- result.map(run_tool( + state, + id, + step, + attempt, + binding.1, + call, + room, + )) + #( + [item, ..ran], + held + runtime.clips_held(state.host, limits, [item.0.input]), + ) + } Error(_) -> Error("provider completed a tool call without its output index") } }), - ), + ) + |> result.map(fn(folded) { #(list.reverse(folded.0), folded.1) }), ) let results = list.map(ran, fn(item) { item.0 }) let #(repeats, repeated) = @@ -973,6 +992,7 @@ fn run_tool( attempt: Int, output_index: Int, call: types.ToolCall, + clip_room: Int, ) -> Result( #(transcript.Entry, List(Told), Result(repetition.Cell, Nil)), String, @@ -988,7 +1008,7 @@ fn run_tool( case state.progress_running(step, attempt, output_index, call.id, call.name) { False -> Error("cancelled before tool execution") True -> { - let invoked = invoke(state, call) + let invoked = invoke(state, call, clip_room) // Drop the running projection before committing the result. A reset // racing with that commit must not snapshot the just-finished call. state.progress_finish(progress_id) @@ -1119,7 +1139,11 @@ type Invoked { ) } -fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { +fn invoke( + state: Loop, + call: types.ToolCall, + clip_room: Int, +) -> Result(Invoked, String) { // Before the hooks, so they judge the cell that runs. let call = runtime.as_cell(state.prepared, call) let asked = hook.Call(call.id, call.name, call.arguments, None) @@ -1141,7 +1165,13 @@ fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { // next checkpoint. Error(why) -> Ok(#(refused(call, why), True)) Ok(kernel) -> - runtime.invoke(state.host, kernel, call, state.upstream.images) + runtime.invoke( + state.host, + kernel, + call, + state.upstream.images, + clip_room, + ) } }) let body = case output { diff --git a/apps/albedo/src/albedo/observation/context_snapshot.gleam b/apps/albedo/src/albedo/observation/context_snapshot.gleam index a11b4e5e5..e62fbe5b0 100644 --- a/apps/albedo/src/albedo/observation/context_snapshot.gleam +++ b/apps/albedo/src/albedo/observation/context_snapshot.gleam @@ -97,6 +97,7 @@ pub type Snapshot { compaction: Compaction, sections: List(Section), retained_tool_calls: List(String), + retained_clips: List(String), ) } @@ -236,6 +237,7 @@ fn ready( compaction, sections, [], + [], ) } @@ -269,6 +271,15 @@ pub fn from_request( _ -> Error(Nil) } }) + let clips = + list.flat_map(request.input, fn(input) { + case input { + types.UserImage(_, images) | types.ToolOutput(_, _, images) -> images + _ -> [] + } + }) + |> list.filter(fn(image) { types.media_kind(image) != types.Picture }) + |> list.map(types.image_identity) let sections = [ instructions_section(request.instructions), @@ -287,7 +298,8 @@ pub fn from_request( sections, ) { - Ready(..) as snapshot -> Ready(..snapshot, retained_tool_calls: calls) + Ready(..) as snapshot -> + Ready(..snapshot, retained_tool_calls: calls, retained_clips: clips) pending -> pending } } @@ -362,6 +374,18 @@ fn instructions_section(instructions: Option(String)) -> Option(Section) { } } +pub fn retained_clips( + snapshot: Snapshot, + model: String, +) -> Option(#(Int, List(String))) { + case snapshot { + Ready(captured_at: Some(at), model: prepared, retained_clips: clips, ..) + if prepared == model + -> Some(#(at, clips)) + _ -> None + } +} + /// Tool calls in the exact prepared request, not in the durable history. pub fn retained_tool_calls(snapshot: Snapshot) -> Option(List(String)) { case snapshot { @@ -510,6 +534,7 @@ pub fn summary(snapshot: Snapshot) -> json.Json { compacted, sections, _, + _, ) -> // Optional detail fields lead the wire order; absent ones are omitted. json.object( diff --git a/apps/albedo/src/albedo/runtime.gleam b/apps/albedo/src/albedo/runtime.gleam index 16a1569cf..ea6ba4d32 100644 --- a/apps/albedo/src/albedo/runtime.gleam +++ b/apps/albedo/src/albedo/runtime.gleam @@ -979,6 +979,7 @@ pub fn execute( code, timeout_ms, types.any_images, + types.request_clip_budget, False, False, ) @@ -1791,6 +1792,7 @@ fn tool_call( session: Session, call: types.ToolCall, images: types.ImageLimits, + clip_room: Int, ) -> Result(#(extension.Tool, extension.Context), Nil) { composition.tool(session.composition, call.name) |> result.map(fn(tool) { @@ -1802,21 +1804,22 @@ fn tool_call( call.id, session.cwd, images, + clip_room, extension.unscoped(runtime.ledger), ), ) }) } -/// Runs `call`; `images` are what the provider its result goes to accepts. pub fn invoke( runtime: Runtime, session: Session, call: types.ToolCall, images: types.ImageLimits, + clip_room: Int, ) -> Result(#(types.Input, Bool), String) { use _ <- result.try(owned_by(runtime, session.owner)) - case tool_call(runtime, session, call, images) { + case tool_call(runtime, session, call, images, clip_room) { Error(_) -> Ok(#( refusal( @@ -1913,12 +1916,13 @@ pub fn recover_all( session: Session, calls: List(types.ToolCall), images: types.ImageLimits, + clip_room: Int, ) -> List(#(types.Input, Bool)) { case calls { [] -> [] _ -> { python.open_claims(session.kernel) - list.map(calls, recover(runtime, session, _, images)) + list.map(calls, recover(runtime, session, _, images, clip_room)) } } } @@ -1928,8 +1932,9 @@ fn recover( session: Session, call: types.ToolCall, images: types.ImageLimits, + clip_room: Int, ) -> #(types.Input, Bool) { - let saved = case tool_call(runtime, session, call, images) { + let saved = case tool_call(runtime, session, call, images, clip_room) { Ok(#(tool, context)) -> extension.recover(tool, context) Error(_) -> None } @@ -2680,10 +2685,10 @@ fn media_read() -> memo.Memo(List(String)) { const media_read_ms = 604_800_000 /// Every request leaves without what the upstream cannot read, whoever built -/// it, so a clip in history never reaches a model that would refuse it, and -/// a history of clips never grows a request past what a provider takes. A +/// it, so a clip in history never reaches a model that would refuse it. A /// clip goes as the copy its model takes in (`media_copies`), so the budget -/// counts what is sent. +/// counts what is sent. Admission keeps a history's clips within the budget +/// (`clips_held`); the trim here only bounds one that is past it already. fn readable_requests( upstream: extension.Upstream, ledger: store.Store, @@ -2728,6 +2733,15 @@ fn readable_requests( ) } +/// before the budget trim, which readable_requests applies on send. +pub fn clips_held( + runtime: Runtime, + limits: types.ImageLimits, + inputs: List(types.Input), +) -> Int { + media_copies.held(ledger(runtime), limits, inputs) +} + fn capacity(info: Option(extension.ModelInfo)) -> Option(compaction.Capacity) { use info <- option.then(info) use tokens <- option.map(selection.window(info)) diff --git a/apps/albedo/src/albedo/runtime/media_copies.gleam b/apps/albedo/src/albedo/runtime/media_copies.gleam index 4be7d6d8a..c844a4a99 100644 --- a/apps/albedo/src/albedo/runtime/media_copies.gleam +++ b/apps/albedo/src/albedo/runtime/media_copies.gleam @@ -89,6 +89,45 @@ pub fn apply( }) } +/// The base64 bytes of the clips `inputs` hold as `limits`' model receives +/// them: each as the copy made for it, or as it is when none was. It reads no +/// payload and encodes nothing, so admission can sum a whole history. +pub fn held( + ledger: store.Store, + limits: types.ImageLimits, + inputs: List(types.Input), +) -> Int { + list.fold(inputs, 0, fn(total, input) { + case types.readable_input(limits, input) { + types.UserImage(_, images) | types.ToolOutput(_, _, images) -> + list.fold(images, total, fn(total, image) { + case types.media_kind(image) { + types.Picture -> total + _ -> total + sent_size(ledger, limits, image) + } + }) + _ -> total + } + }) +} + +/// A stored clip's copy may already be made; an inline one is new. +fn sent_size( + ledger: store.Store, + limits: types.ImageLimits, + image: types.Image, +) -> Int { + let copied = case types.image_data(image), plan(limits, image) { + types.StoredData(hash:, ..), Some(plan) -> + case stored_images.copy(ledger, hash, plan.profile) { + Ok(Some(stored_images.Copied(bytes:, ..))) -> Some(base64_size(bytes)) + _ -> None + } + _, _ -> None + } + option.unwrap(copied, types.image_size(image)) +} + fn swap( ledger: store.Store, limits: types.ImageLimits, @@ -230,7 +269,7 @@ fn copied( types.stored_image( mime_type, hash, - 4 * { { bytes + 2 } / 3 }, + base64_size(bytes), fn() { stored_images.copy_payload(ledger, source, plan.profile) }, 0, 0, @@ -335,6 +374,10 @@ fn readable( } } +fn base64_size(bytes: Int) -> Int { + 4 * { { bytes + 2 } / 3 } +} + fn payload(image: types.Image) -> Result(BitArray, Nil) { case types.image_data(image) { types.InlineData(data) -> Ok(data) diff --git a/apps/albedo/src/albedo/session.gleam b/apps/albedo/src/albedo/session.gleam index 64c7df5dc..d3be7de17 100644 --- a/apps/albedo/src/albedo/session.gleam +++ b/apps/albedo/src/albedo/session.gleam @@ -4935,28 +4935,65 @@ fn family_closed(state: State) -> Result(Bool, String) { /// Why the session's provider would refuse one of the submission's images or /// clips, so it is turned away before the transcript keeps it rather than -/// failing every request after. +/// failing every request after; or why its clips would take the session's +/// next request past its clip budget, so no later request has to leave an +/// older clip out and change what the provider cached. fn refused_image( state: State, submission: Submission, -) -> #(State, Option(String)) { +) -> #(State, Option(operations.Rejection)) { case submission.images { [] -> #(state, None) images -> case session_provider.configured_client(state) { // Without a provider the turn is refused on its own when it starts. Error(_) -> #(state, None) - Ok(#(state, client)) -> #( - state, - list.find_map(images, fn(image) { - types.media_refusal(client.images, image) |> option.to_result(Nil) - }) - |> option.from_result, - ) + Ok(#(state, client)) -> + case + list.find_map(images, fn(image) { + types.media_refusal(client.images, image) |> option.to_result(Nil) + }) + { + Ok(reason) -> #( + state, + Some(operations.Rejection(409, "image_rejected", reason)), + ) + Error(Nil) -> over_clip_budget(state, client.images, images) + } } } } +fn over_clip_budget( + state: State, + limits: types.ImageLimits, + images: List(types.Image), +) -> #(State, Option(operations.Rejection)) { + let adding = + runtime.clips_held(state.host, limits, [types.UserImage("", images)]) + use <- bool.guard(adding == 0, #(state, None)) + case session_history.ensure_history(state) { + // an unreadable history fails the turn when it starts instead. + Error(_) -> #(state, None) + Ok(state) -> { + let held = + types.request_clip_budget - session_history.clip_room(state, limits) + #( + state, + types.clip_budget_refusal(held, adding) + |> option.map(fn(reason) { + operations.Rejection( + 409, + "media_budget", + reason + <> "; /shake lists the session's media and drops what it no longer needs", + ) + }), + ) + } + } +} + /// The resumed turn reads the restart notice first, ahead of everything that /// waited in the inbox. fn resume(state: State) -> State { @@ -5185,7 +5222,7 @@ fn prepare_turn_pipeline( Some(_) if state.results_settled -> [] Some(held) -> session_history.recover_pending( - state.host, + state, session_history.unanswered(state), held, client.images, @@ -6519,8 +6556,7 @@ fn admit_operation( Some(session_creation.rejection( refusal.AttachmentWorkspaceUnsupported, )) - _, Some(reason), _ -> - Some(operations.Rejection(409, "image_rejected", reason)) + _, Some(rejection), _ -> Some(rejection) _, _, turn.Reject(turn.Oversized) -> Some(operations.Rejection( 413, diff --git a/apps/albedo/src/albedo/session/session_history.gleam b/apps/albedo/src/albedo/session/session_history.gleam index e080d9fd2..349334306 100644 --- a/apps/albedo/src/albedo/session/session_history.gleam +++ b/apps/albedo/src/albedo/session/session_history.gleam @@ -8,6 +8,7 @@ import albedo/history/tool_results import albedo/http/http_history import albedo/model_loop/loop import albedo/observation/active_output +import albedo/observation/context_snapshot import albedo/observation/events as view import albedo/runtime import albedo/session/session_state @@ -122,12 +123,59 @@ pub fn unanswered(state: session_state.State(message)) -> List(types.ToolCall) { } pub fn recover_pending( - host: runtime.Runtime, + state: session_state.State(message), calls: List(types.ToolCall), kernel: runtime.Session, images: types.ImageLimits, ) -> List(#(types.Input, Bool)) { - runtime.recover_all(host, kernel, calls, images) + runtime.recover_all( + state.host, + kernel, + calls, + images, + clip_room(state, images), + ) +} + +pub fn clip_room( + state: session_state.State(message), + limits: types.ImageLimits, +) -> Int { + let held = case state.history { + Some(entries) -> + runtime.clips_held(state.host, limits, carried(state, entries)) + None -> 0 + } + types.request_clip_budget - held +} + +fn carried( + state: session_state.State(message), + entries: List(transcript.Entry), +) -> List(types.Input) { + case context_snapshot.retained_clips(state.context, state.info.model) { + None -> list.map(entries, fn(entry) { entry.input }) + Some(#(prepared_at, kept)) -> + list.map(entries, fn(entry) { + case entry.timestamp { + Some(at) if at >= prepared_at -> entry.input + _ -> + types.UserImage( + "", + list.filter(shown(entry.input), fn(image) { + list.contains(kept, types.image_identity(image)) + }), + ) + } + }) + } +} + +fn shown(input: types.Input) -> List(types.Image) { + case input { + types.UserImage(_, images) | types.ToolOutput(_, _, images) -> images + _ -> [] + } } /// What a kernel adopting the session learns of a transcript it holds. diff --git a/apps/albedo/test/albedo/composition/extension_failure_test.gleam b/apps/albedo/test/albedo/composition/extension_failure_test.gleam index 5c2b043a0..b0c63fd98 100644 --- a/apps/albedo/test/albedo/composition/extension_failure_test.gleam +++ b/apps/albedo/test/albedo/composition/extension_failure_test.gleam @@ -144,6 +144,7 @@ fn answer( session, types.ToolCall("call_1", name, "{}"), types.any_images, + types.request_clip_budget, ) body } @@ -232,6 +233,7 @@ pub fn a_fatal_tool_still_ends_the_turn_test() -> Nil { session, types.ToolCall("call_1", "record", "{}"), types.any_images, + types.request_clip_budget, ) |> should.equal(Error("transcript storage failed")) runtime.stop(host) diff --git a/apps/albedo/test/albedo/kernel/tool_image_test.gleam b/apps/albedo/test/albedo/kernel/tool_image_test.gleam index 70e0ea7f2..bc8e8059b 100644 --- a/apps/albedo/test/albedo/kernel/tool_image_test.gleam +++ b/apps/albedo/test/albedo/kernel/tool_image_test.gleam @@ -6,6 +6,7 @@ import albedo/kernel/cell_codec import albedo/kernel/cell_status import albedo/kernel/journal as cells import albedo/kernel/migrations/cell_images +import albedo/kernel/python_tool import albedo/storage/core_store import albedo/storage/images import albedo_model as types @@ -183,3 +184,23 @@ fn unpack_cell( ) -> Result(Result(python.Outcome, python.Error), Nil) { cell_codec.unpack(bytes, fn(_) { Error(Nil) }) } + +/// current kernels refuse at the call, and only an older kernel reaches this check. +pub fn clips_past_the_room_stay_back_test() -> Nil { + let clip = fn(size) { + let assert Ok(image) = + types.stored_image("audio/wav", "h", size, fn() { Error(Nil) }, 0, 0, 1) + image + } + let assert Ok(picture) = + types.stored_image("image/png", "p", 900, fn() { Error(Nil) }, 2, 3, 600) + let #(kept, errors) = + python_tool.within_room([clip(60), picture, clip(50), clip(40)], 100) + kept |> should.equal([clip(60), picture, clip(40)]) + let assert [error] = errors + let assert True = + error + == "audio/wav clip not attached: these clips take 0 MiB, and the session's clips already hold 64 MiB of the 64 MiB one request carries; await commands.shake() lists the session's media and drops what it no longer needs" + let #(kept, _) = python_tool.within_room([clip(60)], 0) + kept |> should.equal([]) +} diff --git a/apps/albedo/test/albedo/manual/coding.gleam b/apps/albedo/test/albedo/manual/coding.gleam index 4df6a5ac7..243378697 100644 --- a/apps/albedo/test/albedo/manual/coding.gleam +++ b/apps/albedo/test/albedo/manual/coding.gleam @@ -146,6 +146,7 @@ fn run( session, call, types.any_images, + types.request_clip_budget, )) case output { types.ToolOutput(_, text, _) -> diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index e6252d532..548d53bbd 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -1759,7 +1759,7 @@ type ImageMetadata struct { Width int64 `json:"width"` } -// ImageUpload Strict base64 of a picture, or of a whole audio or video clip; decoded headers and provider constraints are validated before admission. A clip of a type the session's model does not read is refused. +// ImageUpload Strict base64 of a picture, or of a whole audio or video clip; decoded headers and provider constraints are validated before admission. A clip of a type the session's model does not read is refused with 409 image_rejected. Clips that would take what the session's next request carries past 64 MiB of clips are refused with 409 media_budget. type ImageUpload struct { Data string `json:"data"` MimeType string `json:"mime_type"` @@ -4475,7 +4475,7 @@ type Upload struct { Width int64 `json:"width"` } -// UploadReference A picture or clip uploaded to this session beforehand. An upload that is unknown, expired or taken by an earlier message is refused with 409 upload_unknown. +// UploadReference A picture or clip uploaded to this session beforehand. An upload that is unknown, expired or taken by an earlier message is refused with 409 upload_unknown. It is checked as an ImageUpload is. type UploadReference struct { // Upload Client-generated lowercase UUIDv7. Retained decisions are checked before timestamp expiry. Upload UUIDv7 `json:"upload"` diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 08f2b22a6..c33b014d3 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -14026,7 +14026,9 @@ components: description: Strict base64 of a picture, or of a whole audio or video clip; decoded headers and provider constraints are validated before admission. A clip - of a type the session's model does not read is refused. + of a type the session's model does not read is refused with 409 + image_rejected. Clips that would take what the session's next request + carries past 64 MiB of clips are refused with 409 media_budget. required: [mime_type, data] additionalProperties: false UploadReference: @@ -14037,7 +14039,7 @@ components: description: A picture or clip uploaded to this session beforehand. An upload that is unknown, expired or taken by an earlier message is refused with 409 - upload_unknown. + upload_unknown. It is checked as an ImageUpload is. required: [upload] additionalProperties: false MessageImage: diff --git a/e2e/areas.toml b/e2e/areas.toml index 5f5862149..005d6bea4 100644 --- a/e2e/areas.toml +++ b/e2e/areas.toml @@ -25,8 +25,10 @@ "apps/albedo/src/albedo/model_loop/loop.gleam" = [ "compaction_progress_test.py", "integration_test.py", + "media_input_test.py", "photon_test.py", ] +"apps/albedo/src/albedo/runtime/media_copies.gleam" = ["media_input_test.py"] "apps/albedo/src/albedo/lifecycle/host_install.gleam" = [ "standby_test.py", "discord_test.py", diff --git a/e2e/media_input_test.py b/e2e/media_input_test.py index 77e44c917..221ae8987 100644 --- a/e2e/media_input_test.py +++ b/e2e/media_input_test.py @@ -36,10 +36,16 @@ from harness import ( GEMINI = "gemini-media-fixture" CLAUDE = "claude-media-fixture" CHAT = "glm-media-fixture" +# unpriced clips cost a token per 400 bytes, so a full budget needs a big window. +GEMINI_LONG = "gemini-long-media-fixture" +CHAT_LONG = "glm-long-media-fixture" +LONG = (GEMINI_LONG, CHAT_LONG) MODALITIES = { GEMINI: ["text", "image", "audio", "video"], + GEMINI_LONG: ["text", "image", "audio", "video"], CLAUDE: ["text", "image"], CHAT: ["text", "audio"], + CHAT_LONG: ["text", "audio"], } MODELS_DEV = { "fixture": { @@ -48,7 +54,10 @@ MODELS_DEV = { "api": "http://127.0.0.1", "models": { model: { - "limit": {"context": 200000, "output": 4096}, + "limit": { + "context": 2_000_000 if model in LONG else 200000, + "output": 4096, + }, "modalities": {"input": modalities, "output": ["text"]}, } for model, modalities in MODALITIES.items() @@ -120,6 +129,8 @@ SPOKEN_WAV = wav(200_000) SPOKEN_WAV_DATA = base64.b64encode(SPOKEN_WAV).decode() SHORT_MP3 = mp3(3) SHORT_MP3_DATA = base64.b64encode(SHORT_MP3).decode() +# just under 20 MiB: two fill most of the 64 MiB budget as base64, a third won't fit. +FULL_FRAMES = 50_000 FFMPEG = """#!/bin/sh tools=$(dirname "$0") printf '%s\\n' "$*" >> "$tools/calls" @@ -252,11 +263,27 @@ class MediaInputTests(unittest.TestCase): method="PUT", ) + def send_all(self, app: Albedo, session: str, words: str, uploads: list[str]): + return app.api( + f"/sessions/{session}/inputs/{operation_id()}", + { + "kind": "message", + "text": words, + "images": [{"upload": upload} for upload in uploads], + }, + method="PUT", + ) + def refusal(self, call) -> tuple[int, str]: with self.assertRaises(urllib.error.HTTPError) as refused: call().close() return refused.exception.code, json.load(refused.exception)["code"] + def problem(self, call) -> dict: + with self.assertRaises(urllib.error.HTTPError) as refused: + call().close() + return {"status": refused.exception.code, **json.load(refused.exception)} + def test_a_raw_upload_reaches_the_model_once(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() @@ -851,6 +878,43 @@ class MediaInputTests(unittest.TestCase): json.dumps(asking(provider, "on chat")[-1]), ) + def cell_results(self, request: dict) -> list[dict]: + return [ + cell_result(part["functionResponse"]["response"]["output"]) + for content in request["contents"] + for part in content["parts"] + if "functionResponse" in part + ] + + def test_show_media_holds_to_the_room_only_the_clips_it_attaches(self) -> None: + # room for one wav, and a clip shown twice still takes it once. + code = ( + "import albedo_cells\n" + f"albedo_cells.CELL.get().clip_room = {len(WAV_DATA)}\n" + f"print(show_media({WAV!r}, {WAV!r}))\n" + f"show_media({png(2, 2)!r}, {png(3, 3)!r}, {png(4, 4)!r})\n" + f"print(show_media({wav(50)!r}))\n" + ) + app, provider = self.start( + GEMINI, lambda request: text("done") if answered(request) else python(code) + ) + session = app.session() + app.prompt(session, "show them").close() + app.idle(session) + sent = asking(provider, "show them")[-1] + [result] = self.cell_results(sent) + self.assertEqual(result["status"], "ok", result["output"]) + self.assertIn( + f"attached audio/wav, {len(WAV)} bytes\n" + f"already attached audio/wav, {len(WAV)} bytes\n", + result["output"], + ) + self.assertIn( + "not attached, this cell's 4 attachments is full: saved to", + result["output"], + ) + self.assertEqual(len(inline(sent)), 4) + def test_chat_completions_sends_audio_as_input_audio(self) -> None: app, provider = self.start(CHAT, lambda request: text("ok")) session = app.session() @@ -870,6 +934,145 @@ class MediaInputTests(unittest.TestCase): self.attach(app, session, "video/webm", WEBM_DATA).close() self.assertEqual(refused.exception.code, 409) + def test_clips_past_the_request_budget_are_refused_where_they_arrive(self) -> None: + app, provider = self.start(GEMINI_LONG, lambda request: text("ok")) + session = app.session() + full = mp3(FULL_FRAMES) + uploads = [operation_id() for _ in range(3)] + for upload in uploads: + self.upload(app, session, upload, "audio/mpeg", full).close() + + refused = self.problem(lambda: self.send_all(app, session, "all", uploads)) + self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) + self.assertIn("/shake", refused["detail"]) + self.send_all(app, session, "these two", uploads[:2]).close() + app.idle(session) + self.assertEqual(len(inline(asking(provider, "these two")[-1])), 2) + # the history's clips count toward the budget too. + refused = self.problem(lambda: self.send(app, session, "a third", uploads[2])) + self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) + self.assertIn("already hold 53 MiB of the 64 MiB", refused["detail"]) + + # past the kernel's check, the daemon holds the clip back itself. + code = ( + f"{inspect.getsource(mp3)}\n" + "try:\n show_media(mp3(30_000))\n" + "except ValueError as refused:\n print(refused)\n" + "import albedo_cells\n" + "albedo_cells.CELL.get().clip_room = None\n" + "show_media(mp3(30_000))\n" + ) + provider.script = lambda request: ( + text("done") if answered(request) else python(code) + ) + provider.requests.clear() + app.prompt(session, "one more").close() + app.idle(session) + [sent] = [ + request for request in asking(provider, "one more") if answered(request) + ] + self.assertEqual(len(inline(sent)), 2) + result = cell_result( + next( + part["functionResponse"]["response"]["output"] + for content in sent["contents"] + for part in content["parts"] + if "functionResponse" in part + ) + ) + adding = len(base64.b64encode(mp3(30_000))) / 2**20 + room = (64 * 2**20 - 2 * len(base64.b64encode(full))) / 2**20 + self.assertIn( + f"these clips take {adding:.1f} MiB as base64, and the session's next " + f"request has room for {room:.1f} MiB more; await commands.shake()", + result["output"], + ) + [kept_back] = result["image_errors"] + self.assertTrue(kept_back.startswith("audio/mpeg clip not attached: ")) + self.assertIn("await commands.shake()", kept_back) + + def test_clips_a_compaction_left_out_free_their_room(self) -> None: + app, provider = self.start(GEMINI_LONG, lambda request: text("ok")) + session = app.session() + clips = [mp3(FULL_FRAMES + index) for index in range(3)] + uploads = [operation_id() for _ in clips] + for upload, clip in zip(uploads, clips): + self.upload(app, session, upload, "audio/mpeg", clip).close() + for index in range(2): + self.send(app, session, f"clip {index}", uploads[index]).close() + app.idle(session) + held = sum(len(base64.b64encode(clip)) for clip in clips[:2]) + self.assertEqual(self.media(app, session)["clips_held"], held) + for index in range(4): + app.prompt(session, f"filler {index} " + "words " * 50).close() + app.idle(session) + self.assertEqual(app.compact(session)["state"], "compacted") + room = "import albedo_cells\nprint(albedo_cells.CELL.get().clip_room)" + provider.script = lambda request: ( + text("done") if answered(request) else python(room) + ) + app.prompt(session, "after compaction").close() + app.idle(session) + [first, sent] = asking(provider, "after compaction") + self.assertEqual(inline(first), []) + [result] = self.cell_results(sent) + self.assertEqual(result["output"].strip(), str(64 * 1024 * 1024)) + self.assertEqual(self.media(app, session)["clips_held"], 0) + provider.script = lambda request: text("ok") + + # after a restart every clip counts until the next request is prepared. + app.restart() + self.assertEqual(self.media(app, session)["clips_held"], held) + refused = self.problem(lambda: self.send(app, session, "a third", uploads[2])) + self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) + app.prompt(session, "after the restart").close() + app.idle(session) + with self.send(app, session, "a third", uploads[2]) as response: + self.assertEqual(response.status, 202) + + def test_a_history_past_the_budget_after_a_switch_is_trimmed_the_same_each_time( + self, + ) -> None: + app, provider = self.start(CHAT_LONG, lambda request: text("ok")) + # chat is sent small copies, so three long wavs fit beside each other. + self.encodes(app, "mp3", mp3(3)) + session = app.session() + clips = [wav(10_400_000 + index) for index in range(3)] + for index, clip in enumerate(clips): + upload = operation_id() + self.upload(app, session, upload, "audio/wav", clip).close() + with self.send(app, session, f"clip {index}", upload) as response: + self.assertEqual(response.status, 202) + app.idle(session) + + # with the copies gone, gemini is sent the originals, past the budget. + (app.root / "media-tools" / "encoded.mp3").unlink() + self.use(app, session, GEMINI_LONG) + provider.requests.clear() + for words in ("first after", "second after"): + app.prompt(session, words).close() + app.idle(session) + first, second = ( + asking(provider, "first after")[0], + asking(provider, "second after")[-1], + ) + + def digests(clips: list[bytes]) -> list[str]: + return [hashlib.sha256(clip).hexdigest() for clip in clips] + + sent = [base64.b64decode(data) for _, data in inline(first)] + self.assertEqual(digests(sent), digests(clips[1:])) + self.assertIn( + "[1 clip(s) omitted: newer clips fill this request's media budget]", + json.dumps(first["contents"][0]), + ) + # nothing joins a history past the budget, so the trim stays put. + self.assertEqual( + second["contents"][: len(first["contents"])], first["contents"] + ) + refused = self.problem(lambda: self.attach(app, session, "audio/wav", WAV_DATA)) + self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) + if __name__ == "__main__": unittest.main() diff --git a/packages/albedo_model/src/albedo_model.gleam b/packages/albedo_model/src/albedo_model.gleam index e66b7fa5d..2c8ee4aa2 100644 --- a/packages/albedo_model/src/albedo_model.gleam +++ b/packages/albedo_model/src/albedo_model.gleam @@ -69,8 +69,10 @@ pub const max_clip_bytes = 20_971_520 pub const max_clip_encoded_bytes = 27_962_028 /// The most base64 bytes of clips one request carries: Antigravity took a -/// 100 MB request, and two clips at the bound fit with room for the rest. -/// Older clips past it become a note, so a session full of clips still sends. +/// 100 MB request, and two clips at the bound fit with room for the rest. A +/// clip that would take a session's history past it is refused where it +/// arrives, so a clip in history is never dropped from a later request to +/// make room for a newer one (`within_clip_budget`). pub const request_clip_budget = 67_108_864 pub const max_image_edge = 16_384 @@ -322,7 +324,11 @@ fn sampled(most: Option(Float), image: Image) -> #(Image, String) { } /// `inputs`, oldest first, with the newest clips within -/// `request_clip_budget` and the older ones a note in their message. +/// `request_clip_budget` and the older ones a note in their message. Clips +/// are refused where they arrive once they would not fit, so this trims only +/// a history already past the budget: after a switch to a model that is sent +/// larger copies or the originals, or once ffmpeg is gone. Nothing joins such +/// a history until it fits again, so every request trims it the same way. pub fn within_clip_budget(inputs: List(Input)) -> List(Input) { inputs |> list.reverse @@ -370,6 +376,29 @@ fn budgeted(spent: Int, images: List(Image)) -> #(Int, List(Image), String) { #(spent, kept, note) } +/// Why clips of `adding` base64 bytes do not join a history whose clips +/// already hold `held` bytes of `request_clip_budget`, or `None` when they fit. +pub fn clip_budget_refusal(held: Int, adding: Int) -> Option(String) { + case adding > 0 && held + adding > request_clip_budget { + False -> None + True -> + Some( + "these clips take " + <> mebibytes(adding) + <> ", and the session's clips already hold " + <> mebibytes(held) + <> " of the " + <> mebibytes(request_clip_budget) + <> " one request carries", + ) + } +} + +/// `bytes` in MiB to one decimal, without a trailing `.0`. +pub fn mebibytes(bytes: Int) -> String { + decimal(float.to_precision(int.to_float(bytes) /. 1_048_576.0, 1)) <> " MiB" +} + /// The images a provider held to `limits` reads, and the note that stands /// for the rest. fn unreadable( diff --git a/packages/albedo_model/test/albedo_model/media_budget_test.gleam b/packages/albedo_model/test/albedo_model/media_budget_test.gleam index 01a465ecd..4e3268836 100644 --- a/packages/albedo_model/test/albedo_model/media_budget_test.gleam +++ b/packages/albedo_model/test/albedo_model/media_budget_test.gleam @@ -1,8 +1,10 @@ -//// A history of clips is sent newest first within the request's clip -//// budget, so a long session's request never outgrows what a provider takes. +//// Clips past a request's clip budget are refused where they arrive; a +//// history already past it, after a model switch, is sent newest first +//// within it. import albedo_model as types import gleam/list +import gleam/option.{None, Some} fn clip(hash: String) -> types.Image { let assert Ok(image) = @@ -52,3 +54,16 @@ pub fn a_message_left_without_images_is_text_test() -> Nil { assert text == "old\n[1 clip(s) omitted: newer clips fill this request's media budget]" } + +pub fn clips_that_fill_the_budget_exactly_fit_test() -> Nil { + assert types.clip_budget_refusal(types.request_clip_budget - 10, 10) == None + assert types.clip_budget_refusal(types.request_clip_budget + 5, 0) == None + let assert Some(reason) = + types.clip_budget_refusal(types.request_clip_budget - 10, 11) + assert reason + == "these clips take 0 MiB, and the session's clips already hold 64 MiB of the 64 MiB one request carries" + let assert Some(reason) = + types.clip_budget_refusal(40 * 1_048_576, types.max_clip_encoded_bytes) + assert reason + == "these clips take 26.7 MiB, and the session's clips already hold 40 MiB of the 64 MiB one request carries" +} diff --git a/packages/albedo_sdk/src/albedo_sdk/extension.gleam b/packages/albedo_sdk/src/albedo_sdk/extension.gleam index b66c42236..a3d144675 100644 --- a/packages/albedo_sdk/src/albedo_sdk/extension.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/extension.gleam @@ -67,6 +67,8 @@ pub type Context { /// What the session's provider takes, so a tool never hands the model /// an image its next request would be refused for. images: types.ImageLimits, + /// negative when the session's clips already exceed the request budget + clip_room: Int, /// The store scoped to the extension whose tool runs. The composition /// sets it before the tool is invoked. storage: storage.Storage, diff --git a/python/albedo_capture.py b/python/albedo_capture.py index fbeacb00e..ae782dfe7 100644 --- a/python/albedo_capture.py +++ b/python/albedo_capture.py @@ -73,15 +73,15 @@ class Capture: text_only: bool = False, media: tuple[str, ...] = (), max_fps: float | None = None, + clip_room: int | None = None, ) -> None: self.id: str = id self.kind: str = kind - # The session model's image limits, the clip types it reads, and the - # most frames a second it samples a video at, sent per cell. self.max_edge: int | None = max_edge self.text_only: bool = text_only self.media: tuple[str, ...] = media self.max_fps: float | None = max_fps + self.clip_room: int | None = clip_room self.data: bytearray = bytearray() self._tail: bytearray | None = None self.seen: int = 0 @@ -299,6 +299,7 @@ class Capture: typed = [(data, self._type(data, fps)) for data in read] for data in read: self._check_shown(data, fps) + self._check_room(read) return [ self._picture(data, mime) if image_type(data) is not None @@ -323,6 +324,37 @@ class Capture: raise ValueError(f"fps is for a video, not {mime}; show it without fps") return mime + def room_left(self) -> int | None: + """The base64 bytes of clips the session's next request still has + room for beside the ones this cell attached, if the daemon said.""" + if self.clip_room is None: + return None + clips = [i for i in self.images if image_type(i) is None] + return self.clip_room - sum(encoded_size(len(i)) for i in clips) + + def _check_room(self, items: list[bytes]) -> None: + """Refuse `items` when the clips among them this cell would attach, + rather than find attached already or save as overflow, do not fit.""" + room = self.room_left() + if room is None: + return + attached = list(self.images) + adding = 0 + for data in items: + if data in attached or self._full(attached, data) is not None: + continue + attached.append(data) + if image_type(data) is None: + adding += encoded_size(len(data)) + if adding <= room: + return + raise ValueError( + f"these clips take {adding / MIB:.1f} MiB as base64, and the session's " + f"next request has room for {max(room, 0) / MIB:.1f} MiB more; " + "await commands.shake() lists the session's media and drops what it " + "no longer needs" + ) + def _check_shown(self, data: bytes, fps: float | None) -> None: """Refuse a video this cell already holds at another rate: one attachment carries one rate.""" @@ -394,14 +426,9 @@ class Capture: # A screenshot a plugin attached itself may be shown again by path. if data in self.images: return f"already attached {mime}, {len(data)} bytes" - clip = image_type(data) is None - budget = MAX_CLIPS_BYTES if clip else MAX_IMAGE_BYTES - held = sum(len(i) for i in self.images if (image_type(i) is None) == clip) - if len(self.images) >= MAX_IMAGES: - return self._save(data, mime, f"{MAX_IMAGES} attachments") - if held + len(data) > budget: - what = "clip" if clip else "image" - return self._save(data, mime, f"{budget >> 20} MiB {what} budget") + full = self._full(self.images, data) + if full is not None: + return self._save(data, mime, full) self.images.append(data) self.fps.append(None if fps is None else float(fps)) if fps is None: @@ -412,6 +439,18 @@ class Capture: self.images.clear() self.fps.clear() + @staticmethod + def _full(images: list[bytes], data: bytes) -> str | None: + """What of a cell holding `images` that `data` would overflow, if any.""" + clip = image_type(data) is None + budget = MAX_CLIPS_BYTES if clip else MAX_IMAGE_BYTES + held = sum(len(i) for i in images if (image_type(i) is None) == clip) + if len(images) >= MAX_IMAGES: + return f"{MAX_IMAGES} attachments" + if held + len(data) > budget: + return f"{budget >> 20} MiB {'clip' if clip else 'image'} budget" + return None + def _save(self, data: bytes, mime: str, full: str) -> str: """Save an overflow attachment without adding it to this cell's result.""" fd, path = tempfile.mkstemp( @@ -453,6 +492,14 @@ class Capture: return entry +MIB = 1 << 20 + + +def encoded_size(size: int) -> int: + """The bytes of `size` bytes as base64, as the daemon counts a clip.""" + return 4 * ((size + 2) // 3) + + def image_size(data: bytes) -> tuple[str, int, int] | None: """MIME type, width and height of a whole image, or None. A port of `inspect` in image.gleam, which stays the authority: the daemon checks diff --git a/python/albedo_cells.py b/python/albedo_cells.py index 89dcdb05c..f27df122e 100644 --- a/python/albedo_cells.py +++ b/python/albedo_cells.py @@ -1473,6 +1473,7 @@ class Cells: text_only=outer is not None and outer.text_only, media=() if outer is None else outer.media, max_fps=None if outer is None else outer.max_fps, + clip_room=None if outer is None else outer.room_left(), ) remember(capture) capture.trace.snapshots = outer is not None and outer.trace.snapshots @@ -2759,6 +2760,7 @@ async def serve() -> None: text_only=message.get("text_only", False), media=tuple(message.get("media", [])), max_fps=message.get("max_fps"), + clip_room=message.get("clip_room"), ) capture.trace.snapshots = message.get("snapshots", False) capture.interruption = "" diff --git a/python/albedo_protocol.py b/python/albedo_protocol.py index b23554ca6..306df1b33 100644 --- a/python/albedo_protocol.py +++ b/python/albedo_protocol.py @@ -33,6 +33,7 @@ class Execute(TypedDict): text_only: NotRequired[bool] media: NotRequired[list[str]] max_fps: NotRequired[float | None] + clip_room: NotRequired[int] timeout_ms: NotRequired[int] @@ -428,6 +429,7 @@ def parse_incoming(value: object) -> Incoming: "text_only": "bool", "media": "str_list", "max_fps": "float_or_none", + "clip_room": "int", "timeout_ms": "int", }, ) diff --git a/robot-docs/media.md b/robot-docs/media.md index 33a77a1e6..71028d657 100644 --- a/robot-docs/media.md +++ b/robot-docs/media.md @@ -92,21 +92,57 @@ A new clip is refused where it arrives: - A message's image is refused with 409 `image_rejected` by the session's `refused_image` check, whether it came inline or as an upload. -`types.within_clip_budget` keeps a request's clips newest first within -`types.request_clip_budget` (64 MiB of base64). Older clips past it become -`[N clip(s) omitted: newer clips fill this request's media budget]`, so a -session that keeps attaching clips is not refused for its size. `runtime`'s -wrapper applies `readable_input` to each message, swaps clips for -[copies](#copies-a-model-takes-in), then applies the budget. Antigravity -answered a 100 MB request with a 75 MiB WAV inline; no other wire's ceiling has -been measured, so the budget is one constant rather than a per-wire limit. - Gemini nests only pictures in a function response. The [Gemini](../packages/albedo_gemini/src/albedo_gemini/request.gleam) and [Antigravity](../extensions/antigravity/src/albedo_ext_antigravity/wire.gleam) encoders send a tool result's clips in the following user turn, labelled `Tool result media:`. +### The clip budget + +A request carries at most `types.request_clip_budget` (64 MiB) of clips as +base64. Antigravity answered a 100 MB request with a 75 MiB WAV inline; no other +wire's ceiling has been measured, so the budget is one constant rather than a +per-wire limit. + +The budget is kept where clips arrive, so a request never has to leave an older +clip out to make room for a newer one. That would change an earlier message and +miss the provider's prompt cache from there on. What a session holds is +`runtime.clips_held` over the clips its next request carries, as its current +model receives them, after `readable_input`, each counted as its +[copy](#copies-a-model-takes-in) when an `image_copies` row has one and as it is +otherwise. It reads the sizes stored references carry and the copy rows, never a +payload. A compaction leaves the clips of the messages it summarized out of the +request, so admission counts an entry from before the last prepared request only +for the clips that request carried (`context_snapshot.retained_clips`), and +every clip after it. Without a request prepared on the current model, after a +restart or a switch, every clip in the history counts until the next one. A clip +that would take that past the budget is refused: + +- A message is refused with 409 `media_budget`, inline images and uploads alike, + by the same `refused_image` check, so the upload waits for the next try. Its + detail says how much the session holds, the limit, and that `/shake` frees + room. A new clip counts as it is, since no copy of it exists yet. +- A cell's clips are checked against the room left. The loop sums the step's + prepared history, which leaves out what a compaction summarized, before its + tool calls and passes the room to each call (`extension.Context.clip_room`), + less what the calls before it attached. The daemon sends it in each `execute` + message as `clip_room`, `show_media` raises when the call's clips do not fit, + and the python tool keeps back the clips past it with an `image_errors` entry + that names `commands.shake`. + +Inputs already waiting in the queue are not counted, so two messages queued +behind a running turn can together pass the budget. + +A history can still hold more than the budget: after a switch to a model that is +sent larger copies or the originals, or once ffmpeg is gone. Then +`types.within_clip_budget` keeps a request's clips newest first within it, and +the older ones become +`[N clip(s) omitted: newer clips fill this request's media budget]`. While the +history is past the budget every new clip is refused, so each request trims it +the same way and its prefix stays cached. `runtime`'s wrapper applies +`readable_input` to each message, swaps clips for copies, then applies the trim. + ### Copies a model takes in A clip is sent with every request after it, and a model often takes in less of @@ -179,7 +215,8 @@ nested `cells.run` passes its attachments on to the outer cell. Plugins attach either with `api.attach_media`, and `rem.show_media(path)` (or `rem.show_image`) reads one from a remote host, up to the same 20 MiB. `files.image(index)` returns an uploaded clip's bytes too. The daemon sends the model's types to the -kernel in each `execute` message as `media`. +kernel in each `execute` message as `media`, and the room the session's requests +have left for clips as `clip_room` ([the clip budget](#the-clip-budget)). ### Frame rates diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index 891af2b07..e1547fa99 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -4460,13 +4460,13 @@ export interface components { kind: "acp_prompt"; blocks: components["schemas"]["ACPPromptBlock"][]; }; - /** @description Strict base64 of a picture, or of a whole audio or video clip; decoded headers and provider constraints are validated before admission. A clip of a type the session's model does not read is refused. */ + /** @description Strict base64 of a picture, or of a whole audio or video clip; decoded headers and provider constraints are validated before admission. A clip of a type the session's model does not read is refused with 409 image_rejected. Clips that would take what the session's next request carries past 64 MiB of clips are refused with 409 media_budget. */ ImageUpload: { /** @enum {string} */ mime_type: "image/png" | "image/jpeg" | "image/webp" | "audio/wav" | "audio/mpeg" | "audio/aac" | "audio/flac" | "audio/ogg" | "audio/mp4" | "video/mp4" | "video/webm"; data: string; }; - /** @description A picture or clip uploaded to this session beforehand. An upload that is unknown, expired or taken by an earlier message is refused with 409 upload_unknown. */ + /** @description A picture or clip uploaded to this session beforehand. An upload that is unknown, expired or taken by an earlier message is refused with 409 upload_unknown. It is checked as an ImageUpload is. */ UploadReference: { upload: components["schemas"]["UUIDv7"]; };