feat(plugins): add source-control extension contracts (#2117)

This commit is contained in:
José Almeida
2026-08-13 08:29:29 +01:00
committed by GitHub
parent 064b852884
commit f218880ecb
530 changed files with 39054 additions and 7518 deletions
@@ -0,0 +1,84 @@
package pluginsdk
import (
"fmt"
"net/http"
)
// ActionErrorCode is a transport-independent failure category plugins can use
// when turning domain errors into stable action responses.
type ActionErrorCode string
const (
ActionErrorInvalidArgument ActionErrorCode = "invalid_argument"
ActionErrorUnauthenticated ActionErrorCode = "unauthenticated"
ActionErrorPermissionDenied ActionErrorCode = "permission_denied"
ActionErrorNotFound ActionErrorCode = "not_found"
ActionErrorConflict ActionErrorCode = "conflict"
ActionErrorRateLimited ActionErrorCode = "rate_limited"
ActionErrorUnavailable ActionErrorCode = "unavailable"
ActionErrorUpstream ActionErrorCode = "upstream"
)
// ActionError preserves a machine-readable category and optional retry hint.
// Plugins should return sanitized response bodies; Err is retained only for
// errors.Is/errors.As and local diagnostics.
type ActionError struct {
Code ActionErrorCode
RetryAfter string
Err error
}
func (e *ActionError) Error() string {
if e == nil {
return "plugin action failed"
}
if e.Err != nil {
return fmt.Sprintf("plugin action %s: %v", e.Code, e.Err)
}
return fmt.Sprintf("plugin action %s", e.Code)
}
func (e *ActionError) Unwrap() error {
if e == nil {
return nil
}
return e.Err
}
// CategorizeActionError wraps err without flattening its cause.
func CategorizeActionError(code ActionErrorCode, err error) error {
return CategorizeActionErrorWithRetry(code, "", err)
}
// CategorizeActionErrorWithRetry also projects a provider-neutral Retry-After
// value without flattening the original error.
func CategorizeActionErrorWithRetry(code ActionErrorCode, retryAfter string, err error) error {
if err == nil {
return nil
}
return &ActionError{Code: code, RetryAfter: retryAfter, Err: err}
}
// ActionErrorHTTPStatus is the shared action-category projection used by
// plugins. Unknown future categories fail closed as an upstream failure.
func ActionErrorHTTPStatus(code ActionErrorCode) int {
switch code {
case ActionErrorInvalidArgument:
return http.StatusBadRequest
case ActionErrorUnauthenticated:
return http.StatusUnauthorized
case ActionErrorPermissionDenied:
return http.StatusForbidden
case ActionErrorNotFound:
return http.StatusNotFound
case ActionErrorConflict:
return http.StatusConflict
case ActionErrorRateLimited:
return http.StatusTooManyRequests
case ActionErrorUnavailable:
return http.StatusServiceUnavailable
default:
return http.StatusBadGateway
}
}
@@ -0,0 +1,55 @@
package pluginsdk
import (
"errors"
"net/http"
"testing"
)
func TestCategorizeActionErrorPreservesCause(t *testing.T) {
cause := errors.New("provider rejected request")
err := CategorizeActionError(ActionErrorConflict, cause)
if !errors.Is(err, cause) {
t.Fatal("categorized action error lost its cause")
}
var categorized *ActionError
if !errors.As(err, &categorized) || categorized.Code != ActionErrorConflict {
t.Fatalf("categorized error = %#v", categorized)
}
}
func TestActionErrorHTTPStatusIsStableAcrossPlugins(t *testing.T) {
tests := map[ActionErrorCode]int{
ActionErrorInvalidArgument: http.StatusBadRequest,
ActionErrorUnauthenticated: http.StatusUnauthorized,
ActionErrorPermissionDenied: http.StatusForbidden,
ActionErrorNotFound: http.StatusNotFound,
ActionErrorConflict: http.StatusConflict,
ActionErrorRateLimited: http.StatusTooManyRequests,
ActionErrorUnavailable: http.StatusServiceUnavailable,
ActionErrorUpstream: http.StatusBadGateway,
}
for code, want := range tests {
if got := ActionErrorHTTPStatus(code); got != want {
t.Fatalf("ActionErrorHTTPStatus(%q) = %d, want %d", code, got, want)
}
}
if got := ActionErrorHTTPStatus(ActionErrorCode("future")); got != http.StatusBadGateway {
t.Fatalf("unknown action code status = %d", got)
}
}
func TestCategorizeActionErrorWithRetryPreservesStableMetadata(t *testing.T) {
cause := errors.New("provider throttled request")
err := CategorizeActionErrorWithRetry(ActionErrorRateLimited, "120", cause)
var categorized *ActionError
if !errors.As(err, &categorized) {
t.Fatal("categorized error metadata is unavailable")
}
if categorized.Code != ActionErrorRateLimited || categorized.RetryAfter != "120" {
t.Fatalf("categorized error = %#v", categorized)
}
if !errors.Is(err, cause) {
t.Fatal("categorized retry error lost its cause")
}
}
+217 -29
View File
@@ -61,18 +61,20 @@ func pageInfoFromProto(p *pluginv1.PageInfo) *PageInfo {
// TaskRepository is the Go-native mirror of kandev.plugin.v1.TaskRepository.
type TaskRepository struct {
ID string
RepositoryID string
BaseBranch string
Position int32
ID string
RepositoryID string
BaseBranch string
Position int32
CheckoutBranch string
}
func (r TaskRepository) toProto() *pluginv1.TaskRepository {
return &pluginv1.TaskRepository{
Id: r.ID,
RepositoryId: r.RepositoryID,
BaseBranch: r.BaseBranch,
Position: r.Position,
Id: r.ID,
RepositoryId: r.RepositoryID,
BaseBranch: r.BaseBranch,
Position: r.Position,
CheckoutBranch: r.CheckoutBranch,
}
}
@@ -81,10 +83,11 @@ func taskRepositoryFromProto(p *pluginv1.TaskRepository) TaskRepository {
return TaskRepository{}
}
return TaskRepository{
ID: p.GetId(),
RepositoryID: p.GetRepositoryId(),
BaseBranch: p.GetBaseBranch(),
Position: p.GetPosition(),
ID: p.GetId(),
RepositoryID: p.GetRepositoryId(),
BaseBranch: p.GetBaseBranch(),
Position: p.GetPosition(),
CheckoutBranch: p.GetCheckoutBranch(),
}
}
@@ -427,6 +430,46 @@ type AgentProfile struct {
Mode string
}
// ExecutorProfile is the Go-native mirror of kandev.plugin.v1.ExecutorProfile.
type ExecutorProfile struct {
ID string
DisplayName string
ExecutorType string
}
func (e ExecutorProfile) toProto() *pluginv1.ExecutorProfile {
return &pluginv1.ExecutorProfile{Id: e.ID, DisplayName: e.DisplayName, ExecutorType: e.ExecutorType}
}
func executorProfileFromProto(p *pluginv1.ExecutorProfile) ExecutorProfile {
if p == nil {
return ExecutorProfile{}
}
return ExecutorProfile{ID: p.GetId(), DisplayName: p.GetDisplayName(), ExecutorType: p.GetExecutorType()}
}
func executorProfilesFromProto(profiles []*pluginv1.ExecutorProfile) []ExecutorProfile {
if profiles == nil {
return nil
}
out := make([]ExecutorProfile, len(profiles))
for i, profile := range profiles {
out[i] = executorProfileFromProto(profile)
}
return out
}
func executorProfilesToProto(profiles []ExecutorProfile) []*pluginv1.ExecutorProfile {
if profiles == nil {
return nil
}
out := make([]*pluginv1.ExecutorProfile, len(profiles))
for i, profile := range profiles {
out[i] = profile.toProto()
}
return out
}
func (a AgentProfile) toProto() *pluginv1.AgentProfile {
return &pluginv1.AgentProfile{
Id: a.ID,
@@ -476,18 +519,34 @@ func agentProfilesToProto(items []AgentProfile) []*pluginv1.AgentProfile {
// Repository is the Go-native mirror of kandev.plugin.v1.Repository.
type Repository struct {
ID string
WorkspaceID string
Name string
DefaultBranch *string
ID string
WorkspaceID string
Name string
DefaultBranch *string
SourceType string
ProviderID string
ProviderRepositoryID string
ProviderHost string
ProviderScope string
OwnerOrProject string
ProviderName string
RemoteURL string
}
func (r Repository) toProto() *pluginv1.Repository {
return &pluginv1.Repository{
Id: r.ID,
WorkspaceId: r.WorkspaceID,
Name: r.Name,
DefaultBranch: r.DefaultBranch,
Id: r.ID,
WorkspaceId: r.WorkspaceID,
Name: r.Name,
DefaultBranch: r.DefaultBranch,
SourceType: r.SourceType,
ProviderId: r.ProviderID,
ProviderRepositoryId: r.ProviderRepositoryID,
ProviderHost: r.ProviderHost,
ProviderScope: r.ProviderScope,
OwnerOrProject: r.OwnerOrProject,
ProviderName: r.ProviderName,
RemoteUrl: r.RemoteURL,
}
}
@@ -496,10 +555,18 @@ func repositoryFromProto(p *pluginv1.Repository) Repository {
return Repository{}
}
return Repository{
ID: p.GetId(),
WorkspaceID: p.GetWorkspaceId(),
Name: p.GetName(),
DefaultBranch: p.DefaultBranch,
ID: p.GetId(),
WorkspaceID: p.GetWorkspaceId(),
Name: p.GetName(),
DefaultBranch: p.DefaultBranch,
SourceType: p.GetSourceType(),
ProviderID: p.GetProviderId(),
ProviderRepositoryID: p.GetProviderRepositoryId(),
ProviderHost: p.GetProviderHost(),
ProviderScope: p.GetProviderScope(),
OwnerOrProject: p.GetOwnerOrProject(),
ProviderName: p.GetProviderName(),
RemoteURL: p.GetRemoteUrl(),
}
}
@@ -798,10 +865,17 @@ type CreateTaskInput struct {
// StartAgent asks the host to auto-launch an agent on the created task,
// mirroring the REST/MCP create_task start_agent flag. Best-effort: a
// launch failure does not fail task creation.
StartAgent bool
StartAgent bool
Repositories []PluginTaskRepository
Launch *PluginTaskLaunchOptions
Metadata map[string]any
}
func (in CreateTaskInput) toProto() *pluginv1.CreateTaskRequest {
func (in CreateTaskInput) toProto() (*pluginv1.CreateTaskRequest, error) {
metadata, err := mapToStruct(in.Metadata)
if err != nil {
return nil, fmt.Errorf("pluginsdk: task metadata: %w", err)
}
return &pluginv1.CreateTaskRequest{
WorkspaceId: in.WorkspaceID,
WorkflowId: in.WorkflowID,
@@ -810,12 +884,19 @@ func (in CreateTaskInput) toProto() *pluginv1.CreateTaskRequest {
Description: in.Description,
ParentId: in.ParentID,
StartAgent: in.StartAgent,
}
Repositories: pluginTaskRepositoriesToProto(in.Repositories),
Launch: in.Launch.toProto(),
Metadata: metadata,
}, nil
}
func createTaskInputFromProto(p *pluginv1.CreateTaskRequest) CreateTaskInput {
func createTaskInputFromProto(p *pluginv1.CreateTaskRequest) (CreateTaskInput, error) {
if p == nil {
return CreateTaskInput{}
return CreateTaskInput{}, nil
}
metadata, err := structToMap(p.GetMetadata())
if err != nil {
return CreateTaskInput{}, fmt.Errorf("pluginsdk: task metadata: %w", err)
}
return CreateTaskInput{
WorkspaceID: p.GetWorkspaceId(),
@@ -825,7 +906,114 @@ func createTaskInputFromProto(p *pluginv1.CreateTaskRequest) CreateTaskInput {
Description: p.GetDescription(),
ParentID: p.ParentId,
StartAgent: p.GetStartAgent(),
Repositories: pluginTaskRepositoriesFromProto(p.GetRepositories()),
Launch: pluginTaskLaunchOptionsFromProto(p.GetLaunch()),
Metadata: metadata,
}, nil
}
// RemoteRepositoryDescriptor is a fully resolved plugin-provider repository
// identity. CloneURL is exact and credential-free; the host must not rebuild it.
type RemoteRepositoryDescriptor struct {
ProviderID string
ProviderHost string
ProviderScope string
OwnerOrProject string
ProviderRepositoryID string
Name string
CloneURL string
DefaultBranch *string
BaseBranch *string
HeadBranch *string
PullRequestNumber *int64
}
func (d *RemoteRepositoryDescriptor) toProto() *pluginv1.RemoteRepositoryDescriptor {
if d == nil {
return nil
}
return &pluginv1.RemoteRepositoryDescriptor{
ProviderId: d.ProviderID, ProviderHost: d.ProviderHost, ProviderScope: d.ProviderScope, OwnerOrProject: d.OwnerOrProject,
ProviderRepositoryId: d.ProviderRepositoryID, Name: d.Name, CloneUrl: d.CloneURL,
DefaultBranch: d.DefaultBranch, BaseBranch: d.BaseBranch, HeadBranch: d.HeadBranch, PullRequestNumber: d.PullRequestNumber,
}
}
func remoteRepositoryDescriptorFromProto(p *pluginv1.RemoteRepositoryDescriptor) *RemoteRepositoryDescriptor {
if p == nil {
return nil
}
return &RemoteRepositoryDescriptor{
ProviderID: p.GetProviderId(), ProviderHost: p.GetProviderHost(), ProviderScope: p.GetProviderScope(), OwnerOrProject: p.GetOwnerOrProject(),
ProviderRepositoryID: p.GetProviderRepositoryId(), Name: p.GetName(), CloneURL: p.GetCloneUrl(),
DefaultBranch: p.DefaultBranch, BaseBranch: p.BaseBranch, HeadBranch: p.HeadBranch, PullRequestNumber: p.PullRequestNumber,
}
}
// PluginTaskRepository selects an existing repository or a complete remote
// descriptor to attach when a plugin creates a task.
type PluginTaskRepository struct {
RepositoryID string
Remote *RemoteRepositoryDescriptor
BaseBranch *string
CheckoutBranch *string
PullRequestNumber *int64
}
func (r PluginTaskRepository) toProto() *pluginv1.PluginTaskRepository {
return &pluginv1.PluginTaskRepository{RepositoryId: r.RepositoryID, Remote: r.Remote.toProto(), BaseBranch: r.BaseBranch, CheckoutBranch: r.CheckoutBranch, PullRequestNumber: r.PullRequestNumber}
}
func pluginTaskRepositoryFromProto(p *pluginv1.PluginTaskRepository) PluginTaskRepository {
if p == nil {
return PluginTaskRepository{}
}
return PluginTaskRepository{RepositoryID: p.GetRepositoryId(), Remote: remoteRepositoryDescriptorFromProto(p.GetRemote()), BaseBranch: p.BaseBranch, CheckoutBranch: p.CheckoutBranch, PullRequestNumber: p.PullRequestNumber}
}
func pluginTaskRepositoriesToProto(repositories []PluginTaskRepository) []*pluginv1.PluginTaskRepository {
if repositories == nil {
return nil
}
out := make([]*pluginv1.PluginTaskRepository, len(repositories))
for i, repository := range repositories {
out[i] = repository.toProto()
}
return out
}
func pluginTaskRepositoriesFromProto(repositories []*pluginv1.PluginTaskRepository) []PluginTaskRepository {
if repositories == nil {
return nil
}
out := make([]PluginTaskRepository, len(repositories))
for i, repository := range repositories {
out[i] = pluginTaskRepositoryFromProto(repository)
}
return out
}
// PluginTaskLaunchOptions declares the optional launch context for a plugin-
// created task. Host implementation validates each value before use.
type PluginTaskLaunchOptions struct {
AgentProfileID *string
ExecutorProfileID *string
Prompt *string
PlanMode *string
}
func (o *PluginTaskLaunchOptions) toProto() *pluginv1.PluginTaskLaunchOptions {
if o == nil {
return nil
}
return &pluginv1.PluginTaskLaunchOptions{AgentProfileId: o.AgentProfileID, ExecutorProfileId: o.ExecutorProfileID, Prompt: o.Prompt, PlanMode: o.PlanMode}
}
func pluginTaskLaunchOptionsFromProto(p *pluginv1.PluginTaskLaunchOptions) *PluginTaskLaunchOptions {
if p == nil {
return nil
}
return &PluginTaskLaunchOptions{AgentProfileID: p.AgentProfileId, ExecutorProfileID: p.ExecutorProfileId, Prompt: p.Prompt, PlanMode: p.PlanMode}
}
// UpdateTaskInput is the Go-native mirror of
+51 -5
View File
@@ -47,7 +47,7 @@ func TestTaskProtoRoundTrip(t *testing.T) {
Identifier: "PROJ-42",
IsEphemeral: false,
Repositories: []TaskRepository{
{ID: "tr-1", RepositoryID: "repo-1", BaseBranch: "main", Position: 0},
{ID: "tr-1", RepositoryID: "repo-1", BaseBranch: "main", Position: 0, CheckoutBranch: "feature/fix"},
{ID: "tr-2", RepositoryID: "repo-2", BaseBranch: "develop", Position: 1},
},
Metadata: map[string]any{"source": "plugin:agent-stats", "count": float64(3)},
@@ -58,6 +58,8 @@ func TestTaskProtoRoundTrip(t *testing.T) {
require.Equal(t, "task-1", proto.GetId())
require.Equal(t, "2026-07-15T12:01:00Z", proto.GetStartedAt())
require.Nil(t, proto.CompletedAt)
require.Equal(t, "feature/fix", proto.GetRepositories()[0].GetCheckoutBranch())
require.Empty(t, proto.GetRepositories()[1].GetCheckoutBranch(), "empty checkout branches remain wire-compatible")
back, err := taskFromProto(proto)
require.NoError(t, err)
@@ -150,12 +152,54 @@ func TestAgentProfileProtoRoundTrip(t *testing.T) {
require.Equal(t, profile, agentProfileFromProto(proto))
}
func TestExecutorProfileProtoRoundTrip(t *testing.T) {
profile := ExecutorProfile{ID: "exec-1", DisplayName: "Local Docker", ExecutorType: "local_docker"}
require.Equal(t, profile, executorProfileFromProto(profile.toProto()))
}
func TestCreateTaskInputRichProtoRoundTrip(t *testing.T) {
defaultBranch := "main"
baseBranch := "release"
headBranch := "feature/plugin"
checkoutBranch := "feature/plugin"
pullRequestNumber := int64(42)
prompt := "Implement the fix"
input := CreateTaskInput{
WorkspaceID: "ws-1",
WorkflowID: "wf-1",
Title: "Plugin-created task",
Repositories: []PluginTaskRepository{{
Remote: &RemoteRepositoryDescriptor{
ProviderID: "example", ProviderHost: "code.example.test", OwnerOrProject: "team",
ProviderRepositoryID: "repo-42", Name: "api", CloneURL: "https://code.example.test/scm/team/api.git",
DefaultBranch: &defaultBranch, BaseBranch: &baseBranch, HeadBranch: &headBranch, PullRequestNumber: &pullRequestNumber,
},
BaseBranch: &baseBranch, CheckoutBranch: &checkoutBranch, PullRequestNumber: &pullRequestNumber,
}},
Launch: &PluginTaskLaunchOptions{AgentProfileID: strPtr("agent-1"), ExecutorProfileID: strPtr("exec-1"), Prompt: &prompt, PlanMode: strPtr("replace")},
Metadata: map[string]any{"watch_id": "watch-1"},
}
proto, err := input.toProto()
require.NoError(t, err)
back, err := createTaskInputFromProto(proto)
require.NoError(t, err)
require.Equal(t, input, back)
}
func TestRepositoryProtoRoundTrip(t *testing.T) {
repo := Repository{
ID: "repo-1",
WorkspaceID: "ws-1",
Name: "kdlbs/kandev",
DefaultBranch: strPtr("main"),
ID: "repo-1",
WorkspaceID: "ws-1",
Name: "kdlbs/kandev",
DefaultBranch: strPtr("main"),
SourceType: "provider",
ProviderID: "example-vcs",
ProviderRepositoryID: "repo-42",
ProviderHost: "code.example.test",
OwnerOrProject: "team",
ProviderName: "kandev",
RemoteURL: "https://code.example.test/scm/team/kandev.git",
}
proto := repo.toProto()
require.Equal(t, repo, repositoryFromProto(proto))
@@ -163,6 +207,8 @@ func TestRepositoryProtoRoundTrip(t *testing.T) {
repoNoBranch := Repository{ID: "repo-2", WorkspaceID: "ws-1", Name: "kdlbs/other"}
protoNoBranch := repoNoBranch.toProto()
require.Nil(t, protoNoBranch.DefaultBranch)
require.Empty(t, protoNoBranch.GetProviderId(), "new origin fields preserve empty compatibility")
require.Empty(t, protoNoBranch.GetRemoteUrl(), "new origin fields preserve empty compatibility")
require.Equal(t, repoNoBranch, repositoryFromProto(protoNoBranch))
}
+174 -2
View File
@@ -177,6 +177,25 @@ type AgentProfileReader interface {
List(ctx context.Context, page Page) ([]AgentProfile, *PageInfo, error)
}
// ExecutorProfileHost is an optional Host extension. It is kept separate from
// Host so existing host implementations remain source-compatible.
type ExecutorProfileHost interface {
ExecutorProfiles() ExecutorProfileReader
}
type ExecutorProfileReader interface {
List(ctx context.Context, page Page) ([]ExecutorProfile, *PageInfo, error)
}
// ExecutorProfiles returns the optional executor-profile reader.
func ExecutorProfiles(host Host) (ExecutorProfileReader, bool) {
provider, ok := host.(ExecutorProfileHost)
if !ok {
return nil, false
}
return provider.ExecutorProfiles(), true
}
// RepositoryReader is the read-only accessor behind Host.Repositories(),
// mirroring the Host data API's ListRepositories RPC.
type RepositoryReader interface {
@@ -202,6 +221,30 @@ type MessageReader interface {
Send(ctx context.Context, taskID, sessionID, text string) (*MessageDispatch, error)
}
// PluginOwnedTaskTreeHost is an optional host extension for previewing and
// deleting only task trees whose source provenance matches the caller.
type PluginOwnedTaskTreeHost interface {
PluginOwnedTaskTrees() PluginOwnedTaskTreeManager
}
type PluginOwnedTaskTreeManager interface {
Preview(ctx context.Context, rootTaskID string) ([]Task, error)
// Delete removes descendants before their parent and treats an absent root
// as an idempotent success. A non-nil error may be
// accompanied by deleted task ids when the backing store failed part-way;
// callers must reconcile those ids before retrying the remaining cleanup.
Delete(ctx context.Context, rootTaskID string) ([]string, error)
}
// PluginOwnedTaskTrees returns the optional provenance-safe task-tree manager.
func PluginOwnedTaskTrees(host Host) (PluginOwnedTaskTreeManager, bool) {
manager, ok := host.(PluginOwnedTaskTreeHost)
if !ok {
return nil, false
}
return manager.PluginOwnedTaskTrees(), true
}
// newHostClient wraps a *grpc.ClientConn (dialed over the go-plugin broker)
// as a Go-native Host implementation.
func newHostClient(conn *grpc.ClientConn) Host {
@@ -212,6 +255,14 @@ type grpcHostClient struct {
client pluginv1.HostClient
}
func (h *grpcHostClient) ExecutorProfiles() ExecutorProfileReader {
return grpcExecutorProfileReader{client: h.client}
}
func (h *grpcHostClient) PluginOwnedTaskTrees() PluginOwnedTaskTreeManager {
return grpcPluginOwnedTaskTreeManager{client: h.client}
}
func (h *grpcHostClient) GetState(ctx context.Context, scope, scopeID, key string) (map[string]any, bool, error) {
resp, err := h.client.GetState(ctx, &pluginv1.GetStateRequest{Scope: scope, ScopeId: scopeID, Key: key})
if err != nil {
@@ -361,7 +412,11 @@ func (r grpcTaskReader) Get(ctx context.Context, id string) (*Task, error) {
}
func (r grpcTaskReader) Create(ctx context.Context, in CreateTaskInput) (*Task, error) {
resp, err := r.client.CreateTask(ctx, in.toProto())
request, err := in.toProto()
if err != nil {
return nil, err
}
resp, err := r.client.CreateTask(ctx, request)
if err != nil {
return nil, err
}
@@ -444,6 +499,18 @@ type grpcAgentProfileReader struct {
client pluginv1.HostClient
}
type grpcExecutorProfileReader struct {
client pluginv1.HostClient
}
func (r grpcExecutorProfileReader) List(ctx context.Context, page Page) ([]ExecutorProfile, *PageInfo, error) {
resp, err := r.client.ListExecutorProfiles(ctx, &pluginv1.ListExecutorProfilesRequest{Page: page.toProto()})
if err != nil {
return nil, nil, err
}
return executorProfilesFromProto(resp.GetProfiles()), pageInfoFromProto(resp.GetPageInfo()), nil
}
func (r grpcAgentProfileReader) List(ctx context.Context, page Page) ([]AgentProfile, *PageInfo, error) {
resp, err := r.client.ListAgentProfiles(ctx, &pluginv1.ListAgentProfilesRequest{Page: page.toProto()})
if err != nil {
@@ -470,6 +537,35 @@ type grpcMessageReader struct {
client pluginv1.HostClient
}
type grpcPluginOwnedTaskTreeManager struct {
client pluginv1.HostClient
}
func (m grpcPluginOwnedTaskTreeManager) Preview(ctx context.Context, rootTaskID string) ([]Task, error) {
resp, err := m.client.PreviewPluginOwnedTaskTree(ctx, &pluginv1.PreviewPluginOwnedTaskTreeRequest{RootTaskId: rootTaskID})
if err != nil {
return nil, err
}
return tasksFromProto(resp.GetTasks())
}
func (m grpcPluginOwnedTaskTreeManager) Delete(ctx context.Context, rootTaskID string) ([]string, error) {
resp, err := m.client.DeletePluginOwnedTaskTree(ctx, &pluginv1.DeletePluginOwnedTaskTreeRequest{RootTaskId: rootTaskID})
if err != nil {
return deletedTaskIDsFromStatus(err), err
}
return resp.GetDeletedTaskIds(), nil
}
func deletedTaskIDsFromStatus(err error) []string {
for _, detail := range status.Convert(err).Details() {
if progress, ok := detail.(*pluginv1.DeletePluginOwnedTaskTreeProgress); ok {
return append([]string(nil), progress.GetDeletedTaskIds()...)
}
}
return nil
}
func (r grpcMessageReader) List(ctx context.Context, filter MessageFilter, page Page) ([]Message, *PageInfo, error) {
resp, err := r.client.ListMessages(ctx, &pluginv1.ListMessagesRequest{Filter: filter.toProto(), Page: page.toProto()})
if err != nil {
@@ -690,6 +786,18 @@ func (s *grpcHostServer) ListAgentProfiles(ctx context.Context, req *pluginv1.Li
return &pluginv1.ListAgentProfilesResponse{Profiles: agentProfilesToProto(profiles), PageInfo: pageInfo.toProto()}, nil
}
func (s *grpcHostServer) ListExecutorProfiles(ctx context.Context, req *pluginv1.ListExecutorProfilesRequest) (*pluginv1.ListExecutorProfilesResponse, error) {
provider, ok := s.impl.(ExecutorProfileHost)
if !ok {
return nil, errUnimplementedHostData("executor_profiles")
}
profiles, pageInfo, err := provider.ExecutorProfiles().List(ctx, pageFromProto(req.GetPage()))
if err != nil {
return nil, err
}
return &pluginv1.ListExecutorProfilesResponse{Profiles: executorProfilesToProto(profiles), PageInfo: pageInfo.toProto()}, nil
}
func (s *grpcHostServer) ListRepositories(ctx context.Context, req *pluginv1.ListRepositoriesRequest) (*pluginv1.ListRepositoriesResponse, error) {
page := pageFromProto(req.GetPage())
repos, pageInfo, err := s.impl.Repositories().List(ctx, req.GetWorkspaceId(), page)
@@ -740,7 +848,11 @@ func (s *grpcHostServer) ListMessages(ctx context.Context, req *pluginv1.ListMes
// might, and a plugin should get a gRPC error rather than a server panic.
func (s *grpcHostServer) CreateTask(ctx context.Context, req *pluginv1.CreateTaskRequest) (*pluginv1.CreateTaskResponse, error) {
task, err := s.impl.Tasks().Create(ctx, createTaskInputFromProto(req))
input, err := createTaskInputFromProto(req)
if err != nil {
return nil, err
}
task, err := s.impl.Tasks().Create(ctx, input)
if err != nil {
return nil, err
}
@@ -780,6 +892,43 @@ func (s *grpcHostServer) SendMessage(ctx context.Context, req *pluginv1.SendMess
return dispatch.toProto(), nil
}
func (s *grpcHostServer) PreviewPluginOwnedTaskTree(ctx context.Context, req *pluginv1.PreviewPluginOwnedTaskTreeRequest) (*pluginv1.PreviewPluginOwnedTaskTreeResponse, error) {
provider, ok := s.impl.(PluginOwnedTaskTreeHost)
if !ok {
return nil, errUnimplementedHostData("plugin_owned_task_trees")
}
tasks, err := provider.PluginOwnedTaskTrees().Preview(ctx, req.GetRootTaskId())
if err != nil {
return nil, err
}
protoTasks, err := tasksToProto(tasks)
if err != nil {
return nil, err
}
return &pluginv1.PreviewPluginOwnedTaskTreeResponse{Tasks: protoTasks}, nil
}
func (s *grpcHostServer) DeletePluginOwnedTaskTree(ctx context.Context, req *pluginv1.DeletePluginOwnedTaskTreeRequest) (*pluginv1.DeletePluginOwnedTaskTreeResponse, error) {
provider, ok := s.impl.(PluginOwnedTaskTreeHost)
if !ok {
return nil, errUnimplementedHostData("plugin_owned_task_trees")
}
deletedTaskIDs, err := provider.PluginOwnedTaskTrees().Delete(ctx, req.GetRootTaskId())
if err != nil {
if len(deletedTaskIDs) == 0 {
return nil, err
}
detailed, detailErr := status.Convert(err).WithDetails(
&pluginv1.DeletePluginOwnedTaskTreeProgress{DeletedTaskIds: deletedTaskIDs},
)
if detailErr != nil {
return nil, err
}
return nil, detailed.Err()
}
return &pluginv1.DeletePluginOwnedTaskTreeResponse{DeletedTaskIds: deletedTaskIDs}, nil
}
var _ pluginv1.HostServer = (*grpcHostServer)(nil)
// UnimplementedHostData is an embeddable default for the Host data API
@@ -800,11 +949,18 @@ func (UnimplementedHostData) Workflows() WorkflowReader { return unimplemented
func (UnimplementedHostData) AgentProfiles() AgentProfileReader {
return unimplementedAgentProfileReader{}
}
func (UnimplementedHostData) ExecutorProfiles() ExecutorProfileReader {
return unimplementedExecutorProfileReader{}
}
func (UnimplementedHostData) Repositories() RepositoryReader {
return unimplementedRepositoryReader{}
}
func (UnimplementedHostData) Messages() MessageReader { return unimplementedMessageReader{} }
func (UnimplementedHostData) PluginOwnedTaskTrees() PluginOwnedTaskTreeManager {
return unimplementedPluginOwnedTaskTreeManager{}
}
// InvokeUtilityAgent is the embeddable default for the agent_invoke Host
// method (ADR 0048). It lives on UnimplementedHostData — the shared
// "unimplemented Host extensions" embed both real Host implementations use —
@@ -868,6 +1024,12 @@ func (unimplementedAgentProfileReader) List(context.Context, Page) ([]AgentProfi
return nil, nil, errUnimplementedHostData("agent_profiles")
}
type unimplementedExecutorProfileReader struct{}
func (unimplementedExecutorProfileReader) List(context.Context, Page) ([]ExecutorProfile, *PageInfo, error) {
return nil, nil, errUnimplementedHostData("executor_profiles")
}
type unimplementedRepositoryReader struct{}
func (unimplementedRepositoryReader) List(context.Context, string, Page) ([]Repository, *PageInfo, error) {
@@ -883,3 +1045,13 @@ func (unimplementedMessageReader) List(context.Context, MessageFilter, Page) ([]
func (unimplementedMessageReader) Send(context.Context, string, string, string) (*MessageDispatch, error) {
return nil, errUnimplementedHostData("messages")
}
type unimplementedPluginOwnedTaskTreeManager struct{}
func (unimplementedPluginOwnedTaskTreeManager) Preview(context.Context, string) ([]Task, error) {
return nil, errUnimplementedHostData("plugin_owned_task_trees")
}
func (unimplementedPluginOwnedTaskTreeManager) Delete(context.Context, string) ([]string, error) {
return nil, errUnimplementedHostData("plugin_owned_task_trees")
}
+15 -4
View File
@@ -175,22 +175,29 @@ func (r dataRecordingMessageReader) Send(_ context.Context, taskID, sessionID, t
func TestHostData_TasksListAndGet(t *testing.T) {
impl := &dataRecordingHost{
tasks: map[string]Task{
"task-1": {ID: "task-1", Title: "Fix the bug", State: "todo"},
"task-1": {ID: "task-1", Title: "Fix the bug", State: "todo", Repositories: []TaskRepository{{
ID: "tr-1", RepositoryID: "repo-1", BaseBranch: "main", Position: 0, CheckoutBranch: "feature/fix",
}}},
},
taskList: []Task{{ID: "task-1", Title: "Fix the bug", State: "todo"}},
taskList: []Task{{ID: "task-1", Title: "Fix the bug", State: "todo", Repositories: []TaskRepository{{
ID: "tr-1", RepositoryID: "repo-1", BaseBranch: "main", Position: 0, CheckoutBranch: "feature/fix",
}}}},
taskPageInfo: &PageInfo{NextCursor: "next-1", HasMore: true},
}
host := dialHostOverBufconn(t, impl)
tasks, pageInfo, err := host.Tasks().List(context.Background(), TaskFilter{States: []string{"todo"}}, Page{Limit: 10})
require.NoError(t, err)
require.Equal(t, []Task{{ID: "task-1", Title: "Fix the bug", State: "todo"}}, tasks)
require.Equal(t, []Task{{ID: "task-1", Title: "Fix the bug", State: "todo", Repositories: []TaskRepository{{
ID: "tr-1", RepositoryID: "repo-1", BaseBranch: "main", Position: 0, CheckoutBranch: "feature/fix",
}}}}, tasks)
require.Equal(t, &PageInfo{NextCursor: "next-1", HasMore: true}, pageInfo)
require.Equal(t, TaskFilter{States: []string{"todo"}}, impl.lastTaskFilter)
task, err := host.Tasks().Get(context.Background(), "task-1")
require.NoError(t, err)
require.Equal(t, "Fix the bug", task.Title)
require.Equal(t, "feature/fix", task.Repositories[0].CheckoutBranch)
_, err = host.Tasks().Get(context.Background(), "missing")
require.Error(t, err)
@@ -326,7 +333,11 @@ func TestHostData_AgentProfiles(t *testing.T) {
}
func TestHostData_Repositories(t *testing.T) {
impl := &dataRecordingHost{repositories: []Repository{{ID: "repo-1", WorkspaceID: "ws-1", Name: "kdlbs/kandev"}}}
impl := &dataRecordingHost{repositories: []Repository{{
ID: "repo-1", WorkspaceID: "ws-1", Name: "team/kandev", SourceType: "provider", ProviderID: "example-vcs",
ProviderRepositoryID: "repo-42", ProviderHost: "code.example.test", OwnerOrProject: "team", ProviderName: "kandev",
RemoteURL: "https://code.example.test/scm/team/kandev.git",
}}}
host := dialHostOverBufconn(t, impl)
repos, _, err := host.Repositories().List(context.Background(), "ws-1", Page{})
+38
View File
@@ -8,7 +8,9 @@ import (
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
)
@@ -33,6 +35,27 @@ type recordingHost struct {
payload map[string]any
}
deleteStateCalled bool
taskTrees PluginOwnedTaskTreeManager
}
func (h *recordingHost) PluginOwnedTaskTrees() PluginOwnedTaskTreeManager {
if h.taskTrees != nil {
return h.taskTrees
}
return h.UnimplementedHostData.PluginOwnedTaskTrees()
}
type recordingTaskTreeManager struct {
deletedTaskIDs []string
err error
}
func (m recordingTaskTreeManager) Preview(context.Context, string) ([]Task, error) {
return nil, nil
}
func (m recordingTaskTreeManager) Delete(context.Context, string) ([]string, error) {
return m.deletedTaskIDs, m.err
}
func (h *recordingHost) GetState(ctx context.Context, scope, scopeID, key string) (map[string]any, bool, error) {
@@ -230,3 +253,18 @@ func TestHost_EmitEvent(t *testing.T) {
require.Equal(t, "custom.thing", impl.emitEvent.name)
require.Equal(t, map[string]any{"a": float64(1)}, impl.emitEvent.payload)
}
func TestHost_DeletePluginOwnedTaskTree_PreservesPartialProgressOverWire(t *testing.T) {
impl := &recordingHost{taskTrees: recordingTaskTreeManager{
deletedTaskIDs: []string{"grandchild", "child"},
err: status.Error(codes.Unavailable, "task store became unavailable"),
}}
host := dialHostOverBufconn(t, impl)
manager, ok := PluginOwnedTaskTrees(host)
require.True(t, ok)
deletedTaskIDs, err := manager.Delete(context.Background(), "root")
require.Equal(t, []string{"grandchild", "child"}, deletedTaskIDs)
require.Equal(t, codes.Unavailable, status.Code(err))
}
+48
View File
@@ -22,6 +22,54 @@ type Plugin interface {
HandleWebhook(ctx context.Context, req *WebhookRequest) (*WebhookResponse, error)
}
// ActionHandler is an optional browser-action extension. Keeping it separate
// from Plugin preserves source compatibility for plugins that only handle
// events and public webhooks.
type ActionHandler interface {
HandleAction(context.Context, *PluginActionRequest) (*PluginActionResponse, error)
}
// EntityReferenceSearcher is an optional manifest-owned composer source.
type EntityReferenceSearcher interface {
SearchEntityReferences(context.Context, *SearchEntityReferencesRequest) (*SearchEntityReferencesResponse, error)
}
// EntityReferenceAuthorizer is an optional live authorization extension for
// canonical composer references.
type EntityReferenceAuthorizer interface {
AuthorizeEntityReference(context.Context, *AuthorizeEntityReferenceRequest) (*AuthorizeEntityReferenceResponse, error)
}
// EntityReferenceHandler is the convenient optional extension for plugins
// that own a complete reference source. The narrower interfaces above remain
// available so the transport can return a precise unsupported error per RPC.
type EntityReferenceHandler interface {
EntityReferenceSearcher
EntityReferenceAuthorizer
}
// GitCredentialResolver is an optional provider-neutral credential resolver.
// Returned credentials are transient and must never be logged or persisted.
type GitCredentialResolver interface {
ResolveGitCredential(context.Context, *ResolveGitCredentialRequest) (*ResolveGitCredentialResponse, error)
}
// GitCredentialBinder is an optional companion to GitCredentialResolver. It
// provides a non-secret opaque revision for an exact provider lease scope.
// Generic provider leases require this extension so credential rotation and
// disconnect invalidate an already-issued helper lease without a secret read.
type GitCredentialBinder interface {
GetGitCredentialBinding(context.Context, *GitCredentialBindingRequest) (*GitCredentialBindingResponse, error)
}
// GitCredentialHandler is the complete provider-neutral Git credential
// extension. It keeps existing resolvers source-compatible while allowing
// hosts to fail closed when a generic provider lacks binding support.
type GitCredentialHandler interface {
GitCredentialResolver
GitCredentialBinder
}
// AgentToolPlugin is an optional extension implemented by plugins that
// declare agent_tools in their manifest. Keeping it separate from Plugin
// preserves source compatibility for existing plugins.
@@ -0,0 +1,66 @@
package pluginsdk
import (
"testing"
pluginv1 "github.com/kandev/kandev/proto/kandev/plugin/v1"
"google.golang.org/protobuf/reflect/protoreflect"
)
func TestProtocolDeclaresAdditivePluginAndHostMethods(t *testing.T) {
services := pluginv1.File_kandev_plugin_v1_plugin_proto.Services()
assertServiceMethods(t, services.ByName("Plugin"), "HandleAction", "SearchEntityReferences", "AuthorizeEntityReference", "ResolveGitCredential", "GetGitCredentialBinding")
assertServiceMethods(t, services.ByName("Host"), "ListExecutorProfiles", "PreviewPluginOwnedTaskTree", "DeletePluginOwnedTaskTree")
assertMessageFields(t, "PluginActionRequest", "action_key", "context", "body")
assertMessageFields(t, "PluginActionResponse", "body", "headers", "status")
assertMessageFields(t, "VerifiedActionContext", "actor_id", "workspace_id", "task_id", "repository_id", "session_id", "head_branch")
assertMessageFields(t, "SearchEntityReferencesRequest", "source", "workspace_id", "query", "limit")
assertMessageFields(t, "AuthorizeEntityReferenceRequest", "source", "workspace_id", "purpose", "reference")
assertMessageFields(t, "ResolveGitCredentialRequest", "provider_id", "workspace_id", "task_id", "session_id", "repository_id", "host", "path")
assertMessageFields(t, "GitCredentialBindingRequest", "provider_id", "workspace_id", "task_id", "session_id", "repository_id", "host", "path")
assertMessageFields(t, "GitCredentialBindingResponse", "binding")
assertMessageFields(t, "TaskRepository", "id", "repository_id", "base_branch", "position", "checkout_branch")
assertMessageFields(t, "Repository", "id", "workspace_id", "name", "default_branch", "source_type", "provider_id", "provider_repository_id", "provider_host", "owner_or_project", "provider_name", "remote_url", "provider_scope")
assertMessageOmitsFields(t, "Repository", "local_path", "setup_script", "cleanup_script", "dev_script", "copy_files")
assertMessageFields(t, "CreateTaskRequest", "repositories", "launch", "metadata")
assertMessageFields(t, "RemoteRepositoryDescriptor", "provider_id", "provider_host", "owner_or_project", "provider_repository_id", "name", "clone_url", "provider_scope")
assertMessageFields(t, "DeletePluginOwnedTaskTreeProgress", "deleted_task_ids")
}
func assertServiceMethods(t *testing.T, service protoreflect.ServiceDescriptor, methods ...protoreflect.Name) {
t.Helper()
if service == nil {
t.Fatal("required service is missing")
}
for _, method := range methods {
if service.Methods().ByName(method) == nil {
t.Fatalf("%s service is missing %s", service.FullName(), method)
}
}
}
func assertMessageFields(t *testing.T, messageName string, fields ...protoreflect.Name) {
t.Helper()
message := pluginv1.File_kandev_plugin_v1_plugin_proto.Messages().ByName(protoreflect.Name(messageName))
if message == nil {
t.Fatalf("required message %s is missing", messageName)
}
for _, field := range fields {
if message.Fields().ByName(field) == nil {
t.Fatalf("%s is missing field %s", message.FullName(), field)
}
}
}
func assertMessageOmitsFields(t *testing.T, messageName string, fields ...protoreflect.Name) {
t.Helper()
message := pluginv1.File_kandev_plugin_v1_plugin_proto.Messages().ByName(protoreflect.Name(messageName))
if message == nil {
t.Fatalf("required message %s is missing", messageName)
}
for _, field := range fields {
if message.Fields().ByName(field) != nil {
t.Fatalf("%s must not expose field %s", message.FullName(), field)
}
}
}
+142 -9
View File
@@ -193,14 +193,64 @@ func (r *RemotePlugin) HandleWebhook(ctx context.Context, req *WebhookRequest) (
return webhookResponseFromProto(resp), nil
}
// InvokeAgentTool calls the optional plugin agent-tool RPC. The caller owns
// timeout and retry policy because tool calls may have side effects.
func (r *RemotePlugin) InvokeAgentTool(ctx context.Context, req *AgentToolRequest) (*AgentToolResult, error) {
proto, err := req.toProto()
// HandleAction calls an optional authenticated plugin action.
func (r *RemotePlugin) HandleAction(ctx context.Context, req *PluginActionRequest) (*PluginActionResponse, error) {
resp, err := r.client.HandleAction(ctx, req.toProto())
if err != nil {
return nil, err
}
resp, err := r.client.InvokeAgentTool(ctx, proto)
return pluginActionResponseFromProto(resp), nil
}
// SearchEntityReferences calls an optional manifest-owned reference source.
func (r *RemotePlugin) SearchEntityReferences(ctx context.Context, req *SearchEntityReferencesRequest) (*SearchEntityReferencesResponse, error) {
resp, err := r.client.SearchEntityReferences(ctx, req.toProto())
if err != nil {
return nil, err
}
return searchEntityReferencesResponseFromProto(resp)
}
// AuthorizeEntityReference calls an optional live reference authorizer.
func (r *RemotePlugin) AuthorizeEntityReference(ctx context.Context, req *AuthorizeEntityReferenceRequest) (*AuthorizeEntityReferenceResponse, error) {
protoReq, err := req.toProto()
if err != nil {
return nil, err
}
resp, err := r.client.AuthorizeEntityReference(ctx, protoReq)
if err != nil {
return nil, err
}
return authorizeEntityReferenceResponseFromProto(resp), nil
}
// ResolveGitCredential calls an optional declared-provider credential resolver.
func (r *RemotePlugin) ResolveGitCredential(ctx context.Context, req *ResolveGitCredentialRequest) (*ResolveGitCredentialResponse, error) {
resp, err := r.client.ResolveGitCredential(ctx, req.toProto())
if err != nil {
return nil, err
}
return resolveGitCredentialResponseFromProto(resp), nil
}
// GetGitCredentialBinding calls an optional non-secret credential-binding
// extension for an exact host-verified lease scope.
func (r *RemotePlugin) GetGitCredentialBinding(ctx context.Context, req *GitCredentialBindingRequest) (*GitCredentialBindingResponse, error) {
resp, err := r.client.GetGitCredentialBinding(ctx, req.toProto())
if err != nil {
return nil, err
}
return gitCredentialBindingResponseFromProto(resp), nil
}
// InvokeAgentTool calls the optional plugin agent-tool RPC. The caller owns
// timeout and retry policy because tool calls may have side effects.
func (r *RemotePlugin) InvokeAgentTool(ctx context.Context, req *AgentToolRequest) (*AgentToolResult, error) {
protoReq, err := req.toProto()
if err != nil {
return nil, err
}
resp, err := r.client.InvokeAgentTool(ctx, protoReq)
if err != nil {
return nil, err
}
@@ -234,16 +284,95 @@ func (s *grpcPluginServer) HandleWebhook(ctx context.Context, req *pluginv1.Webh
return resp.toProto(), nil
}
func (s *grpcPluginServer) InvokeAgentTool(ctx context.Context, req *pluginv1.AgentToolRequest) (*pluginv1.AgentToolResponse, error) {
impl, ok := s.impl.(AgentToolPlugin)
func (s *grpcPluginServer) HandleAction(ctx context.Context, req *pluginv1.PluginActionRequest) (*pluginv1.PluginActionResponse, error) {
handler, ok := s.impl.(ActionHandler)
if !ok {
return nil, status.Error(codes.Unimplemented, "agent tool invocation is not implemented")
return nil, unsupportedPluginExtension("action handler")
}
resp, err := handler.HandleAction(ctx, pluginActionRequestFromProto(req))
if err != nil {
return nil, err
}
if resp == nil {
return nil, status.Error(codes.Internal, "pluginsdk: action handler returned nil response")
}
return resp.toProto(), nil
}
func (s *grpcPluginServer) SearchEntityReferences(ctx context.Context, req *pluginv1.SearchEntityReferencesRequest) (*pluginv1.SearchEntityReferencesResponse, error) {
handler, ok := s.impl.(EntityReferenceSearcher)
if !ok {
return nil, unsupportedPluginExtension("entity reference searcher")
}
resp, err := handler.SearchEntityReferences(ctx, searchEntityReferencesRequestFromProto(req))
if err != nil {
return nil, err
}
if resp == nil {
return nil, status.Error(codes.Internal, "pluginsdk: entity reference searcher returned nil response")
}
return resp.toProto()
}
func (s *grpcPluginServer) AuthorizeEntityReference(ctx context.Context, req *pluginv1.AuthorizeEntityReferenceRequest) (*pluginv1.AuthorizeEntityReferenceResponse, error) {
handler, ok := s.impl.(EntityReferenceAuthorizer)
if !ok {
return nil, unsupportedPluginExtension("entity reference authorizer")
}
native, err := authorizeEntityReferenceRequestFromProto(req)
if err != nil {
return nil, err
}
resp, err := handler.AuthorizeEntityReference(ctx, native)
if err != nil {
return nil, err
}
if resp == nil {
return nil, status.Error(codes.Internal, "pluginsdk: entity reference authorizer returned nil response")
}
return resp.toProto(), nil
}
func (s *grpcPluginServer) ResolveGitCredential(ctx context.Context, req *pluginv1.ResolveGitCredentialRequest) (*pluginv1.ResolveGitCredentialResponse, error) {
handler, ok := s.impl.(GitCredentialResolver)
if !ok {
return nil, unsupportedPluginExtension("git credential resolver")
}
resp, err := handler.ResolveGitCredential(ctx, resolveGitCredentialRequestFromProto(req))
if err != nil {
return nil, err
}
if resp == nil {
return nil, status.Error(codes.Internal, "pluginsdk: git credential resolver returned nil response")
}
return resp.toProto(), nil
}
func (s *grpcPluginServer) GetGitCredentialBinding(ctx context.Context, req *pluginv1.GitCredentialBindingRequest) (*pluginv1.GitCredentialBindingResponse, error) {
handler, ok := s.impl.(GitCredentialBinder)
if !ok {
return nil, unsupportedPluginExtension("git credential binder")
}
resp, err := handler.GetGitCredentialBinding(ctx, gitCredentialBindingRequestFromProto(req))
if err != nil {
return nil, err
}
if resp == nil {
return nil, status.Error(codes.Internal, "pluginsdk: git credential binder returned nil response")
}
return resp.toProto(), nil
}
func (s *grpcPluginServer) InvokeAgentTool(ctx context.Context, req *pluginv1.AgentToolRequest) (*pluginv1.AgentToolResponse, error) {
handler, ok := s.impl.(AgentToolPlugin)
if !ok {
return nil, unsupportedPluginExtension("agent tool invocation")
}
converted, err := agentToolRequestFromProto(req)
if err != nil {
return nil, err
}
result, err := impl.InvokeAgentTool(ctx, converted)
result, err := handler.InvokeAgentTool(ctx, converted)
if err != nil {
return nil, err
}
@@ -253,6 +382,10 @@ func (s *grpcPluginServer) InvokeAgentTool(ctx context.Context, req *pluginv1.Ag
return result.toProto()
}
func unsupportedPluginExtension(extension string) error {
return status.Errorf(codes.Unimplemented, "pluginsdk: plugin does not implement %s", extension)
}
var _ pluginv1.PluginServer = (*grpcPluginServer)(nil)
// Option configures Serve.
+93 -1
View File
@@ -18,7 +18,8 @@ import (
// pair with a real GRPCBroker, matching production transport behavior).
type fakeAuthorPlugin struct {
UnimplementedPlugin
events []*Event
events []*Event
actions []*PluginActionRequest
}
func (p *fakeAuthorPlugin) OnEvent(_ context.Context, e *Event) error {
@@ -30,6 +31,27 @@ func (p *fakeAuthorPlugin) HandleWebhook(_ context.Context, req *WebhookRequest)
return &WebhookResponse{Status: 200, Body: append([]byte("got:"), req.Body...)}, nil
}
func (p *fakeAuthorPlugin) HandleAction(_ context.Context, req *PluginActionRequest) (*PluginActionResponse, error) {
p.actions = append(p.actions, req)
return &PluginActionResponse{Body: append([]byte(req.Context.ActorID+":"), req.Body...), Headers: map[string]string{"Content-Type": "application/json"}}, nil
}
func (*fakeAuthorPlugin) SearchEntityReferences(_ context.Context, req *SearchEntityReferencesRequest) (*SearchEntityReferencesResponse, error) {
return &SearchEntityReferencesResponse{Candidates: []EntityReferenceCandidate{{ProviderLocalID: req.Source + "-1", Title: "PR 1", Attributes: map[string]any{"query": req.Query}}}}, nil
}
func (*fakeAuthorPlugin) AuthorizeEntityReference(_ context.Context, req *AuthorizeEntityReferenceRequest) (*AuthorizeEntityReferenceResponse, error) {
return &AuthorizeEntityReferenceResponse{Allowed: req.Purpose == "submission"}, nil
}
func (*fakeAuthorPlugin) ResolveGitCredential(_ context.Context, req *ResolveGitCredentialRequest) (*ResolveGitCredentialResponse, error) {
return &ResolveGitCredentialResponse{Username: req.ProviderID, Secret: "transient", ExpiresAt: "2026-07-31T12:00:00Z"}, nil
}
func (*fakeAuthorPlugin) GetGitCredentialBinding(_ context.Context, _ *GitCredentialBindingRequest) (*GitCredentialBindingResponse, error) {
return &GitCredentialBindingResponse{Binding: "connection:7"}, nil
}
func (p *fakeAuthorPlugin) InvokeAgentTool(_ context.Context, req *AgentToolRequest) (*AgentToolResult, error) {
return &AgentToolResult{
Text: "called:" + req.Context.TaskID,
@@ -105,6 +127,38 @@ func TestServe_EndToEnd(t *testing.T) {
require.Equal(t, []byte("got:hi"), resp.Body)
})
t.Run("OptionalPluginExtensions", func(t *testing.T) {
action, err := remote.HandleAction(context.Background(), &PluginActionRequest{
ActionKey: "connection.get",
Context: VerifiedActionContext{
ActorID: "user-1", WorkspaceID: "ws-1", TaskID: "task-1",
RepositoryID: "repository-1", SessionID: "session-1", HeadBranch: "feature/native-create",
},
Body: []byte(`{"connected":true}`),
})
require.NoError(t, err)
require.Equal(t, []byte(`user-1:{"connected":true}`), action.Body)
require.Equal(t, "application/json", action.Headers["Content-Type"])
require.Equal(t, "session-1", author.actions[0].Context.SessionID)
require.Equal(t, "feature/native-create", author.actions[0].Context.HeadBranch)
search, err := remote.SearchEntityReferences(context.Background(), &SearchEntityReferencesRequest{Source: "bitbucket", WorkspaceID: "ws-1", Query: "build", Limit: 5})
require.NoError(t, err)
require.Equal(t, []EntityReferenceCandidate{{ProviderLocalID: "bitbucket-1", Title: "PR 1", Attributes: map[string]any{"query": "build"}}}, search.Candidates)
authorized, err := remote.AuthorizeEntityReference(context.Background(), &AuthorizeEntityReferenceRequest{Source: "bitbucket", WorkspaceID: "ws-1", Purpose: "submission", Reference: map[string]any{"id": "1"}})
require.NoError(t, err)
require.True(t, authorized.Allowed)
credential, err := remote.ResolveGitCredential(context.Background(), &ResolveGitCredentialRequest{ProviderID: "bitbucket", WorkspaceID: "ws-1", Host: "bitbucket.org", Path: "/team/repo.git"})
require.NoError(t, err)
require.Equal(t, &ResolveGitCredentialResponse{Username: "bitbucket", Secret: "transient", ExpiresAt: "2026-07-31T12:00:00Z"}, credential)
binding, err := remote.GetGitCredentialBinding(context.Background(), &GitCredentialBindingRequest{ProviderID: "bitbucket", WorkspaceID: "ws-1", Host: "bitbucket.org", Path: "/team/repo.git"})
require.NoError(t, err)
require.Equal(t, "connection:7", binding.Binding)
})
t.Run("InvokeAgentTool", func(t *testing.T) {
resp, err := remote.InvokeAgentTool(context.Background(), &AgentToolRequest{
InvocationID: "inv-1", Name: "echo", Arguments: map[string]any{"value": "ok"},
@@ -130,3 +184,41 @@ func TestServe_EndToEnd(t *testing.T) {
require.False(t, found)
})
}
// TestServe_LegacyPluginGetsClearUnsupportedExtensionErrors confirms that
// adding optional RPCs does not force existing Plugin implementations to add
// methods. Calls to an extension they did not opt into fail explicitly rather
// than looking like transport failure or a successful empty response.
func TestServe_LegacyPluginGetsClearUnsupportedExtensionErrors(t *testing.T) {
gp := &GRPCPlugin{Impl: &UnimplementedPlugin{}}
client, server := hcplugin.TestPluginGRPCConn(t, false, map[string]hcplugin.Plugin{
PluginMapKey: gp,
})
defer func() { _ = client.Close() }()
defer server.Stop()
raw, err := client.Dispense(PluginMapKey)
require.NoError(t, err)
remote, ok := raw.(*RemotePlugin)
require.True(t, ok)
_, err = remote.HandleAction(context.Background(), &PluginActionRequest{})
require.Equal(t, codes.Unimplemented, status.Code(err))
require.Contains(t, err.Error(), "plugin does not implement action handler")
_, err = remote.SearchEntityReferences(context.Background(), &SearchEntityReferencesRequest{})
require.Equal(t, codes.Unimplemented, status.Code(err))
require.Contains(t, err.Error(), "plugin does not implement entity reference searcher")
_, err = remote.AuthorizeEntityReference(context.Background(), &AuthorizeEntityReferenceRequest{})
require.Equal(t, codes.Unimplemented, status.Code(err))
require.Contains(t, err.Error(), "plugin does not implement entity reference authorizer")
_, err = remote.ResolveGitCredential(context.Background(), &ResolveGitCredentialRequest{})
require.Equal(t, codes.Unimplemented, status.Code(err))
require.Contains(t, err.Error(), "plugin does not implement git credential resolver")
_, err = remote.GetGitCredentialBinding(context.Background(), &GitCredentialBindingRequest{})
require.Equal(t, codes.Unimplemented, status.Code(err))
require.Contains(t, err.Error(), "plugin does not implement git credential binder")
}
+304
View File
@@ -180,6 +180,310 @@ func webhookResponseFromProto(p *pluginv1.WebhookResponse) *WebhookResponse {
}
}
// VerifiedActionContext is derived by Kandev after authenticating and
// authorizing an action request. Plugins must treat Body as untrusted input
// and use this context for all authority decisions.
type VerifiedActionContext struct {
ActorID string
WorkspaceID string
TaskID string
RepositoryID string
SessionID string
HeadBranch string
}
func (c VerifiedActionContext) toProto() *pluginv1.VerifiedActionContext {
return &pluginv1.VerifiedActionContext{
ActorId: c.ActorID,
WorkspaceId: c.WorkspaceID,
TaskId: c.TaskID,
RepositoryId: c.RepositoryID,
SessionId: c.SessionID,
HeadBranch: c.HeadBranch,
}
}
func verifiedActionContextFromProto(p *pluginv1.VerifiedActionContext) VerifiedActionContext {
if p == nil {
return VerifiedActionContext{}
}
return VerifiedActionContext{
ActorID: p.GetActorId(),
WorkspaceID: p.GetWorkspaceId(),
TaskID: p.GetTaskId(),
RepositoryID: p.GetRepositoryId(),
SessionID: p.GetSessionId(),
HeadBranch: p.GetHeadBranch(),
}
}
// PluginActionRequest is the Go-native mirror of PluginActionRequest.
type PluginActionRequest struct {
ActionKey string
Context VerifiedActionContext
Body []byte
}
func (r *PluginActionRequest) toProto() *pluginv1.PluginActionRequest {
return &pluginv1.PluginActionRequest{ActionKey: r.ActionKey, Context: r.Context.toProto(), Body: r.Body}
}
func pluginActionRequestFromProto(p *pluginv1.PluginActionRequest) *PluginActionRequest {
if p == nil {
return &PluginActionRequest{}
}
return &PluginActionRequest{ActionKey: p.GetActionKey(), Context: verifiedActionContextFromProto(p.GetContext()), Body: p.GetBody()}
}
// PluginActionResponse is the Go-native mirror of PluginActionResponse.
// Kandev filters Headers before returning them to the browser.
type PluginActionResponse struct {
Body []byte
Headers map[string]string
// Status is a final HTTP status in [200, 599]. Zero means 200 for
// compatibility with plugins built before domain responses were added.
Status int
}
func (r *PluginActionResponse) toProto() *pluginv1.PluginActionResponse {
return &pluginv1.PluginActionResponse{Body: r.Body, Headers: r.Headers, Status: int32(r.Status)}
}
func pluginActionResponseFromProto(p *pluginv1.PluginActionResponse) *PluginActionResponse {
if p == nil {
return &PluginActionResponse{}
}
return &PluginActionResponse{Body: p.GetBody(), Headers: p.GetHeaders(), Status: int(p.GetStatus())}
}
// SearchEntityReferencesRequest is a host-verified workspace search request.
type SearchEntityReferencesRequest struct {
Source string
WorkspaceID string
Query string
Limit int32
}
func (r *SearchEntityReferencesRequest) toProto() *pluginv1.SearchEntityReferencesRequest {
return &pluginv1.SearchEntityReferencesRequest{Source: r.Source, WorkspaceId: r.WorkspaceID, Query: r.Query, Limit: r.Limit}
}
func searchEntityReferencesRequestFromProto(p *pluginv1.SearchEntityReferencesRequest) *SearchEntityReferencesRequest {
if p == nil {
return &SearchEntityReferencesRequest{}
}
return &SearchEntityReferencesRequest{Source: p.GetSource(), WorkspaceID: p.GetWorkspaceId(), Query: p.GetQuery(), Limit: p.GetLimit()}
}
// EntityReferenceCandidate is untrusted plugin search output. Kandev adds
// manifest-owned descriptor identity before it reaches a composer result.
type EntityReferenceCandidate struct {
ProviderLocalID string
Title string
URL string
Attributes map[string]any
}
func (c EntityReferenceCandidate) toProto() (*pluginv1.EntityReferenceCandidate, error) {
attributes, err := mapToStruct(c.Attributes)
if err != nil {
return nil, fmt.Errorf("pluginsdk: reference candidate attributes: %w", err)
}
return &pluginv1.EntityReferenceCandidate{ProviderLocalId: c.ProviderLocalID, Title: c.Title, Url: c.URL, Attributes: attributes}, nil
}
func entityReferenceCandidateFromProto(p *pluginv1.EntityReferenceCandidate) (EntityReferenceCandidate, error) {
if p == nil {
return EntityReferenceCandidate{}, nil
}
attributes, err := structToMap(p.GetAttributes())
if err != nil {
return EntityReferenceCandidate{}, fmt.Errorf("pluginsdk: reference candidate attributes: %w", err)
}
return EntityReferenceCandidate{ProviderLocalID: p.GetProviderLocalId(), Title: p.GetTitle(), URL: p.GetUrl(), Attributes: attributes}, nil
}
func entityReferenceCandidatesToProto(candidates []EntityReferenceCandidate) ([]*pluginv1.EntityReferenceCandidate, error) {
if candidates == nil {
return nil, nil
}
out := make([]*pluginv1.EntityReferenceCandidate, len(candidates))
for i, candidate := range candidates {
converted, err := candidate.toProto()
if err != nil {
return nil, err
}
out[i] = converted
}
return out, nil
}
func entityReferenceCandidatesFromProto(candidates []*pluginv1.EntityReferenceCandidate) ([]EntityReferenceCandidate, error) {
if candidates == nil {
return nil, nil
}
out := make([]EntityReferenceCandidate, len(candidates))
for i, candidate := range candidates {
converted, err := entityReferenceCandidateFromProto(candidate)
if err != nil {
return nil, err
}
out[i] = converted
}
return out, nil
}
// SearchEntityReferencesResponse is the Go-native search response.
type SearchEntityReferencesResponse struct{ Candidates []EntityReferenceCandidate }
func (r *SearchEntityReferencesResponse) toProto() (*pluginv1.SearchEntityReferencesResponse, error) {
candidates, err := entityReferenceCandidatesToProto(r.Candidates)
if err != nil {
return nil, err
}
return &pluginv1.SearchEntityReferencesResponse{Candidates: candidates}, nil
}
func searchEntityReferencesResponseFromProto(p *pluginv1.SearchEntityReferencesResponse) (*SearchEntityReferencesResponse, error) {
if p == nil {
return &SearchEntityReferencesResponse{}, nil
}
candidates, err := entityReferenceCandidatesFromProto(p.GetCandidates())
if err != nil {
return nil, err
}
return &SearchEntityReferencesResponse{Candidates: candidates}, nil
}
// AuthorizeEntityReferenceRequest asks a live plugin to approve a canonical
// reference for search or final message submission.
type AuthorizeEntityReferenceRequest struct {
Source string
WorkspaceID string
Purpose string
Reference map[string]any
}
func (r *AuthorizeEntityReferenceRequest) toProto() (*pluginv1.AuthorizeEntityReferenceRequest, error) {
reference, err := mapToStruct(r.Reference)
if err != nil {
return nil, fmt.Errorf("pluginsdk: entity reference: %w", err)
}
return &pluginv1.AuthorizeEntityReferenceRequest{Source: r.Source, WorkspaceId: r.WorkspaceID, Purpose: r.Purpose, Reference: reference}, nil
}
func authorizeEntityReferenceRequestFromProto(p *pluginv1.AuthorizeEntityReferenceRequest) (*AuthorizeEntityReferenceRequest, error) {
if p == nil {
return &AuthorizeEntityReferenceRequest{}, nil
}
reference, err := structToMap(p.GetReference())
if err != nil {
return nil, fmt.Errorf("pluginsdk: entity reference: %w", err)
}
return &AuthorizeEntityReferenceRequest{Source: p.GetSource(), WorkspaceID: p.GetWorkspaceId(), Purpose: p.GetPurpose(), Reference: reference}, nil
}
type AuthorizeEntityReferenceResponse struct {
Allowed bool
Reason string
}
func (r *AuthorizeEntityReferenceResponse) toProto() *pluginv1.AuthorizeEntityReferenceResponse {
return &pluginv1.AuthorizeEntityReferenceResponse{Allowed: r.Allowed, Reason: r.Reason}
}
func authorizeEntityReferenceResponseFromProto(p *pluginv1.AuthorizeEntityReferenceResponse) *AuthorizeEntityReferenceResponse {
if p == nil {
return &AuthorizeEntityReferenceResponse{}
}
return &AuthorizeEntityReferenceResponse{Allowed: p.GetAllowed(), Reason: p.GetReason()}
}
// ResolveGitCredentialRequest contains exact host-verified lease scope.
type ResolveGitCredentialRequest struct {
ProviderID string
WorkspaceID string
TaskID string
SessionID string
RepositoryID string
Host string
Path string
}
func (r *ResolveGitCredentialRequest) toProto() *pluginv1.ResolveGitCredentialRequest {
return &pluginv1.ResolveGitCredentialRequest{ProviderId: r.ProviderID, WorkspaceId: r.WorkspaceID, TaskId: r.TaskID, SessionId: r.SessionID, RepositoryId: r.RepositoryID, Host: r.Host, Path: r.Path}
}
func resolveGitCredentialRequestFromProto(p *pluginv1.ResolveGitCredentialRequest) *ResolveGitCredentialRequest {
if p == nil {
return &ResolveGitCredentialRequest{}
}
return &ResolveGitCredentialRequest{ProviderID: p.GetProviderId(), WorkspaceID: p.GetWorkspaceId(), TaskID: p.GetTaskId(), SessionID: p.GetSessionId(), RepositoryID: p.GetRepositoryId(), Host: p.GetHost(), Path: p.GetPath()}
}
// ResolveGitCredentialResponse is transient authentication material. Hosts
// must not log or persist Secret.
type ResolveGitCredentialResponse struct {
Username string
Secret string
ExpiresAt string
}
func (r *ResolveGitCredentialResponse) toProto() *pluginv1.ResolveGitCredentialResponse {
return &pluginv1.ResolveGitCredentialResponse{Username: r.Username, Secret: r.Secret, ExpiresAt: r.ExpiresAt}
}
func resolveGitCredentialResponseFromProto(p *pluginv1.ResolveGitCredentialResponse) *ResolveGitCredentialResponse {
if p == nil {
return &ResolveGitCredentialResponse{}
}
return &ResolveGitCredentialResponse{Username: p.GetUsername(), Secret: p.GetSecret(), ExpiresAt: p.GetExpiresAt()}
}
// GitCredentialBindingRequest contains the exact host-verified lease scope
// for a non-secret credential revision lookup.
type GitCredentialBindingRequest struct {
ProviderID string
WorkspaceID string
TaskID string
SessionID string
RepositoryID string
Host string
Path string
}
func (r *GitCredentialBindingRequest) toProto() *pluginv1.GitCredentialBindingRequest {
return &pluginv1.GitCredentialBindingRequest{
ProviderId: r.ProviderID, WorkspaceId: r.WorkspaceID, TaskId: r.TaskID, SessionId: r.SessionID,
RepositoryId: r.RepositoryID, Host: r.Host, Path: r.Path,
}
}
func gitCredentialBindingRequestFromProto(p *pluginv1.GitCredentialBindingRequest) *GitCredentialBindingRequest {
if p == nil {
return &GitCredentialBindingRequest{}
}
return &GitCredentialBindingRequest{
ProviderID: p.GetProviderId(), WorkspaceID: p.GetWorkspaceId(), TaskID: p.GetTaskId(), SessionID: p.GetSessionId(),
RepositoryID: p.GetRepositoryId(), Host: p.GetHost(), Path: p.GetPath(),
}
}
// GitCredentialBindingResponse returns an opaque, non-secret revision for a
// credential scope. Hosts must treat an empty response as a revoked binding.
type GitCredentialBindingResponse struct{ Binding string }
func (r *GitCredentialBindingResponse) toProto() *pluginv1.GitCredentialBindingResponse {
return &pluginv1.GitCredentialBindingResponse{Binding: r.Binding}
}
func gitCredentialBindingResponseFromProto(p *pluginv1.GitCredentialBindingResponse) *GitCredentialBindingResponse {
if p == nil {
return &GitCredentialBindingResponse{}
}
return &GitCredentialBindingResponse{Binding: p.GetBinding()}
}
// StateEntry is the Go-native mirror of kandev.plugin.v1.StateEntry, as
// returned by Host.ListState.
type StateEntry struct {