> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nagare.smtdfc.net/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Go

> Viết plugin Nagare bằng Go: đăng ký công cụ, kênh trò chuyện và system prompt.

## Cài đặt

```bash theme={null}
mkdir hello-plugin && cd hello-plugin
go mod init example.com/hello-plugin
go get github.com/smtdfc/nagare/pkgs/plugin/sdk
```

Tạo `metadata.json` như hướng dẫn trong [Tổng quan plugin](https://docs.nagare.smtdfc.net/plugins/overview.md#metadata-json).

## Ví dụ: plugin thêm công cụ

```go main.go theme={null}
package main

import (
	"context"
	_ "embed"
	"fmt"

	sdk "github.com/smtdfc/nagare/pkgs/plugin/sdk"
)

//go:embed metadata.json
var metadata string

type GreetArgs struct {
	Name string `json:"name" jsonschema:"description=Tên người cần chào"`
}

type GreetResult struct {
	Message string `json:"message"`
}

func main() {
	ctx := context.Background()
	plugin := sdk.NewPlugin()

	if _, err := plugin.LoadMetadata(metadata); err != nil {
		panic(err)
	}

	greet := sdk.DefineTool[GreetArgs, GreetResult](
		"greet_tool",
		"Tạo lời chào cho một người.",
		func(ctx *context.Context, args *GreetArgs) (*GreetResult, error) {
			return &GreetResult{Message: fmt.Sprintf("Xin chào, %s!", args.Name)}, nil
		},
		[]string{"greeting"},
	)

	err := plugin.Start(ctx, func() {
		if err := plugin.Handshake(ctx); err != nil {
			plugin.Logger.Error("handshake failed", "error", err)
			return
		}

		_ = plugin.RegisterToolCategories(ctx, map[string]string{
			"greeting": "Công cụ tạo lời chào",
		})

		if err := plugin.RegisterPluginTool(ctx, greet); err != nil {
			plugin.Logger.Error("register tool failed", "error", err)
		}
	})
	if err != nil {
		plugin.Logger.Error("plugin stopped", "error", err)
	}
}
```

`metadata.json` của plugin này cần có `"features": ["plugin_tool"]`.

Build và cài đặt:

```bash theme={null}
nagare plugin build
# Tạo ra <package_name>.nagare_plugin
```

## Vòng đời

1. `sdk.NewPlugin()` tạo client, đọc `NAGARE_PLUGIN_LOG_FILE`, `NAGARE_PLUGIN_CONFIG_DIR`, `NAGARE_PLUGIN_DATA_DIR`.
2. `LoadMetadata(raw)` nạp và kiểm tra metadata. Thường dùng `//go:embed metadata.json`.
3. `Start(ctx, onStart)` kết nối tới gateway, gọi `onStart` rồi chờ cho đến khi kết nối đóng.
4. Trong `onStart`, **luôn gọi `Handshake(ctx)` trước** mọi lệnh khác.

## Tham chiếu API

### Công cụ

| Hàm | Mô tả |
| - | - |
| `sdk.DefineTool[I, O](name, description, callback, categories)` | Định nghĩa công cụ. Schema tham số được sinh tự động từ kiểu `I`. Callback có dạng `func(ctx *context.Context, args *I) (*O, error)`. |
| `RegisterPluginTool(ctx, tool)` | Đăng ký công cụ với gateway. Cần feature `plugin_tool`. |
| `RegisterToolCategories(ctx, map[string]string)` | Đăng ký danh mục mới (tên → mô tả) để agent tìm thấy công cụ. |

Mỗi lần gọi công cụ có thời gian chờ tối đa 60 giây.

### Trò chuyện (feature `chat`)

| Hàm / trường | Mô tả |
| - | - |
| `PrepareChatChannel(ctx, channelID)` | Tạo hoặc mở lại kênh trò chuyện với ID do plugin tự đặt (ví dụ ID chat Telegram). |
| `SendChatMessage(ctx, channelID, text)` | Gửi tin nhắn của người dùng tới agent. |
| `ResetChatChannel(ctx, channelID)` | Bắt đầu phiên mới cho kênh. |
| `RegisterChatListener(ctx, sessionID)` | Nghe tin nhắn của một phiên có sẵn. |
| `SubmitToolApproval(ctx, channelID, requestID, accept)` | Gửi kết quả phê duyệt công cụ. |
| `OnReceivedChatMessage` | Callback `func(channelID, chunk string)` nhận từng đoạn phản hồi dạng JSON. Xem [định dạng tin nhắn](https://docs.nagare.smtdfc.net/plugins/overview.md#tin-nhan-tro-chuyen). |

### Khác

| Hàm / trường | Mô tả |
| - | - |
| `GetListModelProvider(ctx)` | Trả về `map[id]name` các nhà cung cấp mô hình. Cần feature `model_provider`. |
| `InjectSystemPrompt(ctx, content)` | Chèn system prompt của plugin (tối đa 64 KiB, thay thế prompt trước đó). Cần feature `system_prompt`. Phải chèn lại sau khi kết nối lại. |
| `ClearSystemPrompt(ctx)` | Xóa system prompt của plugin. |
| `Logger` | `*slog.Logger` ghi log JSON ra stdout và tệp log của plugin. |
| `ConfigDir`, `DataDir` | Thư mục cấu hình và dữ liệu riêng của plugin. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.