cli

package module
v0.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2025 License: MIT Imports: 16 Imported by: 0

README

kode cli

the standalone binary dependency only

Documentation

Overview

Package cli provides a client interface that wraps the kode CLI binary to provide the same programming interface as the chat package.

This package allows clients to interact with the kode CLI as a pure binary dependency via stdin/stdout using --json mode. The CLI converts events to Go function callbacks, making it feel identical to using the chat package directly.

Usage Example (CLI Binary):

import "github.com/xhd2015/kode-ai/cli"

// Create a client (identical interface to chat.NewClient)
client, err := cli.NewClient(cli.Config{
	Model: "gpt-4o",
	Token: "your-api-token",
})
if err != nil {
	panic(err)
}

// Use the client with functional options (identical to chat package)
response, err := client.Chat(ctx, "Hello, world!",
	cli.WithSystemPrompt("You are a helpful assistant"),
	cli.WithMaxRounds(3),
	cli.WithTools("list_dir", "read_file"),
	cli.WithEventCallback(func(event cli.Event) {
		fmt.Printf("Event: %s - %s\n", event.Type, event.Content)
	}),
	cli.WithToolCallback(func(ctx context.Context, call cli.ToolCall) (cli.ToolResult, bool, error) {
		// Custom tool handling - this now works with the stream protocol!
		if call.Name == "custom_tool" {
			return cli.ToolResult{
				Content: map[string]interface{}{
					"result": "Custom tool executed successfully",
				},
			}, true, nil
		}
		return cli.ToolResult{}, false, nil // Let builtin tools handle it
	}),
)

Usage Example (WebSocket Server):

import "github.com/xhd2015/kode-ai/cli"

// Connect to a WebSocket chat server
response, err := cli.ChatWithServer(ctx, "http://localhost:8080", types.Request{
	Message: "Hello, world!",
	SystemPrompt: "You are a helpful assistant",
	Tools: []string{"list_dir", "read_file"},
	EventCallback: func(event types.Message) {
		fmt.Printf("Event: %s - %s\n", event.Type, event.Content)
	},
	ToolCallback: func(ctx context.Context, stream types.StreamContext, call types.ToolCall) (types.ToolResult, bool, error) {
		// Custom tool handling via WebSocket stream protocol
		if call.Name == "custom_tool" {
			return types.ToolResult{
				Content: map[string]interface{}{
					"result": "Custom tool executed successfully",
				},
			}, true, nil
		}
		return types.ToolResult{}, false, nil // Let builtin tools handle it
	},
})

Key Features:

- Drop-in replacement for the chat package - Uses kode CLI binary with --json mode for communication - Supports all the same functional options (WithSystemPrompt, WithTools, etc.) - Provides event callbacks for real-time event processing - Supports custom tool callbacks via bidirectional stream protocol - Pure binary dependency - no need to import chat package dependencies - WebSocket server support for distributed chat systems

The client communicates with the kode CLI process via stdin/stdout using JSON messages. Events from the CLI are parsed and converted to Go function callbacks. Tool callbacks use a bidirectional stream protocol where the CLI sends tool_call_request messages and waits for tool_call_response messages, providing a seamless integration experience.

The ChatWithServer function connects to a WebSocket server running the chat-server subcommand, allowing for distributed chat systems where the AI processing happens on a remote server while maintaining the same programming interface.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Chat

func Chat(ctx context.Context, req types.Request, opts ...CliOption) (*types.Response, error)

func ChatWithServer added in v0.0.3

func ChatWithServer(ctx context.Context, server string, req types.Request) (*types.Response, error)

ChatWithServer connects to a WebSocket chat server and streams events until finished

func LinesWritter

func LinesWritter(callback func(line string) bool, opts ...LinesWritterOption) (io.Writer, func())

func WithCache

func WithCache(enabled bool) types.ChatOption

WithCache controls whether caching is enabled (default: true)

func WithDefaultToolCwd

func WithDefaultToolCwd(cwd string) types.ChatOption

WithDefaultToolCwd sets the default working directory for tool execution

func WithEventCallback

func WithEventCallback(callback types.EventCallback) types.ChatOption

WithEventCallback sets a callback for receiving events during chat processing

func WithFollowUpCallback

func WithFollowUpCallback(callback types.FollowUpCallback) types.ChatOption

WithFollowUpCallback sets a callback for follow-up tool execution

func WithHistory

func WithHistory(messages []types.Message) types.ChatOption

WithHistory provides historical messages for conversation context

func WithMCPServers

func WithMCPServers(servers ...string) types.ChatOption

WithMCPServers specifies MCP servers to connect to

func WithMaxRounds

func WithMaxRounds(rounds int) types.ChatOption

WithMaxRounds sets the maximum number of conversation rounds

func WithStdStream

func WithStdStream(stdin io.Reader, stdout io.Writer) types.ChatOption

WithStdStream sets stdin and stdout for bidirectional tool callback communication

func WithSystemPrompt

func WithSystemPrompt(prompt string) types.ChatOption

WithSystemPrompt sets the system prompt for the conversation

func WithToolCallback

func WithToolCallback(callback types.ToolCallback) types.ChatOption

WithToolCallback sets a custom tool execution callback

func WithToolDefinitions

func WithToolDefinitions(tool ...*types.UnifiedTool) types.ChatOption

func WithToolFiles

func WithToolFiles(files ...string) types.ChatOption

WithToolFiles specifies custom tool definition files to load

func WithToolJSONs added in v0.0.3

func WithToolJSONs(jsons ...string) types.ChatOption

WithToolJSONs specifies custom tool definitions as JSON strings

func WithTools

func WithTools(tools ...string) types.ChatOption

WithTools specifies the builtin tools to make available

Types

type AskOptions

type AskOptions struct {
	Token    string
	TraceID  string
	RecordID int64
	Prompt   string
	Model    string
	Logger   types.Logger
}

type ChatOptions

type ChatOptions struct {
	Token          string
	MaxRound       int
	System         string
	ToolDefaultCwd string
	Tools          []string
	ToolCustom     []string
	ToolCustomJson []string

	Record           string             // record file
	RecordData       []byte             // record data to write to tmp file
	UpdateRecordData func([]byte) error // callback to update record data after spl cli returns

	LogChat bool
	Logger  types.Logger
}

type CliOption

type CliOption func(cfg *CliOptionConfig)

func WithCli

func WithCli(cli string, args ...string) CliOption

func WithDir

func WithDir(dir string) CliOption

func WithEnv

func WithEnv(envs ...string) CliOption

type CliOptionConfig

type CliOptionConfig struct {
	// contains filtered or unexported fields
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents the CLI-based chat client

Example

ExampleClient demonstrates how to use the CLI client

// Create a CLI-based client (feels identical to chat.NewClient)
client, err := NewClient(types.Config{
	Model: "gpt-4o",
	Token: "your-api-token",
})
if err != nil {
	panic(err)
}

ctx := context.Background()

// Use the client with functional options (identical to chat package)
response, err := client.Chat(ctx, "Hello, world!",
	WithSystemPrompt("You are a helpful assistant"),
	WithMaxRounds(3),
	WithTools("list_dir", "read_file"),
	WithEventCallback(func(event types.Message) {
		fmt.Printf("Event: %s - %s\n", event.Type, event.Content)
	}),
	WithToolCallback(func(ctx context.Context, stream types.StreamContext, call types.ToolCall) (types.ToolResult, bool, error) {
		// Custom tool handling
		if call.Name == "custom_tool" {
			return types.ToolResult{
				Content: map[string]interface{}{
					"result": "Custom tool executed successfully",
				},
			}, true, nil
		}
		return types.ToolResult{}, false, nil // Let builtin tools handle it
	}),
)

if err != nil {
	panic(err)
}

fmt.Printf("Response: %+v\n", response)

func NewClient

func NewClient(config types.Config) (*Client, error)

NewClient creates a new CLI-based chat client

func (*Client) Chat added in v0.0.3

func (c *Client) Chat(ctx context.Context, message string, opts ...types.ChatOption) (*types.Response, error)

Chat performs a chat conversation using the CLI binary

type LinesWritterOption

type LinesWritterOption func(cfg *linesWritterOption)

func WithEndCallback

func WithEndCallback(callback func(err error)) LinesWritterOption

type RunCLIOptions

type RunCLIOptions struct {
	Cli string
	Dir string

	Env []string

	NoCheckUpgrade bool // If true, add SPL_CHECK_UPGRADE=false to environment

	Logger types.Logger
}

type Runner

type Runner interface {
	Stream(ctx context.Context, stdout io.Writer) error
	Output(ctx context.Context) (string, error)
}

Runner defines the interface for command runners

func RunCommand

func RunCommand(ctx context.Context, args []string, opts RunCLIOptions) (Runner, error)

RunCommand executes a general spl command with the given arguments

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL