Documentation
¶
Index ¶
- Constants
- Variables
- func InheritCredentials(fromHome, toHome string) ([]string, error)
- func RedactedID(value string) string
- func ShutdownInstance(ctx context.Context, instance Instance) error
- type BackgroundProgress
- type Client
- func (c *Client) AttachSession(ctx context.Context, id string) (Session, error)
- func (c *Client) Capabilities() []string
- func (c *Client) Close() error
- func (c *Client) CreateSession(ctx context.Context, options CreateSessionOptions) (Session, error)
- func (c *Client) DetachInstance() (Instance, bool)
- func (c *Client) ForkSession(ctx context.Context, id string) (Session, error)
- func (c *Client) Notify(req protocol.RawRequest) error
- func (c *Client) Reconnect(ctx context.Context) error
- func (c *Client) Request(ctx context.Context, req protocol.RawRequest) (protocol.ServerFrame, error)
- func (c *Client) RequestCapability(ctx context.Context, capability string, req protocol.RawRequest) (protocol.ServerFrame, error)
- func (c *Client) RequireCapability(capability string) error
- func (c *Client) SessionID() string
- func (c *Client) SetSessionID(sessionID string)
- func (c *Client) State() State
- func (c *Client) Subscribe(sessionID string) *Subscription
- func (c *Client) Supports(capability string) bool
- type Compacted
- type CompatibilityError
- type ConnectOptions
- type ConnectionPhase
- type CreateSessionOptions
- type CredentialUpdated
- type Event
- type EventError
- type EventSemanticClass
- type FileContent
- type FileStatus
- type Files
- type Instance
- type LaunchError
- type LaunchErrorCode
- type LaunchOptions
- type MessageAccepted
- type ModelInfo
- type ModelRouteInfo
- type Models
- type Observation
- type Observer
- type OptionError
- type Options
- type PermissionRequest
- type ReasoningDelta
- type ReasoningDone
- type ReconnectPolicy
- type RenderedImage
- type RenderedImageAnchor
- type RenderedImageSource
- type RuntimeInfo
- type SendOptions
- type Session
- type SessionForked
- type SessionInfo
- type SessionRenamed
- type SessionStatus
- type SidePaneImages
- type State
- type Subscription
- type TextDelta
- type TextMatch
- type TextMatches
- type TokenUsage
- type ToolDone
- type ToolExec
- type ToolInputDelta
- type ToolStart
- type Turn
- type TurnDone
- type TurnResult
- type TurnResultKind
- type TypedEvent
- type TypedEventStream
- type UnknownEvent
- type WakeRequested
Constants ¶
const ( EventSemanticClassContentProgress EventSemanticClass = "content_progress" EventSemanticClassAdvisoryLifecycle EventSemanticClass = "advisory_lifecycle" EventSemanticClassTerminal EventSemanticClass = "terminal" EventSemanticClassPermission EventSemanticClass = "permission" EventSemanticClassToolEffect EventSemanticClass = "tool_effect" // Short aliases keep handler switches readable while the prefixed names // remain unambiguous in generated documentation and downstream code. SemanticClassContentProgress = EventSemanticClassContentProgress SemanticClassAdvisoryLifecycle = EventSemanticClassAdvisoryLifecycle SemanticClassTerminal = EventSemanticClassTerminal SemanticClassPermission = EventSemanticClassPermission SemanticClassToolEffect = EventSemanticClassToolEffect )
Variables ¶
var ( ErrClosed = errors.New("jcode client closed") ErrDisconnected = errors.New("jcode client disconnected") ErrSubscriberOverflow = errors.New("jcode event subscriber fell behind") ErrCapability = errors.New("jcode capability is not supported") ErrResume = errors.New("jcode session resume failed") )
var ( // ErrTurnCanceled reports explicit server-side cancellation of an owned turn. ErrTurnCanceled = errors.New("jcode turn canceled") // ErrProtocolFailure reports that an owned turn ended because protocol input // could not be framed, validated, or decoded safely. ErrProtocolFailure = errors.New("jcode turn protocol failure") // ErrBridgeExited reports positive evidence that the SDK-owned bridge process // attached to the client exited. ErrBridgeExited = errors.New("jcode bridge exited") )
var ErrInvalidOptions = errors.New("invalid options")
ErrInvalidOptions classifies validation failures in typed SDK options.
var ErrTurnNoReply = errors.New("jcode turn does not support no-reply messages")
ErrTurnNoReply reports that StartTurn was called for a notification-only message, which cannot have an owned turn lifecycle.
Functions ¶
func InheritCredentials ¶
InheritCredentials shares rotating auth files and copies mutable config.
func RedactedID ¶
RedactedID can be used by applications to correlate a session without placing the raw identifier in logs.
func ShutdownInstance ¶ added in v0.1.5
ShutdownInstance shuts down an Instance while allowing a caller context to shorten the cooperative phase of SDK-owned Linux private instances. The Instance interface remains unchanged so external implementations stay source compatible. Cancellation never skips best-effort termination and cleanup.
Types ¶
type BackgroundProgress ¶ added in v0.1.5
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func Connect ¶
func Connect(ctx context.Context, options ConnectOptions) (*Client, error)
Connect attaches to a running local Jcode harness. It never starts or stops a process, and closing the returned client only closes its socket.
func Launch ¶
func Launch(ctx context.Context, options LaunchOptions) (*Client, error)
Launch starts a private bridge and connects a Client to it. Any failure after the process starts performs best-effort teardown before returning.
func NewClient ¶
NewClient starts reading from t and completes the protocol hello handshake. The transport is closed if the handshake fails. Reconnect is always explicit.
func (*Client) AttachSession ¶
func (*Client) Capabilities ¶
Capabilities returns the server-advertised capabilities in stable order. The returned slice is a copy and may be modified by the caller.
func (*Client) CreateSession ¶
func (*Client) DetachInstance ¶ added in v0.1.2
DetachInstance transfers ownership of a private runtime from the client to the caller. After a successful detach, closing the client only closes its protocol transport. The returned Instance remains responsible for the private process, daemon, and SDK-owned state until Shutdown is called.
This is the safe-run boundary for applications that let a worker client come and go while a session owner supervises the runtime independently.
func (*Client) ForkSession ¶ added in v0.1.8
ForkSession clones a session's persisted context into a new session.
func (*Client) Notify ¶ added in v0.1.3
func (c *Client) Notify(req protocol.RawRequest) error
Notify writes a request without waiting for a correlated request-level reply. Use this for protocol operations whose result is delivered as an event.
func (*Client) Reconnect ¶
Reconnect explicitly reconnects and, when configured, safely reattaches the remembered session. In-flight requests are never retried.
func (*Client) Request ¶
func (c *Client) Request(ctx context.Context, req protocol.RawRequest) (protocol.ServerFrame, error)
Request sends a raw request. It never retries, preserving caller control for non-idempotent operations such as send_message.
func (*Client) RequestCapability ¶
func (c *Client) RequestCapability(ctx context.Context, capability string, req protocol.RawRequest) (protocol.ServerFrame, error)
RequestCapability sends req only when the server advertised capability. Unlike Request, this performs a local check and never writes an unsupported request to the wire.
func (*Client) RequireCapability ¶
RequireCapability returns a stable error before a capability-gated request.
func (*Client) SessionID ¶
SessionID returns the caller-selected identity retained across reconnects.
func (*Client) SetSessionID ¶
func (*Client) Subscribe ¶
func (c *Client) Subscribe(sessionID string) *Subscription
Subscribe receives asynchronous events. A full buffer terminates only that subscription, keeping the reader bounded and other callers live.
type CompatibilityError ¶ added in v0.1.5
CompatibilityError is a payload-free, bounded failure for an unsupported or semantically unclassified owned-turn event.
func (*CompatibilityError) Error ¶ added in v0.1.5
func (e *CompatibilityError) Error() string
func (*CompatibilityError) Unwrap ¶ added in v0.1.5
func (*CompatibilityError) Unwrap() error
type ConnectOptions ¶
ConnectOptions controls attaching to an already-running local harness.
type ConnectionPhase ¶ added in v0.1.5
type CreateSessionOptions ¶
type CredentialUpdated ¶ added in v0.1.6
type CredentialUpdated struct {
Provider string `json:"provider"`
Configured bool `json:"configured"`
}
CredentialUpdated reports whether a provider credential is configured.
type Event ¶
type Event struct {
Frame protocol.ServerFrame
Kind string
Fields json.RawMessage
}
Event is a server event with its stable kind and forward-compatible fields.
type EventError ¶ added in v0.1.5
EventError reports a typed error emitted by the harness. It preserves the protocol code and safe message fields for callers that need to classify request or provider failures without inspecting raw protocol frames.
func (EventError) Error ¶ added in v0.1.5
func (e EventError) Error() string
type EventSemanticClass ¶ added in v0.1.5
type EventSemanticClass string
EventSemanticClass is the closed handling policy for an owned-turn event.
func SemanticClassOf ¶ added in v0.1.5
func SemanticClassOf(event TypedEvent) (EventSemanticClass, bool)
SemanticClassOf returns the reviewed class for a known concrete event. Unknown, nil, and unclassified values deliberately return false.
type FileContent ¶ added in v0.1.6
type FileContent struct {
SessionID string `json:"session_id"`
Path string `json:"path"`
Content string `json:"content"`
Size uint64 `json:"size"`
Truncated bool `json:"truncated"`
}
FileContent is the result of reading a file through the harness.
type FileStatus ¶ added in v0.1.6
type FileStatus struct {
SessionID string `json:"session_id"`
Path string `json:"path"`
Exists bool `json:"exists"`
Kind string `json:"kind"`
Size *uint64 `json:"size,omitempty"`
ModifiedMS *uint64 `json:"modified_ms,omitempty"`
}
FileStatus reports file existence and optional metadata.
type Instance ¶
LaunchInstance is the ownership handle for a private runtime.
func LaunchInstance ¶
func LaunchInstance(options LaunchOptions) (Instance, error)
LaunchInstance starts an isolated bridge without connecting the protocol client. This is useful when the caller needs to control connection setup.
type LaunchError ¶
type LaunchError struct {
Code LaunchErrorCode
Binary string
Stderr string
Err error
}
LaunchError reports a failure in private-instance startup or connection.
func (*LaunchError) Error ¶
func (e *LaunchError) Error() string
func (*LaunchError) Unwrap ¶
func (e *LaunchError) Unwrap() error
type LaunchErrorCode ¶
type LaunchErrorCode string
LaunchErrorCode identifies the phase which failed while starting an instance. Callers can use errors.As to inspect a LaunchError without parsing its human-readable message.
const ( LaunchMissingBinary LaunchErrorCode = "missing_binary" LaunchStartupFailed LaunchErrorCode = "startup_failed" LaunchStartupTimeout LaunchErrorCode = "startup_timeout" LaunchHandshakeFailed LaunchErrorCode = "handshake_failed" LaunchTransportFailed LaunchErrorCode = "transport_failed" )
type LaunchOptions ¶
type LaunchOptions struct {
// JcodeHome is a persistent state directory. Empty creates a temporary
// SDK-owned directory which is removed by Shutdown.
JcodeHome string
WorkingDir string
// InheritLogins is tri-state so its nil zero value preserves the SDK
// behavior shared by the Rust and TypeScript SDKs: inherit by default.
InheritLogins *bool
Binary string
// Provider and Model are passed as global jcode CLI selections when starting
// the private API bridge. Empty values preserve jcode's normal auto/config
// resolution.
Provider string
Model string
Env map[string]string
StartupTimeout time.Duration
CleanupTimeout time.Duration
// ShutdownGracePeriod bounds cooperative SIGTERM shutdown before Linux
// private instances escalate to SIGKILL. Non-positive values use 5 seconds.
ShutdownGracePeriod time.Duration
// ShutdownReapTimeout bounds waiting for the single bridge Wait result after
// termination attempts. Non-positive values use 5 seconds.
ShutdownReapTimeout time.Duration
InheritStderr bool
// ClientOptions controls the protocol client created by Launch.
ClientOptions Options
// Observer receives redacted startup lifecycle metadata. If set, it is also
// used by the protocol client created by Launch unless ClientOptions.Observer
// is explicitly provided.
Observer Observer
}
LaunchOptions controls a private jcode instance.
type MessageAccepted ¶ added in v0.1.5
type MessageAccepted struct {
SessionID string `json:"session_id"`
}
type ModelRouteInfo ¶ added in v0.1.6
type ModelRouteInfo struct {
Model string `json:"model"`
Provider string `json:"provider"`
APIMethod string `json:"api_method"`
Available bool `json:"available"`
Detail string `json:"detail"`
}
ModelRouteInfo describes one provider route exposed by the runtime.
type Models ¶ added in v0.1.6
type Models struct {
SessionID string `json:"session_id"`
Models []string `json:"models"`
Current string `json:"current,omitempty"`
}
Models reports the models available to a session and its current model.
type Observation ¶
type Observation struct {
Kind string
State State
Request string
Error string
Attempts int
// EventKind, EventType, and Disposition are set only for the bounded
// advisory compatibility observation emitted by an owned Turn.
EventKind string
EventType string
Disposition string
// Outcome is set only for an immutable terminal turn observation.
Outcome TurnResultKind
}
Observation contains only bounded lifecycle metadata. It intentionally excludes request fields, prompts, credentials and environment values, server response or tool content, raw frames, private paths, and session identifiers.
type Observer ¶
type Observer interface{ Observe(Observation) }
Observer receives redacted lifecycle metadata. Implementations must be safe for concurrent calls and should return quickly. Request events and the launch, connect, owned-turn, and Linux private-instance phases identify a stalled boundary without exposing payloads, credentials, paths, or identifiers.
type OptionError ¶ added in v0.1.6
type OptionError struct {
Field string
}
OptionError identifies the typed option field that failed validation. It intentionally retains no rejected value.
func (*OptionError) Error ¶ added in v0.1.6
func (e *OptionError) Error() string
func (*OptionError) Unwrap ¶ added in v0.1.6
func (*OptionError) Unwrap() error
type Options ¶
type Options struct {
ClientName string
MaxFrameSize int
EventBuffer int
RequestBuffer int
// RequestTimeout bounds each request when the caller's context has no
// earlier deadline. Non-positive values use the 30-second default.
RequestTimeout time.Duration
SessionID string
Reconnect ReconnectPolicy
Observer Observer
}
Options controls client construction and event buffering.
type PermissionRequest ¶
type ReasoningDelta ¶
type ReasoningDone ¶ added in v0.1.5
type ReconnectPolicy ¶
type RenderedImage ¶ added in v0.1.6
type RenderedImage struct {
MediaType string `json:"media_type"`
Data string `json:"data"`
Label *string `json:"label,omitempty"`
Source RenderedImageSource `json:"source"`
Anchor *RenderedImageAnchor `json:"anchor,omitempty"`
}
RenderedImage is an image and its optional transcript placement metadata.
type RenderedImageAnchor ¶ added in v0.1.6
type RenderedImageAnchor struct {
Kind string `json:"kind"`
ID string `json:"id,omitempty"`
Ordinal uint64 `json:"ordinal,omitempty"`
}
RenderedImageAnchor identifies where a rendered image belongs in a transcript.
type RenderedImageSource ¶ added in v0.1.6
type RenderedImageSource struct {
Kind string `json:"kind"`
ToolName string `json:"tool_name,omitempty"`
Role string `json:"role,omitempty"`
}
RenderedImageSource identifies where a rendered image originated.
type RuntimeInfo ¶ added in v0.1.6
type RuntimeInfo struct {
SessionID string `json:"session_id"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
ReasoningEffort string `json:"reasoning_effort,omitempty"`
Routes []ModelRouteInfo `json:"routes"`
}
RuntimeInfo reports provider identity and every route exposed by the runtime.
type SendOptions ¶
type Session ¶
type Session struct {
Info SessionInfo
ID string
// contains filtered or unexported fields
}
func (Session) StartTurn ¶ added in v0.1.5
func (s Session) StartTurn(lifecycleCtx context.Context, content string, options SendOptions) (*Turn, error)
StartTurn starts one owned turn. Its subscription and dispatcher are ready before send_message is written, so fast acceptance and terminal events cannot be missed. The method returns after the write succeeds, before acceptance.
type SessionForked ¶ added in v0.1.8
type SessionForked struct {
Session SessionInfo `json:"session"`
}
SessionForked reports the new session returned by ForkSession.
type SessionInfo ¶
type SessionInfo struct {
ID string `json:"session_id"`
WorkingDir string `json:"working_dir,omitempty"`
Title string `json:"title,omitempty"`
Status string `json:"status"`
TranscriptBytes uint64 `json:"transcript_bytes,omitempty"`
Archived bool `json:"archived,omitempty"`
ArchivedAtMS uint64 `json:"archived_at_ms,omitempty"`
}
SessionInfo is the stable session metadata returned by the harness API.
type SessionRenamed ¶ added in v0.1.6
type SessionRenamed struct {
SessionID string `json:"session_id"`
Title *string `json:"title,omitempty"`
DisplayTitle string `json:"display_title"`
}
SessionRenamed reports a session title change. Title is nil when cleared.
type SessionStatus ¶ added in v0.1.5
type SidePaneImages ¶ added in v0.1.6
type SidePaneImages struct {
SessionID string `json:"session_id"`
Images []RenderedImage `json:"images"`
}
SidePaneImages reports images produced for the attached session.
type Subscription ¶
type Subscription struct {
// contains filtered or unexported fields
}
func (*Subscription) Close ¶
func (s *Subscription) Close()
type TextMatch ¶ added in v0.1.6
type TextMatch struct {
Path string `json:"path"`
Line uint32 `json:"line"`
Column uint32 `json:"column"`
Preview string `json:"preview"`
}
TextMatch identifies one text search result.
type TextMatches ¶ added in v0.1.6
type TextMatches struct {
SessionID string `json:"session_id"`
Matches []TextMatch `json:"matches"`
}
TextMatches is the result of searching text through the harness.
type TokenUsage ¶
type ToolInputDelta ¶
type Turn ¶ added in v0.1.5
type Turn struct {
// contains filtered or unexported fields
}
Turn owns one prompt lifecycle, including its single underlying event subscription, acceptance, ordered typed events, explicit cancellation, and immutable terminal result.
func (*Turn) Accepted ¶ added in v0.1.5
Accepted waits only for server acceptance. Canceling ctx interrupts this wait without changing the turn lifecycle or sending protocol cancellation.
func (*Turn) Cancel ¶ added in v0.1.5
Cancel starts the protocol cancel request at most once. The request runs under the Client request timeout, while each caller's ctx bounds only that caller's wait for the shared attempt result. A successful request is not terminal.
func (*Turn) Next ¶ added in v0.1.5
func (t *Turn) Next(ctx context.Context) (TypedEvent, error)
Next returns the turn's typed events in server order. message_accepted is exposed through Accepted rather than duplicated in this stream. Only one goroutine may call Next at a time. Canceling ctx interrupts only this read.
type TurnResult ¶ added in v0.1.5
type TurnResult struct {
Kind TurnResultKind
Err error
}
TurnResult is the immutable outcome stored by a Turn. Err preserves the underlying cause for errors.Is and errors.As inspection.
type TurnResultKind ¶ added in v0.1.5
type TurnResultKind string
TurnResultKind identifies the stable semantic terminal class of a turn.
const ( // TurnResultCompleted reports successful turn completion. TurnResultCompleted TurnResultKind = "completed" // TurnResultCanceled reports explicit server-side turn cancellation. TurnResultCanceled TurnResultKind = "canceled" // TurnResultLifecycleCanceled reports local lifecycle context cancellation. TurnResultLifecycleCanceled TurnResultKind = "lifecycle_canceled" // TurnResultLifecycleDeadlineExceeded reports local lifecycle deadline expiry. TurnResultLifecycleDeadlineExceeded TurnResultKind = "lifecycle_deadline_exceeded" // TurnResultProviderError reports a provider failure event. TurnResultProviderError TurnResultKind = "provider_error" // TurnResultProtocolError reports invalid framing, protocol data, or typed event data. TurnResultProtocolError TurnResultKind = "protocol_error" // TurnResultSubscriberOverflow reports a bounded event queue overflow. TurnResultSubscriberOverflow TurnResultKind = "subscriber_overflow" // TurnResultBridgeExited reports exit of the attached SDK-owned bridge. TurnResultBridgeExited TurnResultKind = "bridge_exited" // TurnResultTransportDisconnected reports loss of the client transport. TurnResultTransportDisconnected TurnResultKind = "transport_disconnected" // TurnResultClientClosed reports local Client.Close termination. TurnResultClientClosed TurnResultKind = "client_closed" )
type TypedEvent ¶
type TypedEvent interface {
// contains filtered or unexported methods
}
type TypedEventStream ¶
type TypedEventStream struct {
// contains filtered or unexported fields
}
func (*TypedEventStream) Close ¶
func (s *TypedEventStream) Close()
func (*TypedEventStream) Next ¶
func (s *TypedEventStream) Next(ctx context.Context) (TypedEvent, error)
type UnknownEvent ¶
type UnknownEvent struct {
Kind string
Fields json.RawMessage
}
type WakeRequested ¶ added in v0.1.8
type WakeRequested struct {
SessionID string `json:"session_id"`
Reason string `json:"reason"`
Notification string `json:"notification"`
}
WakeRequested asks an external operator to decide when to run a session.