You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/22 15:28:13 UTC
(maka) branch feat/runtime-host-rust updated: feat(workhub): recover model selection through public plugin capabilities
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/feat/runtime-host-rust by this push:
new 83159a92d0 feat(workhub): recover model selection through public plugin capabilities
83159a92d0 is described below
commit 83159a92d072efba8a25c2ab27d1bd5eed925395
Author: Wang <m4...@gmail.com>
AuthorDate: Tue Sep 22 23:28:05 2026 +0800
feat(workhub): recover model selection through public plugin capabilities
Generated-by: Codex
---
crates/event-log/src/sessions/metadata.rs | 35 ++-
crates/js-runtime/src/plugin/sdk.js | 2 +
crates/plugins/src/execution.rs | 8 +
crates/plugins/src/llm.rs | 39 ++++
crates/runtime-host/src/execution/plugins.rs | 6 +
.../src/execution/plugins/configure.rs | 9 +-
crates/runtime-host/src/execution/plugins/llm.rs | 81 +++++++
crates/runtime-host/src/execution/plugins/root.rs | 234 ++++++++++++++++-----
crates/runtime-host/src/plugins/effects.rs | 12 ++
.../runtime-host/src/plugins/javascript/bridge.rs | 5 +
.../src/plugins/javascript/bridge/wire.rs | 4 +
.../tests/fixtures/background-plugin.mjs | 29 +++
crates/runtime-host/tests/fixtures/host-plugin.mjs | 10 +
.../tests/integration/workhub_public.rs | 149 ++++++++++++-
crates/workhub/src/coordinator.rs | 118 +++++++++--
crates/workhub/src/plugin/remote.rs | 82 ++++++--
packages/plugin-sdk/README.md | 4 +-
packages/plugin-sdk/README.zh-CN.md | 4 +-
packages/plugin-sdk/src/execution.ts | 9 +-
packages/plugin-sdk/src/host.ts | 4 +
packages/plugin-sdk/src/llm.ts | 15 ++
packages/workhub/src/access.tsx | 9 +-
packages/workhub/src/client.tsx | 54 +++--
packages/workhub/src/model-selection.tsx | 134 ++++++++++++
packages/workhub/src/styles.css | 23 ++
25 files changed, 950 insertions(+), 129 deletions(-)
diff --git a/crates/event-log/src/sessions/metadata.rs b/crates/event-log/src/sessions/metadata.rs
index 5b42cd250d..0a9d72dd90 100644
--- a/crates/event-log/src/sessions/metadata.rs
+++ b/crates/event-log/src/sessions/metadata.rs
@@ -79,6 +79,39 @@ impl EventLog {
expected: u64,
update: F,
) -> Result<SessionMutation<T>, StoreError>
+ where
+ T: Serialize + DeserializeOwned + Clone + PartialEq + Send + 'static,
+ F: FnOnce(&mut T) -> Result<(), StoreError> + Send + 'static,
+ {
+ self.mutate_session_metadata(id, expected, false, update)
+ .await
+ }
+
+ /// A successful replacement always advances the revision, even for identical
+ /// content. Callers can use the committed choice to fence older configuration CASes.
+ pub async fn replace_session_metadata<T>(
+ &self,
+ id: &str,
+ expected: u64,
+ configuration: T,
+ ) -> Result<SessionMutation<T>, StoreError>
+ where
+ T: Serialize + DeserializeOwned + Clone + PartialEq + Send + 'static,
+ {
+ self.mutate_session_metadata(id, expected, true, move |current| {
+ *current = configuration;
+ Ok(())
+ })
+ .await
+ }
+
+ async fn mutate_session_metadata<T, F>(
+ &self,
+ id: &str,
+ expected: u64,
+ always_advance: bool,
+ update: F,
+ ) -> Result<SessionMutation<T>, StoreError>
where
T: Serialize + DeserializeOwned + Clone + PartialEq + Send + 'static,
F: FnOnce(&mut T) -> Result<(), StoreError> + Send + 'static,
@@ -104,7 +137,7 @@ impl EventLog {
}
let previous = record.configuration.clone();
update(&mut record.configuration)?;
- if record.configuration == previous {
+ if !always_advance && record.configuration == previous {
return Ok(SessionMutation::Committed(record));
}
let configuration = serde_json::to_string(&record.configuration)?;
diff --git a/crates/js-runtime/src/plugin/sdk.js b/crates/js-runtime/src/plugin/sdk.js
index 484dfa9211..f0f18fd651 100644
--- a/crates/js-runtime/src/plugin/sdk.js
+++ b/crates/js-runtime/src/plugin/sdk.js
@@ -225,6 +225,7 @@
restoreChild: (input) => call('restoreChild', input),
createChild: (input) => call('createChild', input),
createRoot: (input) => call('createRoot', input),
+ restoreRoot: (operationId) => call('restoreRoot', { operationId }),
workspacePatch: (operationId) => call('workspacePatch', { operationId }),
query: (operationId) => call('query', { operationId }),
cancel: (operationId) => call('cancel', { operationId }),
@@ -527,6 +528,7 @@
}),
models: Object.freeze({
resolve: (selection) => host('models.resolve', selection),
+ search: (query = {}) => host('models.search', query),
}),
async revision() {
const handle = await host('revision', { kind: 'new' });
diff --git a/crates/plugins/src/execution.rs b/crates/plugins/src/execution.rs
index 6b3ad8b60e..fecd041a41 100644
--- a/crates/plugins/src/execution.rs
+++ b/crates/plugins/src/execution.rs
@@ -433,6 +433,7 @@ pub trait Commands: Send + Sync + std::any::Any {
) -> futures_util::future::BoxFuture<'_, Result<Invocation, CommandError>>;
/// Replace an idle Session's model/Executor selection without changing its
/// workspace, behavior or permission ceiling. Revision mismatch is explicit.
+ /// Every committed choice advances the revision, including identical values.
fn configure(
&self,
input: Configure,
@@ -509,6 +510,13 @@ pub trait Commands: Send + Sync + std::any::Any {
&self,
request: CreateRoot,
) -> futures_util::future::BoxFuture<'_, Result<ChildSession, CommandError>>;
+ /// Recover this namespace's managed root without replaying its creation settings.
+ /// Rechecks the current workspace and source ceilings. Absence is only an
+ /// observation: a concurrent creation may still commit with this operation ID.
+ fn restore_root(
+ &self,
+ operation_id: String,
+ ) -> futures_util::future::BoxFuture<'_, Result<Option<ChildSession>, CommandError>>;
/// Host-captured constraints suitable for persisting with a business intent.
fn boundaries(&self) -> Result<Vec<SessionBoundary>, CommandError>;
/// Export a settled child workspace once; exact retries return its immutable Artifact.
diff --git a/crates/plugins/src/llm.rs b/crates/plugins/src/llm.rs
index af495393b0..0c687f65ef 100644
--- a/crates/plugins/src/llm.rs
+++ b/crates/plugins/src/llm.rs
@@ -50,6 +50,12 @@ impl Selection {
}
pub trait Models: Send + Sync {
+ /// Bounded, non-secret chat model choices. Refine the query when incomplete.
+ /// Discovery does not grant execution authority or promise provider readiness.
+ fn search(
+ &self,
+ query: Search,
+ ) -> futures_util::future::BoxFuture<'_, Result<Choices, crate::Error>>;
/// Resolve an enabled model without exposing credentials, endpoints, or overlays.
/// Admission still validates the selected binding and its current permissions.
fn resolve(
@@ -67,6 +73,39 @@ pub trait Models: Send + Sync {
) -> futures_util::future::BoxFuture<'_, Result<ModelGeneration, maka_runtime::tools::ToolError>>;
}
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Search {
+ #[serde(default)]
+ pub query: String,
+}
+impl Search {
+ pub fn validate(&self) -> Result<(), crate::Error> {
+ if self.query.len() > 512 || self.query.chars().any(char::is_control) {
+ return Err(crate::Error::Invalid("invalid model search query".into()));
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Choice {
+ pub model: maka_runtime::execution::ModelBinding,
+ pub connection_name: String,
+ pub display_name: String,
+ pub thinking_levels: Vec<maka_runtime::execution::ThinkingLevel>,
+ pub is_default: bool,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Choices {
+ pub revision: u64,
+ pub models: Vec<Choice>,
+ pub complete: bool,
+}
+
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Generate {
diff --git a/crates/runtime-host/src/execution/plugins.rs b/crates/runtime-host/src/execution/plugins.rs
index 03f63d6ba6..39d2a89622 100644
--- a/crates/runtime-host/src/execution/plugins.rs
+++ b/crates/runtime-host/src/execution/plugins.rs
@@ -686,6 +686,12 @@ impl Commands for BoundCommands {
) -> BoxFuture<'_, Result<ChildSession, Error>> {
Box::pin(self.root(request))
}
+ fn restore_root(
+ &self,
+ operation_id: String,
+ ) -> BoxFuture<'_, Result<Option<ChildSession>, Error>> {
+ Box::pin(self.restore_managed_root(operation_id))
+ }
fn boundaries(&self) -> Result<Vec<maka_plugins::execution::SessionBoundary>, Error> {
let _lease = self.context.resource_call().map_err(|_| Error::Revoked)?;
Ok(self
diff --git a/crates/runtime-host/src/execution/plugins/configure.rs b/crates/runtime-host/src/execution/plugins/configure.rs
index 3a18d50ae5..22ff528766 100644
--- a/crates/runtime-host/src/execution/plugins/configure.rs
+++ b/crates/runtime-host/src/execution/plugins/configure.rs
@@ -111,14 +111,7 @@ impl BoundCommands {
host.workers.spawn(async move {
let result = worker
.log
- .update_session_metadata(
- &input.session_id,
- input.expected_revision,
- move |configuration: &mut SessionConfiguration| {
- *configuration = next;
- Ok(())
- },
- )
+ .replace_session_metadata(&input.session_id, input.expected_revision, next)
.await
.map(|result| match result {
SessionMutation::Committed(record) => Configured::Committed {
diff --git a/crates/runtime-host/src/execution/plugins/llm.rs b/crates/runtime-host/src/execution/plugins/llm.rs
index 5457d4ff4b..0b9a6d9390 100644
--- a/crates/runtime-host/src/execution/plugins/llm.rs
+++ b/crates/runtime-host/src/execution/plugins/llm.rs
@@ -34,6 +34,80 @@ use std::sync::Arc;
use tokio_util::sync::CancellationToken;
impl Executions {
+ pub(crate) async fn search_plugin_models(
+ &self,
+ query: maka_plugins::llm::Search,
+ ) -> Result<maka_plugins::llm::Choices, maka_plugins::Error> {
+ use maka_plugins::{
+ Error,
+ llm::{Choice, Choices},
+ };
+ let failed = |error: maka_config::ConfigError| Error::Invalid(error.to_string());
+ let catalog = self.configuration.catalog().await.map_err(failed)?;
+ tokio::task::spawn_blocking(move || {
+ let query = query.query.to_lowercase();
+ let terms: Vec<_> = query.split_whitespace().collect();
+ let mut page = Choices {
+ revision: catalog.revision,
+ models: Vec::new(),
+ complete: true,
+ };
+ 'connections: for row in &catalog.connections {
+ if !row.enabled
+ || maka_config::model_catalog::provider_facts(&row.provider_type)
+ .map_err(failed)?
+ .retired
+ {
+ continue;
+ }
+ let default = catalog
+ .default_target
+ .as_ref()
+ .filter(|target| target.connection_id == row.connection_id)
+ .map(|target| target.model_id.as_str());
+ for entry in maka_config::model_catalog::resolve(row, default).map_err(failed)? {
+ if !entry.can_use_as_chat_default || !row.enabled_model_ids.contains(&entry.id)
+ {
+ continue;
+ }
+ let display_name = entry.display_name.unwrap_or_else(|| entry.id.clone());
+ let haystack =
+ format!("{} {} {} {}", row.slug, row.name, entry.id, display_name)
+ .to_lowercase();
+ if !terms.iter().all(|term| haystack.contains(term)) {
+ continue;
+ }
+ if page.models.len() == 50 {
+ page.complete = false;
+ break 'connections;
+ }
+ page.models.push(Choice {
+ model: maka_runtime::execution::ModelBinding {
+ connection_id: row.connection_id.clone(),
+ connection_slug: row.slug.clone(),
+ model: entry.id,
+ },
+ connection_name: row.name.clone(),
+ display_name,
+ thinking_levels: entry.thinking_levels,
+ is_default: entry.is_default,
+ });
+ }
+ }
+ while serde_json::to_vec(&page)
+ .map_err(|error| Error::Invalid(error.to_string()))?
+ .len()
+ > 48 * 1024
+ {
+ page.models.pop();
+ page.complete = false;
+ }
+ Ok(page)
+ })
+ .await
+ .map_err(|error| Error::Invalid(error.to_string()))?
+ }
+
pub(crate) async fn resolve_plugin_model(
&self,
selection: maka_plugins::llm::Selection,
@@ -79,6 +153,13 @@ impl Executions {
{
return Ok(None);
}
+ if !maka_config::model_catalog::resolve(&row, Some(&model))
+ .map_err(|error| maka_plugins::Error::Invalid(error.to_string()))?
+ .iter()
+ .any(|entry| entry.id == model && entry.can_use_as_chat_default)
+ {
+ return Ok(None);
+ }
Ok(Some(maka_runtime::execution::ModelBinding {
connection_id: row.connection_id,
connection_slug: row.slug,
diff --git a/crates/runtime-host/src/execution/plugins/root.rs b/crates/runtime-host/src/execution/plugins/root.rs
index a96fd47f59..7496551374 100644
--- a/crates/runtime-host/src/execution/plugins/root.rs
+++ b/crates/runtime-host/src/execution/plugins/root.rs
@@ -59,6 +59,117 @@ impl From<RootApproval> for RootGrant {
}
impl BoundCommands {
+ fn root_id(&self, operation_id: &str) -> Result<String, Error> {
+ if operation_id.is_empty()
+ || operation_id.len() > 256
+ || operation_id
+ .chars()
+ .any(|c| c.is_control() || c.is_whitespace())
+ {
+ return Err(Error::Invalid("invalid root operation ID".into()));
+ }
+ let bytes = serde_json::to_vec(&(
+ "plugin-root-v1",
+ self.namespace.package(),
+ String::from(self.namespace.scope().clone()),
+ operation_id,
+ ))
+ .map_err(|error| Error::Invalid(error.to_string()))?;
+ Ok(format!("plugin-root-{:x}", Sha256::digest(bytes)))
+ }
+
+ pub(super) async fn restore_managed_root(
+ &self,
+ operation_id: String,
+ ) -> Result<Option<ChildSession>, Error> {
+ let id = self.root_id(&operation_id)?;
+ let approval = self.root_grant.as_ref().ok_or(Error::Denied)?;
+ let host = self.executions()?;
+ let _lease = self.context.admit().map_err(|_| Error::Revoked)?;
+ self.authorize_origin(&host).await?;
+ let project = observe_workspace(&host, approval).await?;
+ let _gate = host.interactions.own_admission().await;
+ self.authorize_origin(&host).await?;
+ recheck_project(&host, project).await?;
+ if !host.accepting() {
+ return Err(Error::Draining);
+ }
+ if self.submission_stop.is_cancelled() {
+ return Err(Error::Revoked);
+ }
+ let Some(record) = host
+ .log
+ .get_session::<SessionConfiguration>(&id)
+ .await
+ .map_err(storage)?
+ else {
+ return Ok(None);
+ };
+ if host
+ .log
+ .session_manager(&id)
+ .await
+ .map_err(storage)?
+ .as_ref()
+ != Some(&self.namespace)
+ {
+ return Err(Error::Denied);
+ }
+ let current = &record.configuration;
+ if record.archived
+ || current.workspace != approval.workspace
+ || current.workspace_origin != approval.workspace_origin
+ || rank(current.sandbox_mode) > rank(approval.sandbox_mode)
+ || !current
+ .approval_policy
+ .is_subset_of(approval.approval_policy)
+ {
+ return Err(Error::Denied);
+ }
+ if let Some(source) = &approval.source {
+ let origin = host
+ .log
+ .get_session::<SessionConfiguration>(&source.session_id)
+ .await
+ .map_err(storage)?
+ .ok_or(Error::NotFound)?;
+ let parent = &origin.configuration;
+ if rank(current.sandbox_mode) > rank(parent.sandbox_mode)
+ || !current.approval_policy.is_subset_of(parent.approval_policy)
+ || current.workspace.host_cwd != parent.workspace.host_cwd
+ || current.workspace_origin != parent.workspace_origin
+ || parent.bound_tools.as_ref().is_some_and(|ceiling| {
+ current
+ .bound_tools
+ .as_ref()
+ .is_none_or(|tools| !tools.is_subset(ceiling))
+ })
+ || parent.tool_profile.is_some() && current.tool_profile != parent.tool_profile
+ || parent.instructions.as_ref().is_some_and(|base| {
+ current.instructions.as_ref().is_none_or(|text| {
+ text != base
+ && !text
+ .strip_prefix(base)
+ .is_some_and(|tail| tail.starts_with("\n\n"))
+ })
+ })
+ {
+ return Err(Error::Denied);
+ }
+ }
+ self.grants.lock().unwrap().insert(
+ id.clone(),
+ Grant {
+ workspace_origin: current.workspace_origin,
+ boundary_revision: current.boundary_revision,
+ sandbox_mode: current.sandbox_mode,
+ approval_policy: current.approval_policy,
+ cwd: current.workspace.host_cwd.clone(),
+ },
+ );
+ Ok(Some(ChildSession { session_id: id }))
+ }
+
pub(super) async fn authorize_origin(&self, host: &Executions) -> Result<(), Error> {
if let Some(call) = &self.call {
match host.plugin_execution_boundary(call).await? {
@@ -152,14 +263,7 @@ impl BoundCommands {
let host = self.executions()?;
let lease = self.context.admit().map_err(|_| Error::Revoked)?;
self.authorize_origin(&host).await?;
- let bytes = serde_json::to_vec(&(
- "plugin-root-v1",
- self.namespace.package(),
- String::from(self.namespace.scope().clone()),
- &request.operation_id,
- ))
- .map_err(|error| Error::Invalid(error.to_string()))?;
- let id = format!("plugin-root-{:x}", Sha256::digest(bytes));
+ let id = self.root_id(&request.operation_id)?;
let fingerprint = format!(
"sha256:{:x}",
Sha256::digest(
@@ -167,57 +271,10 @@ impl BoundCommands {
.map_err(|error| Error::Invalid(error.to_string()))?
)
);
- let observed_project = match &approval.workspace.target {
- WorkspaceTarget::Project { project_id } => Some(
- host.log
- .get_project(project_id)
- .await
- .map_err(storage)?
- .ok_or(Error::NotFound)?,
- ),
- WorkspaceTarget::HostPath { .. } => None,
- };
- // Filesystem observation never holds Host-wide admission.
- if let Some(project) = &observed_project {
- let resolved = crate::server::resolve_project_workspace(project.clone())
- .await
- .map_err(|error| Error::Invalid(error.message))?;
- if resolved.host_cwd != approval.workspace.host_cwd {
- return Err(Error::Denied);
- }
- }
- let path = std::path::PathBuf::from(&approval.workspace.host_cwd);
- let expected = approval.workspace_identity.clone();
- tokio::task::spawn_blocking(move || {
- let canonical = path
- .canonicalize()
- .map_err(|error| Error::Host(error.to_string()))?;
- if maka_fs_tools::workspace::project::host_path(&canonical)
- .map_err(|error| Error::Host(error.to_string()))?
- != path.to_str().ok_or(Error::Denied)?
- || maka_fs_tools::workspace::read_identity(&canonical)
- .map_err(|error| Error::Host(error.to_string()))?
- != expected
- {
- return Err(Error::Denied);
- }
- Ok(())
- })
- .await
- .map_err(|error| Error::Host(error.to_string()))??;
+ let observed_project = observe_workspace(&host, approval).await?;
let gate = host.interactions.own_admission().await;
self.authorize_origin(&host).await?;
- if let Some(project) = observed_project
- && host
- .log
- .get_project(&project.id)
- .await
- .map_err(storage)?
- .as_ref()
- != Some(&project)
- {
- return Err(Error::Conflict);
- }
+ recheck_project(&host, observed_project).await?;
let approval = approval.clone();
let worker = host.clone();
let grants = self.grants.clone();
@@ -313,6 +370,69 @@ impl BoundCommands {
}
}
+// Filesystem observation never holds Host-wide admission.
+async fn observe_workspace(
+ host: &Executions,
+ approval: &RootGrant,
+) -> Result<Option<maka_event_log::projects::ProjectRecord>, Error> {
+ let project = match &approval.workspace.target {
+ WorkspaceTarget::Project { project_id } => Some(
+ host.log
+ .get_project(project_id)
+ .await
+ .map_err(storage)?
+ .ok_or(Error::NotFound)?,
+ ),
+ WorkspaceTarget::HostPath { .. } => None,
+ };
+ if let Some(project) = &project {
+ let resolved = crate::server::resolve_project_workspace(project.clone())
+ .await
+ .map_err(|error| Error::Invalid(error.message))?;
+ if resolved.host_cwd != approval.workspace.host_cwd {
+ return Err(Error::Denied);
+ }
+ }
+ let path = std::path::PathBuf::from(&approval.workspace.host_cwd);
+ let expected = approval.workspace_identity.clone();
+ tokio::task::spawn_blocking(move || {
+ let canonical = path
+ .canonicalize()
+ .map_err(|error| Error::Host(error.to_string()))?;
+ if maka_fs_tools::workspace::project::host_path(&canonical)
+ .map_err(|error| Error::Host(error.to_string()))?
+ != path.to_str().ok_or(Error::Denied)?
+ || maka_fs_tools::workspace::read_identity(&canonical)
+ .map_err(|error| Error::Host(error.to_string()))?
+ != expected
+ {
+ return Err(Error::Denied);
+ }
+ Ok(())
+ })
+ .await
+ .map_err(|error| Error::Host(error.to_string()))??;
+ Ok(project)
+}
+
+async fn recheck_project(
+ host: &Executions,
+ project: Option<maka_event_log::projects::ProjectRecord>,
+) -> Result<(), Error> {
+ if let Some(project) = project
+ && host
+ .log
+ .get_project(&project.id)
+ .await
+ .map_err(storage)?
+ .as_ref()
+ != Some(&project)
+ {
+ return Err(Error::Conflict);
+ }
+ Ok(())
+}
+
async fn configuration(
host: &Arc<Executions>,
id: &str,
diff --git a/crates/runtime-host/src/plugins/effects.rs b/crates/runtime-host/src/plugins/effects.rs
index 2980fb778a..b016216bd6 100644
--- a/crates/runtime-host/src/plugins/effects.rs
+++ b/crates/runtime-host/src/plugins/effects.rs
@@ -147,6 +147,18 @@ impl maka_plugins::permissions::Access for Effects {
}
}
impl maka_plugins::llm::Models for Effects {
+ fn search(
+ &self,
+ query: maka_plugins::llm::Search,
+ ) -> BoxFuture<'_, Result<maka_plugins::llm::Choices, maka_plugins::Error>> {
+ Box::pin(async move {
+ query.validate()?;
+ let _lease = self.owner.resource_call()?;
+ let host = self.host.upgrade().ok_or(maka_plugins::Error::Retired)?;
+ host.search_plugin_models(query).await
+ })
+ }
+
fn resolve(
&self,
selection: maka_plugins::llm::Selection,
diff --git a/crates/runtime-host/src/plugins/javascript/bridge.rs b/crates/runtime-host/src/plugins/javascript/bridge.rs
index ff43a56af3..d9e1f59695 100644
--- a/crates/runtime-host/src/plugins/javascript/bridge.rs
+++ b/crates/runtime-host/src/plugins/javascript/bridge.rs
@@ -283,6 +283,7 @@ impl State {
)
}
Request::ResolveModel(input) => encode(self.models.resolve(input).await?),
+ Request::SearchModels(input) => encode(self.models.search(input).await?),
Request::Revision(input) => {
let _lease = self.context.lifecycle.resource_call()?;
Ok(self.calls.revisions.call(input).await?)
@@ -626,6 +627,10 @@ impl State {
let (commands, input) = self.execution(input)?;
encode(commands.create_root(input).await?)
}
+ Request::RestoreRoot(input) => {
+ let (commands, input) = self.execution(input)?;
+ encode(commands.restore_root(input.operation_id).await?)
+ }
Request::WorkspacePatch(input) => {
let (commands, input) = self.execution(input)?;
encode(commands.workspace_patch(input.operation_id).await?)
diff --git a/crates/runtime-host/src/plugins/javascript/bridge/wire.rs b/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
index 94418b31ef..0d0e8eada4 100644
--- a/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
+++ b/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
@@ -81,6 +81,8 @@ pub(super) enum Request {
HistoryCopy(HistoryCopy),
#[serde(rename = "models.resolve")]
ResolveModel(maka_plugins::llm::Selection),
+ #[serde(rename = "models.search")]
+ SearchModels(maka_plugins::llm::Search),
#[serde(rename = "llm.generate")]
Generate(ModelRequest),
#[serde(rename = "clients.tools")]
@@ -167,6 +169,8 @@ pub(super) enum Request {
CreateChild(Execution<CreateChild>),
#[serde(rename = "execution.createRoot")]
CreateRoot(Execution<CreateRoot>),
+ #[serde(rename = "execution.restoreRoot")]
+ RestoreRoot(Execution<Operation>),
#[serde(rename = "execution.workspacePatch")]
WorkspacePatch(Execution<Operation>),
#[serde(rename = "execution.query")]
diff --git a/crates/runtime-host/tests/fixtures/background-plugin.mjs b/crates/runtime-host/tests/fixtures/background-plugin.mjs
index db0fcb25f9..f9c569edea 100644
--- a/crates/runtime-host/tests/fixtures/background-plugin.mjs
+++ b/crates/runtime-host/tests/fixtures/background-plugin.mjs
@@ -204,6 +204,19 @@ export default async function (ctx) {
});
if (configured.kind !== 'committed' || configured.session.sessionId !== root.sessionId)
throw new Error('managed Session configuration did not commit');
+ if (configured.session.revision <= session.revision)
+ throw new Error('successful configuration must fence older choices, including no-ops');
+ const staleChoice = await commands.configure({
+ sessionId: root.sessionId,
+ expectedRevision: session.revision,
+ target: {
+ kind: 'executor',
+ executorId: 'example.background',
+ settings: { model: 'stale-choice' },
+ },
+ });
+ if (staleChoice.kind !== 'revision_conflict')
+ throw new Error('an older choice overrode the successful no-op configuration');
const replay = await commands.createRoot(request);
if (replay.sessionId !== root.sessionId)
throw new Error('root creation replay changed identity');
@@ -213,6 +226,22 @@ export default async function (ctx) {
} catch (error) {
if (error.code !== 'conflict') throw error;
}
+ // A fresh capability can recover the managed root without remembering
+ // which creation proposal won; changed create retries still conflict.
+ const restoredCommands = await ctx.executions.restore(intent.grant);
+ try {
+ const restored = await restoredCommands.restoreRoot(intent.operation);
+ if (
+ restored?.sessionId !== root.sessionId ||
+ (await restoredCommands.session(restored.sessionId)).revision !==
+ configured.session.revision
+ )
+ throw new Error('managed root recovery lost its identity or configuration');
+ if ((await restoredCommands.restoreRoot('uncreated-root')) !== null)
+ throw new Error('managed root recovery created a Session');
+ } finally {
+ await restoredCommands.close();
+ }
const receipt = await commands.submit({
operationId: 'workspace-work',
sessionId: root.sessionId,
diff --git a/crates/runtime-host/tests/fixtures/host-plugin.mjs b/crates/runtime-host/tests/fixtures/host-plugin.mjs
index 576869f7b7..b0598df77a 100644
--- a/crates/runtime-host/tests/fixtures/host-plugin.mjs
+++ b/crates/runtime-host/tests/fixtures/host-plugin.mjs
@@ -34,6 +34,16 @@ export default async function (ctx) {
throw new Error('model lookup invented an unconfigured default');
if (await ctx.models.resolve({ kind: 'named', connectionSlug: 'recovery', model: 'not-enabled' }))
throw new Error('disabled model is selectable');
+ const choices = await ctx.models.search({ query: 'recovery fixture-model' });
+ if (
+ !choices.complete ||
+ choices.models.length !== 1 ||
+ choices.models[0]?.model.connection_id !== model.connection_id ||
+ choices.models[0]?.isDefault
+ )
+ throw new Error('model search disagrees with selection resolution');
+ if ((await ctx.models.search({ query: 'not-enabled' })).models.length !== 0)
+ throw new Error('model search invented an available choice');
/** @type {import('../../../../packages/plugin-sdk/src/host.js').ReadDirectory | undefined} */
let preparedFiles;
diff --git a/crates/runtime-host/tests/integration/workhub_public.rs b/crates/runtime-host/tests/integration/workhub_public.rs
index 8600a312af..8895992bec 100644
--- a/crates/runtime-host/tests/integration/workhub_public.rs
+++ b/crates/runtime-host/tests/integration/workhub_public.rs
@@ -67,14 +67,34 @@ async fn scenario() {
}
});
let model = configure(&fixture, &provider.base_url).await;
- let config = maka_config::ConfigurationStore::for_root(Arc::new(fixture.owner()))
+ let configuration = maka_config::ConfigurationStore::for_root(Arc::new(fixture.owner()))
.await
.unwrap();
- let revision = config.catalog().await.unwrap().revision;
- config.set_default_target(serde_json::from_value(json!({
- "expectedCatalogRevision":revision, "target":{"connectionId":model.connection_id,"modelId":model.model}
- })).unwrap()).await.unwrap();
- config.close().await.unwrap();
+ {
+ use sha2::{Digest, Sha256};
+ configuration
+ .create_access_credential(
+ maka_config::access::AccessCredential {
+ credential_id: "workhub-viewer".into(),
+ credential_hash: format!("{:x}", Sha256::digest(b"synthetic-workhub-viewer")),
+ principal_id: "workhub-viewer".into(),
+ principal_kind: maka_runtime::access::ManagedPrincipalKind::RemoteOwner,
+ grants: vec!["plugin.remote".into()],
+ can_publish_client_capabilities: false,
+ can_use_host_paths: false,
+ created_at: "2026-09-22T00:00:00Z".into(),
+ state: maka_config::access::CredentialState::Active {
+ client_instance_id: None,
+ },
+ capability_owner: None,
+ },
+ maka_config::access::AccessCreateMode::Issue,
+ None,
+ )
+ .await
+ .unwrap();
+ }
+ configuration.close().await.unwrap();
let mut original = Value::Null;
let mut intent = Value::Null;
let mut coordinator = String::new();
@@ -103,10 +123,17 @@ async fn scenario() {
));
let stop = CancellationToken::new();
let cleanup = stop.clone().drop_guard();
+ let websocket = maka_runtime_host::server::websocket::WebSocketListener::bind(
+ "127.0.0.1:0".parse().unwrap(),
+ vec![],
+ )
+ .await
+ .unwrap();
+ let address = websocket.local_addr().unwrap();
let server = tokio::spawn(
LocalListener::bind(&endpoint)
.unwrap()
- .serve(host.clone(), stop.clone()),
+ .serve_with_websocket(websocket, host.clone(), stop.clone()),
);
let mut peer = Peer::new(host.clone(), "public-workhub-client").await;
super::javascript_plugins::ready(&mut peer).await;
@@ -145,12 +172,50 @@ async fn scenario() {
json!({"id":workspace["id"]}),
)
.await;
- let view = remote(&mut peer, &client, &document, None, "resolve", Value::Null).await;
+ let missing =
+ remote_result(&mut peer, &client, &document, None, "resolve", Value::Null).await;
+ assert_eq!(
+ missing["ok"], false,
+ "an unconfigured default must require a choice"
+ );
+ let choices = remote(
+ &mut peer,
+ &client,
+ &document,
+ None,
+ "models",
+ json!({"query":"fixture-model"}),
+ )
+ .await;
+ assert_eq!(choices["complete"], true);
+ assert_eq!(choices["models"][0]["model"], json!(model));
+ // A valid binding with unsupported thinking leaves a durable, failed
+ // creation intent. A later user choice must repair it at the same ID.
+ let rejected = remote_result(
+ &mut peer,
+ &client,
+ &document,
+ None,
+ "select-coordinator-model",
+ json!({"kind":"model","model":model,"thinkingLevel":"max"}),
+ )
+ .await;
+ assert_eq!(rejected["ok"], false);
+ let view = remote(
+ &mut peer,
+ &client,
+ &document,
+ None,
+ "select-coordinator-model",
+ json!({"kind":"model","model":model,"thinkingLevel":null}),
+ )
+ .await;
coordinator = view["sessionId"].as_str().unwrap().to_owned();
assert_ne!(coordinator, "maka_workhub_coordination");
assert_eq!(view["behavior"], "z.workhub.coordinator");
assert_eq!(view["sandboxMode"], "workspace-write");
assert_eq!(view["approvalPolicy"], json!({"kind":"on-request"}));
+ restricted_selection(address, &client, json!(model)).await;
success(peer.rpc("session.create", json!({
"sessionId":"workhub-target", "workspace":{"kind":"host_path","path":fixture.workspace},
"modelTarget":{"kind":"explicit","connectionId":model.connection_id,"connectionSlug":model.connection_slug,"model":model.model}
@@ -672,6 +737,74 @@ async fn upload(peer: &mut Peer, session: &str) -> Value {
.clone()
}
+async fn restricted_selection(address: std::net::SocketAddr, client: &Value, model: Value) {
+ use futures_util::{SinkExt, StreamExt};
+ use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest};
+ let mut request = format!("ws://{address}/runtime-host")
+ .into_client_request()
+ .unwrap();
+ request.headers_mut().insert(
+ "Authorization",
+ "Bearer synthetic-workhub-viewer".parse().unwrap(),
+ );
+ let (mut socket, _) = tokio_tungstenite::connect_async(request).await.unwrap();
+ socket
+ .send(Message::text(
+ json!({"kind":"hello", "clientInstanceId":"workhub-viewer",
+ "protocolMin":0,"protocolMax":0,"compatibilityEpoch":maka_protocol::COMPATIBILITY_EPOCH,
+ "compositionId":"maka.interactive"})
+ .to_string(),
+ ))
+ .await
+ .unwrap();
+ let hello: Value =
+ serde_json::from_str(socket.next().await.unwrap().unwrap().to_text().unwrap()).unwrap();
+ assert_eq!(hello["state"], "ready");
+ let mut document = Value::Null;
+ let mut target = Value::Null;
+ let binding = json!({"client":client,"method":"select-coordinator-model","sessionId":null});
+ for step in ["document", "bind", "call"] {
+ let input = match step {
+ "document" => json!({"kind":"open_document"}),
+ "bind" => json!({"kind":"bind","binding":binding}),
+ _ => json!({"kind":"call","binding":binding,"document":document,"target":target,
+ "input":{"kind":"model","model":model,"thinkingLevel":null}}),
+ };
+ socket
+ .send(Message::text(
+ json!({"requestId":step,"operation":"plugin.remote","input":input}).to_string(),
+ ))
+ .await
+ .unwrap();
+ let response = loop {
+ let frame: Value =
+ serde_json::from_str(socket.next().await.unwrap().unwrap().to_text().unwrap())
+ .unwrap();
+ if frame["requestId"] == step {
+ break frame;
+ }
+ };
+ match step {
+ "document" => document = success(response)["document"].clone(),
+ "bind" => target = success(response)["target"].clone(),
+ _ => {
+ assert_eq!(
+ response["ok"], false,
+ "a Remote-only principal borrowed another owner's consent"
+ );
+ assert!(
+ response["error"]["message"]
+ .as_str()
+ .unwrap()
+ .contains("plugin execution authority is retired or revoked"),
+ "{response}"
+ );
+ }
+ }
+ }
+ socket.close(None).await.unwrap();
+}
+
async fn wait_assignment(peer: &mut Peer, client: &Value, document: &Value, id: &str) {
loop {
let view = remote(
diff --git a/crates/workhub/src/coordinator.rs b/crates/workhub/src/coordinator.rs
index c67b0ef834..ba4a86db48 100644
--- a/crates/workhub/src/coordinator.rs
+++ b/crates/workhub/src/coordinator.rs
@@ -20,7 +20,7 @@
use crate::{Access, Error, Repository, invalid};
use maka_plugins::{
authorization::Target as AuthorizationTarget,
- execution::{Commands, CreateRoot, RootSettings, Target},
+ execution::{CommandError, Commands, Configure, Configured, CreateRoot, RootSettings, Target},
llm::{Models, Selection},
session::View,
};
@@ -55,6 +55,13 @@ impl Coordinator {
sandbox_mode: SandboxMode::WorkspaceWrite,
};
let commands = self.access.commands(&target).await?;
+ self.resolve_with(commands).await
+ }
+
+ async fn resolve_with(
+ &self,
+ commands: Arc<dyn Commands>,
+ ) -> Result<(View, Arc<dyn Commands>), Error> {
let intent = match self.repository.read::<Intent>(KEY).await? {
Some((_, intent)) => intent,
None => {
@@ -64,25 +71,10 @@ impl Coordinator {
.await
.map_err(invalid)?
.ok_or_else(|| invalid("WorkHub default model is unavailable"))?;
- let intent = Intent {
- request: CreateRoot {
- managed: true,
- operation_id: "coordinator".into(),
- name: "WorkHub".into(),
- settings: RootSettings {
- target: Target::Model {
- model,
- thinking_level: None,
- },
- sandbox_mode: SandboxMode::WorkspaceWrite,
- approval_policy: maka_runtime::execution::ApprovalPolicy::OnRequest,
- collaboration_mode: CollaborationMode::Agent,
- behavior: self.behavior.clone(),
- bound_tools: Some(self.tools.clone()),
- instructions: None,
- },
- },
- };
+ let intent = self.intent(Target::Model {
+ model,
+ thinking_level: None,
+ });
match self.repository.put(KEY, None, &intent).await {
Ok(()) => intent,
Err(Error::Contended) => {
@@ -96,7 +88,18 @@ impl Coordinator {
}
}
};
- let root = commands.create_root(intent.request).await?;
+ let operation = intent.request.operation_id.clone();
+ let root = match commands.restore_root(operation.clone()).await? {
+ Some(root) => root,
+ None => match commands.create_root(intent.request).await {
+ Ok(root) => root,
+ Err(CommandError::Conflict) => commands
+ .restore_root(operation)
+ .await?
+ .ok_or(Error::Conflict)?,
+ Err(error) => return Err(error.into()),
+ },
+ };
match self
.repository
.read::<String>("coordinator-session")
@@ -118,4 +121,77 @@ impl Coordinator {
let view = commands.session(root.session_id).await?;
Ok((view, commands))
}
+
+ /// A user choice can repair an uncreated intent or an already-created coordinator.
+ /// The operation identity never changes, even if an older creation wins a race.
+ pub async fn select_model(
+ &self,
+ target: Target,
+ commands: Arc<dyn Commands>,
+ ) -> Result<View, Error> {
+ let Target::Model { model, .. } = &target else {
+ return Err(invalid("The coordinator requires a model"));
+ };
+ target.validate().map_err(invalid)?;
+ let resolved = self
+ .models
+ .resolve(Selection::Named {
+ connection_slug: model.connection_slug.clone(),
+ model: model.model.clone(),
+ })
+ .await
+ .map_err(invalid)?;
+ if resolved.as_ref() != Some(model) {
+ return Err(invalid("The selected model is no longer available"));
+ }
+ // Consent must precede both durable intent and Host work.
+ commands.validate_authority().await?;
+ let previous = self.repository.read::<Intent>(KEY).await?;
+ let intent = self.intent(target.clone());
+ self.repository
+ .put(KEY, previous.map(|(revision, _)| revision), &intent)
+ .await?;
+ let (view, commands) = self.resolve_with(commands).await?;
+ // Read intent after the Session revision. A competing selection either
+ // prevents this CAS or has a newer revision to reconcile against.
+ let latest = self
+ .repository
+ .read::<Intent>(KEY)
+ .await?
+ .ok_or(Error::Conflict)?
+ .1;
+ if latest.request.settings.target != target {
+ return Err(Error::Contended);
+ }
+ match commands
+ .configure(Configure {
+ session_id: view.session_id,
+ expected_revision: view.revision,
+ target,
+ })
+ .await?
+ {
+ Configured::Committed { session } => Ok(*session),
+ Configured::RevisionConflict { .. } => Err(Error::Contended),
+ }
+ }
+
+ fn intent(&self, target: Target) -> Intent {
+ Intent {
+ request: CreateRoot {
+ managed: true,
+ operation_id: "coordinator".into(),
+ name: "WorkHub".into(),
+ settings: RootSettings {
+ target,
+ sandbox_mode: SandboxMode::WorkspaceWrite,
+ approval_policy: maka_runtime::execution::ApprovalPolicy::OnRequest,
+ collaboration_mode: CollaborationMode::Agent,
+ behavior: self.behavior.clone(),
+ bound_tools: Some(self.tools.clone()),
+ instructions: None,
+ },
+ },
+ }
+ }
}
diff --git a/crates/workhub/src/plugin/remote.rs b/crates/workhub/src/plugin/remote.rs
index 2a91502a54..229ea3ef7b 100644
--- a/crates/workhub/src/plugin/remote.rs
+++ b/crates/workhub/src/plugin/remote.rs
@@ -42,6 +42,8 @@ pub(super) fn publish(
("consent", Action::Consent),
("creation-template", Action::Template),
("resolve", Action::Resolve),
+ ("models", Action::Models),
+ ("select-coordinator-model", Action::SelectModel),
("query", Action::Query),
("candidates", Action::Candidates),
("configure-creation", Action::Creation),
@@ -78,6 +80,8 @@ enum Action {
Consent,
Template,
Resolve,
+ Models,
+ SelectModel,
Query,
Candidates,
Creation,
@@ -130,24 +134,19 @@ impl Method for Call {
struct Template {
authorization: Target,
collaboration_mode: maka_runtime::execution::CollaborationMode,
+ target: maka_plugins::execution::Target,
}
let request: Template = decode(input)?;
let Target::Workspace { sandbox_mode, .. } = &request.authorization else {
return Err(Error::Invalid("Expected a workspace".into()));
};
- let model = manager
- .coordinator
- .models
- .resolve(maka_plugins::llm::Selection::Default)
- .await
- .map_err(|e| Error::Provider(e.to_string()))?
- .ok_or_else(|| Error::Invalid("Choose a default model first".into()))?;
+ request
+ .target
+ .validate()
+ .map_err(|error| Error::Invalid(error.to_string()))?;
encode(crate::decision::Creation {
settings: maka_plugins::execution::RootSettings {
- target: maka_plugins::execution::Target::Model {
- model,
- thinking_level: None,
- },
+ target: request.target,
sandbox_mode: *sandbox_mode,
approval_policy: maka_runtime::execution::ApprovalPolicy::OnRequest,
collaboration_mode: request.collaboration_mode,
@@ -167,6 +166,48 @@ impl Method for Call {
let (view, _) = manager.coordinator.resolve().await.map_err(failure)?;
encode(view)
}
+ Action::Models => encode(
+ manager
+ .coordinator
+ .models
+ .search(decode(input)?)
+ .await
+ .map_err(|error| Error::Provider(error.to_string()))?,
+ ),
+ Action::SelectModel => {
+ let target = decode(input)?;
+ let authority = caller
+ .views
+ .authorize(Authorization {
+ operation_id: uuid::Uuid::new_v4(),
+ title: "Choose the WorkHub coordinator model".into(),
+ target: Target::PluginWorkspace {
+ sandbox_mode: maka_runtime::execution::SandboxMode::WorkspaceWrite,
+ },
+ capabilities: [Capability::Executions].into(),
+ })
+ .await?;
+ let result = async {
+ let commands = manager
+ .executions
+ .acquire(authority.scope())
+ .await
+ .map_err(command)?;
+ encode(
+ manager
+ .coordinator
+ .select_model(target, commands)
+ .await
+ .map_err(failure)?,
+ )
+ }
+ .await;
+ authority
+ .finish()
+ .await
+ .map_err(|_| Error::CleanupUnconfirmed)?;
+ result
+ }
Action::Query => {
empty(input)?;
Ok(
@@ -178,11 +219,22 @@ impl Method for Call {
encode(manager.candidates().await.map_err(failure)?)
}
Action::Creation => {
- manager
- .configure_creation(decode(input)?)
+ let creation: crate::decision::Creation = decode(input)?;
+ let authority = caller
+ .views
+ .authorize(Authorization {
+ operation_id: uuid::Uuid::new_v4(),
+ title: "Choose WorkHub task defaults".into(),
+ target: creation.authorization.clone(),
+ capabilities: [Capability::Executions].into(),
+ })
+ .await?;
+ let result = manager.configure_creation(creation).await.map_err(failure);
+ authority
+ .finish()
.await
- .map_err(failure)?;
- Ok(Value::Null)
+ .map_err(|_| Error::CleanupUnconfirmed)?;
+ result.map(|()| Value::Null)
}
Action::Decide => {
#[derive(Deserialize)]
diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.md
index 5fce80fecd..7aa2a6e928 100644
--- a/packages/plugin-sdk/README.md
+++ b/packages/plugin-sdk/README.md
@@ -121,7 +121,9 @@ Authenticated applications can also bind `plugin.remote` by `{ packageId, method
Native endpoints accepting caller-supplied Host paths declare `Endpoint::requiring_host_paths()`. Host checks that grant at both bind and call, even for a borrowed registration target. Project-ID and existing-Session queries do not require raw-path authority; plugins receive explicitly injected read-only views.
-Model selection uses `ctx.models.resolve({ kind: 'named', connectionSlug, model })`; `{ kind: 'default' }` resolves the current default. Its non-secret result grants no execution authority. `restoreChild` reopens access to an existing child using the original creation request, without creating a Session or workspace.
+`ctx.models.search({ query })` returns enabled chat choices with thinking levels, at most 50 entries / 48 KiB; refine the query when `complete` is false. `ctx.models.resolve({ kind: 'named', connectionSlug, model })` resolves an exact choice; `{ kind: 'default' }` resolves the current default. Neither grants execution authority or promises provider readiness.
+
+`restoreRoot(operationId)` recovers this package/scope's managed root under current workspace and source ceilings, independently of its original model. `restoreChild` requires the original child creation request. Neither creates anything; absence does not exclude a concurrent creation. `configure` advances the Session revision on every committed choice, including identical values, fencing older configuration CASes without changing event history.
## Model adapters
diff --git a/packages/plugin-sdk/README.zh-CN.md b/packages/plugin-sdk/README.zh-CN.md
index 41158bfa26..921bbb7a04 100644
--- a/packages/plugin-sdk/README.zh-CN.md
+++ b/packages/plugin-sdk/README.zh-CN.md
@@ -125,7 +125,9 @@ Remote 回调可以抛出携带 `RemoteFailure.code` 的 `Error`。`outcome_unkn
接受调用者 Host 路径的 Rust endpoint 声明 `Endpoint::requiring_host_paths()`。Host 在绑定和调用时都检查路径授权,借用其他连接的注册目标也不能绕过。项目 ID 和已有 Session 查询不要求原始路径权限;插件通过显式注入的只读视图访问它们。
-`ctx.models.resolve({ kind: 'named', connectionSlug, model })` 或 `ctx.models.resolve({ kind: 'default' })` 只返回可用模型的非敏感绑定,不授予执行权限。`restoreChild` 用原始创建请求恢复已有子会话的访问权,不创建会话或工作区。
+`ctx.models.search({ query })` 返回已启用的聊天模型及思考程度,每页最多 50 项/48 KiB;`complete` 为 false 时应缩小搜索范围。`ctx.models.resolve({ kind: 'named', connectionSlug, model })` 解析精确选择,`{ kind: 'default' }` 解析当前默认模型。两者均不授予执行权限,也不保证提供商当前可用。
+
+`restoreRoot(operationId)` 按当前工作区和来源上限恢复本包/作用域托管的根会话,不依赖原模型。`restoreChild` 要求原始子会话创建请求。两者均不创建资源;不存在的观察不能排除并发创建。`configure` 每次成功选择都会推进 Session revision,包括相同值,以阻止较早的配置 CAS 覆盖它,不修改事件历史。
## 模型适配器
diff --git a/packages/plugin-sdk/src/execution.ts b/packages/plugin-sdk/src/execution.ts
index 91e7d403b3..7a85673be3 100644
--- a/packages/plugin-sdk/src/execution.ts
+++ b/packages/plugin-sdk/src/execution.ts
@@ -138,10 +138,10 @@ export type ExecutionTarget =
| { kind: 'executor'; executorId: string; settings?: ExecutorSettings };
/** Selection belongs to the executor; no Host model connection is implied. */
-export interface ExecutorSettings {
+export type ExecutorSettings = {
model?: string;
thinkingLevel?: 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
-}
+};
export interface SessionConfiguration {
sessionId: string;
revision: number;
@@ -188,6 +188,7 @@ export interface Executions {
input(invocation: Invocation): Promise<MessageContent | null>;
/** Resume this exact sealed model Run; retries preserve its canonical receipt. */
resume(input: { operationId: string; source: Invocation }): Promise<Invocation>;
+ /** Every committed choice advances revision, including identical values. */
configure(input: {
sessionId: string;
expectedRevision: number;
@@ -230,6 +231,10 @@ export interface Executions {
instructions?: string | null;
};
}): Promise<{ sessionId: string }>;
+ /** Recover this package/scope's managed root under current workspace/source ceilings.
+ * Never creates or reconfigures it; null does not rule out a concurrent creation.
+ */
+ restoreRoot(operationId: string): Promise<{ sessionId: string } | null>;
/** Reads only an authorized Session, never the global catalog. */
session(sessionId: string): Promise<SessionConfiguration>;
/** Registered plugin tools/executors visible within this Session's ceiling, not a grant. */
diff --git a/packages/plugin-sdk/src/host.ts b/packages/plugin-sdk/src/host.ts
index 57070f7ca7..84565d93de 100644
--- a/packages/plugin-sdk/src/host.ts
+++ b/packages/plugin-sdk/src/host.ts
@@ -371,6 +371,10 @@ export interface HostContext {
};
/** Non-secret selection lookup; grants no model execution permission. */
readonly models: {
+ /** Enabled chat choices, not a grant or a promise of provider readiness.
+ * At most 50 entries / 48 KiB; refine the query when incomplete.
+ */
+ search(query?: { query?: string }): Promise<import('./llm.js').ModelChoices>;
resolve(
selection: { kind: 'default' } | { kind: 'named'; connectionSlug: string; model: string },
): Promise<{
diff --git a/packages/plugin-sdk/src/llm.ts b/packages/plugin-sdk/src/llm.ts
index 71a01ea0d6..70e4efef0d 100644
--- a/packages/plugin-sdk/src/llm.ts
+++ b/packages/plugin-sdk/src/llm.ts
@@ -17,6 +17,21 @@
* under the License.
*/
+export type ModelChoice = {
+ model: { connection_id: string; connection_slug: string; model: string };
+ connectionName: string;
+ displayName: string;
+ thinkingLevels: readonly NonNullable<
+ import('./execution.js').ExecutorSettings['thinkingLevel']
+ >[];
+ isDefault: boolean;
+};
+export type ModelChoices = {
+ revision: number;
+ models: readonly ModelChoice[];
+ complete: boolean;
+};
+
export interface ModelGeneration {
text: string;
modelId: string;
diff --git a/packages/workhub/src/access.tsx b/packages/workhub/src/access.tsx
index e800554fd7..8c8cc27609 100644
--- a/packages/workhub/src/access.tsx
+++ b/packages/workhub/src/access.tsx
@@ -25,6 +25,7 @@ import type {
ClientSlots,
} from '@maka-agent/plugin-sdk/client';
import type { Executions } from '@maka-agent/plugin-sdk/host';
+import { ModelSelection, type ModelTarget } from './model-selection.js';
type Target = AuthorizationRequest['target'];
type Creation = {
@@ -56,9 +57,11 @@ export function registerAccess(context: ClientContext): void {
context.slots.register('workspace.manage', 'new-work', function Workspace(props) {
const zh = props.locale !== 'en';
return (
- <ConsentButton
+ <ModelSelection
+ context={context}
+ locale={props.locale}
label={zh ? '使用此工作区创建 WorkHub 任务' : 'Create WorkHub tasks in this workspace'}
- action={async () => {
+ onSelect={async (model) => {
const target: Target = {
kind: 'workspace',
workspace: props.workspace,
@@ -73,11 +76,13 @@ export function registerAccess(context: ClientContext): void {
{
authorization: Target;
collaborationMode: ClientSlots['workspace.manage']['collaborationMode'];
+ target: ModelTarget;
},
Creation
>('creation-template')({
authorization: target,
collaborationMode: props.collaborationMode,
+ target: model,
});
await context.remote.method<Creation, null>('configure-creation')(creation);
}}
diff --git a/packages/workhub/src/client.tsx b/packages/workhub/src/client.tsx
index 06422fd2ae..83beba2e71 100644
--- a/packages/workhub/src/client.tsx
+++ b/packages/workhub/src/client.tsx
@@ -25,6 +25,7 @@ import { registerFeedback } from './feedback.js';
import { WorkHubRoot } from './surface.js';
import { coordinationCommands } from './client-session.js';
import { bindSurface } from './client-surface.js';
+import { ModelSelection, type ModelTarget } from './model-selection.js';
import styles from './styles.css';
type Resolution = { sessionId: string };
@@ -83,28 +84,55 @@ const plugin: ClientPlugin = {
};
}, [props.contextRevision, props.onResolved, props.onError, retry]);
return failed ? (
- <Button
- label={props.locale === 'en' ? 'Retry' : props.locale === 'zh-TW' ? '重試' : '重试'}
- onClick={() => {
- props.onResolving();
- void (async () => {
- const zh = props.locale !== 'en';
+ <div>
+ <Button
+ label={props.locale === 'en' ? 'Retry' : props.locale === 'zh-TW' ? '重試' : '重试'}
+ onClick={() => {
+ props.onResolving();
+ void (async () => {
+ const zh = props.locale !== 'en';
+ await authorize(
+ context,
+ { kind: 'plugin_workspace', sandboxMode: 'workspace-write' },
+ zh ? '启用 WorkHub 协调会话' : 'Enable the WorkHub coordinator',
+ );
+ await authorize(
+ context,
+ { kind: 'profile' },
+ zh ? '允许 WorkHub 发现任务' : 'Allow WorkHub to discover tasks',
+ );
+ setRetry((current) => current + 1);
+ })().catch((error: unknown) =>
+ props.onError(error instanceof Error ? error.message : String(error)),
+ );
+ }}
+ />
+ <ModelSelection
+ context={context}
+ locale={props.locale}
+ label={props.locale === 'en' ? 'Use this model' : '使用此模型'}
+ onSelect={async (target) => {
await authorize(
context,
{ kind: 'plugin_workspace', sandboxMode: 'workspace-write' },
- zh ? '启用 WorkHub 协调会话' : 'Enable the WorkHub coordinator',
+ props.locale === 'en'
+ ? 'Enable the WorkHub coordinator'
+ : '启用 WorkHub 协调会话',
);
await authorize(
context,
{ kind: 'profile' },
- zh ? '允许 WorkHub 发现任务' : 'Allow WorkHub to discover tasks',
+ props.locale === 'en'
+ ? 'Allow WorkHub to discover tasks'
+ : '允许 WorkHub 发现任务',
+ );
+ await context.remote.method<ModelTarget, Resolution>('select-coordinator-model')(
+ target,
);
setRetry((current) => current + 1);
- })().catch((error: unknown) =>
- props.onError(error instanceof Error ? error.message : String(error)),
- );
- }}
- />
+ }}
+ />
+ </div>
) : null;
},
);
diff --git a/packages/workhub/src/model-selection.tsx b/packages/workhub/src/model-selection.tsx
new file mode 100644
index 0000000000..f23b3e3e96
--- /dev/null
+++ b/packages/workhub/src/model-selection.tsx
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { useEffect, useState } from 'react';
+import { Button } from '@maka/ui/plugin';
+import type { ClientContext } from '@maka-agent/plugin-sdk/client';
+import type { ExecutionTarget, ModelChoices } from '@maka-agent/plugin-sdk/host';
+
+export type ModelTarget = Extract<ExecutionTarget, { kind: 'model' }>;
+
+export function ModelSelection({
+ context,
+ locale,
+ label,
+ onSelect,
+}: {
+ context: ClientContext;
+ locale: string;
+ label: string;
+ onSelect: (target: ModelTarget) => Promise<void>;
+}) {
+ const zh = locale !== 'en';
+ const [query, setQuery] = useState('');
+ const [choices, setChoices] = useState<ModelChoices>();
+ const [selected, setSelected] = useState('');
+ const [thinking, setThinking] = useState<{ model: string; level: string }>();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string>();
+ useEffect(() => {
+ let active = true;
+ setChoices(undefined);
+ setError(undefined);
+ const timer = setTimeout(() => {
+ void context.remote
+ .method<{ query: string }, ModelChoices>('models')({ query })
+ .then((page) => {
+ if (active) setChoices(page);
+ })
+ .catch((error: unknown) => {
+ if (active) setError(error instanceof Error ? error.message : String(error));
+ });
+ }, 150);
+ return () => {
+ active = false;
+ clearTimeout(timer);
+ };
+ }, [context, query]);
+ const key = (choice: ModelChoices['models'][number]) => JSON.stringify(choice.model);
+ const model =
+ choices?.models.find((choice) => key(choice) === selected) ??
+ choices?.models.find((choice) => choice.isDefault) ??
+ choices?.models[0];
+ const level =
+ model && thinking?.model === key(model)
+ ? model.thinkingLevels.find((level) => level === thinking.level)
+ : undefined;
+ return (
+ <div className="workhub-model-selection">
+ <label>
+ {zh ? '搜索模型' : 'Search models'}
+ <input value={query} disabled={busy} onChange={(event) => setQuery(event.target.value)} />
+ </label>
+ <label>
+ {zh ? '模型' : 'Model'}
+ <select
+ value={model ? key(model) : ''}
+ disabled={busy || !model}
+ onChange={(event) => {
+ setSelected(event.target.value);
+ setThinking(undefined);
+ }}
+ >
+ {!model ? <option value="">{zh ? '没有可用模型' : 'No models available'}</option> : null}
+ {choices?.models.map((choice) => (
+ <option key={key(choice)} value={key(choice)}>
+ {choice.connectionName} · {choice.displayName}
+ </option>
+ ))}
+ </select>
+ </label>
+ {model?.thinkingLevels.length ? (
+ <label>
+ {zh ? '思考程度' : 'Thinking'}
+ <select
+ value={level ?? ''}
+ disabled={busy}
+ onChange={(event) => setThinking({ model: key(model), level: event.target.value })}
+ >
+ <option value="">{zh ? '默认' : 'Default'}</option>
+ {model.thinkingLevels.map((level) => (
+ <option key={level} value={level}>
+ {level}
+ </option>
+ ))}
+ </select>
+ </label>
+ ) : null}
+ {choices?.complete === false ? (
+ <p>{zh ? '请缩小搜索范围以查看其他模型。' : 'Refine the search to find more models.'}</p>
+ ) : null}
+ <Button
+ label={label}
+ isDisabled={busy || !model}
+ onClick={() => {
+ if (!model) return;
+ setBusy(true);
+ setError(undefined);
+ void onSelect({ kind: 'model', model: model.model, thinkingLevel: level ?? null })
+ .catch((error: unknown) =>
+ setError(error instanceof Error ? error.message : String(error)),
+ )
+ .finally(() => setBusy(false));
+ }}
+ />
+ {error ? <p role="alert">{error}</p> : null}
+ </div>
+ );
+}
diff --git a/packages/workhub/src/styles.css b/packages/workhub/src/styles.css
index 4bb3559789..3f75e57d3a 100644
--- a/packages/workhub/src/styles.css
+++ b/packages/workhub/src/styles.css
@@ -24,6 +24,29 @@
initial-value: 0px;
}
+.workhub-model-selection {
+ display: grid;
+ gap: var(--space-3, 12px);
+ max-width: 32rem;
+ padding-block: var(--space-3, 12px);
+}
+
+.workhub-model-selection label {
+ display: grid;
+ gap: var(--space-1, 4px);
+}
+
+.workhub-model-selection input,
+.workhub-model-selection select {
+ box-sizing: border-box;
+ color: inherit;
+ background: var(--color-surface, transparent);
+ border: 1px solid var(--color-border-subtle, var(--border));
+ border-radius: var(--radius-sm, 4px);
+ padding: var(--space-2, 8px);
+ width: 100%;
+}
+
.workhub-body {
display: grid;
width: 100%;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org