From da4a803c114225323bc6e980574279fefff05590 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 13 May 2026 21:25:49 +0800 Subject: [PATCH] feat(locale): enhance locale handling and agent functionalities - Added locale support in various components, including the Assistant's execution context and agent tools, to improve internationalization. - Updated the `pickNodeByFilter` function to include a fallback mechanism for host_exec nodes when no container nodes are available. - Introduced a new `agent_reference` tool for downloading agent source code for read-only study, alongside updates to the `agent_download` tool to restrict downloads to the 'smith' namespace. - Enhanced documentation and tests to reflect the new functionalities and ensure robust locale extraction and handling. --- agent/assistant/sandbox_v2.go | 1 + agent/sandbox/v2/claude/command.go | 4 ++ agent/sandbox/v2/lifecycle.go | 14 +++- agent/sandbox/v2/types/runner.go | 1 + grpc/mcp/mcp.go | 3 + tools/agent/agent.go | 18 +++++ tools/agent/agent_test.go | 107 ++++++++++++++++++++++++++++- tools/agent/download.go | 14 +++- tools/agent/download_schema.json | 4 +- tools/agent/list.go | 69 ++++++++++++++++++- tools/agent/reference.go | 48 +++++++++++++ tools/agent/reference_schema.json | 16 +++++ tools/mcps/agent.json | 1 + tools/prompts/system-tools.md | 3 +- tools/skills/yao-agent/SKILL.md | 30 ++++++-- tools/tools.go | 5 +- 16 files changed, 319 insertions(+), 19 deletions(-) create mode 100644 tools/agent/reference.go create mode 100644 tools/agent/reference_schema.json diff --git a/agent/assistant/sandbox_v2.go b/agent/assistant/sandbox_v2.go index 94e3a124..8ac4baf3 100644 --- a/agent/assistant/sandbox_v2.go +++ b/agent/assistant/sandbox_v2.go @@ -235,6 +235,7 @@ func (ast *Assistant) executeSandboxV2Stream( Token: tok, Logger: ctx.Logger, UserExplicit: p.Options != nil && p.Options.Connector != "", + Locale: ctx.Locale, } execReq := &sandboxv2.ExecuteRequest{ diff --git a/agent/sandbox/v2/claude/command.go b/agent/sandbox/v2/claude/command.go index 7aed39e5..b03c6faa 100644 --- a/agent/sandbox/v2/claude/command.go +++ b/agent/sandbox/v2/claude/command.go @@ -140,6 +140,10 @@ func buildEnv(req *types.StreamRequest, p platform) map[string]string { } env["WORKDIR"] = workDir + if req.Locale != "" { + env["CTX_LOCALE"] = req.Locale + } + assistantID := req.AssistantID if assistantID != "" { configDir := p.PathJoin(workDir, ".yao", "assistants", assistantID) diff --git a/agent/sandbox/v2/lifecycle.go b/agent/sandbox/v2/lifecycle.go index 606352a1..a6cdd2c8 100644 --- a/agent/sandbox/v2/lifecycle.go +++ b/agent/sandbox/v2/lifecycle.go @@ -329,8 +329,9 @@ func resolveOwnerID(ctx *agentContext.Context) string { } // pickNodeByFilter selects a random online node that satisfies the given filter -// and image requirement. If image is non-empty, candidate nodes must have a -// container runtime (Docker or K8s). +// and image requirement. If image is non-empty, nodes with a container runtime +// (Docker or K8s) are preferred; if none are available, host_exec nodes are +// accepted as fallback (ResolveNodeID will resolve them to host mode). func pickNodeByFilter(filter *types.ComputerFilter, image string) (string, error) { reg := registry.Global() if reg == nil { @@ -339,6 +340,7 @@ func pickNodeByFilter(filter *types.ComputerFilter, image string) (string, error nodes := reg.List() var candidates []string + var hostExecFallback []string for _, n := range nodes { if n.Status != "online" && n.Status != "" { continue @@ -372,12 +374,20 @@ func pickNodeByFilter(filter *types.ComputerFilter, image string) (string, error } if image != "" && !(n.Capabilities.Docker || n.Capabilities.K8s) { + if n.Capabilities.HostExec { + hostExecFallback = append(hostExecFallback, n.TaiID) + } continue } candidates = append(candidates, n.TaiID) } + if len(candidates) == 0 && len(hostExecFallback) > 0 { + log.Trace("[sandbox/v2] pickNodeByFilter: no container node for image %q, falling back to host_exec node", image) + candidates = hostExecFallback + } + if len(candidates) == 0 { kind := "" os := "" diff --git a/agent/sandbox/v2/types/runner.go b/agent/sandbox/v2/types/runner.go index 10963075..ee0cfa98 100644 --- a/agent/sandbox/v2/types/runner.go +++ b/agent/sandbox/v2/types/runner.go @@ -60,4 +60,5 @@ type StreamRequest struct { Token *SandboxToken // current user's sandbox token for MCP callbacks Logger *agentContext.RequestLogger // request-scoped logger propagated from agent context UserExplicit bool // true when the user explicitly selected the primary connector + Locale string // user locale (e.g. "zh-cn", "en-us") for i18n in MCP tools } diff --git a/grpc/mcp/mcp.go b/grpc/mcp/mcp.go index da2c4a1e..89426eec 100644 --- a/grpc/mcp/mcp.go +++ b/grpc/mcp/mcp.go @@ -45,6 +45,9 @@ func authProviderFromCtx(ctx context.Context) *grpcAuthProvider { if ids := md.Get("x-sandbox-id"); len(ids) > 0 && ids[0] != "" { m["sandbox_id"] = ids[0] } + if vals := md.Get("x-locale"); len(vals) > 0 && vals[0] != "" { + m["locale"] = vals[0] + } } return &grpcAuthProvider{m: m} } diff --git a/tools/agent/agent.go b/tools/agent/agent.go index 57f060bd..3bdbabf7 100644 --- a/tools/agent/agent.go +++ b/tools/agent/agent.go @@ -22,6 +22,9 @@ var DownloadSchemaJSON []byte //go:embed deploy_schema.json var DeploySchemaJSON []byte +//go:embed reference_schema.json +var ReferenceSchemaJSON []byte + //go:embed connectors_schema.json var ConnectorsSchemaJSON []byte @@ -68,6 +71,21 @@ func extractWorkspaceID(proc *process.Process) string { return "" } +func extractLocale(proc *process.Process) string { + if proc.Context == nil { + return "en-us" + } + md, ok := metadata.FromIncomingContext(proc.Context) + if !ok { + return "en-us" + } + vals := md.Get("x-locale") + if len(vals) > 0 && vals[0] != "" { + return strings.ToLower(vals[0]) + } + return "en-us" +} + func validateID(id string) error { if strings.Contains(id, "..") { return fmt.Errorf("invalid id: path traversal not allowed") diff --git a/tools/agent/agent_test.go b/tools/agent/agent_test.go index 7be82a65..79e157fc 100644 --- a/tools/agent/agent_test.go +++ b/tools/agent/agent_test.go @@ -204,6 +204,7 @@ func TestSchemaJSON_NonEmpty(t *testing.T) { schemas := map[string][]byte{ "ListSchemaJSON": ListSchemaJSON, "DownloadSchemaJSON": DownloadSchemaJSON, + "ReferenceSchemaJSON": ReferenceSchemaJSON, "DeploySchemaJSON": DeploySchemaJSON, "ConnectorsSchemaJSON": ConnectorsSchemaJSON, } @@ -396,12 +397,65 @@ func TestDownloadHandler_InvalidID(t *testing.T) { } } +func TestDownloadHandler_WrongNamespace(t *testing.T) { + proc := &process.Process{Args: []interface{}{"yao.slides"}} + result := DownloadHandler(proc) + m := result.(map[string]interface{}) + errMsg, has := m["error"] + if !has { + t.Fatal("expected error for non-smith namespace") + } + if !contains(errMsg.(string), "smith") { + t.Errorf("error = %q, want substring 'smith'", errMsg) + } + if !contains(errMsg.(string), "agent_reference") { + t.Errorf("error = %q, should suggest agent_reference", errMsg) + } +} + func TestDownloadHandler_MissingWorkspace(t *testing.T) { + proc := &process.Process{ + Args: []interface{}{"smith.test"}, + Context: context.Background(), + } + result := DownloadHandler(proc) + m := result.(map[string]interface{}) + errMsg, has := m["error"] + if !has { + t.Fatal("expected error when workspace_id is missing") + } + if !contains(errMsg.(string), "workspace_id") { + t.Errorf("error = %q, want substring 'workspace_id'", errMsg) + } +} + +func TestReferenceHandler_MissingID(t *testing.T) { + proc := &process.Process{Args: []interface{}{""}} + result := ReferenceHandler(proc) + m := result.(map[string]interface{}) + if _, has := m["error"]; !has { + t.Error("expected error for empty id") + } +} + +func TestReferenceHandler_InvalidID(t *testing.T) { + cases := []string{"no/slash", "a..b", ""} + for _, id := range cases { + proc := &process.Process{Args: []interface{}{id}} + result := ReferenceHandler(proc) + m := result.(map[string]interface{}) + if _, has := m["error"]; !has { + t.Errorf("ReferenceHandler(%q) expected error", id) + } + } +} + +func TestReferenceHandler_MissingWorkspace(t *testing.T) { proc := &process.Process{ Args: []interface{}{"yao.slides"}, Context: context.Background(), } - result := DownloadHandler(proc) + result := ReferenceHandler(proc) m := result.(map[string]interface{}) errMsg, has := m["error"] if !has { @@ -428,6 +482,57 @@ func TestDeployHandler_MissingWorkspace(t *testing.T) { } } +// --- extractLocale tests --- + +func TestExtractLocale_WithMetadata(t *testing.T) { + md := metadata.Pairs("x-locale", "zh-cn") + ctx := metadata.NewIncomingContext(context.Background(), md) + proc := &process.Process{Context: ctx} + + locale := extractLocale(proc) + if locale != "zh-cn" { + t.Errorf("extractLocale = %q, want %q", locale, "zh-cn") + } +} + +func TestExtractLocale_UpperCase(t *testing.T) { + md := metadata.Pairs("x-locale", "ZH-CN") + ctx := metadata.NewIncomingContext(context.Background(), md) + proc := &process.Process{Context: ctx} + + locale := extractLocale(proc) + if locale != "zh-cn" { + t.Errorf("extractLocale = %q, want %q (should lowercase)", locale, "zh-cn") + } +} + +func TestExtractLocale_NoMetadata(t *testing.T) { + proc := &process.Process{Context: context.Background()} + locale := extractLocale(proc) + if locale != "en-us" { + t.Errorf("extractLocale without metadata = %q, want default %q", locale, "en-us") + } +} + +func TestExtractLocale_NilContext(t *testing.T) { + proc := &process.Process{} + locale := extractLocale(proc) + if locale != "en-us" { + t.Errorf("extractLocale with nil context = %q, want default %q", locale, "en-us") + } +} + +func TestExtractLocale_EmptyValue(t *testing.T) { + md := metadata.Pairs("x-locale", "") + ctx := metadata.NewIncomingContext(context.Background(), md) + proc := &process.Process{Context: ctx} + + locale := extractLocale(proc) + if locale != "en-us" { + t.Errorf("extractLocale with empty value = %q, want default %q", locale, "en-us") + } +} + // --- helpers --- func contains(s, substr string) bool { diff --git a/tools/agent/download.go b/tools/agent/download.go index b3a04702..0eb72c61 100644 --- a/tools/agent/download.go +++ b/tools/agent/download.go @@ -3,22 +3,32 @@ package agent import ( "fmt" "path/filepath" + "strings" "github.com/yaoapp/gou/process" "github.com/yaoapp/yao/config" ) // DownloadHandler handles the agent_download tool. -// Args[0]: id (string, dot notation e.g. "yao.slides") +// Restricted to the smith namespace — used for downloading agents to edit. +// For read-only reference of other namespaces, use agent_reference instead. +// Args[0]: id (string, dot notation e.g. "smith.weather") func DownloadHandler(proc *process.Process) interface{} { id := proc.ArgsString(0) if id == "" { - return map[string]interface{}{"error": "id is required (e.g. 'yao.slides')"} + return map[string]interface{}{"error": "id is required (e.g. 'smith.weather')"} } if err := validateID(id); err != nil { return map[string]interface{}{"error": err.Error()} } + parts := strings.SplitN(id, ".", 2) + if len(parts) != 2 || parts[0] != allowedDeployNamespace { + return map[string]interface{}{ + "error": fmt.Sprintf("download restricted to '%s' namespace; use agent_reference for other agents", allowedDeployNamespace), + } + } + wsFS, err := resolveWorkspaceFS(proc) if err != nil { return map[string]interface{}{"error": err.Error()} diff --git a/tools/agent/download_schema.json b/tools/agent/download_schema.json index e0450a90..cc034eda 100644 --- a/tools/agent/download_schema.json +++ b/tools/agent/download_schema.json @@ -1,13 +1,13 @@ { "name": "agent_download", - "description": "Download agent source code from the host into the sandbox development directory. Use this to study existing agents as reference. Any agent can be downloaded (read-only reference).", + "description": "Download a smith-namespace agent into the development directory for editing. Restricted to the 'smith' namespace only. For read-only reference of other agents, use agent_reference instead.", "process": "tools.agent_download", "inputSchema": { "type": "object", "properties": { "id": { "type": "string", - "description": "Agent ID in dot notation (e.g. 'yao.slides', 'smith.weather')" + "description": "Agent ID in dot notation, must be smith namespace (e.g. 'smith.weather')" } }, "required": ["id"] diff --git a/tools/agent/list.go b/tools/agent/list.go index 0b5e287d..e709a995 100644 --- a/tools/agent/list.go +++ b/tools/agent/list.go @@ -8,6 +8,7 @@ import ( goufs "github.com/yaoapp/gou/fs" "github.com/yaoapp/gou/process" + "github.com/yaoapp/yao/agent/i18n" ) // ListHandler handles the agent_list tool. @@ -18,6 +19,8 @@ func ListHandler(proc *process.Process) interface{} { namespace = proc.ArgsString(0) } + locale := extractLocale(proc) + app, err := goufs.Get("app") if err != nil { return map[string]interface{}{"error": fmt.Sprintf("app filesystem: %s", err.Error())} @@ -70,14 +73,74 @@ func ListHandler(proc *process.Process) interface{} { continue } + name := pkg.Name + description := pkg.Description + capabilities := pkg.Capabilities + resolveLocaleFields(agentDir, locale, &name, &description, &capabilities) + agents = append(agents, agentInfo{ ID: id, - Name: pkg.Name, - Description: pkg.Description, - Capabilities: pkg.Capabilities, + Name: name, + Description: description, + Capabilities: capabilities, }) } } return map[string]interface{}{"agents": agents} } + +// resolveLocaleFields replaces {{ key }} templates in name/description using +// the agent's locales/ directory. Falls back gracefully: exact locale → +// language code (e.g. "zh") → en-us → raw template. +func resolveLocaleFields(agentDir, locale string, fields ...*string) { + hasTemplate := false + for _, f := range fields { + if strings.Contains(*f, "{{") { + hasTemplate = true + break + } + } + if !hasTemplate { + return + } + + locales, err := i18n.GetLocales(agentDir) + if err != nil || len(locales) == 0 { + return + } + locales = locales.Flatten() + + li := findLocale(locales, locale) + if li == nil { + return + } + + for _, f := range fields { + if parsed := li.Parse(*f); parsed != nil { + if s, ok := parsed.(string); ok { + *f = s + } + } + } +} + +func findLocale(locales i18n.Map, locale string) *i18n.I18n { + locale = strings.ToLower(locale) + if li, ok := locales[locale]; ok { + return &li + } + parts := strings.SplitN(locale, "-", 2) + if len(parts) > 1 { + if li, ok := locales[parts[0]]; ok { + return &li + } + } + if li, ok := locales["en-us"]; ok { + return &li + } + if li, ok := locales["en"]; ok { + return &li + } + return nil +} diff --git a/tools/agent/reference.go b/tools/agent/reference.go new file mode 100644 index 00000000..f4e08ef0 --- /dev/null +++ b/tools/agent/reference.go @@ -0,0 +1,48 @@ +package agent + +import ( + "fmt" + "path/filepath" + + "github.com/yaoapp/gou/process" + "github.com/yaoapp/yao/config" +) + +// ReferenceHandler handles the agent_reference tool. +// Downloads agent source code to .references/ for read-only study. +// Args[0]: id (string, dot notation e.g. "yao.slides") +func ReferenceHandler(proc *process.Process) interface{} { + id := proc.ArgsString(0) + if id == "" { + return map[string]interface{}{"error": "id is required (e.g. 'yao.slides')"} + } + if err := validateID(id); err != nil { + return map[string]interface{}{"error": err.Error()} + } + + wsFS, err := resolveWorkspaceFS(proc) + if err != nil { + return map[string]interface{}{"error": err.Error()} + } + + relPath := idToPath(id) + appRoot := config.Conf.Root + srcURI := "local:///" + filepath.Join(appRoot, "assistants", relPath) + dstPath := filepath.Join("agent-smith-dev", ".references", relPath) + + result, copyErr := wsFS.Copy(srcURI, dstPath) + if copyErr != nil { + return map[string]interface{}{"error": fmt.Sprintf("reference download failed: %s", copyErr.Error())} + } + + files := 0 + if result != nil { + files = result.FilesSynced + } + + return map[string]interface{}{ + "status": "ok", + "path": dstPath, + "files": files, + } +} diff --git a/tools/agent/reference_schema.json b/tools/agent/reference_schema.json new file mode 100644 index 00000000..39ca81c5 --- /dev/null +++ b/tools/agent/reference_schema.json @@ -0,0 +1,16 @@ +{ + "name": "agent_reference", + "description": "Download agent source code from the host into the .references/ directory for read-only study. Any agent across all namespaces can be downloaded. Use this to study existing agent patterns before building your own.", + "process": "tools.agent_reference", + "inputSchema": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Agent ID in dot notation (e.g. 'yao.slides', 'yao.keeper')" + } + }, + "required": ["id"] + }, + "x-process-args": ["$args.id"] +} diff --git a/tools/mcps/agent.json b/tools/mcps/agent.json index 0ab63fa0..77d50719 100644 --- a/tools/mcps/agent.json +++ b/tools/mcps/agent.json @@ -5,6 +5,7 @@ "tools": { "agent_list": "tools.agent_list", "agent_download": "tools.agent_download", + "agent_reference": "tools.agent_reference", "agent_deploy": "tools.agent_deploy", "agent_connectors": "tools.agent_connectors" } diff --git a/tools/prompts/system-tools.md b/tools/prompts/system-tools.md index bf53daeb..939f7b6b 100644 --- a/tools/prompts/system-tools.md +++ b/tools/prompts/system-tools.md @@ -80,7 +80,8 @@ You have access to Yao system tools via the `tai` command in bash. | `image_generate` | yao-image | Generate images from text prompts | | `image_providers` | yao-image | List available image generation or vision providers | | `agent_list` | yao-agent | List available agents on the host | -| `agent_download` | yao-agent | Download agent source code for reference | +| `agent_download` | yao-agent | Download smith agent for editing (smith only) | +| `agent_reference` | yao-agent | Download agent source to .references/ for study | | `agent_deploy` | yao-agent | Deploy agent code to host (smith namespace only) | | `agent_connectors` | yao-agent | Get LLM connector matrix (no keys) | diff --git a/tools/skills/yao-agent/SKILL.md b/tools/skills/yao-agent/SKILL.md index 67015e89..a7556e89 100644 --- a/tools/skills/yao-agent/SKILL.md +++ b/tools/skills/yao-agent/SKILL.md @@ -1,11 +1,11 @@ --- name: yao-agent -description: Agent management expert. ALWAYS invoke this skill when you need to list available agents, download agent source code for reference, deploy agent code to the host, or query the LLM connector matrix. Do not guess agent structures — use this skill first. +description: Agent management expert. ALWAYS invoke this skill when you need to list available agents, download or reference agent source code, deploy agent code to the host, or query the LLM connector matrix. Do not guess agent structures — use this skill first. --- # Agent Tools -Four tools for managing agents on the host, called via bash. +Five tools for managing agents on the host, called via bash. ## agent_list @@ -22,16 +22,33 @@ tai tool agent_list '{"namespace": "smith"}' ## agent_download -Download agent source code from the host into `agent-smith-dev/assistants/` for reference. Any agent across all namespaces can be downloaded (read-only). +Download a **smith-namespace** agent into the development directory for editing. **Restricted to `smith` namespace only** — for other agents, use `agent_reference`. ```bash -tai tool agent_download '{"id": "yao.slides"}' +tai tool agent_download '{"id": "smith.weather"}' +``` + +| Parameter | Type | Required | Description | +|-----------|--------|----------|----------------------------------------------------------| +| `id` | string | yes | Agent ID in dot notation. Must be `smith.*`. | + +Downloaded code lands in `agent-smith-dev/assistants/smith//`. + +## agent_reference + +Download agent source code from the host into `.references/` for **read-only study**. Any agent across all namespaces can be referenced. + +```bash +tai tool agent_reference '{"id": "yao.slides"}' +tai tool agent_reference '{"id": "yao.keeper"}' ``` | Parameter | Type | Required | Description | |-----------|--------|----------|----------------------------------------------------| | `id` | string | yes | Agent ID in dot notation (e.g. `yao.slides`) | +Referenced code lands in `agent-smith-dev/.references///`. + ## agent_deploy Deploy agent source code from the sandbox development directory to the host. **Restricted to the `smith` namespace only** — attempts to deploy to other namespaces will be rejected. @@ -58,8 +75,9 @@ No parameters required. ## Guidelines -- Use `agent_list` to discover agents before downloading -- Downloaded code lands in `agent-smith-dev/assistants///` +- Use `agent_list` to discover agents before downloading or referencing +- `agent_download` is for editing smith agents — code lands in `agent-smith-dev/assistants/smith//` +- `agent_reference` is for studying any agent — code lands in `agent-smith-dev/.references///` - Deploy is restricted to the `smith` namespace for safety - Connector data never includes API keys, secrets, or tokens - All output is JSON diff --git a/tools/tools.go b/tools/tools.go index f1bc51b5..b0061147 100644 --- a/tools/tools.go +++ b/tools/tools.go @@ -45,6 +45,7 @@ func init() { "image_providers": image.ProvidersHandler, "agent_list": agent.ListHandler, "agent_download": agent.DownloadHandler, + "agent_reference": agent.ReferenceHandler, "agent_deploy": agent.DeployHandler, "agent_connectors": agent.ConnectorsHandler, }) @@ -58,8 +59,8 @@ func init() { registerMCPServer(mcpImageDSL, "yao-image", image.ReadSchemaJSON, image.GenerateSchemaJSON, image.ProvidersSchemaJSON) registerMCPServer(mcpAgentDSL, "yao-agent", - agent.ListSchemaJSON, agent.DownloadSchemaJSON, agent.DeploySchemaJSON, - agent.ConnectorsSchemaJSON) + agent.ListSchemaJSON, agent.DownloadSchemaJSON, agent.ReferenceSchemaJSON, + agent.DeploySchemaJSON, agent.ConnectorsSchemaJSON) } func registerMCPServer(dsl []byte, id string, schemas ...[]byte) {