use std::collections::HashMap;
use std::rc::Rc;
use std::str::FromStr;
use futures::future::LocalBoxFuture;
use perspective_js::utils::ApiError;
use serde::Deserialize;
use serde_json::{Value, json};
use wasm_bindgen::prelude::*;
use super::client::protocol::{FunctionDef, ToolDef};
use super::docs::{DocsBundle, DocsCell};
use super::sandbox::AgentSandbox;
use crate::config::{Alignment, ColumnConfigSchema, ControlSpec};
use crate::custom_elements::viewer::PerspectiveViewerElement;
use crate::queries::{
get_column_config_schema, get_plugin_config_schema, get_viewer_config, validate_expr,
};
use crate::workspace::{Panel, PanelId};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Entitlement {
ReadView,
ConfigureView,
ManageLayout,
ReadDocs,
ExecuteCode,
ReadData,
}
impl Entitlement {
pub const ALL: [Self; 6] = [
Self::ReadView,
Self::ConfigureView,
Self::ManageLayout,
Self::ReadDocs,
Self::ExecuteCode,
Self::ReadData,
];
pub fn default_set() -> Vec<Self> {
vec![
Self::ReadView,
Self::ConfigureView,
Self::ManageLayout,
Self::ReadDocs,
]
}
pub fn as_str(&self) -> &'static str {
match self {
Self::ReadView => "read_view",
Self::ConfigureView => "configure_view",
Self::ManageLayout => "manage_layout",
Self::ReadDocs => "read_docs",
Self::ExecuteCode => "execute_code",
Self::ReadData => "read_data",
}
}
}
impl FromStr for Entitlement {
type Err = String;
fn from_str(value: &str) -> Result<Self, String> {
Self::ALL
.into_iter()
.find(|x| x.as_str() == value)
.ok_or_else(|| {
let valid = Self::ALL.map(|x| x.as_str()).join(", ");
format!("Unknown entitlement `{value}` - valid entitlements: {valid}")
})
}
}
pub struct EntitlementGrant(Vec<(Entitlement, bool)>);
impl EntitlementGrant {
pub fn new(granted: &[Entitlement]) -> Self {
Self(
Entitlement::ALL
.into_iter()
.filter(|x| granted.contains(x))
.map(|x| (x, true))
.collect(),
)
}
pub fn set_enabled(&mut self, entitlement: Entitlement, enabled: bool) {
if let Some(entry) = self.0.iter_mut().find(|(x, _)| *x == entitlement) {
entry.1 = enabled;
}
}
pub fn enabled(&self) -> Vec<Entitlement> {
self.0.iter().filter(|(_, x)| *x).map(|(x, _)| *x).collect()
}
pub fn toggleable(&self) -> Vec<(Entitlement, bool)> {
self.0
.iter()
.filter(|(x, _)| !tool_names(*x).is_empty())
.copied()
.collect()
}
}
pub struct ToolCtx {
pub docs: Option<Rc<DocsCell>>,
pub bundle: Option<Rc<Result<DocsBundle, String>>>,
pub entitlements: Vec<Entitlement>,
pub sandbox: Rc<AgentSandbox>,
}
impl ToolCtx {
fn schemas(&self) -> Option<&HashMap<String, Value>> {
self.bundle
.as_ref()
.and_then(|x| x.as_ref().as_ref().ok())
.map(|x| &x.schemas)
}
}
pub struct Tool {
name: &'static str,
description: &'static str,
entitlement: Entitlement,
available: fn(&ToolCtx) -> bool,
parameters: fn(Option<&HashMap<String, Value>>) -> Value,
call: for<'a> fn(
&'a PerspectiveViewerElement,
&'a ToolCtx,
Value,
) -> LocalBoxFuture<'a, Result<Value, ToolError>>,
}
fn always(_: &ToolCtx) -> bool {
true
}
fn panel_property() -> Value {
json!({
"type": "string",
"description": "Panel id from `list_panels`; omit to target the active panel"
})
}
fn spliced_config(
schemas: Option<&HashMap<String, Value>>,
key: &str,
description: &str,
require: &[&str],
omit: &[&str],
) -> (Value, Option<Value>) {
match schemas.and_then(|x| x.get(key)) {
Some(schema) => {
let mut definitions = schema
.get("definitions")
.and_then(|x| x.as_object())
.cloned()
.unwrap_or_default();
let original = definitions.remove(key);
let mut config = original
.clone()
.unwrap_or_else(|| json!({ "type": "object" }));
if let Some(properties) = config["properties"].as_object_mut() {
for field in omit {
properties.remove(*field);
}
}
let mut required = config["required"].as_array().cloned().unwrap_or_default();
required.retain(|x| !omit.iter().any(|field| x == field));
for field in require {
if !required.iter().any(|x| x == field) {
required.push(json!(field));
}
}
if !required.is_empty() {
config["required"] = Value::Array(required);
}
config["description"] = json!(description);
if let Some(original) = original
&& serde_json::to_string(&definitions)
.unwrap_or_default()
.contains(&format!("#/definitions/{key}"))
{
definitions.insert(key.to_owned(), original);
}
let reachable = reachable_definitions(&config, &definitions);
definitions.retain(|name, _| reachable.contains(name));
let definitions = (!definitions.is_empty()).then(|| Value::Object(definitions));
(config, definitions)
},
None if require.is_empty() => (
json!({ "type": "object", "description": description }),
None,
),
None => (
json!({ "type": "object", "description": description, "required": require }),
None,
),
}
}
fn definition_refs(node: &Value, out: &mut Vec<String>) {
match node {
Value::Object(map) => {
for (key, value) in map {
match value
.as_str()
.and_then(|x| x.strip_prefix("#/definitions/"))
{
Some(name) if key == "$ref" => out.push(name.to_owned()),
_ => definition_refs(value, out),
}
}
},
Value::Array(values) => {
for value in values {
definition_refs(value, out);
}
},
_ => {},
}
}
fn reachable_definitions(
root: &Value,
definitions: &serde_json::Map<String, Value>,
) -> Vec<String> {
let mut pending = Vec::new();
definition_refs(root, &mut pending);
let mut reachable = Vec::new();
while let Some(name) = pending.pop() {
if reachable.contains(&name) {
continue;
}
if let Some(definition) = definitions.get(&name) {
definition_refs(definition, &mut pending);
}
reachable.push(name);
}
reachable
}
fn config_parameters(
schemas: Option<&HashMap<String, Value>>,
key: &str,
description: &str,
with_panel: bool,
require: &[&str],
omit: &[&str],
) -> Value {
let (config, definitions) = spliced_config(schemas, key, description, require, omit);
let mut properties = json!({ "config": config });
if with_panel {
properties["panel"] = panel_property();
}
let mut parameters = json!({
"type": "object",
"properties": properties,
"required": ["config"]
});
if let Some(definitions) = definitions {
parameters["definitions"] = definitions;
}
parameters
}
static TOOLS: &[Tool] = &[
Tool {
name: "get_schema",
description: "Get the column schema (column name -> type) and row count of the data \
currently loaded in a panel. Call this before configuring the view - column \
names must match exactly.",
entitlement: Entitlement::ReadView,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": { "panel": panel_property() }
})
},
call: |elem, ctx, args| Box::pin(elem.tool_get_schema(ctx, args)),
},
Tool {
name: "get_view_config",
description: "Get a panel's current configuration (plugin, group_by, split_by, columns, \
filter, sort, aggregates, expressions).",
entitlement: Entitlement::ReadView,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": { "panel": panel_property() }
})
},
call: |elem, ctx, args| Box::pin(elem.tool_get_view_config(ctx, args)),
},
Tool {
name: "set_view_config",
description: "Apply a partial configuration update to a panel. Only the fields provided \
are changed. Expression columns must be declared in `expressions` before \
being referenced in `columns`/`group_by`/etc. `columns` is POSITIONAL and \
every plugin reads the positions differently - call `list_plugins` for the \
active plugin's column roles and for what `group_by`/`split_by` draw in it. \
Returns the full configuration after the update is applied and rendered, \
plus `aggregation_changed_types` listing any column whose type CHANGED \
under aggregation (a `date` on the default `count` aggregate becomes an \
integer, so an axis bound to it is no longer a date axis).",
entitlement: Entitlement::ConfigureView,
available: always,
parameters: |schemas| {
config_parameters(
schemas,
"ViewerConfigUpdate",
"A partial ViewerConfigUpdate patch",
true,
&[],
&[],
)
},
call: |elem, ctx, args| Box::pin(elem.tool_set_view_config(ctx, args)),
},
Tool {
name: "list_plugins",
description: "List the visualization plugins registered with this viewer, each with the \
contract it declares: the ROLE each `columns` position fills (`columns[i]` \
fills `roles[i]`; extra columns repeat the last role), how many columns it \
requires, and what `group_by` and `split_by` draw in it. Use one of these \
exact names as the `plugin` field of set_view_config, and read its roles \
before writing `columns` - the same array means different things in \
different plugins.",
entitlement: Entitlement::ReadView,
available: always,
parameters: |_| json!({ "type": "object", "properties": {} }),
call: |elem, ctx, args| Box::pin(elem.tool_list_plugins(ctx, args)),
},
Tool {
name: "validate_expression",
description: "Validate an ExprTK expression against a panel's table without applying it. \
ExprTK examples: `\"Sales\" - \"Profit\"`, `if(\"Discount\" > 0.2, 'High', \
'Low')`, `bucket(\"Order Date\", 'M')`. Column references are \
double-quoted; string literals are single-quoted. Use this to iterate on an \
expression before committing it via set_view_config's `expressions` field.",
entitlement: Entitlement::ReadView,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The ExprTK expression to validate"
},
"panel": panel_property()
},
"required": ["expression"]
})
},
call: |elem, ctx, args| Box::pin(elem.tool_validate_expression(ctx, args)),
},
Tool {
name: "get_style_schema",
description: "Get the active plugin's DECLARED style schema: the valid `plugin_config` \
keys, and - when `column` is given - the valid `columns_config` keys for \
that column. These are value-dependent (they vary by plugin, column type \
and current state), so call this before writing `plugin_config` or \
`columns_config` via set_view_config. Plugins that declare no schema return \
null sections - keys then pass through unvalidated.",
entitlement: Entitlement::ReadView,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": {
"column": {
"type": "string",
"description": "An active column name (see get_view_config `columns`)"
},
"panel": panel_property()
}
})
},
call: |elem, ctx, args| Box::pin(elem.tool_get_style_schema(ctx, args)),
},
Tool {
name: "list_panels",
description: "List the panels (independent side-by-side views) in this viewer's dashboard \
layout, and which one is active. View tools target the active panel unless \
given a `panel` argument.",
entitlement: Entitlement::ReadView,
available: always,
parameters: |_| json!({ "type": "object", "properties": {} }),
call: |elem, ctx, args| Box::pin(elem.tool_list_panels(ctx, args)),
},
Tool {
name: "add_panel",
description: "Add a new independent panel to the dashboard layout, configured with the \
given view config - same fields as set_view_config, plus `table`, which is \
REQUIRED (a new panel must bind a data table). `columns` is also REQUIRED: \
omitting it would display every column in the table. Compose the panel's \
COMPLETE configuration (plugin, columns, group_by, expressions, ...) in \
this one call. Returns the new panel's id and resulting configuration. To \
duplicate an existing panel, pass a config obtained from get_view_config. \
`columns` is POSITIONAL - see `list_plugins` for the chosen plugin's roles.",
entitlement: Entitlement::ManageLayout,
available: always,
parameters: |schemas| {
config_parameters(
schemas,
"ViewerConfigInitial",
"The new panel's ViewerConfigInitial (`table` and `columns` required)",
false,
&["table", "columns"],
&[],
)
},
call: |elem, ctx, args| Box::pin(elem.tool_add_panel(ctx, args)),
},
Tool {
name: "remove_panel",
description: "Remove a panel by id, disposing its view. Removing every panel leaves an \
empty viewer.",
entitlement: Entitlement::ManageLayout,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": {
"panel": {
"type": "string",
"description": "Panel id from `list_panels`"
}
},
"required": ["panel"]
})
},
call: |elem, ctx, args| Box::pin(elem.tool_remove_panel(ctx, args)),
},
Tool {
name: "activate_panel",
description: "Make a panel active: the target of the settings sidebar and of view tools \
called without a `panel` argument.",
entitlement: Entitlement::ManageLayout,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": {
"panel": {
"type": "string",
"description": "Panel id from `list_panels`"
}
},
"required": ["panel"]
})
},
call: |elem, ctx, args| Box::pin(elem.tool_activate_panel(ctx, args)),
},
Tool {
name: "get_workspace",
description: "Get the dashboard's workspace state: the `layout` tree arranging the \
panels, each panel's `title`, `plugin` and `table`, the active panel, and \
the element-level `derived_tables`, `masters`, `global_filters` and \
`palette`. Call this before `set_workspace` - its `layout` must name every \
panel id listed here.",
entitlement: Entitlement::ReadView,
available: always,
parameters: |_| json!({ "type": "object", "properties": {} }),
call: |elem, ctx, args| Box::pin(elem.tool_get_workspace(ctx, args)),
},
Tool {
name: "set_workspace",
description: "Apply a field-wise update to the dashboard's workspace state; absent fields \
are unchanged and `null` resets. `layout` arranges the panels into a grid: \
nested `split-layout`s (`orientation` `horizontal` = side by side, \
`vertical` = stacked; `sizes` are fractions summing to 1, one per child) \
whose leaves are `tab-layout` stacks of panel ids, naming EVERY panel \
exactly once. `derived_tables` is the COMPLETE set of derived tables (keep \
existing entries), each a pivoted/filtered view of `table` that panels can \
then bind by name via add_panel. `masters` are panels whose row selection \
cross-filters the others through `global_filters`. Panels themselves are \
created and removed with add_panel / remove_panel. Returns the workspace \
state after the update.",
entitlement: Entitlement::ManageLayout,
available: always,
parameters: |schemas| {
config_parameters(
schemas,
"WorkspaceConfigUpdate",
"A partial WorkspaceConfigUpdate (`panels` excluded)",
false,
&[],
&["panels"],
)
},
call: |elem, ctx, args| Box::pin(elem.tool_set_workspace(ctx, args)),
},
Tool {
name: "search_docs",
description: "Search the reference documentation: Perspective features, configuration \
fields, expression syntax, plugin capabilities, and any host-supplied data \
definitions. Queries are keyword-matched - prefer concrete terms (e.g. \
`expressions bucket date`, not full sentences), and re-query with different \
keywords if the results look irrelevant.",
entitlement: Entitlement::ReadDocs,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Keyword search query"
},
"limit": {
"type": "integer",
"description": "Maximum results (default 4)"
}
},
"required": ["query"]
})
},
call: |elem, ctx, args| Box::pin(elem.tool_search_docs(ctx, args)),
},
Tool {
name: "run_script",
description: "Run a JavaScript ES module in an isolated sandbox to create (or replace) \
the hosted table `name` from external data: fetch or poll an HTTP API, open \
a WebSocket, or `import()` a client library from a CDN such as esm.sh. The \
source is a whole module, NOT a function body: never `return` data (a \
top-level `return` is a syntax error). Instead the module loads rows by \
calling the global `psp.emit(data)` with an array of row objects, an object \
of column arrays, a CSV string, or Arrow IPC bytes \
(`ArrayBuffer`/`Uint8Array`). The first emit creates the table and infers \
its column types; later emits append rows (or upsert by the table's \
`index`), and `psp.emit(data, {replace: true})` swaps the entire contents - \
use it to re-emit a polled snapshot that has no key column. Keep the table \
live with `setInterval` or an open socket. `psp.log(...)` and `console.log` \
lines are returned to you. The module runs in a Web Worker with a `null` \
origin: there is NO DOM (`document`, `window` and `DOMParser` do not exist \
- import an HTML parser from a CDN to read HTML), no access to this page, \
and `fetch` only reaches servers whose CORS headers allow any origin. Once \
the first emit has loaded, this tool's result reports the table's schema \
and row count; if the module throws, or emits nothing within \
`start_timeout_ms`, the result is an error with the script log. Display the \
table with `add_panel` using `table: name`. Re-running an existing `name` \
stops its script and replaces its table.",
entitlement: Entitlement::ExecuteCode,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the table to create; also identifies the script"
},
"source": {
"type": "string",
"description": "The complete ES module source, NOT a function body. Top-level `await` and `import` work and `psp` is a global. Never `return` data - pass it to `psp.emit()`. Example: `const json = await (await fetch(\"https://example.com/data.json\")).json(); psp.emit(json.items.map((x) => ({ name: x.name, value: x.value })));`"
},
"table": {
"type": "object",
"description": "Table options: `index` (a column name, or a list of names, keying rows so re-emitted rows update in place) and `limit` (maximum rows kept, oldest dropped first)",
"properties": {
"index": {
"anyOf": [
{ "type": "string" },
{ "type": "array", "items": { "type": "string" } }
]
},
"limit": { "type": "integer" }
}
},
"start_timeout_ms": {
"type": "integer",
"description": "Milliseconds to wait for the first emit (default 30000, max 120000)"
}
},
"required": ["name", "source"]
})
},
call: |elem, ctx, args| Box::pin(elem.tool_run_script(ctx, args)),
},
Tool {
name: "list_scripts",
description: "List the scripts started by `run_script`, each with its table name, status \
(`running` = the module body is still executing; `finished` = the module \
body completed, but timers and sockets it opened keep updating its table; \
`stopped`), table schema and row count, emit count, last error and recent \
log lines.",
entitlement: Entitlement::ExecuteCode,
available: always,
parameters: |_| json!({ "type": "object", "properties": {} }),
call: |elem, ctx, args| Box::pin(elem.tool_list_scripts(ctx, args)),
},
Tool {
name: "stop_script",
description: "Stop a script started by `run_script`. Its table keeps the rows already \
loaded unless `drop_table` is true; dropping fails while a panel still \
displays the table, so remove those panels first.",
entitlement: Entitlement::ExecuteCode,
available: always,
parameters: |_| {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The script's table name"
},
"drop_table": {
"type": "boolean",
"description": "Also delete the script's table (default false)"
}
},
"required": ["name"]
})
},
call: |elem, ctx, args| Box::pin(elem.tool_stop_script(ctx, args)),
},
];
fn granted(tool: &Tool, ctx: &ToolCtx) -> bool {
ctx.entitlements.contains(&tool.entitlement) && (tool.available)(ctx)
}
pub fn tool_names(entitlement: Entitlement) -> Vec<&'static str> {
TOOLS
.iter()
.filter(|x| x.entitlement == entitlement)
.map(|x| x.name)
.collect()
}
pub fn tool_definitions(ctx: &ToolCtx) -> Vec<ToolDef> {
TOOLS
.iter()
.filter(|x| granted(x, ctx))
.map(|x| ToolDef {
kind: "function",
function: FunctionDef {
name: x.name,
description: x.description,
parameters: (x.parameters)(ctx.schemas()),
},
})
.collect()
}
pub async fn tool_dispatch(
elem: &PerspectiveViewerElement,
ctx: &ToolCtx,
name: &str,
arguments: &str,
) -> Result<Value, ToolError> {
let tool = TOOLS
.iter()
.find(|x| x.name == name && granted(x, ctx))
.ok_or_else(|| ToolError(format!("Unknown tool `{name}`")))?;
let args: Value = if arguments.trim().is_empty() {
json!({})
} else {
serde_json::from_str(arguments)?
};
elem.agent_emit(name, &args);
let result = (tool.call)(elem, ctx, args).await;
if let Err(err) = &result {
elem.agent_emit_error(&format!("{err}"));
}
result
}
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct ToolError(String);
fn retyped_columns(
session: &crate::session::Session,
config: &crate::config::ViewerConfig<String, String>,
) -> Vec<Value> {
let metadata = session.metadata();
config
.view_config
.columns
.iter()
.flatten()
.filter_map(|name| {
let view_type = metadata.get_column_view_type(name)?;
let table_type = metadata.get_column_table_type(name)?;
if view_type == table_type {
return None;
}
Some(json!({
"name": name,
"type": view_type,
"source_type": table_type,
"aggregate": config.view_config.aggregates.get(name),
}))
})
.collect()
}
fn with_docs_hint(ctx: &ToolCtx, err: ToolError) -> ToolError {
if ctx.docs.is_some() {
ToolError(format!(
"{} If a field or value was rejected, its reference documentation is available - call \
`search_docs` with the failing field or function name.",
err.0
))
} else {
err
}
}
impl From<ApiError> for ToolError {
fn from(err: ApiError) -> Self {
Self(format!("{err}"))
}
}
impl From<serde_json::Error> for ToolError {
fn from(err: serde_json::Error) -> Self {
Self(format!("{err}"))
}
}
impl From<JsValue> for ToolError {
fn from(err: JsValue) -> Self {
Self(
err.as_string()
.or_else(|| {
js_sys::Reflect::get(&err, &JsValue::from_str("message"))
.ok()
.and_then(|x| x.as_string())
})
.unwrap_or_else(|| format!("{err:?}")),
)
}
}
#[derive(Deserialize)]
struct PanelArgs {
panel: Option<String>,
}
#[derive(Deserialize)]
struct SetViewConfigArgs {
config: Value,
panel: Option<String>,
}
#[derive(Deserialize)]
struct ValidateExpressionArgs {
expression: String,
panel: Option<String>,
}
#[derive(Deserialize)]
struct AddPanelArgs {
config: Value,
}
#[derive(Deserialize)]
struct PanelNameArgs {
panel: String,
}
#[derive(Deserialize)]
struct SetWorkspaceArgs {
config: serde_json::Map<String, Value>,
}
#[derive(Deserialize)]
struct SearchDocsArgs {
query: String,
limit: Option<usize>,
}
#[derive(Deserialize)]
struct RunScriptArgs {
name: String,
source: String,
table: Option<Value>,
start_timeout_ms: Option<u32>,
}
#[derive(Deserialize)]
struct StopScriptArgs {
name: String,
#[serde(default)]
drop_table: bool,
}
#[derive(Deserialize)]
struct StyleSchemaArgs {
column: Option<String>,
panel: Option<String>,
}
fn control_schema_entries(spec: &ControlSpec) -> Vec<(String, Value)> {
match spec {
ControlSpec::Enum {
key,
variants,
default,
} => vec![(
key.clone(),
json!({
"type": "string",
"enum": variants.iter().map(|x| x.value.clone()).collect::<Vec<_>>(),
"default": default
}),
)],
ControlSpec::Bool { key, default } => vec![(
key.clone(),
json!({ "type": "boolean", "default": default }),
)],
ControlSpec::Number {
key,
default,
min,
max,
..
} => {
let mut node = json!({ "type": "number", "default": default });
if let Some(min) = min {
node["minimum"] = json!(min);
}
if let Some(max) = max {
node["maximum"] = json!(max);
}
vec![(key.clone(), node)]
},
ControlSpec::String { key, default, .. } => {
vec![(key.clone(), json!({ "type": "string", "default": default }))]
},
ControlSpec::Font {
key,
default,
size,
bold,
italic,
} => {
let mut out = vec![(
key.clone(),
json!({
"type": "string",
"description": "A CSS font family: a generic keyword (`inherit`, `monospace`, `sans-serif`, `serif`, `system-ui`) or an installed font name",
"default": default,
}),
)];
if let Some(size) = size {
let mut node = json!({
"type": "number",
"description": "Font size in CSS pixels",
"default": size.default,
});
if let Some(min) = size.min {
node["minimum"] = json!(min);
}
if let Some(max) = size.max {
node["maximum"] = json!(max);
}
out.push((size.key.clone(), node));
}
for (toggle, description) in [(bold, "Bold text"), (italic, "Italic text")] {
if let Some(toggle) = toggle {
out.push((
toggle.key.clone(),
json!({ "type": "boolean", "description": description, "default": toggle.default }),
));
}
}
out
},
ControlSpec::Alignment {
key,
default,
corners,
} => {
let cells: &[Alignment] = if *corners {
&Alignment::CORNERS
} else {
&Alignment::ALL
};
let mut node = json!({
"type": "string",
"enum": cells.iter().map(|x| x.as_str()).collect::<Vec<_>>(),
"description": if *corners {
"Anchor corner of a 3×3 grid: `top-left`, `top-right`, `bottom-left` or `bottom-right`"
} else {
"Anchor cell of a 3×3 grid: a corner `top-left|top-right|bottom-left|bottom-right`, an edge `top|left|right|bottom`, or `center`"
},
});
if let Some(default) = default {
node["default"] = json!(default.as_str());
}
vec![(key.clone(), node)]
},
ControlSpec::Color { key, default } => vec![(
key.clone(),
json!({
"type": "string",
"description": "A CSS color (`#rrggbb`, `rgb()`), or a host-defined named color `var(--psp-user--color-<name>)`",
"default": default,
}),
)],
ControlSpec::Palette { key, default, max } => {
let mut description = "Ordered discrete color palette, cycled over the column's \
categories/series: a CSS `linear-gradient(to right, #rrggbb, \
#rrggbb, …)` of N colors WITHOUT positions, or a host-defined \
named palette `var(--psp-user--palette-<name>)`"
.to_owned();
if let Some(max) = max {
description.push_str(&format!(" (at most {max} colors)"));
}
vec![(
key.clone(),
json!({
"type": "string",
"description": description,
"default": default,
}),
)]
},
ControlSpec::GradientStops {
key,
default,
discrete,
} => {
let mut description = "Multi-stop color gradient: a CSS `linear-gradient(to right, \
#rrggbb P%, …)` with positioned stops (direction normalized to \
`to right`; stops[0] maps to the most negative value), or a \
host-defined named gradient `var(--psp-user--gradient-<name>)`"
.to_owned();
if *discrete {
description.push_str(" — exactly 2 stops (the negative and positive colors)");
}
vec![(
key.clone(),
json!({
"type": "string",
"description": description,
"default": default,
}),
)]
},
ControlSpec::DatetimeFormat { .. } => vec![(
"date_format".to_owned(),
json!({ "description": "Datetime display format, a subset of `Intl.DateTimeFormatOptions`: either `dateStyle`/`timeStyle` presets or per-part fields (`weekday`, `year`, `month`, `day`, `hour`, `minute`, `second`, `fractionalSecondDigits`), never both, plus optional `timeZone` and `hour12`; a missing display field is not shown" }),
)],
ControlSpec::NumberSeriesStyle { .. } => vec![
(
"chart_type".to_owned(),
json!({ "type": "string", "description": "Per-series glyph override" }),
),
(
"stack".to_owned(),
json!({ "description": "Series stack group" }),
),
],
ControlSpec::Symbols { .. } => vec![(
"symbols".to_owned(),
json!({ "type": "object", "description": "Map of column values to symbol names" }),
)],
ControlSpec::NumberFormat { .. } => vec![(
"number_format".to_owned(),
json!({ "type": "object", "description": "Intl.NumberFormat-style options" }),
)],
ControlSpec::AggregateDepth => vec![(
"aggregate_depth".to_owned(),
json!({ "type": "integer", "description": "Group-by rollup depth override" }),
)],
ControlSpec::Group { fields, .. } => {
fields.iter().flat_map(control_schema_entries).collect()
},
}
}
fn schema_object(schema: &ColumnConfigSchema) -> Value {
let mut properties = serde_json::Map::new();
for spec in &schema.fields {
for (key, node) in control_schema_entries(spec) {
properties.insert(key, node);
}
}
json!({ "type": "object", "properties": properties })
}
const SEARCH_DOCS_LIMIT: usize = 4;
const SCRIPT_START_TIMEOUT_MS: u32 = 30_000;
const SCRIPT_START_TIMEOUT_MAX_MS: u32 = 120_000;
fn script_error_hint(message: &str) -> Option<&'static str> {
const TOP_LEVEL_RETURN: [&str; 3] = [
"Illegal return statement",
"return not in function",
"Return statements are only valid inside functions",
];
TOP_LEVEL_RETURN
.iter()
.any(|x| message.contains(x))
.then_some(
"`source` is an ES module, not a function body, so it cannot `return`. Remove the \
`return` and pass the rows to `psp.emit(rows)` instead; top-level `await` works \
without a wrapper function.",
)
}
fn with_script_log(message: String, log: &[String]) -> ToolError {
if log.is_empty() {
ToolError(message)
} else {
ToolError(format!(
"{message}\nScript log (oldest first):\n{}",
log.join("\n")
))
}
}
fn workspace_rollback(snapshot: &Value, update: &serde_json::Map<String, Value>) -> Value {
let mut rollback = serde_json::Map::new();
for key in update.keys() {
let saved = snapshot.get(key).filter(|x| !x.is_null()).cloned();
let value = match key.as_str() {
"layout" => saved,
"derived_tables" => Some(saved.unwrap_or_else(|| json!({}))),
"active" | "masters" | "global_filters" | "palette" => {
Some(saved.unwrap_or(Value::Null))
},
_ => None,
};
if let Some(value) = value {
rollback.insert(key.clone(), value);
}
}
Value::Object(rollback)
}
impl PerspectiveViewerElement {
fn agent_panel(&self, target: Option<&str>) -> Result<Panel, ToolError> {
let id = target.map(|x| PanelId::from(x.to_owned()));
self.workspace
.panel_or_active(id.as_ref())
.ok_or_else(|| match target {
Some(name) => ToolError(format!(
"Unknown panel `{name}` - current panels: {:?}",
self.agent_panel_names()
)),
None => ToolError("No panel - the viewer has no data loaded yet".to_owned()),
})
}
fn agent_panel_names(&self) -> Vec<String> {
self.workspace
.panel_ids()
.iter()
.map(|x| x.as_str().to_owned())
.collect()
}
fn agent_active_name(&self) -> Option<String> {
self.workspace.active_id().map(|x| x.as_str().to_owned())
}
fn agent_emit_error(&self, message: &str) {
self.presentation.agent.record_tool_error(message);
}
fn agent_emit(&self, name: &str, args: &Value) {
self.presentation.agent.record_tool(name, args);
let detail: JsValue = json!({ "name": name, "args": args }).to_string().into();
let event_init = web_sys::CustomEventInit::new();
event_init.set_bubbles(true);
event_init.set_detail(&detail);
if let Ok(event) =
web_sys::CustomEvent::new_with_event_init_dict("perspective-agent-tool", &event_init)
{
let _ = self.elem.dispatch_event(&event);
}
}
async fn tool_get_schema(&self, _ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: PanelArgs = serde_json::from_value(args)?;
let panel = self.agent_panel(args.panel.as_deref())?;
let table = panel
.session
.get_table()
.ok_or_else(|| ToolError("No table loaded".to_owned()))?;
let schema = table.schema().await.map_err(ApiError::from)?;
let size = table.size().await.map_err(ApiError::from)?;
Ok(json!({
"table": table.get_name(),
"columns": serde_json::to_value(&schema)?,
"num_rows": size,
}))
}
async fn tool_get_view_config(&self, _ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: PanelArgs = serde_json::from_value(args)?;
let panel = self.agent_panel(args.panel.as_deref())?;
let config = get_viewer_config(&panel.session, &panel.renderer, &self.presentation).await?;
Ok(serde_json::to_value(&config)?)
}
async fn tool_set_view_config(&self, ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: SetViewConfigArgs = serde_json::from_value(args)?;
let target = args.panel.as_deref();
self.agent_panel(target)?;
if let Err(err) = self.agent_restore(target, &args.config).await {
return Err(with_docs_hint(ctx, err));
}
let panel = self.agent_panel(target)?;
let config = get_viewer_config(&panel.session, &panel.renderer, &self.presentation).await?;
let mut result = serde_json::to_value(&config)?;
let retyped = retyped_columns(&panel.session, &config);
if !retyped.is_empty() {
result["aggregation_changed_types"] = json!(retyped);
}
Ok(result)
}
async fn agent_restore(&self, target: Option<&str>, config: &Value) -> Result<(), ToolError> {
let options = js_sys::Object::new();
js_sys::Reflect::set(
&options,
&JsValue::from_str("suppress_errors"),
&JsValue::TRUE,
)?;
if let Some(name) = target {
js_sys::Reflect::set(
&options,
&JsValue::from_str("panel"),
&JsValue::from_str(name),
)?;
}
let js_config = js_sys::JSON::parse(&config.to_string())?;
let restored = self.restore(js_config.unchecked_into(), Some(options.unchecked_into()));
let promise: js_sys::Promise = JsValue::from(restored).unchecked_into();
wasm_bindgen_futures::JsFuture::from(promise).await?;
Ok(())
}
async fn tool_list_plugins(&self, _ctx: &ToolCtx, _args: Value) -> Result<Value, ToolError> {
let panel = self.agent_panel(None)?;
let plugins = panel
.renderer
.get_all_plugin_configs()
.iter()
.map(|config| {
let mut value = json!({
"name": config.name,
"category": config.category,
"columns": {
"roles": config.config_column_names,
"required": config.min_config_columns.unwrap_or(1),
"extra_columns": config.tail_column_role(),
},
"ordering": if config.connects_row_order {
json!("connects points in row order - `sort` by the \
X-axis column unless the table already \
arrives ordered")
} else {
Value::Null
},
"select_mode": match config.select_mode {
crate::config::ColumnSelectMode::Select => "select",
crate::config::ColumnSelectMode::Toggle => "toggle",
},
"supports_column_styles": config.can_render_column_styles,
});
if let Some(max) = config.max_columns {
value["columns"]["max"] = json!(max);
}
value["group_by"] = match &config.group_by_role {
Some(role) => json!(role),
None => json!("aggregates rows; no visual role"),
};
value["split_by"] = match &config.split_by_role {
Some(role) => json!(role),
None => json!("aggregates rows; no visual role"),
};
value
})
.collect::<Vec<_>>();
Ok(json!({
"plugins": plugins,
"columns_are_positional": "`columns[i]` fills the role at `roles[i]`; columns past the last named role repeat `extra_columns`.",
}))
}
async fn tool_validate_expression(
&self,
ctx: &ToolCtx,
args: Value,
) -> Result<Value, ToolError> {
let args: ValidateExpressionArgs = serde_json::from_value(args)?;
let panel = self.agent_panel(args.panel.as_deref())?;
match validate_expr(&panel.session, &args.expression).await? {
None => Ok(json!({ "valid": true })),
Some(err) => {
let mut result = json!({
"valid": false,
"error": err.error_message,
"line": err.line,
"column": err.column,
});
if ctx.docs.is_some() {
result["hint"] = json!(
"ExprTK syntax and functions are documented - call `search_docs` with the \
function name or feature, e.g. `expressions bucket`."
);
}
Ok(result)
},
}
}
async fn tool_list_panels(&self, _ctx: &ToolCtx, _args: Value) -> Result<Value, ToolError> {
Ok(json!({
"panels": self.agent_panel_names(),
"active": self.agent_active_name(),
}))
}
async fn tool_add_panel(&self, ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: AddPanelArgs = serde_json::from_value(args)?;
if let Err(err) =
serde_json::from_value::<crate::config::ViewerConfigInitial>(args.config.clone())
{
let mut message = format!("Invalid panel config: {err}");
if message.contains("table")
&& let Some(names) = self.agent_hosted_table_names().await
{
message.push_str(&format!(" - available tables: {names:?}"));
}
return Err(with_docs_hint(ctx, ToolError(message)));
}
match args.config.get("columns") {
Some(Value::Array(columns)) if !columns.is_empty() => {},
_ => {
return Err(ToolError(
"Invalid panel config: a new panel requires a non-empty `columns` list \
(omitting it would display every column in the table). Choose the columns - \
including any `expressions` names - this panel should display."
.to_owned(),
));
},
}
let before = self.agent_panel_names();
let js_config = js_sys::JSON::parse(&args.config.to_string())?;
let added = self.addPanel(js_config.unchecked_into(), None);
let result = wasm_bindgen_futures::JsFuture::from(js_sys::Promise::from(added)).await;
let id = match result {
Ok(id) => id
.as_string()
.ok_or_else(|| ToolError("addPanel returned no id".to_owned()))?,
Err(err) => {
for name in self.agent_panel_names() {
if !before.contains(&name) {
let removed = self.removePanel(name);
let _ =
wasm_bindgen_futures::JsFuture::from(js_sys::Promise::from(removed))
.await;
}
}
return Err(with_docs_hint(ctx, ToolError::from(err)));
},
};
let panel = self.agent_panel(Some(&id))?;
let config = get_viewer_config(&panel.session, &panel.renderer, &self.presentation).await?;
let mut result = json!({
"panel": id,
"config": serde_json::to_value(&config)?,
});
let retyped = retyped_columns(&panel.session, &config);
if !retyped.is_empty() {
result["aggregation_changed_types"] = json!(retyped);
}
Ok(result)
}
async fn agent_hosted_table_names(&self) -> Option<Vec<String>> {
let panel = self.agent_panel(None).ok()?;
let client = panel.session.get_client()?;
client.get_hosted_table_names().await.ok()
}
async fn tool_get_workspace(&self, _ctx: &ToolCtx, _args: Value) -> Result<Value, ToolError> {
let token = self.agent_save_workspace().await?;
Ok(self.agent_workspace_summary(&token))
}
async fn tool_set_workspace(&self, ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: SetWorkspaceArgs = serde_json::from_value(args)?;
if args.config.contains_key("panels") {
return Err(ToolError(
"`panels` cannot be set with set_workspace - create, configure and remove panels \
with `add_panel`, `set_view_config` and `remove_panel`, then arrange them with \
`layout`."
.to_owned(),
));
}
if let Some(layout) = args.config.get("layout").filter(|x| !x.is_null()) {
let layout: crate::js::Layout = serde_json::from_value(layout.clone())?;
let ids = self
.workspace
.panel_ids()
.iter()
.map(|id| id.as_str().to_owned())
.collect::<Vec<_>>();
let unplaced = layout.validate(&ids).map_err(ToolError)?;
if !unplaced.is_empty() {
return Err(ToolError(format!(
"Invalid layout: panels {unplaced:?} are missing - name every panel, or \
remove it first with `remove_panel`"
)));
}
}
let snapshot = self.agent_save_workspace().await?;
if let Some(derived) = args.config.get("derived_tables") {
self.agent_check_derived(&snapshot, derived).await?;
}
let update = Value::Object(args.config.clone());
if let Err(err) = self.agent_restore_workspace(&update).await {
let rollback = workspace_rollback(&snapshot, &args.config);
if let Err(rollback_err) = self.agent_restore_workspace(&rollback).await {
return Err(ToolError(format!(
"{err} (restoring the previous workspace also failed: {rollback_err})"
)));
}
return Err(with_docs_hint(ctx, err));
}
let token = self.agent_save_workspace().await?;
Ok(self.agent_workspace_summary(&token))
}
async fn agent_check_derived(
&self,
snapshot: &Value,
derived: &Value,
) -> Result<(), ToolError> {
let Some(derived) = derived.as_object() else {
return Ok(());
};
let current = snapshot["derived_tables"]
.as_object()
.map(|x| x.keys().cloned().collect::<Vec<_>>())
.unwrap_or_default();
let mut dropped = snapshot["panels"]
.as_object()
.into_iter()
.flat_map(|panels| panels.values())
.filter_map(|config| config["table"].as_str())
.filter(|table| current.iter().any(|x| x == table) && !derived.contains_key(*table))
.map(str::to_owned)
.collect::<Vec<_>>();
dropped.sort();
dropped.dedup();
if !dropped.is_empty() {
return Err(ToolError(format!(
"`derived_tables` is the COMPLETE set of derived tables, not a patch: {dropped:?} \
are read by panels and must stay in it (current derived tables: {current:?})"
)));
}
let Some(hosted) = self.agent_hosted_table_names().await else {
return Ok(());
};
let loaded = hosted
.into_iter()
.filter(|x| !current.contains(x))
.collect::<Vec<_>>();
for (name, config) in derived {
let Some(parent) = config["table"].as_str() else {
continue;
};
if !derived.contains_key(parent) && !loaded.iter().any(|x| x == parent) {
return Err(ToolError(format!(
"Derived table `{name}` reads unknown table `{parent}` - its `table` must be \
a loaded table or another entry in `derived_tables` (loaded tables: \
{loaded:?})"
)));
}
}
Ok(())
}
fn agent_workspace_summary(&self, token: &Value) -> Value {
let panels = token["panels"]
.as_object()
.into_iter()
.flatten()
.map(|(id, config)| {
(
id.clone(),
json!({
"title": config["title"],
"plugin": config["plugin"],
"table": config["table"],
}),
)
})
.collect::<serde_json::Map<_, _>>();
let or = |key: &str, default: Value| {
token
.get(key)
.filter(|x| !x.is_null())
.cloned()
.unwrap_or(default)
};
json!({
"active": self.agent_active_name(),
"layout": token["layout"],
"panels": panels,
"derived_tables": or("derived_tables", json!({})),
"masters": or("masters", json!([])),
"global_filters": or("global_filters", json!([])),
"palette": or("palette", json!({})),
})
}
async fn agent_save_workspace(&self) -> Result<Value, ToolError> {
let options = js_sys::Object::new();
js_sys::Reflect::set(&options, &JsValue::from_str("full_palette"), &JsValue::TRUE)?;
let saved = self.saveWorkspace(Some(options.unchecked_into()));
let promise: js_sys::Promise = JsValue::from(saved).unchecked_into();
let token = wasm_bindgen_futures::JsFuture::from(promise).await?;
let json = String::from(js_sys::JSON::stringify(&token)?);
Ok(serde_json::from_str(&json)?)
}
async fn agent_restore_workspace(&self, update: &Value) -> Result<(), ToolError> {
let js_update = js_sys::JSON::parse(&update.to_string())?;
let restored = self.restoreWorkspace(js_update.unchecked_into(), None);
let promise: js_sys::Promise = JsValue::from(restored).unchecked_into();
wasm_bindgen_futures::JsFuture::from(promise).await?;
Ok(())
}
async fn tool_remove_panel(&self, _ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: PanelNameArgs = serde_json::from_value(args)?;
self.agent_panel(Some(&args.panel))?;
let removed = self.removePanel(args.panel);
wasm_bindgen_futures::JsFuture::from(js_sys::Promise::from(removed)).await?;
Ok(json!({
"panels": self.agent_panel_names(),
"active": self.agent_active_name(),
}))
}
async fn tool_activate_panel(&self, _ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: PanelNameArgs = serde_json::from_value(args)?;
self.agent_panel(Some(&args.panel))?;
let activated = self.setActivePanel(args.panel);
wasm_bindgen_futures::JsFuture::from(js_sys::Promise::from(activated)).await?;
Ok(json!({ "active": self.agent_active_name() }))
}
async fn tool_get_style_schema(&self, _ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: StyleSchemaArgs = serde_json::from_value(args)?;
let panel = self.agent_panel(args.panel.as_deref())?;
let viewer_config =
get_viewer_config(&panel.session, &panel.renderer, &self.presentation).await?;
let columns_config = serde_json::to_value(&viewer_config.columns_config)?;
let plugin_schema = {
let view_config = panel.session.get_view_config();
get_plugin_config_schema(
&panel.renderer,
&view_config,
Some(&viewer_config.panel.plugin_config),
)
.ok()
};
let column_schema = match &args.column {
None => None,
Some(column) => {
let metadata = panel.session.metadata();
if metadata.get_column_view_type(column).is_none() {
let view_config = panel.session.get_view_config();
let active = view_config
.columns
.iter()
.flatten()
.cloned()
.collect::<Vec<_>>();
return Err(ToolError(format!(
"Unknown or inactive column `{column}` - active columns: {active:?}"
)));
}
let current = columns_config.get(column).and_then(|x| x.as_object());
let view_config = panel.session.get_view_config();
Some(
get_column_config_schema(
&panel.renderer,
&view_config,
&panel.session,
column,
current,
)
.ok(),
)
},
};
let mut out = json!({
"plugin": viewer_config.plugin,
"plugin_config": plugin_schema.as_ref().map(schema_object),
});
if let Some(column) = &args.column {
out["column"] = json!(column);
out["column_config"] = json!(column_schema.flatten().as_ref().map(schema_object));
}
if out["plugin_config"].is_null() && out["column_config"].is_null() {
out["note"] = json!(
"The active plugin declares no style schema; `plugin_config` and `columns_config` \
keys pass through unvalidated."
);
}
Ok(out)
}
async fn tool_search_docs(&self, ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: SearchDocsArgs = serde_json::from_value(args)?;
let Some(bundle) = ctx.bundle.as_ref() else {
return Ok(json!({
"results": [],
"hint": "No documentation is configured for this viewer",
}));
};
match bundle.as_ref() {
Err(err) => Err(ToolError(format!("Docs failed to load: {err}"))),
Ok(bundle) => {
let results = bundle
.index
.search(&args.query, args.limit.unwrap_or(SEARCH_DOCS_LIMIT))
.iter()
.map(|chunk| {
json!({
"title": chunk.title,
"path": chunk.path,
"text": chunk.text,
})
})
.collect::<Vec<_>>();
if results.is_empty() {
Ok(json!({
"results": [],
"hint": "No matches - retry with different, more specific keywords",
}))
} else {
Ok(json!({ "results": results }))
}
},
}
}
fn agent_client(&self) -> Result<perspective_client::Client, ToolError> {
self.workspace
.default_client()
.or_else(|| self.workspace.active_client())
.or_else(|| self.workspace.clients().into_iter().next())
.ok_or_else(|| ToolError("No Perspective client is attached to this viewer".to_owned()))
}
async fn tool_run_script(&self, ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: RunScriptArgs = serde_json::from_value(args)?;
let name = args.name.trim().to_owned();
if name.is_empty() {
return Err(ToolError("`name` must not be empty".to_owned()));
}
let mut options = match args.table {
Some(table) => serde_json::from_value::<perspective_client::TableInitOptions>(table)
.map_err(|err| ToolError(format!("Invalid `table` options: {err}")))?,
None => perspective_client::TableInitOptions::default(),
};
options.name = Some(name.clone());
options.format = None;
let client = self.agent_client()?;
let previous = match ctx.sandbox.remove(&name) {
Some(job) => {
job.terminate();
job.table()
},
None => {
if client
.get_hosted_table_names()
.await
.map_err(ApiError::from)?
.contains(&name)
{
return Err(ToolError(format!(
"A table named `{name}` already exists and was not created by \
`run_script` - choose another `name`"
)));
}
None
},
};
let (job, first) = ctx.sandbox.start(&args.source, client, options, previous)?;
let timeout = args
.start_timeout_ms
.unwrap_or(SCRIPT_START_TIMEOUT_MS)
.min(SCRIPT_START_TIMEOUT_MAX_MS);
let deadline = Box::pin(crate::utils::set_timeout(timeout as i32));
let failure = match futures::future::select(first, deadline).await {
futures::future::Either::Left((Ok(Ok(())), _)) => None,
futures::future::Either::Left((Ok(Err(err)), _)) => Some(err),
futures::future::Either::Left((Err(_), _)) => {
Some("The script was stopped before it emitted any rows".to_owned())
},
futures::future::Either::Right(_) if job.finished() => Some(format!(
"No rows were emitted within {timeout}ms and the module finished evaluating \
without calling `psp.emit()` - a script with no timers or sockets will emit \
nothing more"
)),
futures::future::Either::Right(_) if job.started() => Some(format!(
"No rows were emitted within {timeout}ms - call `psp.emit()` with the first batch \
as soon as it is available, or raise `start_timeout_ms`"
)),
futures::future::Either::Right(_) => Some(
"The script sandbox did not start - the host page's Content-Security-Policy may \
forbid sandboxed iframes or `blob:` workers"
.to_owned(),
),
};
if let Some(mut message) = failure {
if let Some(hint) = script_error_hint(&message) {
message = format!("{message} - {hint}");
}
job.terminate();
if job.table().is_none() {
ctx.sandbox.remove(&name);
}
return Err(with_script_log(message, &job.log_tail()));
}
Ok(job.summary().await)
}
async fn tool_list_scripts(&self, ctx: &ToolCtx, _args: Value) -> Result<Value, ToolError> {
let mut scripts = vec![];
for job in ctx.sandbox.jobs() {
scripts.push(job.summary().await);
}
Ok(json!({ "scripts": scripts }))
}
async fn tool_stop_script(&self, ctx: &ToolCtx, args: Value) -> Result<Value, ToolError> {
let args: StopScriptArgs = serde_json::from_value(args)?;
let job = ctx.sandbox.get(&args.name).ok_or_else(|| {
let names = ctx
.sandbox
.jobs()
.iter()
.map(|x| x.name().to_owned())
.collect::<Vec<_>>();
ToolError(format!(
"Unknown script `{}` - current scripts: {names:?}",
args.name
))
})?;
job.terminate();
if args.drop_table {
if let Some(table) = job.table() {
table
.delete(perspective_client::DeleteOptions::default())
.await
.map_err(|err| {
ToolError(format!(
"The script was stopped, but its table could not be dropped: {err} - \
remove the panels that display it first"
))
})?;
}
ctx.sandbox.remove(&args.name);
}
Ok(json!({
"name": args.name,
"status": "stopped",
"table_dropped": args.drop_table,
}))
}
}