utils

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 21 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

pi: utils/diagnostics.ts.

pi: utils/error-body.ts.

Shared normalization for provider HTTP error objects. Endpoints behind a proxy / gateway may return a non-2xx response whose body the provider SDK cannot fold into error.message; pig's adapters return *ProviderHTTPError for those, and NormalizeProviderError extracts status/body from it.

pi: utils/estimate.ts.

pi: utils/hash.ts.

pi: utils/headers.ts.

pi: utils/json-parse.ts.

pi: utils/node-http-proxy.ts.

Resolves the HTTP(S) proxy URL for an outbound provider request from proxy environment variables, honoring NO_PROXY exclusions. First consumers: bedrock-converse-stream (NodeHttpHandler proxy agents) and openai-codex-responses; pig re-uses it wherever a proxy-aware transport is assembled.

pi: src/utils/overflow.ts — context-overflow detection from assistant error messages and usage.

Go's regexp is RE2: every pi pattern here is RE2-compatible (no backreferences or lookarounds), so the patterns port verbatim.

pi: utils/pi-user-agent.ts.

pi: utils/provider-env.ts.

pi: utils/provider-retry.ts.

Reproduces the retry behavior used by the OpenAI and Anthropic SDKs while making their backoff sleep interruptible. Their built-in retry timers ignore the request AbortSignal, so callers must invoke the SDK with maxRetries: 0 and wrap the request with this helper. Provider-requested delays above MaxRetryDelayMS fail immediately (60s default); set it to 0 to disable the limit.

pi: src/utils/retry.ts — bounded retry for assistant-producing calls with transient-error classification.

Deviations:

  • pi's sleep-with-abort-signal collapses to a context-aware timer; RetrySleepAbortError has no counterpart (ctx.Err() plays that role).
  • RetryCallbacks members may return Promise in TS; Go callbacks are synchronous (per the pi-Promise → sync-callback rule).
  • produce may return an error, which propagates immediately (pi's produce() promise rejection propagates the same way).

pi: utils/sanitize-unicode.ts.

pi: src/utils/text.ts — extract and join text from message content.

Package ai/utils: transcript normalization helpers (pi: src/utils/transcript.ts, #9548 mid-conversation system messages).

The prompt and tool declarations live in the transcript's system messages. These helpers build, replay, collapse, and diff that state.

pi: src/utils/uuid.ts — time-ordered UUIDv7 generation.

Deviations:

  • TS keeps lastTimestamp/sequence as module-level mutable state relying on the single-threaded event loop; Go guards them with a package-level mutex (same monotonic-counter semantics: same-millisecond calls advance the sequence, sequence wrap bumps the millisecond).
  • TS falls back to Math.random when crypto.getRandomValues is missing; Go always uses crypto/rand.

pi: utils/validation.ts (exported through pi-ai's index; pig re-exports it from ai/index.go).

Validates tool call arguments against a tool's JSON Schema, coercing near-miss values (string "42" into a number parameter, null into "" and so on) the way providers' own SDKs do before failing the call.

Language-convergence deviations from the TS source, all declared here:

  • TS carries two paths: a TypeBox validator (Compile/Value.Convert) for TypeBox schemas and a hand-rolled JSON Schema coercion path for plain JSON schemas. pig has no TypeBox: tool schemas are JSON Schema documents by definition (types.Tool.Parameters is json.RawMessage), so the two paths merge into one — the hand-rolled coercion rules are the single coercion pass, and validation uses a checker over the same schema subset. Value.Convert's coercion space is covered by coerceWithJSONSchema; the merged pass is at least as coercive.
  • The TYPEBOX_KIND symbol escape hatch (schemas with custom TypeBox kinds skip the JSON Schema coercion pass) has no Go counterpart; every schema goes through coercion.
  • The schema subset handled is the one TS's JsonSchemaObject already commits to (type/properties/required/items/additionalProperties/ allOf/anyOf/oneOf) plus enum/const, which TypeBox tool schemas use heavily. Missing, to add when a real tool schema needs them: numeric and string bound keywords (minimum/maximum/minLength/maxLength/pattern /format) and $ref resolution inside validation (normalizeOptionalNulls already treats $ref properties as opaque, matching TS).
  • Validator error message strings differ from TypeBox's (no Go TypeBox to mirror); the message *shape* — "Validation failed for tool "x":" header, " - <path>: <message>" lines, received-arguments dump — is preserved because callers surface it verbatim in tool results.

Index

Constants

View Source
const MaxProviderErrorBodyChars = 4000

MaxProviderErrorBodyChars caps the raw HTTP body kept in NormalizedProviderError.

View Source
const UnsupportedProxyProtocolMessage = "Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL."

UnsupportedProxyProtocolMessage is pi's UNSUPPORTED_PROXY_PROTOCOL_MESSAGE.

Variables

View Source
var DefaultMaxAgentRetryDelayMs int64 = 60_000

DefaultMaxAgentRetryDelayMs is the default cap for agent-level retry delays (pi: DEFAULT_MAX_AGENT_RETRY_DELAY_MS).

Functions

func AppendAssistantMessageDiagnostic

func AppendAssistantMessageDiagnostic(message *types.AssistantMessage, diagnostic types.AssistantMessageDiagnostic)

AppendAssistantMessageDiagnostic appends one diagnostic to the message's diagnostics list (pi: appendAssistantMessageDiagnostic). pi rebuilds the array; pig appends in place — the message is adapter-owned during streaming.

func CalculateContextTokens

func CalculateContextTokens(usage *types.Usage) int64

CalculateContextTokens returns the reported context size of one usage block (pi: calculateContextTokens).

func CollapseSystemMessages added in v0.86.0

func CollapseSystemMessages(context *aitypes.TranscriptContext) *aitypes.TranscriptContext

CollapseSystemMessages rebuilds the transcript for APIs without mid-conversation system messages: the replayed system message leads, and every later system message is dropped.

func ContentText

func ContentText(content []types.Content, separator string) string

ContentText extracts and joins text from message content (pi: contentText). Non-text blocks are skipped; separator defaults to "\n" at call sites in pi (pass it explicitly here).

func CreateAssistantMessageDiagnostic

func CreateAssistantMessageDiagnostic(diagType string, err any, details map[string]any) types.AssistantMessageDiagnostic

CreateAssistantMessageDiagnostic builds one error diagnostic stamped now (pi: createAssistantMessageDiagnostic).

func CreateInitialSystemMessage added in v0.86.0

func CreateInitialSystemMessage(systemPrompt string, tools []tool) *systemMessage

CreateInitialSystemMessage builds the leading system message for a prompt and tool set. Returns nil when both are empty, so an empty transcript stays empty.

func DeclarationsEqual added in v0.86.0

func DeclarationsEqual(left, right tool) bool

DeclarationsEqual reports whether two tools declare the same interface to the model. Both sides go through ToToolDeclaration first: its JSON round-trip drops the typebox symbol keys and undefined fields that a structural comparison would see, and builds both objects with the same key order, so comparing the serialized declarations is exact. This avoids a deep-equal dependency in a browser-safe package.

func EstimateMessageTokens

func EstimateMessageTokens(message types.Message) int64

EstimateMessageTokens estimates the tokens of one message (pi: estimateMessageTokens).

func EstimateTextAndImageContentTokens

func EstimateTextAndImageContentTokens(content *types.UserContent) int64

EstimateTextAndImageContentTokens estimates the tokens of a user/tool-result content body (pi: estimateTextAndImageContentTokens).

func EstimateTextTokens

func EstimateTextTokens(text string) int64

EstimateTextTokens estimates the token count of a text (pi: estimateTextTokens).

func ExtractDiagnosticError

func ExtractDiagnosticError(err error) types.DiagnosticErrorInfo

ExtractDiagnosticError flattens a thrown error into diagnostic info (pi: extractDiagnosticError). pi's Error-shaped name/message/stack/code have no uniform Go counterpart: name comes from DiagnosticErrorNamer (falling back to "ThrownValue" only for nil), message from Error(), stack and code from the optional interfaces above.

func FormatProviderError

func FormatProviderError(norm NormalizedProviderError, prefix string) string

FormatProviderError composes a display string from a normalized error (pi: formatProviderError). When the message already carries the body or no body/status was extracted, the message is returned unchanged. Otherwise the status and body are surfaced, with an optional provider prefix:

  • no prefix: "<status>: <body>"
  • prefix: "<prefix> (<status>): <body>"

func FormatThrownValue

func FormatThrownValue(value any) string

FormatThrownValue renders a thrown value as a string (pi: formatThrownValue): an error's message (falling back to its name), a string as-is, anything else via its default string form.

func GetCurrentSystemMessage added in v0.86.0

func GetCurrentSystemMessage(messages TranscriptMessages) *systemMessage

GetCurrentSystemMessage replays every system message into one leading system message holding the current prompt and tools. Later Content is appended to the base prompt, Sections are patched by name, and tools are resolved with GetCurrentTools.

func GetCurrentSystemPrompt added in v0.86.0

func GetCurrentSystemPrompt(messages TranscriptMessages) string

GetCurrentSystemPrompt renders the current system prompt text after replaying every system message.

func GetCurrentTools added in v0.86.0

func GetCurrentTools(messages TranscriptMessages) []tool

GetCurrentTools resolves the tools available after applying every transcript delta in order.

pi builds a single TS Map: delete drops the key, set on an existing key updates in place, set on a deleted/new key appends at the end of the iteration order. The ordered slice below emulates exactly that (a two-pass rebuild would leave stale entries for add-then-remove histories).

func GetDeclaredTools added in v0.86.0

func GetDeclaredTools(messages TranscriptMessages) []tool

GetDeclaredTools returns every definition referenced by transcript tool state, in first-declaration order.

func GetInitialSystemMessage added in v0.86.0

func GetInitialSystemMessage(messages TranscriptMessages) *systemMessage

GetInitialSystemMessage returns the leading system message, if the transcript starts with one.

func GetPiUserAgent

func GetPiUserAgent() string

GetPiUserAgent builds the user agent sent to providers (pi: getPiUserAgent). pi renders `pi (<platform> <release>; <arch>)` from the runtime OS, or "pi (browser)" when it cannot reach node:os; pig always runs on a native OS, so it renders the native form. The release string comes from `uname -r` (the same kernel release node:os surfaces) and falls back to the GOOS string when uname is unavailable.

func GetProviderEnvValue

func GetProviderEnvValue(name string, env types.ProviderEnv) string

GetProviderEnvValue resolves a provider env value from scoped overrides, then normal process env (pi: getProviderEnvValue). pi's third fallback — a duplicate of process.env read from /proc/self/environ for Bun compiled binaries inside Linux sandboxes — has no Go counterpart: the Go runtime's os.Getenv already reads the real environment, so the workaround is unnecessary here.

func GetSystemMessageText added in v0.86.0

func GetSystemMessageText(message *types.SystemMessage) string

GetSystemMessageText renders a system message as a complete prompt: its content followed by its sections (pi: getSystemMessageText).

func HasNonAdditiveToolChanges added in v0.86.0

func HasNonAdditiveToolChanges(messages TranscriptMessages) bool

HasNonAdditiveToolChanges reports whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay.

func HasToolRedefinitions deprecated added in v0.86.0

func HasToolRedefinitions(messages TranscriptMessages) bool

HasToolRedefinitions reports whether a tool name was declared twice with different definitions. A transport that can only reference previously declared tools by name cannot replay such a history.

Deprecated: no built-in transport needs this anymore — Anthropic expresses redefinitions with inline tool_definition blocks. Kept for API compatibility and will be removed in a future release.

func HeadersToRecord

func HeadersToRecord(headers http.Header) map[string]string

HeadersToRecord converts an http.Header to a string map (pi: headersToRecord).

func IsContextOverflow

func IsContextOverflow(message *types.AssistantMessage, contextWindow int64) bool

IsContextOverflow reports whether an assistant message represents a context-overflow error (pi: isContextOverflow). Three cases:

  1. Error-based overflow: most providers return stopReason "error" with a specific error message pattern.
  2. Silent overflow: some providers accept overflow requests and return successfully; check whether usage input exceeds the context window.
  3. Length-stop overflow: Xiaomi MiMo can return "length" with zero output when the input fills the context window.

contextWindow == 0 means pi's undefined (the silent-overflow checks are skipped).

func IsRecoverableLength

func IsRecoverableLength(message *types.AssistantMessage, desiredMaxOutput int64) bool

IsRecoverableLength reports whether a length stop ended below the caller or model's intended output limit (pi: isRecoverableLength). Such responses may be caused by context pressure or provider-side truncation, so callers can make one bounded compact-and-retry attempt. desiredMaxOutput must be the original limit before any context-based clamping.

func IsRetryableAssistantError

func IsRetryableAssistantError(message *types.AssistantMessage) bool

IsRetryableAssistantError classifies whether a failed assistant message looks like a transient provider or transport error, so callers can decide if the last assistant turn should be restarted (pi: isRetryableAssistantError).

This does not implement retry policy. Callers should first handle context overflow separately, then apply their own retry budget, backoff, and reporting before restarting the assistant turn.

func NormalizeContext added in v0.86.0

func NormalizeContext(context *aitypes.Context) *aitypes.TranscriptContext

NormalizeContext folds Context.SystemPrompt and Context.Tools into a leading system message. This is the only entry point that produces a TranscriptContext; every provider-facing function expects the result.

func ParseJSONWithRepair

func ParseJSONWithRepair(input string) (any, error)

ParseJSONWithRepair parses JSON, repairing string literals on first failure (pi: parseJsonWithRepair).

func ParsePartialJSON

func ParsePartialJSON(jsonString string) (any, error)

ParsePartialJSON is a port of the partial-json package's parseJSON with Allow.ALL (pi: partial-json's parse, used by parseStreamingJson). It parses incomplete JSON, returning what it can and swallowing PartialJSON errors. Malformed input yields a malformedJSONError.

func ParseStreamingJSON

func ParseStreamingJSON(partialJSON *string) map[string]any

ParseStreamingJSON attempts to parse potentially incomplete JSON during streaming; it always returns a valid object, even when the JSON is incomplete (pi: parseStreamingJson, whose generic T is instantiated with Record<string, unknown> by every caller). An empty or blank input yields an empty map; an unparseable input also yields an empty map.

func ProviderHeadersToRecord

func ProviderHeadersToRecord(headers types.ProviderHeaders) map[string]string

ProviderHeadersToRecord converts ProviderHeaders to a string map, dropping nil entries (pi: providerHeadersToRecord). Returns nil when no non-nil entry remains.

func RenderSystemMessageUpdate added in v0.86.0

func RenderSystemMessageUpdate(message *types.SystemMessage) string

RenderSystemMessageUpdate renders a later system message for APIs that accept system messages mid-conversation. Section changes are framed by name so the model can relate them to the leading prompt. This framing is request-time only and may change between versions (pi: renderSystemMessageUpdate).

func RepairJSON

func RepairJSON(json string) string

repairJson repairs malformed JSON string literals by escaping raw control characters inside strings and doubling backslashes before invalid escape characters (pi: repairJson).

func ResolveHTTPProxyURLForTarget

func ResolveHTTPProxyURLForTarget(targetURL string, env types.ProviderEnv) (*url.URL, error)

ResolveHTTPProxyURLForTarget resolves the proxy URL for a target request URL from proxy env vars, or nil when the target should go direct (pi: resolveHttpProxyUrlForTarget). SOCKS/PAC proxies are rejected explicitly.

func ResolveTranscript added in v0.86.0

func ResolveTranscript(context *aitypes.TranscriptContext, supportsMidConvoSystemMessages bool) *aitypes.TranscriptContext

ResolveTranscript keeps later system messages in place when the model accepts them; otherwise collapses them.

func RetryAssistantCall

func RetryAssistantCall(ctx context.Context, produce func() (*types.AssistantMessage, error), policy *RetryPolicy, callbacks *RetryCallbacks) (*types.AssistantMessage, error)

RetryAssistantCall runs a single assistant-producing call with bounded retry on transient errors (pi: retryAssistantCall).

Behavior:

  • A successful response is returned immediately. Aborts are terminal and never retried, but reported as unsuccessful if they happen after a retry was scheduled. Aborts during the backoff sleep are normalized to an aborted AssistantMessage too, so callers do not need to care when cancellation happened.
  • A non-retryable error (per IsRetryableAssistantError, including quota/ billing exhaustion) is returned immediately so deterministic errors fail fast.
  • Otherwise retries up to maxRetries times with exponential backoff, emitting onRetryScheduled before each sleep, onRetryAttemptStart after each sleep before the retried call starts, and onRetryFinished once at the end (whether the loop ends in success, exhausted retries, or an aborted backoff).

When policy is nil or disabled, the first response is returned unchanged (equivalent to calling produce directly). ctx carries the caller's cancellation (pi: options.signal).

func RetryDelayMs added in v0.86.0

func RetryDelayMs(policy *RetryPolicy, attempt int) int64

RetryDelayMs computes the per-attempt delay with the agent-level cap (pi: retryDelayMs).

func RetryProviderRequest

func RetryProviderRequest[T any](request func() (T, error), options ProviderRetryOptions) (T, error)

RetryProviderRequest wraps one request in the SDK-style retry loop (pi: retryProviderRequest). Each retry is a fresh request. Non-provider errors are never retried; provider errors are retried when their status/headers mark them retryable.

func SafeJSONStringify

func SafeJSONStringify(value any) string

SafeJSONStringify serializes a value, falling back to fmt-style rendering when marshaling fails (pi: safeJsonStringify, whose catch path uses String(value)).

func SanitizeSurrogates

func SanitizeSurrogates(text string) string

SanitizeSurrogates removes unpaired UTF-16 surrogate code points from a string (pi: sanitizeSurrogates). Unpaired surrogates (U+D800-U+DBFF without a following low surrogate, or U+DC00-U+DFFF without a preceding high surrogate) cause JSON serialization errors in many API providers.

Go strings are UTF-8, where a non-BMP character is one 4-byte sequence (never a surrogate pair), so well-formed input contains no surrogates at all. The only surrogates that can appear are the raw 3-byte UTF-8 encodings of unpaired surrogates from malformed producers (e.g. hand-built tool results); those are stripped here, exactly the characters pi's regex removes. Valid emoji and other non-BMP characters are unaffected.

func ShortHash

func ShortHash(str string) string

ShortHash is the fast deterministic hash used to shorten long strings (pi: shortHash, a 64-bit splitmix-style two-lane hash rendered in base-36).

func ToToolDeclaration added in v0.86.0

func ToToolDeclaration(t tool) tool

ToToolDeclaration strips executable and display-only fields from a tool before transcript comparison or persistence.

func TruncateErrorText

func TruncateErrorText(text string, maxChars int) string

TruncateErrorText caps text at maxChars, appending a truncation note (pi: truncateErrorText).

func UUIDv7

func UUIDv7() string

UUIDv7 generates a time-ordered UUIDv7 (pi: uuidv7).

func UUIDv7WithTime

func UUIDv7WithTime(timestampMs int64) string

UUIDv7WithTime generates a time-ordered UUIDv7 stamped with the supplied Unix-millisecond timestamp (pi: uuidv7(timestampMs)). Timestamps equal to or older than the module high-water mark fall back to the monotonic counter, matching pi's sequence semantics.

func ValidateToolArguments

func ValidateToolArguments(tool *types.Tool, toolCall *types.ToolCall) (any, error)

ValidateToolArguments validates tool call arguments against the tool's schema (pi: validateToolArguments), coercing near-miss values along the way. Returns the validated (and potentially coerced) arguments, or an error with the formatted message callers embed into error tool results.

func ValidateToolCall

func ValidateToolCall(tools []types.Tool, toolCall *types.ToolCall) (any, error)

ValidateToolCall finds a tool by name and validates the tool call arguments against its schema (pi: validateToolCall). Returns the validated arguments. Returns an error if the tool is not found or validation fails.

func WithoutInitialSystemMessage added in v0.86.0

func WithoutInitialSystemMessage(messages []aitypes.Message) []aitypes.Message

WithoutInitialSystemMessage drops the leading system message for APIs that carry the prompt outside the message list.

Types

type AbortError

type AbortError struct{}

AbortError marks a cancelled request (pi: createAbortError — an Error named AbortError).

func (*AbortError) Error

func (e *AbortError) Error() string

type ContextUsageEstimate

type ContextUsageEstimate struct {
	// Tokens is the estimated total context tokens.
	Tokens int64
	// UsageTokens is tokens reported by the most recent applicable assistant
	// usage block.
	UsageTokens int64
	// TrailingTokens is the estimated tokens after the most recent applicable
	// assistant usage block.
	TrailingTokens int64
	// LastUsageIndex is the index of the applicable message that provided
	// usage, or -1 when none exists (pi: number | null).
	LastUsageIndex int64
}

ContextUsageEstimate is the token estimate of one context (pi: ContextUsageEstimate).

func EstimateContextTokens

func EstimateContextTokens(context *types.TranscriptContext) ContextUsageEstimate

EstimateContextTokens estimates the tokens of a normalized transcript (pi: estimateContextTokens; the TS function also accepts a bare message list, split here into EstimateContextTokensOfMessages since Go cannot overload).

func EstimateContextTokensOfMessages added in v0.86.0

func EstimateContextTokensOfMessages(messages []types.Message) ContextUsageEstimate

EstimateContextTokensOfMessages estimates the tokens of a bare message list (pi: estimateContextTokens union arm).

type DiagnosticErrorCoder

type DiagnosticErrorCoder interface {
	ErrorCode() any
}

DiagnosticErrorCoder is the optional error surface carrying a JS-style error code (pi: (error as {code?}).code).

type DiagnosticErrorNamer

type DiagnosticErrorNamer interface {
	ErrorName() string
}

DiagnosticErrorNamer is the optional error surface carrying a JS-style error name (pi: error.name). Go errors have no name member; adapters that want one in diagnostics implement this.

type DiagnosticErrorStacker

type DiagnosticErrorStacker interface {
	ErrorStack() string
}

DiagnosticErrorStacker is the optional error surface carrying a stack trace (pi: error.stack, captured when the error was thrown). Go errors do not capture stacks; only errors implementing this contribute one.

type NormalizedProviderError

type NormalizedProviderError struct {
	// Status is the HTTP status code, when one could be extracted.
	Status int
	// Body is the raw HTTP body reason, already trimmed and truncated to the
	// cap.
	Body string
	// Message is the error message.
	Message string
	// MessageCarriesBody is true when Message already contains the body (no
	// separate body to add).
	MessageCarriesBody bool
}

NormalizedProviderError is the flattened display surface of one provider failure (pi: NormalizedProviderError).

func NormalizeProviderError

func NormalizeProviderError(err error) NormalizedProviderError

NormalizeProviderError probes a thrown error for an HTTP status and raw body (pi: normalizeProviderError). *ProviderHTTPError carries them directly; any other error yields just its message.

type ProviderHTTPError

type ProviderHTTPError struct {
	Status  int
	Headers http.Header
	// Body is the raw HTTP response body, already read and size-capped by the
	// caller. Empty when the body was not captured.
	Body string
	// Message is the error message; when Body is empty the adapter usually
	// sets it to the reason line.
	Message string
}

ProviderHTTPError is the Go counterpart of an SDK error with a known HTTP status and headers (pi: the SdkErrorShape probe targets). Adapters return it for non-2xx responses; the retry helper and error normalizer both read it.

func (*ProviderHTTPError) Error

func (e *ProviderHTTPError) Error() string

type ProviderRetryOptions

type ProviderRetryOptions struct {
	// MaxRetries caps client-side retries; the caller decides its default
	// (openai-completions passes options.MaxRetries through, nil defaulting
	// to 0 / no retries in pi).
	MaxRetries int
	// MaxRetryDelayMs caps how long a server-requested retry wait may be; nil
	// means the 60s default, 0 disables the cap (pi: ?? default semantics).
	MaxRetryDelayMs *int64
	// Ctx replaces pi's AbortSignal: cancellation interrupts backoff sleeps.
	Ctx context.Context
}

ProviderRetryOptions are RetryProviderRequest's knobs (pi: ProviderRetryOptions; signal → Ctx).

type RetryCallbacks

type RetryCallbacks struct {
	// OnRetryScheduled is emitted before the backoff sleep of each retry
	// attempt (1-indexed).
	OnRetryScheduled func(attempt int, maxAttempts int, delayMs int64, errorMessage string)
	// OnRetryAttemptStart is emitted after the backoff sleep, immediately
	// before the retried call starts.
	OnRetryAttemptStart func()
	// OnRetryFinished is emitted once when the loop ends: success if a later
	// call completed normally.
	OnRetryFinished func(success bool, attempt int, finalError string)
}

RetryCallbacks are optional callbacks emitted by RetryAssistantCall around each retry (pi: interface RetryCallbacks).

type RetryPolicy

type RetryPolicy struct {
	Enabled bool
	// MaxRetries is the max retry attempts (0 = no retries). The initial call
	// never counts as a retry.
	MaxRetries int
	// BaseDelayMs is the base delay in ms. Per-attempt delay is
	// `baseDelayMs * 2^(attempt-1)` before jitter.
	BaseDelayMs int64
	// MaxAgentDelayMs is an optional cap for agent-level retry delays in ms.
	// Defaults to 60 seconds (pi: maxAgentDelayMs).
	MaxAgentDelayMs *int64
}

RetryPolicy is a retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`). MaxAgentDelayMs caps each computed delay and defaults to 60 seconds. Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept here so the classifier and the policy-driven retry loop live together and stay reusable by the SDK and other callers (pi: interface RetryPolicy).

type ToolStateChanges added in v0.86.0

type ToolStateChanges struct {
	ToolsAdded   []tool
	ToolsRemoved []aitypes.ToolReference
}

ToolStateChanges is the delta between two complete tool states.

func GetToolStateChanges added in v0.86.0

func GetToolStateChanges(previous []tool, current []tool) ToolStateChanges

GetToolStateChanges compares two complete tool states. A changed definition is a removal followed by an addition.

type TranscriptMessages added in v0.86.0

type TranscriptMessages = []aitypes.Message

TranscriptMessages is any message list. The replay helpers only read entries whose role is "system", so agent transcripts that carry custom message roles can be passed without filtering.

type TranscriptTools added in v0.86.0

type TranscriptTools struct {
	// RequestTools are the tools sent in the top-level request field.
	RequestTools []tool
	// AnchorsAdditions reports whether later system messages carry their own
	// ToolsAdded as in-place additions. When false, RequestTools already
	// holds the complete current tool set.
	AnchorsAdditions bool
}

TranscriptTools splits tool declarations between the top-level request field and in-place additions.

func ResolveTranscriptTools added in v0.86.0

func ResolveTranscriptTools(messages TranscriptMessages, supportsToolAdditions bool) TranscriptTools

ResolveTranscriptTools splits tool declarations between the top-level request field and in-place additions. Transports that can anchor additions at a system message keep the initial tools at the top and load later ones where they appear; that only works when no tool was removed or redeclared, so everything else sends the current tool list.

Jump to

Keyboard shortcuts

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