Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion pkg/cmd/agents/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type CreateOptions struct {
File string
Name string
Instructions string
RawTools json.RawMessage
}

// NewCreateCmd returns the `agents create` command.
Expand Down Expand Up @@ -86,6 +87,7 @@ func NewCreateCmd(f *cmdutil.Factory) *cobra.Command {
}

func buildAgent(opts *CreateOptions) (*agentStudio.AgentConfigCreate, error) {
opts.RawTools = nil
raw, err := cmdutil.JSONPayload(opts.JSON, opts.File, opts.IO.In)
if err != nil {
return nil, err
Expand All @@ -103,6 +105,11 @@ func buildAgent(opts *CreateOptions) (*agentStudio.AgentConfigCreate, error) {
if body.Name == "" || body.Instructions == "" {
return nil, cmdutil.FlagErrorf("agent JSON requires `name` and `instructions`")
}
var fields map[string]json.RawMessage
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
return nil, fmt.Errorf("parsing agent JSON: %w", err)
}
opts.RawTools = fields["tools"]

return &body, nil
}
Expand All @@ -125,7 +132,12 @@ func runCreateCmd(opts *CreateOptions) error {

opts.IO.StartProgressIndicatorWithLabel("Creating agent")

res, err := client.CreateAgent(client.NewApiCreateAgentRequest(body))
var requestOptions []agentStudio.RequestOption
if opts.RawTools != nil {
// Preserve tool variants and fields not yet modeled by the pinned SDK.
requestOptions = append(requestOptions, agentStudio.WithBodyParam("tools", opts.RawTools))
}
res, err := client.CreateAgent(client.NewApiCreateAgentRequest(body), requestOptions...)
if err != nil {
opts.IO.StopProgressIndicator()
return err
Expand Down
73 changes: 73 additions & 0 deletions pkg/cmd/agents/create/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,76 @@ func TestCreateAgent_EmptyStdin(t *testing.T) {
assert.Contains(t, err.Error(), "parsing agent JSON")
r.Verify(t)
}

func TestCreateAgent_PreservesPublicCompareToolFromFile(t *testing.T) {
payload := `{"name":"bot","instructions":"help","tools":[{"type":"algolia_compare_products","name":"algolia_compare_products","description":"Compare products carefully"}]}`
path := filepath.Join(t.TempDir(), "agent.json")
require.NoError(t, os.WriteFile(path, []byte(payload), 0o600))
r := &httpmock.Registry{}
var body []byte
r.Register(httpmock.REST("POST", "agent-studio/1/agents"), func(req *http.Request) (*http.Response, error) {
body, _ = io.ReadAll(req.Body)
return httpmock.StringResponse(createdAgentBody)(req)
})
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(create.NewCreateCmd(f), "--file "+path, out)
require.NoError(t, err)
assert.JSONEq(t, payload, string(body))
r.Verify(t)
}

func TestCreateAgent_ToolsPresenceAndOtherFields(t *testing.T) {
for _, tt := range []struct{ name, payload string }{
{"omitted", `{"name":"bot","instructions":"help","description":"other","config":{"temperature":0.7}}`},
{"empty", `{"name":"bot","instructions":"help","tools":[],"config":{"temperature":0.7}}`},
{"null", `{"name":"bot","instructions":"help","tools":null,"config":{"temperature":0.7}}`},
{"mixed", `{"name":"bot","instructions":"help","systemPrompt":"rules","tools":[{"type":"algolia_compare_products","name":"algolia_compare_products","description":"compare"},{"type":"client_side","name":"show","description":"display","inputSchema":{"type":"object","properties":{},"required":[]},"isTerminal":true}],"config":{"max_tokens":100}}`},
} {
t.Run(tt.name, func(t *testing.T) {
r := &httpmock.Registry{}
var body []byte
r.Register(httpmock.REST("POST", "agent-studio/1/agents"), func(req *http.Request) (*http.Response, error) {
body, _ = io.ReadAll(req.Body)
return httpmock.StringResponse(createdAgentBody)(req)
})
f, out := test.NewFactory(false, r, nil, tt.payload)
_, err := test.Execute(create.NewCreateCmd(f), "--file -", out)
require.NoError(t, err)
assert.JSONEq(t, tt.payload, string(body))
r.Verify(t)
})
}
}

func TestCreateAgent_RejectsInvalidToolsBeforeRequest(t *testing.T) {
r := &httpmock.Registry{}
f, out := test.NewFactory(false, r, nil, `{"name":"bot","instructions":"help","tools":"invalid"}`)
_, err := test.Execute(create.NewCreateCmd(f), "--file -", out)
require.Error(t, err)
assert.Empty(t, r.Requests)
}

func TestCreateAgent_InvalidToolsDoesNotExposePayload(t *testing.T) {
r := &httpmock.Registry{}
f, out := test.NewFactory(false, r, nil, `{"name":"bot","instructions":"help","tools":"sensitive-tool-secret"}`)
_, err := test.Execute(create.NewCreateCmd(f), "--file -", out)
require.Error(t, err)
assert.NotContains(t, err.Error(), "sensitive-tool-secret")
assert.NotContains(t, out.Stderr(), "sensitive-tool-secret")
assert.Empty(t, r.Requests)
}

func TestCreateAgent_PreservesToolsFromJSONFlag(t *testing.T) {
const payload = `{"name":"bot","instructions":"help","tools":[{"type":"algolia_compare_products","name":"algolia_compare_products","description":"compare"}]}`
r := &httpmock.Registry{}
var body []byte
r.Register(httpmock.REST("POST", "agent-studio/1/agents"), func(req *http.Request) (*http.Response, error) {
body, _ = io.ReadAll(req.Body)
return httpmock.StringResponse(createdAgentBody)(req)
})
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(create.NewCreateCmd(f), "--json '"+payload+"'", out)
require.NoError(t, err)
assert.JSONEq(t, payload, string(body))
r.Verify(t)
}
111 changes: 107 additions & 4 deletions pkg/cmd/agents/get/get.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
package get

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"

"github.com/MakeNowJust/heredoc"
agentStudio "github.com/algolia/algoliasearch-client-go/v4/algolia/agent-studio"
"github.com/algolia/algoliasearch-client-go/v4/algolia/errs"
"github.com/spf13/cobra"

"github.com/algolia/cli/pkg/cmdutil"
Expand Down Expand Up @@ -63,13 +70,109 @@ func runGetCmd(opts *GetOptions) error {

opts.IO.StartProgressIndicatorWithLabel("Fetching agent")

res, err := client.GetAgent(client.NewApiGetAgentRequest(opts.AgentID))
res, body, err := client.GetAgentWithHTTPInfo(client.NewApiGetAgentRequest(opts.AgentID))
opts.IO.StopProgressIndicator()
if err != nil {
opts.IO.StopProgressIndicator()
return err
}
if res == nil {
return fmt.Errorf("res is nil")
}
if res.Body != nil {
defer res.Body.Close()
}
if res.StatusCode >= 300 {
return agentAPIError(res, body)
}
if len(body) == 0 || bytes.Equal(bytes.TrimSpace(body), []byte("null")) {
return p.Print(opts.IO, nil)
}

opts.IO.StopProgressIndicator()
var typed agentStudio.AgentWithVersionResponse
if err := json.Unmarshal(body, &typed); err != nil {
return errs.NewDeserializationError(fmt.Errorf("failed to unmarshal response body: %w", err), res.Header.Get("Correlation-ID"))
}
encoded, err := json.Marshal(typed)
if err != nil {
return err
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(encoded, &fields); err != nil {
return err
}
var source map[string]json.RawMessage
if err := json.Unmarshal(body, &source); err != nil {
return err
}
if tools, ok := source["tools"]; ok {
fields["tools"] = tools
}
encoded, err = json.Marshal(fields)
if err != nil {
return err
}
var outputTools any
if rawTools, ok := source["tools"]; ok {
decoder := json.NewDecoder(bytes.NewReader(rawTools))
decoder.UseNumber()
if err := decoder.Decode(&outputTools); err != nil {
return err
}
}
output := printableAgent{
Id: typed.Id, Name: typed.Name, Description: typed.Description, Status: typed.Status,
ProviderId: typed.ProviderId, Model: typed.Model, Instructions: typed.Instructions,
SystemPrompt: typed.SystemPrompt, Config: typed.Config, Tools: outputTools,
TemplateType: typed.TemplateType, CreatedAt: typed.CreatedAt, UpdatedAt: typed.UpdatedAt,
LastUsedAt: typed.LastUsedAt, json: encoded,
}
return p.Print(opts.IO, output)
}

// Keep SDK field names and JSON tags available to JSONPath while rendering the
// original tools payload in JSON and JSONPath output.
type printableAgent struct {
// Id and ProviderId keep the SDK's Go field names so existing JSONPath
// templates such as {.Id} keep working.
Id any `json:"id"` //nolint:stylecheck
Name any `json:"name"`
Description any `json:"description"`
Status any `json:"status"`
ProviderId any `json:"providerId"` //nolint:stylecheck
Model any `json:"model"`
Instructions any `json:"instructions"`
SystemPrompt any `json:"systemPrompt"`
Config any `json:"config"`
Tools any `json:"tools"`
TemplateType any `json:"templateType"`
CreatedAt any `json:"createdAt"`
UpdatedAt any `json:"updatedAt"`
LastUsedAt any `json:"lastUsedAt"`
json []byte
}

return p.Print(opts.IO, res)
func (a printableAgent) MarshalJSON() ([]byte, error) { return a.json, nil }

// JSONPath errors format their input with %#v; avoid exposing agent data there.
func (a printableAgent) GoString() string { return "AgentWithVersionResponse{[REDACTED]}" }

// Match the SDK's error decoding for the raw response path.
func agentAPIError(res *http.Response, body []byte) error {
apiErr := &agentStudio.APIError{Message: string(body), Status: res.StatusCode, CorrelationID: res.Header.Get("Correlation-ID")}
if strings.Contains(res.Header.Get("Content-Type"), "application/json") {
var base agentStudio.ErrorBase
if len(body) > 0 {
if err := json.Unmarshal(body, &base); err != nil {
apiErr.Message = fmt.Sprintf("failed to unmarshal response body: %v", err)
return apiErr
}
}
if base.Message != nil {
apiErr.Message = *base.Message
}
apiErr.AdditionalProperties = base.AdditionalProperties
} else if strings.Contains(res.Header.Get("Content-Type"), "text/html") {
apiErr.Message = http.StatusText(res.StatusCode)
}
return apiErr
}
98 changes: 98 additions & 0 deletions pkg/cmd/agents/get/get_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package get_test

import (
"encoding/json"
"io"
"net/http"
"strings"
"testing"

agentStudio "github.com/algolia/algoliasearch-client-go/v4/algolia/agent-studio"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -49,3 +54,96 @@ func TestGetAgent_MissingArg(t *testing.T) {
require.Error(t, err)
assert.Contains(t, err.Error(), "agentstudio agents get requires a <agent-id> argument")
}

func TestGetAgentPreservesToolDescription(t *testing.T) {
const response = `{"id":"agt_1","name":"test-agent","description":null,"providerId":null,"lastUsedAt":null,"instructions":"Hello","status":"draft","config":{},"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","tools":[{"type":"algolia_compare_products","name":"algolia_compare_products","description":"Compare selected products"}]}`
for _, tt := range []struct{ name, args, expected string }{
{"json", "agt_1", response},
{"jsonpath", "agt_1 -o jsonpath={.tools[0].description}", "Compare selected products"},
{"jsonpath name", "agt_1 -o jsonpath={.name}", "test-agent"},
{"jsonpath Go field name", "agt_1 -o jsonpath={.Name}", "test-agent"},
{"jsonpath Go identifier name", "agt_1 -o jsonpath={.Id}", "agt_1"},
} {
t.Run(tt.name, func(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/agents/agt_1"), httpmock.StringResponse(response))
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(get.NewGetCmd(f), tt.args, out)
require.NoError(t, err)
if tt.name == "json" {
assert.JSONEq(t, tt.expected, strings.TrimSpace(out.String()))
} else {
assert.Equal(t, tt.expected, strings.TrimSpace(out.String()))
}
r.Verify(t)
})
}
}

func TestGetAgentAPIError(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/agents/agt_1"), func(req *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 403, Header: http.Header{"Content-Type": []string{"application/json"}, "Correlation-Id": []string{"test-correlation"}}, Request: req, Body: io.NopCloser(strings.NewReader(`{"message":"access denied"}`))}, nil
})
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(get.NewGetCmd(f), "agt_1", out)
require.Error(t, err)
var apiErr *agentStudio.APIError
require.ErrorAs(t, err, &apiErr)
assert.Equal(t, 403, apiErr.Status)
assert.Equal(t, "access denied", apiErr.Message)
assert.Equal(t, "test-correlation", apiErr.CorrelationID)
assert.Empty(t, strings.TrimSpace(out.String()))
r.Verify(t)
}

func TestGetAgentMalformedJSON(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/agents/agt_1"), httpmock.StringResponse(`{"tools":`))
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(get.NewGetCmd(f), "agt_1", out)
require.Error(t, err)
assert.Empty(t, strings.TrimSpace(out.String()))
r.Verify(t)
}

func TestGetAgentToolValues(t *testing.T) {
for _, tt := range []struct {
name, field string
wantPresent bool
expected any
}{
{name: "omitted"},
{name: "null", field: `,"tools":null`, wantPresent: true},
{name: "empty", field: `,"tools":[]`, wantPresent: true, expected: []any{}},
} {
t.Run(tt.name, func(t *testing.T) {
body := strings.TrimSuffix(getAgentBody, "}") + tt.field + "}"
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/agents/agt_1"), httpmock.StringResponse(body))
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(get.NewGetCmd(f), "agt_1", out)
require.NoError(t, err)
var result map[string]any
require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
value, present := result["tools"]
assert.Equal(t, tt.wantPresent, present)
if tt.wantPresent {
assert.Equal(t, tt.expected, value)
}
r.Verify(t)
})
}
}

func TestGetAgentJSONPathErrorDoesNotExposeToolData(t *testing.T) {
const response = `{"id":"agt_1","name":"test-agent","instructions":"Hello","status":"draft","config":{},"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","tools":[{"type":"algolia_compare_products","name":"algolia_compare_products","description":"synthetic-sensitive-description"}]}`
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/agents/agt_1"), httpmock.StringResponse(response))
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(get.NewGetCmd(f), `agt_1 -o jsonpath={.tools[0].description[0]}`, out)
require.Error(t, err)
assert.NotContains(t, err.Error(), "synthetic-sensitive-description")
assert.NotContains(t, out.String(), "synthetic-sensitive-description")
r.Verify(t)
}
Loading
Loading