Documentation
¶
Overview ¶
Package agents adapts remote task creation and the toolsy-step-stream-v1 SSE/cancel extension to toolsy.Tool. It is not a remote workflow scheduler.
Index ¶
- func AsBackgroundTool(name, desc string, schema []byte, client *Client) (toolsy.Tool, error)
- func AsTool(name, description string, inputSchema []byte, client *Client) (toolsy.Tool, error)
- func WithAllowPrivateIPs(allow bool) func(*ClientOptions)
- func WithCancellationObserver(observer CancellationObserver) func(*ClientOptions)
- func WithHTTPSettings(settings httptool.ClientSettings) func(*ClientOptions)
- func WithMaxResponseBody(n int) func(*ClientOptions)
- func WithMaxSSEStreamBytes(n int) func(*ClientOptions)
- func WithStreamPolicy(policy StreamPolicy) func(*ClientOptions)
- type AcceptedTaskReference
- type Artifact
- type CancellationDiagnostic
- type CancellationObserver
- type CancellationStage
- type Client
- func (c *Client) CancelTask(ctx context.Context, taskID string, authHeader string) error
- func (c *Client) CloseIdleConnections()
- func (c *Client) CreateTask(ctx context.Context, args json.RawMessage, authHeader string) (*Task, error)
- func (c *Client) StreamSteps(ctx context.Context, taskID, authHeader string) iter.Seq2[Step, error]
- type ClientOptions
- type Outcome
- type RemoteOutcomeError
- type Step
- type StreamPolicy
- type Task
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AsBackgroundTool ¶
AsBackgroundTool returns an AcceptedTaskReference after creation acknowledgement, without claiming completion.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"github.com/skosovsky/toolsy"
"github.com/skosovsky/toolsy/agents"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"task_id":"remote-1","artifacts":[]}`))
}))
defer server.Close()
client, err := agents.NewClient(server.URL, agents.WithAllowPrivateIPs(true))
if err != nil {
panic(err)
}
defer client.CloseIdleConnections()
tool, err := agents.AsBackgroundTool("start", "Start remote work", []byte(`{"type":"object"}`), client)
if err != nil {
panic(err)
}
// A host-owned store. Production hosts choose persistence and status retrieval.
references := make(map[string]agents.AcceptedTaskReference)
err = tool.Execute(
context.Background(),
toolsy.NewRunEnv(nil),
toolsy.ToolInput{ArgsJSON: []byte(`{}`)},
func(chunk toolsy.Chunk) error {
var reference agents.AcceptedTaskReference
if decodeErr := json.Unmarshal(chunk.Data, &reference); decodeErr != nil {
return decodeErr
}
references[reference.TaskID] = reference
return nil
},
)
if err != nil {
panic(err)
}
fmt.Println(references["remote-1"].Accepted)
}
Output: true
func AsTool ¶
AsTool adapts remote task creation and the toolsy-step-stream-v1 observation extension. inputSchema is the JSON Schema the host must satisfy; args are sent as task input.
func WithAllowPrivateIPs ¶ added in v0.11.0
func WithAllowPrivateIPs(allow bool) func(*ClientOptions)
WithAllowPrivateIPs relaxes SSRF IP blocking on the default safe transport (tests and private networks).
func WithCancellationObserver ¶ added in v0.18.0
func WithCancellationObserver(observer CancellationObserver) func(*ClientOptions)
WithCancellationObserver installs optional host diagnostics for parent-triggered cancellation attempts. Nil disables diagnostics. Observations do not replace the primary execution error or appear in tool output. No observer is invoked on stream-only timeout or consumer stop while the parent remains active.
func WithHTTPSettings ¶ added in v0.18.0
func WithHTTPSettings(settings httptool.ClientSettings) func(*ClientOptions)
WithHTTPSettings applies explicit timeout/TLS settings to the owned safe pool.
func WithMaxResponseBody ¶ added in v0.11.2
func WithMaxResponseBody(n int) func(*ClientOptions)
WithMaxResponseBody sets the maximum REST response body size in bytes (default 4 MiB).
func WithMaxSSEStreamBytes ¶ added in v0.11.2
func WithMaxSSEStreamBytes(n int) func(*ClientOptions)
WithMaxSSEStreamBytes sets the total byte budget for SSE step streams (default httptool.DefaultMaxSSEStreamBytes).
func WithStreamPolicy ¶ added in v0.17.0
func WithStreamPolicy(policy StreamPolicy) func(*ClientOptions)
WithStreamPolicy replaces all read limits. Timeout/event size must be positive; reconnect count and backoff must be nonnegative. Invalid policy fails before dispatch.
Types ¶
type AcceptedTaskReference ¶ added in v0.17.0
type AcceptedTaskReference struct {
TaskID string `json:"task_id"`
Accepted bool `json:"accepted"`
}
AcceptedTaskReference acknowledges creation only. The host owns persistence, status retrieval and continuation; Accepted never means business completion.
type Artifact ¶
type Artifact struct {
ArtifactID string `json:"artifact_id"`
FileName string `json:"file_name"`
MimeType string `json:"mime_type,omitempty"` // e.g. "image/png"
Data string `json:"data,omitempty"` // Base64 when server includes inline data
}
Artifact represents a file or data generated by the agent (multimodal output).
type CancellationDiagnostic ¶ added in v0.18.0
type CancellationDiagnostic struct {
TaskID string
ParentInterrupt error
ParentCause error
Stage CancellationStage
Acknowledged bool
Cause error
}
CancellationDiagnostic is a host-only observation, never retry authorization. TaskID and Cause can contain untrusted/sensitive observations; inspect deliberately.
type CancellationObserver ¶ added in v0.18.0
type CancellationObserver func(ctx context.Context, diagnostic CancellationDiagnostic)
CancellationObserver observes one best-effort cleanup synchronously. It must be safe for concurrent client calls, cooperate with ctx and not panic. Its lifetime is host-owned; the adapter cannot preempt a blocking opaque observer.
type CancellationStage ¶ added in v0.18.0
type CancellationStage string
CancellationStage identifies where interrupted-task cleanup completed or failed.
const ( // CancellationCredentials means cancellation credentials could not be resolved. CancellationCredentials CancellationStage = "credentials" // CancellationRequest means CancelTask was called; acknowledgement is not remote completion. CancellationRequest CancellationStage = "request" )
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client uses Agent Protocol task envelopes and the custom toolsy step-stream extension.
func NewClient ¶
func NewClient(baseURL string, opts ...func(*ClientOptions)) (*Client, error)
NewClient creates an Agent Protocol client with one owned safe pool. Invalid HTTP settings fail construction.
func (*Client) CancelTask ¶
CancelTask requests cancellation through the custom toolsy step-stream extension. A successful HTTP acknowledgement does not prove remote execution stopped.
func (*Client) CloseIdleConnections ¶ added in v0.18.0
func (c *Client) CloseIdleConnections()
CloseIdleConnections releases this client's owned idle pool; active calls are unaffected. Stop initiating calls before disposing the configuration. This is not terminal Close.
func (*Client) CreateTask ¶
func (c *Client) CreateTask(ctx context.Context, args json.RawMessage, authHeader string) (*Task, error)
CreateTask sends POST /ap/v1/agent/tasks with object args in additional_input. Unknown acceptance is reported explicitly.
type ClientOptions ¶
type ClientOptions struct {
HTTPSettings httptool.ClientSettings
// contains filtered or unexported fields
}
ClientOptions configures the remote task HTTP/SSE extension adapter.
type Outcome ¶ added in v0.17.0
type Outcome string
Outcome identifies what is known about remote business completion.
const ( // PhaseCreate marks an action whose acceptance may be unknown. PhaseCreate = "create" // PhaseObserve marks read failure after a known task reference. PhaseObserve = "observe" OutcomeFailed Outcome = "failed" OutcomeCancelled Outcome = "cancelled" OutcomeIncomplete Outcome = "incomplete" OutcomeMalformed Outcome = "malformed" OutcomeUnknown Outcome = "unknown" )
type RemoteOutcomeError ¶ added in v0.17.0
type RemoteOutcomeError struct {
// Phase is create or observe; create errors may have no recoverable task ID.
Phase string
Outcome Outcome
TaskID string
Step *Step
Cause error
}
RemoteOutcomeError preserves a task reference and partial observation without declaring success or granting permission to repeat task creation.
func (*RemoteOutcomeError) Error ¶ added in v0.17.0
func (e *RemoteOutcomeError) Error() string
func (*RemoteOutcomeError) Unwrap ¶ added in v0.17.0
func (e *RemoteOutcomeError) Unwrap() error
type Step ¶
type Step struct {
StepID string `json:"step_id"`
TaskID string `json:"task_id"`
Name string `json:"name"`
Status string `json:"status"` // created/running/completed; extension terminal failed/cancelled.
IsLast bool `json:"is_last"`
Output string `json:"output,omitempty"`
Artifacts []Artifact `json:"artifacts,omitempty"`
}
Step represents one step of the agent's internal execution (streamed via SSE).
func (*Step) UnmarshalJSON ¶ added in v0.17.0
UnmarshalJSON validates the required fields of the pinned v1 Step envelope. Extension statuses are checked separately so protocol failures remain typed outcomes.
type StreamPolicy ¶ added in v0.17.0
type StreamPolicy struct {
MaxReconnects int
Backoff time.Duration
Timeout time.Duration
MaxEventBytes int
}
StreamPolicy bounds one logical read, including reconnects. Zero reconnects disables resume.
func DefaultStreamPolicy ¶ added in v0.17.0
func DefaultStreamPolicy() StreamPolicy
DefaultStreamPolicy limits reads to five minutes, two reconnects and 1 MiB per event.
type Task ¶
type Task struct {
TaskID string `json:"task_id"`
Input *string `json:"input"` // Optional normative string/null input; BYO arguments use additional_input.
Artifacts []Artifact `json:"artifacts"`
}
Task projects the creation envelope from the supported Agent Protocol subset.
func (*Task) UnmarshalJSON ¶ added in v0.17.0
UnmarshalJSON prevents case-insensitive aliases from changing task references.