Documentation
¶
Overview ¶
Package runner abstracts where a job's process executes. The MVP ships the local runner (internal/runner/local); the peer-http runner (internal/runner/peerhttp), added in P7, forwards a job to a peer bridge. See plan §6.3, §9 (P4) and §11.1 (P7).
Index ¶
- Constants
- func ACPArtifactPath(resultDir string) string
- func AppendACPMirror(resultDir, text string) (int, error)
- func ErrorKindMarker(kind, resetAt string) string
- func ParseErrorKindMarker(text string) (kind, resetAt string, ok bool)
- type ACPMCPServer
- type ACPRequest
- type AgentBudgetUsage
- type ApprovalOption
- type ApprovalOutcome
- type ApprovalRequest
- type ApprovalSink
- type ApprovalToolCall
- type BudgetBreach
- type BudgetMeter
- type Commit
- type Forward
- type ImageInput
- type InteractionSink
- type MessengerDispatch
- type Outcome
- type PeerProber
- type ProbeResult
- type RemoteInteraction
- type RemoteInteractionOption
- type RemoteInteractionToolCall
- type Request
- type Result
- type Runner
- type SessionCommand
- type SessionUsage
- type Usage
- type VerifyResult
- type XferUpload
Constants ¶
const ( BudgetLimitTokens = "max_tokens" BudgetLimitCost = "max_cost_usd" BudgetLimitTurns = "max_turns" )
The budget limit names (BudgetBreach.Limit): the JSON keys of config.Budget, which is also what a user typed, so an error names the exact knob that tripped.
const ( ErrorKindTransient = "provider_transient" ErrorKindQuota = "provider_quota" ErrorKindRejected = "provider_rejected" ErrorKindBadResponse = "provider_bad_response" )
The agent's own verdict on a provider failure (suga's error_kind contract). suga labels every provider error it reports, so gofer need not guess from the message text:
- provider_transient: the stream broke, or an overload / rate-limit / 408 / 429 / 5xx / connection error outlived suga's own retries — the only kind worth continuing;
- provider_quota: an allowance (credit, weekly usage) is exhausted — continuing burns a dispatch and fails the same way until the limit resets;
- provider_rejected: the request itself was refused (400 / 401 / 403 / 404 / 422);
- provider_bad_response: an invalid JSON body or a permanent API error.
Any other value is treated as "not transient": a kind this build has never heard of is a reason to stop, not to repeat the run.
const ( EventPermissionRequested = "job.permission_requested" EventPermissionAnswered = "job.permission_answered" EventPermissionTimedOut = "job.permission_timed_out" )
The approval-gate job events (GATE-01 §1): recorded by the acp runner when a session/request_permission is raised, answered (by a human or automatically) or timed out. They live here for the same reason as EventInputInjected — the acp runner cannot import job — and, since SUP-01 G, also because the job package's worker→hub mirror whitelist must name them without a second literal that could drift. job.EventJobPermission* alias these.
const ( EventTurnTimeoutPaused = "job.turn_timeout_paused" EventTurnTimeoutResumed = "job.turn_timeout_resumed" )
The turn-clock job events (gofer-ji7m): recorded by the acp runner when a resident turn's running budget is paused for a wait on a human (an approval) and resumed by the answer. They live here for the same reason as the approval-gate events above — the acp runner cannot import job (G022) and the worker→hub mirror whitelist must name them; job.EventJobTurnTimeoutPaused / job.EventJobTurnTimeoutResumed alias them.
const ( // VerifyPassed: the step ran and exited 0 — the job keeps its status. VerifyPassed = "passed" // VerifyFailed: the step ran and exited non-zero — the job fails (or parks in // needs_review when a human is asked to rule on the delivery). VerifyFailed = "failed" // VerifyTimeout: the step exceeded its own deadline and was killed. VerifyTimeout = "timeout" // VerifySkipped: the step never ran because the agent did not finish normally // (failed / cancelled / timed out) — the agent's outcome is the job's outcome. VerifySkipped = "skipped" )
Verify step statuses (VerifyResult.Status).
const ( // UsageSourceNDJSONOMP: the completed assistant messages of an `omp --mode json` // stream, summed (each carries one model request's usage). UsageSourceNDJSONOMP = "ndjson:omp" // UsageSourceNDJSONClaude: the terminal `result` row of a `claude --output-format // stream-json` stream. UsageSourceNDJSONClaude = "ndjson:claude" // UsageSourceNDJSONPrefix + agent key: the usage object a self-built cli-agent's // result line carries at its configured ndjson_usage_path. UsageSourceNDJSONPrefix = "ndjson:" // UsageSourceCodexStderr: the `tokens used` tail codex prints on stderr. UsageSourceCodexStderr = "codex:stderr" // UsageSourceACP: the `usage_update` session/updates an acp agent sends. UsageSourceACP = "acp:usage_update" )
The usage sources (Usage.Source): which capture produced the numbers. They are the vocabulary the job row, `job show` and the dashboard print.
const BudgetErrorPrefix = "budget exceeded: "
BudgetErrorPrefix starts the error text of a budget failure. The job service recognises a failed job by it (a remote worker reports the failure as text only), so it is the contract between the executing side and the host's failure classification.
const EventACPSummary = "job.acp_summary"
EventACPSummary is the ONE lifecycle row an acp turn contributes to the job timeline (bd h-aii-rnxk): {tool_calls,thoughts,permissions,permissions_auto,stop_reason}, recorded when the prompt turn ends. The per-tool-call detail it replaces lives on the job's stderr as compact events (bd h-aii-7kja), and the AUTO-answered requests it counts live only here + on stderr + in acp.jsonl — they are no job events (F4). It lives in this package for the same reason as the permission events; job.EventJobACPSummary aliases it.
const EventCancelRequested = "job.cancel_requested"
EventCancelRequested is the job event a runner records when the cancel frame for a worker-run job could not be DELIVERED (F3, bd h-aii-tcpm): {delivered:false, worker_id}. The host has already finished the job as cancelled, so this is what makes "the worker may still be running it" visible on the job's own timeline instead of only in a server log. It lives in this package for the same reason as the events above (the runner cannot import job, G022); job.EventJobCancelRequested aliases it.
const EventCredentialSkipped = "job.credential_skipped"
EventCredentialSkipped is the job event a worker runner records when it dispatched a job to a peer whose protocol predates the job-credential frame (SEC-01): {reason:"worker_protocol"}. The job runs — it just has no credential of its own, so it cannot call the hub back — and this event is the only place that omission is visible, exactly like EventSkillsSkipped above (which it mirrors). It lives in this package for the same reason (the runner cannot import job, G022); job.EventJobCredentialSkipped aliases it.
const EventInputInjected = "job.input_injected"
EventInputInjected is the job event a runner records when it wrote priming input into an interactive child's stdin (session relay §9.1 B). It lives here — not in the job package — because the runner emits it and the runner package cannot import job (G022); job.EventJobInputInjected aliases it, so the literal has exactly one definition.
const EventMCPSkipped = "job.mcp_skipped"
EventMCPSkipped records that a dispatched job's MCP servers were not sent because the worker's protocol predates them (MCP-06).
const EventSkillsMounted = "job.skills_mounted"
EventSkillsMounted is the job event the HOST records for a job whose skill mount travelled to a ws-worker as uploads (JOB-10, S4 2026-09-23): {names, via:"uploads"}. The local mount path records its own receipt (job.mountSkills runs on the machine that places the files — the worker, for a dispatched job, where it is a local job of its own and the host sees nothing); this one is the host's half, raised by the worker runner the moment the dispatch carrying the mount went out. It lives in this package for the same reason as the events above (the runner cannot import job, G022); job.EventJobSkillsMounted aliases it.
const EventSkillsSkipped = "job.skills_skipped"
EventSkillsSkipped is the job event a worker runner records when it dispatched a job to a peer that cannot carry the job's skill mount (JOB-10, design §横切): {reason:"worker_protocol", count, names}. The job runs — the skills are dropped rather than risk a pre-v10 worker writing them into the shared working tree — so this event is the only place that omission is visible. It lives in this package for the same reason as the events above (the runner cannot import job, G022); job.EventJobSkillsSkipped aliases it.
const UsageSourceTranscriptPrefix = "transcript:"
UsageSourceTranscriptPrefix + dialect labels usage read from an agent's own transcript (terminal sessions, N2 §A), e.g. "transcript:claude".
Variables ¶
This section is empty.
Functions ¶
func ACPArtifactPath ¶ added in v0.136.0
ACPArtifactPath is where a job's structured ACP stream lives under its result dir: the acp runner writes it there on the executing machine, and a hub mirrors a worker job's copy to the same place on the HOST (gofer-e2x7), so every reader (/v1/jobs/{id}/acp/stream) resolves one path regardless of where the job ran.
func AppendACPMirror ¶ added in v0.136.0
AppendACPMirror appends one mirrored chunk of a remote job's acp.jsonl to the host job's copy under resultDir, creating the artifacts dir on first use. The file is opened per chunk on purpose: a mirror chunk is rare (a few per turn) and the sinks that call this (a dispatched job's sink, an adopted job's sink after a serve restart) then need no close hook tied to their own lifetime. It returns the bytes that landed; an empty resultDir or text is a no-op.
func ErrorKindMarker ¶ added in v0.168.0
ErrorKindMarker renders the kind (and the quota reset time, when the agent gave one) as a bracketed suffix of an error string, the one carrier that survives every route a job error takes (a remote worker's result carries only the error text). The ACP runner writes it from a prompt error response's `data`; ParseErrorKindMarker reads it back.
func ParseErrorKindMarker ¶ added in v0.168.0
ParseErrorKindMarker reads an ErrorKindMarker back out of an error string.
Types ¶
type ACPMCPServer ¶
type ACPMCPServer struct {
Name string
Command string
Args []string
Env map[string]string
// Type is "" / stdio (Command/Args/Env) or http (URL/Headers, MCP-06); an http
// server is only sent to an agent whose mcpCapabilities.http is true.
Type string
URL string
Headers map[string]string
}
ACPMCPServer is one MCP server advertised to an acp-agent through session/new.
type ACPRequest ¶
type ACPRequest struct {
// Prompt is the turn's prompt text (sent as one text content block).
Prompt string
// SessionCommands keeps one ACP process alive for subsequent prompts. Nil means
// the existing one-turn job. The job service owns admission and the channel.
SessionCommands <-chan SessionCommand
OnSessionReady func(string)
// OnImageCapability reports whether the agent advertised promptCapabilities.image.
// It is called once per session, before OnSessionReady (initialize runs on every
// start, including a session/load recovery, so the fact is re-learned each time).
OnImageCapability func(bool)
OnTurnStart func() error
OnTurnEnd func(string) error
OnAwaitInput func() error
TurnTimeoutSec int
IdleTimeoutSec int
MaxSessionSec int
IdleDeadlineAt int64
MaxSessionDeadlineAt int64
AppendEvents bool
InitialTurnNo int
// ResultDir is the job's result directory; the runner writes its structured
// event stream to <ResultDir>/artifacts/acp.jsonl.
ResultDir string
// Approval is the RESOLVED approval policy of this job (GATE-01 §1): the project's
// approval block tightened by the agent's acp.permission_policy
// (config.Config.EffectiveApproval), defaults applied. It is the runner's ONLY
// input for session/request_permission — the agent's raw permission_policy is
// folded in by the resolver, so a stricter policy can never be lost in transit —
// and Mode off reproduces the S0 auto-allow.
Approval config.ApprovalConfig
// MCPServers are advertised to the agent in session/new.
MCPServers []ACPMCPServer
// MailResident marks the gofer mailbox's resident 收件会话 (mail.agents.<name>): the
// gate auto-allows its call to gofer_session_mail_reply, so answering a letter does
// not park on a human. Everything else stays gated (gofer-sh7r).
MailResident bool
// LoadSessionID, when non-empty, is the agent session this job CONTINUES: the
// runner calls session/load{sessionId} instead of session/new (ACP-01 S2). It is
// filled only for a resume (JobRequest.ResumedFrom set) — a plain job that carries
// a session_id binds to it without replaying the agent's history. An agent that
// does not advertise agentCapabilities.loadSession fails the job rather than
// silently running the prompt in a fresh, context-free session.
LoadSessionID string
// ModelID, when non-empty, is the model the job asked for (N1 §B): after the
// session is opened and BEFORE the first prompt the runner selects it through the
// protocol (a session config option of category "model", else session/set_model).
// An agent that exposes neither, or does not offer this id, fails the job with an
// explicit error rather than answering with a model nobody asked for.
ModelID string
// ReadOnlyModeID, when non-empty, switches the session into this agent mode
// (session/set_mode) BEFORE the prompt turn (bd h-aii-0ql3): it is the operator's
// acp.modes.read_only mapping, and admission has already refused the job when the
// agent maps none. When the session reports availableModes and this id is not
// among them, the run fails instead of prompting in a writable mode.
ReadOnlyModeID string
// LogThoughts keeps the agent's thinking in the job's logs (bd h-aii-7kja ②):
// true (the default) writes the coalesced thought line to stderr and acp.jsonl,
// false keeps the run's logs free of it. config.ACPConfig.LogsThoughts is the
// reader of the operator's `agents.<k>.acp.log_thoughts`.
LogThoughts bool
// ClaudeSettingsEnv lets the runner seed the agent's environment from claude's
// user settings file before it starts the process (F14): the `env` block's keys
// that neither the process environment nor Env already define, minus SEC-01's
// denied ones. config.ACPConfig.InheritsClaudeSettingsEnv is the reader of the
// operator's `agents.<k>.acp.claude_settings_env`; the value is read on the
// EXECUTING machine (the runner is where the ACP process starts).
ClaudeSettingsEnv bool
}
ACPRequest is the acp-agent payload of a runner.Request: everything the acp runner needs beyond the process argv (Command/Args/WorkDir/Env) and the log writers.
type AgentBudgetUsage ¶ added in v0.175.0
type AgentBudgetUsage struct {
Scope string `json:"scope,omitempty"`
LimitTokens int64 `json:"limit_tokens,omitempty"`
UsedTokens int64 `json:"used_tokens,omitempty"`
RemainingTokens int64 `json:"remaining_tokens,omitempty"`
LimitCostUSD float64 `json:"limit_cost_usd,omitempty"`
UsedCostUSD float64 `json:"used_cost_usd,omitempty"`
RemainingCostUSD float64 `json:"remaining_cost_usd,omitempty"`
Exceeded bool `json:"exceeded,omitempty"`
Reason string `json:"reason,omitempty"`
// Estimated marks usage the agent estimated locally instead of reading from the
// provider (not a billed figure).
Estimated bool `json:"estimated,omitempty"`
}
AgentBudgetUsage is the last soft-budget snapshot an agent reported. A zero Limit means that dimension is not limited. Exceeded is the agent saying it ran out and is winding the run up (a soft finish, not a kill).
func AgentBudgetFromLine ¶ added in v0.175.0
func AgentBudgetFromLine(line map[string]any) *AgentBudgetUsage
AgentBudgetFromLine reads the `budget` object of a stream-json line (suga's usage / result rows): {scope, exceeded, reason, tokens:{limit,used,remaining}, cost_usd:{limit,used,remaining}}, with the line-level `estimated` flag. nil when the line carries none.
func AgentBudgetFromMeta ¶ added in v0.175.0
func AgentBudgetFromMeta(meta map[string]any) *AgentBudgetUsage
AgentBudgetFromMeta reads the budget fields an ACP usage_update carries under its `_meta` object: budget_scope, budget_limit / budget_used / budget_remaining (each a {tokens, cost_usd} map holding only the configured dimensions), budget_exceeded, budget_reason and the top-level estimated flag. nil when the update carries no budget (the keys are optional and absent unless a budget is on).
type ApprovalOption ¶
type ApprovalOption struct {
// ID is the ACP optionId — what an answer selects.
ID string
// Label is the agent's human-facing name for the option.
Label string
// Kind is the ACP option kind: allow_once|allow_always|reject_once|reject_always.
Kind string
}
ApprovalOption is one choice offered for an approval request, mirroring an ACP permission option (session/request_permission.options).
type ApprovalOutcome ¶
type ApprovalOutcome struct {
// Answer is the chosen optionId ("" when the request was cancelled instead of
// answered — the caller decides what a cancellation means).
Answer string
// By is the interaction's answered_by attribution (human / agent:<id> /
// auto:<policy>); "" for an unattributed or cancelled answer.
By string
}
ApprovalOutcome is the approver's decision.
type ApprovalRequest ¶
type ApprovalRequest struct {
// Prompt is the question shown to the approver.
Prompt string
// Options are the agent's own options, verbatim and in its order.
Options []ApprovalOption
// ToolCall is the gated tool call (nil when the agent sent none).
ToolCall *ApprovalToolCall
// PolicyHint is the human-readable rationale, e.g. "ask: kind=edit".
PolicyHint string
// TimeoutSec is how long this request may wait for an answer (0 = no deadline).
// The sink stamps it onto the raised interaction so an answerer can show a
// countdown: the deadline is the one the runner will actually honour.
TimeoutSec int
// OnRaised (nil-safe) is invoked EXACTLY ONCE, synchronously, with the interaction
// id as soon as the request is visible to approvers — before the call starts
// waiting. That is where a caller records its "a human is needed" event or
// notification; emitting it after the wait would announce an approval nobody can
// act on any more.
OnRaised func(interactionID string)
}
ApprovalRequest is one approval gate request (GATE-01 §1): the tool call an agent wants to run, the options the agent offered for it, and why the gate stopped it.
type ApprovalSink ¶
type ApprovalSink interface {
RequestApproval(ctx context.Context, req ApprovalRequest) (ApprovalOutcome, error)
}
ApprovalSink raises an approval request on a job and blocks until it is answered or ctx ends. The implementation is the job service (an interaction of type permission); the interface lives here so runner implementations need not import job. A ctx that ends (the gate's own deadline or the job's) MUST leave no pending interaction behind.
type ApprovalToolCall ¶
type ApprovalToolCall struct {
ID string
Title string
Kind string
Locations []string
RawInputSummary string
}
ApprovalToolCall is the tool call an approval request is about (ACP toolCall, reduced to what an approver needs).
type BudgetBreach ¶
type BudgetBreach struct {
Limit string `json:"limit"`
Max float64 `json:"max"`
Actual float64 `json:"actual"`
}
BudgetBreach is the first limit a job went over (N2 §B): which one, its ceiling and the value that crossed it.
func ParseBudgetBreach ¶
func ParseBudgetBreach(errText string) (BudgetBreach, bool)
ParseBudgetBreach recovers a breach from a failed job's error text (ok=false when the text is not a budget failure). Used where only the text survives: a remote worker reports the failure as an error string.
func (BudgetBreach) Error ¶
func (b BudgetBreach) Error() string
Error renders the failure text: `budget exceeded: max_tokens 50000 (used 51234)`.
type BudgetMeter ¶
type BudgetMeter struct {
// contains filtered or unexported fields
}
BudgetMeter accumulates one job's spend from the agent's streamed accounting and reports the first limit crossed (N2 §B). It is fed from the execution-side capture points — the ndjson projection, the acp handler, the codex stderr sniff — and is safe for concurrent use. A nil *BudgetMeter is a valid no-op meter, so call sites never branch on "is there a budget".
Accounting rules:
- tokens: input+output+cache of every distinct model message. A message that is reported several times (claude emits one line per content block, all carrying the message's usage) is keyed by its id and counted once, with the largest total seen. A source with no per-message id (omp, acp usage_update, a generic usage path) reports a RUNNING tally instead; that is kept as a high-water mark. The job total is the larger of the two views.
- cost: the largest cost a source reported (0 where it reports none).
- turns: model requests — assistant messages (ndjson) or prompt turns (acp).
The limit is "more than": max_turns=3 lets the third request finish and trips on the fourth, so a run is never cut off while delivering its last allowed answer.
func NewBudgetMeter ¶
func NewBudgetMeter(b *config.Budget, onBreach func(BudgetBreach)) *BudgetMeter
NewBudgetMeter returns a meter for b, or nil when b limits nothing. onBreach (may be nil) is called once, from the goroutine that fed the crossing value, with no meter lock held.
func (*BudgetMeter) AddMessage ¶
func (m *BudgetMeter) AddMessage(id string, u *Usage)
AddMessage records one assistant message: id is the provider's message id ("" = no id, every call is a distinct message) and u its usage (may be nil: the message still counts as a turn).
func (*BudgetMeter) AddTurn ¶
func (m *BudgetMeter) AddTurn()
AddTurn counts one model request that carries no usage of its own (an acp prompt turn, an omp assistant message whose usage arrives separately).
func (*BudgetMeter) Breach ¶
func (m *BudgetMeter) Breach() *BudgetBreach
Breach returns the first limit crossed, or nil.
func (*BudgetMeter) SetCost ¶
func (m *BudgetMeter) SetCost(c float64)
SetCost records a reported cost (high-water).
func (*BudgetMeter) SetTally ¶
func (m *BudgetMeter) SetTally(u *Usage)
SetTally records a source's running usage tally (high-water, never decreasing).
type Commit ¶
Commit is one commit the execution machine captured for a job (SUP-01 C): abbreviated sha + subject line, as `git log --oneline` prints them.
type Forward ¶
type Forward struct {
ProjectKey string
Agent string
PeerRunner string // runner to use on the peer; default "local"
Prompt string
AgentArgs []string
Model string // N1 §B: the executing machine renders ITS agent's model_args
FromSession string // gofer-f4z8: the executing machine renders ITS agent's from_session_args
Budget *config.Budget // N2 §B: decided spend ceiling the EXECUTING machine meters; nil = unlimited
SystemPrompt string
Cmd []string
Cwd string // ORIGINAL relative cwd; peer SafeJoins against ITS project
// Worktree (WT-01) asks the EXECUTING machine to run the job in a managed git
// worktree of ITS project checkout (the peer SafeJoins Cwd against its own
// project root and then maps it into the worktree). WorktreeBase is the base ref
// (empty = the executing checkout's HEAD). The project-level worktree_default is
// already resolved into Worktree by the submitting service, so the executor never
// re-derives a default from its own config.
Worktree bool
WorktreeBase string
// WorktreeName / WorktreeBranch are the caller's --worktree-name and --branch
// (2026-10-21 design 一). The EXECUTOR renders the project's worktree.dir/branch
// templates with them, so the name override has to travel with a dispatched job.
WorktreeName string
WorktreeBranch string
// Ref is the commit the EXECUTING machine checks out in a TEMPORARY detached
// worktree for this job (design 一·3 `ref:`). The submitting side resolved the
// spec's ref to a full sha, so every fan of a step checks out the same commit. The
// executor fetches the commit if its checkout lacks it, runs the job there and
// removes the checkout when the job ends. Mutually exclusive with Worktree.
Ref string
// Env is the job's extra environment (a workflow step / fan `env`), layered over
// the executor's process env. It travels in Dispatch.Env, so a worker below
// wsproto.JobEnvMinProtocolVersion is refused rather than given a job that runs
// without its variables.
Env map[string]string
TimeoutSec int
Interactive bool
Cols int
Rows int
// InitialInput / InitialInputQuietMs carry path B's priming text and quiet
// window to the EXECUTING machine (session relay §9.1 B): the pty is started
// there, so the text and the window the hub resolved must travel with the
// dispatch instead of being re-derived from the worker's own config.
InitialInput string
InitialInputQuietMs int
// Stdin is text piped to the (non-interactive) command's stdin on the executing
// machine (protocol v18).
Stdin string
// ResumeSourceAgent is an internal resume marker carried over trusted worker
// dispatch so the worker validates the exec resume carrier against the source
// agent. It is not part of the public HTTP job contract.
ResumeSourceAgent string
// SessionID / ResumedFrom (ACP-01 S2) carry a continuation to a remote executor:
// ResumedFrom is the source job id (set only by ResumeJob) and SessionID the agent
// session to LOAD. A remote runner sends them over Dispatch only when the request
// really is a resume — a plain job that merely carries a session_id is not one.
SessionID string
ResumedFrom string
AutoResumeAttempt int
// ReadOnly (bd h-aii-0ql3) asks the remote executor to run the job in its own
// read-only mode (cli-agent argv sandbox / acp-agent session/set_mode). The
// executor validates it against ITS agent config, so an agent without a read-only
// mode fails there with the explanation the host could not have produced.
ReadOnly bool
// NoRules is the caller's `--no-rules`: the executing machine must not add the
// sections it renders itself (its declared tools, CFG-16). The rules were already
// decided — and skipped — by the submitting machine.
NoRules bool
// WorkerID is the resolved target worker for a runner=worker job (P2 dynamic
// routing): the explicit req.WorkerID or the one auto-selected from labels.
// Empty for peer-http forwards and for worker jobs that rely on the runner's
// configured default worker (D4 fallback).
WorkerID string
// TodoID (SUP-01 C) is the hub's checklist item for this job, carried so the
// execution machine's job row can DISPLAY it. The todo itself lives in the
// hub's store, so the linkage is the hub's alone (JobRequest.TodoForeign) — a
// peer re-submits without it and links its own nothing.
TodoID string
// Verify / VerifyTimeoutSec are the job's验证步骤 (SUP-01 B): the argv to run
// AFTER the agent finishes normally, and its own deadline in seconds. The
// EXECUTING machine runs it in its checkout with the job's env, because that is
// where the work happened — the hub has no checkout to verify. Empty = no step
// (an old hub never sets them, and an old worker ignores them; the hub refuses
// the dispatch instead, see wsproto.VerifyMinProtocolVersion).
Verify []string
VerifyTimeoutSec int
// Uploads / Collect are the job's file-transfer steps (XFER-01 X2). The executor
// owns the cwd they act on, so both travel to it: the uploads' staged ids (the
// bytes are fetched over HTTP, this frame carries only the instruction) and the
// collect globs. Empty on a job that carries no files, and absent entirely from a
// pre-v9 hub's frame — such a hub never dispatches a job that needs them (see
// wsproto.FileXferMinProtocolVersion).
Uploads []XferUpload
Collect []string
// Skills (JOB-10) is the RESOLVED skill binding the executing machine mounts —
// the union the hub decided, never re-derived there (the peer's own config names
// a different library). The files travel as Uploads with Base=result_dir, so the
// machine that owns the result dir writes them and renders the prompt list from
// these names (决策 1). It is dropped for a peer below wsproto.SkillsMinProtocolVersion
// (the hub dispatches without it and records job.skills_skipped instead of risking a
// mount in the shared working tree).
Skills []string
// MCP are the job's registry MCP servers (MCP-06), resolved by the hub.
MCP []wsproto.MCPSpec
// ExclusiveDir / StallTimeoutSec are the JOB-11 / AUTO-05 execution policies the
// submitting hub RESOLVED (server.dir_lock + the agent's max_concurrent/stall
// knobs): the executing machine applies them instead of re-deriving its own from
// its own config, exactly like TimeoutSec/Verify above. Pointers because "0 /
// false" is a DECISION (no lock, no watchdog) that must not be confused with
// "unresolved" — an old hub omits both keys and the executor falls back to its own
// config. Additive/optional: a peer that predates them ignores the fields, which
// only means these protections do not apply on that machine (nothing is corrupted
// by running as before), so no protocol floor refuses the dispatch.
ExclusiveDir *bool
StallTimeoutSec *int
// DirWaitMaxSec (JOB-11, F12) is how long the EXECUTOR may leave this job queued on
// the same-directory lock before failing it, in seconds (0 = no cap). It travels for
// the same reason as ExclusiveDir: the lock is taken on that machine, and the
// policy the hub resolved is what must apply there.
DirWaitMaxSec *int
// EnvDenyExtra is an internal trusted execution policy carried to workers.
EnvDenyExtra []string
// JobToken (SEC-01) is the job-scoped credential the HUB minted for this job. The
// ws-worker runner puts it on the dispatch frame (protocol ≥ 11) and the worker's
// own job service injects it as GOFER_JOB_TOKEN, which is what lets a job talk to
// the hub after the inherited server token is gone. It is deliberately NOT
// serialisable: peer-http posts this whole struct to another gofer
// (`POST /v1/jobs`), and a credential minted by this hub must never travel to an
// unrelated peer. A peer-http job therefore runs with no job credential — that
// transport has no field to carry one.
JobToken string `json:"-"`
// Session fields are carried only by the ws-worker transport in protocol v13.
// Peer-http remains a one-shot transport and rejects session jobs.
Session bool
IdleTimeoutSec int
MaxSessionSec int
// Messenger is an additive worker dispatch hint. Old workers ignore it and
// execute Cmd, the explicitly retained v13 fallback.
Messenger *MessengerDispatch
}
Forward carries the original (pre-resolution) request a remote runner needs to re-submit to a peer bridge (peer resolves agent/cwd/command with its own config). Nil for local jobs; the local runner ignores it.
type ImageInput ¶ added in v0.177.0
ImageInput is one image attached to a resident-session prompt: its media type and raw (not base64) bytes.
type InteractionSink ¶
type InteractionSink interface {
Open(ctx context.Context, it RemoteInteraction) (<-chan string, error)
}
InteractionSink lets a remote runner bridge a peer's running-job interactions into the HOST job: Open records the interaction on the host job (host -> pending_interaction) and returns a channel delivering the host-side answer once the user answers it; the runner then forwards that answer to the peer. The channel is closed WITHOUT a value if the host job ends / ctx is cancelled before an answer. Open must be idempotent-safe for a repeated interaction id.
type MessengerDispatch ¶
type MessengerDispatch struct {
// Op is "" / "send" (forward Command's prompt) or "list_agents" (v16).
Op string
SessionName string
Command []string
Cwd string
TimeoutSec int
IdleSec int
}
MessengerDispatch mirrors the wire payload without making runner depend on wsproto. The worker runner projects it at the transport boundary.
type Outcome ¶
type Outcome struct {
RenderedCommand string `json:"rendered_command,omitempty"`
ResultJSON string `json:"result_json,omitempty"`
DiffSummary string `json:"diff_summary,omitempty"`
UncommittedFiles []string `json:"uncommitted_files,omitempty"`
UncommittedCount int `json:"uncommitted_count,omitempty"`
Artifacts json.RawMessage `json:"artifacts,omitempty"` // []ArtifactItem 清单元数据(JSON)
// Source marks WHERE the job actually ran: "worker:<id>" or "peer:<name>"
// (empty for local). It is persisted (jobs.source) and surfaced so the详情
// can标注 "在 worker w-xxx / peer X 执行" (P4-c).
Source string `json:"source,omitempty"`
// SessionID is the底层 agent CLI 会话标识 the EXECUTION machine captured/injected
// for this job (P3). The remote runner (worker/peer) ran its own P1
// captureOutcomes against its local JobResult, so this carries that machine's
// SessionID back to the host (applyOutcome → entry.result.SessionID), enabling
// `job resume` / `list --session` for remotely-executed jobs. Empty = the
// remote produced no session id (unsupported agent / not captured).
SessionID string `json:"session_id,omitempty"`
// WT-01: the managed worktree the job ran in — recorded on the EXECUTION machine
// (it owns that path), so a host row for a runner=worker/peer job still shows
// where the deliverable branch lives. All empty/0 for a non-worktree job and for
// an old worker that never sends them (host fields stay empty).
WorktreePath string `json:"worktree_path,omitempty"`
WorktreeBranch string `json:"worktree_branch,omitempty"`
WorktreeBaseSHA string `json:"worktree_base_sha,omitempty"`
WorktreeHeadSHA string `json:"worktree_head_sha,omitempty"`
CommitsAhead int `json:"commits_ahead,omitempty"`
// BaseSHA / Commits are the SUP-01 C提交采集: the commit the job started from
// and the commits it produced (newest first), captured on the execution machine
// — the host has no checkout there, so both travel with the outcome.
BaseSHA string `json:"base_sha,omitempty"`
Commits []Commit `json:"commits,omitempty"`
// Verify is the job's验证步骤 result (SUP-01 B). The step runs on the EXECUTION
// machine (it owns the checkout being verified), so its structured result travels
// back here; nil = the job had no verify step (or the worker predates it — the
// hub refuses such a dispatch rather than running a step it can no longer trust).
Verify *VerifyResult `json:"verify,omitempty"`
// Usage is the token/cost accounting the EXECUTION machine captured for this job
// (SUP-01 E): an agent's own numbers live in the log stream / stderr tail over
// there, so they travel with the outcome like the commits and the verify verdict.
// Nil = that machine captured none.
Usage *Usage `json:"usage,omitempty"`
// Xfer is the job's file-transfer summary as the EXECUTION machine computed it
// (XFER-01 X2): which uploads it placed and which files its collect globs matched.
// It travels with the rest of the outcome because the host has no cwd there — and
// it is what the host's row shows (`xfer_json`) and what tells the hub which
// collected files to PULL. Nil = the job carried no files.
//
// Raw JSON for the same reason as Artifacts: the job package owns the summary
// type, and runner stays a cycle-free leaf. The job service unmarshals it into
// job.XferSummary.
Xfer json.RawMessage `json:"xfer,omitempty"`
}
Outcome is the产出与审计 payload a REMOTE runner回传 from the execution machine to the host job (P4, design §6.6). v1 carries only清单+小结果: the rendered command, the structured result.json, the diff摘要 and the artifacts清单 METADATA — the大产物文件本身留 worker 侧/共享盘, NOT inlined here (D6).
Artifacts is carried as raw JSON (the `[]ArtifactItem` manifest the execution machine already serialised) so the runner package stays a cycle-free leaf: the job package owns ArtifactItem and imports runner, never the reverse. The job service applies it verbatim into the jobs.artifacts_json column.
type PeerProber ¶
type PeerProber struct {
// contains filtered or unexported fields
}
PeerProber is the C6/P4 peer-http active health-probe component held by serve. It periodically GETs each peer-http runner's /health and caches the last result (up/down + millis timestamp + latency + error) under an RWMutex. The /v1/runners handler reads the cache via Snapshot (never a live probe), so probing never blocks request handling (§7 D1/D4).
It does NOT reuse the peer-http job-forwarding client (D1): the probe only needs a lightweight unauthenticated GET /health with its own timeout, so it uses a dedicated http.Client and stays decoupled from job dispatch.
func NewPeerProber ¶
func NewPeerProber(cfg *config.Config, timeout time.Duration) *PeerProber
NewPeerProber builds a prober over the peer-http runners in cfg.Runners (type=="peer-http"). It returns nil when there are no such runners so serve can skip wiring the probe loop entirely (zero behaviour change without peers). The timeout bounds a single /health GET.
func (*PeerProber) ProbeOnce ¶
func (p *PeerProber) ProbeOnce(ctx context.Context)
ProbeOnce probes every target concurrently and writes the results into the cache. Each probe is bounded by ctx (the http.Client timeout is the hard cap); a non-2xx or transport error yields a down result with the error text. The write takes the full Lock once after all probes complete so a Snapshot reader never observes a half-updated set.
func (*PeerProber) Reload ¶
func (p *PeerProber) Reload(cfg *config.Config, timeout time.Duration)
Reload replaces the probe target set and timeout in place. Existing cached results for removed runners are discarded; the next probe repopulates the cache for the new set without rebuilding the HTTP handler wiring.
func (*PeerProber) Snapshot ¶
func (p *PeerProber) Snapshot() []ProbeResult
Snapshot returns a copy of the current cached probe results (one per target). It is the non-blocking read the /v1/runners handler uses; it takes only the RLock and never triggers a live probe. Implements httpapi's runnerProber.
func (*PeerProber) TargetCount ¶
func (p *PeerProber) TargetCount() int
TargetCount returns the number of peer-http targets the prober polls. It lets serve log the wired target count without exposing the unexported targets slice.
type ProbeResult ¶
type ProbeResult struct {
Name string
Up bool
CheckedAt int64 // unix millis of the probe; 0 when never probed yet
LatencyMS int64
Err string
}
ProbeResult is the cached outcome of one peer-http /health probe (C6/P4). It is the DTO the serve-side prober feeds into the httpapi handler through its consumer-side runnerProber interface. CheckedAt is a unix-millis timestamp (SR102, matching handleHealth's server_time); Up=false with a non-empty Err is a down result.
It lives in the runner package (the probe's natural产物) so httpapi/serve reference runner.ProbeResult without runner ever importing httpapi (httpapi → runner is the正向 dependency; the reverse would be a cycle — D-B3).
type RemoteInteraction ¶
type RemoteInteraction struct {
ID string
Type string
Prompt string
Options []RemoteInteractionOption
// ToolCall / PolicyHint carry a type=permission interaction's approval detail
// (GATE-01 §1); nil/"" for every other interaction, as does ExpiresAt (the
// approval deadline, unix seconds, 0 = none).
ToolCall *RemoteInteractionToolCall
PolicyHint string
ExpiresAt int64
}
RemoteInteraction is a peer-raised interaction a remote runner surfaces to the host job via an InteractionSink. Fields mirror job.Interaction's wire shape.
type RemoteInteractionOption ¶
type RemoteInteractionOption struct {
Value string
Label string
// ID / Kind carry a permission interaction's ACP option identity and kind
// (GATE-01 §1); "" for every other interaction.
ID string
Kind string
}
RemoteInteractionOption mirrors a peer interaction option without importing the job package (runner must stay cycle-free: job imports runner).
type RemoteInteractionToolCall ¶
type RemoteInteractionToolCall struct {
ID string
Title string
Kind string
Locations []string
RawInputSummary string
}
RemoteInteractionToolCall mirrors job.InteractionToolCall for the same cycle-free reason as RemoteInteractionOption.
type Request ¶
type Request struct {
// OnProcessStarted is a local-only observation of the direct child PID.
// It is not part of Forward or any wire protocol.
OnProcessStarted func(pid int)
JobID string
WorkDir string // absolute host dir; the job service supplies a SafeJoin'd path
LockPaths []string // resolved directory lock paths selected by the job service
Command string
Args []string
Env map[string]string // agent-config env, layered over the process env
Stdout io.Writer // child stdout sink / mirrored remote stdout (see type doc)
Stderr io.Writer // child stderr sink / mirrored remote stderr (see type doc)
// Interactive requests a pty-backed run. Cols/Rows are the initial terminal
// size in character cells; zero values let the runner apply its defaults.
Interactive bool
Cols int
Rows int
ExitKeys []string // ordered literal PTY input on cancellation
ExitGraceSec int // <= 0 uses the PTY runner's 8s default
SessionStoreGlob string // execution-machine glob for a non-injected CLI session
SessionStoreIDRegex string
// InitialInput is text the pty runner writes to the interactive child's stdin
// once its terminal is ready — after the FIRST output and then a quiet window,
// so a TUI has drawn its prompt before the text arrives (session relay §9.1 B:
// the takeover job's first message). "" = nothing is written. Only the pty
// runner reads it; every other runner ignores it.
InitialInput string
// InitialInputQuietMs is that quiet window in milliseconds (0 = the runner's
// default, resolved from session.takeover_input_delay_ms by the job service).
InitialInputQuietMs int
// Stdin is text written to a NON-interactive command's standard input, then EOF
// (the local runner; the pty runner ignores it — use InitialInput there).
Stdin string
// EnvDeny / EnvAllow are SEC-01's env-privacy decision for this job, resolved by
// the job service from the process's own config (server.job_env_denylist) and the
// project's (projects.<k>.job_env_allow). Every runner that spawns a child filters
// the INHERITED environment through them (util.EnvironWithout), so a job never
// starts with the serve process's bearer token in its environment unless an
// operator deliberately allowed that key for the project. Env is not filtered: it
// is the caller's own written-down config.
EnvDeny []string
EnvAllow []string
// EnvDenyExtra is an internal additive policy for trusted worker dispatches;
// it is never caller input or persisted job state.
EnvDenyExtra []string
// Forward carries the original (pre-resolution) request a remote runner
// re-submits to a peer bridge. Nil for local jobs.
Forward *Forward
// ResultDir is the HOST job's result directory, set for remote jobs only: the
// ws-worker runner appends the worker's mirrored acp.jsonl under it
// (ACPArtifactPath, gofer-e2x7). A local runner never reads it — the acp runner
// gets its own result dir on ACPRequest.
ResultDir string
// Uploads / Collect are the job's file-transfer steps (XFER-01 X2), already
// resolved by the job service. The EXECUTING machine carries them out (its cwd is
// the only one that matters): it places each staged upload in the job's cwd BEFORE
// the agent starts, and matches the collect globs there AFTER the job ends. A
// remote job's copies ride the Forward instead (a worker's own job service runs
// them on its machine).
Uploads []XferUpload
Collect []string
// Skills / SkillsResolved are JOB-10's resolved skill binding for THIS request.
// Skills is the decided list (config.EffectiveSkills); SkillsResolved is the
// dispatch-side marker: true means the submitting machine already resolved it, so
// the executing machine must NOT re-union the binding against its own config (a
// worker's library may hold a different set, and re-deriving would mount skills
// the hub never chose). False on a local job that has not been through resolution
// yet, which is the pre-JOB-10 reading.
Skills []string
SkillsResolved bool
// Verify / VerifyTimeoutSec are the job's验证步骤 (SUP-01 B), already resolved by
// the job service (project default + --no-verify). The LOCAL runner does not read
// them: the job service runs the step itself right after Run returns, on this
// machine and in this WorkDir/Env — which is why they are on the request the job
// service built rather than on the Forward (a remote job's step runs on the
// EXECUTING machine and travels in Forward).
Verify []string
VerifyTimeoutSec int
// Interactions bridges a peer's running-job interactions onto the host job.
// Nil for local jobs; set by the job service for remote runners so a peer's
// interactions surface on the host job (see InteractionSink).
Interactions InteractionSink
// Approvals lets a runner RAISE an approval request of its own — an interaction of
// type permission — and block until it is answered (GATE-01 §1). The acp runner
// uses it for a tool call the project's approval policy will not auto-approve; nil
// means the executing side has no interaction surface, and a runner that needs one
// must refuse to run the gated action rather than approve it silently.
Approvals ApprovalSink
// OnRendered (nil-safe) is invoked by a remote runner with the rendered command
// as soon as the executing machine reports it, so the host can show WHAT is
// running immediately (G1). The host cannot render a remote agent's argv itself
// (it lacks that worker's agent config), so a worker/peer reports it out-of-band.
// Local runs set the rendered command inline and leave this nil.
OnRendered func(rendered string)
// OnStarted is called by a remote runner when the execution machine has
// actually begun running the job (after its own queue). Local runners leave it nil.
OnStarted func()
// OnStartedAt is the timestamped form of OnStarted. A terminal remote result
// may use this as a last-chance start notification when a fast job finishes
// before the periodic started status frame is sent.
OnStartedAt func(startedAt int64)
// OnSessionStatus mirrors protocol-v13 remote ACP turn state onto the host job.
OnSessionStatus func(wsproto.Status)
// OnSuspend (nil-safe) is invoked by a remote runner when the executing machine's
// connection dropped but the job is being HELD for a possible reconnect (RECOV-01)
// instead of failed: the host job moves to `recovering` and keeps its timeout
// running. Local runs leave it nil.
OnSuspend func(reason string)
// OnResume (nil-safe) is called when that connection came back and the executing
// machine still runs the job: the host job returns to `running` (RECOV-01). It
// must be safe to call after a terminal signal (it is a no-op then). Local runs
// leave it nil.
OnResume func()
// OnDispatchedWorker (nil-safe) is invoked by a remote runner the moment it has
// committed the job to a resolved target — after the sink is registered and the
// worker proven online, before the dispatch frame is written (RECOV-01 R4). It
// carries the RESOLVED worker_id (explicit, label-selected, or the runner's
// configured default — the D4 fallback the request itself never names) plus that
// connection's process instance id, so the host row records which worker PROCESS
// owns the job. Only the same instance may later ADOPT the job after a serve
// restart. Local runs leave it nil.
OnDispatchedWorker func(workerID, instanceID string)
// ACP carries the inputs of an acp-agent job (prompt, event-stream directory,
// MCP servers, permission policy). It is set by the job service when the
// resolved agent is type acp-agent, and the acp runner is the only runner that
// reads it. Nil for every other job.
ACP *ACPRequest
// OnJobEvent (nil-safe) lets a runner record a job lifecycle event (e.g. the acp
// runner's job.permission_* / job.acp_summary rows) on the job. The job service
// wires it to its event log; the runner never touches the store itself.
OnJobEvent func(eventType string, detail map[string]any)
// Meter, when non-nil, is the job's budget meter (N2 §B GATE-02): a runner that
// observes the agent's accounting itself (the acp runner) feeds it; it is also wired
// into the ndjson capture by the job service. Local-only, never on the wire. nil =
// no budget.
Meter *BudgetMeter
}
Request is a ready-to-execute command for a runner.
Stdout/Stderr meaning differs by runner:
- The LOCAL runner wires these io.Writers directly to the child process so the job service can stream output straight into stdout.log / stderr.log as it is produced.
- REMOTE runners (peer-http, P7) do NOT resolve a local command. They re-submit the original request (carried in Forward) to a peer bridge and MIRROR the peer's log stream back into these same writers, so the local job's stdout.log / stderr.log (and thus /logs, /stream and list) stay transparently usable for the proxied job. Command/Args/WorkDir are unset for remote runners (the peer resolves them with its own config). A remote runner additionally uses Interactions (an InteractionSink) to bridge the peer's running-job interactions (P9) onto the HOST job.
Forward is nil for local jobs (the local runner ignores it) and set by the job service for remote-runner jobs.
type Result ¶
type Result struct {
ExitCode int
Err error
// TimedOut is set when a remote executor reports its own execution deadline.
// It avoids a race with the host's delayed timeout context.
TimedOut bool
// Outcome, when non-nil, carries产出 captured on a remote execution machine
// (worker / peer). Nil for local jobs. See Outcome doc.
Outcome *Outcome
// SessionID is a session identifier an execution-local runner learned out of
// band from the process it ran — today the acp runner's sessionId, which the job
// row records so `job resume` has a uniform entry point. Empty when the runner
// has none (local, remote: a remote's session id travels in Outcome).
SessionID string
// StopReason is the acp runner's session/prompt stopReason. It is empty for
// runners with no such notion; the job row records it when set.
StopReason string
SessionEndReason string
// Usage is the token/cost accounting an execution-local runner learned from the
// process it ran — today the acp runner's accumulated usage_update tally
// (SUP-01 E). Nil when the runner has none (local exec, and the ndjson/codex
// captures, which run inside the job service rather than in a runner).
Usage *Usage
}
Result is the outcome of a single Run. ExitCode is the process exit status (or a synthetic non-zero when the process could not start / was killed); Err carries the underlying error when execution failed or the context ended. The job service maps ExitCode/Err plus the context reason to a job status.
Outcome is the P4 remote-capture channel: a LOCAL runner leaves it nil (the job service then captures产出 from its own result dir / DB — P1–P3). A REMOTE runner (worker / peer-http) executed the job on another machine, so it carries the产出 captured there back to the host job here; the job service detects a non-nil Outcome and applies it directly instead of scanning a (远端) result dir the host does not own (design §6.6 / D6).
type Runner ¶
type Runner interface {
// Name returns the runner's stable identifier (e.g. "local").
Name() string
// Run executes req under ctx and returns the exit code and any error.
Run(ctx context.Context, req Request) Result
}
Runner executes one resolved command and reports how it ended.
type SessionCommand ¶
type SessionCommand struct {
Prompt string
// Images are sent after the Prompt text, in order, as ACP image content blocks.
// Only set for an agent that advertised promptCapabilities.image (the job layer
// gates it); the runner refuses them otherwise.
Images []ImageInput
End bool
}
SessionCommand is one message or a graceful end for a resident ACP job.
type SessionUsage ¶
type SessionUsage struct {
Main Usage `json:"main"`
Sub Usage `json:"sub"`
ByModel map[string]Usage `json:"by_model,omitempty"`
}
SessionUsage is the token accounting of one terminal agent-CLI session (N2 §A, OBS-14), in the same Usage shape a job uses. The hook reads the agent's transcript and reports DELTAS (since its last report); the server adds them up, so the same type is both the heartbeat's `usage_delta` and the session's stored total.
Main is the session's own conversation, Sub everything its sub-agents burned (sidechain rows plus the transcript's subagents/*.jsonl files). ByModel splits the SAME tokens (main + sub) by the model that produced them, so Main+Sub equals the sum of ByModel for a transcript that names its models.
func (*SessionUsage) Add ¶
func (s *SessionUsage) Add(o SessionUsage)
Add folds o into s (counters add; ByModel merges per model).
func (SessionUsage) Empty ¶
func (s SessionUsage) Empty() bool
Empty reports that nothing was counted (so there is nothing to report or store).
func (SessionUsage) EstimateCost ¶ added in v0.146.0
func (s SessionUsage) EstimateCost(price func(model string) (config.ModelPrice, bool)) (float64, []string)
EstimateCost prices the per-model tallies that carry no reported cost with price (gofer-2ldy): the estimate in USD and the models price does not know (sorted). Reported costs are left out — they are already in the tallies' CostUSD.
type Usage ¶
type Usage struct {
InputTokens int64 `json:"input_tokens,omitempty"`
OutputTokens int64 `json:"output_tokens,omitempty"`
CacheReadTokens int64 `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int64 `json:"cache_write_tokens,omitempty"`
TotalTokens int64 `json:"total_tokens,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
// ToolCalls is the number of tool calls the run made, when the agent reports it
// (`tool_calls` in its usage object); 0 = not reported.
ToolCalls int64 `json:"tool_calls,omitempty"`
// Turns is the number of model requests the run made, as counted by the job's
// budget meter (N2 §B); 0 unless the job carried a budget.
Turns int64 `json:"turns,omitempty"`
Source string `json:"source,omitempty"`
// AgentBudget is the agent's own view of the soft budget it was given
// (agent_tokens / agent_cost_usd): limit, used and whether it ran out. Additive —
// nil unless the agent reports it (suga's usage_update _meta / result `budget`).
AgentBudget *AgentBudgetUsage `json:"agent_budget,omitempty"`
}
Usage is one job's token/cost accounting (SUP-01 E): what the agent that ran the job reported about the work, in ONE shape for every source. It lives here — not in the job package — because the acp runner and the ndjson capture produce it and the job package reads it (job imports runner, never the reverse: G022).
Every field is best-effort: a zero counter means "the agent did not report this one" (these payloads are partial by nature), and CostUSD stays 0 for an agent with no cost notion (codex). Source names WHERE the numbers came from, so a reader can tell a provider's own accounting from a projected one.
func UsageFromObject ¶
UsageFromObject reads an agent's usage payload — its own JSON object — into the one shape gofer records. It is deliberately tolerant: ACP leaves the field names to the agent and the ndjson agents differ from each other, so every spelling seen in the wild is accepted (camelCase / snake_case / a numeric string), while a payload with nothing recognisable yields nil — a guess would put made-up numbers on a job row.
Total is the agent's own total when it reports one, otherwise the sum of the counters it did report (claude's usage block carries no total field).
func (*Usage) Add ¶ added in v0.142.0
Add folds one model request's usage into u (counters and cost summed). A stream that reports PER-REQUEST usage (omp's assistant message_end) is totalled with it; Source is kept from u, or taken from o when u has none yet. A nil o is a no-op.
type VerifyResult ¶
type VerifyResult struct {
// Command is the argv as submitted (element-wise, never a shell join).
Command []string `json:"command,omitempty"`
// Status is passed|failed|timeout|skipped.
Status string `json:"status"`
// ExitCode is the step's exit status (-1 when it did not end on its own: a
// timeout, or a job cancelled while the step ran). 0 for skipped/passed.
ExitCode int `json:"exit_code"`
// DurationMs is how long the step ran, in milliseconds (0 for skipped).
DurationMs int64 `json:"duration_ms"`
// Reason explains a non-obvious status, e.g. why the step was skipped
// ("agent failed") or why it timed out.
Reason string `json:"reason,omitempty"`
}
VerifyResult is the outcome of one job's verify step (SUP-01 B): the argv that ran, how it ended and how long it took. It lives in the runner package — not in job — because it is carried across the wire by Outcome (job imports runner, so the job package aliases this type: job.VerifyResult).
type XferUpload ¶
type XferUpload struct {
// XferID is the staging-area id (the payload itself rides HTTP).
XferID string `json:"xfer_id"`
// Dest is the destination path on the executing machine, relative to Base.
Dest string `json:"dest"`
// Base is the directory Dest is relative to: "" / "cwd" is the job's working
// directory (the pre-JOB-10 reading, and what every ordinary --upload uses), and
// "result_dir" is the job's own result directory (a skills mount, which must
// never land in the shared checkout). It only reaches a peer at
// wsproto.SkillsMinProtocolVersion or above — see splitSkillUploads.
Base string `json:"base,omitempty"`
}
XferUpload is one staged file a job takes with it (XFER-01 X2): the id of a transfer already staged on the hub and the path it must be placed at on the EXECUTING machine, relative to Base.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package acp runs an `acp-agent` job: it starts the agent's ACP server over stdio, drives exactly one prompt turn (initialize → session/new → session/prompt) and maps the protocol's events onto the job's outputs.
|
Package acp runs an `acp-agent` job: it starts the agent's ACP server over stdio, drives exactly one prompt turn (initialize → session/new → session/prompt) and maps the protocol's events onto the job's outputs. |
|
Package local implements the in-process (local host) runner.
|
Package local implements the in-process (local host) runner. |
|
Package ndjsonfilter turns a structured (NDJSON / JSON-Lines) agent output stream into the two streams gofer captures (bd h-aii-rpky, bd h-aii-525u).
|
Package ndjsonfilter turns a structured (NDJSON / JSON-Lines) agent output stream into the two streams gofer captures (bd h-aii-rpky, bd h-aii-525u). |
|
Package peerhttp implements a remote runner that forwards a job to a peer gofer over HTTP (plan §11.1, P7).
|
Package peerhttp implements a remote runner that forwards a job to a peer gofer over HTTP (plan §11.1, P7). |
|
Package ptyrunner is the worker-side runner variant for interactive (pty-attached) jobs (WEB-03 design §5/§6, D1).
|
Package ptyrunner is the worker-side runner variant for interactive (pty-attached) jobs (WEB-03 design §5/§6, D1). |
|
Package worker implements the ws-worker host-side runner (main plan §4, internal/runner/worker).
|
Package worker implements the ws-worker host-side runner (main plan §4, internal/runner/worker). |