From 4eff4ce6a74fb86ca796011e0c300fbf2409c87e Mon Sep 17 00:00:00 2001 From: zerob13 Date: Fri, 20 Nov 2026 13:07:18 +0800 Subject: [PATCH 1/5] fix(modality): serve Dim account image models and keep the snapshot consistent The Dim account relay (dimcode-api-oauth) had no adapter row, so its image models were listed as available options while image.generate reported "The adapter serves no image model Provider lists". Two fixes: - dim-modality-aimux binds dimcode-api-oauth to the aimux openai package: the relay's /v1 base speaks the OpenAI Image API with the account's bearer, so arcship-image runs image.generate and image.edit. - Modality lists every declared model as an option and marks it available only when an available adapter serves the operation for it; otherwise the option carries its runtime, build or adapter reason. default and effective follow, so a client never sees a selectable model the operation refuses. configure accepts any declared option, served or not, so a default can be saved before a runtime lands; host targets still require a runnable target. Provider recognizes image models whose listing carries no modalityCapabilities, as the previous product did: an explicit list (empty included) wins; otherwise known image ids (arcship-image, the gpt-image-2 and grok-imagine-image families, seedream), an image kind or image-only output declares image.generate, plus image.edit when the model reads images; imageGeneration: false recognizes nothing. openai-codex image models stay unserved with the adapter reason: the aimux codex package answers NoSuchModel for image models, and their transport belongs in aimux. Fixes #1887 --- crates/dim-app-server/src/provider.rs | 85 +++++++-- crates/dim-app-server/tests/provider_flow.rs | 42 ++++- crates/dim-modality-aimux/src/vendor.rs | 12 ++ crates/dim-modality-aimux/tests/adapter.rs | 67 +++++++ crates/dim-modality-aimux/tests/flows.rs | 36 +++- crates/dim-modality/src/lib.rs | 172 +++++++++--------- crates/dim-modality/tests/modality_flow.rs | 111 +++++++---- docs/design/appserver/provider-management.md | 20 +- docs/design/plugins/Modality.md | 12 +- .../design/appserver/provider-management.md | 14 +- docs/zh/design/plugins/Modality.md | 12 +- 11 files changed, 424 insertions(+), 159 deletions(-) diff --git a/crates/dim-app-server/src/provider.rs b/crates/dim-app-server/src/provider.rs index f4ef34a6cf..6b5e3b2973 100644 --- a/crates/dim-app-server/src/provider.rs +++ b/crates/dim-app-server/src/provider.rs @@ -757,22 +757,79 @@ impl ProviderCatalog { } } +/// Image models whose listing may carry no media metadata: a relay or an +/// account catalog lists them under their bare id. The operations are the ones +/// the vendor documents for the id. +const KNOWN_IMAGE_MODELS: &[&str] = &[ + "arcship-image", + "gpt-image-2", + "gpt-image-2.5-flare", + "gpt-image-2.5-sunburst", + "gpt-image-2.5-flare-2026-09-08", + "gpt-image-2.5-sunburst-2026-09-08", + "grok-imagine-image", + "grok-imagine-image-2.0", + "grok-imagine-image-quality", +]; + impl ProviderModel { - /// The `.` ids this entry declares for modality - /// (Modality §9.2), in their catalog order; `None` when it declares none. + /// The `.` ids this entry serves for modality + /// (Modality §9.2, provider management §3.6); `None` when it serves none. + /// An explicit `modalityCapabilities` list is the answer, an empty one + /// included. Without one, an image model is recognized from its id or its + /// kind and output: `image.generate`, and `image.edit` when it also reads + /// images; `imageGeneration: false` recognizes nothing. fn modality_operations(&self) -> Option> { - let values = self - .metadata - .as_ref()? - .raw - .get("modalityCapabilities")? - .as_array()?; - let operations: Vec = values - .iter() - .filter_map(serde_json::Value::as_str) - .map(str::to_owned) - .collect(); - (!operations.is_empty()).then_some(operations) + let raw = self.metadata.as_ref().map(|metadata| &metadata.raw); + let field = |name: &str| raw.and_then(|raw| raw.get(name)); + if let Some(values) = field("modalityCapabilities").and_then(serde_json::Value::as_array) { + let operations: Vec = values + .iter() + .filter_map(serde_json::Value::as_str) + .map(str::to_owned) + .collect(); + return (!operations.is_empty()).then_some(operations); + } + if field("imageGeneration") == Some(&serde_json::Value::Bool(false)) { + return None; + } + let modalities = |direction: &str| -> Vec<&str> { + field("modalities") + .and_then(|modalities| modalities.get(direction)) + .and_then(serde_json::Value::as_array) + .map(|values| { + values + .iter() + .filter_map(serde_json::Value::as_str) + .collect() + }) + .unwrap_or_default() + }; + let (input, output) = (modalities("input"), modalities("output")); + let kind = field("type").and_then(serde_json::Value::as_str); + let operations: &[&str] = if KNOWN_IMAGE_MODELS.contains(&self.id.as_str()) + || self + .id + .split(['.', '/', '_', '-']) + .any(|part| part == "seedream") + { + &["image.generate", "image.edit"] + } else if kind == Some("image-edit") { + &["image.edit"] + } else if field("imageGeneration") == Some(&serde_json::Value::Bool(true)) + || (matches!(kind, Some("image" | "image-generation")) + && (output.is_empty() || output.contains(&"image"))) + || (output == ["image"]) + { + if input.contains(&"image") { + &["image.generate", "image.edit"] + } else { + &["image.generate"] + } + } else { + return None; + }; + Some(operations.iter().map(|id| (*id).to_owned()).collect()) } /// The realtime transport this entry's `metadata.raw.realtime` declares, diff --git a/crates/dim-app-server/tests/provider_flow.rs b/crates/dim-app-server/tests/provider_flow.rs index 897b495dcd..857076a317 100644 --- a/crates/dim-app-server/tests/provider_flow.rs +++ b/crates/dim-app-server/tests/provider_flow.rs @@ -2195,7 +2195,33 @@ async fn selectable_modality_models_carry_declared_operations_without_chat_rules "modality", 1000, ); - mine.models = vec![media(), both, model("modality-text", 1000)]; + let undeclared = |id: &str, raw: Value| -> ModelEntry { + serde_json::from_value(json!({ + "modelId": id, "displayName": id, "status": "active", + "capabilities":{"modalities":["image"],"toolCalling":false,"streaming":true, + "structuredOutput":false,"vision":false,"audio":false,"reasoning":false}, + "metadata":{"raw": raw} + })) + .unwrap() + }; + mine.models = vec![ + media(), + both, + model("modality-text", 1000), + undeclared("arcship-image", json!({})), + undeclared( + "modality-inferred", + json!({"type":"image","modalities":{"input":["text","image"],"output":["image"]}}), + ), + undeclared( + "modality-none", + json!({"type":"image-generation","modalityCapabilities":[]}), + ), + undeclared( + "modality-off", + json!({"type":"image-generation","imageGeneration":false}), + ), + ]; let created = provider.create(mine, &cancel).await.unwrap(); let mut off = input( OFF, @@ -2254,8 +2280,18 @@ async fn selectable_modality_models_carry_declared_operations_without_chat_rules "modality-both".to_owned(), vec!["image.generate".to_owned()] ), + ( + "arcship-image".to_owned(), + vec!["image.generate".to_owned(), "image.edit".to_owned()] + ), + ( + "modality-inferred".to_owned(), + vec!["image.generate".to_owned(), "image.edit".to_owned()] + ), ], - "a model that declares no operation is omitted" + "a model that declares no operation is omitted; a known or image-output model \ + without a declaration is recognized, and an explicit empty list or \ + `imageGeneration: false` recognizes nothing" ); assert!( !modality @@ -2390,7 +2426,7 @@ async fn selectable_modality_models_carry_declared_operations_without_chat_rules .collect(); assert_eq!( listed, - ["modality-media"], + ["modality-media", "arcship-image", "modality-inferred"], "a disabled model leaves the modality options" ); let cancelled = CancellationToken::new(); diff --git a/crates/dim-modality-aimux/src/vendor.rs b/crates/dim-modality-aimux/src/vendor.rs index dfbf27c4db..fdcca96d19 100644 --- a/crates/dim-modality-aimux/src/vendor.rs +++ b/crates/dim-modality-aimux/src/vendor.rs @@ -365,6 +365,18 @@ pub static VENDORS: &[Vendor] = &[ base: Base::AsIs, format: None, }, + // The Dim account relay speaks the OpenAI Image API on its `/v1` base: + // JSON `/images/generations` and multipart `/images/edits`, with the + // account's bearer. The relay names the model, so a model the package + // does not know keeps edit. + Vendor { + catalog: "dimcode-api-oauth", + aimux: "openai", + options: "openai", + kinds: kinds(true, false, false, false), + base: Base::AsIs, + format: Some("outputFormat"), + }, // The catalog's `/speechtotext/v1` is the prefix the package appends. Vendor { catalog: "rev-ai", diff --git a/crates/dim-modality-aimux/tests/adapter.rs b/crates/dim-modality-aimux/tests/adapter.rs index 5a52c5f6f8..34d9a8e64b 100644 --- a/crates/dim-modality-aimux/tests/adapter.rs +++ b/crates/dim-modality-aimux/tests/adapter.rs @@ -622,6 +622,73 @@ fn path_is_inside(path: &Path, dir: &Path) -> bool { path.strip_prefix(dir).is_ok() } +/// The Dim account relay speaks the OpenAI Image API on its `/v1` base with +/// the account's bearer, for a model id only the relay knows (#1887). +#[tokio::test] +async fn the_dim_account_relay_serves_its_image_models_over_the_openai_image_api() { + let relay = ModelId { + provider_id: "dimcode-api-oauth".into(), + model_id: "arcship-image".into(), + }; + let names: Vec = MediaAdapter::new() + .operations(&relay) + .into_iter() + .map(|operation| format!("{}.{}", operation.category, operation.operation)) + .collect(); + assert_eq!(names, ["realtime.voice", "image.generate", "image.edit"]); + + let dir = work_dir("relay"); + let (adapter, requests) = + scripted(|_| ok_json(json!({"created": 1, "data": [{"b64_json": base64(PNG_HEADER)}]}))); + let base = "https://relay.example.test/v1"; + let generate = job( + "dimcode-api-oauth", + "arcship-image", + "image", + "generate", + json!({"prompt": "a red circle"}), + Vec::new(), + &dir, + ); + let output = run(&adapter, generate, base, "arcship-image") + .await + .unwrap(); + assert_eq!(output.files[0].media_type, "image/png"); + let reference = input(&dir, "in.png", "image/png", PNG_HEADER); + let edit = job( + "dimcode-api-oauth", + "arcship-image", + "image", + "edit", + json!({"prompt": "add a hat"}), + vec![reference], + &dir, + ); + run(&adapter, edit, base, "arcship-image").await.unwrap(); + + let requests = requests.lock().unwrap(); + let urls: Vec<&str> = requests + .iter() + .map(|request| request.url.as_str()) + .collect(); + assert_eq!( + urls, + [ + "https://relay.example.test/v1/images/generations", + "https://relay.example.test/v1/images/edits" + ] + ); + for request in requests.iter() { + assert_eq!( + request.header("authorization"), + Some("Bearer test-credential") + ); + } + let body: Value = serde_json::from_slice(&requests[0].body).unwrap(); + assert_eq!(body["model"], "arcship-image"); + assert_eq!(body["prompt"], "a red circle"); +} + /// One (row, operation) pair with the exact request it must send. struct Case { provider: &'static str, diff --git a/crates/dim-modality-aimux/tests/flows.rs b/crates/dim-modality-aimux/tests/flows.rs index f2c1ccf7c5..44b760319d 100644 --- a/crates/dim-modality-aimux/tests/flows.rs +++ b/crates/dim-modality-aimux/tests/flows.rs @@ -944,15 +944,47 @@ async fn capabilities_show_the_mapped_provider_and_refuse_a_created_one() { ) .await; assert_ok(&reply); + let capabilities = client.rpc("modality.capabilities", json!({})).await; + let unserved = json!({"providerId": created, "modelId": "custom-image", "available": false, + "reason": {"dimension": "adapter", "detail": "No available adapter serves the model"}}); + let generate = |snapshot: &Value| -> Value { + snapshot["result"]["categories"] + .as_array() + .unwrap() + .iter() + .find(|category| category["category"] == "image") + .unwrap()["operations"] + .as_array() + .unwrap() + .iter() + .find(|operation| operation["operation"] == "generate") + .unwrap() + .clone() + }; + assert!( + generate(&capabilities)["options"] + .as_array() + .unwrap() + .contains(&unserved), + "the created provider's model is listed with the adapter reason: {capabilities}" + ); let revision = capabilities["result"]["revision"].as_str().unwrap(); - let refused = client + let configured = client .rpc( "modality.configure", json!({"expectedRevision": revision, "category": "image", "operation": "generate", "model": model(created, "custom-image")}), ) .await; - assert_eq!(app_error(&refused), "modality_invalid_selection"); + assert_ok(&configured); + assert_eq!(generate(&configured)["default"], unserved); + let refused = client + .rpc( + "modality.task.submit", + json!({"category": "image", "operation": "generate", "params": {"prompt": "a cat"}, "files": []}), + ) + .await; + assert_eq!(app_error(&refused), "default_unavailable", "{refused}"); assert!( refused["error"]["message"] .as_str() diff --git a/crates/dim-modality/src/lib.rs b/crates/dim-modality/src/lib.rs index 8102f7d0fb..ed06a1f9a1 100644 --- a/crates/dim-modality/src/lib.rs +++ b/crates/dim-modality/src/lib.rs @@ -714,60 +714,10 @@ impl Evaluation { reason: None, } } - /// Options for one operation: Provider's candidates narrowed by the - /// adapter when it serves the category, a selectable vision model for - /// understanding, the models Provider declares for a realtime operation, - /// and otherwise the models Provider declares for the operation id - /// (Modality §9.2), in each read's order. The candidates of an - /// adapter-served category are the deduplicated union of the two Provider - /// reads, selectable first, so a declared media model execution rejects is - /// still offered when the adapter serves it. A realtime session's adapter - /// is handed the transport its entry declares, so the entry is the - /// per-model answer and narrows nothing (A.3, D2). The persisted default - /// follows when it is no longer an option. + /// Options for one operation, followed by the persisted default when it is + /// no longer one of them. fn options(&self, category: &str, row: &OperationRow) -> Vec { - let mut options: Vec = if host_target(category, row.operation).is_some() { - // A host target this platform or build cannot run is absent, never - // an unavailable option; a plugin target another contract supplies - // is listed with its reason (A.2.1, decision 4). - self.host_options() - } else if is_understand(category, row.operation) { - self.selectable - .iter() - .filter(|model| model.capabilities.vision) - .map(|model| Self::option(&model.target)) - .collect() - } else if is_realtime(category) { - self.declared - .iter() - .filter(|model| declares(&model.operations, category, row.operation)) - .map(|model| Self::option(&model.target)) - .collect() - } else if self.adapter_serves(category) { - let mut served: Vec = Vec::new(); - for model in self - .selectable - .iter() - .map(|model| &model.target) - .chain(self.declared.iter().map(|model| &model.target)) - { - let (provider_id, model_id) = (model.provider_id.as_str(), model.model_id.as_str()); - if !served - .iter() - .any(|option| option.model() == (provider_id, model_id)) - && self.serves(model, category, row.operation) - { - served.push(Self::option(model)); - } - } - served - } else { - self.declared - .iter() - .filter(|model| declares(&model.operations, category, row.operation)) - .map(|model| Self::option(&model.target)) - .collect() - }; + let mut options = self.candidates_for(category, row); if let Some(key) = row.key && let Some(default) = self.defaults.get(key) && !options.iter().any(|option| { @@ -788,6 +738,68 @@ impl Evaluation { } options } + /// The models one operation offers: the host targets, a selectable vision + /// model for understanding, and otherwise the models Provider declares + /// for the operation id (Modality §9.2), in Provider's order. A realtime + /// session's adapter is handed the transport its entry declares, so the + /// entry is the per-model answer (A.3, D2). Any other declared model is + /// available only when an available adapter serves the operation for it; + /// one no adapter serves stays listed with its reason, so an option and + /// the operation never disagree. + fn candidates_for(&self, category: &str, row: &OperationRow) -> Vec { + if host_target(category, row.operation).is_some() { + // A host target this platform or build cannot run is absent, never + // an unavailable option; a plugin target another contract supplies + // is listed with its reason (A.2.1, decision 4). + self.host_options() + } else if is_understand(category, row.operation) { + self.selectable + .iter() + .filter(|model| model.capabilities.vision) + .map(|model| Self::option(&model.target)) + .collect() + } else { + self.declared + .iter() + .filter(|model| declares(&model.operations, category, row.operation)) + .map(|model| { + if is_realtime(category) || self.serves(&model.target, category, row.operation) + { + Self::option(&model.target) + } else { + OptionSnapshot { + available: false, + reason: Some(self.unserved_reason(&model.target, category)), + ..Self::option(&model.target) + } + } + }) + .collect() + } + } + /// Why no adapter runs a declared model's operation, in the operation's + /// own vocabulary. + fn unserved_reason(&self, model: &ModelId, category: &str) -> Reason { + match self.adapter(&model.provider_id) { + Some(adapter) if !adapter.0.available() => { + reason("runtime", "The adapter is unavailable") + } + _ if category != "image" && !self.adapter_serves(category) => { + reason("build", "Not in this build") + } + _ => reason("adapter", "No available adapter serves the model"), + } + } + /// Whether `configure` may persist `model` for one operation: an option + /// the operation offers, served or not, so a default can be saved before + /// a runtime lands. A host target must also run here (A.2.1). + pub(crate) fn configurable(&self, category: &str, row: &OperationRow, model: &ModelId) -> bool { + let host = host_target(category, row.operation).is_some(); + self.candidates_for(category, row).iter().any(|option| { + option.model() == (model.provider_id.as_str(), model.model_id.as_str()) + && (option.available || !host) + }) + } /// Why `model` is not an available option of the operation, naming it as /// the client configured it: `name` is the operation id, or the category /// when the write is category-wide. A persisted default and a refused @@ -829,17 +841,16 @@ impl Evaluation { if !self.known(model) { return reason("provider", "Model is no longer selectable"); } - if self.adapter_serves(category) { - reason( - "adapter", - "No available adapter serves the configured model", - ) - } else { - reason( - "configuration", - format!("The model does not declare {name}"), - ) + if self + .declared_for(&model.provider_id, &model.model_id) + .is_some_and(|declared| declares(&declared.operations, category, operation)) + { + return self.unserved_reason(model, category); } + reason( + "configuration", + format!("The model does not declare {name}"), + ) } pub(crate) fn operation(&self, category: &str, row: &OperationRow) -> OperationSnapshot { let options = self.options(category, row); @@ -930,8 +941,9 @@ impl Evaluation { .as_ref() .filter(|global| { options.iter().any(|option| { - option.model() - == (global.provider_id.as_str(), global.model_id.as_str()) + option.available + && option.model() + == (global.provider_id.as_str(), global.model_id.as_str()) }) }) .cloned() @@ -1350,27 +1362,19 @@ impl DynPlugin for ModalityPlugin { ) .await?; if let Some(model) = model { - let options: Vec = if configured.category_wide { - configured - .category - .rows - .iter() - .flat_map(|row| { - evaluation.options(configured.category.name, row) - }) - .collect() + // A category-wide save is valid when any + // of the category's rows offers the model. + let rows: &[OperationRow] = if configured.category_wide { + configured.category.rows } else { - evaluation.options(configured.category.name, configured.row) + std::slice::from_ref(configured.row) }; - // A category-wide save flattens every row, - // and each row appends the persisted - // default when it is not an option, marked - // unavailable. The model is valid when any - // row offers it as available. - let selected = options.iter().any(|option| { - option.model() - == (model.provider_id.as_str(), model.model_id.as_str()) - && option.available + let selected = rows.iter().any(|row| { + evaluation.configurable( + configured.category.name, + row, + model, + ) }); if !selected { return Err(selection_refusal( diff --git a/crates/dim-modality/tests/modality_flow.rs b/crates/dim-modality/tests/modality_flow.rs index 7dc6b57c7a..a407e191ea 100644 --- a/crates/dim-modality/tests/modality_flow.rs +++ b/crates/dim-modality/tests/modality_flow.rs @@ -694,6 +694,7 @@ fn home(prefix: &str) -> std::path::PathBuf { home } +const IMAGE_OPERATIONS: [&str; 3] = ["image.generate", "image.edit", "image.enhance"]; async fn create_provider(client: &mut Client) { let mut vision = CatalogCapabilities::with_limits(128_000, 16_384); vision.vision = true; @@ -707,8 +708,8 @@ async fn create_provider(client: &mut Client) { "displayName": "Fixture", "connection": {"driverKind": "openai-compatible", "baseUrl": "http://127.0.0.1:1/v1", "auth": {"type": "anonymous"}}, "models": [ - {"modelId": "alpha", "displayName": "alpha", "status": "active", "capabilities": vision}, - {"modelId": "beta", "displayName": "beta", "status": "active", "capabilities": text} + {"modelId": "alpha", "displayName": "alpha", "status": "active", "capabilities": vision, "metadata": {"raw": {"modalityCapabilities": IMAGE_OPERATIONS}}}, + {"modelId": "beta", "displayName": "beta", "status": "active", "capabilities": text, "metadata": {"raw": {"modalityCapabilities": IMAGE_OPERATIONS}}} ], "enabled": true }), @@ -1451,14 +1452,19 @@ async fn capabilities_and_configure_resolve_defaults_through_the_fixture_adapter json!({"expectedRevision": cleared["result"]["revision"], "category": "image", "operation": "edit", "model": model("beta")}), ) .await; + assert_ok(&beta_edit); + let edit = operation(&beta_edit, "edit"); assert_eq!( - beta_edit["error"]["data"]["appError"], "modality_invalid_selection", - "the adapter serves edit only for the models it declares" + edit["default"], + json!({"providerId": PROVIDER, "modelId": "beta", "available": false, + "reason": {"dimension": "adapter", "detail": "No available adapter serves the model"}}), + "a declared model saves as a default before an adapter serves it, and says so: {edit}" ); + assert!(edit["effective"].is_null()); let beta_generate = client .rpc( "modality.configure", - json!({"expectedRevision": cleared["result"]["revision"], "category": "image", "operation": "generate", "model": model("beta")}), + json!({"expectedRevision": beta_edit["result"]["revision"], "category": "image", "operation": "generate", "model": model("beta")}), ) .await; assert_ok(&beta_generate); @@ -1489,15 +1495,21 @@ async fn capabilities_and_configure_resolve_defaults_through_the_fixture_adapter let generate = operation(&offline, "generate"); assert_eq!(generate["available"], false); assert_eq!(generate["reasons"][0]["dimension"], "runtime"); + assert_eq!( + generate["default"]["reason"], + json!({"dimension": "runtime", "detail": "The adapter is unavailable"}), + "the default agrees with the operation: {generate}" + ); + assert!(generate["effective"].is_null()); let refused = client .rpc( "modality.configure", - json!({"expectedRevision": offline["result"]["revision"], "category": "image", "operation": "generate", "model": model("beta")}), + json!({"expectedRevision": offline["result"]["revision"], "category": "image", "operation": "generate", "model": model("gamma")}), ) .await; assert_eq!( refused["error"]["data"]["appError"], "modality_invalid_selection", - "an unavailable adapter cannot serve a new default" + "a model Provider does not list is no option" ); let mut bare = Client::new_version(&server, true, 3).await; @@ -1565,7 +1577,8 @@ async fn a_declared_media_model_served_by_the_adapter_is_an_option() { } /// An adapter that serves no model either Provider read names is not the same -/// as a build without an adapter: the operation says which case it is. +/// as a build without an adapter: the operation says which case it is, and +/// its options, default and effective model agree with it (#1887). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn an_adapter_serving_no_provider_model_is_not_reported_as_missing() { let fixture = Arc::new(FixtureAdapter::default()); @@ -1582,11 +1595,27 @@ async fn an_adapter_serving_no_provider_model_is_not_reported_as_missing() { generate["reasons"][0]["detail"], "The adapter serves no image model Provider lists", "a collected adapter that serves no candidate is not a missing adapter: {generate}" ); + let unserved = json!({"providerId": PROVIDER, "modelId": "image-media", "available": false, + "reason": {"dimension": "adapter", "detail": "No available adapter serves the model"}}); assert_eq!( generate["options"], - json!([{"providerId": PROVIDER, "modelId": "image-media", "available": true}]), - "an operation no adapter serves falls back to the declared models" + json!([unserved]), + "a declared model no adapter serves is listed as unavailable" + ); + assert!(generate["effective"].is_null(), "{generate}"); + let configured = client + .rpc( + "modality.configure", + json!({"expectedRevision": snapshot["result"]["revision"], "category": "image", "operation": "generate", "model": model("image-media")}), + ) + .await; + assert_ok(&configured); + let generate = operation(&configured, "generate"); + assert_eq!( + generate["default"], unserved, + "a saved default that cannot run says why" ); + assert!(generate["effective"].is_null(), "{generate}"); server.shutdown(); server.join().await.unwrap(); std::fs::remove_dir_all(home).unwrap(); @@ -1620,18 +1649,26 @@ async fn the_product_build_reports_image_operations_without_an_adapter() { let entry = operation(&snapshot, name); assert_eq!(entry["available"], false, "{entry}"); assert_eq!(entry["reasons"][0]["dimension"], "adapter"); - assert!(entry["options"].as_array().unwrap().is_empty()); + let unserved = |model_id: &str| { + json!({"providerId": PROVIDER, "modelId": model_id, "available": false, + "reason": {"dimension": "adapter", "detail": "No available adapter serves the model"}}) + }; + assert_eq!( + entry["options"], + json!([unserved("alpha"), unserved("beta")]), + "declared models are listed and none can run: {entry}" + ); assert!(entry["default"].is_null()); assert!(entry["effective"].is_null()); let refused = client .rpc( "modality.configure", - json!({"expectedRevision": snapshot["result"]["revision"], "category": "image", "operation": name, "model": model("alpha")}), + json!({"expectedRevision": snapshot["result"]["revision"], "category": "image", "operation": name, "model": model("gamma")}), ) .await; assert_eq!( refused["error"]["data"]["appError"], "modality_invalid_selection", - "{name} cannot have a default without an adapter: {refused}" + "{name} refuses a model Provider does not list: {refused}" ); } let understand = operation(&snapshot, "understand"); @@ -1685,8 +1722,8 @@ async fn clearing_an_operation_after_all_defaults_matches_the_next_read() { "displayName": "Fixture", "connection": {"driverKind": "openai-compatible", "baseUrl": "http://127.0.0.1:1/v1", "auth": {"type": "anonymous"}}, "models": [ - {"modelId": "alpha", "displayName": "alpha", "status": "active", "capabilities": vision}, - {"modelId": "gamma", "displayName": "gamma", "status": "active", "capabilities": vision} + {"modelId": "alpha", "displayName": "alpha", "status": "active", "capabilities": vision, "metadata": {"raw": {"modalityCapabilities": IMAGE_OPERATIONS}}}, + {"modelId": "gamma", "displayName": "gamma", "status": "active", "capabilities": vision, "metadata": {"raw": {"modalityCapabilities": IMAGE_OPERATIONS}}} ], "enabled": true }), @@ -1883,23 +1920,23 @@ async fn declared_models_are_the_options_of_an_operation_without_an_adapter() { let generate = operation_in(&snapshot, "video", "generate"); assert_eq!(generate["available"], false); assert_eq!(generate["reasons"][0]["dimension"], "build"); + let unbuilt = |model_id: &str| { + json!({"providerId": PROVIDER, "modelId": model_id, "available": false, + "reason": {"dimension": "build", "detail": "Not in this build"}}) + }; assert_eq!( generate["options"], - json!([{"providerId": PROVIDER, "modelId": "video-generate", "available": true}]), - "only a declared model is an option, in Provider's order" + json!([unbuilt("video-generate")]), + "only a declared model is an option, in Provider's order, unavailable with the operation" ); - assert_eq!( - generate["effective"], - json!({"providerId": PROVIDER, "modelId": "video-generate", "source": "automatic"}), - "the global selection does not serve video, so the first declared option resolves" + assert!( + generate["effective"].is_null(), + "no option can run, so nothing resolves: {generate}" ); let edit = operation_in(&snapshot, "video", "edit"); assert_eq!( edit["options"], - json!([ - {"providerId": PROVIDER, "modelId": "video-edit", "available": true}, - {"providerId": PROVIDER, "modelId": "video-generate", "available": true} - ]) + json!([unbuilt("video-edit"), unbuilt("video-generate")]) ); let enhance = operation_in(&snapshot, "video", "enhance"); assert!(enhance["options"].as_array().unwrap().is_empty()); @@ -2073,13 +2110,13 @@ async fn operations_without_a_default_key_or_unknown_answers_are_unknown() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn effective_resolves_over_declared_options_and_stays_null_for_an_unavailable_default() { - let (server, home) = start(None, "dm-effective").await; + let (server, home) = start(Some(Arc::new(FixtureAdapter::default())), "dm-effective").await; let mut client = Client::new_version(&server, false, 3).await; create_provider_with( &mut client, vec![ - media("media-option", &["video.generate"]), - chat("chat-option", &["video.generate"]), + media("media-option", &["image.generate"]), + chat("chat-option", &["image.generate"]), ], ) .await; @@ -2093,7 +2130,7 @@ async fn effective_resolves_over_declared_options_and_stays_null_for_an_unavaila ); let initial = client.rpc("modality.capabilities", json!({})).await; assert_ok(&initial); - let generate = operation_in(&initial, "video", "generate"); + let generate = operation(&initial, "generate"); assert!(generate["default"].is_null()); assert_eq!( generate["effective"], @@ -2103,12 +2140,12 @@ async fn effective_resolves_over_declared_options_and_stays_null_for_an_unavaila let configured = client .rpc( "modality.configure", - json!({"expectedRevision": initial["result"]["revision"], "category": "video", "operation": "generate", "model": model("chat-option")}), + json!({"expectedRevision": initial["result"]["revision"], "category": "image", "operation": "generate", "model": model("chat-option")}), ) .await; assert_ok(&configured); assert_eq!( - operation_in(&configured, "video", "generate")["effective"]["source"], + operation(&configured, "generate")["effective"]["source"], "default" ); let catalog = client @@ -2125,7 +2162,7 @@ async fn effective_resolves_over_declared_options_and_stays_null_for_an_unavaila ); let disabled = client.rpc("modality.capabilities", json!({})).await; assert_ok(&disabled); - let generate = operation_in(&disabled, "video", "generate"); + let generate = operation(&disabled, "generate"); assert_eq!(generate["default"]["available"], false, "{generate}"); assert_eq!(generate["default"]["reason"]["dimension"], "provider"); assert!( @@ -2144,12 +2181,12 @@ async fn effective_resolves_over_declared_options_and_stays_null_for_an_unavaila let cleared = client .rpc( "modality.configure", - json!({"expectedRevision": disabled["result"]["revision"], "category": "video", "operation": "generate", "model": null}), + json!({"expectedRevision": disabled["result"]["revision"], "category": "image", "operation": "generate", "model": null}), ) .await; assert_ok(&cleared); assert_eq!( - operation_in(&cleared, "video", "generate")["effective"], + operation(&cleared, "generate")["effective"], json!({"providerId": PROVIDER, "modelId": "media-option", "source": "automatic"}) ); server.shutdown(); @@ -2317,7 +2354,11 @@ async fn a_provider_copy_serves_its_provider_and_the_family_copy_takes_over() { assert_eq!(operation(&capabilities, "edit")["available"], false); assert_eq!( operation(&capabilities, "generate")["options"], - json!([{"providerId": PROVIDER, "modelId": "alpha", "available": true}]), + json!([ + {"providerId": PROVIDER, "modelId": "alpha", "available": true}, + {"providerId": PROVIDER, "modelId": "beta", "available": false, + "reason": {"dimension": "adapter", "detail": "No available adapter serves the model"}} + ]), "the next snapshot uses the family copy's narrower operation support" ); let submitted = submit_task( diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 30020b8034..c4e7f1bafa 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -1023,9 +1023,19 @@ process read, for non-conversational uses (Modality §9.2): operation `selectableForModality`, asynchronous, request `{}`, reply `{models: ModalityModelSnapshot[]}` with each element `{target: {providerId, modelId}, operations: string[]}`. `operations` holds the -`.` ids the model's catalog entry declares in -`metadata.raw.modalityCapabilities`, in that entry's order; a model that -declares none is omitted. The read applies the same provider, account, model, +`.` ids the model's catalog entry declares, in that entry's +order; a model that declares none is omitted. An entry declares its operations +in `metadata.raw.modalityCapabilities`, and an explicit list, an empty one +included, is the whole answer. An entry with no list is recognized as an image +model, because relay and account catalogs list such models without media +metadata: its id is one of the known image models (`arcship-image`, the +`gpt-image-2` family, the `grok-imagine-image` family) or names `seedream`, or +its `type` is `image`/`image-generation` with image or no stated output, or +`imageGeneration` is true, or its only output is `image`. Such a model declares +`image.generate`, and `image.edit` too when it also reads images or is a known +model; a `type` of `image-edit` declares `image.edit` alone, and +`imageGeneration: false` recognizes nothing. The connection rule below reads +the same declaration. The read applies the same provider, account, model, route, credential and status rules as `selectableModels`, without its text-modality, chat-kind and declared-text-limit requirements: a model without a `text` modality, a non-chat model and a model with `limits_undeclared` @@ -1159,8 +1169,8 @@ adapters. A cross-language operation contract is tracked in [#1613](https://gith **Rules.** It applies exactly the rules of the `selectableForModality` read — provider, account, model, route, credential and status — and additionally -requires the model's catalog entry to declare `operation` in its -`metadata.raw.modalityCapabilities`. A model that fails any of these is refused +requires the model's catalog entry to declare `operation`, as the read above +derives it. A model that fails any of these is refused before any network call: the availability cases with the reason execution reports for that model, and an undeclared operation as an invalid request that names it. The read and the connection cannot disagree, because they share the catalog and diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index 7c133cc65d..45fe0b5fff 100644 --- a/docs/design/plugins/Modality.md +++ b/docs/design/plugins/Modality.md @@ -164,7 +164,7 @@ A session ends on `close`; when the opening client connection ends, silently, be `dimcode modality` and the Web settings page call `modality.capabilities`, which returns every category and operation with its availability reasons, selectable options, the persisted default and the model a task or consumer would use now. Nothing is hidden and there is no `--all`. Each unavailable category or operation is shown with its reason per dimension, for example "not in this build", "Apple Vision needs macOS 12 or later on Apple Silicon", "the PP-OCR plugin is not running", "the PP-OCR plugin needs an update", "no adapter", "not configured", "no adapter for the configured model" (decision E16). The last is derived from business configuration Modality has adopted (the default in the `modality` settings document or an explicit model, and its Provider connection) against the adapters Modality can resolve (§9.1). -The image operations are the first implementation slice, and the product build now ships an adapter for part of it: the built-in `dim-modality-aimux` adapter (A.2) serves `generate` and, where the provider's package reads an edit's input files, `edit` through aimux, and `enhance` remains an adapter operation no build serves, so it reports `unavailable` with an `adapter` reason. Availability is a property of the runtime and is answered per model: `available` is true once the adapter is installed, and `operations` decides what it serves for the model a task names. The built-in family copy answers image `operations` for the bundled catalog providers listed in A.2. A created provider whose UUID has no provider copy still resolves the family copy; its image models get the `adapter` reason because that copy's `operations` returns no image operation for them, not because no binding exists. A resolved adapter that serves none of the models Provider lists is not a missing adapter and says so: the image operations keep the `adapter` dimension with "the adapter serves no image model Provider lists", and their options are the declared models, as for any operation no adapter serves. `understand` resolves the target for its Session consumer (§9.4). Configurability is a property of settings: `configure` accepts a default for every A.1 operation that has a default key whenever the model is in that operation's options, so defaults can be persisted before a runtime lands, and an operation this build cannot run keeps `available: false` with its `build` or `adapter` reason. Flow tests configure the fixture adapter to serve the adapter operations they exercise, and the end-to-end flows run the built-in adapter against a stub provider. +The image operations are the first implementation slice, and the product build now ships an adapter for part of it: the built-in `dim-modality-aimux` adapter (A.2) serves `generate` and, where the provider's package reads an edit's input files, `edit` through aimux, and `enhance` remains an adapter operation no build serves, so it reports `unavailable` with an `adapter` reason. Availability is a property of the runtime and is answered per model: `available` is true once the adapter is installed, and `operations` decides what it serves for the model a task names. The built-in family copy answers image `operations` for the bundled catalog providers listed in A.2. A created provider whose UUID has no provider copy still resolves the family copy; its image models get the `adapter` reason because that copy's `operations` returns no image operation for them, not because no binding exists. A resolved adapter that serves none of the models Provider lists is not a missing adapter and says so: the image operations keep the `adapter` dimension with "the adapter serves no image model Provider lists", and their options are the declared models, each `available: false` with the reason no adapter runs it, so an option never claims a run its operation refuses. `understand` resolves the target for its Session consumer (§9.4). Configurability is a property of settings: `configure` accepts a default for every A.1 operation that has a default key whenever the model is in that operation's options, served or not, so defaults can be persisted before a runtime lands; the saved default then reads `available: false` with its reason, and an operation this build cannot run keeps `available: false` with its `build` or `adapter` reason. A host target is the exception: it is configurable only while it can run here (A.2.1). Flow tests configure the fixture adapter to serve the adapter operations they exercise, and the end-to-end flows run the built-in adapter against a stub provider. Realtime options follow Provider's transport declarations rather than narrowing through the resolved adapter's `operations`. A specialized provider copy that does not serve realtime can therefore leave a declared model in the option list while `realtime.open` rejects it as `unavailable`; resolution does not retry the family copy when a present provider copy lacks an operation. @@ -351,7 +351,7 @@ The connection-bearing calls carry credential material for one call, not seriali `Job` is `{ task_id, category, operation, model: {providerId, modelId}, params, files: [{ name, media_type, path }], work_dir }`. Every input's `path` is the absolute path of the file Modality stored at `modality/tasks//input/`. A `node_path` source is opened once without following a final symlink, bounded by the submission budget, copied through `pluginFiles`, and hashed while copying. Source removal or replacement after submission cannot change the accepted input. `work_dir` is the task's `modality/tasks//work` directory, created before the call; every result file resolves to a regular file inside it. The `connection` a call carries is `ModalityConnection`, the Rust shape Provider's non-conversational connection resolution returns (`kind`, `provider_id`, `model`, endpoint and credential material, and the catalog entry's `realtime: { protocol, path }` declaration for a `realtime.*` use). It is not data: it is passed by value for one call, never stored, logged, returned or serialized, which is why the adapter service is in-process today (A.2, [#1613](https://github.com/arcships/dim/issues/1613)). The declaration is Provider's read of the entry's `metadata.raw.realtime`; a model whose entry declares none, and a configured-model profile, which never carries one, is refused `unavailable` with "The model declares no realtime transport" before the adapter is called. The relay takes the socket URL from the connection's base URL, the declared `path` and the model id, so the path is declared by the catalog entry and never derived. -The product's built-in adapter is the `dim-modality-aimux` crate: aimux vocabulary stays inside the adapter. It serves `image.generate`, `image.edit`, `video.generate`, `speech.synthesize` and `speech.transcribe`, bound by catalog provider id, and `realtime.voice` for any model whose entry declares the openai-realtime transport: a realtime session is built from the connection, not from a vendor row. The relay connects to the connection's base URL with the declared path and the model id as its query, `http` and `https` becoming `ws` and `wss`; it sends the connection's headers and its bearer, connects through the connection's proxy, writes text frames as JSON and audio frames as the decoded bytes, and ends the session on a provider close, a socket failure or a frame it cannot write within ten seconds. It carries no control frames; those belong to a `direct` transport. A row exists for each bundled catalog provider whose media models an aimux vendor package executes (openai, google, xai, grok-build, elevenlabs, fal, deepgram, assemblyai, cartesia, gladia, groq, replicate, stability-ai, recraft, black-forest-labs, luma-ai, runway, kling, hume-ai, mistral-ai, rev-ai), and each row serves only what its package implements. `image.edit` is served only by a package that reads the bytes an edit sends: openai, google, fal, replicate and black-forest-labs do, while stability-ai, recraft and luma-ai serve `image.generate` alone; a package that reports no file input for a given model drops edit for that model too. xAI's image models report `adapter` because that package answers `NoSuchModel`, and its transcription and synthesis models are served. A created provider's id is a canonical UUID, which matches no row, so its media operations report the `adapter` reason and `configure` refuses its models with it. The other A.1 categories (music, audio, 3D asset, motion) have no rows and keep the `build` reason. Amazon Bedrock has no media declaration in the bundled catalog, so a Bedrock connection serves no media operation. `available` answers true once the adapter is installed; what it serves is answered per model by `operations`, so an unreachable endpoint is a call's failure, not a capability. Video is the one resumable operation: `submit` stores the provider's operation reference as the handle and `wait` polls it and streams the result to a file, so a restart resumes the same job instead of starting another; a job that has not settled one hour after its start fails `provider_error`, which keeps a never-settling job from holding a scheduler slot. The hour also bounds a status request in flight and the wait between polls, so a stalled request fails at the deadline rather than running out the connection's longer timeout. aimux exposes no cancel for a started video job, so `cancelRemote` answers `unsupported` and the provider job runs to completion and is billed on its side. An output file's media type is read from the returned bytes, so a provider that answers a format other than the requested one is recorded by what it returned. +The product's built-in adapter is the `dim-modality-aimux` crate: aimux vocabulary stays inside the adapter. It serves `image.generate`, `image.edit`, `video.generate`, `speech.synthesize` and `speech.transcribe`, bound by catalog provider id, and `realtime.voice` for any model whose entry declares the openai-realtime transport: a realtime session is built from the connection, not from a vendor row. The relay connects to the connection's base URL with the declared path and the model id as its query, `http` and `https` becoming `ws` and `wss`; it sends the connection's headers and its bearer, connects through the connection's proxy, writes text frames as JSON and audio frames as the decoded bytes, and ends the session on a provider close, a socket failure or a frame it cannot write within ten seconds. It carries no control frames; those belong to a `direct` transport. A row exists for each bundled catalog provider whose media models an aimux vendor package executes (openai, google, xai, grok-build, elevenlabs, fal, deepgram, assemblyai, cartesia, gladia, groq, replicate, stability-ai, recraft, black-forest-labs, luma-ai, runway, kling, hume-ai, mistral-ai, rev-ai), and for the Dim account relay (`dimcode-api-oauth`), whose `/v1` base speaks the OpenAI Image API and is executed by the openai package; each row serves only what its package implements. `openai-codex` has no row: the aimux codex package answers `NoSuchModel` for image models, so its declared image models report the `adapter` reason. `image.edit` is served only by a package that reads the bytes an edit sends: openai (and so the Dim account relay), google, fal, replicate and black-forest-labs do, while stability-ai, recraft and luma-ai serve `image.generate` alone; a package that reports no file input for a given model drops edit for that model too. xAI's image models report `adapter` because that package answers `NoSuchModel`, and its transcription and synthesis models are served. A created provider's id is a canonical UUID, which matches no row, so its media operations report the `adapter` reason and `configure` refuses its models with it. The other A.1 categories (music, audio, 3D asset, motion) have no rows and keep the `build` reason. Amazon Bedrock has no media declaration in the bundled catalog, so a Bedrock connection serves no media operation. `available` answers true once the adapter is installed; what it serves is answered per model by `operations`, so an unreachable endpoint is a call's failure, not a capability. Video is the one resumable operation: `submit` stores the provider's operation reference as the handle and `wait` polls it and streams the result to a file, so a restart resumes the same job instead of starting another; a job that has not settled one hour after its start fails `provider_error`, which keeps a never-settling job from holding a scheduler slot. The hour also bounds a status request in flight and the wait between polls, so a stalled request fails at the deadline rather than running out the connection's longer timeout. aimux exposes no cancel for a started video job, so `cancelRemote` answers `unsupported` and the provider job runs to completion and is billed on its side. An output file's media type is read from the returned bytes, so a provider that answers a format other than the requested one is recorded by what it returned. `available` reports runtime availability without a reload (for example, a provider endpoint unreachable). An operation whose available adapters do not serve the configured or explicit model is reported as "no adapter for the configured model", and its submits fail `unavailable`. `image.understand` is not an adapter operation: it is served by a selectable vision model and is selection-only. OCR is not an adapter: it is a host task whose target is one of the host targets this build offers, `local/apple-vision` or `local/pp-ocr`, and both are started from a description the target publishes (A.2.1); when `local/pp-ocr` is not offered, it is not an option and `modality.ocr` still resolves `local/apple-vision`. A task naming a node other than the control node fails `node_unavailable`. `wait` names its job by `task_id`; when `submit` returned a `remote_handle`, the adapter may use it instead. `wait` with a stored `remote_handle` must work in a new generation; an adapter that returns no handle keys its own in-flight work by `task_id`, and only within one generation, so it cannot be resumed. @@ -458,11 +458,11 @@ The default snapshot is the one shape both methods return. A model reference is ``` - `revision` is the `modality` settings document revision; one CAS covers every operation key in that document, so a `configure` for one operation also invalidates a client holding a draft for another. Only `configure` consumes it. -- `default` is the persisted choice or `null`. When the model is no longer selectable or no available adapter serves it (for `image.understand`, when it is not a selectable vision model), `available` is `false` and `reason` says why. -- `effective` is the model a task or consumer would use now once the operation can run: it is resolved from the options even when the operation itself is `available: false` (no adapter in this build), so a client never has to know which part is settings and which is runtime. It is the default when available. When `default` is `null`, it is automatic resolution: Provider's global default selection when selectable and serving the operation, else the first selectable model that serves it in the order Provider's selectable-model read returns; `source` is `"automatic"`. An unavailable default yields `effective: null`, never a substituted model. -- `options` lists the models that serve the operation. The candidates come from Provider's non-conversational read (`selectableForModality`, §9.2), so a media model execution rejects — a non-chat model, or one whose text limits are undeclared — is a candidate when its catalog entry declares the operation. For `generate`, `edit` and `enhance` an available adapter decides which candidates serve which operation: the options are the deduplicated union of Provider's two reads, the execution-selectable models first and the declared ones after, in each read's order, kept when the adapter's `operations` serves them for that operation. For `image.understand` a selectable vision model serves instead, from Provider's `vision` capability. For a realtime operation the options are the models whose entry declares that `.` id, in Provider's order: the session's adapter is handed the transport the entry declares, so the entry itself is the per-model answer, and `open` refuses `unavailable` a declared model that has no transport. When no adapter serves the operation's category, the adapter narrows nothing and the options are the models whose Provider catalog entry declares that `.` id, in Provider's order, and an operation nothing declares has none. The owner computes the candidates from Provider's declared capabilities so clients never derive them. The current default is included when it is no longer an option, marked with its reason. The owner computes them at read time from Provider's read-only contract (§9.2) and the available adapters. An option carries only `{providerId, modelId, available, reason?}`: #790 returns ids and capabilities, not display names, so the client joins names from its existing Provider list or catalog reads by `{providerId, modelId}` and shows the ids when a name is unavailable. +- `default` is the persisted choice or `null`. When the model is no longer selectable or no available adapter serves it (for `image.understand`, when it is not a selectable vision model), `available` is `false` and `reason` says why: `provider` for a model no longer selectable, `runtime` when its adapter is unavailable, `build` for a category this build has no adapter for, and `adapter` otherwise. +- `effective` is the model a task or consumer would use now: it is resolved from the available options only, so it is `null` while no option can run, and a client never names a model the operation would refuse. It is the default when available. When `default` is `null`, it is automatic resolution: Provider's global default selection when it is an available option, else the first available option in Provider's order; `source` is `"automatic"`. An unavailable default yields `effective: null`, never a substituted model. +- `options` lists the models that serve the operation. The candidates come from Provider's non-conversational read (`selectableForModality`, §9.2), so a media model execution rejects — a non-chat model, or one whose text limits are undeclared — is a candidate when its catalog entry declares the operation. For every other operation the options are the models whose Provider catalog entry declares that `.` id, in Provider's order, and an operation nothing declares has none; each is `available` only when an available adapter's `operations` serves it for that operation, and is otherwise listed `available: false` with the reason no adapter runs it. An option's `available` therefore agrees with what a submission naming it would do. For `image.understand` a selectable vision model serves instead, from Provider's `vision` capability. For a realtime operation the options are the models whose entry declares that `.` id, in Provider's order: the session's adapter is handed the transport the entry declares, so the entry itself is the per-model answer, and `open` refuses `unavailable` a declared model that has no transport. The owner computes the candidates from Provider's declared capabilities so clients never derive them. The current default is included when it is no longer an option, marked with its reason. The owner computes them at read time from Provider's read-only contract (§9.2) and the available adapters. An option carries only `{providerId, modelId, available, reason?}`: #790 returns ids and capabilities, not display names, so the client joins names from its existing Provider list or catalog reads by `{providerId, modelId}` and shows the ids when a name is unavailable. - `configure` validates the operation and that the model is in that operation's options (for `image.understand`, selectable vision support; for `ocr.recognize`, one of the host targets the snapshot offers), then writes or clears the operation key through Settings' owner write with CAS. It accepts every A.1 operation that has a default key and never answers `modality_unavailable`: configuring is a settings write, not a runtime claim. An unknown category or operation answers `modality_unknown_operation`; `operation` is required where the operation has its own key (image, speech, OCR) and may be absent only for a category-keyed category. `model: null` clears that key (for OCR, `modality.ocr`); clearing restores automatic resolution, and a missing `model` is `invalid_params`. The write happens before the reply is sent, so a success means the default is persisted, and the reply is the same snapshot a following `modality.capabilities` call returns unless Provider changed in between. -- Configurable and available are different properties: the first belongs to settings, the second to the runtime. A persisted default can name a model of an operation this build cannot run; the snapshot stays honest by keeping that operation's `available: false` and its `build` or `adapter` reason, and `effective` still resolves over the options (the default when available, otherwise automatic) so clients do not implement resolution themselves. +- Configurable and available are different properties: the first belongs to settings, the second to the runtime. A persisted default can name a model of an operation this build cannot run; the snapshot stays honest by keeping that operation's `available: false` and its `build` or `adapter` reason, and `effective` resolves over the available options only (the default when available, otherwise automatic), so it is `null` whenever no option can run and clients do not implement resolution themselves. Boundary validation: inline inputs at most 8 MiB in total per submission, larger inputs by `node_path`, an absolute path of an existing regular file on the control node whose last component is not a link (earlier links are resolved); its opened file length is compared with the remaining submission budget, and copying rejects growth or truncation; all input files at most 100 MiB per submission (A5). Media types follow A.1's input column: image operations accept `image/*`, video operations `image/*` and `video/*`, `speech.transcribe` `audio/*`, and `asset` `image/*`; an operation whose input names no file refuses files. Each file name is one component, a valid pluginFiles name, distinct within the submission. `node` is refused `invalid_input` for a provider category, and for a host category it names the executing node, which is the control node (A15). Parameters are validated at submission against the adapter's `params_schema`; invalid parameters fail `invalid_input` and write nothing. Availability is checked before model resolution: an operation this build cannot run fails with the `reasons` `modality.capabilities` shows for it (Appendix C), so a missing adapter is never reported as a missing model. Model selection: explicit `model`; else the operation default; else automatic resolution; else `no_default_model`. An explicit model that is not selectable fails `model_unavailable`, an unavailable default fails `default_unavailable`, and a resolved model no available adapter serves fails `unavailable`; none of them falls back to another model. The resolved model is fixed in the record. `image.understand` and every `realtime.*` operation are not tasks: a submission for any of them fails `modality_unknown_operation`. `ocr.recognize` is a host task (§3.2): it takes exactly one input file of `image/*` or `application/pdf`, accepts `params.outputMode` `"text"` (the default) or `"layout"`, and validates no adapter schema. Its options are the host targets this host offers (A.2.1) and its default is `modality.ocr`; an explicit model that is neither `local/apple-vision` nor `local/pp-ocr` fails `model_unavailable`, and a host target this host cannot run fails `submit` `unavailable` with the operation's `platform` or `runtime` reason. A `node` other than the control node fails the task `node_unavailable`. At most 4 running tasks per category; others stay `queued` in submission order (A6). diff --git a/docs/zh/design/appserver/provider-management.md b/docs/zh/design/appserver/provider-management.md index 88d5e1fd54..87f43163e9 100644 --- a/docs/zh/design/appserver/provider-management.md +++ b/docs/zh/design/appserver/provider-management.md @@ -616,9 +616,15 @@ ModelCapabilities, reasoning?, serviceTier?}`——不是新的模型类型: **第二个操作:`selectableForModality`。** 同一端口还提供一次面向非对话用途的进程读取 (Modality §9.2):操作 `selectableForModality`,异步,请求 `{}`,回复 `{models: ModalityModelSnapshot[]}`,元素为 -`{target: {providerId, modelId}, operations: string[]}`。`operations` 是该模型目录条目在 -`metadata.raw.modalityCapabilities` 中声明的 `.` id,按条目中的顺序; -未声明任何操作的模型被省略。本次读取应用与 `selectableModels` 相同的 provider、账号、模型、 +`{target: {providerId, modelId}, operations: string[]}`。`operations` 是该模型目录条目声明的 +`.` id,按条目中的顺序;未声明任何操作的模型被省略。条目在 +`metadata.raw.modalityCapabilities` 中声明操作,显式列表(包括空列表)就是全部答案。没有列表的 +条目会被识别为图像模型,因为中转与账号目录列出这类模型时不带媒体元数据:其 id 是已知图像模型之一 +(`arcship-image`、`gpt-image-2` 系列、`grok-imagine-image` 系列)或包含 `seedream`;或其 `type` +为 `image`/`image-generation` 且输出包含图像或未说明;或 `imageGeneration` 为 true;或其唯一输出是 +`image`。这样的模型声明 `image.generate`,当它也读取图像或是已知模型时还声明 `image.edit`;`type` +为 `image-edit` 时只声明 `image.edit`,`imageGeneration: false` 不识别任何操作。下面的连接规则读取 +同一份声明。本次读取应用与 `selectableModels` 相同的 provider、账号、模型、 路由、凭据与状态规则,但去掉其 text modality、chat 类型与已声明文本上限三项要求:没有 `text` modality 的模型、非 chat 模型与 `limits_undeclared` 的模型只要声明了 modality 操作 仍是候选;不可用状态、停用的 Provider 或模型、缺少路由、已登出的账号与缺少静态凭据仍会排除 @@ -708,7 +714,7 @@ owner 实现是 `ProviderService::selectable_models` 与 跨语言操作契约由 [#1613](https://github.com/arcships/dim/issues/1613) 跟踪。 **规则。** 它应用 `selectableForModality` 读取的同一组规则——provider、账号、模型、路由、 -凭据与状态——并要求模型目录条目在其 `metadata.raw.modalityCapabilities` 中声明 `operation`。 +凭据与状态——并要求模型目录条目声明 `operation`,按上面读取的推导方式。 任何一条不满足的模型都在任何网络调用之前被拒绝:可用性类失败带执行对该模型报告的原因, 未声明的操作作为指明它的 invalid request 拒绝。读取与连接不会给出不同结论,因为二者共用 目录与其选择判定。托管账号的凭据租约读取同一条规则:只拒绝排除所有用途的原因,因此目录标记为 diff --git a/docs/zh/design/plugins/Modality.md b/docs/zh/design/plugins/Modality.md index ecb8566747..4ccad32ad4 100644 --- a/docs/zh/design/plugins/Modality.md +++ b/docs/zh/design/plugins/Modality.md @@ -164,7 +164,7 @@ sequenceDiagram `dimcode modality` 和 Web 设置页调用 `modality.capabilities`,返回每个类别与操作及其可用性原因、可选选项、已持久化的默认值,以及任务或使用方现在会使用的模型。不隐藏任何内容,也没有 `--all`。每个不可用的类别或操作都按维度显示原因,例如“not in this build”“Apple Vision needs macOS 12 or later on Apple Silicon”“the PP-OCR plugin is not running”“the PP-OCR plugin needs an update”“no adapter”“not configured”“no adapter for the configured model”(决策 E16)。最后一项由 Modality 已采纳的业务配置(`modality` 设置文档中的默认值或显式模型,及其 Provider 连接)对照 Modality 能解析到的适配器得出(§9.1)。 -图像操作是第一个实现切片,产品构建现在为该切片的一部分内置了适配器:内置 `dim-modality-aimux` 适配器(A.2)经 aimux 服务 `generate`,并在提供方的包读取编辑输入文件时服务 `edit`,而 `enhance` 仍是没有任何构建服务的适配器操作,因此以 `adapter` 原因报告 `unavailable`。可用性是运行时的属性,并按模型回答:安装后 `available` 即为 true,具体服务什么由 `operations` 针对任务所指的模型决定。内置家族名副本为 A.2 列出的内建目录提供方回答图像 `operations`。自建提供方的 UUID 没有专属副本时,仍会解析到家族名副本;其图像模型报 `adapter` 原因是因为该副本的 `operations` 不为它们返回图像操作,而不是没有绑定。已解析的适配器若不为 Provider 列出的任何模型服务,不算缺少适配器,并如实说明:图像操作仍用 `adapter` 维度,报“the adapter serves no image model Provider lists”,其选项是已声明的模型——与任何没有适配器服务的操作相同。`understand` 为 Session 使用方解析目标(§9.4)。可配置性是设置的属性:只要模型在该操作的可选选项中,`configure` 就接受任何有默认 key 的 A.1 操作的默认值,因此默认值可以在运行时落地之前持久化;本构建不能运行的操作仍保持 `available: false` 及其 `build` 或 `adapter` 原因。流程测试配置 fixture 适配器服务它们所覆盖的适配器操作,端到端流程则让内置适配器对着桩提供方运行。 +图像操作是第一个实现切片,产品构建现在为该切片的一部分内置了适配器:内置 `dim-modality-aimux` 适配器(A.2)经 aimux 服务 `generate`,并在提供方的包读取编辑输入文件时服务 `edit`,而 `enhance` 仍是没有任何构建服务的适配器操作,因此以 `adapter` 原因报告 `unavailable`。可用性是运行时的属性,并按模型回答:安装后 `available` 即为 true,具体服务什么由 `operations` 针对任务所指的模型决定。内置家族名副本为 A.2 列出的内建目录提供方回答图像 `operations`。自建提供方的 UUID 没有专属副本时,仍会解析到家族名副本;其图像模型报 `adapter` 原因是因为该副本的 `operations` 不为它们返回图像操作,而不是没有绑定。已解析的适配器若不为 Provider 列出的任何模型服务,不算缺少适配器,并如实说明:图像操作仍用 `adapter` 维度,报“the adapter serves no image model Provider lists”,其选项是已声明的模型,每个都 `available: false` 并带上没有适配器运行它的原因,因此选项从不声称能运行一个其操作会拒绝的模型。`understand` 为 Session 使用方解析目标(§9.4)。可配置性是设置的属性:只要模型在该操作的选项中(无论是否有适配器服务),`configure` 就接受任何有默认 key 的 A.1 操作的默认值,因此默认值可以在运行时落地之前持久化;保存后的默认值显示 `available: false` 及其原因,本构建不能运行的操作仍保持 `available: false` 及其 `build` 或 `adapter` 原因。主机目标例外:只有在本机能运行时才可配置(A.2.1)。流程测试配置 fixture 适配器服务它们所覆盖的适配器操作,端到端流程则让内置适配器对着桩提供方运行。 Realtime 选项跟随 Provider 的传输声明,不经解析到的适配器的 `operations` 收窄。因此,不服务 realtime 的提供方专属副本可能让声明过的模型仍出现在选项中,但 `realtime.open` 以 `unavailable` 拒绝;已存在的提供方副本缺少某个操作时,不会重试家族名副本。 @@ -349,7 +349,7 @@ Settings 业务来源与 `pluginFiles` 补充是对其他插件的改动,列 `Job` 为 `{ task_id, category, operation, model: {providerId, modelId}, params, files: [{ name, media_type, path }], work_dir }`。内联输入的 `path` 是 Modality 存放在 `modality/tasks//input/` 的文件的绝对路径;通过 `node_path` 给出的输入记录 Modality 得到的规范路径(最后一个组件不得是链接;更早的链接会被解析),Modality 只读取一次以取得 `bytes` 与 `sha256`,从不复制,执行方就地读取。`work_dir` 是任务的 `modality/tasks//work` 目录,调用前创建;每个结果文件解析为其中的普通文件。调用携带的 `connection` 是 `ModalityConnection`,即 Provider 非对话连接解析返回的 Rust 形态(`kind`、`provider_id`、`model`、端点与凭据材料,以及 `realtime.*` 用途下目录条目的 `realtime: { protocol, path }` 声明)。它不是数据:仅为一次调用按值传入,从不存储、记录日志、返回或序列化,这也是适配器服务目前只在进程内的原因(A.2,[#1613](https://github.com/arcships/dim/issues/1613))。该声明是 Provider 对条目 `metadata.raw.realtime` 的读取;条目未声明的模型,以及从不携带它的配置模型 profile,会在适配器被调用之前以 `unavailable` 拒绝,消息为 “The model declares no realtime transport”。中继从连接的 base URL、声明的 `path` 与模型 id 组合出套接字地址,因此路径由目录条目声明,从不推导。 -产品内置适配器是 `dim-modality-aimux` crate:aimux 的词汇留在适配器内部。它服务 `image.generate`、`image.edit`、`video.generate`、`speech.synthesize` 与 `speech.transcribe`,按目录提供方 id 绑定;并对任何条目声明了 openai-realtime 传输的模型服务 `realtime.voice`,因为实时会话由连接构建,而不是由厂商行决定。中继以连接的 base URL 加声明的路径和作为查询的模型 id 连接,`http` 与 `https` 变为 `ws` 与 `wss`;它发送连接的头部与 bearer、经连接的代理连接、把文本帧写成 JSON 并把音频帧写成解码后的字节,并在提供方关闭、套接字失败或十秒内写不出一帧时结束会话。它不承载控制帧——控制帧属于 `direct` 传输。凡是其媒体模型由某个 aimux 厂商包执行的内建目录提供方都有一行(openai、google、xai、grok-build、elevenlabs、fal、deepgram、assemblyai、cartesia、gladia、groq、replicate、stability-ai、recraft、black-forest-labs、luma-ai、runway、kling、hume-ai、mistral-ai、rev-ai),每行只服务其包实际实现的操作。`image.edit` 只由读取编辑输入字节的包服务:openai、google、fal、replicate、black-forest-labs 会读取;stability-ai、recraft、luma-ai 只服务 `image.generate`;包对某个模型报告不接受文件输入时,该模型也不提供 edit。xAI 的图像模型因该包回答 `NoSuchModel` 而报 `adapter`,其转录与合成模型则被服务。自建提供方的 id 是规范 UUID,不匹配任何行,因此其媒体操作报 `adapter` 原因,`configure` 也以该原因拒绝其模型。其他 A.1 类别(音乐、音频、3D 资产、动作)没有对应行,保持 `build` 原因。内建目录没有为 Amazon Bedrock 声明任何媒体模型,因此 Bedrock 连接不服务媒体操作。安装后 `available` 即为 true;服务范围按模型由 `operations` 回答,端点不可达是某次调用的失败,而不是能力。视频是唯一可恢复的操作:`submit` 把提供方的操作引用存为句柄,`wait` 轮询它并把结果流式写入文件,因此重启恢复同一作业而不会重新发起;开始后一小时仍未结束的作业以 `provider_error` 失败,避免永不结束的作业一直占用调度槽位。该上限同样约束在途的状态请求与两次轮询之间的等待,因此挂起的请求会在截止时失败,而不是跑满连接更长的超时。aimux 对已启动的视频作业不提供取消,因此 `cancelRemote` 回答 `unsupported`,提供方作业会在其一侧跑完并计费。输出文件的媒体类型从返回字节读取,提供方返回与请求不同的格式时,按实际返回记录。 +产品内置适配器是 `dim-modality-aimux` crate:aimux 的词汇留在适配器内部。它服务 `image.generate`、`image.edit`、`video.generate`、`speech.synthesize` 与 `speech.transcribe`,按目录提供方 id 绑定;并对任何条目声明了 openai-realtime 传输的模型服务 `realtime.voice`,因为实时会话由连接构建,而不是由厂商行决定。中继以连接的 base URL 加声明的路径和作为查询的模型 id 连接,`http` 与 `https` 变为 `ws` 与 `wss`;它发送连接的头部与 bearer、经连接的代理连接、把文本帧写成 JSON 并把音频帧写成解码后的字节,并在提供方关闭、套接字失败或十秒内写不出一帧时结束会话。它不承载控制帧——控制帧属于 `direct` 传输。凡是其媒体模型由某个 aimux 厂商包执行的内建目录提供方都有一行(openai、google、xai、grok-build、elevenlabs、fal、deepgram、assemblyai、cartesia、gladia、groq、replicate、stability-ai、recraft、black-forest-labs、luma-ai、runway、kling、hume-ai、mistral-ai、rev-ai),以及 Dim 账号中转(`dimcode-api-oauth`)——它的 `/v1` 基址提供 OpenAI Image API,由 openai 包执行;每行只服务其包实际实现的操作。`openai-codex` 没有行:aimux 的 codex 包对图像模型回答 `NoSuchModel`,因此它声明的图像模型报 `adapter` 原因。`image.edit` 只由读取编辑输入字节的包服务:openai(因此包括 Dim 账号中转)、google、fal、replicate、black-forest-labs 会读取;stability-ai、recraft、luma-ai 只服务 `image.generate`;包对某个模型报告不接受文件输入时,该模型也不提供 edit。xAI 的图像模型因该包回答 `NoSuchModel` 而报 `adapter`,其转录与合成模型则被服务。自建提供方的 id 是规范 UUID,不匹配任何行,因此其媒体操作报 `adapter` 原因,`configure` 也以该原因拒绝其模型。其他 A.1 类别(音乐、音频、3D 资产、动作)没有对应行,保持 `build` 原因。内建目录没有为 Amazon Bedrock 声明任何媒体模型,因此 Bedrock 连接不服务媒体操作。安装后 `available` 即为 true;服务范围按模型由 `operations` 回答,端点不可达是某次调用的失败,而不是能力。视频是唯一可恢复的操作:`submit` 把提供方的操作引用存为句柄,`wait` 轮询它并把结果流式写入文件,因此重启恢复同一作业而不会重新发起;开始后一小时仍未结束的作业以 `provider_error` 失败,避免永不结束的作业一直占用调度槽位。该上限同样约束在途的状态请求与两次轮询之间的等待,因此挂起的请求会在截止时失败,而不是跑满连接更长的超时。aimux 对已启动的视频作业不提供取消,因此 `cancelRemote` 回答 `unsupported`,提供方作业会在其一侧跑完并计费。输出文件的媒体类型从返回字节读取,提供方返回与请求不同的格式时,按实际返回记录。 `available` 在不重载的情况下报告运行时可用性(例如提供方端点不可达)。若某个操作的可用适配器都不服务已配置或显式指定的模型,则报告为“no adapter for the configured model”,其提交以 `unavailable` 失败。`image.understand` 不是适配器操作:它由一个可选的视觉模型服务,且只做选择。OCR 不是适配器:它是宿主任务,其目标是本构建提供的宿主目标之一 `local/apple-vision` 或 `local/pp-ocr`,两者都从目标发布的描述启动(A.2.1);当 `local/pp-ocr` 未提供时,它不是选项,`modality.ocr` 仍解析 `local/apple-vision`。指明控制节点以外节点的任务以 `node_unavailable` 失败。`wait` 以 `task_id` 指名它等待的作业;当 `submit` 返回了 `remote_handle` 时,适配器可以改用它。带已存储 `remote_handle` 的 `wait` 必须能在新一代中工作;不返回句柄的适配器以 `task_id` 记录自己进行中的工作,且仅限同一代内,因此无法恢复。 @@ -452,11 +452,11 @@ wire 参数形状错误为 `invalid_params`,未知类别或操作为 `modality ``` - `revision` 是 `modality` 设置文档的 revision;一次 CAS 覆盖该文档中的全部操作 key,因此对某个操作的 `configure` 也会让持有其他操作草稿的客户端失效。只有 `configure` 使用它。 -- `default` 是已持久化的选择或 `null`。模型不再可选、或没有可用适配器服务它时(对 `image.understand`,是它不是可选的视觉模型时),`available` 为 `false`,`reason` 说明原因。 -- `effective` 是该操作能运行之后,任务或使用方现在会使用的模型:即使操作本身 `available: false`(本构建没有适配器),它仍从选项解析,客户端因此无需分辨哪部分属于设置、哪部分属于运行时。默认值可用时就是默认值。`default` 为 `null` 时它是自动解析:Provider 的全局默认选择可选且服务该操作时用它,否则用 Provider 可选模型读取顺序中第一个可选的、服务该操作的模型;`source` 为 `"automatic"`。不可用的默认值给出 `effective: null`,从不替换成别的模型。 -- `options` 列出服务该操作的模型。候选来自 Provider 的非会话读取(`selectableForModality`,§9.2),因此被执行拒绝的媒体模型——非 chat 模型,或未声明文本上限的模型——只要其目录条目声明了该操作就是候选。对 `generate`、`edit` 与 `enhance`,由可用适配器决定哪些候选服务哪个操作:选项是 Provider 两次读取的去重并集,先执行可选的模型、后已声明的模型,各自按读取顺序,并保留适配器的 `operations` 为该操作服务的那些。对 `image.understand`,改由可选的视觉模型服务,取自 Provider 的 `vision` 能力。对实时操作,选项是其条目声明了该 `.` id 的模型,按 Provider 的顺序:会话适配器收到的正是条目声明的传输,因此条目本身就是逐模型答案;声明了操作但没有传输的模型由 `open` 以 `unavailable` 拒绝。当没有适配器服务该操作的类别时,适配器不收窄任何候选,选项是其 Provider 目录条目声明了该 `.` id 的模型,按 Provider 的顺序;没有任何声明的操作选项为空。所有者从 Provider 的已声明能力计算候选,客户端不自行推导。当前默认值不再是选项时也会列出,并标注原因。所有者读取时从 Provider 的只读契约(§9.2)与可用适配器计算它们。选项只带 `{providerId, modelId, available, reason?}`:读取返回 id 与能力,不返回展示名,因此客户端按 `{providerId, modelId}` 从它已有的 Provider 列表或目录读取中并入名字,取不到名字时显示 id。 +- `default` 是已持久化的选择或 `null`。模型不再可选、或没有可用适配器服务它时(对 `image.understand`,是它不是可选的视觉模型时),`available` 为 `false`,`reason` 说明原因:不再可选时为 `provider`,其适配器不可用时为 `runtime`,本构建没有该类别的适配器时为 `build`,其余为 `adapter`。 +- `effective` 是任务或使用方现在会使用的模型:它只从可用的选项解析,因此没有选项能运行时为 `null`,客户端从不会拿到一个操作会拒绝的模型。默认值可用时就是默认值。`default` 为 `null` 时它是自动解析:Provider 的全局默认选择是可用选项时用它,否则用 Provider 顺序中第一个可用选项;`source` 为 `"automatic"`。不可用的默认值给出 `effective: null`,从不替换成别的模型。 +- `options` 列出服务该操作的模型。候选来自 Provider 的非会话读取(`selectableForModality`,§9.2),因此被执行拒绝的媒体模型——非 chat 模型,或未声明文本上限的模型——只要其目录条目声明了该操作就是候选。对其他操作,选项是其 Provider 目录条目声明了该 `.` id 的模型,按 Provider 的顺序,没有任何声明的操作选项为空;只有可用适配器的 `operations` 为该操作服务它时才 `available`,否则列为 `available: false` 并带上没有适配器运行它的原因。因此选项的 `available` 与以它提交时的结果一致。对 `image.understand`,改由可选的视觉模型服务,取自 Provider 的 `vision` 能力。对实时操作,选项是其条目声明了该 `.` id 的模型,按 Provider 的顺序:会话适配器收到的正是条目声明的传输,因此条目本身就是逐模型答案;声明了操作但没有传输的模型由 `open` 以 `unavailable` 拒绝。所有者从 Provider 的已声明能力计算候选,客户端不自行推导。当前默认值不再是选项时也会列出,并标注原因。所有者读取时从 Provider 的只读契约(§9.2)与可用适配器计算它们。选项只带 `{providerId, modelId, available, reason?}`:读取返回 id 与能力,不返回展示名,因此客户端按 `{providerId, modelId}` 从它已有的 Provider 列表或目录读取中并入名字,取不到名字时显示 id。 - `configure` 先校验操作以及模型在该操作的可选选项中(对 `image.understand`,可选视觉支持;对 `ocr.recognize`,快照当前提供的宿主目标之一),再经 Settings 的所有者写入以 CAS 写入或清除该操作 key。它接受任何有默认 key 的 A.1 操作,且从不答复 `modality_unavailable`:配置是设置写入,不是运行时断言。未知类别或操作答复 `modality_unknown_operation`;操作有自己的 key 时(image、speech、OCR)`operation` 必填,只有按类别划分 key 的类别可以省略。`model: null` 清除该 key(对 OCR 即 `modality.ocr`);清除即恢复自动解析;缺少 `model` 为 `invalid_params`。写入在回复发出之前完成,因此成功即表示默认值已持久化,且该回复与紧随其后的 `modality.capabilities` 读到的一致(除非 Provider 在此期间变化)。 -- 可配置性与可用性是两个不同的属性:前者属于设置,后者属于运行时。已持久化的默认值可以指向本构建不能运行的操作的模型;快照通过保持该操作的 `available: false` 及其 `build` 或 `adapter` 原因保持诚实,而 `effective` 仍在选项上解析(默认值可用时用默认值,否则自动解析),客户端因此无需自行实现解析。 +- 可配置性与可用性是两个不同的属性:前者属于设置,后者属于运行时。已持久化的默认值可以指向本构建不能运行的操作的模型;快照通过保持该操作的 `available: false` 及其 `build` 或 `adapter` 原因保持诚实,而 `effective` 只在可用选项上解析(默认值可用时用默认值,否则自动解析),没有选项能运行时为 `null`,客户端因此无需自行实现解析。 边界校验:每次提交的内联输入合计至多 8 MiB,更大的输入使用 `node_path`——控制节点上已存在普通文件的绝对路径,最后一个组件不得是链接(更早的链接会被解析);读取前先将其长度与 100 MiB 提交预算的剩余量比较,记录的是规范路径,执行方在该路径读取,Modality 从不复制;每次提交的输入文件合计至多 100 MiB(A5)。媒体类型遵循 A.1 的输入列:图像操作接受 `image/*`,视频操作接受 `image/*` 与 `video/*`,`speech.transcribe` 接受 `audio/*`,`asset` 接受 `image/*`;输入不指名文件的操作拒绝文件。每个文件名是单个组件、合法的 pluginFiles 名称,且在提交内互不相同。`node` 对提供方类别以 `invalid_input` 拒绝,对宿主类别则指明执行节点,即控制节点(A15)。参数在提交时按适配器的 `params_schema` 校验;非法参数以 `invalid_input` 失败且不写入任何内容。可用性检查先于模型解析:本构建无法运行的操作会带着 `modality.capabilities` 中该操作的原因失败,见附录 C,因此缺失适配器不会被报成缺失模型。模型选择:显式 `model`;否则操作默认值;否则自动解析;否则 `no_default_model`。不可选的显式模型以 `model_unavailable` 失败,不可用的默认值以 `default_unavailable` 失败,解析出的模型没有可用适配器服务时以 `unavailable` 失败;都不回退到其他模型。解析出的模型固定在记录中。`image.understand` 与每个 `realtime.*` 操作都不是任务:为它们提交会以 `modality_unknown_operation` 失败。`ocr.recognize` 是宿主任务(§3.2):只接受一个输入文件,`image/*` 或 `application/pdf`,接受 `params.outputMode` `"text"`(默认)或 `"layout"`,不校验适配器 schema。其选项是本宿主提供的宿主目标(A.2.1),其默认值是 `modality.ocr`;既非 `local/apple-vision` 也非 `local/pp-ocr` 的显式模型以 `model_unavailable` 失败,本宿主无法运行的宿主目标使 `submit` 以 `unavailable` 失败并带该操作的 `platform` 或 `runtime` 原因。指明控制节点以外节点的任务以 `node_unavailable` 失败。每个类别至多 4 个运行中任务;其余按提交顺序保持 `queued`(A6)。 From c77746ed0c3e884db28704bd212d98053caa5d32 Mon Sep 17 00:00:00 2001 From: zerob13 Date: Fri, 20 Nov 2026 18:43:16 +0800 Subject: [PATCH 2/5] fix(modality): avoid relay retries and report operation-specific availability --- crates/dim-modality-aimux/Cargo.toml | 2 +- crates/dim-modality-aimux/src/job.rs | 4 ++ crates/dim-modality-aimux/tests/adapter.rs | 40 ++++++++++++++-- crates/dim-modality/src/lib.rs | 31 +++++++------ crates/dim-modality/tests/modality_flow.rs | 46 ++++++++++++++++++- docs/design/appserver/provider-management.md | 5 +- docs/design/plugins/Modality.md | 4 +- .../design/appserver/provider-management.md | 2 +- docs/zh/design/plugins/Modality.md | 4 +- 9 files changed, 111 insertions(+), 27 deletions(-) diff --git a/crates/dim-modality-aimux/Cargo.toml b/crates/dim-modality-aimux/Cargo.toml index fa19b8179f..43e8593869 100644 --- a/crates/dim-modality-aimux/Cargo.toml +++ b/crates/dim-modality-aimux/Cargo.toml @@ -35,7 +35,7 @@ dim-app-server.workspace = true http = "1" serde_json.workspace = true sha2 = "0.10.9" -tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] } +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util", "time"] } tokio-tungstenite.workspace = true tokio-util.workspace = true uuid.workspace = true diff --git a/crates/dim-modality-aimux/src/job.rs b/crates/dim-modality-aimux/src/job.rs index 8e698c96e9..b5a9757174 100644 --- a/crates/dim-modality-aimux/src/job.rs +++ b/crates/dim-modality-aimux/src/job.rs @@ -51,6 +51,10 @@ fn milliseconds(seconds: f64) -> i64 { pub fn image_options(job: &Job, vendor: &Vendor) -> Result { let params = &job.params; let mut options = ImageCallOptions::new(text(params, "prompt").unwrap_or_default()); + if vendor.catalog == "dimcode-api-oauth" { + // A timed-out relay request may already have started a paid job. + options.max_retries = Some(0); + } if text(params, "prompt").is_none() { options.prompt = None; } diff --git a/crates/dim-modality-aimux/tests/adapter.rs b/crates/dim-modality-aimux/tests/adapter.rs index 34d9a8e64b..032ab7f18c 100644 --- a/crates/dim-modality-aimux/tests/adapter.rs +++ b/crates/dim-modality-aimux/tests/adapter.rs @@ -75,7 +75,7 @@ fn unauthorized() -> Reply { #[derive(Clone)] struct Scripted { requests: Arc>>, - respond: Arc Reply + Send + Sync>, + respond: Arc Option + Send + Sync>, } #[async_trait] @@ -97,7 +97,9 @@ impl Fetch for Scripted { body: request.body.to_vec(), }; self.requests.lock().unwrap().push(recorded.clone()); - let reply = (self.respond)(&recorded); + let Some(reply) = (self.respond)(&recorded) else { + return std::future::pending().await; + }; Ok(FetchResponse::from_bytes( reply.status, HeaderMap::new(), @@ -114,7 +116,7 @@ fn scripted( let requests = Arc::new(Mutex::new(Vec::new())); let fetch: FetchFunction = Arc::new(Scripted { requests: requests.clone(), - respond: Arc::new(respond), + respond: Arc::new(move |request| Some(respond(request))), }); (Arc::new(MediaAdapter::scripted(fetch)), requests) } @@ -622,6 +624,38 @@ fn path_is_inside(path: &Path, dir: &Path) -> bool { path.strip_prefix(dir).is_ok() } +#[tokio::test(start_paused = true)] +async fn the_dim_account_relay_does_not_retry_a_timed_out_post() { + let requests = Arc::new(Mutex::new(Vec::new())); + let adapter = Arc::new(MediaAdapter::scripted(Arc::new(Scripted { + requests: requests.clone(), + respond: Arc::new(|_| None), + }))); + let dir = work_dir("relay-timeout"); + let error = run( + &adapter, + job( + "dimcode-api-oauth", + "arcship-image", + "image", + "generate", + json!({"prompt": "a red circle"}), + Vec::new(), + &dir, + ), + "https://relay.example.test/v1", + "arcship-image", + ) + .await + .unwrap_err(); + assert_eq!(error.code, AdapterErrorCode::ProviderError); + let requests = requests.lock().unwrap(); + assert_eq!(requests.len(), 1, "{requests:?}"); + assert_eq!(requests[0].method, Method::POST); + assert!(requests[0].url.ends_with("/images/generations")); + std::fs::remove_dir_all(dir).unwrap(); +} + /// The Dim account relay speaks the OpenAI Image API on its `/v1` base with /// the account's bearer, for a model id only the relay knows (#1887). #[tokio::test] diff --git a/crates/dim-modality/src/lib.rs b/crates/dim-modality/src/lib.rs index 23e9b2011d..6b4961d9f1 100644 --- a/crates/dim-modality/src/lib.rs +++ b/crates/dim-modality/src/lib.rs @@ -863,27 +863,16 @@ impl Evaluation { vec![reason("configuration", "No selectable vision model")], ) } - } else if self.adapter_serves(category) { + } else if is_realtime(category) && self.adapter_serves(category) { match self.adapter_available() { false => (false, vec![reason("runtime", "The adapter is unavailable")]), - // A realtime operation names itself: the adapter serves the - // category for one of its operations and nothing serves this - // one, which a client reads as an adapter gap, not a - // configuration one (A.3). - true if !served && is_realtime(category) => ( + true if !served => ( false, vec![reason( "adapter", format!("No available adapter serves {}", row.id(category)), )], ), - true if !served => ( - false, - vec![reason( - "configuration", - "No selectable model is served by an available adapter", - )], - ), true => (true, vec![]), } } else if host_target(category, row.operation).is_some() { @@ -899,6 +888,22 @@ impl Evaluation { } (false, reasons) } + } else if served && !is_realtime(category) { + (true, vec![]) + } else if let Some(runtime) = options + .iter() + .filter_map(|option| option.reason.as_ref()) + .find(|reason| reason.dimension == "runtime") + { + (false, vec![runtime.clone()]) + } else if self.adapter_serves(category) { + ( + false, + vec![reason( + "adapter", + format!("No available adapter serves {}", row.id(category)), + )], + ) } else if category == "image" { let detail = if self.has_adapter() { "The adapter serves no image model Provider lists" diff --git a/crates/dim-modality/tests/modality_flow.rs b/crates/dim-modality/tests/modality_flow.rs index a407e191ea..24d5d8db73 100644 --- a/crates/dim-modality/tests/modality_flow.rs +++ b/crates/dim-modality/tests/modality_flow.rs @@ -1488,6 +1488,7 @@ async fn capabilities_and_configure_resolve_defaults_through_the_fixture_adapter "a selectable default that no adapter serves is unavailable: {edit}" ); assert_eq!(edit["default"]["reason"]["dimension"], "adapter"); + assert_eq!(edit["reasons"][0]["dimension"], "adapter"); assert!(edit["effective"].is_null()); fixture.set_available(false); @@ -1567,9 +1568,50 @@ async fn a_declared_media_model_served_by_the_adapter_is_an_option() { ); let edit = operation(&snapshot, "edit"); assert_eq!(edit["available"], false); + assert_eq!(edit["reasons"][0]["dimension"], "adapter"); assert_eq!( - edit["reasons"][0]["detail"], "No selectable model is served by an available adapter", - "the adapter narrows the candidates per operation" + operation(&snapshot, "enhance")["reasons"][0]["dimension"], + "adapter" + ); + server.shutdown(); + server.join().await.unwrap(); + std::fs::remove_dir_all(home).unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_online_speech_adapter_does_not_hide_the_offline_image_adapter() { + let image = Arc::new(FixtureAdapter::default()); + image.serve(&[("image-media", &["image.generate"])]); + image.set_available(false); + let speech = Arc::new(FixtureAdapter::default()); + speech.serve(&[("voice", &["speech.synthesize"])]); + let home = home("dm-mixed-adapters"); + let server = start_with_copies(home.clone(), speech, image).await; + let mut client = Client::new_version(&server, false, 3).await; + create_provider_with(&mut client, vec![media("image-media", &["image.generate"])]).await; + assert_ok( + &client + .rpc( + "provider.create", + json!({ + "providerId": "018ec73f-0000-7000-8000-0000000000bb", + "displayName": "Speech fixture", + "connection": {"driverKind": "openai-compatible", "baseUrl": "http://127.0.0.1:1/v1", "auth": {"type": "anonymous"}}, + "models": [chat("voice", &["speech.synthesize"])], + "enabled": true + }), + ) + .await, + ); + let snapshot = client.rpc("modality.capabilities", json!({})).await; + assert_ok(&snapshot); + let generate = operation(&snapshot, "generate"); + assert_eq!(generate["available"], false, "{generate}"); + assert_eq!(generate["options"][0]["reason"]["dimension"], "runtime"); + assert_eq!(generate["reasons"][0], generate["options"][0]["reason"]); + assert_eq!( + operation_in(&snapshot, "speech", "synthesize")["available"], + true ); server.shutdown(); server.join().await.unwrap(); diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 19a7582f62..f37b9e71f7 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -1030,9 +1030,8 @@ order; a model that declares none is omitted. An entry declares its operations in `metadata.raw.modalityCapabilities`, and an explicit list, an empty one included, is the whole answer. An entry with no list is recognized as an image model, because relay and account catalogs list such models without media -metadata: its id is one of the known image models (`arcship-image`, the -`gpt-image-2` family, the `grok-imagine-image` family) or names `seedream`, or -its `type` is `image`/`image-generation` with image or no stated output, or +metadata: its id is `arcship-image`, a known ID in the `gpt-image-2` or +`grok-imagine-image` family, or names `seedream`, or its `type` is `image`/`image-generation` with image or no stated output, or `imageGeneration` is true, or its only output is `image`. Such a model declares `image.generate`, and `image.edit` too when it also reads images or is a known model; a `type` of `image-edit` declares `image.edit` alone, and diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index 9220671b10..b95a42294c 100644 --- a/docs/design/plugins/Modality.md +++ b/docs/design/plugins/Modality.md @@ -351,7 +351,7 @@ The connection-bearing calls carry credential material for one call, not seriali `Job` is `{ task_id, category, operation, model: {providerId, modelId}, params, files: [{ name, media_type, path }], work_dir }`. Every input's `path` is the absolute path of the file Modality stored at `modality/tasks//input/`. A `node_path` source is opened once without following a final symlink, bounded by the submission budget, copied through `pluginFiles`, and hashed while copying. Source removal or replacement after submission cannot change the accepted input. `work_dir` is the task's `modality/tasks//work` directory, created before the call; every result file resolves to a regular file inside it. The `connection` a call carries is `ModalityConnection`, the Rust shape Provider's non-conversational connection resolution returns (`kind`, `provider_id`, `model`, endpoint and credential material, and the catalog entry's `realtime: { protocol, path }` declaration for a `realtime.*` use). It is not data: it is passed by value for one call, never stored, logged, returned or serialized, which is why the adapter service is in-process today (A.2, [#1613](https://github.com/arcships/dim/issues/1613)). The declaration is Provider's read of the entry's `metadata.raw.realtime`; a model whose entry declares none, and a configured-model profile, which never carries one, is refused `unavailable` with "The model declares no realtime transport" before the adapter is called. The relay takes the socket URL from the connection's base URL, the declared `path` and the model id, so the path is declared by the catalog entry and never derived. -The product's built-in adapter is the `dim-modality-aimux` crate: aimux vocabulary stays inside the adapter. It serves `image.generate`, `image.edit`, `video.generate`, `speech.synthesize` and `speech.transcribe`, bound by catalog provider id, and `realtime.voice` for any model whose entry declares the openai-realtime transport: a realtime session is built from the connection, not from a vendor row. The relay connects to the connection's base URL with the declared path and the model id as its query, `http` and `https` becoming `ws` and `wss`; it sends the connection's headers and its bearer, connects through the connection's proxy, writes text frames as JSON and audio frames as the decoded bytes, and ends the session on a provider close, a socket failure or a frame it cannot write within ten seconds. It carries no control frames; those belong to a `direct` transport. A row exists for each bundled catalog provider whose media models an aimux vendor package executes (openai, google, xai, grok-build, elevenlabs, fal, deepgram, assemblyai, cartesia, gladia, groq, replicate, stability-ai, recraft, black-forest-labs, luma-ai, runway, kling, hume-ai, mistral-ai, rev-ai), and for the Dim account relay (`dimcode-api-oauth`), whose `/v1` base speaks the OpenAI Image API and is executed by the openai package; each row serves only what its package implements. `openai-codex` has no row: the aimux codex package answers `NoSuchModel` for image models, so its declared image models report the `adapter` reason. `image.edit` is served only by a package that reads the bytes an edit sends: openai (and so the Dim account relay), google, fal, replicate and black-forest-labs do, while stability-ai, recraft and luma-ai serve `image.generate` alone; a package that reports no file input for a given model drops edit for that model too. xAI's image models report `adapter` because that package answers `NoSuchModel`, and its transcription and synthesis models are served. A created provider's id is a canonical UUID, which matches no row, so its media operations report the `adapter` reason and `configure` refuses its models with it. The other A.1 categories (music, audio, 3D asset, motion) have no rows and keep the `build` reason. Amazon Bedrock has no media declaration in the bundled catalog, so a Bedrock connection serves no media operation. `available` answers true once the adapter is installed; what it serves is answered per model by `operations`, so an unreachable endpoint is a call's failure, not a capability. Video is the one resumable operation: `submit` stores the provider's operation reference as the handle and `wait` polls it and streams the result to a file, so a restart resumes the same job instead of starting another; a job that has not settled one hour after its start fails `provider_error`, which keeps a never-settling job from holding a scheduler slot. The hour also bounds a status request in flight and the wait between polls, so a stalled request fails at the deadline rather than running out the connection's longer timeout. aimux exposes no cancel for a started video job, so `cancelRemote` answers `unsupported` and the provider job runs to completion and is billed on its side. An output file's media type is read from the returned bytes, so a provider that answers a format other than the requested one is recorded by what it returned. +The product's built-in adapter is the `dim-modality-aimux` crate: aimux vocabulary stays inside the adapter. It serves `image.generate`, `image.edit`, `video.generate`, `speech.synthesize` and `speech.transcribe`, bound by catalog provider id, and `realtime.voice` for any model whose entry declares the openai-realtime transport: a realtime session is built from the connection, not from a vendor row. The relay connects to the connection's base URL with the declared path and the model id as its query, `http` and `https` becoming `ws` and `wss`; it sends the connection's headers and its bearer, connects through the connection's proxy, writes text frames as JSON and audio frames as the decoded bytes, and ends the session on a provider close, a socket failure or a frame it cannot write within ten seconds. It carries no control frames; those belong to a `direct` transport. A row exists for each bundled catalog provider whose media models an aimux vendor package executes (openai, google, xai, grok-build, elevenlabs, fal, deepgram, assemblyai, cartesia, gladia, groq, replicate, stability-ai, recraft, black-forest-labs, luma-ai, runway, kling, hume-ai, mistral-ai, rev-ai), and for the Dim account relay (`dimcode-api-oauth`), whose `/v1` base speaks the OpenAI Image API and is executed by the openai package. The adapter does not automatically retry the relay’s image requests because a failed response can follow the start of a paid job. Each row serves only what its package implements. `openai-codex` has no row: the aimux codex package answers `NoSuchModel` for image models, so its declared image models report the `adapter` reason. `image.edit` is served only by a package that reads the bytes an edit sends: openai (and so the Dim account relay), google, fal, replicate and black-forest-labs do, while stability-ai, recraft and luma-ai serve `image.generate` alone; a package that reports no file input for a given model drops edit for that model too. xAI's image models report `adapter` because that package answers `NoSuchModel`, and its transcription and synthesis models are served. A created provider's id is a canonical UUID, which matches no row, so its declared media models are listed with the `adapter` reason. The other A.1 categories (music, audio, 3D asset, motion) have no rows and keep the `build` reason. Amazon Bedrock has no media declaration in the bundled catalog, so a Bedrock connection serves no media operation. `available` answers true once the adapter is installed; what it serves is answered per model by `operations`, so an unreachable endpoint is a call's failure, not a capability. Video is the one resumable operation: `submit` stores the provider's operation reference as the handle and `wait` polls it and streams the result to a file, so a restart resumes the same job instead of starting another; a job that has not settled one hour after its start fails `provider_error`, which keeps a never-settling job from holding a scheduler slot. The hour also bounds a status request in flight and the wait between polls, so a stalled request fails at the deadline rather than running out the connection's longer timeout. aimux exposes no cancel for a started video job, so `cancelRemote` answers `unsupported` and the provider job runs to completion and is billed on its side. An output file's media type is read from the returned bytes, so a provider that answers a format other than the requested one is recorded by what it returned. `available` reports runtime availability without a reload (for example, a provider endpoint unreachable). An operation whose available adapters do not serve the configured or explicit model is reported as "no adapter for the configured model", and its submits fail `unavailable`. `image.understand` is not an adapter operation: it is served by a selectable vision model and is selection-only. OCR is not an adapter: it is a host task whose target is one of the host targets this build offers, `local/apple-vision` or `local/pp-ocr`, and both are started from a description the target publishes (A.2.1); when `local/pp-ocr` is not offered, it is not an option and `modality.ocr` still resolves `local/apple-vision`. A task naming a node other than the control node fails `node_unavailable`. `wait` names its job by `task_id`; when `submit` returned a `remote_handle`, the adapter may use it instead. `wait` with a stored `remote_handle` must work in a new generation; an adapter that returns no handle keys its own in-flight work by `task_id`, and only within one generation, so it cannot be resumed. @@ -460,7 +460,7 @@ The default snapshot is the one shape both methods return. A model reference is - `revision` is the `modality` settings document revision; one CAS covers every operation key in that document, so a `configure` for one operation also invalidates a client holding a draft for another. Only `configure` consumes it. - `default` is the persisted choice or `null`. When the model is no longer selectable or no available adapter serves it (for `image.understand`, when it is not a selectable vision model), `available` is `false` and `reason` says why: `provider` for a model no longer selectable, `runtime` when its adapter is unavailable, `build` for a category this build has no adapter for, and `adapter` otherwise. - `effective` is the model a task or consumer would use now: it is resolved from the available options only, so it is `null` while no option can run, and a client never names a model the operation would refuse. It is the default when available. When `default` is `null`, it is automatic resolution: Provider's global default selection when it is an available option, else the first available option in Provider's order; `source` is `"automatic"`. An unavailable default yields `effective: null`, never a substituted model. -- `options` lists the models that serve the operation. The candidates come from Provider's non-conversational read (`selectableForModality`, §9.2), so a media model execution rejects — a non-chat model, or one whose text limits are undeclared — is a candidate when its catalog entry declares the operation. For every other operation the options are the models whose Provider catalog entry declares that `.` id, in Provider's order, and an operation nothing declares has none; each is `available` only when an available adapter's `operations` serves it for that operation, and is otherwise listed `available: false` with the reason no adapter runs it. An option's `available` therefore agrees with what a submission naming it would do. For `image.understand` a selectable vision model serves instead, from Provider's `vision` capability. For a realtime operation the options are the models whose entry declares that `.` id, in Provider's order: the session's adapter is handed the transport the entry declares, so the entry itself is the per-model answer, and `open` refuses `unavailable` a declared model that has no transport. The owner computes the candidates from Provider's declared capabilities so clients never derive them. The current default is included when it is no longer an option, marked with its reason. The owner computes them at read time from Provider's read-only contract (§9.2) and the available adapters. An option carries only `{providerId, modelId, available, reason?}`: #790 returns ids and capabilities, not display names, so the client joins names from its existing Provider list or catalog reads by `{providerId, modelId}` and shows the ids when a name is unavailable. +- `options` lists the models that serve the operation. The candidates come from Provider's non-conversational read (`selectableForModality`, §9.2), so a media model execution rejects — a non-chat model, or one whose text limits are undeclared — is a candidate when its catalog entry declares the operation. For every other operation the options are the models whose Provider catalog entry declares that `.` id, in Provider's order, and an operation nothing declares has none; each is `available` only when an available adapter's `operations` serves it for that operation, and is otherwise listed `available: false` with the reason no adapter runs it. For adapter-backed tasks, the operation is available when one of its options is available. If none is available and a declared option reports `runtime`, the operation reports that reason. For `image.understand` a selectable vision model serves instead, from Provider's `vision` capability. For a realtime operation the options are the models whose entry declares that `.` id, in Provider's order: the session's adapter is handed the transport the entry declares, so the entry itself is the per-model answer, and `open` refuses `unavailable` a declared model that has no transport. The owner computes the candidates from Provider's declared capabilities so clients never derive them. The current default is included when it is no longer an option, marked with its reason. The owner computes them at read time from Provider's read-only contract (§9.2) and the available adapters. An option carries only `{providerId, modelId, available, reason?}`: #790 returns ids and capabilities, not display names, so the client joins names from its existing Provider list or catalog reads by `{providerId, modelId}` and shows the ids when a name is unavailable. - `configure` validates the operation and that the model is in that operation's options (for `image.understand`, selectable vision support; for `ocr.recognize`, one of the host targets the snapshot offers), then writes or clears the operation key through Settings' owner write with CAS. It accepts every A.1 operation that has a default key and never answers `modality_unavailable`: configuring is a settings write, not a runtime claim. An unknown category or operation answers `modality_unknown_operation`; `operation` is required where the operation has its own key (image, speech, OCR) and may be absent only for a category-keyed category. `model: null` clears that key (for OCR, `modality.ocr`); clearing restores automatic resolution, and a missing `model` is `invalid_params`. The write happens before the reply is sent, so a success means the default is persisted, and the reply is the same snapshot a following `modality.capabilities` call returns unless Provider changed in between. - Configurable and available are different properties: the first belongs to settings, the second to the runtime. A persisted default can name a model of an operation this build cannot run; the snapshot stays honest by keeping that operation's `available: false` and its `build` or `adapter` reason, and `effective` resolves over the available options only (the default when available, otherwise automatic), so it is `null` whenever no option can run and clients do not implement resolution themselves. diff --git a/docs/zh/design/appserver/provider-management.md b/docs/zh/design/appserver/provider-management.md index e716ce33dc..aa2fb47fe5 100644 --- a/docs/zh/design/appserver/provider-management.md +++ b/docs/zh/design/appserver/provider-management.md @@ -620,7 +620,7 @@ ModelCapabilities, reasoning?, serviceTier?}`——不是新的模型类型: `.` id,按条目中的顺序;未声明任何操作的模型被省略。条目在 `metadata.raw.modalityCapabilities` 中声明操作,显式列表(包括空列表)就是全部答案。没有列表的 条目会被识别为图像模型,因为中转与账号目录列出这类模型时不带媒体元数据:其 id 是已知图像模型之一 -(`arcship-image`、`gpt-image-2` 系列、`grok-imagine-image` 系列)或包含 `seedream`;或其 `type` +(`arcship-image`、`gpt-image-2` 和 `grok-imagine-image` 系列中的已知 ID)或包含 `seedream`;或其 `type` 为 `image`/`image-generation` 且输出包含图像或未说明;或 `imageGeneration` 为 true;或其唯一输出是 `image`。这样的模型声明 `image.generate`,当它也读取图像或是已知模型时还声明 `image.edit`;`type` 为 `image-edit` 时只声明 `image.edit`,`imageGeneration: false` 不识别任何操作。下面的连接规则读取 diff --git a/docs/zh/design/plugins/Modality.md b/docs/zh/design/plugins/Modality.md index 8a82417f78..e3883a3353 100644 --- a/docs/zh/design/plugins/Modality.md +++ b/docs/zh/design/plugins/Modality.md @@ -349,7 +349,7 @@ Settings 业务来源与 `pluginFiles` 补充是对其他插件的改动,列 `Job` 为 `{ task_id, category, operation, model: {providerId, modelId}, params, files: [{ name, media_type, path }], work_dir }`。内联输入的 `path` 是 Modality 存放在 `modality/tasks//input/` 的文件的绝对路径;通过 `node_path` 给出的输入记录 Modality 得到的规范路径(最后一个组件不得是链接;更早的链接会被解析),Modality 只读取一次以取得 `bytes` 与 `sha256`,从不复制,执行方就地读取。`work_dir` 是任务的 `modality/tasks//work` 目录,调用前创建;每个结果文件解析为其中的普通文件。调用携带的 `connection` 是 `ModalityConnection`,即 Provider 非对话连接解析返回的 Rust 形态(`kind`、`provider_id`、`model`、端点与凭据材料,以及 `realtime.*` 用途下目录条目的 `realtime: { protocol, path }` 声明)。它不是数据:仅为一次调用按值传入,从不存储、记录日志、返回或序列化,这也是适配器服务目前只在进程内的原因(A.2,[#1613](https://github.com/arcships/dim/issues/1613))。该声明是 Provider 对条目 `metadata.raw.realtime` 的读取;条目未声明的模型,以及从不携带它的配置模型 profile,会在适配器被调用之前以 `unavailable` 拒绝,消息为 “The model declares no realtime transport”。中继从连接的 base URL、声明的 `path` 与模型 id 组合出套接字地址,因此路径由目录条目声明,从不推导。 -产品内置适配器是 `dim-modality-aimux` crate:aimux 的词汇留在适配器内部。它服务 `image.generate`、`image.edit`、`video.generate`、`speech.synthesize` 与 `speech.transcribe`,按目录提供方 id 绑定;并对任何条目声明了 openai-realtime 传输的模型服务 `realtime.voice`,因为实时会话由连接构建,而不是由厂商行决定。中继以连接的 base URL 加声明的路径和作为查询的模型 id 连接,`http` 与 `https` 变为 `ws` 与 `wss`;它发送连接的头部与 bearer、经连接的代理连接、把文本帧写成 JSON 并把音频帧写成解码后的字节,并在提供方关闭、套接字失败或十秒内写不出一帧时结束会话。它不承载控制帧——控制帧属于 `direct` 传输。凡是其媒体模型由某个 aimux 厂商包执行的内建目录提供方都有一行(openai、google、xai、grok-build、elevenlabs、fal、deepgram、assemblyai、cartesia、gladia、groq、replicate、stability-ai、recraft、black-forest-labs、luma-ai、runway、kling、hume-ai、mistral-ai、rev-ai),以及 Dim 账号中转(`dimcode-api-oauth`)——它的 `/v1` 基址提供 OpenAI Image API,由 openai 包执行;每行只服务其包实际实现的操作。`openai-codex` 没有行:aimux 的 codex 包对图像模型回答 `NoSuchModel`,因此它声明的图像模型报 `adapter` 原因。`image.edit` 只由读取编辑输入字节的包服务:openai(因此包括 Dim 账号中转)、google、fal、replicate、black-forest-labs 会读取;stability-ai、recraft、luma-ai 只服务 `image.generate`;包对某个模型报告不接受文件输入时,该模型也不提供 edit。xAI 的图像模型因该包回答 `NoSuchModel` 而报 `adapter`,其转录与合成模型则被服务。自建提供方的 id 是规范 UUID,不匹配任何行,因此其媒体操作报 `adapter` 原因,`configure` 也以该原因拒绝其模型。其他 A.1 类别(音乐、音频、3D 资产、动作)没有对应行,保持 `build` 原因。内建目录没有为 Amazon Bedrock 声明任何媒体模型,因此 Bedrock 连接不服务媒体操作。安装后 `available` 即为 true;服务范围按模型由 `operations` 回答,端点不可达是某次调用的失败,而不是能力。视频是唯一可恢复的操作:`submit` 把提供方的操作引用存为句柄,`wait` 轮询它并把结果流式写入文件,因此重启恢复同一作业而不会重新发起;开始后一小时仍未结束的作业以 `provider_error` 失败,避免永不结束的作业一直占用调度槽位。该上限同样约束在途的状态请求与两次轮询之间的等待,因此挂起的请求会在截止时失败,而不是跑满连接更长的超时。aimux 对已启动的视频作业不提供取消,因此 `cancelRemote` 回答 `unsupported`,提供方作业会在其一侧跑完并计费。输出文件的媒体类型从返回字节读取,提供方返回与请求不同的格式时,按实际返回记录。 +产品内置适配器是 `dim-modality-aimux` crate:aimux 的词汇留在适配器内部。它服务 `image.generate`、`image.edit`、`video.generate`、`speech.synthesize` 与 `speech.transcribe`,按目录提供方 id 绑定;并对任何条目声明了 openai-realtime 传输的模型服务 `realtime.voice`,因为实时会话由连接构建,而不是由厂商行决定。中继以连接的 base URL 加声明的路径和作为查询的模型 id 连接,`http` 与 `https` 变为 `ws` 与 `wss`;它发送连接的头部与 bearer、经连接的代理连接、把文本帧写成 JSON 并把音频帧写成解码后的字节,并在提供方关闭、套接字失败或十秒内写不出一帧时结束会话。它不承载控制帧——控制帧属于 `direct` 传输。凡是其媒体模型由某个 aimux 厂商包执行的内建目录提供方都有一行(openai、google、xai、grok-build、elevenlabs、fal、deepgram、assemblyai、cartesia、gladia、groq、replicate、stability-ai、recraft、black-forest-labs、luma-ai、runway、kling、hume-ai、mistral-ai、rev-ai),以及 Dim 账号中转(`dimcode-api-oauth`)——它的 `/v1` 基址提供 OpenAI Image API,由 openai 包执行。收到失败响应时,付费作业可能已经启动,因此适配器不会自动重试该中转的图像请求。每行只服务其包实际实现的操作。`openai-codex` 没有行:aimux 的 codex 包对图像模型回答 `NoSuchModel`,因此它声明的图像模型报 `adapter` 原因。`image.edit` 只由读取编辑输入字节的包服务:openai(因此包括 Dim 账号中转)、google、fal、replicate、black-forest-labs 会读取;stability-ai、recraft、luma-ai 只服务 `image.generate`;包对某个模型报告不接受文件输入时,该模型也不提供 edit。xAI 的图像模型因该包回答 `NoSuchModel` 而报 `adapter`,其转录与合成模型则被服务。自建提供方的 id 是规范 UUID,不匹配任何行,因此其声明的媒体模型会列为不可用,并附上 `adapter` 原因。其他 A.1 类别(音乐、音频、3D 资产、动作)没有对应行,保持 `build` 原因。内建目录没有为 Amazon Bedrock 声明任何媒体模型,因此 Bedrock 连接不服务媒体操作。安装后 `available` 即为 true;服务范围按模型由 `operations` 回答,端点不可达是某次调用的失败,而不是能力。视频是唯一可恢复的操作:`submit` 把提供方的操作引用存为句柄,`wait` 轮询它并把结果流式写入文件,因此重启恢复同一作业而不会重新发起;开始后一小时仍未结束的作业以 `provider_error` 失败,避免永不结束的作业一直占用调度槽位。该上限同样约束在途的状态请求与两次轮询之间的等待,因此挂起的请求会在截止时失败,而不是跑满连接更长的超时。aimux 对已启动的视频作业不提供取消,因此 `cancelRemote` 回答 `unsupported`,提供方作业会在其一侧跑完并计费。输出文件的媒体类型从返回字节读取,提供方返回与请求不同的格式时,按实际返回记录。 `available` 在不重载的情况下报告运行时可用性(例如提供方端点不可达)。若某个操作的可用适配器都不服务已配置或显式指定的模型,则报告为“no adapter for the configured model”,其提交以 `unavailable` 失败。`image.understand` 不是适配器操作:它由一个可选的视觉模型服务,且只做选择。OCR 不是适配器:它是宿主任务,其目标是本构建提供的宿主目标之一 `local/apple-vision` 或 `local/pp-ocr`,两者都从目标发布的描述启动(A.2.1);当 `local/pp-ocr` 未提供时,它不是选项,`modality.ocr` 仍解析 `local/apple-vision`。指明控制节点以外节点的任务以 `node_unavailable` 失败。`wait` 以 `task_id` 指名它等待的作业;当 `submit` 返回了 `remote_handle` 时,适配器可以改用它。带已存储 `remote_handle` 的 `wait` 必须能在新一代中工作;不返回句柄的适配器以 `task_id` 记录自己进行中的工作,且仅限同一代内,因此无法恢复。 @@ -454,7 +454,7 @@ wire 参数形状错误为 `invalid_params`,未知类别或操作为 `modality - `revision` 是 `modality` 设置文档的 revision;一次 CAS 覆盖该文档中的全部操作 key,因此对某个操作的 `configure` 也会让持有其他操作草稿的客户端失效。只有 `configure` 使用它。 - `default` 是已持久化的选择或 `null`。模型不再可选、或没有可用适配器服务它时(对 `image.understand`,是它不是可选的视觉模型时),`available` 为 `false`,`reason` 说明原因:不再可选时为 `provider`,其适配器不可用时为 `runtime`,本构建没有该类别的适配器时为 `build`,其余为 `adapter`。 - `effective` 是任务或使用方现在会使用的模型:它只从可用的选项解析,因此没有选项能运行时为 `null`,客户端从不会拿到一个操作会拒绝的模型。默认值可用时就是默认值。`default` 为 `null` 时它是自动解析:Provider 的全局默认选择是可用选项时用它,否则用 Provider 顺序中第一个可用选项;`source` 为 `"automatic"`。不可用的默认值给出 `effective: null`,从不替换成别的模型。 -- `options` 列出服务该操作的模型。候选来自 Provider 的非会话读取(`selectableForModality`,§9.2),因此被执行拒绝的媒体模型——非 chat 模型,或未声明文本上限的模型——只要其目录条目声明了该操作就是候选。对其他操作,选项是其 Provider 目录条目声明了该 `.` id 的模型,按 Provider 的顺序,没有任何声明的操作选项为空;只有可用适配器的 `operations` 为该操作服务它时才 `available`,否则列为 `available: false` 并带上没有适配器运行它的原因。因此选项的 `available` 与以它提交时的结果一致。对 `image.understand`,改由可选的视觉模型服务,取自 Provider 的 `vision` 能力。对实时操作,选项是其条目声明了该 `.` id 的模型,按 Provider 的顺序:会话适配器收到的正是条目声明的传输,因此条目本身就是逐模型答案;声明了操作但没有传输的模型由 `open` 以 `unavailable` 拒绝。所有者从 Provider 的已声明能力计算候选,客户端不自行推导。当前默认值不再是选项时也会列出,并标注原因。所有者读取时从 Provider 的只读契约(§9.2)与可用适配器计算它们。选项只带 `{providerId, modelId, available, reason?}`:读取返回 id 与能力,不返回展示名,因此客户端按 `{providerId, modelId}` 从它已有的 Provider 列表或目录读取中并入名字,取不到名字时显示 id。 +- `options` 列出服务该操作的模型。候选来自 Provider 的非会话读取(`selectableForModality`,§9.2),因此被执行拒绝的媒体模型——非 chat 模型,或未声明文本上限的模型——只要其目录条目声明了该操作就是候选。对其他操作,选项是其 Provider 目录条目声明了该 `.` id 的模型,按 Provider 的顺序,没有任何声明的操作选项为空;只有可用适配器的 `operations` 为该操作服务它时才 `available`,否则列为 `available: false` 并带上没有适配器运行它的原因。对于适配器执行的任务,只要有一个选项可用,操作就可用。若所有选项均不可用且有声明的选项报告 `runtime`,操作也报告该原因。对 `image.understand`,改由可选的视觉模型服务,取自 Provider 的 `vision` 能力。对实时操作,选项是其条目声明了该 `.` id 的模型,按 Provider 的顺序:会话适配器收到的正是条目声明的传输,因此条目本身就是逐模型答案;声明了操作但没有传输的模型由 `open` 以 `unavailable` 拒绝。所有者从 Provider 的已声明能力计算候选,客户端不自行推导。当前默认值不再是选项时也会列出,并标注原因。所有者读取时从 Provider 的只读契约(§9.2)与可用适配器计算它们。选项只带 `{providerId, modelId, available, reason?}`:读取返回 id 与能力,不返回展示名,因此客户端按 `{providerId, modelId}` 从它已有的 Provider 列表或目录读取中并入名字,取不到名字时显示 id。 - `configure` 先校验操作以及模型在该操作的可选选项中(对 `image.understand`,可选视觉支持;对 `ocr.recognize`,快照当前提供的宿主目标之一),再经 Settings 的所有者写入以 CAS 写入或清除该操作 key。它接受任何有默认 key 的 A.1 操作,且从不答复 `modality_unavailable`:配置是设置写入,不是运行时断言。未知类别或操作答复 `modality_unknown_operation`;操作有自己的 key 时(image、speech、OCR)`operation` 必填,只有按类别划分 key 的类别可以省略。`model: null` 清除该 key(对 OCR 即 `modality.ocr`);清除即恢复自动解析;缺少 `model` 为 `invalid_params`。写入在回复发出之前完成,因此成功即表示默认值已持久化,且该回复与紧随其后的 `modality.capabilities` 读到的一致(除非 Provider 在此期间变化)。 - 可配置性与可用性是两个不同的属性:前者属于设置,后者属于运行时。已持久化的默认值可以指向本构建不能运行的操作的模型;快照通过保持该操作的 `available: false` 及其 `build` 或 `adapter` 原因保持诚实,而 `effective` 只在可用选项上解析(默认值可用时用默认值,否则自动解析),没有选项能运行时为 `null`,客户端因此无需自行实现解析。 From f6cf5ca6636d31888244179d5f076569b689c1cb Mon Sep 17 00:00:00 2001 From: zerob13 Date: Sun, 22 Nov 2026 10:20:48 +0800 Subject: [PATCH 3/5] fix(modality): classify offline adapters by operation Share the adapter operation check between option listing and task submission. Report runtime only when the adapter declares the specific operation, including when the same offline adapter serves another operation for the configured model. --- crates/dim-modality-aimux/src/job.rs | 1 - crates/dim-modality/src/engine.rs | 29 +++---- crates/dim-modality/src/lib.rs | 81 ++++++++------------ crates/dim-modality/src/realtime.rs | 2 +- crates/dim-modality/tests/modality_flow.rs | 6 ++ docs/design/appserver/provider-management.md | 5 +- docs/design/plugins/Modality.md | 2 +- docs/zh/design/plugins/Modality.md | 2 +- 8 files changed, 51 insertions(+), 77 deletions(-) diff --git a/crates/dim-modality-aimux/src/job.rs b/crates/dim-modality-aimux/src/job.rs index b5a9757174..356872a17a 100644 --- a/crates/dim-modality-aimux/src/job.rs +++ b/crates/dim-modality-aimux/src/job.rs @@ -52,7 +52,6 @@ pub fn image_options(job: &Job, vendor: &Vendor) -> Result format!("{message}\n{}", reason_line(reason)), - None => message, - })); - }; + let spec = evaluation + .operation_spec(&model, category.name, row.operation) + .map_err(|reason| { + unavailable(format!( + "No available adapter serves {} for this model\n{}", + row.id(category.name), + reason_line(&reason) + )) + })?; check_spec_params(&spec, ¶ms.params, &row.id(category.name))?; } // Boundary: names, media types and sizes (decision 1, decision 2). diff --git a/crates/dim-modality/src/lib.rs b/crates/dim-modality/src/lib.rs index 6b4961d9f1..2372a52a66 100644 --- a/crates/dim-modality/src/lib.rs +++ b/crates/dim-modality/src/lib.rs @@ -657,17 +657,6 @@ impl Evaluation { }) }) } - fn serves(&self, model: &ModelId, category: &str, operation: &str) -> bool { - let Some(adapter) = self.adapter(&model.provider_id) else { - return false; - }; - adapter.0.available() - && adapter - .0 - .operations(model) - .iter() - .any(|served| served.category == category && served.operation == operation) - } fn selectable(&self, provider_id: &str, model_id: &str) -> Option<&ModelCapabilitySnapshot> { self.selectable.iter().find(|model| { model.target.provider_id == provider_id && model.target.model_id == model_id @@ -686,24 +675,32 @@ impl Evaluation { .declared_for(&model.provider_id, &model.model_id) .is_some() } - /// The adapter's declaration of one operation for `model`: its parameter - /// schema, read per submission (A.2, decision 3). `None` when no - /// available adapter serves the operation for that model. + /// The parameter schema of the available adapter for this model and + /// operation, or the reason the operation cannot run (Modality A.2). pub(crate) fn operation_spec( &self, model: &ModelId, category: &str, operation: &str, - ) -> Option { - let adapter = self.adapter(&model.provider_id)?; - if !adapter.0.available() { - return None; + ) -> Result { + if let Some(adapter) = self.adapter(&model.provider_id) + && let Some(spec) = adapter + .0 + .operations(model) + .into_iter() + .find(|spec| spec.category == category && spec.operation == operation) + { + return if adapter.0.available() { + Ok(spec) + } else { + Err(reason("runtime", "The adapter is unavailable")) + }; + } + if category != "image" && !self.adapter_serves(category) { + Err(reason("build", "Not in this build")) + } else { + Err(reason("adapter", "No available adapter serves the model")) } - adapter - .0 - .operations(model) - .into_iter() - .find(|spec| spec.category == category && spec.operation == operation) } fn option(model: &ModelId) -> OptionSnapshot { OptionSnapshot { @@ -762,33 +759,21 @@ impl Evaluation { .iter() .filter(|model| declares(&model.operations, category, row.operation)) .map(|model| { - if is_realtime(category) || self.serves(&model.target, category, row.operation) - { - Self::option(&model.target) - } else { - OptionSnapshot { - available: false, - reason: Some(self.unserved_reason(&model.target, category)), - ..Self::option(&model.target) - } + if is_realtime(category) { + return Self::option(&model.target); + } + let reason = self + .operation_spec(&model.target, category, row.operation) + .err(); + OptionSnapshot { + available: reason.is_none(), + reason, + ..Self::option(&model.target) } }) .collect() } } - /// Why no adapter runs a declared model's operation, in the operation's - /// own vocabulary. - fn unserved_reason(&self, model: &ModelId, category: &str) -> Reason { - match self.adapter(&model.provider_id) { - Some(adapter) if !adapter.0.available() => { - reason("runtime", "The adapter is unavailable") - } - _ if category != "image" && !self.adapter_serves(category) => { - reason("build", "Not in this build") - } - _ => reason("adapter", "No available adapter serves the model"), - } - } /// Whether `configure` may persist `model` for one operation: an option /// the operation offers, served or not, so a default can be saved before /// a runtime lands. A host target must also run here (A.2.1). @@ -840,12 +825,6 @@ impl Evaluation { if !self.known(model) { return reason("provider", "Model is no longer selectable"); } - if self - .declared_for(&model.provider_id, &model.model_id) - .is_some_and(|declared| declares(&declared.operations, category, operation)) - { - return self.unserved_reason(model, category); - } reason( "configuration", format!("The model does not declare {name}"), diff --git a/crates/dim-modality/src/realtime.rs b/crates/dim-modality/src/realtime.rs index cd0371b130..51e70ec7d3 100644 --- a/crates/dim-modality/src/realtime.rs +++ b/crates/dim-modality/src/realtime.rs @@ -224,7 +224,7 @@ impl Realtime { ) .await?; let model = resolve_task_model(&evaluation, category.name, row, request.model.as_ref())?; - let Some(spec) = evaluation.operation_spec(&model, category.name, row.operation) else { + let Ok(spec) = evaluation.operation_spec(&model, category.name, row.operation) else { return Err(unavailable(format!( "No available adapter serves {} for this model", row.id(category.name) diff --git a/crates/dim-modality/tests/modality_flow.rs b/crates/dim-modality/tests/modality_flow.rs index 34408f91ca..abf66423df 100644 --- a/crates/dim-modality/tests/modality_flow.rs +++ b/crates/dim-modality/tests/modality_flow.rs @@ -1501,6 +1501,12 @@ async fn capabilities_and_configure_resolve_defaults_through_the_fixture_adapter "the default agrees with the operation: {generate}" ); assert!(generate["effective"].is_null()); + let edit = operation(&offline, "edit"); + assert_eq!(edit["reasons"][0]["dimension"], "adapter"); + assert_eq!( + edit["reasons"][0]["dimension"], + edit["default"]["reason"]["dimension"] + ); let refused = client .rpc( "modality.configure", diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index f37b9e71f7..e6564cf3e1 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -1031,8 +1031,9 @@ in `metadata.raw.modalityCapabilities`, and an explicit list, an empty one included, is the whole answer. An entry with no list is recognized as an image model, because relay and account catalogs list such models without media metadata: its id is `arcship-image`, a known ID in the `gpt-image-2` or -`grok-imagine-image` family, or names `seedream`, or its `type` is `image`/`image-generation` with image or no stated output, or -`imageGeneration` is true, or its only output is `image`. Such a model declares +`grok-imagine-image` family, or names `seedream`, or its `type` is +`image`/`image-generation` with image or no stated output, or `imageGeneration` +is true, or its only output is `image`. Such a model declares `image.generate`, and `image.edit` too when it also reads images or is a known model; a `type` of `image-edit` declares `image.edit` alone, and `imageGeneration: false` recognizes nothing. The connection rule below reads diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index b95a42294c..e7843c72cf 100644 --- a/docs/design/plugins/Modality.md +++ b/docs/design/plugins/Modality.md @@ -458,7 +458,7 @@ The default snapshot is the one shape both methods return. A model reference is ``` - `revision` is the `modality` settings document revision; one CAS covers every operation key in that document, so a `configure` for one operation also invalidates a client holding a draft for another. Only `configure` consumes it. -- `default` is the persisted choice or `null`. When the model is no longer selectable or no available adapter serves it (for `image.understand`, when it is not a selectable vision model), `available` is `false` and `reason` says why: `provider` for a model no longer selectable, `runtime` when its adapter is unavailable, `build` for a category this build has no adapter for, and `adapter` otherwise. +- `default` is the persisted choice or `null`. When the model is no longer selectable or no available adapter serves it (for `image.understand`, when it is not a selectable vision model), `available` is `false` and `reason` says why: `provider` for a model no longer selectable, `runtime` when an adapter serves the operation for that model but is unavailable, `build` for a category this build has no adapter for, and `adapter` otherwise. - `effective` is the model a task or consumer would use now: it is resolved from the available options only, so it is `null` while no option can run, and a client never names a model the operation would refuse. It is the default when available. When `default` is `null`, it is automatic resolution: Provider's global default selection when it is an available option, else the first available option in Provider's order; `source` is `"automatic"`. An unavailable default yields `effective: null`, never a substituted model. - `options` lists the models that serve the operation. The candidates come from Provider's non-conversational read (`selectableForModality`, §9.2), so a media model execution rejects — a non-chat model, or one whose text limits are undeclared — is a candidate when its catalog entry declares the operation. For every other operation the options are the models whose Provider catalog entry declares that `.` id, in Provider's order, and an operation nothing declares has none; each is `available` only when an available adapter's `operations` serves it for that operation, and is otherwise listed `available: false` with the reason no adapter runs it. For adapter-backed tasks, the operation is available when one of its options is available. If none is available and a declared option reports `runtime`, the operation reports that reason. For `image.understand` a selectable vision model serves instead, from Provider's `vision` capability. For a realtime operation the options are the models whose entry declares that `.` id, in Provider's order: the session's adapter is handed the transport the entry declares, so the entry itself is the per-model answer, and `open` refuses `unavailable` a declared model that has no transport. The owner computes the candidates from Provider's declared capabilities so clients never derive them. The current default is included when it is no longer an option, marked with its reason. The owner computes them at read time from Provider's read-only contract (§9.2) and the available adapters. An option carries only `{providerId, modelId, available, reason?}`: #790 returns ids and capabilities, not display names, so the client joins names from its existing Provider list or catalog reads by `{providerId, modelId}` and shows the ids when a name is unavailable. - `configure` validates the operation and that the model is in that operation's options (for `image.understand`, selectable vision support; for `ocr.recognize`, one of the host targets the snapshot offers), then writes or clears the operation key through Settings' owner write with CAS. It accepts every A.1 operation that has a default key and never answers `modality_unavailable`: configuring is a settings write, not a runtime claim. An unknown category or operation answers `modality_unknown_operation`; `operation` is required where the operation has its own key (image, speech, OCR) and may be absent only for a category-keyed category. `model: null` clears that key (for OCR, `modality.ocr`); clearing restores automatic resolution, and a missing `model` is `invalid_params`. The write happens before the reply is sent, so a success means the default is persisted, and the reply is the same snapshot a following `modality.capabilities` call returns unless Provider changed in between. diff --git a/docs/zh/design/plugins/Modality.md b/docs/zh/design/plugins/Modality.md index e3883a3353..f151e2ae46 100644 --- a/docs/zh/design/plugins/Modality.md +++ b/docs/zh/design/plugins/Modality.md @@ -452,7 +452,7 @@ wire 参数形状错误为 `invalid_params`,未知类别或操作为 `modality ``` - `revision` 是 `modality` 设置文档的 revision;一次 CAS 覆盖该文档中的全部操作 key,因此对某个操作的 `configure` 也会让持有其他操作草稿的客户端失效。只有 `configure` 使用它。 -- `default` 是已持久化的选择或 `null`。模型不再可选、或没有可用适配器服务它时(对 `image.understand`,是它不是可选的视觉模型时),`available` 为 `false`,`reason` 说明原因:不再可选时为 `provider`,其适配器不可用时为 `runtime`,本构建没有该类别的适配器时为 `build`,其余为 `adapter`。 +- `default` 是已持久化的选择或 `null`。模型不再可选、或没有可用适配器服务它时(对 `image.understand`,是它不是可选的视觉模型时),`available` 为 `false`,`reason` 说明原因:不再可选时为 `provider`,有适配器为该模型服务此操作但当前不可用时为 `runtime`,本构建没有该类别的适配器时为 `build`,其余为 `adapter`。 - `effective` 是任务或使用方现在会使用的模型:它只从可用的选项解析,因此没有选项能运行时为 `null`,客户端从不会拿到一个操作会拒绝的模型。默认值可用时就是默认值。`default` 为 `null` 时它是自动解析:Provider 的全局默认选择是可用选项时用它,否则用 Provider 顺序中第一个可用选项;`source` 为 `"automatic"`。不可用的默认值给出 `effective: null`,从不替换成别的模型。 - `options` 列出服务该操作的模型。候选来自 Provider 的非会话读取(`selectableForModality`,§9.2),因此被执行拒绝的媒体模型——非 chat 模型,或未声明文本上限的模型——只要其目录条目声明了该操作就是候选。对其他操作,选项是其 Provider 目录条目声明了该 `.` id 的模型,按 Provider 的顺序,没有任何声明的操作选项为空;只有可用适配器的 `operations` 为该操作服务它时才 `available`,否则列为 `available: false` 并带上没有适配器运行它的原因。对于适配器执行的任务,只要有一个选项可用,操作就可用。若所有选项均不可用且有声明的选项报告 `runtime`,操作也报告该原因。对 `image.understand`,改由可选的视觉模型服务,取自 Provider 的 `vision` 能力。对实时操作,选项是其条目声明了该 `.` id 的模型,按 Provider 的顺序:会话适配器收到的正是条目声明的传输,因此条目本身就是逐模型答案;声明了操作但没有传输的模型由 `open` 以 `unavailable` 拒绝。所有者从 Provider 的已声明能力计算候选,客户端不自行推导。当前默认值不再是选项时也会列出,并标注原因。所有者读取时从 Provider 的只读契约(§9.2)与可用适配器计算它们。选项只带 `{providerId, modelId, available, reason?}`:读取返回 id 与能力,不返回展示名,因此客户端按 `{providerId, modelId}` 从它已有的 Provider 列表或目录读取中并入名字,取不到名字时显示 id。 - `configure` 先校验操作以及模型在该操作的可选选项中(对 `image.understand`,可选视觉支持;对 `ocr.recognize`,快照当前提供的宿主目标之一),再经 Settings 的所有者写入以 CAS 写入或清除该操作 key。它接受任何有默认 key 的 A.1 操作,且从不答复 `modality_unavailable`:配置是设置写入,不是运行时断言。未知类别或操作答复 `modality_unknown_operation`;操作有自己的 key 时(image、speech、OCR)`operation` 必填,只有按类别划分 key 的类别可以省略。`model: null` 清除该 key(对 OCR 即 `modality.ocr`);清除即恢复自动解析;缺少 `model` 为 `invalid_params`。写入在回复发出之前完成,因此成功即表示默认值已持久化,且该回复与紧随其后的 `modality.capabilities` 读到的一致(除非 Provider 在此期间变化)。 From ac2c7f62208d0c7131fb08db79efeb38f163519c Mon Sep 17 00:00:00 2001 From: zerob13 Date: Sun, 22 Nov 2026 10:26:11 +0800 Subject: [PATCH 4/5] test(modality): simplify the scripted relay responder Store the responder closure directly in the scripted transport. The fetch function already owns the transport through an Arc. --- crates/dim-modality-aimux/tests/adapter.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/dim-modality-aimux/tests/adapter.rs b/crates/dim-modality-aimux/tests/adapter.rs index 032ab7f18c..a404d03d66 100644 --- a/crates/dim-modality-aimux/tests/adapter.rs +++ b/crates/dim-modality-aimux/tests/adapter.rs @@ -72,14 +72,16 @@ fn unauthorized() -> Reply { } } -#[derive(Clone)] -struct Scripted { +struct Scripted { requests: Arc>>, - respond: Arc Option + Send + Sync>, + respond: F, } #[async_trait] -impl Fetch for Scripted { +impl Fetch for Scripted +where + F: Fn(&Recorded) -> Option + Send + Sync + 'static, +{ async fn fetch(&self, request: FetchRequest) -> Result { let recorded = Recorded { method: request.method.clone(), @@ -116,7 +118,7 @@ fn scripted( let requests = Arc::new(Mutex::new(Vec::new())); let fetch: FetchFunction = Arc::new(Scripted { requests: requests.clone(), - respond: Arc::new(move |request| Some(respond(request))), + respond: move |request: &Recorded| Some(respond(request)), }); (Arc::new(MediaAdapter::scripted(fetch)), requests) } @@ -629,7 +631,7 @@ async fn the_dim_account_relay_does_not_retry_a_timed_out_post() { let requests = Arc::new(Mutex::new(Vec::new())); let adapter = Arc::new(MediaAdapter::scripted(Arc::new(Scripted { requests: requests.clone(), - respond: Arc::new(|_| None), + respond: |_: &Recorded| None, }))); let dir = work_dir("relay-timeout"); let error = run( From 1f38d8622725ef660d44a4877bf3543211e29cf2 Mon Sep 17 00:00:00 2001 From: zerob13 Date: Sun, 22 Nov 2026 10:54:07 +0800 Subject: [PATCH 5/5] docs(modality): align operation defaults with declared options --- docs/design/plugins/Modality.md | 16 ++++++++-------- docs/zh/design/plugins/Modality.md | 16 ++++++++-------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index e7843c72cf..c76b099aa5 100644 --- a/docs/design/plugins/Modality.md +++ b/docs/design/plugins/Modality.md @@ -168,9 +168,9 @@ The image operations are the first implementation slice, and the product build n Realtime options follow Provider's transport declarations rather than narrowing through the resolved adapter's `operations`. A specialized provider copy that does not serve realtime can therefore leave a declared model in the option list while `realtime.open` rejects it as `unavailable`; resolution does not retry the family copy when a present provider copy lacks an operation. -`dimcode modality set-default image.generate /` and the Web page call `modality.configure`, which validates that the model is one of the operation's options: for an adapter operation, that an available adapter serves it; for `image.understand`, that it is a selectable vision model; for an operation no adapter serves, that the model is in Provider's modality read and its catalog entry declares `.`, which may be a model execution cannot select (a non-chat model or one whose text limits are undeclared). It then writes the operation key in Modality's own `modality` settings document through its owner write (Settings CAS). `model: null` clears that key. The reply is the same snapshot `modality.capabilities` returns, including the new `revision`, so a client applies it without a second read. +`dimcode modality set-default image.generate /` and the Web page call `modality.configure`, which validates the model against the operation's options (A.3). A Provider model offered for the operation can be saved with `available: false`. An OCR host target must be able to run on this host (A.2.1). It then writes the operation key in Modality's own `modality` settings document through its owner write (Settings CAS). `model: null` clears that key. The reply is the same snapshot `modality.capabilities` returns, including the new `revision`, so a client applies it without a second read. -A task resolves its model in this order: the explicit `model` in the request; the persisted default for the operation key; automatic resolution — Provider's global default selection when that model is selectable and serving the operation, otherwise the first selectable model that serves it in the order Provider's selectable-model read returns. An explicit model or a persisted default that is no longer selectable fails the task (`model_unavailable` or `default_unavailable`); an operation with no available adapter for the resolved model fails `unavailable`. Modality never substitutes another model. Only an absent default reaches automatic resolution, so clearing a default restores it. The resolved model is written into the task record and does not change when the default changes later. +A task uses the explicit `model` in the request, then the persisted default for the operation key if no model is given. With neither, automatic resolution uses Provider's global default selection when it is an available option for the operation. Otherwise it uses the first available option. For adapter-backed operations, the options follow the order of Provider's modality declarations (§9.2). An explicit model or a persisted default that is no longer selectable fails the task (`model_unavailable` or `default_unavailable`); an operation with no available adapter for the resolved model fails `unavailable`. Modality never substitutes another model. Only an absent default reaches automatic resolution, so clearing a default restores it. The resolved model is written into the task record and does not change when the default changes later. `image.understand` uses the same resolution but has no task: Modality exposes the effective target in `modality.capabilities` and through `modalityTargets`. Its Session consumer is [ImageUnderstanding](ImageUnderstanding.md), which resolves the target per tool call (§9.4), independently of the conversational model. @@ -458,11 +458,11 @@ The default snapshot is the one shape both methods return. A model reference is ``` - `revision` is the `modality` settings document revision; one CAS covers every operation key in that document, so a `configure` for one operation also invalidates a client holding a draft for another. Only `configure` consumes it. -- `default` is the persisted choice or `null`. When the model is no longer selectable or no available adapter serves it (for `image.understand`, when it is not a selectable vision model), `available` is `false` and `reason` says why: `provider` for a model no longer selectable, `runtime` when an adapter serves the operation for that model but is unavailable, `build` for a category this build has no adapter for, and `adapter` otherwise. -- `effective` is the model a task or consumer would use now: it is resolved from the available options only, so it is `null` while no option can run, and a client never names a model the operation would refuse. It is the default when available. When `default` is `null`, it is automatic resolution: Provider's global default selection when it is an available option, else the first available option in Provider's order; `source` is `"automatic"`. An unavailable default yields `effective: null`, never a substituted model. +- `default` is the persisted choice or `null`. An unavailable default has `available: false` and a `reason` such as `provider` for a model no longer selectable, `configuration` for a known model outside the operation's options, `runtime` when an adapter serving the model for this operation is unavailable, `build` for a category this build has no adapter for, or `adapter` when no adapter serves the model for the operation. For example, a category-wide default that only declares `video.generate` has a `configuration` reason on the `video.edit` row. +- `effective` is the model a task or consumer would use now: it is resolved from the available options only, so it is `null` while no option can run, and a client never names a model the operation would refuse. It is the default when available. When `default` is `null`, it follows automatic resolution in §3.4 and `source` is `"automatic"` if a model is selected. An unavailable default yields `effective: null`, never a substituted model. - `options` lists the models that serve the operation. The candidates come from Provider's non-conversational read (`selectableForModality`, §9.2), so a media model execution rejects — a non-chat model, or one whose text limits are undeclared — is a candidate when its catalog entry declares the operation. For every other operation the options are the models whose Provider catalog entry declares that `.` id, in Provider's order, and an operation nothing declares has none; each is `available` only when an available adapter's `operations` serves it for that operation, and is otherwise listed `available: false` with the reason no adapter runs it. For adapter-backed tasks, the operation is available when one of its options is available. If none is available and a declared option reports `runtime`, the operation reports that reason. For `image.understand` a selectable vision model serves instead, from Provider's `vision` capability. For a realtime operation the options are the models whose entry declares that `.` id, in Provider's order: the session's adapter is handed the transport the entry declares, so the entry itself is the per-model answer, and `open` refuses `unavailable` a declared model that has no transport. The owner computes the candidates from Provider's declared capabilities so clients never derive them. The current default is included when it is no longer an option, marked with its reason. The owner computes them at read time from Provider's read-only contract (§9.2) and the available adapters. An option carries only `{providerId, modelId, available, reason?}`: #790 returns ids and capabilities, not display names, so the client joins names from its existing Provider list or catalog reads by `{providerId, modelId}` and shows the ids when a name is unavailable. -- `configure` validates the operation and that the model is in that operation's options (for `image.understand`, selectable vision support; for `ocr.recognize`, one of the host targets the snapshot offers), then writes or clears the operation key through Settings' owner write with CAS. It accepts every A.1 operation that has a default key and never answers `modality_unavailable`: configuring is a settings write, not a runtime claim. An unknown category or operation answers `modality_unknown_operation`; `operation` is required where the operation has its own key (image, speech, OCR) and may be absent only for a category-keyed category. `model: null` clears that key (for OCR, `modality.ocr`); clearing restores automatic resolution, and a missing `model` is `invalid_params`. The write happens before the reply is sent, so a success means the default is persisted, and the reply is the same snapshot a following `modality.capabilities` call returns unless Provider changed in between. -- Configurable and available are different properties: the first belongs to settings, the second to the runtime. A persisted default can name a model of an operation this build cannot run; the snapshot stays honest by keeping that operation's `available: false` and its `build` or `adapter` reason, and `effective` resolves over the available options only (the default when available, otherwise automatic), so it is `null` whenever no option can run and clients do not implement resolution themselves. +- `configure` validates against the options the operation offers before the snapshot appends a persisted default. When `operation` is omitted for a category key, any operation in the category may offer the model. A declared Provider option is configurable even when it is unavailable. `image.understand` offers selectable vision models, and `ocr.recognize` requires a host target that can run here (A.2.1). It then writes or clears the default key through Settings' owner write with CAS. It accepts every A.1 operation that has a default key and never answers `modality_unavailable`: configuring is a settings write, not a runtime claim. An unknown category or operation answers `modality_unknown_operation`; `operation` is required where the operation has its own key (image, speech, OCR) and may be absent only for a category-keyed category. `model: null` clears that key (for OCR, `modality.ocr`); clearing restores automatic resolution, and a missing `model` is `invalid_params`. The write happens before the reply is sent, so a success means the default is persisted, and the reply is the same snapshot a following `modality.capabilities` call returns unless Provider changed in between. +- Configurable and available are different properties: the first belongs to settings, the second to the runtime. A persisted default can name a model of an operation this build cannot run; the snapshot stays honest by keeping that operation's `available: false` and its `build` or `adapter` reason. Clients read the resolved model from `effective`. Boundary validation: inline inputs at most 8 MiB in total per submission, larger inputs by `node_path`, an absolute path of an existing regular file on the control node whose last component is not a link (earlier links are resolved); its opened file length is compared with the remaining submission budget, and copying rejects growth or truncation; all input files at most 100 MiB per submission (A5). Media types follow A.1's input column: image operations accept `image/*`, video operations `image/*` and `video/*`, `speech.transcribe` `audio/*`, and `asset` `image/*`; an operation whose input names no file refuses files. Each file name is one component, a valid pluginFiles name, distinct within the submission. `node` is refused `invalid_input` for a provider category, and for a host category it names the executing node, which is the control node (A15). Parameters are validated at submission against the adapter's `params_schema`; invalid parameters fail `invalid_input` and write nothing. Availability is checked before model resolution: an operation this build cannot run fails with the `reasons` `modality.capabilities` shows for it (Appendix C), so a missing adapter is never reported as a missing model. Model selection: explicit `model`; else the operation default; else automatic resolution; else `no_default_model`. An explicit model that is not selectable fails `model_unavailable`, an unavailable default fails `default_unavailable`, and a resolved model no available adapter serves fails `unavailable`; none of them falls back to another model. The resolved model is fixed in the record. `image.understand` and every `realtime.*` operation are not tasks: a submission for any of them fails `modality_unknown_operation`. `ocr.recognize` is a host task (§3.2): it takes exactly one input file of `image/*` or `application/pdf`, accepts `params.outputMode` `"text"` (the default) or `"layout"`, and validates no adapter schema. Its options are the host targets this host offers (A.2.1) and its default is `modality.ocr`; an explicit model that is neither `local/apple-vision` nor `local/pp-ocr` fails `model_unavailable`, and a host target this host cannot run fails `submit` `unavailable` with the operation's `platform` or `runtime` reason. A `node` other than the control node fails the task `node_unavailable`. At most 4 running tasks per category; others stay `queued` in submission order (A6). @@ -553,7 +553,7 @@ The adapter row holds for every adapter copy; the other rows hold today. | `model_unavailable` | An explicit model is not selectable | | `realtime_limit` | At most four realtime sessions run per process; close one and retry | | `modality_conflict` | The settings revision is stale; reread and retry | -| `modality_invalid_selection` | The model is not selectable through Provider, no available adapter serves the operation, or `image.understand` names a model without vision; the reply carries the reason | +| `modality_invalid_selection` | The model is outside the options offered for the configured operation or category, or the OCR target cannot run on this host. The reply carries the reason. | | `modality_unknown_operation` | Unknown operation or default key | | `modality_unavailable` | `modality.task.submit` answers it for a known category or operation that this build does not implement: one of its `modality.capabilities` reasons has the `build` dimension, and the message names the operation and gives each reason as a `dimension: detail` line (A.3) | | `modality_failed` | An unexpected Settings or Provider failure while reading or writing the owner's configuration | @@ -584,7 +584,7 @@ Flow tests through `modality.*` methods with a fake adapter plugin (controllable 12. Changing the `modality` settings document (operation defaults, limits) applies at the next use without reloading Modality. 13. Disabling or deleting the default model, its Provider or its adapter makes `default.available` false with a reason; for a task operation, submit fails `default_unavailable`; clearing the default restores automatic resolution; no other operation is disabled. 14. Two `configure` calls with the same revision: the second fails `modality_conflict` and writes nothing; a reread shows the first writer's value. -15. Automatic resolution: with no default, a task uses Provider's global default selection when it serves the operation, otherwise the first served model in Provider's order; `effective.source` is `"automatic"` and names that model. +15. Automatic resolution with no explicit model or persisted default follows §3.4. When an available option is selected, `effective` names it with `source: "automatic"`. 16. Web admission: the authenticated loopback Web entry can call `modality.capabilities` and `modality.configure`; the bare and unauthenticated WebSocket cannot; `modality.task.*` and realtime methods are not admitted; advertisement matches dispatch. 17. Web rendering: wide and compact layouts show owner options, automatic effective model and unavailable reasons; the understanding row explains that it configures `image_understand`, not the conversational model. A conflict keeps the typed draft and offers reload; a Provider or model mutation made in the Web session refreshes the page; replies carry no credentials. 18. `image.understand` resolves and displays a default through `modality.capabilities`/`modality.configure`. A fixture [image-understanding flow](ImageUnderstanding.md#9-acceptance) uses the configured default, clearing it restores automatic resolution, and an unavailable default never falls back. diff --git a/docs/zh/design/plugins/Modality.md b/docs/zh/design/plugins/Modality.md index f151e2ae46..8eba574f21 100644 --- a/docs/zh/design/plugins/Modality.md +++ b/docs/zh/design/plugins/Modality.md @@ -168,9 +168,9 @@ sequenceDiagram Realtime 选项跟随 Provider 的传输声明,不经解析到的适配器的 `operations` 收窄。因此,不服务 realtime 的提供方专属副本可能让声明过的模型仍出现在选项中,但 `realtime.open` 以 `unavailable` 拒绝;已存在的提供方副本缺少某个操作时,不会重试家族名副本。 -`dimcode modality set-default image.generate /` 和 Web 页调用 `modality.configure`:它先校验该模型属于该操作的选项——适配器操作要求有可用适配器服务它;`image.understand` 要求它是可选的视觉模型;没有适配器服务的操作要求该模型在 Provider 的 modality 读取中、且其目录条目声明了 `.`,这样的模型可能是执行不能选择的(非 chat 模型,或未声明文本上限的模型)——再经所有者写入(Settings CAS)把该操作 key 写入 Modality 自己的 `modality` 设置文档。`model: null` 清除该 key。回复与 `modality.capabilities` 返回的是同一个快照,含新的 `revision`,客户端无需再读一次。 +`dimcode modality set-default image.generate /` 和 Web 页调用 `modality.configure`,由它按操作的选项校验模型(A.3)。该操作提供的 Provider 模型即使标为 `available: false` 也可以保存。OCR 宿主目标必须能在本机运行(A.2.1)。随后经所有者写入(Settings CAS)把默认值写入 Modality 自己的 `modality` 设置文档。`model: null` 清除该默认值。回复与 `modality.capabilities` 返回的是同一个快照,含新的 `revision`,客户端无需再读一次。 -任务按此顺序解析模型:请求中的显式 `model`;该操作 key 已持久化的默认值;自动解析——当 Provider 的全局默认选择可选且服务该操作时用它,否则用 Provider 可选模型读取顺序中第一个可选的、服务该操作的模型。显式模型或已持久化的默认值不再可选时任务失败(`model_unavailable` 或 `default_unavailable`);解析出的模型没有可用适配器服务时以 `unavailable` 失败。Modality 从不替换成别的模型。只有默认值缺失时才进入自动解析,因此清除默认值即恢复自动解析。解析出的模型写入任务记录,之后默认值变化不影响它。 +任务先使用请求中的显式 `model`,省略时使用该操作 key 已持久化的默认值。两者都缺失时进入自动解析。Provider 的全局默认选择是该操作的可用选项时优先使用,否则取第一个可用选项。适配器操作的选项沿用 Provider 的 Modality 声明顺序(§9.2)。显式模型或已持久化的默认值不再可选时任务失败(`model_unavailable` 或 `default_unavailable`);解析出的模型没有可用适配器服务时以 `unavailable` 失败。Modality 从不替换成别的模型。只有默认值缺失时才进入自动解析,因此清除默认值即恢复自动解析。解析出的模型写入任务记录,之后默认值变化不影响它。 `image.understand` 使用同样的解析但没有任务:Modality 经 `modality.capabilities` 与 `modalityTargets` 暴露生效目标。Session 使用方是 [ImageUnderstanding](../../../design/plugins/ImageUnderstanding.md),它每次工具调用时解析目标(§9.4),独立于对话模型。 @@ -452,11 +452,11 @@ wire 参数形状错误为 `invalid_params`,未知类别或操作为 `modality ``` - `revision` 是 `modality` 设置文档的 revision;一次 CAS 覆盖该文档中的全部操作 key,因此对某个操作的 `configure` 也会让持有其他操作草稿的客户端失效。只有 `configure` 使用它。 -- `default` 是已持久化的选择或 `null`。模型不再可选、或没有可用适配器服务它时(对 `image.understand`,是它不是可选的视觉模型时),`available` 为 `false`,`reason` 说明原因:不再可选时为 `provider`,有适配器为该模型服务此操作但当前不可用时为 `runtime`,本构建没有该类别的适配器时为 `build`,其余为 `adapter`。 -- `effective` 是任务或使用方现在会使用的模型:它只从可用的选项解析,因此没有选项能运行时为 `null`,客户端从不会拿到一个操作会拒绝的模型。默认值可用时就是默认值。`default` 为 `null` 时它是自动解析:Provider 的全局默认选择是可用选项时用它,否则用 Provider 顺序中第一个可用选项;`source` 为 `"automatic"`。不可用的默认值给出 `effective: null`,从不替换成别的模型。 +- `default` 是已持久化的选择或 `null`。默认值不可用时,`available` 为 `false`,`reason` 可以是模型不再可选时的 `provider`、已知模型不在操作选项中时的 `configuration`、为该模型服务此操作的适配器当前不可用时的 `runtime`、本构建没有该类别适配器时的 `build`,或没有适配器为该模型服务此操作时的 `adapter`。例如,按类别保存的默认模型只声明了 `video.generate` 时,`video.edit` 行会报告 `configuration`。 +- `effective` 是任务或使用方现在会使用的模型:它只从可用的选项解析,因此没有选项能运行时为 `null`,客户端从不会拿到一个操作会拒绝的模型。默认值可用时就是默认值。`default` 为 `null` 时按 §3.4 自动解析。选中模型时,`source` 为 `"automatic"`。不可用的默认值给出 `effective: null`,从不替换成别的模型。 - `options` 列出服务该操作的模型。候选来自 Provider 的非会话读取(`selectableForModality`,§9.2),因此被执行拒绝的媒体模型——非 chat 模型,或未声明文本上限的模型——只要其目录条目声明了该操作就是候选。对其他操作,选项是其 Provider 目录条目声明了该 `.` id 的模型,按 Provider 的顺序,没有任何声明的操作选项为空;只有可用适配器的 `operations` 为该操作服务它时才 `available`,否则列为 `available: false` 并带上没有适配器运行它的原因。对于适配器执行的任务,只要有一个选项可用,操作就可用。若所有选项均不可用且有声明的选项报告 `runtime`,操作也报告该原因。对 `image.understand`,改由可选的视觉模型服务,取自 Provider 的 `vision` 能力。对实时操作,选项是其条目声明了该 `.` id 的模型,按 Provider 的顺序:会话适配器收到的正是条目声明的传输,因此条目本身就是逐模型答案;声明了操作但没有传输的模型由 `open` 以 `unavailable` 拒绝。所有者从 Provider 的已声明能力计算候选,客户端不自行推导。当前默认值不再是选项时也会列出,并标注原因。所有者读取时从 Provider 的只读契约(§9.2)与可用适配器计算它们。选项只带 `{providerId, modelId, available, reason?}`:读取返回 id 与能力,不返回展示名,因此客户端按 `{providerId, modelId}` 从它已有的 Provider 列表或目录读取中并入名字,取不到名字时显示 id。 -- `configure` 先校验操作以及模型在该操作的可选选项中(对 `image.understand`,可选视觉支持;对 `ocr.recognize`,快照当前提供的宿主目标之一),再经 Settings 的所有者写入以 CAS 写入或清除该操作 key。它接受任何有默认 key 的 A.1 操作,且从不答复 `modality_unavailable`:配置是设置写入,不是运行时断言。未知类别或操作答复 `modality_unknown_operation`;操作有自己的 key 时(image、speech、OCR)`operation` 必填,只有按类别划分 key 的类别可以省略。`model: null` 清除该 key(对 OCR 即 `modality.ocr`);清除即恢复自动解析;缺少 `model` 为 `invalid_params`。写入在回复发出之前完成,因此成功即表示默认值已持久化,且该回复与紧随其后的 `modality.capabilities` 读到的一致(除非 Provider 在此期间变化)。 -- 可配置性与可用性是两个不同的属性:前者属于设置,后者属于运行时。已持久化的默认值可以指向本构建不能运行的操作的模型;快照通过保持该操作的 `available: false` 及其 `build` 或 `adapter` 原因保持诚实,而 `effective` 只在可用选项上解析(默认值可用时用默认值,否则自动解析),没有选项能运行时为 `null`,客户端因此无需自行实现解析。 +- `configure` 按操作提供的选项校验模型,校验以快照附加已持久化的默认值之前的选项为准。对按类别划分的 key,省略 `operation` 时可选该类别内任一操作提供的模型。Provider 已声明的选项暂不可用时仍可配置。`image.understand` 提供可选的视觉模型,`ocr.recognize` 要求宿主目标能在本机运行(A.2.1)。随后经 Settings 的所有者写入以 CAS 写入或清除该默认值。它接受任何有默认 key 的 A.1 操作,且从不答复 `modality_unavailable`:配置是设置写入,不是运行时断言。未知类别或操作答复 `modality_unknown_operation`;操作有自己的 key 时(image、speech、OCR)`operation` 必填,只有按类别划分 key 的类别可以省略。`model: null` 清除该 key(对 OCR 即 `modality.ocr`);清除即恢复自动解析;缺少 `model` 为 `invalid_params`。写入在回复发出之前完成,因此成功即表示默认值已持久化,且该回复与紧随其后的 `modality.capabilities` 读到的一致(除非 Provider 在此期间变化)。 +- 可配置性与可用性是两个不同的属性:前者属于设置,后者属于运行时。已持久化的默认值可以指向本构建不能运行的操作的模型;快照通过保持该操作的 `available: false` 及其 `build` 或 `adapter` 原因保持诚实。客户端从 `effective` 读取解析后的模型。 边界校验:每次提交的内联输入合计至多 8 MiB,更大的输入使用 `node_path`——控制节点上已存在普通文件的绝对路径,最后一个组件不得是链接(更早的链接会被解析);读取前先将其长度与 100 MiB 提交预算的剩余量比较,记录的是规范路径,执行方在该路径读取,Modality 从不复制;每次提交的输入文件合计至多 100 MiB(A5)。媒体类型遵循 A.1 的输入列:图像操作接受 `image/*`,视频操作接受 `image/*` 与 `video/*`,`speech.transcribe` 接受 `audio/*`,`asset` 接受 `image/*`;输入不指名文件的操作拒绝文件。每个文件名是单个组件、合法的 pluginFiles 名称,且在提交内互不相同。`node` 对提供方类别以 `invalid_input` 拒绝,对宿主类别则指明执行节点,即控制节点(A15)。参数在提交时按适配器的 `params_schema` 校验;非法参数以 `invalid_input` 失败且不写入任何内容。可用性检查先于模型解析:本构建无法运行的操作会带着 `modality.capabilities` 中该操作的原因失败,见附录 C,因此缺失适配器不会被报成缺失模型。模型选择:显式 `model`;否则操作默认值;否则自动解析;否则 `no_default_model`。不可选的显式模型以 `model_unavailable` 失败,不可用的默认值以 `default_unavailable` 失败,解析出的模型没有可用适配器服务时以 `unavailable` 失败;都不回退到其他模型。解析出的模型固定在记录中。`image.understand` 与每个 `realtime.*` 操作都不是任务:为它们提交会以 `modality_unknown_operation` 失败。`ocr.recognize` 是宿主任务(§3.2):只接受一个输入文件,`image/*` 或 `application/pdf`,接受 `params.outputMode` `"text"`(默认)或 `"layout"`,不校验适配器 schema。其选项是本宿主提供的宿主目标(A.2.1),其默认值是 `modality.ocr`;既非 `local/apple-vision` 也非 `local/pp-ocr` 的显式模型以 `model_unavailable` 失败,本宿主无法运行的宿主目标使 `submit` 以 `unavailable` 失败并带该操作的 `platform` 或 `runtime` 原因。指明控制节点以外节点的任务以 `node_unavailable` 失败。每个类别至多 4 个运行中任务;其余按提交顺序保持 `queued`(A6)。 @@ -547,7 +547,7 @@ wire 参数形状错误为 `invalid_params`,未知类别或操作为 `modality | `model_unavailable` | 显式模型不可选 | | `realtime_limit` | 每个进程至多四个实时会话;关闭一个后重试 | | `modality_conflict` | 设置 revision 已过期;重新读取后重试 | -| `modality_invalid_selection` | 模型不可经 Provider 选择、没有可用适配器服务该操作,或 `image.understand` 指定的模型没有视觉能力;回复带原因 | +| `modality_invalid_selection` | 模型不在指定操作或类别提供的选项中,或 OCR 宿主目标无法在本机运行。回复带原因。 | | `modality_unknown_operation` | 未知操作或默认值 key | | `modality_unavailable` | 由 `modality.task.submit` 对已知但本构建未实现的类别或操作答复:其 `modality.capabilities` 原因中有一个是 `build` 维度,消息点名该操作并逐行给出每个原因,形如 `dimension: detail`(A.3) | | `modality_failed` | 读写所有者配置时 Settings 或 Provider 的意外失败 | @@ -578,7 +578,7 @@ wire 参数形状错误为 `invalid_params`,未知类别或操作为 `modality 12. 修改 `modality` 设置文档(操作默认值、上限)在下次使用时生效,无需重载 Modality。 13. 禁用或删除默认模型、其 Provider 或其适配器会使 `default.available` 为 false 并带原因;对任务操作,提交以 `default_unavailable` 失败;清除默认值恢复自动解析;没有其他操作被禁用。 14. 两次使用同一 revision 的 `configure`:第二次以 `modality_conflict` 失败且不写入;重新读取看到第一个写入者的值。 -15. 自动解析:没有默认值时,任务在 Provider 的全局默认选择服务该操作时使用它,否则使用 Provider 可选模型读取顺序中第一个被服务的模型;`effective.source` 为 `"automatic"` 并给出该模型。 +15. 没有显式模型和已持久化的默认值时,按 §3.4 自动解析。选中可用选项后,`effective` 给出该模型,`source` 为 `"automatic"`。 16. Web 入口准入:经认证的 loopback Web 入口可调用 `modality.capabilities` 与 `modality.configure`;裸与未认证的 WebSocket 不能;`modality.task.*` 与实时方法不被准入;声明与分发一致。 17. Web 渲染:宽与紧凑布局显示所有者选项、自动生效模型与不可用原因;理解行说明该设置用于 `image_understand`,而非对话模型。冲突保留已输入的草稿并提供重新加载;在 Web 会话中所做的 Provider 或模型变更会刷新页面;回复不带凭据。 18. `image.understand` 经 `modality.capabilities`/`modality.configure` 解析并显示默认值。fixture [图像理解流程](../../../design/plugins/ImageUnderstanding.md#9-acceptance)使用已配置的默认值,清除它即恢复自动解析,不可用的默认值从不回退。