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/identity.ts — how pi-ai identifies the calling app to providers. The ClientIdentity definitions live in ai/types so ProviderRequestOptions can reference them; this file carries the formatting/header helpers.
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/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.
pi: utils/version.ts.
Index ¶
- Constants
- Variables
- func AppendAssistantMessageDiagnostic(message *types.AssistantMessage, diagnostic types.AssistantMessageDiagnostic)
- func CalculateContextTokens(usage *types.Usage) int64
- func CollapseSystemMessages(context *aitypes.TranscriptContext) *aitypes.TranscriptContext
- func ContentText(content []types.Content, separator string) string
- func CreateAssistantMessageDiagnostic(diagType string, err any, details map[string]any) types.AssistantMessageDiagnostic
- func CreateInitialSystemMessage(systemPrompt string, tools []tool) *systemMessage
- func DeclarationsEqual(left, right tool) bool
- func EstimateMessageTokens(message types.Message) int64
- func EstimateTextAndImageContentTokens(content *types.UserContent) int64
- func EstimateTextTokens(text string) int64
- func ExtractDiagnosticError(err error) types.DiagnosticErrorInfo
- func FormatProviderError(norm NormalizedProviderError, prefix string) string
- func FormatThrownValue(value any) string
- func FormatUserAgent(identity *types.ClientIdentity) string
- func GetAttributionHeaders(target types.ClientIdentityTarget, identity *types.ClientIdentity) types.ProviderHeaders
- func GetClientVersion(identity *types.ClientIdentity) string
- func GetCurrentSystemMessage(messages TranscriptMessages) *systemMessage
- func GetCurrentSystemPrompt(messages TranscriptMessages) string
- func GetCurrentTools(messages TranscriptMessages) []tool
- func GetDeclaredTools(messages TranscriptMessages) []tool
- func GetIdentityHeaders(target types.ClientIdentityTarget, identity *types.ClientIdentity) types.ProviderHeaders
- func GetInitialSystemMessage(messages TranscriptMessages) *systemMessage
- func GetOpenCodeSessionHeaders(target types.ClientIdentityTarget, sessionID string) types.ProviderHeaders
- func GetProviderEnvValue(name string, env types.ProviderEnv) string
- func GetSystemMessageText(message *types.SystemMessage) string
- func HasNonAdditiveToolChanges(messages TranscriptMessages) bool
- func HasToolRedefinitions(messages TranscriptMessages) booldeprecated
- func HeadersToRecord(headers http.Header) map[string]string
- func IsContextOverflow(message *types.AssistantMessage, contextWindow int64) bool
- func IsRecoverableLength(message *types.AssistantMessage, desiredMaxOutput int64) bool
- func IsRetryableAssistantError(message *types.AssistantMessage) bool
- func MergeClientIdentity(sources ...*types.ClientIdentity) *types.ClientIdentity
- func NormalizeContext(context *aitypes.Context) *aitypes.TranscriptContext
- func ParseJSONWithRepair(input string) (any, error)
- func ParsePartialJSON(jsonString string) (any, error)
- func ParseStreamingJSON(partialJSON *string) map[string]any
- func ParseToolCallArguments(jsonStr string) (map[string]any, string)
- func ProviderHeadersToRecord(headers types.ProviderHeaders) map[string]string
- func RenderSystemMessageUpdate(message *types.SystemMessage) string
- func RepairJSON(json string) string
- func ResolveHTTPProxyURLForTarget(targetURL string, env types.ProviderEnv) (*url.URL, error)
- func ResolveTranscript(context *aitypes.TranscriptContext, supportsMidConvoSystemMessages bool) *aitypes.TranscriptContext
- func RetryAssistantCall(ctx context.Context, produce func() (*types.AssistantMessage, error), ...) (*types.AssistantMessage, error)
- func RetryDelayMs(policy *RetryPolicy, attempt int) int64
- func RetryProviderRequest[T any](request func() (T, error), options ProviderRetryOptions) (T, error)
- func SafeJSONStringify(value any) string
- func SanitizeSurrogates(text string) string
- func ShortHash(str string) string
- func ToToolDeclaration(t tool) tool
- func TruncateErrorText(text string, maxChars int) string
- func UUIDv7() string
- func UUIDv7WithTime(timestampMs int64) string
- func ValidateToolArguments(tool *types.Tool, toolCall *types.ToolCall) (any, error)
- func ValidateToolCall(tools []types.Tool, toolCall *types.ToolCall) (any, error)
- func WithoutInitialSystemMessage(messages []aitypes.Message) []aitypes.Message
- type AbortError
- type ContextUsageEstimate
- type DiagnosticErrorCoder
- type DiagnosticErrorNamer
- type DiagnosticErrorStacker
- type NormalizedProviderError
- type ProviderHTTPError
- type ProviderRetryOptions
- type RetryCallbacks
- type RetryPolicy
- type ToolStateChanges
- type TranscriptMessages
- type TranscriptToolSupport
- type TranscriptTools
Constants ¶
const MaxProviderErrorBodyChars = 4000
MaxProviderErrorBodyChars caps the raw HTTP body kept in NormalizedProviderError.
const PiAIVersion = "1.4.0"
PiAIVersion is the pi-ai package version (pi: PI_AI_VERSION). Keep it in sync with the pi release pig tracks; the coding agent's Version constant is the source of truth for the CLI.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 FormatUserAgent ¶ added in v1.4.0
func FormatUserAgent(identity *types.ClientIdentity) string
FormatUserAgent is the User-Agent value of an identity (pi: formatUserAgent). pi renders the Node/Bun runtime description; pig renders the Go runtime as `go/<version>` in the same slot.
func GetAttributionHeaders ¶ added in v1.4.0
func GetAttributionHeaders(target types.ClientIdentityTarget, identity *types.ClientIdentity) types.ProviderHeaders
GetAttributionHeaders returns provider attribution headers of an identity for a request target; nil when attribution is off (pi: getAttributionHeaders).
func GetClientVersion ¶ added in v1.4.0
func GetClientVersion(identity *types.ClientIdentity) string
GetClientVersion is the version in the detailed User-Agent (pi: getClientVersion).
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 GetIdentityHeaders ¶ added in v1.4.0
func GetIdentityHeaders(target types.ClientIdentityTarget, identity *types.ClientIdentity) types.ProviderHeaders
GetIdentityHeaders returns the default headers an identity adds to a request: User-Agent and provider attribution (pi: getIdentityHeaders). APIs apply them below model, provider, and request headers, so configured headers override them and nil request headers remove them.
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 GetOpenCodeSessionHeaders ¶ added in v1.4.0
func GetOpenCodeSessionHeaders(target types.ClientIdentityTarget, sessionID string) types.ProviderHeaders
GetOpenCodeSessionHeaders is OpenCode's per-conversation routing header for requests to OpenCode, including custom providers pointing at it; nil without a session or for other targets (pi: getOpenCodeSessionHeaders).
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 ¶
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:
- Error-based overflow: most providers return stopReason "error" with a specific error message pattern.
- Silent overflow: some providers accept overflow requests and return successfully; check whether usage input exceeds the context window.
- 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 MergeClientIdentity ¶ added in v1.4.0
func MergeClientIdentity(sources ...*types.ClientIdentity) *types.ClientIdentity
MergeClientIdentity merges identities field by field; later sources win and unset fields are skipped (pi: mergeClientIdentity).
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 ¶
ParseJSONWithRepair parses JSON, repairing string literals on first failure (pi: parseJsonWithRepair).
func ParsePartialJSON ¶
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 ¶
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 ParseToolCallArguments ¶ added in v1.3.0
ParseToolCallArguments parses the model's complete arguments text of a finished tool call (pi: parseToolCallArguments). Unlike ParseStreamingJSON it never keeps a partially parsed prefix: once the call is finished, text that is not a valid JSON object means the model sent malformed arguments. In that case arguments is an empty map and argumentsError describes the problem, including the text the model sent, so tool validation can report it back to the model.
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 ¶
repairJson repairs malformed JSON string literals by escaping raw control characters inside strings and doubling backslashes before invalid escape characters (pi: repairJson).
func ResolveHTTPProxyURLForTarget ¶
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 ¶
SafeJSONStringify serializes a value, falling back to fmt-style rendering when marshaling fails (pi: safeJsonStringify, whose catch path uses String(value)).
func SanitizeSurrogates ¶
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 ¶
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 ¶
TruncateErrorText caps text at maxChars, appending a truncation note (pi: truncateErrorText).
func UUIDv7WithTime ¶
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 ¶
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 ¶
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.
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
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 TranscriptToolSupport ¶ added in v1.4.0
type TranscriptToolSupport string
TranscriptToolSupport describes how a transport can express tool changes after the first request.
const ( // TranscriptToolSupportNone means only the top-level tool list exists; it // always holds the current tools. TranscriptToolSupportNone TranscriptToolSupport = "none" // TranscriptToolSupportAdditions means tools can be added at a later // message, but not removed or redefined. TranscriptToolSupportAdditions TranscriptToolSupport = "additions" // TranscriptToolSupportChanges means every tool, including the initial // ones, is declared in place, and a later declaration under the same name // replaces the earlier one. Removals are not expressible on the wire, so // the transport announces them as text and the removed tools stay // declared. TranscriptToolSupportChanges TranscriptToolSupport = "changes" )
type TranscriptTools ¶ added in v0.86.0
type TranscriptTools struct {
// RequestTools are the tools sent in the top-level request field.
RequestTools []tool
// FoldedSystemMessages is the number of leading system messages whose
// tool changes RequestTools already holds. Every later system message
// carries its own tool changes in place.
FoldedSystemMessages int
}
TranscriptTools splits tool declarations between the top-level request field and in-place changes.
func ResolveTranscriptTools ¶ added in v0.86.0
func ResolveTranscriptTools(messages TranscriptMessages, support TranscriptToolSupport) TranscriptTools
ResolveTranscriptTools splits tool declarations between the top-level request field and in-place changes.
With "changes", the top-level list stays empty and every system message, including the leading one, declares its tools in place: an in-place declaration can replace an earlier in-place one, but not a top-level one. With "additions", a removal or redefinition cannot be expressed in place, so the top-level list becomes the tool state after the last such change; later additions stay anchored, and the cached prefix is invalidated once per removal instead of on every later addition. With "none", the top-level list is the current tool set.