Tools schema generation and ux tweaks.

This commit is contained in:
2026-07-07 17:48:52 -07:00
parent a29422d870
commit a3d01ca1b3
3 changed files with 239 additions and 25 deletions

View File

@@ -6,15 +6,15 @@ import {
ChevronLeft, ChevronLeft,
ChevronRight, ChevronRight,
Clock, Clock,
Gauge,
Globe, Globe,
KeyRound, KeyRound,
LayoutDashboard, LayoutDashboard,
Menu, Menu,
Package,
Search, Search,
Server, Server,
Share2, Share2,
Map as MapIcon, SquareCode,
Wrench, Wrench,
X, X,
type LucideIcon, type LucideIcon,
@@ -32,6 +32,7 @@ type NavGroup = { label: string; icon: LucideIcon; children: NavLeaf[] }
// "Deployments" parent. Programs (the catalog) stays top-level. // "Deployments" parent. Programs (the catalog) stays top-level.
const NAV: (NavLeaf | NavGroup)[] = [ const NAV: (NavLeaf | NavGroup)[] = [
{ to: "/", label: "Overview", icon: LayoutDashboard, end: true }, { to: "/", label: "Overview", icon: LayoutDashboard, end: true },
{ to: "/map", label: "System", icon: Gauge },
{ to: "/gateway", label: "Gateway", icon: Globe }, { to: "/gateway", label: "Gateway", icon: Globe },
{ {
label: "Deployments", label: "Deployments",
@@ -42,8 +43,7 @@ const NAV: (NavLeaf | NavGroup)[] = [
{ to: "/tools", label: "Tools", icon: Wrench }, { to: "/tools", label: "Tools", icon: Wrench },
], ],
}, },
{ to: "/programs", label: "Programs", icon: Package }, { to: "/programs", label: "Programs", icon: SquareCode },
{ to: "/map", label: "System Map", icon: MapIcon },
{ to: "/mesh", label: "Mesh", icon: Share2 }, { to: "/mesh", label: "Mesh", icon: Share2 },
{ to: "/secrets", label: "Secrets", icon: KeyRound }, { to: "/secrets", label: "Secrets", icon: KeyRound },
] ]

View File

@@ -1,6 +1,10 @@
import { useState } from "react" import { useState } from "react"
import { Loader2 } from "lucide-react"
import type { DeploymentDetail } from "@/types" import type { DeploymentDetail } from "@/types"
import { TextField, FormFooter, useEnvSecrets } from "./fields" import { apiClient, ApiError } from "@/services/api/client"
import { Field, TextField, FormFooter } from "./fields"
type GenKind = "help" | "deep" | "ai"
interface Props { interface Props {
tool: DeploymentDetail tool: DeploymentDetail
@@ -8,30 +12,94 @@ interface Props {
onDelete?: (name: string) => Promise<void> onDelete?: (name: string) => Promise<void>
} }
type Obj = Record<string, unknown>
const obj = (v: unknown): Obj => (v as Obj) ?? {}
/** Edit a tool's (path) deployment config. A path deployment has no launcher, /** Edit a tool's (path) deployment config. A path deployment has no launcher,
* port, or schedule — only a description and env, plus its manager. */ * port, or schedule — only a description and its `tool_schema` (the neutral
* tool-call definition handed to agents), plus its manager. It has no run env:
* a tool is a CLI on PATH, invoked from a shell with castle out of the loop, so
* `defaults.env` is never applied (deploy.py only wires env for systemd units). */
export function ToolFields({ tool, onSave, onDelete }: Props) { export function ToolFields({ tool, onSave, onDelete }: Props) {
const m = tool.manifest const m = tool.manifest
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false) const [saved, setSaved] = useState(false)
const [description, setDescription] = useState((m.description as string) ?? "") const [description, setDescription] = useState((m.description as string) ?? "")
const { element: envEditor, merged } = useEnvSecrets( const [schemaText, setSchemaText] = useState(
obj(obj(m.defaults).env) as Record<string, string>, m.tool_schema ? JSON.stringify(m.tool_schema, null, 2) : "",
) )
const [schemaError, setSchemaError] = useState<string | null>(null)
// Which generate action is in-flight (null = idle) — lets each button show its
// own spinner/label rather than all three reacting to one shared flag.
const [genKind, setGenKind] = useState<GenKind | null>(null)
const generating = genKind !== null
const [validating, setValidating] = useState(false)
const [validation, setValidation] = useState<{ ok: boolean; msg: string } | null>(null)
const validate = async () => {
setValidation(null)
setSchemaError(null)
let parsed: unknown
try {
parsed = JSON.parse(schemaText)
} catch (e) {
setValidation({ ok: false, msg: `Invalid JSON: ${e instanceof Error ? e.message : String(e)}` })
return
}
setValidating(true)
try {
const res = await apiClient.post<{ valid: boolean; errors: string[] }>(
"/config/tools/schema/validate",
parsed,
)
setValidation(
res.valid
? { ok: true, msg: "Schema is valid." }
: { ok: false, msg: res.errors.join(" · ") },
)
} catch (e) {
setValidation({ ok: false, msg: e instanceof ApiError ? e.message : String(e) })
} finally {
setValidating(false)
}
}
const generate = async (kind: GenKind) => {
setGenKind(kind)
setSchemaError(null)
setValidation(null)
try {
const params = new URLSearchParams()
if (kind === "deep") params.set("deep", "true")
if (kind === "ai") params.set("assist", "llm")
const qs = params.toString()
const res = await apiClient.post<{ schema: unknown }>(
`/config/tools/${tool.id}/schema${qs ? `?${qs}` : ""}`,
)
setSchemaText(JSON.stringify(res.schema, null, 2))
} catch (e) {
setSchemaError(e instanceof ApiError ? e.message : String(e))
} finally {
setGenKind(null)
}
}
const handleSave = async () => { const handleSave = async () => {
// Validate the (optional) tool_schema JSON before saving.
let parsedSchema: unknown = undefined
if (schemaText.trim()) {
try {
parsedSchema = JSON.parse(schemaText)
} catch (e) {
setSchemaError(`Invalid JSON: ${e instanceof Error ? e.message : String(e)}`)
return
}
}
setSchemaError(null)
setSaving(true) setSaving(true)
setSaved(false) setSaved(false)
try { try {
const config: Record<string, unknown> = JSON.parse(JSON.stringify(m)) const config: Record<string, unknown> = JSON.parse(JSON.stringify(m))
delete config.id delete config.id
config.description = description || undefined config.description = description || undefined
const env = merged() config.tool_schema = parsedSchema ?? null // null clears (PATCH semantics)
if (Object.keys(env).length > 0) config.defaults = { ...obj(config.defaults), env }
else if (config.defaults) delete (config.defaults as Obj).env
await onSave(tool.id, config) await onSave(tool.id, config)
setSaved(true) setSaved(true)
setTimeout(() => setSaved(false), 2000) setTimeout(() => setSaved(false), 2000)
@@ -43,7 +111,88 @@ export function ToolFields({ tool, onSave, onDelete }: Props) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<TextField label="Description" value={description} onChange={setDescription} /> <TextField label="Description" value={description} onChange={setDescription} />
{envEditor} <Field
label="Tool schema"
hint="Neutral tool-call definition ({name, description, parameters}) handed to agents — rendered to OpenAI or Anthropic on read. Generate it from the tool's --help, then edit freely. Leave empty for none."
>
<div className="space-y-2">
<div className="flex items-center gap-2">
<button
onClick={() => generate("help")}
disabled={generating}
className="px-2.5 py-1 text-xs rounded border border-[var(--border)] hover:bg-white/5 transition-colors disabled:opacity-40"
>
{genKind === "help" ? "Generating…" : "Generate from --help"}
</button>
<button
onClick={() => generate("deep")}
disabled={generating}
className="px-2.5 py-1 text-xs rounded border border-[var(--border)] hover:bg-white/5 transition-colors disabled:opacity-40"
title="Also walk subcommands"
>
Deep
</button>
<button
onClick={() => generate("ai")}
disabled={generating}
className="flex items-center gap-1.5 px-2.5 py-1 text-xs rounded border border-[var(--border)] hover:bg-white/5 transition-colors disabled:opacity-40"
title="Use the LLM to structure subcommand trees the parser can't (requires LLM assist enabled)"
>
{genKind === "ai" ? (
<>
<Loader2 size={12} className="animate-spin" /> Generating
</>
) : (
<> Generate with AI</>
)}
</button>
<button
onClick={validate}
disabled={validating || generating || !schemaText.trim()}
className="flex items-center gap-1.5 px-2.5 py-1 text-xs rounded border border-[var(--border)] hover:bg-white/5 transition-colors disabled:opacity-40"
title="Deterministically check the schema in the box is a valid tool-call definition"
>
{validating ? (
<>
<Loader2 size={12} className="animate-spin" /> Validating
</>
) : (
"Validate"
)}
</button>
{schemaText && (
<button
onClick={() => {
setSchemaText("")
setSchemaError(null)
setValidation(null)
}}
className="text-xs text-red-400 hover:text-red-300"
>
Clear
</button>
)}
</div>
<textarea
value={schemaText}
onChange={(e) => {
setSchemaText(e.target.value)
setValidation(null)
}}
spellCheck={false}
rows={schemaText ? 12 : 3}
placeholder="{ } — generate from --help, or paste an Anthropic tool definition"
className="w-full bg-black/30 border border-[var(--border)] rounded px-3 py-2 text-xs font-mono focus:outline-none focus:border-[var(--primary)]"
/>
{validation && (
<p className={`text-xs ${validation.ok ? "text-green-400" : "text-amber-400"}`}>
{validation.ok ? "✓ " : "✗ "}
{validation.msg}
</p>
)}
{schemaError && <p className="text-xs text-red-400">{schemaError}</p>}
</div>
</Field>
<FormFooter <FormFooter
saving={saving} saving={saving}
saved={saved} saved={saved}

View File

@@ -1,5 +1,5 @@
import { useMemo, useState } from "react" import { useMemo, useState } from "react"
import { Trash2 } from "lucide-react" import { Trash2, X } from "lucide-react"
import { SecretsEditor } from "@/components/SecretsEditor" import { SecretsEditor } from "@/components/SecretsEditor"
import { ConfirmModal } from "@/components/ConfirmModal" import { ConfirmModal } from "@/components/ConfirmModal"
@@ -89,6 +89,26 @@ export function useEnvSecrets(initial: Record<string, string>) {
const [env, setEnv] = useState<Record<string, string>>(plain) const [env, setEnv] = useState<Record<string, string>>(plain)
const [secrets, setSecrets] = useState<Record<string, string>>(secretRefs) const [secrets, setSecrets] = useState<Record<string, string>>(secretRefs)
// Inline "add variable" row (replaces a native prompt). `adding` toggles it;
// the key is committed only when non-blank and not already an env/secret name.
const [adding, setAdding] = useState(false)
const [newKey, setNewKey] = useState("")
const [newVal, setNewVal] = useState("")
const trimmedKey = newKey.trim()
const duplicate = trimmedKey !== "" && (trimmedKey in env || trimmedKey in secrets)
const canCommit = trimmedKey !== "" && !duplicate
const cancelNew = () => {
setAdding(false)
setNewKey("")
setNewVal("")
}
const commitNew = () => {
if (!canCommit) return
setEnv((p) => ({ ...p, [trimmedKey]: newVal }))
cancelNew()
}
const merged = (): Record<string, string> => { const merged = (): Record<string, string> => {
const out: Record<string, string> = { ...env } const out: Record<string, string> = { ...env }
for (const [k, name] of Object.entries(secrets)) out[k] = `\${secret:${name}}` for (const [k, name] of Object.entries(secrets)) out[k] = `\${secret:${name}}`
@@ -134,15 +154,60 @@ export function useEnvSecrets(initial: Record<string, string>) {
</button> </button>
</div> </div>
))} ))}
<button {adding ? (
onClick={() => { <div className="space-y-1">
const key = prompt("Variable name:") <div className="flex items-center gap-2">
if (key) setEnv((p) => ({ ...p, [key]: "" })) <input
}} autoFocus
className="text-xs text-[var(--primary)] hover:underline" value={newKey}
> onChange={(e) => setNewKey(e.target.value)}
+ Add variable onKeyDown={(e) => {
</button> if (e.key === "Enter") commitNew()
if (e.key === "Escape") cancelNew()
}}
placeholder="VARIABLE_NAME"
className={`w-24 sm:w-56 min-w-0 ${INPUT} text-xs font-mono`}
/>
<span className="text-[var(--muted)] shrink-0">=</span>
<input
value={newVal}
onChange={(e) => setNewVal(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") commitNew()
if (e.key === "Escape") cancelNew()
}}
placeholder="value"
className={`flex-1 min-w-0 ${INPUT} text-xs font-mono`}
/>
<button
onClick={commitNew}
disabled={!canCommit}
className="px-2 py-1 text-xs rounded bg-blue-700 hover:bg-blue-600 text-white transition-colors disabled:opacity-40 shrink-0"
>
Add
</button>
<button
onClick={cancelNew}
className="text-[var(--muted)] hover:text-[var(--foreground)] p-0.5 shrink-0"
title="Cancel"
>
<X size={12} />
</button>
</div>
{duplicate && (
<p className="text-xs text-amber-400">
<span className="font-mono">{trimmedKey}</span> already exists.
</p>
)}
</div>
) : (
<button
onClick={() => setAdding(true)}
className="text-xs text-[var(--primary)] hover:underline"
>
+ Add variable
</button>
)}
</div> </div>
</Field> </Field>
<Field label="Secrets"> <Field label="Secrets">