Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

Initial commit of the skills support (#49)

Jaana Dogan431fbd894f79
diff --git a/internal/skills/exec.go b/internal/skills/exec.go
new file mode 100644
index 0000000..184a125
--- /dev/null
+++ b/internal/skills/exec.go
@@ -0,0 +1,241 @@
+// Copyright 2026 Google LLC
+//
+// Licensed 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.
+
+package skills
+
+import (
+ "context"
+ "io"
+ "os"
+ "path/filepath"
+
+ "google.golang.org/genai"
+)
+
+// UpdateKind identifies the type of an UpdateEvent.
+type UpdateKind int
+
+const (
+ UpdateSkillActivated UpdateKind = iota
+ UpdateScriptRunning
+ UpdateScriptDone
+)
+
+// UpdateEvent describes a state change during execution.
+type UpdateEvent struct {
+ Kind UpdateKind
+ Skill string
+ Script string // UpdateScriptRunning and UpdateScriptDone
+ ExitCode int // UpdateScriptDone only
+}
+
+// Executor runs an agentskills.io-compatible agentic loop.
+type Executor struct {
+ client *genai.Client
+ model string
+ cfg *genai.GenerateContentConfig
+
+ byName map[string]Skill
+ onUpdate func(UpdateEvent)
+}
+
+// OnUpdate registers a callback that is called when a skill is activated or a
+// script is run. Replaces any previously registered callback.
+func (e *Executor) OnUpdate(fn func(UpdateEvent)) {
+ e.onUpdate = fn
+}
+
+func (e *Executor) update(ev UpdateEvent) {
+ if e.onUpdate != nil {
+ e.onUpdate(ev)
+ }
+}
+
+// NewExecutor discovers skills in dir, then creates an Executor. The caller is
+// responsible for creating the client and choosing a model.
+func NewExecutor(client *genai.Client, model, dir string) (*Executor, error) {
+ if dir == "" {
+ dir = os.Getenv("SKILLS_DIR")
+ }
+ if dir == "" {
+ dir = filepath.Join(os.Getenv("HOME"), ".agents", "skills")
+ }
+
+ found, err := Discover(dir)
+ if err != nil {
+ return nil, err
+ }
+ if len(found) == 0 {
+ return nil, io.EOF
+ }
+
+ names := make([]string, len(found))
+ byName := make(map[string]Skill, len(found))
+ for i, s := range found {
+ names[i] = s.Name
+ byName[s.Name] = s
+ }
+
+ si := "You are a helpful AI assistant with access to a set of skills.\n" +
+ "When a user task matches one or more skills, call activate_skill to load\n" +
+ "its full instructions before answering.\n\n" +
+ systemPrompt(found)
+
+ cfg := &genai.GenerateContentConfig{
+ SystemInstruction: genai.NewContentFromText(si, genai.RoleUser),
+ Tools: []*genai.Tool{buildTool(names)},
+ }
+
+ return &Executor{
+ client: client,
+ byName: byName,
+ cfg: cfg,
+ model: model,
+ }, nil
+}
+
+// Run sends task to the model and returns the final text response, activating
+// skills and executing scripts as requested by the model along the way.
+func (e *Executor) Run(ctx context.Context, prompt string) (string, error) {
+ history := []*genai.Content{
+ genai.NewContentFromText(prompt, genai.RoleUser),
+ }
+
+ for {
+ resp, err := e.client.Models.GenerateContent(ctx, e.model, history, e.cfg)
+ if err != nil {
+ return "", err
+ }
+ if len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {
+ history = append(history, resp.Candidates[0].Content)
+ }
+
+ calls := resp.FunctionCalls()
+ if len(calls) == 0 {
+ return resp.Text(), nil
+ }
+
+ var results []*genai.Part
+ for _, call := range calls {
+ results = append(results, e.handleCall(ctx, call))
+ }
+ history = append(history, genai.NewContentFromParts(results, genai.RoleUser))
+ }
+}
+
+func (e *Executor) handleCall(ctx context.Context, call *genai.FunctionCall) *genai.Part {
+ respond := func(v map[string]any) *genai.Part {
+ return genai.NewPartFromFunctionResponse(call.Name, v)
+ }
+
+ switch call.Name {
+ case "activate_skill":
+ name, ok := call.Args["name"].(string)
+ if !ok {
+ return respond(map[string]any{"error": "invalid or missing 'name' argument"})
+ }
+ s, ok := e.byName[name]
+ if !ok {
+ return respond(map[string]any{"error": "unknown skill: " + name})
+ }
+ e.update(UpdateEvent{Kind: UpdateSkillActivated, Skill: name})
+ body, err := s.Body()
+ if err != nil {
+ return respond(map[string]any{"error": err.Error()})
+ }
+ return respond(map[string]any{"instructions": body})
+
+ case "run_skill_script":
+ skillName, ok := call.Args["skill"].(string)
+ if !ok {
+ return respond(map[string]any{"error": "invalid or missing 'skill' argument"})
+ }
+ script, ok := call.Args["script"].(string)
+ if !ok {
+ return respond(map[string]any{"error": "invalid or missing 'script' argument"})
+ }
+ var args []string
+ if raw, ok := call.Args["args"].([]any); ok {
+ for _, a := range raw {
+ if s, ok := a.(string); ok {
+ args = append(args, s)
+ }
+ }
+ }
+ s, ok := e.byName[skillName]
+ if !ok {
+ return respond(map[string]any{"error": "unknown skill: " + skillName})
+ }
+ e.update(UpdateEvent{Kind: UpdateScriptRunning, Skill: skillName, Script: script})
+ result, err := s.RunScript(ctx, script, args)
+ if err != nil {
+ return respond(map[string]any{"error": err.Error()})
+ }
+ e.update(UpdateEvent{Kind: UpdateScriptDone, Skill: skillName, Script: script, ExitCode: result.ExitCode})
+ return respond(map[string]any{
+ "stdout": result.Stdout,
+ "stderr": result.Stderr,
+ "exit_code": result.ExitCode,
+ })
+
+ default:
+ return respond(map[string]any{"error": "unknown tool: " + call.Name})
+ }
+}
+
+func buildTool(names []string) *genai.Tool {
+ return &genai.Tool{
+ FunctionDeclarations: []*genai.FunctionDeclaration{
+ {
+ Name: "activate_skill",
+ Description: "Load the full instructions for a named skill. Call this whenever the user task matches an available skill.",
+ Parameters: &genai.Schema{
+ Type: genai.TypeObject,
+ Properties: map[string]*genai.Schema{
+ "name": {
+ Type: genai.TypeString,
+ Description: "Skill name – must exactly match one of the available skills.",
+ Enum: names,
+ },
+ },
+ Required: []string{"name"},
+ },
+ },
+ {
+ Name: "run_skill_script",
+ Description: "Execute a script from a skill's scripts/ directory. Only call this after activating the skill.",
+ Parameters: &genai.Schema{
+ Type: genai.TypeObject,
+ Properties: map[string]*genai.Schema{
+ "skill": {
+ Type: genai.TypeString,
+ Description: "The skill that owns the script.",
+ Enum: names,
+ },
+ "script": {
+ Type: genai.TypeString,
+ Description: `Filename inside the skill's scripts/ directory, e.g. "extract.py".`,
+ },
+ "args": {
+ Type: genai.TypeArray,
+ Description: "Optional command-line arguments to pass to the script.",
+ Items: &genai.Schema{Type: genai.TypeString},
+ },
+ },
+ Required: []string{"skill", "script"},
+ },
+ },
+ },
+ }
+}
diff --git a/internal/skills/skills.go b/internal/skills/skills.go
new file mode 100644
index 0000000..1b1a4b2
--- /dev/null
+++ b/internal/skills/skills.go
@@ -0,0 +1,188 @@
+// Copyright 2026 Google LLC
+//
+// Licensed 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.
+
+// Package skills implements the agentskills.io discovery and execution protocol.
+//
+// Skills are directories containing a SKILL.md file with YAML frontmatter
+// (name, description) followed by Markdown instructions. An optional scripts/
+// subdirectory may contain executable files that agents can run.
+package skills
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+
+ "gopkg.in/yaml.v3"
+)
+
+const maxSkillFileSize = 32 * 1024 // 32 KB
+
+// Skill represents a discovered agentskills.io skill.
+type Skill struct {
+ Name string
+ Description string
+ Dir string // absolute path to the skill directory
+}
+
+// ScriptResult holds the output of a RunScript call.
+type ScriptResult struct {
+ Stdout string
+ Stderr string
+ ExitCode int
+}
+
+// Discover scans dir for agentskills.io-compatible skill directories and
+// returns their parsed metadata. Invisible entries (names starting with ".")
+// and entries that are not directories (including broken symlinks) are skipped.
+// Directories that lack a valid SKILL.md are silently skipped.
+func Discover(dir string) ([]Skill, error) {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return nil, fmt.Errorf("read skills dir %s: %w", dir, err)
+ }
+
+ var out []Skill
+ for _, e := range entries {
+ if strings.HasPrefix(e.Name(), ".") {
+ continue
+ }
+ skillDir := filepath.Join(dir, e.Name())
+ // os.Stat follows symlinks, so symlinked skill directories are supported.
+ info, err := os.Stat(skillDir)
+ if err != nil || !info.IsDir() {
+ continue
+ }
+ raw, err := readAndTruncate(filepath.Join(skillDir, "SKILL.md"), maxSkillFileSize)
+ if err != nil {
+ continue
+ }
+ s, err := parseMetadata(raw)
+ if err != nil {
+ continue
+ }
+ s.Dir = skillDir
+ out = append(out, s)
+ }
+ return out, nil
+}
+
+// Body returns the Markdown body of the skill's SKILL.md with the YAML
+// frontmatter stripped. This is the full instruction text to inject into a
+// model context when the skill is activated.
+func (s Skill) Body() (string, error) {
+ raw, err := os.ReadFile(filepath.Join(s.Dir, "SKILL.md"))
+ if err != nil {
+ return "", err
+ }
+ content := string(raw)
+ if strings.HasPrefix(content, "---") {
+ rest := content[3:]
+ _, after, ok := strings.Cut(rest, "\n---")
+ if !ok {
+ return "", fmt.Errorf("unclosed frontmatter in %s", filepath.Join(s.Dir, "SKILL.md"))
+ }
+ content = after
+ }
+ return strings.TrimSpace(content), nil
+}
+
+// RunScript executes scripts/<script> inside the skill directory and returns
+// its stdout, stderr, and exit code. script must be a plain filename with no
+// path separators to prevent traversal outside the scripts/ directory.
+func (s Skill) RunScript(ctx context.Context, script string, args []string) (*ScriptResult, error) {
+ if filepath.Base(script) != script {
+ return nil, fmt.Errorf("invalid script name: %q", script)
+ }
+ scriptPath := filepath.Join(s.Dir, "scripts", script)
+ if _, err := os.Stat(scriptPath); err != nil {
+ return nil, fmt.Errorf("script %q not found or inaccessible: %w", script, err)
+ }
+
+ cmd := exec.CommandContext(ctx, scriptPath, args...)
+ cmd.Dir = s.Dir
+
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+
+ exitCode := 0
+ if err := cmd.Run(); err != nil {
+ if ee, ok := err.(*exec.ExitError); ok {
+ exitCode = ee.ExitCode()
+ } else {
+ return nil, err
+ }
+ }
+ return &ScriptResult{
+ Stdout: stdout.String(),
+ Stderr: stderr.String(),
+ ExitCode: exitCode,
+ }, nil
+}
+
+// systemPrompt returns the <available_skills> XML block for injection into a
+// model system prompt, following the agentskills.io integration guide.
+func systemPrompt(skills []Skill) string {
+ var b strings.Builder
+ b.WriteString("<available_skills>\n")
+ for _, s := range skills {
+ b.WriteString(" <skill>\n")
+ fmt.Fprintf(&b, " <name>%s</name>\n", s.Name)
+ fmt.Fprintf(&b, " <description>%s</description>\n", s.Description)
+ b.WriteString(" </skill>\n")
+ }
+ b.WriteString("</available_skills>")
+ return b.String()
+}
+
+// parseMetadata extracts skill metadata from raw SKILL.md content.
+func parseMetadata(content []byte) (Skill, error) {
+ s := string(content)
+ if !strings.HasPrefix(s, "---") {
+ return Skill{}, fmt.Errorf("no frontmatter")
+ }
+ yamlBlock, _, ok := strings.Cut(s[3:], "\n---")
+ if !ok {
+ return Skill{}, fmt.Errorf("unclosed frontmatter")
+ }
+ var fm struct {
+ Name string `yaml:"name"`
+ Description string `yaml:"description"`
+ }
+ if err := yaml.Unmarshal([]byte(yamlBlock), &fm); err != nil {
+ return Skill{}, fmt.Errorf("invalid YAML: %w", err)
+ }
+ if fm.Name == "" || fm.Description == "" {
+ return Skill{}, fmt.Errorf("name and description are required")
+ }
+ return Skill{Name: fm.Name, Description: fm.Description}, nil
+}
+
+func readAndTruncate(filename string, limit int64) ([]byte, error) {
+ f, err := os.Open(filename)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ // Will read up to 'limit' bytes and stop, returning no error for truncation
+ lr := io.LimitReader(f, limit)
+ return io.ReadAll(lr)
+}