Documentation
¶
Overview ¶
pi: harness/context.ts — telemetry-context propagation helpers.
pi's Context/ContextKey come from @earendil-works/chord (a type-only dependency, per the SYNC-0 exclusion decision); pig maps the chord Context onto Go's context.Context: values travel via context.WithValue with package-private key types, BACKGROUND_CONTEXT/TODO_CONTEXT collapse to context.Background()/context.TODO(), and awaitWithContext/withCancel/ withAbortSignal collapse into plain ctx propagation (single-threaded event loop → goroutine convention). Only the telemetry-parent members have a real consumer in pig today.
Package harness corresponds to pi's packages/agent/src/harness.
pi: src/harness/events.ts — harness run lifecycle events and event bus.
Segment deviations:
- TS discriminated union HarnessEvent → HarnessEvent interface + *RunStartEvent/*RunEndEvent concrete types (pointer receivers keep the EventType probe callable on the nil typed-nil used by OnTyped).
- pi's generic on<TType> / watch<TSnapshot> → non-generic Events.On plus package-level generic helpers OnTyped[TEvent] / Watch[TSnapshot]: Go interfaces cannot declare generic methods, and methods cannot add type parameters. The generic helpers preserve pi's call-site shape.
- pi's Promise<void> listeners → synchronous callbacks (per the callback rule); emit stays synchronous and never awaits.
- pi relies on the single-threaded event loop for bus state; pig guards listener/watch state with a mutex. Listeners are snapshotted under the lock and invoked outside it, so listeners added or removed during delivery are not observed by the in-flight emit (matching Set iteration semantics) and reentrant Emit from a listener preserves the nested-delivery order of TS's synchronous loop.
- pi's WatchHandle<TSnapshot> object literal → exported Snapshot field + Start/Unsubscribe methods.
pig-specific: tool-result image elision at the LLM context boundary.
pi sends every tool-result image back on every request for the whole session, which pig kept 1:1. With phone-photo-sized JPEGs that means each read adds ~4-5MB of base64 to history and every subsequent request body grows unboundedly — providers reject the whole conversation with 413 once the accumulated images exceed the gateway body limit, and in-memory request serialization churns hundreds of MB per turn (see docs/fix/2026-09-22-image-tool-413-oversize-and-history-bloat.md).
Policy: an image block in a tool result is elided from the LLM context as soon as the model has produced an assistant response after it. In other words each image survives exactly the request(s) the model has not yet responded to; afterwards the model can re-read the file (it is on disk) if it needs to view it again. Session entries keep the full data — the transcript, /export, and branch summaries are unaffected; only provider request payloads shrink. User-message images (e.g. clipboard pastes, not re-readable from disk) are never elided; the blockImages setting remains the nuclear option for those.
pi: src/harness/messages.ts — harness-level custom agent messages (bashExecution / custom / branchSummary / compactionSummary) and the AgentMessage → LLM message conversion.
Deviations:
- pi declares these types via CustomAgentMessages declaration merging (interface augmentation of AgentMessage). pig's AgentMessage is the open types.Message interface: any type implementing MessageRole() rides the same channel, so the four message structs here implement it directly — no extension-point counterpart is needed (see agent/types.go header note).
- create*Message take int64 millisecond timestamps only; pi also accepts ISO date strings (callers convert before calling).
- CustomMessage.Content holds a string or a []types.Content (pi: `string | (TextContent | ImageContent)[]`); values decoded from generic JSON arrive as map/slice values and are not re-typed here (the typed path is createCustomMessage).
- convertToLlm filters via a type switch and nil skips (pi: map + filter over `Message | undefined`).
pi: src/harness/prompt-templates.ts — prompt template loading and argument formatting.
Segment deviations:
- Result<T, E> collapses to (T, error) / extra return values; the load functions report failures via diagnostics and never fail the call.
- pi duplicates parseFrontmatter and resolveKind verbatim in prompt-templates.ts and skills.ts; in a single Go package the symbols would collide, so both live here once and skills.go uses them.
- The npm `yaml` parse result's "properties of anything" access collapses to a map[string]any: a non-mapping frontmatter (scalar/list top level) contributes no keys, matching TS property access on a non-object.
- entries.sort((a, b) => a.name.localeCompare(b.name)) → byte-order strings.Compare; all pi call sites sort ASCII filenames where both orders agree.
- pi's async/await over the (synchronous) FileSystem interface collapses to direct calls; the AbortSignal → context rule maps the env calls' optional signals to a background context (the TS source passes none).
pi: src/harness/result.ts — Result<T, E> and the TaggedError factory.
Segment deviations:
- Result<TValue, TError> (the Result object with ok/err/isOk/isErr) collapses to Go's (T, error) at every consumer; there is no runtime counterpart (see types.go header note). pi's getOrThrow becomes plain error propagation.
- matchError / ErrorMatchers are TS type-map machinery: Go consumers dispatch with a type switch on the concrete tagged error structs. No helper is ported.
- pi's TaggedError(tag) factory generates error classes at runtime; Go declares one struct per tag, each embedding TaggedErrorBase (see agent_harness.go for the instances). The embedded base reproduces the toJSON shape exactly: {"_tag", "message", ...payload}.
pi: src/harness/skills.ts — skill loading from SKILL.md trees.
Segment deviations:
- Result<T, E> collapses to (T, error) / extra return values; failures surface as diagnostics and never fail the load call.
- pi's `ignore` npm package → github.com/sabhiram/go-gitignore. Only add(patterns) + ignores(path) are consumed; the matcher is recompiled from the accumulated pattern list on each add. gitignore semantics are approximated for the directory-suffix forms pi feeds it (pi appends "/" to directory paths itself); no pi test pins the divergent edges.
- parseFrontmatter/resolveKind are shared with prompt_templates.go (pi duplicates them verbatim; see that file's header note).
- pi's recursive async walk collapses to direct recursion; env calls use a background context (the TS source passes no abort signals).
- localeCompare sorting applies only to directory entries and root files here; byte-order strings.Compare is used (ASCII names).
pi: src/harness/system-prompt.ts — model-visible skills system-prompt block.
pi: src/harness/telemetry.ts — agent-owned telemetry schemas and typed span starters.
Segment deviations:
- pi's schema objects are `as const satisfies TelemetrySchemaDefinition` literals whose span/attribute keys rely on object insertion order. Go maps are unordered, so spans are stored as an ordered entry slice (TelemetrySchemaDefinition.Spans) preserving pi's declaration order; attributes stay plain maps (their order is not consumed anywhere).
- The TS type-inference scaffolding (AiSpanStartAttributes, SchemaTelemetrySpan, ExactTelemetryAttributes, the generic starters' const-attribute inference, and the pi-telemetry re-export type aliases) is compile-time typing with no runtime counterpart and is not ported (same decision as the telemetry package). startAiSpan/startHarnessSpan keep pi's shape minus the generics; the callback is synchronous and reports an error (pi: Result | Promise<Result> propagation through startSpan's callback, see telemetry.TelemetryContext).
- pi re-exports the pi-telemetry type surface from this module; pig's consumers import package telemetry directly, so no re-export aliases are needed.
pi: src/harness/types.ts — harness capability types.
Not yet ported (arrive with their consumers, placeholders left at their source positions below): Result/ok/err/getOrThrow/getOrUndefined/toError (TS Result<T, E> collapses to Go (T, error) at each consumer; no runtime counterpart is needed so far — the TaggedError half now lives in result.go).
Segment deviations (FileSystem):
- pi's FileSystem methods return Promise<Result<T, FileError>>; Go methods return (T, error) with *FileError as the concrete error type (same collapse as the session layer's Result handling).
- pi's optional abortSignal parameters (bare or inside options objects) map to a leading context.Context on every method, per the AbortSignal → context rule. Callers without a signal pass a non-nil background context; the session layer (whose TS source never forwards an abort signal) does exactly that.
- cleanup() keeps its best-effort no-throw contract as a nil error.
- pi's `content: string | Uint8Array` on writeFile/appendFile collapses to []byte (callers convert strings).
Index ¶
- Constants
- Variables
- func BashExecutionToText(msg BashExecutionMessage) string
- func ConvertToLlm(messages []agent.AgentMessage) []types.Message
- func ElideRespondedToolResultImages(messages []types.Message) []types.Message
- func FormatPromptTemplateInvocation(template PromptTemplate, args []string) string
- func FormatSkillInvocation(skill Skill, additionalInstructions string) string
- func FormatSkillsForSystemPrompt(skills []Skill) string
- func GetTelemetryContext(ctx context.Context) telemetry.TelemetryContext
- func LoadPromptTemplates(env ExecutionEnv, paths []string) ([]PromptTemplate, []PromptTemplateDiagnostic)
- func LoadSkills(env ExecutionEnv, dirs []string) ([]Skill, []SkillDiagnostic)
- func LoadSourcedPromptTemplates[TSource any](env ExecutionEnv, inputs []SourcedInput[TSource], ...) ([]SourcedPromptTemplate[TSource], []SourcedPromptTemplateDiagnostic[TSource])
- func LoadSourcedSkills[TSource any](env ExecutionEnv, inputs []SourcedInput[TSource], ...) ([]SourcedSkill[TSource], []SourcedSkillDiagnostic[TSource])
- func OnTyped[TEvent HarnessEvent](e Events, listener func(TEvent)) func()
- func ParseCommandArgs(argsString string) []string
- func StartAiSpan(telemetryContext telemetry.TelemetryContext, name string, ...) error
- func StartHarnessSpan(telemetryContext telemetry.TelemetryContext, name string, ...) error
- func WithTelemetryContext(ctx context.Context, telemetryContext telemetry.TelemetryContext) context.Context
- type AgentHarnessResources
- type AgentHarnessStreamOptions
- type AgentHarnessStreamOptionsPatch
- type AgentHarnessTool
- type BashExecutionMessage
- type BranchSummaryError
- type BranchSummaryErrorCode
- type BranchSummaryMessage
- type CompactionError
- type CompactionErrorCode
- type CompactionSettings
- type CompactionSummaryMessage
- type CustomMessage
- type Events
- type ExecutionEnv
- type ExecutionError
- type ExecutionErrorCode
- type FileError
- type FileErrorCode
- type FileInfo
- type FileKind
- type FileSystem
- type HarnessEvent
- type HarnessEventBus
- type HarnessEventListener
- type HarnessEventType
- type PromptTemplate
- type PromptTemplateDiagnostic
- type PromptTemplateDiagnosticCode
- type RunEndEvent
- type RunOutcome
- type RunStartEvent
- type Shell
- type ShellExecOptions
- type ShellExecResult
- type Skill
- type SkillDiagnostic
- type SkillDiagnosticCode
- type SourcedInput
- type SourcedPromptTemplate
- type SourcedPromptTemplateDiagnostic
- type SourcedSkill
- type SourcedSkillDiagnostic
- type TaggedErrorBase
- type TaggedErrorValue
- type TelemetryAttributeDefinition
- type TelemetrySchemaDefinition
- type TelemetrySchemaSpan
- type TelemetrySchemaSpanEntry
- type TelemetrySpanParents
- type TelemetryStatusDefinition
- type WatchHandle
Constants ¶
const ( RoleBashExecution types.Role = "bashExecution" RoleCustomMessage types.Role = "custom" RoleBranchSummary types.Role = "branchSummary" RoleCompactionSummary types.Role = "compactionSummary" )
Role literals for the harness custom messages (pi: the `role` string members of the custom message union).
const AiSpanName = "pi.ai.request"
AiSpanName is the closed span-name vocabulary of AiTelemetrySchema (pi: AiSpanName). Names are declared as constants because Go has no string-literal types; consumers must pass one of these values.
const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:
<summary>
`
BRANCH_SUMMARY_PREFIX wraps a branch summary in the LLM context (pi: BRANCH_SUMMARY_PREFIX).
const BRANCH_SUMMARY_SUFFIX = `</summary>`
BRANCH_SUMMARY_SUFFIX closes the branch summary block (pi: BRANCH_SUMMARY_SUFFIX).
const COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary:
<summary>
`
COMPACTION_SUMMARY_PREFIX wraps a compaction summary in the LLM context (pi: COMPACTION_SUMMARY_PREFIX).
const COMPACTION_SUMMARY_SUFFIX = `
</summary>`
COMPACTION_SUMMARY_SUFFIX closes the compaction summary block (pi: COMPACTION_SUMMARY_SUFFIX).
Variables ¶
var AGENT_TELEMETRY_SCHEMAS = []*TelemetrySchemaDefinition{AI_TELEMETRY_SCHEMA, HARNESS_TELEMETRY_SCHEMA}
AGENT_TELEMETRY_SCHEMAS is the combined typed span vocabulary for agent-owned AI-request and harness telemetry (pi: AGENT_TELEMETRY_SCHEMAS).
var AI_TELEMETRY_SCHEMA = &TelemetrySchemaDefinition{ Version: 1, Spans: []TelemetrySchemaSpanEntry{ { Name: "pi.ai.request", Span: TelemetrySchemaSpan{ Description: "One logical request to an AI provider", Parents: TelemetrySpanParents{Kind: "any"}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.ai.operation": { Type: "string", Required: true, Values: []string{"stream", "fetch_deferred", "cancel_deferred", "generate_images"}, Description: "Logical provider operation", }, "pi.ai.provider": { Type: "string", Required: true, Description: "Selected provider id", }, "pi.ai.model": { Type: "string", Required: true, Description: "Requested model id", }, "pi.ai.api": { Type: "string", Required: true, Description: "Provider API id", }, "pi.ai.streaming": { Type: "boolean", Required: true, Description: "Whether this operation returns a stream", }, "pi.ai.deferred": { Type: "boolean", Required: false, Description: "Whether the operation requests or participates in deferred execution", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{ "pi.ai.response.model": {Type: "string", Description: "Concrete response model"}, "pi.ai.response.id": { Type: "string", Cardinality: "high", Description: "Provider response id", }, "pi.ai.response.stop_reason": { Type: "string", Values: []string{"stop", "length", "tool_use", "error", "aborted", "deferred"}, Description: "Normalized terminal response reason", }, "pi.ai.http.status_code": {Type: "number", Description: "Final HTTP status"}, "pi.ai.usage.input_tokens": {Type: "number", Description: "Reported input tokens"}, "pi.ai.usage.output_tokens": {Type: "number", Description: "Reported output tokens"}, "pi.ai.usage.cache_read_tokens": {Type: "number", Description: "Reported cache-read tokens"}, "pi.ai.usage.cache_write_tokens": {Type: "number", Description: "Reported cache-write tokens"}, "pi.ai.usage.reasoning_tokens": {Type: "number", Description: "Reported reasoning tokens"}, "pi.ai.usage.total_tokens": {Type: "number", Description: "Reported total tokens"}, "pi.ai.usage.cost": {Type: "number", Description: "Reported total cost"}, "pi.ai.stream.chunk_count": {Type: "number", Description: "Streamed update chunk count"}, "pi.ai.stream.time_to_first_chunk_ms": { Type: "number", Description: "Elapsed milliseconds to first update chunk", }, "pi.ai.error.type": { Type: "string", Cardinality: "low", Description: "Provider or transport error class", }, }, Status: TelemetryStatusDefinition{ Default: "ok", ErrorWhen: "The operation throws or returns an error result", }, }, }, }, }
AI_TELEMETRY_SCHEMA is the AI-request telemetry schema (pi: AI_TELEMETRY_SCHEMA).
var DefaultCompactionSettings = CompactionSettings{ Enabled: true, ReserveTokens: 16384, KeepRecentTokens: 20000, }
DefaultCompactionSettings are the default compaction settings used by the harness (pi: DEFAULT_COMPACTION_SETTINGS).
var EventTypes = []string{
"run_start",
"run_resume",
"run_suspend",
"run_abort",
"run_end",
"fault",
"handler_error",
"turn_start",
"turn_end",
"retry_scheduled",
"retry_start",
"retry_end",
"message_start",
"message_update",
"message_end",
"tool_start",
"tool_update",
"tool_end",
"entry_added",
"write_pending",
"queue_update",
"fact_update",
"config_update",
"compaction_start",
"compaction_end",
"navigation_start",
"navigation_end",
"lane_created",
"usage",
}
EventTypes enumerates the passive harness event types (pi: EVENT_TYPES; the event vocabulary itself lives in events.ts).
var HARNESS_TELEMETRY_SCHEMA = &TelemetrySchemaDefinition{ Version: 1, Spans: []TelemetrySchemaSpanEntry{ { Name: "pi.harness.run", Span: TelemetrySchemaSpan{ Description: "One admitted in-process run invocation", Parents: TelemetrySpanParents{Kind: "root_or_external"}, StartAttributes: mergeAttributes(operationStartAttributes, map[string]TelemetryAttributeDefinition{ "pi.operation.kind": { Type: "string", Required: true, Values: []string{"run"}, Description: "Run operation kind", }, }), EndAttributes: mergeAttributes(map[string]TelemetryAttributeDefinition{ "pi.operation.outcome": { Type: "string", Values: []string{"completed", "aborted", "failed", "suspended"}, Description: "Run invocation outcome", }, }, operationErrorAttributes), Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "The run fails or throws"}, }, }, { Name: "pi.harness.compaction", Span: TelemetrySchemaSpan{ Description: "One admitted in-process manual compaction invocation", Parents: TelemetrySpanParents{Kind: "root_or_external"}, StartAttributes: mergeAttributes(operationStartAttributes, map[string]TelemetryAttributeDefinition{ "pi.operation.kind": { Type: "string", Required: true, Values: []string{"compaction"}, Description: "Compaction operation kind", }, }), EndAttributes: mergeAttributes(map[string]TelemetryAttributeDefinition{ "pi.operation.outcome": { Type: "string", Values: []string{"completed", "declined", "aborted", "failed"}, Description: "Compaction invocation outcome", }, }, operationErrorAttributes), Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "The compaction fails or throws"}, }, }, { Name: "pi.harness.navigation", Span: TelemetrySchemaSpan{ Description: "One admitted in-process navigation invocation", Parents: TelemetrySpanParents{Kind: "root_or_external"}, StartAttributes: mergeAttributes(operationStartAttributes, map[string]TelemetryAttributeDefinition{ "pi.operation.kind": { Type: "string", Required: true, Values: []string{"navigation"}, Description: "Navigation operation kind", }, }), EndAttributes: mergeAttributes(map[string]TelemetryAttributeDefinition{ "pi.operation.outcome": { Type: "string", Values: []string{"completed", "declined", "aborted", "failed"}, Description: "Navigation invocation outcome", }, }, operationErrorAttributes), Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "The navigation fails or throws"}, }, }, { Name: "pi.harness.checkpoint", Span: TelemetrySchemaSpan{ Description: "One run checkpoint", Parents: TelemetrySpanParents{Kind: "spans", Spans: []string{"pi.harness.run"}}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.lane.name": { Type: "string", Required: true, Cardinality: "high", Description: "Lane name", }, "pi.operation.id": { Type: "string", Required: true, Cardinality: "high", Description: "Durable operation id", }, "pi.checkpoint.kind": { Type: "string", Required: true, Values: []string{"normal", "failure_drain", "abort_reconcile"}, Description: "Checkpoint purpose", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{}, Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "Checkpoint work throws"}, }, }, { Name: "pi.harness.turn", Span: TelemetrySchemaSpan{ Description: "One assistant response and its tool batch", Parents: TelemetrySpanParents{Kind: "spans", Spans: []string{"pi.harness.run"}}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.lane.name": { Type: "string", Required: true, Cardinality: "high", Description: "Lane name", }, "pi.operation.id": { Type: "string", Required: true, Cardinality: "high", Description: "Durable operation id", }, "pi.turn.id": { Type: "string", Required: true, Cardinality: "high", Description: "Invocation-local turn id", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{}, Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "Turn work throws"}, }, }, { Name: "pi.harness.step", Span: TelemetrySchemaSpan{ Description: "One durable retry attempt", Parents: TelemetrySpanParents{Kind: "spans", Spans: []string{ "pi.harness.turn", "pi.harness.checkpoint", "pi.harness.compaction", "pi.harness.navigation", }}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.lane.name": { Type: "string", Required: true, Cardinality: "high", Description: "Lane name", }, "pi.operation.id": { Type: "string", Required: true, Cardinality: "high", Description: "Durable operation id", }, "pi.step.kind": { Type: "string", Required: true, Values: []string{"assistant", "compaction", "branch_summary"}, Description: "Retryable step kind", }, "pi.step.attempt": { Type: "number", Required: true, Description: "One-based durable attempt number", }, "pi.compaction.reason": { Type: "string", Required: false, Values: []string{"manual", "threshold", "overflow"}, Description: "Compaction trigger", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{ "pi.step.outcome": { Type: "string", Values: []string{"succeeded", "retry", "failed", "aborted", "deferred", "overflow"}, Description: "Attempt outcome", }, }, Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "The attempt retries, fails, or throws"}, }, }, { Name: "pi.harness.tool", Span: TelemetrySchemaSpan{ Description: "One raw phase-2 tool execution", Parents: TelemetrySpanParents{Kind: "spans", Spans: []string{"pi.harness.turn", "pi.harness.run"}}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.lane.name": { Type: "string", Required: true, Cardinality: "high", Description: "Lane name", }, "pi.operation.id": { Type: "string", Required: true, Cardinality: "high", Description: "Durable operation id", }, "pi.turn.id": { Type: "string", Required: false, Cardinality: "high", Description: "Invocation-local live turn id", }, "pi.tool.name": { Type: "string", Required: true, Description: "Tool name", }, "pi.tool.call_id": { Type: "string", Required: true, Cardinality: "high", Description: "Tool call id", }, "pi.tool.replay": { Type: "string", Required: true, Values: []string{"never", "safe"}, Description: "Declared replay policy", }, "pi.tool.recovery": { Type: "boolean", Required: true, Description: "Whether this is recovery execution", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{ "pi.tool.is_error": { Type: "boolean", Description: "Whether raw phase-2 execution returned an error", }, }, Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "Raw phase-2 execution returns an error"}, }, }, { Name: "pi.harness.hook", Span: TelemetrySchemaSpan{ Description: "One registered hook handler invocation", Parents: TelemetrySpanParents{Kind: "any"}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.lane.name": { Type: "string", Required: true, Cardinality: "high", Description: "Lane name", }, "pi.operation.id": { Type: "string", Required: false, Cardinality: "high", Description: "Durable operation id when accepted", }, "pi.hook.name": { Type: "string", Required: true, Values: HookNames, Description: "Hook name", }, "pi.hook.registration_id": { Type: "string", Required: false, Description: "Stable hook registration id", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{ "pi.hook.outcome": { Type: "string", Values: []string{"completed", "skipped", "blocked", "failed"}, Description: "Handler outcome", }, }, Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "The handler throws"}, }, }, { Name: "pi.harness.sleep", Span: TelemetrySchemaSpan{ Description: "One retry delay", Parents: TelemetrySpanParents{Kind: "spans", Spans: []string{"pi.harness.step", "pi.harness.run"}}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.operation.id": { Type: "string", Required: true, Cardinality: "high", Description: "Durable operation id", }, "pi.sleep.delay_ms": { Type: "number", Required: true, Description: "Requested delay in milliseconds", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{ "pi.sleep.outcome": { Type: "string", Values: []string{"elapsed", "aborted"}, Description: "Delay outcome", }, }, Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "Sleep work throws"}, }, }, { Name: "pi.harness.event_handler", Span: TelemetrySchemaSpan{ Description: "One passive event listener invocation", Parents: TelemetrySpanParents{Kind: "any"}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.event.type": { Type: "string", Required: true, Cardinality: "low", Values: EventTypes, Description: "Delivered harness event type", }, "pi.lane.name": { Type: "string", Required: false, Cardinality: "high", Description: "Lane name for lane-scoped events", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{}, Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "The listener throws"}, }, }, { Name: "pi.session.write", Span: TelemetrySchemaSpan{ Description: "One committed session mutation", Parents: TelemetrySpanParents{Kind: "any"}, StartAttributes: map[string]TelemetryAttributeDefinition{ "pi.lane.name": { Type: "string", Required: true, Cardinality: "high", Description: "Lane name", }, "pi.operation.id": { Type: "string", Required: false, Cardinality: "high", Description: "Durable operation id when accepted", }, "pi.session.mutation": { Type: "string", Required: true, Values: []string{"entry", "record", "lane", "fact"}, Description: "Session mutation kind", }, "pi.session.item_type": { Type: "string", Required: false, Description: "Entry, record, lane, or fact subtype", }, }, EndAttributes: map[string]TelemetryAttributeDefinition{ "pi.session.seq": { Type: "number", Description: "Committed session sequence when exposed", }, }, Status: TelemetryStatusDefinition{Default: "ok", ErrorWhen: "Storage rejects the mutation"}, }, }, }, }
HARNESS_TELEMETRY_SCHEMA is the harness telemetry schema (pi: HARNESS_TELEMETRY_SCHEMA). Span order matches pi's object literal.
var HookNames = []string{
"before_run",
"before_resume",
"before_run_end",
"transform_context",
"before_request",
"before_payload",
"after_response",
"before_tool",
"after_tool",
"before_compaction",
"before_navigation",
}
HookName values reused by the harness telemetry schema (pi: HOOK_NAMES; the HookName union itself lives in agent_harness.go).
Functions ¶
func BashExecutionToText ¶
func BashExecutionToText(msg BashExecutionMessage) string
BashExecutionToText renders one bash execution for the LLM context (pi: bashExecutionToText).
func ConvertToLlm ¶
func ConvertToLlm(messages []agent.AgentMessage) []types.Message
ConvertToLlm converts AgentMessages to LLM-compatible messages before the agent loop streams (pi: convertToLlm). Custom roles project to user messages; unknown message types are dropped.
pig deviation (v0.86.1): tool-result images the model has already responded to are elided from the converted context (see image_elision.go); pi sends them on every request, which makes request bodies grow without bound over image-heavy sessions. Single choke point: all LLM callers (agent loop, compaction, branch summaries, bug reports) go through here.
func ElideRespondedToolResultImages ¶ added in v0.87.0
ElideRespondedToolResultImages replaces image blocks in tool-result messages that precede the last assistant message with the elision note. Messages are copied on write; the input slice is never mutated. Returns the original slice when nothing changed.
func FormatPromptTemplateInvocation ¶
func FormatPromptTemplateInvocation(template PromptTemplate, args []string) string
FormatPromptTemplateInvocation formats a prompt template invocation with positional arguments (pi: formatPromptTemplateInvocation; pi's default `args = []` becomes a nil-tolerant slice).
func FormatSkillInvocation ¶
FormatSkillInvocation formats a skill invocation prompt, optionally appending additional user instructions (pi: formatSkillInvocation).
func FormatSkillsForSystemPrompt ¶
FormatSkillsForSystemPrompt renders the model-visible skills block for the system prompt (pi: formatSkillsForSystemPrompt). Skills with DisableModelInvocation are excluded; an empty result means "no skills section".
func GetTelemetryContext ¶
func GetTelemetryContext(ctx context.Context) telemetry.TelemetryContext
GetTelemetryContext returns the telemetry parent attached to a context, or the shared no-op parent (pi: getTelemetryContext).
func LoadPromptTemplates ¶
func LoadPromptTemplates(env ExecutionEnv, paths []string) ([]PromptTemplate, []PromptTemplateDiagnostic)
LoadPromptTemplates loads prompt templates from one or more paths (pi: loadPromptTemplates).
Directory inputs load direct `.md` children non-recursively. File inputs load explicit `.md` files. Missing paths and non-markdown files are skipped. Read and parse failures are returned as diagnostics.
func LoadSkills ¶
func LoadSkills(env ExecutionEnv, dirs []string) ([]Skill, []SkillDiagnostic)
LoadSkills loads skills from one or more directories (pi: loadSkills).
Traverses directories recursively, loads `SKILL.md` files, loads direct root `.md` files with skill frontmatter, honors ignore files, and returns diagnostics for invalid declared skill files. Missing input directories are skipped.
func LoadSourcedPromptTemplates ¶
func LoadSourcedPromptTemplates[TSource any]( env ExecutionEnv, inputs []SourcedInput[TSource], mapPromptTemplate func(PromptTemplate, TSource) PromptTemplate, ) ([]SourcedPromptTemplate[TSource], []SourcedPromptTemplateDiagnostic[TSource])
LoadSourcedPromptTemplates loads prompt templates from source-tagged paths (pi: loadSourcedPromptTemplates<TSource, TPromptTemplate>).
Source values are preserved exactly and attached to every loaded prompt template and diagnostic. The agent package does not interpret source values; applications define their own provenance shape. pi's TPromptTemplate generic collapses to PromptTemplate: TS only widens the struct via a mapper that returns a compatible shape, which Go models by keeping the base struct and letting applications carry their own source-tagged view.
func LoadSourcedSkills ¶
func LoadSourcedSkills[TSource any]( env ExecutionEnv, inputs []SourcedInput[TSource], mapSkill func(Skill, TSource) Skill, ) ([]SourcedSkill[TSource], []SourcedSkillDiagnostic[TSource])
LoadSourcedSkills loads skills from source-tagged directories (pi: loadSourcedSkills<TSource, TSkill>).
Source values are preserved exactly and attached to every loaded skill and diagnostic. The agent package does not interpret source values; applications define their own provenance shape. pi's TSkill generic collapses to Skill (see LoadSourcedPromptTemplates).
func OnTyped ¶
func OnTyped[TEvent HarnessEvent](e Events, listener func(TEvent)) func()
OnTyped is pi's generic Events.on<TType> with the type parameter restored at the call site: Go interfaces cannot declare generic methods, so the type assertion moves into this package-level helper. TEvent must be a concrete event type (*RunStartEvent or *RunEndEvent).
func ParseCommandArgs ¶
ParseCommandArgs parses an argument string using simple shell-style single and double quotes (pi: parseCommandArgs).
func StartAiSpan ¶
func StartAiSpan(telemetryContext telemetry.TelemetryContext, name string, attributes telemetry.SpanAttributes, callback func(span telemetry.TelemetrySpan) error) error
StartAiSpan starts an AI-request span and runs callback inside it (pi: startAiSpan). pi's typed-span generics and ExactTelemetryAttributes checking are compile-time only; attributes pass through as-is.
func StartHarnessSpan ¶
func StartHarnessSpan(telemetryContext telemetry.TelemetryContext, name string, attributes telemetry.SpanAttributes, callback func(span telemetry.TelemetrySpan) error) error
StartHarnessSpan starts a harness span and runs callback inside it (pi: startHarnessSpan).
func WithTelemetryContext ¶
func WithTelemetryContext(ctx context.Context, telemetryContext telemetry.TelemetryContext) context.Context
WithTelemetryContext derives a context whose telemetry children use the supplied parent or active span (pi: withTelemetryContext).
Types ¶
type AgentHarnessResources ¶
type AgentHarnessResources struct {
// PromptTemplates available for explicit invocation.
PromptTemplates []PromptTemplate `json:"promptTemplates,omitempty"`
// Skills available to the model and explicit skill invocation.
Skills []Skill `json:"skills,omitempty"`
}
AgentHarnessResources are resources made available to explicit invocation methods and system-prompt callbacks (pi: AgentHarnessResources<...>).
pi's TSkill/TPromptTemplate generics default to Skill/PromptTemplate and have no other instantiation in the codebase; per the generic-collapse rule they are inlined as the concrete types.
type AgentHarnessStreamOptions ¶
type AgentHarnessStreamOptions struct {
// Transport is the preferred transport forwarded to the stream function.
// Pointer: TS optional; nil = pi's `undefined`.
Transport *types.Transport
// TimeoutMs is the provider request timeout in milliseconds. Pointer:
// TS optional number.
TimeoutMs *int64
// MaxRetries is the maximum provider retry attempts. Pointer: TS
// optional number.
MaxRetries *int
// MaxRetryDelayMs caps provider-requested retry delays in milliseconds.
// Pointer: TS optional number.
MaxRetryDelayMs *int64
// Headers are additional request headers merged with auth and lifecycle
// headers (pi: Record<string, string>).
Headers map[string]string
// Metadata is provider metadata forwarded with requests (pi:
// SimpleStreamOptions["metadata"]).
Metadata map[string]any
// CacheRetention is the provider cache retention hint. Zero value "" =
// pi's `undefined`, matching types.StreamOptions' convention.
CacheRetention types.CacheRetention
}
AgentHarnessStreamOptions are curated provider request options owned by the harness and snapshotted per turn (pi: AgentHarnessStreamOptions).
type AgentHarnessStreamOptionsPatch ¶
type AgentHarnessStreamOptionsPatch struct {
Transport *types.Transport
TimeoutMs *int64
MaxRetries *int
MaxRetryDelayMs *int64
CacheRetention *types.CacheRetention
}
AgentHarnessStreamOptionsPatch is a partial update of the harness stream options (pi: AgentHarnessStreamOptionsPatch = Omit<Partial<...>, "headers" | "metadata">). Nil fields keep the current values; pi's omitted headers/members are not patchable and therefore absent here.
type AgentHarnessTool ¶
type AgentHarnessTool struct {
Name string
Label string
Description string
Parameters json.RawMessage
PrepareArguments func(args any) any
ExecutionMode agent.ToolExecutionMode
Execute func(ctx context.Context, toolCallID string, params any, onUpdate agent.AgentToolUpdateCallback, context any) (agent.AgentToolResult, error)
}
AgentHarnessTool is a tool definition used with the harness (pi: AgentHarnessTool<TContext, TParameters, TDetails> = Omit<AgentTool, "execute"> & { execute }). The generics are dropped (same rule as agent.AgentTool, see the agent/types.go note): params arrive as a schema-validated map[string]any (pi: Static<TParameters>), details as any (pi: TDetails), and the turn context as any (pi: TContext). The Execute signature differs from agent.AgentTool by the trailing context parameter, resolved for the current turn snapshot.
type BashExecutionMessage ¶
type BashExecutionMessage struct {
Role types.Role `json:"role"` // "bashExecution"
Command string `json:"command"`
Output string `json:"output"`
ExitCode *int `json:"exitCode"`
Cancelled bool `json:"cancelled"`
Truncated bool `json:"truncated"`
// FullOutputPath points at the spilled full output when truncated.
FullOutputPath string `json:"fullOutputPath,omitempty"`
Timestamp int64 `json:"timestamp"`
// ExcludeFromContext drops the message from LLM conversion entirely.
ExcludeFromContext *bool `json:"excludeFromContext,omitempty"`
}
BashExecutionMessage reports one shell execution to the UI and context (pi: BashExecutionMessage).
func (BashExecutionMessage) MessageRole ¶
func (m BashExecutionMessage) MessageRole() types.Role
type BranchSummaryError ¶
type BranchSummaryError struct {
// Code is the backend-independent error code.
Code BranchSummaryErrorCode
// contains filtered or unexported fields
}
BranchSummaryError is the error returned by branch summarization helpers (pi: BranchSummaryError class).
func NewBranchSummaryError ¶
func NewBranchSummaryError(code BranchSummaryErrorCode, message string, cause error) *BranchSummaryError
NewBranchSummaryError builds a BranchSummaryError; cause may be nil.
func (*BranchSummaryError) Error ¶
func (e *BranchSummaryError) Error() string
func (*BranchSummaryError) Unwrap ¶
func (e *BranchSummaryError) Unwrap() error
type BranchSummaryErrorCode ¶
type BranchSummaryErrorCode string
BranchSummaryErrorCode is the stable branch-summary error code vocabulary returned by branch summarization helpers (pi: BranchSummaryErrorCode).
const ( BranchSummaryCodeAborted BranchSummaryErrorCode = "aborted" BranchSummaryCodeSummarizationFailed BranchSummaryErrorCode = "summarization_failed" )
type BranchSummaryMessage ¶
type BranchSummaryMessage struct {
Role types.Role `json:"role"` // "branchSummary"
Summary string `json:"summary"`
// FromID is the source entry id; nil = pi's null (summary of a session
// boundary with no single source entry).
FromID *string `json:"fromId"`
Timestamp int64 `json:"timestamp"`
}
BranchSummaryMessage reports a branch summarization result (pi: BranchSummaryMessage; v0.85.1: fromId is string | null).
func CreateBranchSummaryMessage ¶
func CreateBranchSummaryMessage(summary string, fromID *string, timestamp int64) BranchSummaryMessage
CreateBranchSummaryMessage builds a branch summary message (pi: createBranchSummaryMessage; v0.85.1: fromId is string | null; nil = null).
func (BranchSummaryMessage) MessageRole ¶
func (m BranchSummaryMessage) MessageRole() types.Role
type CompactionError ¶
type CompactionError struct {
// Code is the backend-independent error code.
Code CompactionErrorCode
// contains filtered or unexported fields
}
CompactionError is the error returned by compaction helpers (pi: CompactionError class).
func NewCompactionError ¶
func NewCompactionError(code CompactionErrorCode, message string, cause error) *CompactionError
NewCompactionError builds a CompactionError; cause may be nil.
func (*CompactionError) Error ¶
func (e *CompactionError) Error() string
func (*CompactionError) Unwrap ¶
func (e *CompactionError) Unwrap() error
type CompactionErrorCode ¶
type CompactionErrorCode string
CompactionErrorCode is the stable compaction error code vocabulary returned by compaction helpers (pi: CompactionErrorCode).
const ( CompactionCodeAborted CompactionErrorCode = "aborted" CompactionCodeSummarizationFailed CompactionErrorCode = "summarization_failed" )
type CompactionSettings ¶
type CompactionSettings struct {
// Enabled enables automatic compaction decisions.
Enabled bool
// ReserveTokens is the token budget reserved for summary prompt and
// output.
ReserveTokens int64
// KeepRecentTokens is the approximate recent-context tokens to keep
// after compaction.
KeepRecentTokens int64
}
CompactionSettings holds compaction thresholds and retention settings (pi: CompactionSettings from compaction/compaction.ts).
Defined here (package harness) instead of the compaction subpackage to break an import cycle: pi's agent-harness.ts lives in the harness root and consumes CompactionSettings, while pig's compaction package imports harness for the message helpers and error types. The compaction package re-exports the alias, keeping both pi import paths working.
type CompactionSummaryMessage ¶
type CompactionSummaryMessage struct {
Role types.Role `json:"role"` // "compactionSummary"
Summary string `json:"summary"`
TokensBefore int64 `json:"tokensBefore"`
Timestamp int64 `json:"timestamp"`
}
CompactionSummaryMessage reports a compaction result (pi: CompactionSummaryMessage).
func CreateCompactionSummaryMessage ¶
func CreateCompactionSummaryMessage(summary string, tokensBefore int64, timestamp int64) CompactionSummaryMessage
CreateCompactionSummaryMessage builds a compaction summary message (pi: createCompactionSummaryMessage).
func (CompactionSummaryMessage) MessageRole ¶
func (m CompactionSummaryMessage) MessageRole() types.Role
type CustomMessage ¶
type CustomMessage struct {
Role types.Role `json:"role"` // "custom"
CustomType string `json:"customType"`
// Content is a string or a []types.Content of text/image parts.
Content any `json:"content"`
Display bool `json:"display"`
Details any `json:"details,omitempty"`
Timestamp int64 `json:"timestamp"`
}
CustomMessage carries an application-defined UI/context message (pi: CustomMessage<T>; details loses its generic).
func CreateCustomMessage ¶
func CreateCustomMessage( customType string, content any, display bool, details any, timestamp int64, ) CustomMessage
CreateCustomMessage builds a custom message (pi: createCustomMessage).
func (CustomMessage) MessageRole ¶
func (m CustomMessage) MessageRole() types.Role
type Events ¶
type Events interface {
// On registers a passive listener for future events and returns its
// unsubscribe function. Earlier events are not replayed and no
// current-state snapshot is provided; use a lane or session watch for
// both. pi's generic on<TType> collapses to a type-erased listener;
// OnTyped restores the typed call shape.
On(eventType HarnessEventType, listener HarnessEventListener) (unsubscribe func())
}
Events is the passive event subscription surface (pi: interface Events).
type ExecutionEnv ¶
type ExecutionEnv interface {
FileSystem
Shell
}
ExecutionEnv is the filesystem and process execution environment used by the harness (pi: interface ExecutionEnv extends FileSystem, Shell).
type ExecutionError ¶
type ExecutionError struct {
// Code is the backend-independent error code.
Code ExecutionErrorCode
// contains filtered or unexported fields
}
ExecutionError is the error returned by ExecutionEnv.Exec (pi: ExecutionError class).
func NewExecutionError ¶
func NewExecutionError(code ExecutionErrorCode, message string, cause error) *ExecutionError
NewExecutionError builds an ExecutionError; cause may be nil.
func (*ExecutionError) Error ¶
func (e *ExecutionError) Error() string
func (*ExecutionError) Unwrap ¶
func (e *ExecutionError) Unwrap() error
type ExecutionErrorCode ¶
type ExecutionErrorCode string
ExecutionErrorCode is the stable, backend-independent execution error code vocabulary returned by ExecutionEnv.Exec (pi: ExecutionErrorCode).
const ( ExecCodeAborted ExecutionErrorCode = "aborted" ExecCodeTimeout ExecutionErrorCode = "timeout" ExecCodeSpawnError ExecutionErrorCode = "spawn_error" ExecCodeCallbackError ExecutionErrorCode = "callback_error" ExecCodeUnknown ExecutionErrorCode = "unknown" )
type FileError ¶
type FileError struct {
// Code is the backend-independent error code.
Code FileErrorCode
// Path is the absolute addressed path associated with the failure, when
// available.
Path string
// contains filtered or unexported fields
}
FileError is the error returned by FileSystem file operations (pi: FileError class).
func AsFileError ¶
AsFileError extracts a *FileError from an error chain (pi: property access on Result<T, FileError>.error, whose code field drives the branching in the skill/template loaders).
func NewFileError ¶
func NewFileError(code FileErrorCode, message string, path string, cause error) *FileError
NewFileError builds a FileError; path may be empty and cause may be nil.
type FileErrorCode ¶
type FileErrorCode string
FileErrorCode is the stable, backend-independent file error code vocabulary (pi: FileErrorCode).
const ( FileCodeAborted FileErrorCode = "aborted" FileCodeNotFound FileErrorCode = "not_found" FileCodePermission FileErrorCode = "permission_denied" FileCodeNotDirectory FileErrorCode = "not_directory" FileCodeIsDirectory FileErrorCode = "is_directory" FileCodeInvalid FileErrorCode = "invalid" FileCodeNotSupported FileErrorCode = "not_supported" FileCodeUnknown FileErrorCode = "unknown" )
type FileInfo ¶
type FileInfo struct {
// Name is the basename of Path.
Name string `json:"name"`
// Path is the absolute, syntactically normalized addressed path.
// Symlinks are not followed.
Path string `json:"path"`
// Kind is the object kind; symlink targets are not followed.
Kind FileKind `json:"kind"`
// Size is the size in bytes.
Size int64 `json:"size"`
// MtimeMs is the modification time as milliseconds since Unix epoch.
MtimeMs int64 `json:"mtimeMs"`
}
FileInfo is the metadata for one filesystem object in a FileSystem (pi: FileInfo).
type FileKind ¶
type FileKind string
FileKind is the kind of filesystem object as addressed by a FileSystem (pi: FileKind). Symlinks are not followed automatically.
type FileSystem ¶
type FileSystem interface {
// Cwd is the current working directory for relative paths.
Cwd() string
// AbsolutePath returns an absolute addressed path without requiring it to
// exist and without resolving symlinks.
AbsolutePath(ctx context.Context, path string) (string, error)
// JoinPath joins path segments in the filesystem namespace without
// requiring the result to exist.
JoinPath(ctx context.Context, parts []string) (string, error)
// ReadTextFile reads a UTF-8 text file.
ReadTextFile(ctx context.Context, path string) (string, error)
// ReadTextLines reads UTF-8 text lines. Implementations should stop once
// maxLines lines have been read.
ReadTextLines(ctx context.Context, path string, maxLines *int) ([]string, error)
// ReadBinaryFile reads a binary file.
ReadBinaryFile(ctx context.Context, path string) ([]byte, error)
// WriteFile creates or overwrites a file, creating parent directories
// when supported (pi: writeFile).
WriteFile(ctx context.Context, path string, content []byte) error
// AppendFile creates or appends to a file, creating parent directories
// when supported (pi: appendFile).
AppendFile(ctx context.Context, path string, content []byte) error
// RenameFile atomically renames a file, replacing the destination when it
// exists. Does not copy across filesystems.
RenameFile(ctx context.Context, sourcePath string, destinationPath string) error
// FileInfo returns metadata for the addressed path without following
// symlinks.
FileInfo(ctx context.Context, path string) (FileInfo, error)
// ListDir lists direct children of a directory without following
// symlinks.
ListDir(ctx context.Context, path string) ([]FileInfo, error)
// CanonicalPath returns the canonical path for an existing path,
// resolving symlinks where supported.
CanonicalPath(ctx context.Context, path string) (string, error)
// Exists returns false for missing paths. Other errors, such as
// permission failures, return a *FileError.
Exists(ctx context.Context, path string) (bool, error)
// CreateDir creates a directory. Defaults: recursive true (pi:
// createDir's options.recursive).
CreateDir(ctx context.Context, path string, recursive *bool) error
// Remove removes a file or directory. Defaults: recursive false, force
// false (pi: remove's options).
Remove(ctx context.Context, path string, recursive *bool, force *bool) error
// CreateTempDir creates a temporary directory and returns its absolute
// path. Defaults: prefix "tmp-".
CreateTempDir(ctx context.Context, prefix *string) (string, error)
// CreateTempFile creates a temporary file and returns its absolute path.
// Defaults: prefix "", suffix "".
CreateTempFile(ctx context.Context, prefix *string, suffix *string) (string, error)
// Cleanup releases filesystem resources. Must be best-effort and must
// not fail session flow (pi: "must not throw or reject").
Cleanup() error
}
FileSystem is the filesystem capability used by the harness (pi: FileSystem).
Paths passed to methods may be absolute or relative to Cwd. Paths returned by file operations are addressed paths in the filesystem namespace, but are not canonicalized through symlinks unless returned by CanonicalPath.
Operation methods must never panic; all filesystem failures, including unexpected backend failures, must be encoded in the returned error as a *FileError. Implementations must preserve this invariant.
type HarnessEvent ¶
type HarnessEvent interface {
EventType() HarnessEventType
}
HarnessEvent is the union of run lifecycle events (pi: HarnessEvent).
type HarnessEventBus ¶
type HarnessEventBus struct {
// contains filtered or unexported fields
}
HarnessEventBus fans run lifecycle events out to direct per-type listeners and watch subscriptions (pi: HarnessEventBus).
func NewHarnessEventBus ¶
func NewHarnessEventBus() *HarnessEventBus
NewHarnessEventBus builds an empty bus (pi: constructor).
func (*HarnessEventBus) Emit ¶
func (b *HarnessEventBus) Emit(event HarnessEvent)
Emit publishes an event to current event subscriptions and watch subscriptions (pi: HarnessEventBus.emit). Delivery is synchronous: per-type listeners first, then every watcher.
func (*HarnessEventBus) On ¶
func (b *HarnessEventBus) On(eventType HarnessEventType, listener HarnessEventListener) func()
On registers a listener for future events of one type and returns its unsubscribe function. Earlier events are not replayed, and no snapshot or event buffer is provided (pi: HarnessEventBus.on<TType>).
type HarnessEventListener ¶
type HarnessEventListener func(event HarnessEvent)
HarnessEventListener observes harness events (pi: HarnessEventListener). pi's Promise<void> return collapses to a synchronous callback.
type HarnessEventType ¶
type HarnessEventType string
HarnessEventType discriminates the HarnessEvent union (pi: HarnessEventType).
const ( HarnessEventRunStart HarnessEventType = "run_start" HarnessEventRunEnd HarnessEventType = "run_end" )
type PromptTemplate ¶
type PromptTemplate struct {
// Name is the stable template name used for lookup or application
// command routing.
Name string `json:"name"`
// Description is an optional description for command lists or
// autocomplete. Pointer: TS optional string; nil = pi's `undefined`.
Description *string `json:"description,omitempty"`
// Content is the template content. Argument placeholders are formatted
// by FormatPromptTemplateInvocation.
Content string `json:"content"`
}
PromptTemplate that can be formatted into a prompt for explicit invocation (pi: PromptTemplate).
type PromptTemplateDiagnostic ¶
type PromptTemplateDiagnostic struct {
// Type is the diagnostic severity. Currently only warnings are emitted
// (pi's literal "warning").
Type string `json:"type"`
Code PromptTemplateDiagnosticCode `json:"code"`
Message string `json:"message"`
Path string `json:"path"`
}
PromptTemplateDiagnostic is a warning produced while loading prompt templates (pi: PromptTemplateDiagnostic).
type PromptTemplateDiagnosticCode ¶
type PromptTemplateDiagnosticCode string
PromptTemplateDiagnosticCode is the stable diagnostic vocabulary for prompt template loading (pi: PromptTemplateDiagnosticCode).
const ( PromptTemplateDiagFileInfoFailed PromptTemplateDiagnosticCode = "file_info_failed" PromptTemplateDiagListFailed PromptTemplateDiagnosticCode = "list_failed" PromptTemplateDiagReadFailed PromptTemplateDiagnosticCode = "read_failed" PromptTemplateDiagParseFailed PromptTemplateDiagnosticCode = "parse_failed" )
type RunEndEvent ¶
type RunEndEvent struct {
Type HarnessEventType `json:"type"`
Lane string `json:"lane"`
RunID string `json:"runId"`
Outcome RunOutcome `json:"outcome"`
LeafID string `json:"leafId"`
}
RunEndEvent is emitted when a run ends (pi: RunEndEvent).
func (*RunEndEvent) EventType ¶
func (*RunEndEvent) EventType() HarnessEventType
EventType implements HarnessEvent (pi: the "run_end" discriminator).
type RunOutcome ¶
type RunOutcome string
RunOutcome is the terminal outcome of a run (pi: RunEndEvent["outcome"]).
const ( RunOutcomeCompleted RunOutcome = "completed" RunOutcomeAborted RunOutcome = "aborted" RunOutcomeFailed RunOutcome = "failed" )
type RunStartEvent ¶
type RunStartEvent struct {
Type HarnessEventType `json:"type"`
Lane string `json:"lane"`
RunID string `json:"runId"`
}
RunStartEvent is emitted when a run starts (pi: RunStartEvent).
func (*RunStartEvent) EventType ¶
func (*RunStartEvent) EventType() HarnessEventType
EventType implements HarnessEvent (pi: the "run_start" discriminator).
type Shell ¶
type Shell interface {
// Exec executes a shell command in FileSystem.Cwd unless options.Cwd is
// provided. ctx carries the caller's cancellation (pi: options.
// abortSignal).
Exec(ctx context.Context, command string, options *ShellExecOptions) (*ShellExecResult, error)
// Cleanup releases shell resources. Must be best-effort and must not
// fail session flow (pi: "must not throw or reject").
Cleanup() error
}
Shell is the shell execution capability used by the harness (pi: interface Shell). Exec failures return a *ExecutionError as the concrete error (pi: Result<..., ExecutionError> collapse, see header note).
type ShellExecOptions ¶
type ShellExecOptions struct {
// Cwd is the working directory for the command. Relative paths are
// resolved against ExecutionEnv.Cwd; empty defaults to it.
Cwd string
// Env holds environment variables for the command. Values override
// inherited defaults when InheritEnv is true.
Env map[string]string
// InheritEnv controls whether the execution environment's default
// variables are inherited. Pointer because pi's default is true; nil
// means that default.
InheritEnv *bool
// Timeout is the timeout in seconds. Implementations should return a
// timeout error when the command exceeds this duration. nil means no
// timeout (pi: number seconds).
Timeout *float64
// OnStdout is called with stdout chunks as they are produced.
OnStdout func(chunk string)
// OnStderr is called with stderr chunks as they are produced.
OnStderr func(chunk string)
}
ShellExecOptions are options for Shell.Exec (pi: ShellExecOptions).
type ShellExecResult ¶
ShellExecResult is the success payload of Shell.Exec (pi: the anonymous `{ stdout, stderr, exitCode }` result).
type Skill ¶
type Skill struct {
// Name is the stable skill name used for lookup and model-visible
// listings.
Name string `json:"name"`
// Description is the short model-visible description of when to use the
// skill.
Description string `json:"description"`
// Content is the full skill instructions.
Content string `json:"content"`
// FilePath is the absolute path to the skill file. Used for
// model-visible location and resolving relative references.
FilePath string `json:"filePath"`
// DisableModelInvocation excludes this skill from model-visible skill
// lists while still allowing explicit application invocation. Pointer:
// TS optional boolean; nil = pi's `undefined`.
DisableModelInvocation *bool `json:"disableModelInvocation,omitempty"`
}
Skill loaded from a `SKILL.md` file or provided by an application (pi: Skill).
Name, Description, and FilePath are inserted into the system prompt in an XML-formatted block as suggested by agentskills.io. Use FormatSkillsForSystemPrompt to generate the spec-compatible system prompt block.
type SkillDiagnostic ¶
type SkillDiagnostic struct {
// Type is the diagnostic severity. Currently only warnings are emitted
// (pi's literal "warning").
Type string `json:"type"`
Code SkillDiagnosticCode `json:"code"`
Message string `json:"message"`
Path string `json:"path"`
}
SkillDiagnostic is a warning produced while loading skills (pi: SkillDiagnostic).
type SkillDiagnosticCode ¶
type SkillDiagnosticCode string
SkillDiagnosticCode is the stable diagnostic vocabulary for skill loading (pi: SkillDiagnosticCode).
const ( SkillDiagFileInfoFailed SkillDiagnosticCode = "file_info_failed" SkillDiagListFailed SkillDiagnosticCode = "list_failed" SkillDiagReadFailed SkillDiagnosticCode = "read_failed" SkillDiagParseFailed SkillDiagnosticCode = "parse_failed" SkillDiagInvalidMetadata SkillDiagnosticCode = "invalid_metadata" )
type SourcedInput ¶
SourcedInput is one source-tagged path (pi: the Array<{ path: string; source: TSource }> input shape).
type SourcedPromptTemplate ¶
type SourcedPromptTemplate[TSource any] struct { PromptTemplate PromptTemplate Source TSource }
SourcedPromptTemplate pairs a loaded template with its provenance source (pi: the returned Array<{ promptTemplate: TPromptTemplate; source: TSource }> shape).
type SourcedPromptTemplateDiagnostic ¶
type SourcedPromptTemplateDiagnostic[TSource any] struct { PromptTemplateDiagnostic Source TSource }
SourcedPromptTemplateDiagnostic is a diagnostic tagged with its provenance source (pi: PromptTemplateDiagnostic & { source: TSource }).
type SourcedSkill ¶
SourcedSkill pairs a loaded skill with its provenance source (pi: the returned Array<{ skill: TSkill; source: TSource }> shape).
type SourcedSkillDiagnostic ¶
type SourcedSkillDiagnostic[TSource any] struct { SkillDiagnostic Source TSource }
SourcedSkillDiagnostic is a skill diagnostic tagged with its provenance source (pi: SkillDiagnostic & { source: TSource }).
type TaggedErrorBase ¶
type TaggedErrorBase struct {
// Tag is the stable discriminant (pi: the _tag field / class name).
Tag string `json:"_tag"`
// Message is the error message (pi: the Error message). TS keeps message
// on Error.prototype (not an own property) and re-adds it explicitly in
// toJSON; the promoted field lands in the same JSON position.
Message string `json:"message"`
}
TaggedErrorBase carries the tag and message shared by every tagged error (pi: the TaggedErrorClass base). Embed by value in a concrete error struct and the promoted fields serialize as {"_tag", "message", ...payload}, matching pi's toJSON.
func (*TaggedErrorBase) Error ¶
func (e *TaggedErrorBase) Error() string
func (*TaggedErrorBase) ErrorTag ¶
func (e *TaggedErrorBase) ErrorTag() string
type TaggedErrorValue ¶
TaggedErrorValue is the runtime contract shared by tagged errors (pi: interface TaggedErrorValue<Tag>). pi's toJSON member is provided by the TaggedErrorBase embedding instead of a separate method.
func AsTaggedError ¶
func AsTaggedError(err error) (TaggedErrorValue, bool)
AsTaggedError extracts a TaggedErrorValue from an error chain (pi: TaggedErrorClass.is(value) via instanceof; Go uses errors.As on the interface). Returns false for non-tagged errors.
type TelemetryAttributeDefinition ¶
type TelemetryAttributeDefinition struct {
// Type is the attribute value type: "string", "number", or "boolean".
Type string `json:"type"`
// Required marks attributes that must be present at span start.
Required bool `json:"required,omitempty"`
// Values enumerates the allowed values, when closed.
Values []string `json:"values,omitempty"`
// Description is the human-readable attribute description.
Description string `json:"description,omitempty"`
// Cardinality is the expected distinct-value volume: "low" or "high".
Cardinality string `json:"cardinality,omitempty"`
}
TelemetryAttributeDefinition describes one span attribute (pi: TelemetryAttributeDefinition from pi-telemetry).
type TelemetrySchemaDefinition ¶
type TelemetrySchemaDefinition struct {
Version int `json:"version"`
Spans []TelemetrySchemaSpanEntry `json:"-"`
}
TelemetrySchemaDefinition is one telemetry schema (pi: TelemetrySchemaDefinition).
func (*TelemetrySchemaDefinition) Span ¶
func (s *TelemetrySchemaDefinition) Span(name string) (TelemetrySchemaSpan, bool)
Span looks up one span definition by name.
func (*TelemetrySchemaDefinition) SpanNames ¶
func (s *TelemetrySchemaDefinition) SpanNames() []string
SpanNames returns the span names in declaration order (pi: Object.keys(schema.spans)).
type TelemetrySchemaSpan ¶
type TelemetrySchemaSpan struct {
Description string `json:"description"`
Parents TelemetrySpanParents `json:"parents"`
StartAttributes map[string]TelemetryAttributeDefinition `json:"startAttributes"`
EndAttributes map[string]TelemetryAttributeDefinition `json:"endAttributes"`
Status TelemetryStatusDefinition `json:"status"`
}
TelemetrySchemaSpan defines one span (pi: TelemetrySpanDefinition).
type TelemetrySchemaSpanEntry ¶
type TelemetrySchemaSpanEntry struct {
Name string
Span TelemetrySchemaSpan
}
TelemetrySchemaSpanEntry pairs a span name with its definition; the slice preserves pi's object key order.
type TelemetrySpanParents ¶
type TelemetrySpanParents struct {
// Kind is "any", "root_or_external", or "spans".
Kind string `json:"kind"`
// Spans names the allowed parent spans when Kind is "spans".
Spans []string `json:"spans,omitempty"`
}
TelemetrySpanParents defines where a span may attach (pi: the `parents` member of TelemetrySpanDefinition).
type TelemetryStatusDefinition ¶
type TelemetryStatusDefinition struct {
// Default is the default status kind ("ok").
Default string `json:"default"`
// ErrorWhen describes the condition that sets an error status.
ErrorWhen string `json:"errorWhen"`
}
TelemetryStatusDefinition declares the default span status and when it becomes an error (pi: the `status` member).
type WatchHandle ¶
type WatchHandle[TSnapshot any] struct { // Snapshot is the captured at-subscription state snapshot (pi: // watch's captureSnapshot result, taken after the receive function is // registered so events emitted during capture are buffered, not lost). Snapshot TSnapshot // contains filtered or unexported fields }
WatchHandle is a watch subscription handle (pi: WatchHandle<TSnapshot>).
func Watch ¶
func Watch[TSnapshot any](bus *HarnessEventBus, captureSnapshot func() TSnapshot) *WatchHandle[TSnapshot]
Watch registers a watch subscription and captures the snapshot (pi: HarnessEventBus.watch<TSnapshot>). The generic type parameter moves to this package-level function because Go methods cannot be generic.
func (*WatchHandle[TSnapshot]) Start ¶
func (h *WatchHandle[TSnapshot]) Start(listener HarnessEventListener)
Start delivers buffered events and then live events to listener (pi: WatchHandle.start).
func (*WatchHandle[TSnapshot]) Unsubscribe ¶
func (h *WatchHandle[TSnapshot]) Unsubscribe()
Unsubscribe removes the watch from the bus and discards the buffer (pi: WatchHandle.unsubscribe). The live listener is not cleared, matching pi.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agentharness corresponds to pi's packages/agent/src/harness/agent-harness.ts.
|
Package agentharness corresponds to pi's packages/agent/src/harness/agent-harness.ts. |
|
pi: src/harness/compaction/branch-summarization.ts — summarization of abandoned session branches before navigation.
|
pi: src/harness/compaction/branch-summarization.ts — summarization of abandoned session branches before navigation. |
|
Package env corresponds to pi's packages/agent/src/harness/env.
|
Package env corresponds to pi's packages/agent/src/harness/env. |
|
Package reducer corresponds to pi's packages/agent/src/harness/reducer.ts — pure lane-state reconstruction and record-log validation over bounded recovery slices.
|
Package reducer corresponds to pi's packages/agent/src/harness/reducer.ts — pure lane-state reconstruction and record-log validation over bounded recovery slices. |
|
pi: harness/session/commit.ts — transaction write materialization and validation shared by every storage backend.
|
pi: harness/session/commit.ts — transaction write materialization and validation shared by every storage backend. |
|
jsonl
pi: harness/session/jsonl/codec.ts — header parsing/validation for both the current format-4 header and the legacy v3 session header.
|
pi: harness/session/jsonl/codec.ts — header parsing/validation for both the current format-4 header and the legacy v3 session header. |
|
testing
pi: harness/session/testing/conformance/session-repo.ts — SessionRepo conformance case groups (lifecycle, ownership, messages, forks, fork coordination).
|
pi: harness/session/testing/conformance/session-repo.ts — SessionRepo conformance case groups (lifecycle, ownership, messages, forks, fork coordination). |
|
pi: src/harness/tools/bash.ts — the bash tool.
|
pi: src/harness/tools/bash.ts — the bash tool. |
|
Package utils corresponds to pi's packages/agent/src/harness/utils.
|
Package utils corresponds to pi's packages/agent/src/harness/utils. |