agent

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agent defines the optional adapter-neutral contract for one live Agent session.

agentcodex.New and agentclaude.New construct concrete Cores that implement Core. A Core owns its lifecycle and any native resources shared across sessions; an adapter may instead place native resources, such as Claude CLI processes, in each Session. After Start, Open creates a main session and Resume restores an existing native identity; both return the same Session contract. Each Session exposes one EventStream to one consumer, accepts text through StartOrSteer, answers original requests through opaque InteractionRef values, and releases its own attachment and session-owned resources through Close. StartOrSteer lets the adapter start new work, join acceptable current work, or report that input was not applied; it never queues, waits for idle, persists, or retries. Sessions may implement Injector to append context without requesting a model response. InjectReceipt reports acceptance only; native timing and version limits are defined in docs/modules/unified-agent/design.md#context-inject. OpenOptions.Config groups main-session Model and Effort values. An empty field omits that value; a nonempty value is passed literally, without trimming, aliasing or cross-provider conversion. Sessions may optionally implement ConfigController to update one value through SetConfig using the closed IDs model and effort. Runtime updates affect provider-determined later work: they do not wait for idle, interrupt an active turn, restart the process or configure child sessions. Callers that require ordering must serialize calls. A ConfigReceipt reports only the exact change and native acceptance stages. It does not report requested or effective configuration state. Successful native acceptance is therefore not proof that a value is currently effective. Sandbox, approval, permission-profile, ACP mode, collaboration, fast-mode and custom-agent settings remain native-specific capabilities.

Event payloads form a closed live union with stable session and item identity. Adapters preserve native order, time, raw evidence, and explicit capability gaps. They do not invent cross-provider equivalence.

ToolCallPayload and ToolResultPayload carry the required provider-native (ToolName, Provider) identity and SDK-assigned Kind. ToolName and Provider form the identity; Kind is an ACP-derived action category, not a permission decision or proof that tools from different providers behave equivalently. A result copies the provider, tool name and kind observed on its call. ToolChunkPayload is deliberately only {id, content} because a chunk can arrive before the complete tool identity.

Tool status remains a native-specific lifecycle projection. Tool call and result JSON requires kind, toolName and provider and has no scope field. This unreleased schema is intentionally breaking: strict decoding rejects the legacy name member and old arbitrary kind strings, with no compatibility alias. The accepted provider forms, kind boundaries, provider mappings and exact validation rules are defined by ToolProvider, ToolKind and the unified-agent design under docs/modules/unified-agent.

This package intentionally has no unified history, LoadSession, replay, root client, or multi-session aggregation. Codex and Claude keep their native history APIs, and Resume does not turn saved content into live events. MASS resource identity and persistence also remain outside this contract.

OpenOptions.MCPServers []mcp.Server carries the final adapter-neutral external MCP list for one Open or Resume call. The shared mcp.Server type is also the native Codex and Claude configuration type. The caller that interprets Runtime configuration must compose Runtime defaults and the Session declaration before calling a Core. Cores do not merge or persist that list; Resume requires a new final list. The repository README section "External MCP servers" describes the composition and adapter-specific limits.

OpenOptions.AdditionalSystemPrompt adds optional caller text for that Open or Resume call only; empty requests no addition. It is per-operation configuration, not Session state. The complete field contract is defined in docs/modules/unified-agent/design.md#additional-system-prompt.

Features.RestrictLocalTools applies available native restrictions to built-in local file and command tools on Open or Resume. EffectiveFeatures reports whether restrictions were configured, without guaranteeing all local tools are disabled. See docs/modules/unified-agent/design.md#restrict-local-tools for scope and provider gaps.

The unified contract accepts only explicit mcp.TransportStdio and mcp.TransportHTTP and rejects mcp.TransportSSE. It has no MCPConfigMode, StrictMCPConfig, SDKMCPServers, or ambient-clear control. Adapter-specific field restrictions are rejected before native side effects. The SDK forwards environment and header values without resolving them; it does not persist MCP configuration or include its values in unified Events, Meta, or logs. MCP validation and adapter field-support errors do not echo those values. Open or Resume errors can wrap native diagnostics as a cause, which callers must protect separately. Open or Resume success does not prove MCP connectivity, authentication, or tool discovery.

ExampleCore runs the complete open, start-or-steer, stream, answer, close, resume, and stop flow over two synthetic Cores without launching a native CLI. ExampleOpenOptions_mcpServers validates an offline final MCP list without connecting to a server.

Index

Examples

Constants

View Source
const (
	CapabilityTextInput         = "textInput"
	CapabilityImageInput        = "imageInput"
	CapabilityAudioInput        = "audioInput"
	CapabilityResourceInput     = "resourceInput"
	CapabilityResourceLinkInput = "resourceLinkInput"
	CapabilityPermission        = "permission"
	CapabilityForm              = "form"
	CapabilityURL               = "url"
	CapabilityProcessEnv        = "processEnv"
	CapabilityShellEnv          = "shellEnv"
	CapabilityPromptTrace       = "promptTrace"
)
View Source
const (
	ErrorReasonAdditionalDirsUnsupported  = "additional_dirs_unsupported"
	ErrorReasonAgentQuestionsDisabled     = "agent_questions_disabled"
	ErrorReasonAnswerKindUnsupported      = "answer_kind_unsupported"
	ErrorReasonAnswerOutcomeUnknown       = "answer_outcome_unknown"
	ErrorReasonContentBlockUnsupported    = "content_block_unsupported"
	ErrorReasonEventDeliveryFailed        = "event_delivery_failed"
	ErrorReasonEventIDFailed              = "event_id_failed"
	ErrorReasonEventInvalid               = "event_invalid"
	ErrorReasonEventsAlreadyClaimed       = "events_already_claimed"
	ErrorReasonInvalidFormAnswer          = "invalid_form_answer"
	ErrorReasonInvalidFormOutcome         = "invalid_form_outcome"
	ErrorReasonInvalidInteractionRef      = "invalid_interaction_ref"
	ErrorReasonInvalidPermissionPreset    = "invalid_permission_preset"
	ErrorReasonInteractionNotPending      = "interaction_not_pending"
	ErrorReasonInteractionRefFailed       = "interaction_ref_failed"
	ErrorReasonMissingAnswer              = "missing_answer"
	ErrorReasonNativeRequestEnded         = "native_request_ended"
	ErrorReasonPermissionOptionNotOffered = "permission_option_not_offered"
	ErrorReasonPermissionPresetConflict   = "permission_preset_conflict"
	ErrorReasonProcessEnvUnsupported      = "process_env_unsupported"
	ErrorReasonShellEnvUnsupported        = "shell_env_unsupported"
	ErrorReasonSessionClosed              = "session_closed"
	ErrorReasonSessionTerminated          = "session_terminated"
	ErrorReasonTextAnnotationsUnsupported = "text_annotations_unsupported"
	ErrorReasonUnknownFormQuestion        = "unknown_form_question"
	ErrorReasonUnsupportedAnswer          = "unsupported_answer"
)

Stable Error.Reason values shared by the unified contract and provider adapters. Callers may match these values without parsing Error.Message.

View Source
const (
	ErrorReasonAdditionalSystemPromptContainsNUL = "additional_system_prompt_contains_nul"
	ErrorReasonAdditionalSystemPromptInvalidUTF8 = "additional_system_prompt_invalid_utf8"
	ErrorReasonConfigValueContainsNUL            = "config_value_contains_nul"
	ErrorReasonConfigValueEmpty                  = "config_value_empty"
	ErrorReasonConfigValueInvalidUTF8            = "config_value_invalid_utf8"
	ErrorReasonConfigIDUnknown                   = "config_id_unknown"
	ErrorReasonEnvironmentInvalid                = "environment_invalid"
	ErrorReasonCoreHasOpenSessions               = "core_has_open_sessions"
	ErrorReasonCoreNotStarted                    = "core_not_started"
	ErrorReasonCoreStopped                       = "core_stopped"
)

Stable Error.Reason values produced by adapter-neutral validation and lifecycle code shared by both adapters.

View Source
const ErrorReasonSuffixFailed = "_failed"

ErrorReasonSuffixFailed is the operation suffix for an unclassified native failure. Other operation suffixes are the corresponding ErrorCode values.

View Source
const SpanStartOrSteer = "agent.start_or_steer"

SpanStartOrSteer is the name of the optional SDK-local submission span.

Variables

This section is empty.

Functions

func ErrorReasonForCode

func ErrorReasonForCode(operation string, code ErrorCode) string

ErrorReasonForCode appends an ErrorCode to an operation.

func ErrorReasonForOperation

func ErrorReasonForOperation(operation, suffix string) string

ErrorReasonForOperation appends a stable reason suffix to an operation.

func ValidateAnswer

func ValidateAnswer(kind InteractionKind, answer Answer) error

ValidateAnswer checks that answer matches the live request kind and that its outcome has the fields required by that branch.

func WithTraceContext

func WithTraceContext(ctx context.Context, trace TraceContext) context.Context

WithTraceContext attaches the per-call carrier without validating it. Repeated calls keep the most recent value.

Types

type Acceptance

type Acceptance struct {
	Sent           *bool
	NativeAccepted *bool
	NativeRecorded *bool
}

Acceptance records three independent stages of native acceptance.

type ActionReceipt

type ActionReceipt struct {
	Acceptance Acceptance
}

ActionReceipt records the acceptance observed for an adapter-specific action.

type AgentMessage

type AgentMessage MessagePayload

type AgentThinking

type AgentThinking MessagePayload

type Annotations

type Annotations struct {
	Audience     []string
	Priority     *float64
	LastModified *time.Time
}

type Answer

type Answer interface {
	// contains filtered or unexported methods
}

func MatchAnswer

func MatchAnswer(kind InteractionKind, answer Answer) (Answer, error)

MatchAnswer returns answer as one of the concrete answer values after checking that it matches the live request kind and that its outcome has the fields required by that branch.

type Archiver

type Archiver interface {
	Archive(ctx context.Context) (ActionReceipt, error)
	Unarchive(ctx context.Context) (ActionReceipt, error)
}

Archiver is implemented only by sessions that can archive and unarchive their native main session.

type AvailableCommand

type AvailableCommand struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

type AvailableCommandsUpdatePayload

type AvailableCommandsUpdatePayload struct {
	AvailableCommands []AvailableCommand `json:"availableCommands"`
}

type Capabilities

type Capabilities map[string]bool

Capabilities describes the optional support that a provider or session actually has. Missing and false values both mean that support is unavailable.

func (Capabilities) Supports

func (c Capabilities) Supports(capability string) bool

Supports reports whether capability is both defined by this contract and explicitly true. Unknown keys never imply support.

func (Capabilities) Validate

func (c Capabilities) Validate() error

Validate rejects capability keys that are not declared by this contract.

type ConfigChange

type ConfigChange struct {
	ID    ConfigID
	Value string
}

ConfigChange requests one literal value update for one configuration ID.

func (ConfigChange) Validate

func (c ConfigChange) Validate() error

Validate checks a runtime configuration change before native side effects. Empty runtime values are invalid; they do not clear or restore a default.

type ConfigController

type ConfigController interface {
	SetConfig(
		ctx context.Context,
		change ConfigChange,
	) (ConfigReceipt, error)
}

ConfigController updates one main-session configuration value at a time. Updates affect provider-determined later work; they do not wait for idle, interrupt active work, restart the process, retry, or configure child sessions. Callers that require ordering must serialize calls.

Example

ExampleConfigController shows the single runtime configuration entry point. A receipt reports the exact change and native acceptance, not a current or effective configuration snapshot.

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"sync"
	"time"

	"github.com/zoumo/agent-sdk-go/agent"
)

func main() {
	ctx := context.Background()
	provider := newExampleProvider("codex")
	_, err := provider.Start(ctx)
	mustExample(err)
	defer func() { mustExample(provider.Stop(context.Background())) }()

	session, err := provider.Open(ctx, agent.OpenOptions{
		Cwd: "/synthetic",
		Config: agent.SessionConfig{
			Model:  " Caller/Model v2 ",
			Effort: " Native/High ",
		},
	})
	mustExample(err)
	controller, ok := session.(agent.ConfigController)
	if !ok {
		panic("example session does not implement configuration control")
	}

	modelReceipt, err := controller.SetConfig(
		ctx,
		agent.ConfigChange{
			ID:    agent.ConfigModel,
			Value: "next/model",
		},
	)
	mustExample(err)
	fmt.Printf(
		"model id=%s value=%q sent=%t accepted=%t\n",
		modelReceipt.Change.ID,
		modelReceipt.Change.Value,
		*modelReceipt.Acceptance.Sent,
		*modelReceipt.Acceptance.NativeAccepted,
	)

	effortReceipt, err := controller.SetConfig(
		ctx,
		agent.ConfigChange{
			ID:    agent.ConfigEffort,
			Value: "next/effort",
		},
	)
	mustExample(err)
	fmt.Printf(
		"effort id=%s value=%q sent=%t accepted=%t\n",
		effortReceipt.Change.ID,
		effortReceipt.Change.Value,
		*effortReceipt.Acceptance.Sent,
		*effortReceipt.Acceptance.NativeAccepted,
	)
	mustExample(session.Close(ctx))

}

type exampleProvider struct {
	name     string
	mu       sync.Mutex
	started  bool
	stopped  bool
	sessions map[string]*exampleSession
}

func newExampleProvider(name string) *exampleProvider {
	return &exampleProvider{name: name, sessions: make(map[string]*exampleSession)}
}

func (p *exampleProvider) Start(context.Context) (agent.Capabilities, error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.stopped {
		return nil, errors.New("provider stopped")
	}
	p.started = true
	return agent.Capabilities{
		agent.CapabilityTextInput:  true,
		agent.CapabilityPermission: true,
	}, nil
}

func (p *exampleProvider) Open(
	_ context.Context,
	options agent.OpenOptions,
) (agent.Session, error) {
	if err := options.Validate(); err != nil {
		return nil, err
	}
	return p.newSession(p.name + "-session")
}

func (p *exampleProvider) Resume(
	_ context.Context,
	options agent.ResumeOptions,
) (agent.Session, error) {
	if err := options.Validate(); err != nil {
		return nil, err
	}
	return p.newSession(options.SessionID)
}

func (p *exampleProvider) Stop(context.Context) error {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.stopped = true
	return nil
}

func (p *exampleProvider) newSession(
	id string,
) (agent.Session, error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if !p.started || p.stopped {
		return nil, errors.New("provider is not active")
	}
	created := newExampleSession(p.name, id)
	p.sessions[id] = created
	return created, nil
}

type exampleSession struct {
	provider string
	id       string
	events   []agent.Event
	next     int
	claimed  bool
	answered bool
	mu       sync.Mutex
	closed   bool
	done     chan struct{}
	close    sync.Once
}

func newExampleSession(
	provider, id string,
) *exampleSession {
	interaction := agent.InteractionRef(provider + "/interaction-1")
	idle := agent.StateIdle
	request := agent.InteractionRequest{
		Kind:       agent.InteractionPermission,
		ToolCallID: provider + "-tool",
		Title:      "Approve synthetic tool",
		Options: []agent.PermissionOption{{
			OptionID: "allow-once",
			Name:     "Allow once",
			Kind:     agent.PermissionAllow,
			Scope:    agent.PermissionScopeOnce,
		}},
	}
	return &exampleSession{
		provider: provider,
		id:       id,
		done:     make(chan struct{}),
		events: []agent.Event{
			exampleEvent(id, 1, "user-1", agent.UserMessage{
				MessageID: "user-1",
				Content:   []agent.ContentBlock{{Text: &agent.ContentBlockText{Text: "Explain the change"}}},
			}),
			exampleEvent(id, 2, "", agent.InteractionRequestedPayload{
				Interaction: interaction,
				Request:     request,
				Blocking:    true,
			}),
			exampleEvent(id, 3, "", agent.InteractionClosedPayload{
				Interaction: interaction,
				Outcome:     agent.InteractionAnswered,
				Reason:      "synthetic_answer",
			}),
			exampleEvent(id, 4, "agent-1", agent.AgentMessage{
				MessageID: "agent-1",
				Content: []agent.ContentBlock{
					{Text: &agent.ContentBlockText{Text: "Offline reply for " + provider}},
				},
			}),
			exampleEvent(id, 5, "", agent.StateUpdatePayload{State: &idle}),
		},
	}
}

func (s *exampleSession) ID() string { return s.id }

func (s *exampleSession) Capabilities() agent.Capabilities {
	return agent.Capabilities{
		agent.CapabilityTextInput:  true,
		agent.CapabilityPermission: true,
	}
}

func (s *exampleSession) EffectiveFeatures() agent.EffectiveFeatures {
	return agent.EffectiveFeatures{AgentQuestions: false}
}

func (s *exampleSession) SetConfig(
	ctx context.Context,
	change agent.ConfigChange,
) (agent.ConfigReceipt, error) {
	receipt := exampleConfigNotSent(change)
	if err := change.Validate(); err != nil {
		return receipt, err
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.closed {
		return receipt, &agent.Error{
			Code:    agent.ErrorClosed,
			Reason:  "session_closed",
			Message: "session is closed",
		}
	}
	if err := ctx.Err(); err != nil {
		return receipt, &agent.Error{
			Code:    agent.ErrorUnavailable,
			Reason:  "set_config_not_sent",
			Message: "session configuration was not sent",
			Cause:   err,
		}
	}
	sent, accepted := true, true
	return agent.ConfigReceipt{
		Change: change,
		Acceptance: agent.Acceptance{
			Sent:           &sent,
			NativeAccepted: &accepted,
		},
	}, nil
}

func exampleConfigNotSent(change agent.ConfigChange) agent.ConfigReceipt {
	sent := false
	return agent.ConfigReceipt{
		Change:     change,
		Acceptance: agent.Acceptance{Sent: &sent},
	}
}

func (s *exampleSession) Events() (agent.EventStream, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.closed {
		return nil, errors.New("session closed")
	}
	if s.claimed {
		return nil, errors.New("event stream already claimed")
	}
	s.claimed = true
	return exampleStream{session: s}, nil
}

func (s *exampleSession) StartOrSteer(
	ctx context.Context,
	input agent.Input,
) (agent.InputReceipt, error) {
	receipt, err := s.acceptInput(ctx, input)
	if err != nil {
		return agent.InputReceipt{}, err
	}
	receipt.Result = agent.InputAppliedBestEffort
	return receipt, nil
}

func (s *exampleSession) acceptInput(
	ctx context.Context,
	input agent.Input,
) (agent.InputReceipt, error) {
	if err := input.Validate(); err != nil {
		return agent.InputReceipt{}, err
	}
	if err := ctx.Err(); err != nil {
		return agent.InputReceipt{}, err
	}
	sent := true
	return agent.InputReceipt{
		Submission: s.provider + "-submission",
		Acceptance: agent.Acceptance{Sent: &sent},
	}, nil
}

func (s *exampleSession) Answer(
	ctx context.Context,
	interaction agent.InteractionRef,
	answer agent.Answer,
) (agent.InteractionReceipt, error) {
	if err := ctx.Err(); err != nil {
		return agent.InteractionReceipt{}, err
	}
	if err := agent.ValidateAnswer(agent.InteractionPermission, answer); err != nil {
		return agent.InteractionReceipt{}, err
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.closed {
		return agent.InteractionReceipt{}, errors.New("session closed")
	}
	if s.answered {
		return agent.InteractionReceipt{}, errors.New("interaction already answered")
	}
	if interaction != agent.InteractionRef(s.provider+"/interaction-1") {
		return agent.InteractionReceipt{}, errors.New("interaction is not owned by session")
	}
	s.answered = true
	sent := true
	return agent.InteractionReceipt{
		Interaction: interaction,
		Acceptance:  agent.Acceptance{Sent: &sent},
	}, nil
}

func (s *exampleSession) Interrupt(
	context.Context,
	agent.InterruptOptions,
) (agent.InterruptReceipt, error) {
	return agent.InterruptReceipt{Result: agent.InterruptNoActiveWork}, nil
}

func (s *exampleSession) Close(context.Context) error {
	s.mu.Lock()
	s.closed = true
	s.mu.Unlock()
	s.close.Do(func() { close(s.done) })
	return nil
}

func (s *exampleSession) Done() <-chan struct{} { return s.done }

func (s *exampleSession) Err() error { return nil }

type exampleStream struct {
	session *exampleSession
}

func (s exampleStream) Next(context.Context) (agent.Event, error) {
	s.session.mu.Lock()
	defer s.session.mu.Unlock()
	if s.session.next == len(s.session.events) {
		return agent.Event{}, io.EOF
	}
	event := s.session.events[s.session.next]
	s.session.next++
	return event, nil
}

func exampleEvent(
	sessionID string,
	sequence int,
	itemID string,
	payload agent.Payload,
) agent.Event {
	return agent.Event{
		EventID:   fmt.Sprintf("00000000-0000-4000-8000-%012d", sequence),
		SessionID: sessionID,
		Time:      time.Date(2026, 11, 8, 0, 0, sequence, 0, time.UTC),
		ItemID:    itemID,
		Payload:   payload,
	}
}

func mustExample(err error) {
	if err != nil {
		panic(err)
	}
}
Output:
model id=model value="next/model" sent=true accepted=true
effort id=effort value="next/effort" sent=true accepted=true

type ConfigID

type ConfigID string

ConfigID identifies one adapter-neutral runtime session configuration value.

const (
	ConfigModel  ConfigID = "model"
	ConfigEffort ConfigID = "effort"
)

type ConfigOption

type ConfigOption struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	Description  string `json:"description,omitempty"`
	Category     string `json:"category,omitempty"`
	Type         string `json:"type"`
	CurrentValue any    `json:"currentValue"`
	Options      any    `json:"options,omitempty"`
}

func (*ConfigOption) UnmarshalJSON

func (o *ConfigOption) UnmarshalJSON(data []byte) error

type ConfigOptionGroup

type ConfigOptionGroup struct {
	Group   string              `json:"group"`
	Name    string              `json:"name"`
	Options []ConfigOptionValue `json:"options"`
}

type ConfigOptionUpdatePayload

type ConfigOptionUpdatePayload struct {
	ConfigOptions []ConfigOption `json:"configOptions"`
}

type ConfigOptionValue

type ConfigOptionValue struct {
	Value       string `json:"value"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

type ConfigReceipt

type ConfigReceipt struct {
	Change     ConfigChange
	Acceptance Acceptance
}

ConfigReceipt reports the change requested by this call and the native acceptance stages observed for it. Change echoes the request for every result, including invalid and closed-session failures; Acceptance.Sent distinguishes a change sent to the provider from one rejected before a native write. It does not claim that a configuration value is currently effective.

type ContentBlock

type ContentBlock struct {
	Text         *ContentBlockText         `json:"-"`
	Image        *ContentBlockImage        `json:"-"`
	Audio        *ContentBlockAudio        `json:"-"`
	ResourceLink *ContentBlockResourceLink `json:"-"`
	Resource     *ContentBlockResource     `json:"-"`
}

ContentBlock is one of the five supported input content kinds. Exactly one branch must be non-nil.

func (ContentBlock) MarshalJSON

func (b ContentBlock) MarshalJSON() ([]byte, error)

func (*ContentBlock) UnmarshalJSON

func (b *ContentBlock) UnmarshalJSON(data []byte) error

func (ContentBlock) Validate

func (b ContentBlock) Validate() error

Validate checks that exactly one content branch is present and valid.

type ContentBlockAudio

type ContentBlockAudio struct {
	Data        string
	MIMEType    string
	Annotations *Annotations
}

func (ContentBlockAudio) MarshalJSON

func (b ContentBlockAudio) MarshalJSON() ([]byte, error)

func (ContentBlockAudio) Validate

func (b ContentBlockAudio) Validate() error

Validate checks required media fields, Base64 data, and annotations.

type ContentBlockImage

type ContentBlockImage struct {
	Data        string
	MIMEType    string
	URI         *string
	Annotations *Annotations
}

func (ContentBlockImage) MarshalJSON

func (b ContentBlockImage) MarshalJSON() ([]byte, error)

func (ContentBlockImage) Validate

func (b ContentBlockImage) Validate() error

Validate checks required media fields, Base64 data, and annotations.

type ContentBlockResource

type ContentBlockResource struct {
	Resource    EmbeddedResource
	Annotations *Annotations
}

func (ContentBlockResource) MarshalJSON

func (b ContentBlockResource) MarshalJSON() ([]byte, error)

func (ContentBlockResource) Validate

func (b ContentBlockResource) Validate() error

Validate checks the embedded resource and annotations.

type ContentBlockResourceLink struct {
	URI         string
	Name        string
	MIMEType    *string
	Title       *string
	Description *string
	Size        *int64
	Annotations *Annotations
}

func (ContentBlockResourceLink) MarshalJSON

func (b ContentBlockResourceLink) MarshalJSON() ([]byte, error)

func (ContentBlockResourceLink) Validate

func (b ContentBlockResourceLink) Validate() error

Validate checks required link fields, nonnegative size, and annotations.

type ContentBlockText

type ContentBlockText struct {
	Text        string
	Annotations *Annotations
}

func (ContentBlockText) MarshalJSON

func (b ContentBlockText) MarshalJSON() ([]byte, error)

func (ContentBlockText) Validate

func (b ContentBlockText) Validate() error

Validate checks the text block's annotations and string encoding.

type Core

type Core interface {
	// Start acquires Core-scoped resources and enters the started state.
	// It returns the base capabilities supplied by the adapter; the lifecycle
	// freezes a copy and returns copies from repeated calls without creating
	// another owner. After an admitted Stop, Start cannot be called again.
	Start(ctx context.Context) (Capabilities, error)

	// Open creates a new native main session with a nonempty, stable identity.
	// An adapter may assign that identity through an official native creation
	// option and return after initialization, before later session notifications.
	// The Core must have been started successfully.
	Open(ctx context.Context, options OpenOptions) (Session, error)

	// Resume restores an existing native main session instead of creating one.
	// The Core must have been started successfully. Saved native history may
	// support recovery but must not be emitted as live events.
	Resume(ctx context.Context, options ResumeOptions) (Session, error)

	// Stop releases only resources owned by this Core. It rejects the call
	// while any Open or Resume is in flight or any session remains open. Once
	// admitted, Stop is terminal even if release fails: it releases at most
	// once, caches the release result, and prevents later Start, Open, or Resume.
	// Repeating Stop returns the same cached result.
	Stop(ctx context.Context) error
}

Core owns Core-scoped lifecycle resources. An adapter may share one native connection across sessions or create native resources per session.

Example

ExampleCore shows one application flow over two synthetic adapters. The production adapter constructors are agentcodex.New and agentclaude.New. This example keeps both providers offline so it never launches a native CLI.

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"sync"
	"time"

	"github.com/zoumo/agent-sdk-go/agent"
	agentclaude "github.com/zoumo/agent-sdk-go/agent/claude"

	agentcodex "github.com/zoumo/agent-sdk-go/agent/codex"
)

func main() {
	ctx := context.Background()
	for _, providerName := range []string{"codex", "claude"} {
		provider := newExampleProvider(providerName)
		capabilities, err := provider.Start(ctx)
		mustExample(err)
		fmt.Printf("%s text_input=%t\n", providerName, capabilities.Supports(agent.CapabilityTextInput))

		options := agent.OpenOptions{Cwd: "/synthetic"}
		session, err := provider.Open(ctx, options)
		mustExample(err)
		fmt.Printf("%s open=%s\n", providerName, session.ID())

		stream, err := session.Events()
		mustExample(err)
		receipt, err := session.StartOrSteer(ctx, agent.Input{
			Content: []agent.ContentBlock{{Text: &agent.ContentBlockText{Text: "Explain the change"}}},
		})
		mustExample(err)
		fmt.Printf("%s start_or_steer=%s\n", providerName, receipt.Submission)

		idle := false
		for !idle {
			event, nextErr := stream.Next(ctx)
			if errors.Is(nextErr, io.EOF) {
				panic("event stream ended before idle")
			}
			mustExample(nextErr)
			switch payload := event.Payload.(type) {
			case agent.UserMessage:
				fmt.Printf("%s event=%s text=%q\n",
					providerName, event.Type(), exampleMessageText(payload.Content))
			case agent.InteractionRequestedPayload:
				fmt.Printf("%s interaction=%s tool=%s\n",
					providerName, payload.Interaction, payload.Request.ToolCallID)
				answerReceipt, answerErr := session.Answer(
					ctx,
					payload.Interaction,
					agent.PermissionAnswer{
						Outcome:  agent.PermissionSelected,
						OptionID: "allow-once",
					},
				)
				mustExample(answerErr)
				fmt.Printf("%s answer=%s\n", providerName, answerReceipt.Interaction)
			case agent.InteractionClosedPayload:
				fmt.Printf("%s event=%s outcome=%s\n",
					providerName, event.Type(), payload.Outcome)
			case agent.AgentMessage:
				fmt.Printf("%s event=%s text=%q\n",
					providerName, event.Type(), exampleMessageText(payload.Content))
			case agent.StateUpdatePayload:
				idle = payload.State != nil && *payload.State == agent.StateIdle
			}
		}
		mustExample(session.Close(ctx))
		fmt.Printf("%s close=ok\n", providerName)

		resumed, err := provider.Resume(ctx, agent.ResumeOptions{
			SessionID:   session.ID(),
			OpenOptions: options,
		})
		mustExample(err)
		fmt.Printf("%s resume=%s\n", providerName, resumed.ID())
		mustExample(resumed.Close(ctx))
		mustExample(provider.Stop(ctx))
		fmt.Printf("%s stop=ok\n", providerName)
	}

	var _ agent.Core = agentcodex.New(agentcodex.Config{})
	var _ agent.Core = agentclaude.New(agentclaude.Config{})
	fmt.Println("codex and claude adapters implement agent.Core")

}

type exampleProvider struct {
	name     string
	mu       sync.Mutex
	started  bool
	stopped  bool
	sessions map[string]*exampleSession
}

func newExampleProvider(name string) *exampleProvider {
	return &exampleProvider{name: name, sessions: make(map[string]*exampleSession)}
}

func (p *exampleProvider) Start(context.Context) (agent.Capabilities, error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.stopped {
		return nil, errors.New("provider stopped")
	}
	p.started = true
	return agent.Capabilities{
		agent.CapabilityTextInput:  true,
		agent.CapabilityPermission: true,
	}, nil
}

func (p *exampleProvider) Open(
	_ context.Context,
	options agent.OpenOptions,
) (agent.Session, error) {
	if err := options.Validate(); err != nil {
		return nil, err
	}
	return p.newSession(p.name + "-session")
}

func (p *exampleProvider) Resume(
	_ context.Context,
	options agent.ResumeOptions,
) (agent.Session, error) {
	if err := options.Validate(); err != nil {
		return nil, err
	}
	return p.newSession(options.SessionID)
}

func (p *exampleProvider) Stop(context.Context) error {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.stopped = true
	return nil
}

func (p *exampleProvider) newSession(
	id string,
) (agent.Session, error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if !p.started || p.stopped {
		return nil, errors.New("provider is not active")
	}
	created := newExampleSession(p.name, id)
	p.sessions[id] = created
	return created, nil
}

type exampleSession struct {
	provider string
	id       string
	events   []agent.Event
	next     int
	claimed  bool
	answered bool
	mu       sync.Mutex
	closed   bool
	done     chan struct{}
	close    sync.Once
}

func newExampleSession(
	provider, id string,
) *exampleSession {
	interaction := agent.InteractionRef(provider + "/interaction-1")
	idle := agent.StateIdle
	request := agent.InteractionRequest{
		Kind:       agent.InteractionPermission,
		ToolCallID: provider + "-tool",
		Title:      "Approve synthetic tool",
		Options: []agent.PermissionOption{{
			OptionID: "allow-once",
			Name:     "Allow once",
			Kind:     agent.PermissionAllow,
			Scope:    agent.PermissionScopeOnce,
		}},
	}
	return &exampleSession{
		provider: provider,
		id:       id,
		done:     make(chan struct{}),
		events: []agent.Event{
			exampleEvent(id, 1, "user-1", agent.UserMessage{
				MessageID: "user-1",
				Content:   []agent.ContentBlock{{Text: &agent.ContentBlockText{Text: "Explain the change"}}},
			}),
			exampleEvent(id, 2, "", agent.InteractionRequestedPayload{
				Interaction: interaction,
				Request:     request,
				Blocking:    true,
			}),
			exampleEvent(id, 3, "", agent.InteractionClosedPayload{
				Interaction: interaction,
				Outcome:     agent.InteractionAnswered,
				Reason:      "synthetic_answer",
			}),
			exampleEvent(id, 4, "agent-1", agent.AgentMessage{
				MessageID: "agent-1",
				Content: []agent.ContentBlock{
					{Text: &agent.ContentBlockText{Text: "Offline reply for " + provider}},
				},
			}),
			exampleEvent(id, 5, "", agent.StateUpdatePayload{State: &idle}),
		},
	}
}

func (s *exampleSession) ID() string { return s.id }

func (s *exampleSession) Capabilities() agent.Capabilities {
	return agent.Capabilities{
		agent.CapabilityTextInput:  true,
		agent.CapabilityPermission: true,
	}
}

func (s *exampleSession) EffectiveFeatures() agent.EffectiveFeatures {
	return agent.EffectiveFeatures{AgentQuestions: false}
}

func (s *exampleSession) SetConfig(
	ctx context.Context,
	change agent.ConfigChange,
) (agent.ConfigReceipt, error) {
	receipt := exampleConfigNotSent(change)
	if err := change.Validate(); err != nil {
		return receipt, err
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.closed {
		return receipt, &agent.Error{
			Code:    agent.ErrorClosed,
			Reason:  "session_closed",
			Message: "session is closed",
		}
	}
	if err := ctx.Err(); err != nil {
		return receipt, &agent.Error{
			Code:    agent.ErrorUnavailable,
			Reason:  "set_config_not_sent",
			Message: "session configuration was not sent",
			Cause:   err,
		}
	}
	sent, accepted := true, true
	return agent.ConfigReceipt{
		Change: change,
		Acceptance: agent.Acceptance{
			Sent:           &sent,
			NativeAccepted: &accepted,
		},
	}, nil
}

func exampleConfigNotSent(change agent.ConfigChange) agent.ConfigReceipt {
	sent := false
	return agent.ConfigReceipt{
		Change:     change,
		Acceptance: agent.Acceptance{Sent: &sent},
	}
}

func (s *exampleSession) Events() (agent.EventStream, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.closed {
		return nil, errors.New("session closed")
	}
	if s.claimed {
		return nil, errors.New("event stream already claimed")
	}
	s.claimed = true
	return exampleStream{session: s}, nil
}

func (s *exampleSession) StartOrSteer(
	ctx context.Context,
	input agent.Input,
) (agent.InputReceipt, error) {
	receipt, err := s.acceptInput(ctx, input)
	if err != nil {
		return agent.InputReceipt{}, err
	}
	receipt.Result = agent.InputAppliedBestEffort
	return receipt, nil
}

func (s *exampleSession) acceptInput(
	ctx context.Context,
	input agent.Input,
) (agent.InputReceipt, error) {
	if err := input.Validate(); err != nil {
		return agent.InputReceipt{}, err
	}
	if err := ctx.Err(); err != nil {
		return agent.InputReceipt{}, err
	}
	sent := true
	return agent.InputReceipt{
		Submission: s.provider + "-submission",
		Acceptance: agent.Acceptance{Sent: &sent},
	}, nil
}

func (s *exampleSession) Answer(
	ctx context.Context,
	interaction agent.InteractionRef,
	answer agent.Answer,
) (agent.InteractionReceipt, error) {
	if err := ctx.Err(); err != nil {
		return agent.InteractionReceipt{}, err
	}
	if err := agent.ValidateAnswer(agent.InteractionPermission, answer); err != nil {
		return agent.InteractionReceipt{}, err
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.closed {
		return agent.InteractionReceipt{}, errors.New("session closed")
	}
	if s.answered {
		return agent.InteractionReceipt{}, errors.New("interaction already answered")
	}
	if interaction != agent.InteractionRef(s.provider+"/interaction-1") {
		return agent.InteractionReceipt{}, errors.New("interaction is not owned by session")
	}
	s.answered = true
	sent := true
	return agent.InteractionReceipt{
		Interaction: interaction,
		Acceptance:  agent.Acceptance{Sent: &sent},
	}, nil
}

func (s *exampleSession) Interrupt(
	context.Context,
	agent.InterruptOptions,
) (agent.InterruptReceipt, error) {
	return agent.InterruptReceipt{Result: agent.InterruptNoActiveWork}, nil
}

func (s *exampleSession) Close(context.Context) error {
	s.mu.Lock()
	s.closed = true
	s.mu.Unlock()
	s.close.Do(func() { close(s.done) })
	return nil
}

func (s *exampleSession) Done() <-chan struct{} { return s.done }

func (s *exampleSession) Err() error { return nil }

type exampleStream struct {
	session *exampleSession
}

func (s exampleStream) Next(context.Context) (agent.Event, error) {
	s.session.mu.Lock()
	defer s.session.mu.Unlock()
	if s.session.next == len(s.session.events) {
		return agent.Event{}, io.EOF
	}
	event := s.session.events[s.session.next]
	s.session.next++
	return event, nil
}

func exampleEvent(
	sessionID string,
	sequence int,
	itemID string,
	payload agent.Payload,
) agent.Event {
	return agent.Event{
		EventID:   fmt.Sprintf("00000000-0000-4000-8000-%012d", sequence),
		SessionID: sessionID,
		Time:      time.Date(2026, 11, 8, 0, 0, sequence, 0, time.UTC),
		ItemID:    itemID,
		Payload:   payload,
	}
}

func exampleMessageText(content []agent.ContentBlock) string {
	if len(content) != 1 {
		return ""
	}
	if content[0].Text == nil {
		return ""
	}
	return content[0].Text.Text
}

func mustExample(err error) {
	if err != nil {
		panic(err)
	}
}
Output:
codex text_input=true
codex open=codex-session
codex start_or_steer=codex-submission
codex event=user.message text="Explain the change"
codex interaction=codex/interaction-1 tool=codex-tool
codex answer=codex/interaction-1
codex event=session.interaction_closed outcome=answered
codex event=agent.message text="Offline reply for codex"
codex close=ok
codex resume=codex-session
codex stop=ok
claude text_input=true
claude open=claude-session
claude start_or_steer=claude-submission
claude event=user.message text="Explain the change"
claude interaction=claude/interaction-1 tool=claude-tool
claude answer=claude/interaction-1
claude event=session.interaction_closed outcome=answered
claude event=agent.message text="Offline reply for claude"
claude close=ok
claude resume=claude-session
claude stop=ok
codex and claude adapters implement agent.Core

type EffectiveFeatures

type EffectiveFeatures struct {
	AgentQuestions bool
	// RestrictLocalTools reports whether the adapter configured local tool
	// restrictions. True does not mean every local tool is disabled. MCP, hooks
	// and the CLI process's own file access are outside this feature's scope.
	RestrictLocalTools bool
}

EffectiveFeatures reports the requested features that the adapter can configure for a session. These values describe adapter mappings, not a runtime tool inventory or an operating-system security boundary.

type EmbeddedResource

type EmbeddedResource struct {
	URI      string
	MIMEType *string
	Text     *string
	Blob     *string
}

func (EmbeddedResource) Validate

func (r EmbeddedResource) Validate() error

Validate requires exactly one of text or blob and validates their encoding.

type Error

type Error struct {
	Code    ErrorCode
	Reason  string
	Message string
	Cause   error
}

Error carries a stable classification while retaining the native cause. Message is suitable for callers and must not contain credentials or recovery material.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCode

type ErrorCode string

ErrorCode is a stable classification that callers may use without parsing native diagnostic text.

const (
	ErrorInvalidArgument    ErrorCode = "invalid_argument"
	ErrorFailedPrecondition ErrorCode = "failed_precondition"
	ErrorUnsupported        ErrorCode = "unsupported"
	ErrorUnavailable        ErrorCode = "unavailable"
	ErrorResourceExhausted  ErrorCode = "resource_exhausted"
	ErrorOutcomeUnknown     ErrorCode = "outcome_unknown"
	ErrorNativeRejected     ErrorCode = "native_rejected"
	ErrorClosed             ErrorCode = "closed"
)

func CodeOf

func CodeOf(err error) ErrorCode

CodeOf returns the nearest classified error code in err's unwrap chain. An empty result means the error has not been classified.

type Event

type Event struct {
	EventID   string
	SessionID string
	Time      time.Time
	ItemID    string
	Payload   Payload
	Meta      map[string]any
}

Event is one adapter-neutral live event. EventID identifies this event once; it is not an order or a persistent history cursor.

func (Event) MarshalJSON

func (e Event) MarshalJSON() ([]byte, error)

func (Event) Type

func (e Event) Type() EventType

Type returns the payload's fixed event type. It is empty when no payload is present.

func (*Event) UnmarshalJSON

func (e *Event) UnmarshalJSON(data []byte) error

func (Event) Validate

func (e Event) Validate() error

Validate checks the event envelope, the closed payload branch, and JSON-safe extension metadata.

type EventStream

type EventStream interface {
	// Next returns the next accepted event. io.EOF means normal completion;
	// other errors are stable abnormal termination causes. One stream must not
	// be read concurrently.
	Next(ctx context.Context) (Event, error)
}

EventStream is the single-consumer stream for one session.

type EventType

type EventType string

EventType identifies the single payload branch carried by an Event.

const (
	EventUserMessage               EventType = "user.message"
	EventAgentMessage              EventType = "agent.message"
	EventAgentThinking             EventType = "agent.thinking"
	EventAgentToolCall             EventType = "agent.tool_call"
	EventAgentToolResult           EventType = "agent.tool_result"
	EventAgentMessageChunk         EventType = "agent.message_chunk"
	EventAgentThinkingChunk        EventType = "agent.thinking_chunk"
	EventAgentToolCallChunk        EventType = "agent.tool_call_chunk"
	EventSessionStateUpdate        EventType = "session.state_update"
	EventSessionError              EventType = "session.error"
	EventSessionInfoUpdate         EventType = "session.info_update"
	EventSessionConfigOptionUpdate EventType = "session.config_option_update"
	EventSessionCommandsUpdate     EventType = "session.available_commands_update"
	EventSessionUsageUpdate        EventType = "session.usage_update"
	EventInteractionRequested      EventType = "session.interaction_requested"
	EventInteractionClosed         EventType = "session.interaction_closed"
)

type Features

type Features struct {
	AgentQuestions *bool
	// RestrictLocalTools applies available native restrictions to built-in local
	// file read, write and command tools. False leaves native defaults unchanged.
	// Restrictions are best-effort and do not guarantee all such tools are disabled.
	RestrictLocalTools bool
}

Features contains adapter-neutral runtime feature requests.

func (Features) AgentQuestionsEnabled

func (f Features) AgentQuestionsEnabled() bool

AgentQuestionsEnabled reports the requested value, applying the current default of true when the request omits the field.

type FormAnswer

type FormAnswer struct {
	Outcome FormOutcome
	Content map[string]any
}

type FormOutcome

type FormOutcome string
const (
	FormAccept  FormOutcome = "accept"
	FormDecline FormOutcome = "decline"
	FormCancel  FormOutcome = "cancel"
)

type InfoUpdatePayload

type InfoUpdatePayload struct {
	Title     *string    `json:"title,omitempty"`
	UpdatedAt *time.Time `json:"updatedAt,omitempty"`
}

type InjectReceipt

type InjectReceipt struct {
	Acceptance Acceptance
}

InjectReceipt records only the observed acceptance stages of an injection. It has no work identity and does not prove model consumption or persistence. An outcome_unknown error must not be retried without reconciliation.

type Injector

type Injector interface {
	Inject(ctx context.Context, input Input) (InjectReceipt, error)
}

Injector is an optional Session operation that appends user context without requesting a model response. Native consumption timing is provider-specific. Inject never starts, steers, interrupts, queues or retries work on the caller's behalf. Callers must serialize it with other input operations for ordering.

type Input

type Input struct {
	Content []ContentBlock
}

Input is an ordered sequence of adapter-neutral content blocks.

func (Input) MarshalJSON

func (i Input) MarshalJSON() ([]byte, error)

func (*Input) UnmarshalJSON

func (i *Input) UnmarshalJSON(data []byte) error

func (Input) Validate

func (i Input) Validate() error

Validate checks that the input contains at least one valid content block.

type InputReceipt

type InputReceipt struct {
	Submission string
	Result     InputResult
	Acceptance Acceptance
}

InputReceipt identifies a submission, describes the observed result, and records the acceptance stages observed for it. Submission identifies the applied input; it is empty for InputNotApplied and does not prove execution started or completed.

type InputResult

type InputResult string

InputResult describes what the provider could truthfully confirm about input after StartOrSteer. The values are part of the public contract.

const (
	// InputAppliedCurrentWork means the provider accepted the input as current
	// work already observed for the session.
	InputAppliedCurrentWork InputResult = "applied_current_work"
	// InputAppliedNewWork means the provider accepted the input with a new work
	// identity, or no current work was known before the operation.
	InputAppliedNewWork InputResult = "applied_new_work"
	// InputAppliedBestEffort means the local write succeeded but the provider did
	// not prove where or whether the input was scheduled. An adapter may retain
	// internal candidate state for attribution without changing this result.
	InputAppliedBestEffort InputResult = "applied_best_effort"
	// InputNotApplied means the input was definitely not applied. Submission is
	// empty; the caller retains the input and controls any retry.
	InputNotApplied InputResult = "not_applied"
)

type InteractionClosedPayload

type InteractionClosedPayload struct {
	Interaction InteractionRef     `json:"interaction"`
	Outcome     InteractionOutcome `json:"outcome"`
	Reason      string             `json:"reason,omitempty"`
}

type InteractionKind

type InteractionKind string
const (
	InteractionPermission InteractionKind = "permission"
	InteractionForm       InteractionKind = "form"
	InteractionURL        InteractionKind = "url"
)

type InteractionOutcome

type InteractionOutcome string
const (
	InteractionAnswered  InteractionOutcome = "answered"
	InteractionCompleted InteractionOutcome = "completed"
	InteractionCancelled InteractionOutcome = "cancelled" //nolint:misspell // Published event value.
	InteractionExpired   InteractionOutcome = "expired"
	InteractionFailed    InteractionOutcome = "failed"
)

type InteractionReceipt

type InteractionReceipt struct {
	Interaction InteractionRef
	Acceptance  Acceptance
}

InteractionReceipt identifies the answered interaction and acceptance stages observed during the answer operation.

type InteractionRef

type InteractionRef string

InteractionRef is an opaque reference to one live native request. It grants no authority outside the adapter and session that created it.

type InteractionRequest

type InteractionRequest struct {
	Kind            InteractionKind
	ToolCallID      string
	Title           string
	Options         []PermissionOption
	Content         []ContentBlock
	Message         string
	URL             string
	RequestedSchema map[string]any
}

func (InteractionRequest) MarshalJSON

func (r InteractionRequest) MarshalJSON() ([]byte, error)

func (*InteractionRequest) UnmarshalJSON

func (r *InteractionRequest) UnmarshalJSON(data []byte) error

func (InteractionRequest) Validate

func (r InteractionRequest) Validate() error

Validate checks the fields required by the request's interaction kind and rejects fields that belong to another kind.

type InteractionRequestedPayload

type InteractionRequestedPayload struct {
	Interaction InteractionRef     `json:"interaction"`
	Request     InteractionRequest `json:"request"`
	Blocking    bool               `json:"blocking"`
}

type InterruptOptions

type InterruptOptions struct{}

InterruptOptions is reserved for adapter-neutral interrupt options.

type InterruptReceipt

type InterruptReceipt struct {
	Target string
	Result InterruptResult
}

InterruptReceipt identifies the target work known to the session and the control acknowledgement observed for the interrupt.

type InterruptResult

type InterruptResult string

InterruptResult describes the native control outcome of an interrupt.

const (
	InterruptAcknowledged InterruptResult = "control_acknowledged"
	InterruptNoActiveWork InterruptResult = "no_active_work"
)

type MessageChunk

type MessageChunk MessagePayload

type MessagePayload

type MessagePayload struct {
	MessageID string         `json:"messageId"`
	Content   []ContentBlock `json:"content"`
	Phase     string         `json:"phase,omitempty"`
}

type ObservedError

type ObservedError struct {
	Code    any    `json:"code,omitempty"`
	Message string `json:"message"`
}

type OpenOptions

type OpenOptions struct {
	Cwd string
	// PermissionPreset selects the approval and sandbox settings for this
	// operation. Core.Open and Core.Resume default to PermissionPresetAutoReview.
	PermissionPreset PermissionPreset
	// ProcessEnv is an additive, set-only overlay for a Claude Session CLI.
	// Nil or empty leaves the provider environment unchanged; empty values set
	// variables to empty strings. Other adapters reject nonempty declarations.
	ProcessEnv map[string]string
	// ShellEnv adds variables to Codex shell/unified-exec environments. It does
	// not change the app-server environment. Claude rejects nonempty declarations.
	ShellEnv map[string]string
	// AdditionalSystemPrompt appends caller text after provider defaults for
	// this Open or Resume operation. Empty omits provider-native prompt
	// configuration. See docs/modules/unified-agent/design.md#additional-system-prompt
	// for the complete contract.
	AdditionalSystemPrompt string
	AdditionalDirs         []string
	Features               Features
	// MCPServers is the complete final external MCP list for this operation. The
	// caller composes Runtime defaults with Session declarations before calling a
	// provider, which does not merge them again. Resume callers must repeat the
	// complete list because the SDK does not persist it.
	MCPServers []mcp.Server

	Config SessionConfig
}

OpenOptions contains adapter-neutral creation options. An adapter that cannot enforce a nonzero option rejects it before native side effects, except for the best-effort RestrictLocalTools feature. Adapter-specific creation options belong on the concrete adapter.

Example (McpServers)

ExampleOpenOptions_mcpServers shows the shared external MCP list accepted by Open and Resume. EnvHeaders and BearerTokenEnvVar use environment-variable names for Codex; the Claude adapter accepts the common stdio and HTTP URL/Headers subset and rejects those two Codex-specific HTTP references.

This example only validates parameters. It does not resolve a secret, launch a native CLI, or connect to an MCP server.

package main

import (
	"fmt"

	"github.com/zoumo/agent-sdk-go/agent"
	"github.com/zoumo/agent-sdk-go/mcp"
)

func main() {
	options := agent.OpenOptions{
		Cwd: "/synthetic/workspace",
		MCPServers: []mcp.Server{
			{
				Name:      "local-tools",
				Transport: mcp.TransportStdio,
				Command:   "mcp-local",
				Args:      []string{"--stdio"},
				Env:       map[string]string{"LOCAL_TOOLS_MODE": "read-only"},
			},
			{
				Name:              "remote-tools",
				Transport:         mcp.TransportHTTP,
				URL:               "https://mcp.example.invalid/tools",
				Headers:           map[string]string{"X-Workspace": "sdk"},
				EnvHeaders:        map[string]string{"Authorization": "REMOTE_AUTHORIZATION"},
				BearerTokenEnvVar: "REMOTE_TOKEN",
			},
		},
	}
	if err := options.Validate(); err != nil {
		fmt.Println("invalid:", err)
		return
	}

	fmt.Printf("validated %d final MCP servers\n", len(options.MCPServers))
	for _, server := range options.MCPServers {
		fmt.Printf("%s transport=%s\n", server.Name, server.Transport)
	}

	resume := agent.ResumeOptions{
		SessionID:   "saved-session",
		OpenOptions: options,
	}
	if err := resume.Validate(); err != nil {
		fmt.Println("invalid resume:", err)
		return
	}
	fmt.Printf("resume parameters validated with %d servers\n", len(resume.MCPServers))

}
Output:
validated 2 final MCP servers
local-tools transport=stdio
remote-tools transport=http
resume parameters validated with 2 servers

func (OpenOptions) Validate

func (o OpenOptions) Validate() error

Validate checks the adapter-neutral creation options before native side effects. Adapter-specific support is checked by the adapter.

type Payload

type Payload interface {
	// contains filtered or unexported methods
}

Payload is a closed event-payload union. Its unexported method prevents implementations outside this package.

type PermissionAnswer

type PermissionAnswer struct {
	Outcome  PermissionOutcome
	OptionID string
}

type PermissionOption

type PermissionOption struct {
	OptionID string               `json:"optionId"`
	Name     string               `json:"name"`
	Kind     PermissionOptionKind `json:"kind"`
	Scope    PermissionScope      `json:"scope,omitempty"`
}

type PermissionOptionKind

type PermissionOptionKind string
const (
	PermissionAllow  PermissionOptionKind = "allow"
	PermissionReject PermissionOptionKind = "reject"
	PermissionCancel PermissionOptionKind = "cancel"
)
const (
	PermissionAllowOnce    PermissionOptionKind = "allow_once"
	PermissionAllowAlways  PermissionOptionKind = "allow_always"
	PermissionRejectOnce   PermissionOptionKind = "reject_once"
	PermissionRejectAlways PermissionOptionKind = "reject_always"
)

Deprecated: These kinds preserve historical events. The old "always" kinds did not distinguish session approval from a persistent policy change.

type PermissionOutcome

type PermissionOutcome string
const (
	PermissionSelected  PermissionOutcome = "selected"
	PermissionCancelled PermissionOutcome = "cancelled" //nolint:misspell // Native contract spelling.
)

type PermissionPreset

type PermissionPreset string

PermissionPreset selects the approval and sandbox settings for one session open or resume. Each adapter maps the preset to its native controls.

const (
	PermissionPresetManualReview PermissionPreset = "manualReview"
	PermissionPresetAutoReview   PermissionPreset = "autoReview"
	PermissionPresetFullAccess   PermissionPreset = "fullAccess"
)

type PermissionScope

type PermissionScope string

PermissionScope is the validity period of an allow or reject option.

const (
	PermissionScopeOnce    PermissionScope = "once"
	PermissionScopeTurn    PermissionScope = "turn"
	PermissionScopeSession PermissionScope = "session"
	PermissionScopeAlways  PermissionScope = "always"
)

func (*PermissionScope) UnmarshalJSON

func (s *PermissionScope) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects explicit empty and null scopes. A scope-free option omits the JSON member entirely.

type ResumeOptions

type ResumeOptions struct {
	SessionID string
	OpenOptions
}

ResumeOptions identifies an existing native main session to resume.

func (ResumeOptions) Validate

func (o ResumeOptions) Validate() error

Validate checks the adapter-neutral resume options before native side effects.

type Session

type Session interface {
	// ID is the nonempty native main-session identity fixed before Open or
	// Resume returns. It remains unchanged for the attachment's lifetime.
	ID() string

	Capabilities() Capabilities
	EffectiveFeatures() EffectiveFeatures

	// Events returns the session's only event stream. Only the first successful
	// call may return a stream; later calls must fail. A stream has one
	// consumer and retains accepted events for draining after Close.
	Events() (EventStream, error)

	// StartOrSteer validates and copies input before writing to the native
	// protocol. It tries to join acceptable active work, otherwise it starts or
	// hands the input to native scheduling. It never queues, waits for idle,
	// persists, or retries. An adapter may retain internal attribution state for
	// accepted input without claiming the provider scheduled it. InputNotApplied
	// leaves Submission empty and leaves the input with the caller.
	StartOrSteer(ctx context.Context, input Input) (InputReceipt, error)

	// Answer rechecks the live session, current work, request identity, and
	// answer kind before sending. An interaction is answerable at most once.
	Answer(
		ctx context.Context,
		interaction InteractionRef,
		answer Answer,
	) (InteractionReceipt, error)

	// Interrupt targets work already confirmed for this session. It returns
	// no_active_work without a native interrupt when no work is active.
	Interrupt(
		ctx context.Context,
		options InterruptOptions,
	) (InterruptReceipt, error)

	// Close releases this session attachment and its session-owned resources
	// without stopping the provider or recursively stopping all child agents. It
	// rejects new operations, invalidates unsettled interactions, does not wait
	// for external consumers, and returns the same cleanup result when repeated.
	Close(ctx context.Context) error

	// Done closes when session interaction terminates. Err retains the first
	// stable termination cause.
	Done() <-chan struct{}
	Err() error
}

Session owns one native main-session attachment, its interaction authority, and native resources whose lifetime ends with the session.

type SessionConfig

type SessionConfig struct {
	Model  string
	Effort string
}

SessionConfig contains provider-native configuration for a main session. An empty field is omitted and is not a request to clear or restore a default. Nonempty values are passed literally without trimming, aliasing or cross-provider conversion.

func (SessionConfig) Validate

func (c SessionConfig) Validate() error

Validate checks session configuration before native side effects. Empty values are valid because they omit the option.

type SessionErrorPayload

type SessionErrorPayload struct {
	Message string `json:"message"`
	Reason  string `json:"reason,omitempty"`
}

type SessionState

type SessionState string
const (
	StateIdle           SessionState = "idle"
	StateRunning        SessionState = "running"
	StateRequiresAction SessionState = "requires_action"
)

type Span

type Span interface {
	// TraceContext returns a carrier for provider propagation. A zero or invalid
	// carrier falls back to the valid carrier from the submission context.
	TraceContext() TraceContext
	// End receives the returned business error exactly once before return.
	End(err error)
}

Span covers only the StartOrSteer call, not execution or later events. Implementations must be non-blocking; SDK calls isolate telemetry panics.

type StateUpdatePayload

type StateUpdatePayload struct {
	PreviousState *SessionState  `json:"previousState"`
	State         *SessionState  `json:"state"`
	StopReason    string         `json:"stopReason,omitempty"`
	Error         *ObservedError `json:"error,omitempty"`
}

type ThinkingChunk

type ThinkingChunk MessagePayload

type ToolCallPayload

type ToolCallPayload struct {
	ID                  string         `json:"id"`
	Kind                ToolKind       `json:"kind"`
	ToolName            string         `json:"toolName"`
	Provider            ToolProvider   `json:"provider"`
	Title               string         `json:"title,omitempty"`
	Phase               string         `json:"phase,omitempty"`
	InputRepresentation string         `json:"inputRepresentation,omitempty"`
	RawInput            any            `json:"rawInput"`
	RawOutput           *any           `json:"rawOutput,omitempty"`
	Content             []ContentBlock `json:"content,omitempty"`
	ExitCode            *int32         `json:"exitCode,omitempty"`
	DurationMs          *float64       `json:"durationMs,omitempty"`
	Output              *ToolOutput    `json:"output,omitempty"`
	Status              string         `json:"status,omitempty"`
}

ToolCallPayload records an observed provider-native tool call. ToolName and Provider form the required identity; Kind is a required action category. Status is a native-specific lifecycle projection.

func (ToolCallPayload) MarshalJSON

func (p ToolCallPayload) MarshalJSON() ([]byte, error)

func (*ToolCallPayload) UnmarshalJSON

func (p *ToolCallPayload) UnmarshalJSON(data []byte) error

type ToolChunkPayload

type ToolChunkPayload struct {
	ID      string         `json:"id"`
	Content []ContentBlock `json:"content"`
}

ToolChunkPayload is partial tool input. It intentionally carries only the call ID and content because a chunk may precede the complete tool identity.

type ToolKind

type ToolKind string

ToolKind is the closed, ACP-derived cross-agent action category for a tool. It is display and routing metadata, not a permission decision or evidence of behavioral equivalence between providers.

const (
	ToolKindRead       ToolKind = "read"
	ToolKindEdit       ToolKind = "edit"
	ToolKindDelete     ToolKind = "delete"
	ToolKindMove       ToolKind = "move"
	ToolKindSearch     ToolKind = "search"
	ToolKindExecute    ToolKind = "execute"
	ToolKindThink      ToolKind = "think"
	ToolKindFetch      ToolKind = "fetch"
	ToolKindSwitchMode ToolKind = "switch_mode"
	ToolKindOther      ToolKind = "other"
)

ToolKind values classify a tool independently of its invocation arguments.

type ToolOutput

type ToolOutput struct {
	Availability string      `json:"availability"`
	Completeness string      `json:"completeness"`
	Truncation   *Truncation `json:"truncation,omitempty"`
}

type ToolProvider

type ToolProvider string

ToolProvider identifies who provides a tool. Valid values are exactly ToolProviderAgent, ToolProviderDynamic, ToolProviderMCP, or a nonempty "mcp:<server>" suffix. The server suffix may contain additional colons.

const (
	ToolProviderAgent   ToolProvider = "agent"
	ToolProviderDynamic ToolProvider = "dynamic"
	ToolProviderMCP     ToolProvider = "mcp"
)

Fixed ToolProvider values. A located MCP server is constructed as ToolProvider("mcp:" + server) rather than another constant.

type ToolResultPayload

type ToolResultPayload struct {
	ID                  string         `json:"id"`
	Kind                ToolKind       `json:"kind"`
	ToolName            string         `json:"toolName"`
	Provider            ToolProvider   `json:"provider"`
	Title               string         `json:"title,omitempty"`
	Phase               string         `json:"phase,omitempty"`
	InputRepresentation string         `json:"inputRepresentation,omitempty"`
	RawInput            *any           `json:"rawInput,omitempty"`
	RawOutput           *any           `json:"rawOutput,omitempty"`
	Content             []ContentBlock `json:"content,omitempty"`
	ExitCode            *int32         `json:"exitCode,omitempty"`
	DurationMs          *float64       `json:"durationMs,omitempty"`
	Output              *ToolOutput    `json:"output,omitempty"`
	Status              string         `json:"status"`
}

ToolResultPayload records an observed provider-native tool result. Its provider and tool name must equal the call identity remembered by the adapter, and its kind must equal the call classification. The core validates this event independently rather than reconstructing missing fields from another event.

func (ToolResultPayload) MarshalJSON

func (p ToolResultPayload) MarshalJSON() ([]byte, error)

func (*ToolResultPayload) UnmarshalJSON

func (p *ToolResultPayload) UnmarshalJSON(data []byte) error

type TraceContext

type TraceContext struct {
	// Traceparent is the W3C traceparent value.
	Traceparent string
	// Tracestate is propagated only with a valid Traceparent.
	Tracestate string
}

TraceContext carries the W3C parent for one prompt submission. It is call metadata and is never encoded into Input or unified events.

func TraceContextFromContext

func TraceContextFromContext(ctx context.Context) (TraceContext, bool)

TraceContextFromContext returns the stored value; presence does not imply validity. Derived contexts inherit the value using normal context rules.

func (TraceContext) Validate

func (trace TraceContext) Validate() error

Validate checks the W3C carrier without changing it.

type Tracer

type Tracer interface {
	StartSpan(ctx context.Context, name string, parent *TraceContext) Span
}

Tracer creates one local submission span. Implementations must be safe for concurrent use and non-blocking. A non-nil parent takes precedence over any active span in ctx. With no explicit parent, ctx may supply an active span. Returning nil disables the span. SDK calls isolate telemetry panics.

type Truncation

type Truncation struct {
	RetainedBytes int64  `json:"retainedBytes"`
	OmittedBytes  *int64 `json:"omittedBytes,omitempty"`
}

type URLAnswer

type URLAnswer struct {
	Outcome URLOutcome
}

type URLOutcome

type URLOutcome string
const (
	URLAccept  URLOutcome = "accept"
	URLDecline URLOutcome = "decline"
	URLCancel  URLOutcome = "cancel"
)

type UsageCost

type UsageCost struct {
	Amount   json.Number `json:"amount"`
	Currency string      `json:"currency"`
}

type UsageUpdatePayload

type UsageUpdatePayload struct {
	Used int64 `json:"used"`
	// Size is zero when the provider did not report a context-window size.
	Size int64      `json:"size"`
	Cost *UsageCost `json:"cost,omitempty"`
}

type UserMessage

type UserMessage MessagePayload

Directories

Path Synopsis
Package agentclaude adapts the native Claude Session to the adapter-neutral live agent contract.
Package agentclaude adapts the native Claude Session to the adapter-neutral live agent contract.
Package agentcodex adapts the native Codex app-server SDK to the optional adapter-neutral agent runtime contract.
Package agentcodex adapts the native Codex app-server SDK to the optional adapter-neutral agent runtime contract.
internal
corelease
Package corelease owns the Core-scoped state shared by unified Agent adapters.
Package corelease owns the Core-scoped state shared by unified Agent adapters.
eventenvelope
Package eventenvelope builds validated adapter-neutral event envelopes.
Package eventenvelope builds validated adapter-neutral event envelopes.
interactionledger
Package interactionledger owns adapter-neutral interaction authority state.
Package interactionledger owns adapter-neutral interaction authority state.
submissiontrace
Package submissiontrace owns the best-effort span lifecycle of one admitted unified submission.
Package submissiontrace owns the best-effort span lifecycle of one admitted unified submission.
telemetry
Package telemetry instruments the public operations of the unified adapters.
Package telemetry instruments the public operations of the unified adapters.

Jump to

Keyboard shortcuts

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