Documentation
¶
Overview ¶
Caller scope ceilings (上限): the operator-declared upper bound of what ONE caller (one token) may reach, and the load-time checks that keep a ceiling honest.
A ceiling is a subtractive layer, never a grant: a caller's effective range is its permissions ∩ its ceiling. An absent ceiling (`ceiling` key missing, or nil) restricts nothing, which is why every predicate here allows everything on a nil receiver — the caller of these functions is expected to ask `CallerCeiling(id)` first and treat ok=false as "no ceiling".
The design is docs/design/2026-10-18-caller-scope-ceilings-design.md; this file owns the model and the pure predicates, the job layer owns admission, and httpapi owns the route/read-write judgment.
Package config defines the gofer configuration model and the loader/writer that resolve, decode, default and persist it. See plan §6.1.
Index ¶
- Constants
- Variables
- func ApplyAgentExtends(agents map[string]AgentConfig, raw []byte) error
- func ApplyDefaults(cfg *Config)
- func ApplyProjectOverlays(cfg *Config) []string
- func BuiltinDeliver(name string) (command []string, stdin bool, offlineMatch string)
- func BuiltinMCP(name string) (string, []string)
- func BuiltinModelArgs(name string) []string
- func BuiltinReadOnlyArgs(name string) []string
- func CheckWorkerID(id string) error
- func ConfigDir() (string, error)
- func DeleteTunnel(name string) error
- func EditableAgentFields() []string
- func EffectiveSubmitAgents(list []string) []string
- func EnsureWorkspaceDir() (dir string, created bool, err error)
- func EventHookName(target string) (string, bool)
- func InjectDefaultProject(cfg *Config)
- func IsBuiltinLocalRunnerName(name string) bool
- func IsClientRunMode() bool
- func IsLocalRunnerName(name string) bool
- func IsSecretFieldName(name string) bool
- func LoadDotenv() ([]string, error)
- func MCPEnvRefs(s string) []string
- func MCPInjectedEnvName(server, key string) string
- func MissingToolBins(tools []Tool) []string
- func NewWorkerToken() (string, error)
- func NormalizeRunnerName(name string) string
- func ParseBroadcastRate(v string) (count int, window time.Duration, err error)
- func ProjectKeyFromDir(dir string) (string, error)
- func RegisterWorkerInto(cfg *Config, id string, labels, projects []string, token string) error
- func RejectRemovedKeys(raw []byte) error
- func RemoveWorkerFrom(cfg *Config, id, expectFingerprint string) (removed bool, err error)
- func RenderYAML(v any) (string, error)
- func ReplaceMCPEnvRefs(s string, repl func(name string) string) string
- func ReservedNameError(what, name string) error
- func ReservedRunnerName(name string) bool
- func Resolve(explicitPath string) (string, error)
- func ResolveLocalPath(field, value string) (string, error)
- func ResolveLocalPathAt(field, value, configDir string) (string, error)
- func RunMode() string
- func RuntimeFilePath(sub, name string) string
- func Save(path string, cfg *Config) error
- func SaveTunnels(t *Tunnels) error
- func SecretFields() []string
- func SectionFileOf(mainPath, key string) (string, error)
- func SectionPolicies(section string) map[string]FieldPolicy
- func TimeoutLimitKey(source, projectKey string) string
- func ToolLine(t Tool) string
- func UpsertTunnel(name string, profile TunnelProfile, force bool) error
- func UserConfigPath() (string, error)
- func UserTunnelsPath() (string, error)
- func UserWorkerConfigPath() (string, error)
- func ValidDeliveryMode(m string) bool
- func ValidInjectProcessName(n string) bool
- func ValidMCPFormat(f string) bool
- func ValidWebhookKind(k string) bool
- func Validate(cfg *Config) error
- func ValidateTools(tools []Tool) error
- func ValidateTunnelProfile(name string, p TunnelProfile) error
- func ValidateWorkerTunnel(w WorkerConfig) error
- func WorkerTokenFingerprint(token string) string
- func WorkspaceDir(explicit string) (string, error)
- func WorktreeNameValid(name string) bool
- func WriteReloadResult(path string, result ReloadResult) error
- type ACPConfig
- type ACPMCPServerConfig
- type AgentBudgetMap
- type AgentConfig
- type AgentFallbackConfig
- type AgentHealthConfig
- type ApprovalConfig
- type ArgList
- type AttachmentSettings
- type AttachmentsConfig
- type BackoffSec
- type Budget
- type CallerCeiling
- func (c *CallerCeiling) AllowsAgent(a string) bool
- func (c *CallerCeiling) AllowsProject(p string) bool
- func (c *CallerCeiling) AllowsRunner(r string) bool
- func (c *CallerCeiling) AllowsWorker(w string) bool
- func (c *CallerCeiling) ExecAllowed() bool
- func (c *CallerCeiling) GlobalMemoryAllowed() bool
- func (c *CallerCeiling) IsReadOnly() bool
- type CallerConfig
- type CastConfig
- type CastEncryptionConfig
- type CommentTriggerConfig
- type Config
- func (c *Config) AgentFallbackOnFailure() bool
- func (c *Config) AgentFallbackPreDispatch() bool
- func (c *Config) AgentFallbacksFor(projectKey, agentKey string) []string
- func (c *Config) Clone() *Config
- func (c *Config) ConfiguredSessionStopJobWait() string
- func (c *Config) DecisionHooksFor(point, projectKey string, internal bool) []DecisionHookConfig
- func (c *Config) EffectiveAgentHealth() AgentHealthConfig
- func (c *Config) EffectiveApproval(projectKey, agent string) ApprovalConfig
- func (c *Config) EffectiveAttachments() AttachmentSettings
- func (c *Config) EffectiveAutoRelayIdleSec() int
- func (c *Config) EffectiveAutoRelaySkipWhenSupervising() bool
- func (c *Config) EffectiveAutoRelayTurnSec() int
- func (c *Config) EffectiveBudget(projectKey, agentKey string, requested *Budget) *Budget
- func (c *Config) EffectiveCommentTrigger() (minIntervalSec, maxPerScope int)
- func (c *Config) EffectiveContinueMaxChain(projectKey string) int
- func (c *Config) EffectiveDirLock() bool
- func (c *Config) EffectiveDirLockMaxWaitSec(requested *int) int
- func (c *Config) EffectiveHoldTimeoutSec(requested int) (int, error)
- func (c *Config) EffectiveImageInput(key string) string
- func (c *Config) EffectiveMCP(projectKey, agentKey string, requested []string, disable bool, ...) []string
- func (c *Config) EffectiveMail() MailSettings
- func (c *Config) EffectiveMaxTimeout(projectKey string) (sec int, source string)
- func (c *Config) EffectiveMaxTimeoutSec(projectKey string) int
- func (c *Config) EffectivePtyTranscriptMaxBytes() int64
- func (c *Config) EffectiveRetryPolicy(projectKey, agentKey string, requested *RetryPolicy) *RetryPolicy
- func (c *Config) EffectiveRules(projectKey, agentKey string, requested []string, disable bool, ...) []string
- func (c *Config) EffectiveRulesMaxBytes() int
- func (c *Config) EffectiveSessionOfflineAfterSec() int
- func (c *Config) EffectiveSessionProgressIntervalSec() int
- func (c *Config) EffectiveSessionRelayAutoWaitSec() int
- func (c *Config) EffectiveSessionRelayOnWaitSec() int
- func (c *Config) EffectiveSessionStopJobWait() string
- func (c *Config) EffectiveSessionSupervisingWindowSec() int
- func (c *Config) EffectiveSessionTakeoverAliveSec() int
- func (c *Config) EffectiveSessionTakeoverInputDelayMs() int
- func (c *Config) EffectiveSkills(projectKey, agentKey string, requested []string, disable bool, ...) []string
- func (c *Config) EffectiveStallTimeoutSec(agentKey, agentType string, requested *int, interactive bool) int
- func (c *Config) EffectiveVerifyTimeoutSec(projectKey string) int
- func (c *Config) EventHook(name string) (EventHookConfig, bool)
- func (c *Config) ExecPath(p ProjectConfig) string
- func (c *Config) InjectedAgents() map[string]bool
- func (c *Config) InjectedProjects() map[string]bool
- func (c *Config) IsInjectedAgent(key string) bool
- func (c *Config) IsInjectedProject(key string) bool
- func (c *Config) JobRecoverWindow() time.Duration
- func (c *Config) LeaderConfig() *LeaderConfig
- func (c *Config) LeaderEnabled() bool
- func (c *Config) LoadWarnings() []string
- func (c *Config) MCPBoundBy(name string) (server bool, agents, projects []string)
- func (c *Config) MarkInjectedAgents(keys map[string]bool)
- func (c *Config) MarkServeRuntimeOverrides(before ServerConfig)
- func (c *Config) MetricsExposureWarning() string
- func (c *Config) MutateProjects(mut func(map[string]ProjectConfig) error) error
- func (c *Config) PolicyRepush() (time.Duration, int)
- func (c *Config) PriceFor(model string) (ModelPrice, bool)
- func (c *Config) ProjectAllowedAgents(projectKey string) ([]string, bool)
- func (c *Config) ProjectForPath(cwd string) (key string, ok bool)
- func (c *Config) ProjectMatchForPath(cwd string) (key, root string, ok bool)
- func (c *Config) ResolveDBPath() string
- func (c *Config) ResolveDBPathChecked() (string, error)
- func (c *Config) ResolveSecretValue(name string) (jobVar, value string, err error)
- func (c *Config) ResolveStorageRoot() (string, error)
- func (c *Config) ResolveWorkerDBPath(workerID string) string
- func (c *Config) ResolvedExchangeSubdir(p ProjectConfig) string
- func (c *Config) ResolvedResultSubdir(p ProjectConfig) string
- func (c *Config) SectionFile(key string) string
- func (c *Config) SectionSources() map[string]string
- func (c *Config) SourceFiles() []string
- func (c *Config) UnmarkInjectedAgent(key string)
- func (c *Config) ValidateDelivery() error
- func (c *Config) ValidateLocalPaths() error
- func (c *Config) ValidateMCPServers() error
- func (c *Config) ValidatePricing() error
- func (c *Config) ValidateSecrets() error
- func (c *Config) WakeupTTL() time.Duration
- type DecisionHookConfig
- type DeliveryConfig
- type DetectConfig
- type EventHookConfig
- type FieldPolicy
- type GovernanceConfig
- type HTTPProxyConfig
- type HoldConfig
- type LeaderConfig
- type LogConfig
- type MCPServerConfig
- type MailAgentConfig
- type MailConfig
- type MailSettings
- type MetricsConfig
- type ModelPrice
- type NotificationConfig
- type PolicyRepushConfig
- type ProjectConfig
- func (p ProjectConfig) ApprovalPolicy() ApprovalConfig
- func (p ProjectConfig) EffectiveKnowledgeCapture() string
- func (p ProjectConfig) EffectiveScopeDiscipline() string
- func (p ProjectConfig) EffectiveTrackerPrime() string
- func (p ProjectConfig) IsInteractiveAllowed() bool
- func (p ProjectConfig) IsNotifyEnabled() bool
- func (p *ProjectConfig) RenderWorktreeBranch(name, jobID string) string
- func (p *ProjectConfig) RenderWorktreeDir(name, jobID string) string
- func (p *ProjectConfig) UnmarshalYAML(data []byte) error
- func (p *ProjectConfig) WorktreeLinks() []string
- type ProjectOverlay
- type ProjectWorktree
- type PtyConfig
- type PushConfig
- type ReconnectConfig
- type ReloadResult
- type RetentionConfig
- type RetryPolicy
- type RoleConfig
- type RunnerConfig
- type RunnerProbeConfig
- type ScheduleConfig
- type SecretConfig
- type ServerConfig
- func (sc *ServerConfig) CallerCanAdmin(callerID string) bool
- func (sc *ServerConfig) CallerCanAnswer(callerID string) bool
- func (sc *ServerConfig) CallerCanAttach(callerID string) bool
- func (sc *ServerConfig) CallerCanTunnel(callerID string) bool
- func (sc *ServerConfig) CallerCeiling(id string) (*CallerCeiling, bool)
- func (sc *ServerConfig) CallerConcurrencyLimit(callerID string) int
- func (sc *ServerConfig) CallerName(callerID string) string
- func (sc *ServerConfig) CallerNames() map[string]string
- func (sc *ServerConfig) CallerRate(callerID string) (rps float64, burst int)
- func (sc *ServerConfig) CeilingCallers() []string
- func (sc *ServerConfig) EffectiveAutoResumeMax() int
- func (c ServerConfig) EffectiveSessionMessaging() SessionMessagingConfig
- func (sc *ServerConfig) HasRootAdmin() bool
- func (sc ServerConfig) IsWebEnabled() bool
- func (sc *ServerConfig) RootAdminCallers() []string
- type ServerTunnelConfig
- type SessionConfig
- type SessionMessagingConfig
- type SkillLimitsConfig
- type SplitResult
- type StewardConfig
- type StorageConfig
- type TLSConfig
- type Tool
- type TunnelProfile
- type Tunnels
- type UpdateConfig
- type WakeupConfig
- type WebhookConfig
- type WorkConfig
- func (w WorkConfig) AutoHandoffOn() bool
- func (w WorkConfig) DigestClock() (hour, minute int)
- func (w WorkConfig) NeedsMeNotifyOn() bool
- func (w WorkConfig) NeedsMeThrottle() time.Duration
- func (w WorkConfig) RequestTimeout() time.Duration
- func (w WorkConfig) StallAfterDuration() time.Duration
- func (w WorkConfig) SummarizeDaily() int
- func (w WorkConfig) SummarizeIdle() time.Duration
- func (w WorkConfig) SummarizeMinInterval() time.Duration
- func (w WorkConfig) SummarizeOn() bool
- func (w WorkConfig) SummarizerAgentName() string
- func (w WorkConfig) SummarizerArgsOrDefault() []string
- func (w WorkConfig) SummarizerSessionAge() time.Duration
- func (w WorkConfig) SummarizerSessionRuns() int
- func (w WorkConfig) WorkDigestEnabled() bool
- type WorkerAuthConfig
- type WorkerConfig
- type WorkerEnrollmentConfig
- func (w WorkerEnrollmentConfig) EffectiveCollectSec() int
- func (w WorkerEnrollmentConfig) EffectiveDecideSec() int
- func (w WorkerEnrollmentConfig) EffectiveMaxPending() int
- func (w WorkerEnrollmentConfig) EffectivePerSourcePerMin() int
- func (w WorkerEnrollmentConfig) TrustedProxyPrefixes() []netip.Prefix
- type WorkerGuards
- type WorkerRoot
- type WorkerServerLink
- type WorkerTunnelConfig
- type XferConfig
Constants ¶
const ( DefaultAttachmentMaxBytes int64 = 10 << 20 DefaultAttachmentMaxPerMessage = 6 DefaultAttachmentHourlyPerCaller = 200 // DefaultAttachmentRetentionDays is storage.attachment_retention_days when unset. DefaultAttachmentRetentionDays = 14 )
Attachment defaults.
const ( // DecisionPointSubmit runs before a job is admitted. DecisionPointSubmit = "job.submit" // DecisionPointDeliver runs before a worktree job's branch is handed over. DecisionPointDeliver = "job.deliver" )
Decision points a hook can attach to.
const ( DecisionOnErrorDeny = "deny" DecisionOnErrorAllow = "allow" )
Decision hook outcomes when the hook itself fails (on_error).
const ( // DefaultDecisionHookTimeoutSec bounds one run when timeout_sec is unset: the // caller is waiting on the other side of the request. DefaultDecisionHookTimeoutSec = 5 // MaxDecisionHookTimeoutSec is the ceiling a hook may ask for. MaxDecisionHookTimeoutSec = 30 )
const ( // DefaultEventHookTimeoutSec bounds one hook run when timeout_sec is unset. DefaultEventHookTimeoutSec = 30 // MaxEventHookTimeoutSec is the ceiling a hook may ask for: the delivery sweep // waits for its hooks, so an unbounded one would stall the whole queue. MaxEventHookTimeoutSec = 300 // DefaultEventHookMaxAttempts is the attempt cap (first run included) when // max_attempts is unset. DefaultEventHookMaxAttempts = 3 // EventHookTargetPrefix marks an event_deliveries row aimed at a hook rather than // a webhook URL: the row's target is "hook:<name>". EventHookTargetPrefix = "hook:" // EventHookWildcard in a hook's events list subscribes it to every event type. EventHookWildcard = "*" )
Event hook defaults and limits (AUTO-04, design docs/design/2026-10-11-event-hooks-design.md).
const ( DefaultHoldTimeoutSec = 86400 DefaultHoldMaxTimeoutSec = 604800 )
Hold-for-approval timeouts (gofer-9b1b). A held job waits in awaiting_approval until a human approves or rejects it, or until its hold expires and the expiry sweep cancels it. A day is long enough to cover "I am away from the desk"; a week is the ceiling a caller may ask for.
const ( RunModeServer = "server" RunModeWorker = "worker" // RunModeClient marks a node that has NO local gofer config: `config.Load` skips // the discovery chain, and commands that edit or serve a local config refuse to // run (get whatever the server knows via the API instead). RunModeClient = "client" )
Run-mode values for EnvRunMode.
const ( DefaultMailAgentIdleMinutes = 120 DefaultMailAgentMaxLetters = 50 DefaultMailAgentMaxHours = 24 DefaultMailAgentsMaxResident = 6 )
Mail agent defaults.
const ( DefaultMailTickSec = 30 DefaultMailWakeIdleSec = 300 DefaultMailWakeIntervalSec = 600 DefaultMailDeliverBySec = 24 * 3600 DefaultMailClaimLeaseSec = 60 DefaultMailBroadcastMaxRecipients = 20 DefaultMailBroadcastRate = "5/10m" )
Mail defaults (seconds), and the broadcast numbers.
const ( MCPTypeStdio = "stdio" MCPTypeHTTP = "http" )
MCP server transport types.
const ( MCPFormatACP = "acp" // session/new mcpServers (acp-agent) MCPFormatClaudeJSON = "claude-json" // <result_dir>/mcp.json in Claude's mcpServers shape + mcp_args MCPFormatCodexConfig = "codex-config" // `-c mcp_servers.<name>.*` overrides )
MCP injection formats an agent declares with mcp_format.
const ( DefaultAddr = "0.0.0.0:8765" DefaultExchangeSubdir = "tmp" DefaultResultSubdir = "gofer" )
Default values used during config loading. See plan §6.1.
const ( // DefaultLeaderWakeDelaySec is the wake delay when wake_delay_sec is unset. DefaultLeaderWakeDelaySec = 30 // DefaultLeaderMaxRounds is the per-plan round budget when max_rounds_per_scope is unset. DefaultLeaderMaxRounds = 6 )
Leader-round defaults (MCP-05 阶段 B). The delay is the human's window to take over a round; the cap is small on purpose — a leader that cannot finish a plan in six rounds is not going to finish it in twelve, and every round costs money.
const ( DefaultMessengerCommand = "claude" DefaultMessengerTimeoutSec = 90 DefaultMessengerIdleSec = 600 DefaultMessengerMaxMessages = 50 // rotate the resident process after this many messages DefaultMessengerMaxAgeSec = 7200 // rotate the resident process after this long (2h) )
const ( DefaultAgentHealthWindowSec = 3600 DefaultAgentDegradedAfter = 3 DefaultAgentRecoverAfterOK = 1 )
Agent health defaults (SUP-01 P3): an hour is long enough to see "the provider is down right now" and short enough that yesterday's outage does not colour today.
const ( // DefaultCommentTriggerMinIntervalSec is the per-scope spacing between two // dispatching comments when server.comment_trigger.min_interval_sec is unset. DefaultCommentTriggerMinIntervalSec = 60 // DefaultCommentTriggerMaxPerScope is the per-scope lifetime budget of // dispatching comments when server.comment_trigger.max_per_scope is unset. DefaultCommentTriggerMaxPerScope = 10 )
Comment-trigger defaults (MCP-05 阶段 A, design §二.A.4): a comment may start work only so often per scope, because every @-mention spends money. 60s is one dispatching comment per minute and 10 is a job's lifetime budget — generous for a conversation, small enough that a stuck loop is noticed.
const ( // StopJobWaitAway is the default: a Stop blocks on the session's watched jobs // only while the person is away. StopJobWaitAway = "away" // StopJobWaitAlways keeps the pre-knob behaviour: any pending watched job blocks // the Stop until one of them finishes. StopJobWaitAlways = "always" // StopJobWaitNever releases every Stop immediately; the notices are caught up by // the next SessionStart / UserPromptSubmit. StopJobWaitNever = "never" )
Values of session.stop_job_wait (SessionConfig.StopJobWait).
const ( DefaultSessionRelayOnWaitSec = 3600 DefaultSessionRelayAutoWaitSec = 600 )
Default Stop-wait budgets the server hands to the hook (N1 §C).
const ( WebhookKindGeneric = "generic" WebhookKindDingTalk = "dingtalk" WebhookKindFeishu = "feishu" )
WebhookConfig is one E14 outbound webhook target (design §5.5). Events is the subscribed trigger set (omit => the default set job.terminal + interaction.created); SecretEnv names the env var holding the HMAC secret (SR403, never inlined); Projects restricts the webhook to those project keys (omit => all projects). Webhook kinds (OBS-07a): the outbound adapter a webhook speaks. The list lives here, next to the yaml field it validates, because internal/notify imports this package (the reverse would be an import cycle).
const ( // ApprovalOff auto-allows every permission request (the S0 behaviour, and the // default: upgrading gofer must not park every job on a human). ApprovalOff = "off" // ApprovalAsk auto-allows the auto_allow_kinds and asks a human for the rest. ApprovalAsk = "ask" // ApprovalStrict asks a human for every permission request. ApprovalStrict = "strict" // ApprovalAutoAllow is the AGENT-level spelling of "no tightening" // (agents.<key>.acp.permission_policy). It is deliberately distinct from // ApprovalOff at the agent level: an agent may never turn the gate OFF, only // decline to raise it. ApprovalAutoAllow = "auto_allow" )
Approval modes (ApprovalConfig.Mode, ACPConfig.PermissionPolicy).
const ( // ApprovalOnTimeoutReject answers a timed-out request with a reject option (or a // cancellation when the agent offers none) — the default: an unanswered request // must not become an approval. ApprovalOnTimeoutReject = "reject" // ApprovalOnTimeoutAllow answers a timed-out request with allow_once. ApprovalOnTimeoutAllow = "allow" )
Approval on-timeout outcomes (ApprovalConfig.OnTimeout).
const ( // OutputFormatText captures the agent's stdout verbatim. It is the default, // so an agent that does not ask for structured capture is never filtered. OutputFormatText = "text" // OutputFormatNDJSON declares the agent's stdout a JSON-Lines event stream to // be compacted at capture time (bd h-aii-rpky). See AgentConfig.NDJSONKeep. OutputFormatNDJSON = "ndjson" )
Agent stdout capture formats (AgentConfig.OutputFormat).
const ( // NDJSONEventsStderr writes the events to stderr.log — the default, and the // shape codex users expect: stdout is the answer, stderr is the process log. NDJSONEventsStderr = "stderr" // NDJSONEventsStdout keeps the phase-1 destination (events on stdout.log). NDJSONEventsStdout = "stdout" // NDJSONStdoutFinalText writes only the agent's final answer to stdout.log. NDJSONStdoutFinalText = "final_text" // NDJSONStdoutAssistantText writes every non-empty assistant message (narration // and final answer, blank-line separated) — the omp default since v0.47, because // a harness-injected trailing turn otherwise hides the real report behind a // one-line reply (bd h-aii-lvo9). NDJSONStdoutAssistantText = "assistant_text" // NDJSONStdoutEvents writes the compact event stream to stdout.log and skips // answer extraction: the pre-525u capture, byte for byte. NDJSONStdoutEvents = "events" )
Where the compacted event lines go (AgentConfig.NDJSONEventsTo), and what the stdout stream carries (AgentConfig.NDJSONStdout). The capture projects a structured agent stream onto the two logs (bd h-aii-525u): the process events belong on stderr, the agent's final answer on stdout.
const ( // BuiltinLocalRunner is the canonical key of the in-process runner. BuiltinLocalRunner = "local" // BuiltinLocalRunnerAlias is the CLI/public spelling of that same runner. BuiltinLocalRunnerAlias = "server" )
The built-in in-process runner needs no `runners:` declaration and has TWO accepted spellings on any INPUT surface:
- "local" — the canonical key: what the wire, /v1/runners, the jobs.runner column and the web console carry, and what a project's allowed_runners lists.
- "server" — the human-facing spelling the CLI advertises (`--runner`'s default: "server = server-local"), picked because on a WORKER host "local" means that worker's own runner.
They are one runner, so an input boundary that receives the alias must translate it (NormalizeRunnerName) rather than reject a caller who used the documented spelling; allowlist checks accept either spelling.
const ( DefaultContinueMaxChain = 3 MaxContinueMaxChain = 10 )
DefaultContinueMaxChain is the default limit of consecutive plan-item continuations of one session; MaxContinueMaxChain is the largest value a project may configure.
const ( DefaultPolicyRepushTimeoutSec = 60 DefaultPolicyRepushMaxAttempts = 3 )
const ( TimeoutLimitProject = "project" TimeoutLimitServer = "server" )
Sources of the job timeout ceiling (EffectiveMaxTimeout, job.timeout_limit_source).
const ( DefaultWorkSummarizerAgent = "claude" DefaultWorkSummarizeIdleMin = 15 DefaultWorkSummarizeIntervalM = 30 DefaultWorkSummarizeDaily = 50 DefaultWorkRequestTimeoutMin = 30 DefaultWorkNeedsMeThrottleMin = 30 // DefaultWorkSummarizerSessionRuns / Age are how long one summarizer session is // reused before it is replaced by a fresh one. DefaultWorkSummarizerSessionRuns = 20 DefaultWorkSummarizerSessionAge = 24 * time.Hour )
W2a work defaults.
const ( ScopeDisciplineAuto = "auto" ScopeDisciplineOn = "on" ScopeDisciplineOff = "off" )
Scope-discipline modes of ProjectConfig.ScopeDiscipline (gofer-3nxa.3).
const ( // TrackerPrimeRepo injects the tracker of the git repository the job's cwd // belongs to; the upward search stops at that repository's top. TrackerPrimeRepo = "repo" // TrackerPrimeNearest (the default) injects the nearest ancestor tracker, // whichever repository it sits in. TrackerPrimeNearest = "nearest" // TrackerPrimeOff injects no tracker-prime section at all. TrackerPrimeOff = "off" )
Tracker-prime modes of ProjectConfig.TrackerPrime (gofer-krzy).
const ( // DefaultWorktreeDir 是项目没配 worktree.dir 时的落点模板(相对仓库顶层)。 DefaultWorktreeDir = "tmp/gofer/wt/{job_id}" // DefaultWorktreeBranch 是项目没配 worktree.branch 时的分支模板,完整名 gofer/<job-id>。 DefaultWorktreeBranch = "gofer/{job_id}" )
Worktree 模板(WT-01 扩展,2026-10-21 design「一、worktree 的位置、分支名与依赖链接」)。
项目的 `worktree:` 段只描述「本项目的 --worktree job 落在哪、分支叫什么、从主 checkout 链接哪些目录过来」,默认值即历史行为(`tmp/gofer/wt/{job_id}` / `gofer/{job_id}`), 因此老配置完全不受影响。模板展开在提交侧完成(见 job.worktreeOptionsFor),执行机拿到 的是已解析好的路径与分支。
const ( // ImageInputPath: the agent opens an image the message NAMES by absolute path. ImageInputPath = "path" // ImageInputArg: the agent takes an image path as an argv flag instead (the agent's // image_args template, one expansion per image), so gofer appends it to the argv of // the job that carries the message rather than writing the path into the text. ImageInputArg = "arg" // ImageInputNone: the agent cannot take an image the console hands it at all. ImageInputNone = "none" )
ImageInput values (AgentConfig.ImageInput).
const ( DefaultStewardIdleEndMin = 30 DefaultStewardReviewMaxItems = 20 DefaultStewardEventThrottle = 30 DefaultStewardReviewLeadMin = 10 StewardNotesMaxBytes = 8 << 10 StewardPrimeMaxBytes = 24 << 10 StewardEventDraftsThreshold = 5 )
W2b steward defaults.
const ( ToolsMaxCount = 50 ToolNameMaxLen = 64 ToolDescMaxRunes = 200 ToolsListMaxBytes = 4 << 10 )
Limits on a tools declaration. They keep the rendered prompt section small: a runner's tool list is prepended to every agent job it runs.
const ( // DefaultUpdateInterval is the periodic check interval when interval is unset. DefaultUpdateInterval = 2 * time.Hour // MinUpdateInterval keeps the timer from hammering the source. MinUpdateInterval = 10 * time.Minute // DefaultUpdateRepo is the GitHub repository checked when no mirror is set. DefaultUpdateRepo = "inhere/gofer" )
const ( DefaultEnrollDecideSec = 120 DefaultEnrollCollectSec = 60 DefaultEnrollPerSourceMin = 3 DefaultEnrollMaxPending = 20 MinEnrollWindowSec = 30 MaxEnrollWindowSec = 600 MaxEnrollPerSource = 60 MaxEnrollPending = 200 )
Defaults and bounds of server.worker_enrollment (design 「默认数值」).
const ( DefaultWorkspaceDirName = ".gofer" DefaultWorkspaceSubdir = "workspace" )
DefaultWorkspaceDirName / DefaultWorkspaceSubdir compose the workspace path under the user's home: ~/.gofer/workspace. Short and identical on every platform (the design settled on ~/.gofer rather than ~/.local/gofer, which is not a Windows convention); os.UserHomeDir resolves %USERPROFILE% on Windows.
const BuiltinExecAgentKey = "exec"
BuiltinExecAgentKey is the always-available exec agent. It needs no declaration, so the default project's allowed_agents never lists it.
const DBFileName = "gofer.db"
DBFileName is the SQLite metadata database file name used when db_path is resolved from storage.root or the config dir (see ResolveDBPath, design §11).
const DefaultApprovalTimeoutSec = 1800
DefaultApprovalTimeoutSec is how long a pending approval waits for an answer when the project does not say (30min — long enough for a human to notice the card, short enough that a forgotten job does not hold the agent forever).
const DefaultConfigDirName = "gofer"
DefaultConfigDirName is the user-level config dir under the OS config home (~/.config/<name>).
const DefaultDirLockMaxWaitSec = 3600
DefaultDirLockMaxWaitSec is how long a job may queue for the same-directory lock when nothing (request, agent, server) says otherwise: one hour, the same order as the default job timeout. It exists so a holder that wedged can never park its queue forever (F12: jobs sat in `waiting_dir` behind an unkillable ACP job).
const DefaultJobRecoverWindowSec = 120
DefaultJobRecoverWindowSec is the RECOV-01 window applied when server.job_recover_window_sec is UNSET: how long a worker's in-flight jobs are held in `recovering` while the same worker process reconnects (e.g. a WSL / Docker / VPN blip). 120s covers a reconnect with exponential backoff plus a few retries; an explicit 0 disables recovery (Config.JobRecoverWindow returns 0).
const DefaultMaxAttempts = 6
DefaultMaxAttempts is the delivery retry cap used when NotificationConfig .MaxAttempts is unset (<= 0): the backoff table has 5 steps, so 6 attempts (initial + 5 retries) exhausts it before the delivery is marked failed.
const DefaultMaxJobTimeoutSec = 3600
DefaultMaxJobTimeoutSec is the job-timeout ceiling used when NEITHER server.max_job_timeout_sec NOR the project's max_timeout_sec is set. It is the value the clamp was hard-coded to before it became configurable (bd h-aii-s9ck), so an existing config keeps its exact previous behaviour.
const DefaultMaxTextRunes = 3000
const DefaultProjectKey = "default"
DefaultProjectKey is the key of the default-workspace project: the one project every gofer server can count on (`gofer init` writes it, and a server whose config does not declare it gets the built-in one injected, InjectDefaultProject).
const DefaultPtyTranscriptMaxBytes = 4 << 20
DefaultPtyTranscriptMaxBytes is the transcript tail cap when pty.transcript_max_bytes is unset (PTY-01 decision 3: the transcript is on by default, so the cap is the only knob).
const DefaultRulesMaxBytes = 16384
DefaultRulesMaxBytes is the shipped cap on the TOTAL rule text injected into one job (JOB-06① 决策 3): 16KiB. Rules are meant to be short and hard — a submit whose rules exceed the cap is rejected naming the largest ones, and long reference material belongs in a skill (which the agent reads only if it needs it).
const DefaultSessionAutoRelayIdleSec = 300
DefaultSessionAutoRelayIdleSec is the idle-detection auto-arm threshold used when session.auto_relay_idle_sec is unset: 5 minutes away from the keyboard is long enough to mean "not coming back in a moment".
const DefaultSessionAutoRelayTurnSec = 900
DefaultSessionAutoRelayTurnSec is the last-human-input fallback threshold used when session.auto_relay_turn_sec is unset: 15 minutes of silence from the human in this session.
const DefaultSessionOfflineAfterSec = 1800
DefaultSessionOfflineAfterSec is how long a session may be silent before it is marked offline when session.offline_after_sec is unset (30 minutes).
const DefaultSessionProgressIntervalSec = 30
DefaultSessionProgressIntervalSec is the minimum interval between progress heartbeats emitted by a PostToolUse hook.
const DefaultSessionReplyDelaySec = 120
const DefaultSessionSupervisingWindowSec = 7200
DefaultSessionSupervisingWindowSec is how far back the supervision gate looks for the caller's live jobs when session.supervising_window_sec is unset: two hours is longer than any job a human watches in one sitting, and short enough that a forgotten job does not keep their sessions unarmed forever.
const DefaultSessionTakeoverAliveSec = 120
DefaultSessionTakeoverAliveSec is the takeover liveness window when session.takeover_alive_sec is unset.
const DefaultSessionTakeoverInputDelayMs = 1500
DefaultSessionTakeoverInputDelayMs is path B's priming delay when session.takeover_input_delay_ms is unset: a terminal that has stopped painting for 1.5s has drawn its prompt, and typing earlier would race the TUI's own startup output.
const DefaultStallTimeoutSec = 900
DefaultStallTimeoutSec is the AUTO-05 output-stall window an unset configuration gets: 15 minutes of total silence from a running agent job means the provider stream hung (or the CLI is waiting for an interaction nobody will ever send), and waiting for the job's own deadline (default 1h) wastes the whole slot.
const DefaultSubmitAgents = "exec"
DefaultSubmitAgents is what an unset submit_agents yields: the exec agent, which runs the argv the submitter passes and nothing else. A job that may start work should be able to start a COMMAND; letting it start an arbitrary agent (with that agent's tools and prompts) is a much larger grant and must be written down.
The literal is spelled here rather than via agent.ExecAgentKey because internal/agent imports this package, not the other way round (G022).
const DefaultVerifyTimeoutSec = 600
DefaultVerifyTimeoutSec bounds a job's verify step when neither the request nor the project sets one (SUP-01 B). 10 minutes: a full test suite of a medium project fits, while a hung suite still ends the job well before an agent-sized budget would.
const DefaultWakeupTTLSec = 7 * 24 * 3600
DefaultWakeupTTLSec is the 7-day wakeup lifetime used when `wakeup.ttl_sec` is unset (design §五 决策 6).
const DefaultWorkDigestTime = "09:00"
DefaultWorkDigestTime is the daily digest time when work.digest_time is unset.
const DefaultWorkStallAfter = 4 * time.Hour
DefaultWorkStallAfter is the stall threshold when work.stall_after is unset.
const DefaultWorkerXferTimeoutSec = 600
DefaultWorkerXferTimeoutSec is a worker's default single-transfer deadline (10 minutes). A transfer is not resumable, so a stalled one must be FAILED at its deadline rather than held open.
const EnvConfigDir = "GOFER_CONFIG_DIR"
EnvConfigDir overrides the user-level config directory. When set, both the default config file (<dir>/config.yaml) and the global dotenv (<dir>/.env) resolve under it instead of ~/.config/gofer.
const EnvConfigPath = "GOFER_CONFIG"
EnvConfigPath is the env var consulted in the config lookup chain (§6.1).
const EnvFileName = ".env"
EnvFileName is the dotenv file name loaded from the config dir and the cwd.
const EnvJobToken = "GOFER_JOB_TOKEN"
EnvJobToken is the variable a job's own credential arrives in (SEC-01). Its presence means the process IS a job rather than the operator — the dotenv loader keys off that (a job must not pick the server's *_TOKEN keys out of the server's .env), and the CLI/MCP default their bearer token to it.
const EnvRunMode = "GOFER_RUN_MODE"
EnvRunMode declares a node's ROLE so role-default commands pick the matching LOCAL config file: "server" (default) → config.yaml; "worker" → worker.yaml; "client" → NO local config at all (a pure client node holds only the connection env in <config-dir>/.env and talks to a remote server). E38②/C1. mcp is intentionally NOT a value here — standalone mcp still loads config.yaml (it executes jobs in-process), and client-mode mcp's config is governed by its --server flag (E28), not by this role.
const EnvWorkspace = "GOFER_WORKSPACE"
EnvWorkspace overrides the default workspace directory (F-g). It is the env-var form of `gofer init --workspace`; an explicit flag still wins.
const ExtendsBuiltin = "builtin"
ExtendsBuiltin as an agent's `extends` starts from the built-in template of the same name and overrides just the keys written (gofer-arsj). `builtin:<template>` names the template explicitly; any other value names another agent declared in the same config, which is resolved first (chains are allowed, cycles are not).
const LeaderPlanScope = "plan"
LeaderPlanScope is the only scope the leader round implements in this phase.
const MCPReservedName = "gofer"
MCPReservedName is the entry gofer itself injects for the steward and leader jobs.
const MaxCallerNameLen = 64
MaxCallerNameLen caps a caller display name, in characters.
const MinSecretValueLen = 4
MinSecretValueLen is the shortest value a secret may have: output masking replaces the literal value, and a shorter one would mangle ordinary output.
const ProjectOverlayName = ".gofer.project.yaml"
ProjectOverlayName is the per-project thin config file (E29/D1). It lives in the project dir and carries ONLY preference fields — server/storage/host_path/ container_path 与准入字段 (allowed_agents/allowed_runners/allow_exec) 一律不在此 (D2: 准入真源在全局 config, overlay 不得放权).
const WorkerConfigFileName = "worker.yaml"
WorkerConfigFileName is the conventional worker config filename, alongside the global config.yaml / .env in the config dir.
Variables ¶
var ( // DefaultApprovalAutoAllowKinds are read-only, side-effect-free tool calls. DefaultApprovalAutoAllowKinds = []string{ acp.ToolKindRead, acp.ToolKindSearch, acp.ToolKindThink, acp.ToolKindFetch, } // DefaultApprovalAskKinds are the kinds that mutate the workspace or run code. DefaultApprovalAskKinds = []string{ acp.ToolKindEdit, acp.ToolKindDelete, acp.ToolKindMove, acp.ToolKindExecute, acp.ToolKindOther, acp.ToolKindSwitchMode, } )
Approval tool kinds approved/asked by default. Together they cover the whole ACP vocabulary; a kind in NEITHER list (a future protocol addition) asks.
var ( // ErrWorkerAlreadyRegistered is returned by RegisterWorkerInto when server.workers already has the id. ErrWorkerAlreadyRegistered = errors.New("worker already registered") // ErrWorkerNotFound is returned by RemoveWorkerFrom when server.workers has no such id. ErrWorkerNotFound = errors.New("worker not found") // ErrWorkerFingerprintMismatch is returned by RemoveWorkerFrom when the expected token fingerprint differs. ErrWorkerFingerprintMismatch = errors.New("worker token fingerprint mismatch") )
var BuiltinAgentTemplate func(name string) (AgentConfig, bool)
BuiltinAgentTemplate looks up the built-in agent template named name (a deep copy). The agent package registers it at init — templates live there, and config cannot import agent (G022). Nil means no templates are linked in, so `extends` fails.
var BuiltinAgentTemplateNames func() []string
BuiltinAgentTemplateNames lists the template names for error messages (registered with BuiltinAgentTemplate).
var CurrentDirConfigNames = []string{".gofer.local.yaml", ".gofer.yaml"}
CurrentDirConfigNames are the per-directory config file names, in priority order (§6.1): a local override (.gofer.local.yaml, gitignored) takes precedence over the shared .gofer.yaml when both exist in the cwd.
var DefaultSplitKeys = []string{"agents", "projects"}
DefaultSplitKeys are the sections `gofer config split` moves out by default: the two that usually make up most of a server config.
var DeliveryModes = []string{"none", "merge", "push", "pr"}
DeliveryModes lists the accepted modes.
var ErrBuiltinProject = errors.New("内置项目不能删除(可在配置里显式声明同名项目来覆盖)")
ErrBuiltinProject is returned when a write would delete a built-in project.
var InputCfgFile string
InputCfgFile file path, from CLI bind options
var TranscriptDialects = []string{"claude", "codex", "omp", "generic"}
TranscriptDialects are the values AgentConfig.TranscriptDialect accepts (they mirror the dialect constants of internal/work/transcript).
Functions ¶
func ApplyAgentExtends ¶ added in v0.142.0
func ApplyAgentExtends(agents map[string]AgentConfig, raw []byte) error
ApplyAgentExtends resolves every agent declared with `extends`. The base is a built-in template (`builtin` = the template of the same name, `builtin:<name>` = the named one) or another declared agent, itself resolved first. Each key WRITTEN in the declaration replaces that whole field (lists and maps are replaced, not merged). Whether a key was written is read from raw — the yaml document holding the agents mapping — never from zero values, so `interactive: false` or `interactive_args: []` really override the base. Used for config.yaml (via Load) and worker.yaml.
func ApplyDefaults ¶
func ApplyDefaults(cfg *Config)
ApplyDefaults fills storage defaults and initializes nil maps. It is exported so the ws-worker command can default a Config it builds from a WorkerConfig (so the worker's local store/registries behave like a serve process).
func ApplyProjectOverlays ¶
ApplyProjectOverlays merges each project's .gofer.project.yaml into cfg.Projects IN PLACE (D6). Read dir = cfg.ExecPath(p) (D10, supersedes the original D4 ContainerPath||HostPath): the overlay is read from the SAME execution-root the rest of the gofer process uses (host_path by default, or container_path under server.path_view=container), so overlay lookup can never diverge from the execution chain. A missing file is skipped silently; a decode error or forbidden key appends a warning but never aborts (one bad project overlay must not take down serve). Returns the warnings for the caller to log.
func BuiltinDeliver ¶
BuiltinDeliver returns the built-in delivery argv, whether the text travels on stdin, and the offline marker for an agent name; nil command when that name has none. Copies — a caller must never be able to mutate the table.
func BuiltinMCP ¶ added in v0.144.0
BuiltinMCP returns the built-in mcp_format / mcp_args for an agent name ("" when none).
func BuiltinModelArgs ¶
BuiltinModelArgs returns the built-in model_args for an agent name, or nil. A copy.
func BuiltinReadOnlyArgs ¶
BuiltinReadOnlyArgs returns the built-in read-only argv for an agent name, or nil when that name has none. The caller decides which names to try: the agent's config key first, then the base name of its command (agent.applyReadOnlyDefaults), so an operator-renamed agent still inherits its CLI's sandbox flags. The result is a copy — a caller must never be able to mutate the table.
func CheckWorkerID ¶
CheckWorkerID rejects a worker id that spells a reserved runner name. Worker ids double as runner keys, so letting one be "server" or "local" would make a remote machine indistinguishable from this server's own runner.
func ConfigDir ¶
ConfigDir returns the effective user-level config directory. When the env var GOFER_CONFIG_DIR is set it wins (absolute); otherwise the default is ~/.config/gofer. It holds both config.yaml and the global .env.
func DeleteTunnel ¶
DeleteTunnel removes a preset, reporting a name that was never saved.
func EditableAgentFields ¶
func EditableAgentFields() []string
EditableAgentFields returns the agent field names PUT accepts, sorted. It is the whitelist the write endpoint enforces and the field list the console builds its form from — one source for both, so a form can never offer an input the server refuses.
func EffectiveSubmitAgents ¶
EffectiveSubmitAgents returns the agents this definition permits, defaulting to DefaultSubmitAgents for an empty list. A fresh slice every call — never the caller's to mutate.
func EnsureWorkspaceDir ¶
EnsureWorkspaceDir makes sure the default workspace directory (WorkspaceDir("")) exists. It exists for processes that were upgraded in place: `gofer init` creates the directory, a long-installed serve/worker never did, so the Runners page flagged the missing directory forever. It returns the resolved path and whether this call created it; an existing directory is left untouched. Callers treat an error as a warning only — a read-only home must not stop the process.
func EventHookName ¶ added in v0.140.0
EventHookName extracts the hook name from a delivery target; ok=false for a webhook target.
func InjectDefaultProject ¶
func InjectDefaultProject(cfg *Config)
InjectDefaultProject materializes the built-in `default` project when the operator did not declare one. Like agent.Resolve it runs on every config snapshot (build and reload), BEFORE the snapshot is published, and is idempotent: a previously injected project is dropped first and re-derived, so an agent installed since is picked up.
The project points at the server's default workspace (WorkspaceDir(""), so GOFER_WORKSPACE applies). It is a server-side path, resolved by this process (G002): host_path is always set, container_path additionally under server.path_view=container so ExecPath returns it. The directory is created by the startup workspace ensure. An operator-declared `default` wins whole and is never marked.
func IsBuiltinLocalRunnerName ¶
IsBuiltinLocalRunnerName reports whether name spells the built-in in-process runner (either the canonical key or the CLI alias). The comparison ignores surrounding whitespace and letter case: both spellings are reserved names (see ReservedRunnerName), so "Server" can never be somebody else's runner.
func IsClientRunMode ¶
func IsClientRunMode() bool
IsClientRunMode reports whether this process is a pure client node (GOFER_RUN_MODE=client). It is the single predicate every client-mode branch reads, so the role string is never compared by hand at the call sites.
func IsLocalRunnerName ¶
IsLocalRunnerName reports whether name — a label as stored or received, in either spelling — names the built-in in-process runner. Use it instead of comparing against the literals "local" / "server": a comparison done on a raw label silently misses the other spelling.
func IsSecretFieldName ¶
IsSecretFieldName reports whether a request field name denotes a secret LITERAL and must be refused: it carries one of SecretFields' markers and does NOT end in `_env`. The `_env` suffix is exactly what separates the two halves of the rule in design §一.2 — `token_env` names an environment variable and carries no value, so it is never treated as a secret (whether it is editable is a separate, per-field question).
func LoadDotenv ¶
LoadDotenv loads dotenv files BEFORE config resolution so env-driven settings (GOFER_CONFIG, GOFER_TOKEN, the per-runner *_token envs, ...) can come from a file during local dev. GOFER_CONFIG_DIR is read directly from the OS env (it selects WHERE the global .env lives, so it cannot come from one).
Files load in this order, with later files overriding earlier ones:
- <config-dir>/.env — global (config-dir = $GOFER_CONFIG_DIR or ~/.config/gofer)
- ./.env — current working dir, project-local; wins over global
Precedence: an exported OS env var always wins over any .env file. goutil's Dotenv unconditionally os.Setenv's parsed keys (upper-cased), so we snapshot the OS env up front and, for every key the dotenv touched that already existed in the OS env, restore the original value. Missing files are skipped. Returns the list of files actually loaded (for optional --verbose logging).
Inside a job (the process carries EnvJobToken) every *_TOKEN key in the files is skipped: the .env a job finds is the SERVER's — the CLI locates it through GOFER_CONFIG_DIR, which the job used to inherit — and its credential keys would hand the job the operator's own token. That is leak 1 of the v0.60 field trial: the host's 0.53.1 `gofer` (which knows nothing about job credentials) loaded <config-dir>/.env and called the API as the user. The job's identity comes from its environment; the rest of the file still loads, it is the deployment's settings file.
func MCPEnvRefs ¶ added in v0.144.0
MCPEnvRefs returns the secret_env keys a string references as {{env:NAME}}.
func MCPInjectedEnvName ¶ added in v0.144.0
MCPInjectedEnvName is the variable a secret is handed to the agent process under: GOFER_MCP_<SERVER>_<KEY>, upper-cased, every other character turned into '_'.
func MissingToolBins ¶ added in v0.140.0
MissingToolBins returns the declared tools whose executable this machine cannot find (exec.LookPath), as "name (bin)" strings. It backs the validate / doctor WARNING — a declaration may describe another environment, so a miss never fails.
func NewWorkerToken ¶ added in v0.169.0
NewWorkerToken generates a random worker token.
func NormalizeRunnerName ¶
NormalizeRunnerName maps a caller-supplied runner key onto the canonical key for that runner: the alias "server" becomes "local" (case-insensitively, since both names are reserved). Every other value (a configured runner key, or the empty string) is trimmed and returned unchanged — an empty runner stays empty so "runner is required" is still reported for it.
This is THE normalizer every input boundary and stored-label comparison uses (G043). There is no declare-wins branch: a config cannot declare a non-local runner named "server", so the alias always means the built-in.
func ParseBroadcastRate ¶ added in v0.184.0
ParseBroadcastRate parses "<count>/<window>" ("5/10m"): the broadcast ceiling of one caller. A malformed value is a load error, never silently defaulted — a limit nobody can read is a limit nobody can rely on.
func ProjectKeyFromDir ¶
ProjectKeyFromDir reads dir/.gofer.project.yaml and returns its `key:` self- identifier (xu64.15), trimmed. It is the primary `--project auto` resolution source — client (thin MCP, no cfg) and standalone both use it, so it takes no Config. A missing file → ("", nil) (unregistered dir is not an error); a decode error → ("", err); a file without `key:` → ("", nil).
func RegisterWorkerInto ¶ added in v0.169.0
RegisterWorkerInto registers worker id in cfg: server.workers, runners and the allowed_runners of each listed project. cfg is only mutated on success.
func RejectRemovedKeys ¶
RejectRemovedKeys fails the load when an operator yaml still carries a config key that has been REMOVED (G032 / v0.48): server.session_auto_relay_idle_sec (R2 alias of session.auto_relay_idle_sec) and projects.<key>.interactive_allowed_agents (replaced by allow_interactive, AGT-02 0.3). Both used to be read as one-shot compat aliases; the deadline arrived, and the typed decode is non-strict (goccy ignores unknown keys so an operator's stray key never bricks a running server), so a silently-ignored removed key would be exactly the unmarked compatibility layer G032 forbids — say which key to rewrite instead.
The probe is a second decode of the raw document into plain maps: values are never interpreted, only the presence of the key is (any value, including "" / [] / null). A document the typed decode already rejected (or one that is not a mapping) is a no-op here — the caller has the real error. Callers: config.Load (config.yaml) and the worker's own worker.yaml decode, so both yaml surfaces for projects agree.
func RemoveWorkerFrom ¶ added in v0.169.0
RemoveWorkerFrom removes worker id from server.workers, runners and project allowed_runners. A non-empty expectFingerprint must equal the fingerprint of the configured token, otherwise cfg is untouched and removed is false.
func RenderYAML ¶
RenderYAML renders v the way the config writer writes it, for a surface that shows a candidate BEFORE it is saved (the console's dry-run preview, WEB-04③ V1.1). It uses the same encoder as Save, so a preview and the file it previews cannot disagree about formatting.
It renders only what it is given: callers must pass a block whose secret-bearing fields have been masked (SR403) — config.Save's runtime source filtering lives in withoutRuntimeValues and does not apply here.
func ReplaceMCPEnvRefs ¶ added in v0.144.0
ReplaceMCPEnvRefs rewrites every {{env:NAME}} in s with repl(NAME).
func ReservedNameError ¶
ReservedNameError is the user-facing reason a reserved name was refused. what describes the thing being named ("runner", "worker id", ...).
func ReservedRunnerName ¶
ReservedRunnerName is IsBuiltinLocalRunnerName under the name that states the rule: "server" and "local" belong to the built-in runner, so no custom runner and no worker id may use them. The only legal declaration is the built-in itself: `runners: {local: {type: local}}` (or `server: {type: local}`).
func Resolve ¶
Resolve returns the absolute path of the config file to use, or "" when none of the candidate locations exist. An explicit path that does not exist is still returned (callers like `project add` may create it).
func ResolveLocalPath ¶
ResolveLocalPath expands the single supported local path variable. A path without a variable is returned unchanged, including its relative semantics.
func ResolveLocalPathAt ¶
ResolveLocalPathAt resolves a frozen service spec against its registered config directory without changing process-wide environment variables.
func RunMode ¶
func RunMode() string
RunMode returns the node role from GOFER_RUN_MODE: RunModeWorker / RunModeClient when the env is set to that value (case-insensitive), else RunModeServer (the default for any empty/other value). Role-default commands (e.g. `project list`) use it to read the matching local config (config.yaml vs worker.yaml vs none).
func RuntimeFilePath ¶
RuntimeFilePath returns the path of a runtime file <config-dir>/<sub>/<name> (e.g. RuntimeFilePath("run", "serve.pid") → <config-dir>/run/serve.pid). It is where daemon mode (-d) keeps pidfiles and redirected logs. When ConfigDir is unresolvable it degrades to ./<sub>/<name> so the process still has a usable path. Callers MkdirAll the parent dir before writing.
func Save ¶
Save writes cfg back to path as YAML.
Critical (§12): when the target file already exists, the human's own text must survive the rewrite. Two rules, both keyed on TOP-LEVEL keys:
- A key this tool does NOT manage (e.g. `custom_top: 123`) is carried over from the original file verbatim, text and comments included.
- A MANAGED key is re-rendered from the struct — but only if its canonical serialization actually changed (surgical save, bd h-aii-kd57). An untouched block therefore keeps the operator's comments, key order and (AGT-02) `interactive_args: []` exactly as written, while an edit still re-emits the whole block from the struct (comments INSIDE an edited block are lost).
If the file does not exist, parent directories are created and a clean config is written.
func SaveTunnels ¶
SaveTunnels writes the preset file 0600: a preset names internal hosts and the worker that can reach them.
func SecretFields ¶
func SecretFields() []string
SecretFields returns those markers. The handler refuses a body field that matches one and points at the `*_env` alternative; the console uses the same list to label a secret field "由 env 提供".
func SectionFileOf ¶ added in v0.142.0
SectionFileOf reads the config at mainPath (with its includes, without defaults or validation) and returns the file holding top-level section key — the main file when the section is not split out. It is what `config edit --key` opens.
func SectionPolicies ¶
func SectionPolicies(section string) map[string]FieldPolicy
SectionPolicies returns one section's field policies keyed by the FIELD NAME a write body carries — `server` → "addr", "max_job_timeout_sec", …; `agents` → every agent field. That is exactly the vocabulary PUT accepts and the console builds its form from, so the view and the endpoint cannot offer different fields. An unknown section returns an empty map.
func TimeoutLimitKey ¶ added in v0.177.0
TimeoutLimitKey names the config key behind a timeout limit source for a project.
func ToolLine ¶ added in v0.140.0
ToolLine renders one tool as the prompt list line, e.g.
- `ffmpeg` — transcoder
- `plc-sim`(`D:\tools\plcsim.exe`)— simulator
It is the single renderer of a line, so the size check in ValidateTools and the prompt the job carries measure the same text.
func UpsertTunnel ¶
func UpsertTunnel(name string, profile TunnelProfile, force bool) error
UpsertTunnel stores a preset, refusing to replace an existing one unless force. The stored rule list is the SPLIT one (design §三): a preset is a set of rules, and the comma form is only a way to write it.
func UserConfigPath ¶
UserConfigPath returns the user-level default config path (<config-dir>/config.yaml; config-dir defaults to ~/.config/gofer).
func UserTunnelsPath ¶
UserTunnelsPath returns the user-level tunnel presets path.
DEPRECATED(v0.60.2): remove in v0.63 — see LoadTunnels. The file remains the offline fallback and the source of `gofer tun presets push`.
func UserWorkerConfigPath ¶
UserWorkerConfigPath returns the user-level default worker config path (<config-dir>/worker.yaml; config-dir defaults to ~/.config/gofer). It is the fallback `gofer worker` uses when no --worker-config is given (mirrors how the server config falls back to <config-dir>/config.yaml).
func ValidDeliveryMode ¶ added in v0.146.0
ValidDeliveryMode reports whether m is a mode ("" = unset).
func ValidInjectProcessName ¶
ValidInjectProcessName reports whether n is a bare process name: non-empty, no path separator, no whitespace, and no ".exe"-style extension (the matcher strips the extension from the live process name, so a configured one could never match).
func ValidMCPFormat ¶ added in v0.144.0
ValidMCPFormat reports whether f is a known mcp_format ("" = none).
func ValidWebhookKind ¶
ValidWebhookKind reports whether k names a supported adapter ("" = generic).
func Validate ¶
Validate runs the same structural checks config.Load applies to a freshly decoded file. It is exported for the config write API (WEB-04③ V1.1 R3), which builds a CANDIDATE config in memory and must hold it to exactly the bar a written file is held to: anything weaker would let the API persist a config the next Reload refuses — a process that cannot come back from its own edit.
The candidate must already be defaulted (it is a Clone of the live config, which went through Load → ApplyDefaults); Validate itself never mutates cfg.
func ValidateTools ¶ added in v0.140.0
ValidateTools checks a tools declaration: name required / unique / charset / length, desc length, count, and the total size of the rendered list. An empty list is valid (the runner declares nothing). Errors name the yaml key (`tools`), which is the same in config.yaml and worker.yaml.
func ValidateTunnelProfile ¶
func ValidateTunnelProfile(name string, p TunnelProfile) error
ValidateTunnelProfile rejects a preset that could not be run. Validation lives here rather than in the CLI so every caller gets it and a bad preset can never reach the file.
The rule list may arrive comma-joined (TUN-04): validation sees the SPLIT list, so a profile is judged by what it will actually run. A malformed rule is reported with its position and text (`spec #2 "not-a-spec"`), not as a bare "invalid spec".
func ValidateWorkerTunnel ¶
func ValidateWorkerTunnel(w WorkerConfig) error
ValidateWorkerTunnel validates worker tunnel allowlist entries.
func WorkerTokenFingerprint ¶ added in v0.169.0
WorkerTokenFingerprint returns the hex SHA-256 of a worker token.
func WorkspaceDir ¶
WorkspaceDir resolves the default workspace directory: an explicit path (the --workspace flag) wins, then GOFER_WORKSPACE, then ~/.gofer/workspace. The path is returned absolute but is NOT created — callers that own the directory (the init commands) decide whether to mkdir.
func WorktreeNameValid ¶ added in v0.180.0
WorktreeNameValid 报告一个 `--worktree-name` 是否能安全地拼进路径与分支名: 只允许 [A-Za-z0-9._-],且不能是 "." / ".."。空名合法(表示沿用 job id)。
func WriteReloadResult ¶
func WriteReloadResult(path string, result ReloadResult) error
WriteReloadResult atomically publishes the latest reload receipt. The caller chooses the component-specific run path; readers can therefore wait without scraping transient stdout/stderr.
Types ¶
type ACPConfig ¶
type ACPConfig struct {
// Modes maps a gofer-level mode to the agent's own mode id, e.g.
// `read_only: "ask"`. It is PARSED in S0 and driven (session/set_mode) in S2.
Modes map[string]string `yaml:"modes,omitempty"`
// PermissionPolicy selects how session/request_permission is answered.
// Unset/`auto_allow` (S0) approves automatically, preferring an allow_once
// option; `ask`/`strict` belong to the S1 approval gate, and the runner refuses
// them rather than silently auto-approving.
PermissionPolicy string `yaml:"permission_policy,omitempty"`
// LoadSession declares whether a resume may try session/load on this agent.
// nil/true = try (the protocol negotiates the real capability at initialize and a
// refusal fails the job); explicit false = "don't even try": `job resume` and the
// automatic continuation refuse the source up front (ErrResumeUnsupported) instead
// of submitting a job the agent cannot serve.
LoadSession *bool `yaml:"load_session,omitempty"`
// MCPServers are advertised to the agent in session/new (stdio transport). S0
// passes them through verbatim; empty means the agent gets none.
MCPServers []ACPMCPServerConfig `yaml:"mcp_servers,omitempty"`
// LogThoughts keeps the agent's thinking (agent_thought_chunk) in the job's logs:
// the runner coalesces a thought stream into ONE compact line on stderr plus ONE
// acp.jsonl line (bd h-aii-7kja ②). unset/true = keep them, explicit false = drop
// them entirely, for an operator whose logs are dominated by the agent thinking
// out loud.
LogThoughts *bool `yaml:"log_thoughts,omitempty"`
// ClaudeSettingsEnv lets the executing side read claude's USER SETTINGS FILE and
// start the ACP process with the `env` block it declares (F14, 2026-09-25). It
// exists because claude's key and relay URL live in `~/.claude/settings.json` for
// the CLI (which reads that file itself) but NOT in gofer's environment, so an
// adapter that resolves credentials before the session (claude-code-acp, via the
// Claude Agent SDK) answers "Authentication required" — the key would otherwise
// have to be maintained twice.
//
// true only (the built-in claude-acp template turns it on; unset/false = off):
// the file is $CLAUDE_CONFIG_DIR/settings.json if that variable is set, else
// <home>/.claude/settings.json; a key the process environment or the job's own env
// already defines is NEVER overridden (an explicit setting wins), a key SEC-01
// denies is dropped, and a missing/unreadable/malformed file is a warning, not a
// failure. Values stay in the child's environment: they never reach request_json,
// the rendered command, an event or a log (only the KEY names are logged).
ClaudeSettingsEnv *bool `yaml:"claude_settings_env,omitempty"`
}
ACPConfig is the acp-agent's protocol-level configuration (docs/design/2026-09-17-acp-agent-and-approval-gate-design.md §一.1).
func (*ACPConfig) AllowsLoadSession ¶
AllowsLoadSession reports whether a resume may try session/load on this agent: unset means yes (the protocol negotiates it), an explicit false means "don't try". A nil ACPConfig has no acp-agent settings at all and therefore allows the attempt.
func (*ACPConfig) InheritsClaudeSettingsEnv ¶
InheritsClaudeSettingsEnv reports whether an acp-agent may start with the `env` block of claude's user settings file layered in (F14): explicit true only — a nil ACPConfig and an unset field both mean "no". Unlike LogsThoughts/AllowsLoadSession the default here is OFF for every agent except the built-in claude-acp template, which sets the field explicitly.
func (*ACPConfig) LogsThoughts ¶
LogsThoughts reports whether this agent's thinking is kept in the job's logs: unset means yes (the coalesced line is small), an explicit false means never.
type ACPMCPServerConfig ¶
type ACPMCPServerConfig struct {
Name string `yaml:"name"`
Command string `yaml:"command"`
Args []string `yaml:"args,omitempty"`
Env map[string]string `yaml:"env,omitempty"`
}
ACPMCPServerConfig is one MCP server handed to an acp-agent at session/new.
type AgentBudgetMap ¶ added in v0.175.0
type AgentBudgetMap struct {
TokensArgs []string `yaml:"tokens_args,omitempty"`
CostArgs []string `yaml:"cost_args,omitempty"`
TokensEnv string `yaml:"tokens_env,omitempty"`
CostEnv string `yaml:"cost_env,omitempty"`
}
AgentBudgetMap is how an agent takes the soft budget of a job (AgentConfig.AgentBudget). Each dimension is declared by an argv fragment (carrying the {{budget_tokens}} / {{budget_cost_usd}} placeholder) and/or the name of an environment variable the value is exported as. A cli-agent uses the argv fragment when present and the variable otherwise; an acp-agent has no per-job argv slot of its own, so it prefers the variable (its launch argv still takes the fragment when no variable is declared). A dimension with neither is not supported by the agent.
func (*AgentBudgetMap) SupportsCost ¶ added in v0.175.0
func (m *AgentBudgetMap) SupportsCost() bool
SupportsCost reports whether the agent takes a USD cost budget. Safe on nil.
func (*AgentBudgetMap) SupportsTokens ¶ added in v0.175.0
func (m *AgentBudgetMap) SupportsTokens() bool
SupportsTokens reports whether the agent takes a token budget. Safe on nil.
type AgentConfig ¶
type AgentConfig struct {
// Extends: builtin starts the agent from the built-in template of the same name;
// only the keys written here override it (gofer-arsj, see ApplyAgentExtends).
Extends string `yaml:"extends,omitempty"`
Type string `yaml:"type,omitempty"`
Command string `yaml:"command,omitempty"`
Args []string `yaml:"args,omitempty"`
// GlobalArgs are command-wide options placed before the template subcommand.
// They are reused for normal and resumed invocations. When unset, the agent
// adapter may infer leading options from Args for a known resume subcommand.
GlobalArgs []string `yaml:"global_args,omitempty"`
// InteractiveArgs defines argv for interactive mode. Four combinations: args with {{prompt}} only=batch; InteractiveArgs non-nil only=interactive; both=dual-mode; neither=mode-less (except exec, which is batch by definition).
InteractiveArgs ArgList `yaml:"interactive_args,omitempty"`
Env map[string]string `yaml:"env,omitempty"`
AllowRawCmd bool `yaml:"allow_raw_cmd,omitempty"`
// Interactive 兼容别名:仅交互、args 即交互 argv。
Interactive bool `yaml:"interactive,omitempty"`
NoRawCmd bool `yaml:"no_raw_cmd,omitempty"`
Detect DetectConfig `yaml:"detect,omitempty"`
// SessionInject 注入模式 argv 模板(模式①,首选)。非空 => 提交时 gofer 生成 uuid
// 渲染追加到 argv,立即知 id、无需解析输出。{{session_id}} 占位(session-capture §6.4)。
SessionInject []string `yaml:"session_inject,omitempty"`
// ExitKeys is the ordered input written to an interactive TUI on cancel.
// Each element is a literal byte sequence; use YAML escapes for control keys.
ExitKeys []string `yaml:"exit_keys,omitempty"`
// ExitGraceSec bounds the graceful exit wait. Nil or non-positive means 8s.
ExitGraceSec *int `yaml:"exit_grace_sec,omitempty"`
// SessionStoreGlob scans the CLI's own session files when it cannot accept
// session_inject. {{home}} and {{cwd}} expand on the execution machine.
SessionStoreGlob string `yaml:"session_store_glob,omitempty"`
// SessionStoreIDRegex extracts an id from the filename or metadata content.
// The first non-empty capture group is used.
SessionStoreIDRegex string `yaml:"session_store_id_regex,omitempty"`
// SessionCapture 捕获模式正则(模式②,兜底),第一个**非空**捕获组 = session_id
// (可写多分支,各分支各占一个捕获组,只有命中的那个非空:如 omp 的 ndjson 会话行
// 与 TUI 退出横幅)。仅当 SessionInject 为空时使用(注入优先于捕获)。
SessionCapture string `yaml:"session_capture,omitempty"`
// SessionResume resume 的整条 agent argv 模板(非追加 flag),{{session_id}}/{{prompt}}
// 占位。供 `gofer job resume`(P2)拼接续接命令。
SessionResume []string `yaml:"session_resume,omitempty"`
// SessionResumeInteractive 是 pty/交互会话续接的 argv 模板(区别于非交互 SessionResume)。
// 交互会话进 TUI 续接,不用非交互的一次性 flag(claude 的 -p / codex 的 exec)。
// 仅当源 job 是 interactive 时由 ResumeJob 选用;未配置则回退到内置默认。
SessionResumeInteractive []string `yaml:"session_resume_interactive,omitempty"`
// TransientErrorPatterns override the complete built-in list, including when empty.
// Matching is case insensitive; nil selects the command's built-in defaults.
TransientErrorPatterns []string `yaml:"transient_error_patterns,omitempty"`
// FallbackAgents is this agent's ordered candidate list for a TRANSIENT failure
// that its own session cannot continue (SUP-01 P3): the first candidate that the
// project admits takes the work over. Empty = no transfer (the default, so an
// existing config is unaffected). A project may override the list per agent with
// agent_fallbacks; `job run --fallback` overrides both for one job. Candidates
// must be declared agents that can run in batch mode (validated at load).
FallbackAgents []string `yaml:"fallback_agents,omitempty"`
// Skills are this agent's own bindings (JOB-10 §一.3): the CLI quirks knowledge
// that only applies when THIS agent runs (e.g. "how to apply a patch on Windows"
// for the one agent whose tooling needs it). They are unioned with server.skills
// and the project's list rather than replacing them — skills accumulate across
// the levels — and an exec agent carries none at all (it runs a command, it does
// not read docs). See Config.EffectiveSkills.
Skills []string `yaml:"skills,omitempty"`
// ImageInput says how the agent takes an image the console hands it (workbench image
// attachments): path = it opens a local image when the message names its absolute
// path (delivery 1: the text carries a `[附图 n] <path>` line); arg = the image path
// rides the ARGV of the job that carries the message, expanded through ImageArgs
// (delivery 2: the text stays clean); none = it cannot take an image at all. Unset
// means "use the built-in table for this agent" (EffectiveImageInput: claude / codex
// and their -acp variants = path, suga = arg, suga-acp = none — it takes images
// inline when its model can see them); an agent with none greys out the attach button.
// Inline ACP image blocks are decided by the agent's own promptCapabilities.image,
// not by this field.
ImageInput string `yaml:"image_input,omitempty"`
// ImageArgs is the argv fragment an image_input: arg agent takes one image with, e.g.
// `["--image", "{{path}}"]`: the fragment is expanded ONCE PER IMAGE and appended to
// the argv of the job that carries the message, so a message with three images adds
// `--image p1 --image p2 --image p3`. It must contain {{path}} and must not contain
// {{prompt}}, and it is required by image_input: arg (validation rejects the pair
// otherwise: an arg agent with no template could name no image).
ImageArgs []string `yaml:"image_args,omitempty"`
// MCP lists the registry MCP servers this agent's jobs get (MCP-06).
MCP []string `yaml:"mcp,omitempty"`
// MCPFormat is how MCP servers are injected into this agent: acp (session/new
// mcpServers), claude-json (a generated mcp.json passed through mcp_args) or
// codex-config (`-c mcp_servers.*`). Built-in templates set it; an agent without
// one cannot take MCP servers and a job binding any is refused.
MCPFormat string `yaml:"mcp_format,omitempty"`
// MCPArgs is the argv fragment that hands the generated MCP config to a
// claude-json agent; it carries {{mcp_config_file}} and is inserted like model_args.
MCPArgs []string `yaml:"mcp_args,omitempty"`
// Rules are this agent's own MANDATORY bindings (JOB-06①): the constraints that
// only apply when THIS agent runs (its CLI's quoting rules, its sandbox limits).
// Unioned with server.rules and the project's list — rules accumulate across the
// levels — and an exec agent carries none at all (it runs a command, it does not
// read a prompt). See Config.EffectiveRules.
Rules []string `yaml:"rules,omitempty"`
// ReadOnlyArgs is the argv a `job run --read-only` appends to a cli-agent's argv
// (both the batch and the interactive shape, at the end like AgentArgs) so the
// sandbox is the CLI's own. Unset means "use the built-in table for this agent"
// (agent.applyReadOnlyDefaults: codex `-s read-only`, claude `--permission-mode
// plan`); an agent with no built-in and no configured value cannot run read-only
// at all and a --read-only submit is refused (bd h-aii-0ql3). An acp-agent has no
// argv suffix — its read-only mode is the protocol's, see acp.modes.read_only.
ReadOnlyArgs []string `yaml:"read_only_args,omitempty"`
// ModelArgs is the argv fragment a `job run --model <m>` splices into a cli-agent's
// argv (N1 §B): it carries {{model}}, and is inserted right BEFORE the argument
// holding {{prompt}} — before the flag whose value it is, for `--prompt {{prompt}}`
// / `-p {{prompt}}` — (appended after the template when none does, e.g. an
// interactive_args / interactive-resume shape) in every shape — batch, interactive
// and the resume templates. Unset means "use the built-in table for this agent"
// (agent.applyModelDefaults: claude `--model {{model}}`, codex `-m {{model}}`); an
// agent with neither cannot take --model and the submit is refused. An acp-agent
// has no argv fragment — its model is picked over the protocol.
ModelArgs []string `yaml:"model_args,omitempty"`
// FromSessionArgs is the argv fragment a `job run --from-session <id>` APPENDS to a
// cli-agent's rendered args template (gofer-f4z8): it carries {{from_session}} and
// asks the CLI to open a NEW session that inherits an earlier one's context (suag
// `[--from, "{{from_session}}"]`). Appended (not spliced before the prompt) so a
// `--prompt "{{prompt}}"` pair stays intact; the new session id still comes from
// session_inject. Only rendered when a value is given; an agent without it refuses
// --from-session. No built-in default — no well-known CLI has such a flag.
FromSessionArgs []string `yaml:"from_session_args,omitempty"`
// AgentBudget declares how the agent takes a SOFT budget (job `agent_tokens` /
// `agent_cost_usd`, `job run --agent-budget-tokens/--agent-budget-cost-usd`): a
// per-dimension argv fragment and/or environment variable the job's value is rendered
// into. The agent enforces it itself (winding the run up once spent), unlike the hard
// `budget` limits gofer meters. Unset means "use the built-in table for this agent"
// (agent.applyAgentBudgetDefaults: suga); an agent with no mapping for a dimension
// REFUSES a job that carries it. See AgentBudgetMap.
AgentBudget *AgentBudgetMap `yaml:"agent_budget,omitempty"`
// AddDirArgs is the argv fragment that hands the agent an EXTRA directory, rendered
// with {{dir}} (an agent taking `--add-dir` writes `["--add-dir", "{{dir}}:ro"]`).
// It is appended when the job runs in a NESTED repository: the job's cwd sits in a git
// repository whose top level is NOT the project root, i.e. the agent works in one of
// the repositories INSIDE the project (see job.addDirArgs). The project root is what
// gets passed, so the workspace-level rules / tracker / docs an enclosing project keeps
// stay readable from the nested checkout. Appended after every other fragment (a
// `--prompt "{{prompt}}"` pair stays intact); a cli-agent concept only, and nothing at
// all is appended for a cwd whose repository cannot be established.
AddDirArgs []string `yaml:"add_dir_args,omitempty"`
// SystemInject 是 per-agent 的 system prompt 注入 argv 模板(E35 角色,类比
// SessionInject)。非空 + 请求带 system_prompt 时,submit 渲染 {{system_prompt}}
// 追加到 argv(如 claude `--append-system-prompt <p>`)。保 argv 结构、不 shell
// 拼接(SR403)。claude 有内置默认(applySystemDefaults),codex 留空待实测。
SystemInject []string `yaml:"system_inject,omitempty"`
// OutputFormat 是采集该 agent stdout 的格式(bd h-aii-rpky):""/"text"(默认)
// 逐字落盘;"ndjson" 表示 stdout 是逐行 JSON 事件流(omp --mode json、claude
// --output-format stream-json),落盘时按 NDJSONKeep 过滤掉逐 token 增量事件,
// 否则日志体积膨胀 10~30 倍且 web 实时日志不可读(过滤实现见
// internal/runner/ndjsonfilter)。
OutputFormat string `yaml:"output_format,omitempty"`
// NDJSONKeep 是事件类型白名单(仅 OutputFormat=="ndjson" 时有意义):无点号的条目
// 匹配顶层 `type`,带点号的条目按嵌套路径取(如 `message.role` 命中该路径存在非空
// 字符串的行)。留空且未命中内置默认 = 不过滤。内置默认见 agent.applyOutputDefaults。
NDJSONKeep []string `yaml:"ndjson_keep,omitempty"`
// NDJSONRaw 为 true 时把原始(未过滤)行另存 <result_dir>/stdout.raw.log,仅排障用
// (体积与过滤前一致,默认关闭)。
NDJSONRaw bool `yaml:"ndjson_raw,omitempty"`
// NDJSONEventsTo 选择紧凑事件行的落点(bd h-aii-525u,仅 ndjson 时有意义):
// "stderr"(默认)像 codex 那样把过程事件写进 stderr、stdout 只留最终答复;
// "stdout" 保持一期落点(事件写到 stdout,答复追加其后)。
NDJSONEventsTo string `yaml:"ndjson_events_to,omitempty"`
// NDJSONStdout 决定 stdout 承载什么(仅 ndjson 时有意义):"assistant_text"(omp 默认)
// 写全部非空 assistant 消息(过程叙述 + 最终答复,空行分隔);"final_text"(claude 默认)
// 只写最终答复(omp 取最后一条 assistant 消息,claude 取 result.result)——注意 omp 的
// "最后一条"在收尾多一回合(todo 提醒、后台任务通知)时会丢掉真正的汇报(bd h-aii-lvo9),
// 所以 omp 不再默认它;"events" = 一期行为:stdout 即紧凑事件流,不提取答复。
NDJSONStdout string `yaml:"ndjson_stdout,omitempty"`
// NDJSONStdoutPath 是最终答复所在的 JSON 路径(点号分隔,如 result.result),给内置
// 投影器认不出的 agent 用;显式配置覆盖内置的答复提取规则。
NDJSONStdoutPath string `yaml:"ndjson_stdout_path,omitempty"`
// NDJSONUsagePath is the dotted path of the usage OBJECT in an ndjson result line
// (`usage`, `result.usage`), for a cli-agent whose usage the built-in projectors do
// not know. The object goes through runner.UsageFromObject (snake_case and camelCase
// spellings both read), so a custom agent's job gets token usage and cost like
// claude/omp/codex do. Only meaningful with output_format: ndjson.
NDJSONUsagePath string `yaml:"ndjson_usage_path,omitempty"`
// TranscriptDialect names the jsonl dialect of the transcript file a session of THIS
// agent registers (claude|codex|omp|generic). Unset = guess from the agent key, then
// sniff the content. See internal/work/transcript.
TranscriptDialect string `yaml:"transcript_dialect,omitempty"`
// InjectProcess adds foreground process names (no path, no extension) to the set a
// tmux pane may be running for a web message to be typed into it. It unions with
// session.inject_commands and applies only to sessions registered as THIS agent.
InjectProcess []string `yaml:"inject_process,omitempty"`
// DeliverCommand is how a web message reaches the LIVE process of one of this
// agent's sessions (session relay path C): argv appended to the agent's `command`
// (like session_resume), or a full argv when its first element is an absolute
// path. Placeholders {{session_id}} and {{text}} (the text carries the
// "[来自 web 回复,<user>] " prefix, or a gofer system prefix of its own when the
// message is gofer's). It runs as an internal job on the runner the
// session registered. Exit codes: 0 = delivered to the live process, 3 = the
// session's process is not running, anything else = failure (stderr is the
// reason). Unset = no live-process channel (tmux injection, then takeover).
DeliverCommand []string `yaml:"deliver_command,omitempty"`
// DeliverStdin sends the text on the command's stdin instead of a {{text}} argv
// placeholder (long text / special characters). Needs a worker at protocol v18+
// when the session runs on one.
DeliverStdin bool `yaml:"deliver_stdin,omitempty"`
// DeliverOfflineMatch is a Go regexp: a deliver_command that exits non-zero AND
// whose stdout+stderr match it is treated as exit 3 (the session's process is not
// running; the ladder continues to tmux / takeover) instead of deliver_failed. It
// lets a CLI that signals "no such session" with its own exit code and message (e.g.
// codex queue: exit 1, "no rollout found for thread id") work without a wrapper
// script. The judgement is made on the server, after the exec job finishes, so it
// holds for sessions on a remote worker too. Needs deliver_command.
DeliverOfflineMatch string `yaml:"deliver_offline_match,omitempty"`
// SessionFamily declares which session store this agent shares, overriding the
// built-in table: agents with the same family can continue each other's sessions.
SessionFamily string `yaml:"session_family,omitempty"`
// NDJSONFields 按事件类型覆盖投影输出的事件内容(如
// `ndjson_fields: {turn_end: [type, usage, model]}`):该类型的行只带这些路径
// (点号分隔,取最后一段作键);对投影器默认丢弃的类型也生效。
NDJSONFields map[string][]string `yaml:"ndjson_fields,omitempty"`
// McpServerName 是该 agent(codex)config.toml 里 gofer MCP server 的块名
// (`[mcp_servers.<name>]`)。gap①(issue 7z6j):codex 启动 MCP stdio 子进程用净化
// env、不透传 codex 进程 env,故 role.env 注入 codex 进程对 MCP 子进程无效;改经
// codex `-c mcp_servers.<name>.env.<KEY>=<VALUE>` 覆盖 MCP server env,使 sup 的
// gofer MCP 自注册 role=supervisor。约定默认 `gofer`(agent.McpServerNameDefault),
// 仅当 codex config 改了块名时才需配置此项。
McpServerName string `yaml:"mcp_server_name,omitempty"`
// ACP is the type=acp-agent sub-block (protocol-level settings). Ignored by
// every other agent type.
ACP *ACPConfig `yaml:"acp,omitempty"`
// MaxConcurrent caps how many jobs of THIS agent may run at once (JOB-11).
// 0/unset = unlimited, i.e. exactly the pre-JOB-11 behaviour. Like the project
// and caller caps it QUEUES the excess (the job stays `queued`), it never
// rejects: a saturated agent is a throughput limit, not an admission error.
MaxConcurrent int `yaml:"max_concurrent,omitempty"`
// StallTimeoutSec overrides the AUTO-05 output-stall window for THIS agent
// (AUTO-05): nil = inherit server.stall_timeout_sec, 0 = never watch this agent's
// jobs, N = kill a job of this agent after N silent seconds. A pointer because
// "off" and "unset" are different decisions.
StallTimeoutSec *int `yaml:"stall_timeout_sec,omitempty"`
// Budget is the default spend ceiling of THIS agent's jobs (N2 §B GATE-02): agent
// budget < project budget < the request's own, merged per dimension. See
// Config.EffectiveBudget.
Budget *Budget `yaml:"budget,omitempty"`
// CanSubmit opens the SUBMIT gate for this agent's jobs (SEC-01 §一.3): a member
// job running this agent may submit further jobs in its OWN project — it is the
// "a job that dispatches work" case, and it stays closed until an operator says
// otherwise. What it may start is SubmitAgents below, and the new job is tagged
// `submitted_by_job:<id>` so the provenance is on the job, not only in a log.
CanSubmit bool `yaml:"can_submit,omitempty"`
// SubmitAgents is the allowlist of agents such a job may submit (the agent/role of
// the job ASKING, not the one being asked for). Unset means
// EffectiveSubmitAgents' default of ["exec"] — the narrowest useful answer (start a
// command), never "any agent".
SubmitAgents []string `yaml:"submit_agents,omitempty"`
// Retry is this agent's default job retry policy (R2/AUTO-03, design §二.2): it
// applies to jobs that run THIS agent, overriding server.retry and being
// overridden by projects.<k>.retry / JobRequest.Retry. Nil = this agent says
// nothing (the layer below answers). See Config.EffectiveRetryPolicy.
Retry *RetryPolicy `yaml:"retry,omitempty"`
// contains filtered or unexported fields
}
AgentConfig describes a configurable CLI agent. Detect is refined in P3; P2 only needs it to decode cleanly.
func (AgentConfig) DeclaredKeys ¶ added in v0.142.0
func (a AgentConfig) DeclaredKeys() []string
DeclaredKeys lists the keys an `extends` agent wrote itself (sorted); nil for an agent without extends.
func (AgentConfig) EffectiveOutputFormat ¶
func (a AgentConfig) EffectiveOutputFormat() string
EffectiveOutputFormat is the configured capture format with the default applied: unset and "text" are the same thing.
func (AgentConfig) MarshalYAML ¶ added in v0.142.0
func (a AgentConfig) MarshalYAML() (any, error)
MarshalYAML writes an `extends` agent as its DIFFERENCE from the template: the keys it declared plus any field an edit moved away from the template value. Template values are never materialised into the file, so the agent keeps following the built-in template across upgrades. Any other agent marshals field by field as before.
func (AgentConfig) NDJSONOutput ¶
func (a AgentConfig) NDJSONOutput() bool
NDJSONOutput reports whether this agent's stdout is a structured NDJSON stream that must be compacted at capture time.
type AgentFallbackConfig ¶
type AgentFallbackConfig struct {
// OnFailure moves a job to the next candidate agent after a TRANSIENT failure
// the same agent cannot continue (SUP-01 P3). Unset means ON: configuring
// fallback_agents is the opt-in, and the transfer then needs no second switch. A
// pointer so an explicit false (e.g. an incident where every自动转移 must be off)
// is distinguishable from "not configured".
OnFailure *bool `yaml:"on_failure,omitempty"`
// PreDispatch substitutes a DEGRADED agent at submit time instead of waiting for
// it to fail (SUP-01 P3). Default OFF: silently running "not the agent I asked
// for" is a surprising thing to do by default.
PreDispatch bool `yaml:"pre_dispatch,omitempty"`
}
AgentFallbackConfig is the server.agent_fallback block (SUP-01 P3): the two switches of the failover machinery. Both default to the value an operator would expect from the design's decision 1 — the transfer runs, the substitution does not.
type AgentHealthConfig ¶
type AgentHealthConfig struct {
// WindowSec bounds the aggregation (0/unset => DefaultAgentHealthWindowSec).
WindowSec int `yaml:"window_sec,omitempty"`
// DegradedAfter is how many transient failures inside the window make an agent
// degraded (0/unset => DefaultAgentDegradedAfter).
DegradedAfter int `yaml:"degraded_after,omitempty"`
// RecoverAfterOK is how many successes after the last transient failure restore
// the agent (0/unset => DefaultAgentRecoverAfterOK).
RecoverAfterOK int `yaml:"recover_after_ok,omitempty"`
}
AgentHealthConfig is the server.agent_health block (SUP-01 P3): the window and thresholds `degraded` is computed from. Zero/unset fields take the defaults below.
type ApprovalConfig ¶
type ApprovalConfig struct {
// Mode is off|ask|strict ("" => off).
Mode string `yaml:"mode,omitempty"`
// AutoAllowKinds lists the ACP ToolKinds approved without asking under mode=ask
// ("" => DefaultApprovalAutoAllowKinds).
AutoAllowKinds []string `yaml:"auto_allow_kinds,omitempty"`
// AskKinds lists the ACP ToolKinds that always ask ("" => DefaultApprovalAskKinds).
// It takes precedence over AutoAllowKinds, so a kind in both lists asks.
AskKinds []string `yaml:"ask_kinds,omitempty"`
// TimeoutSec bounds how long a pending approval waits for an answer ("" / <=0 =>
// DefaultApprovalTimeoutSec). The job's own timeout still applies on top.
TimeoutSec int `yaml:"timeout_sec,omitempty"`
// OnTimeout is reject|allow — what the agent is told when nobody answers in time
// ("" => reject).
OnTimeout string `yaml:"on_timeout,omitempty"`
// RememberAllowAlways makes a human's allow_always answer cover the SAME tool
// kind for the rest of the job, so one approval does not become twenty prompts.
// A pointer so "unset" defaults to true while an explicit false asks every time.
RememberAllowAlways *bool `yaml:"remember_allow_always,omitempty"`
}
ApprovalConfig is a project's approval gate for ACP permission requests (docs/design/2026-09-17-acp-agent-and-approval-gate-design.md §二.1).
It only applies to acp-agent jobs: the ACP `session/request_permission` request is the gate's input. `mode` decides — off auto-allows exactly as S0 did, ask asks a human unless the tool call's kind is auto_allowed, strict asks for everything. An agent may only TIGHTEN this (Config.EffectiveApproval).
func (ApprovalConfig) AllowsAlways ¶
func (a ApprovalConfig) AllowsAlways() bool
AllowsAlways reports the remember_allow_always switch (unset = true).
func (ApprovalConfig) AutoAllow ¶
func (a ApprovalConfig) AutoAllow(kind string) bool
AutoAllow reports whether a tool call of this kind needs no approval. It is asked of a RESOLVED policy (WithDefaults/ApprovalPolicy): ask_kinds wins over auto_allow_kinds, and a kind named by neither list is asked about — fail closed, so a new protocol kind can never slip through unapproved.
func (ApprovalConfig) WithDefaults ¶
func (a ApprovalConfig) WithDefaults() ApprovalConfig
WithDefaults returns the policy with every unset field resolved, so a consumer (the runner) never has to know the defaults. Slices are copied: the returned value shares no backing array with the config.
type ArgList ¶
type ArgList []string
ArgList is an argv template list that distinguishes UNSET (nil) from SET BUT EMPTY (`[]`). AgentConfig.InteractiveArgs needs the distinction because the empty list is a value, not an absence: AGT-02 defines `args` + `interactive_args: []` as the dual-mode agent whose interactive launch is the CLI's bare TUI, and the length-based `omitempty` a plain []string gets would silently drop the key on every write-back — turning a dual-mode agent into a batch-only one (bd h-aii-kd57).
goccy/go-yaml consults IsZeroer for `omitempty`, so only nil is "unset" here.
type AttachmentSettings ¶ added in v0.177.0
AttachmentSettings is AttachmentsConfig with the defaults applied.
type AttachmentsConfig ¶ added in v0.177.0
type AttachmentsConfig struct {
// MaxBytes caps ONE uploaded image (0 => 10 MiB; upper bound attachmentsMaxBytesLimit,
// because an upload is held in memory while it is validated).
MaxBytes int64 `yaml:"max_bytes,omitempty"`
// MaxPerMessage is how many attachments one message may carry (0 => 6). The upload route
// does not enforce it — the send path of the workbench does.
MaxPerMessage int `yaml:"max_per_message,omitempty"`
// HourlyPerCaller caps the uploads one caller may attempt per rolling hour (0 => 200).
HourlyPerCaller int `yaml:"hourly_per_caller,omitempty"`
}
AttachmentsConfig is the server.attachments block: the numbers of the workbench image attachments (design 2026-10-19-workbench-image-attachments-design.md 「大小与数量」). Every key is optional; 0 / unset takes the documented default and a negative value is a load error. The upload handler reads them per request, so an edit applies to the next upload.
type BackoffSec ¶ added in v0.182.0
type BackoffSec []int
BackoffSec is the retry backoff table, in seconds. It decodes from BOTH spellings a person writes in YAML or JSON: the list (`backoff_sec: [300, 600]`) and a single number (`backoff_sec: 300`), the latter meaning the SAME wait before every retry. A single number that had to be written as a one-element list was the most common way to get "int was used where sequence is expected" from a workflow file (gofer-pn0x).
Encoding always emits the list form, so a round-tripped config states the meaning explicitly and never depends on which spelling a reader understands.
func (*BackoffSec) UnmarshalJSON ¶ added in v0.182.0
func (b *BackoffSec) UnmarshalJSON(data []byte) error
UnmarshalJSON accepts either form: a number or an array of numbers.
func (*BackoffSec) UnmarshalYAML ¶ added in v0.182.0
func (b *BackoffSec) UnmarshalYAML(data []byte) error
UnmarshalYAML accepts either form (goccy's raw-bytes unmarshaler hook).
type Budget ¶
type Budget struct {
MaxTokens int64 `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
MaxCostUSD float64 `json:"max_cost_usd,omitempty" yaml:"max_cost_usd,omitempty"`
MaxTurns int `json:"max_turns,omitempty" yaml:"max_turns,omitempty"`
// AgentTokens / AgentCostUSD are the SOFT budget handed to the agent itself (not
// metered or enforced by gofer): the agent winds the run up on its own once it has
// spent that much, so the report is still delivered. They are rendered into the
// agent's argv through agents.<k>.agent_budget_args; an agent without that mapping
// refuses a job that carries them. Keep them below the hard max_* limits — a hard
// kill lands before the agent's own wrap-up.
AgentTokens int64 `json:"agent_tokens,omitempty" yaml:"agent_tokens,omitempty"`
AgentCostUSD float64 `json:"agent_cost_usd,omitempty" yaml:"agent_cost_usd,omitempty"`
}
Budget is a job's spend ceiling (N2 §B, GATE-02). Every field is optional and 0 means "no limit on this dimension"; an all-zero Budget is the same as none. It is the shared shape of the request (JobRequest.Budget), the config defaults (agents.<k>.budget / projects.<k>.budget), the task-book frontmatter and the worker dispatch frame, which is why it lives in the config package (the lowest layer all of them already import).
The limits are enforced on the EXECUTING machine from the agent's own streamed accounting: MaxTokens against input+output+cache (the job usage total), MaxCostUSD only where the source reports a cost, MaxTurns against the number of model requests.
func (*Budget) HasAgent ¶ added in v0.175.0
HasAgent reports whether a soft budget for the agent itself (agent_*) is set. Safe on a nil receiver.
func (*Budget) HasHard ¶ added in v0.175.0
HasHard reports whether a gofer-enforced limit (max_*) is set. Safe on a nil receiver.
func (*Budget) Normalize ¶
Normalize returns nil for an empty budget, else a copy, so "no budget" has exactly one representation (and request_json / wire frames stay byte-identical to before).
func (*Budget) Over ¶
Over returns b with every unset (0) dimension filled from def — the layered default rule (agent < project < request: the more specific layer wins per dimension). Either side may be nil; the result is nil when nothing is limited.
func (*Budget) Validate ¶
Validate rejects a negative, NaN or infinite limit (0 = unlimited is fine).
func (*Budget) WithoutAgent ¶ added in v0.175.0
WithoutAgent returns a copy of b with the agent_* soft budget removed (nil when nothing else is left). Safe on a nil receiver.
func (*Budget) WithoutHard ¶ added in v0.175.0
WithoutHard returns a copy of b with the max_* limits removed (nil when nothing else is left). Safe on a nil receiver.
type CallerCeiling ¶ added in v0.172.0
type CallerCeiling struct {
// Projects are the project keys the caller may touch (glob).
Projects []string `yaml:"projects,omitempty" json:"projects,omitempty"`
// Runners are the runner keys the caller may submit to (glob, `local`/`server`
// included). Empty = no machine runner (worker runners only).
Runners []string `yaml:"runners,omitempty" json:"runners,omitempty"`
// Workers are the workers the caller's jobs may be routed to (glob). Empty = any.
Workers []string `yaml:"workers,omitempty" json:"workers,omitempty"`
// Agents are the agents the caller may use (glob). Empty = any.
Agents []string `yaml:"agents,omitempty" json:"agents,omitempty"`
// AllowExec permits exec jobs (agent exec, a Cmd, a Verify argv, hooks) for this
// caller. nil = not allowed.
AllowExec *bool `yaml:"allow_exec,omitempty" json:"allow_exec,omitempty"`
// GlobalMemory permits writing memory that is not scoped to one of the caller's
// projects. nil = not allowed.
GlobalMemory *bool `yaml:"global_memory,omitempty" json:"global_memory,omitempty"`
// ReadOnly refuses every state-changing request of this caller. nil = not read-only.
ReadOnly *bool `yaml:"read_only,omitempty" json:"read_only,omitempty"`
}
CallerCeiling is one caller's upper bound. Every dimension is a glob list (path.Match semantics, `*` does not cross `/`) or a tri-state switch:
- Projects, Agents, Workers: EMPTY = the dimension is not restricted. A non-empty list requires the value to match one of its patterns; the empty value matches only a pattern that matches the empty string (e.g. `*`), so a request that names nothing in a restricted dimension is refused (fail closed).
- Runners: EMPTY = every runner EXCEPT the built-in in-process one, i.e. remote workers only. The machine runner (local / server) must be listed explicitly — a job on it runs on the server host and its agent can read the server's config and tokens, so a ceiling is not a security boundary for a caller that has it. Entries are compared after NormalizeRunnerName, so either spelling of the built-in runner works.
- AllowExec / GlobalMemory / ReadOnly: nil (the key absent) resolves to the STRICT side of the design — exec off, global memory off, read-only off. The first two are restrictions, so `*bool` is what distinguishes "the operator left it out" from an explicit `false`; ReadOnly defaults to off because a ceiling is not a read-only switch unless it says so.
It is a pure value: no method mutates it, and Clone deep-copies it (cloneServer).
func (*CallerCeiling) AllowsAgent ¶ added in v0.172.0
func (c *CallerCeiling) AllowsAgent(a string) bool
AllowsAgent reports whether the ceiling admits agent key a. A nil ceiling (or an empty Agents list) admits everything.
func (*CallerCeiling) AllowsProject ¶ added in v0.172.0
func (c *CallerCeiling) AllowsProject(p string) bool
AllowsProject reports whether the ceiling admits project key p. A nil ceiling (or an empty Projects list) admits everything.
func (*CallerCeiling) AllowsRunner ¶ added in v0.172.0
func (c *CallerCeiling) AllowsRunner(r string) bool
AllowsRunner reports whether the ceiling admits runner r. Both sides are normalized through NormalizeRunnerName, so `runners: [server]` and `runners: [local]` are the same declaration (G043: one normalizer for the two spellings of the built-in runner).
An empty Runners list admits every runner EXCEPT the built-in in-process one (the machine runner must be spelled out); a non-empty list admits only what it matches, and the built-in runner only by name — a glob never matches it.
func (*CallerCeiling) AllowsWorker ¶ added in v0.172.0
func (c *CallerCeiling) AllowsWorker(w string) bool
AllowsWorker reports whether the ceiling admits worker w. A nil ceiling (or an empty Workers list) admits everything.
func (*CallerCeiling) ExecAllowed ¶ added in v0.172.0
func (c *CallerCeiling) ExecAllowed() bool
ExecAllowed reports whether the caller may run exec jobs. A nil ceiling restricts nothing and answers true; a ceiling that does not set allow_exec answers false (the strict default of decision 3).
func (*CallerCeiling) GlobalMemoryAllowed ¶ added in v0.172.0
func (c *CallerCeiling) GlobalMemoryAllowed() bool
GlobalMemoryAllowed reports whether the caller may write global (not project-scoped) memory. A nil ceiling restricts nothing and answers true; a ceiling that does not set global_memory answers false.
func (*CallerCeiling) IsReadOnly ¶ added in v0.172.0
func (c *CallerCeiling) IsReadOnly() bool
IsReadOnly reports whether every state-changing request of this caller is refused. A nil ceiling (or one that does not set read_only) answers false.
type CallerConfig ¶
type CallerConfig struct {
ID string `yaml:"id,omitempty"`
// Name is an optional display name (e.g. `admin` for the main-token caller `default`).
// Display only: the id stays the identity recorded on jobs, grants and audit lines, and
// no permission decision reads the name. Trimmed on load; when non-empty it must be
// unique across callers (case-insensitive) and at most MaxCallerNameLen characters.
Name string `yaml:"name,omitempty"`
Token string `yaml:"token,omitempty"`
TokenEnv string `yaml:"token_env,omitempty"`
// CanAnswer permits this caller to answer/punt interactions when
// governance.require_answer_capability is enabled.
//
// DEPRECATED(v0.161): remove in v0.164. Grant the answer permissions
// (`interaction.answer`, `job.review`, `job.wake.others`) to the caller on the web
// instead; a migration keeps the same behaviour by declaring the bit holder as a
// root administrator (`can_admin: true`).
CanAnswer bool `yaml:"can_answer,omitempty"`
// CanAdmin permits this caller to edit config/projects when
// governance.require_admin_capability is enabled.
//
// can_admin is NOT deprecated: it is what names a root administrator (design §2),
// which holds every permission and is the only subject that may manage grants.
CanAdmin bool `yaml:"can_admin,omitempty"`
// CanAttach permits this caller to attach to interactive sessions when
// governance.require_attach_capability is enabled.
//
// DEPRECATED(v0.161): remove in v0.164. Grant `job.attach` on the web instead.
CanAttach bool `yaml:"can_attach,omitempty"`
// CanTunnel permits TCP tunnel connections when governance requires it.
//
// DEPRECATED(v0.161): remove in v0.164. Grant `tunnel.open` on the web instead.
CanTunnel bool `yaml:"can_tunnel,omitempty"`
// E17 per-caller quota overrides (design §7.1). Each 0/empty value falls back to
// the server.governance default; if that is also 0 the dimension is unlimited
// (向后兼容). A value > 0 wins over the governance default.
MaxConcurrentJobs int `yaml:"max_concurrent_jobs,omitempty"` // 同时在跑上限(信号量排队语义,超额排队不拒)
RateLimit float64 `yaml:"rate_limit,omitempty"` // 每秒提交请求数(令牌桶速率); 0 = 不限
RateBurst int `yaml:"rate_burst,omitempty"` // 桶容量(突发); <=0 时取 max(1, ceil(RateLimit))
// Ceiling is the upper bound (上限) of what this caller may reach: which projects,
// runners, workers and agents it may use, whether it may run exec jobs, whether it
// may write global memory, and whether it is read-only. nil (the key absent) means
// NO ceiling — the caller keeps exactly the permissions it has without one.
//
// A ceiling only ever SUBTRACTS: the caller's effective range is its permissions
// ∩ the ceiling, and the dimensions left out of the block are resolved strictly
// (see CallerCeiling). The sub-tree is decoded strictly (an unknown key fails the
// load) and an empty `ceiling: {}` is refused, because a ceiling that restricts
// nothing is a trap: it reads as if the caller had been limited.
Ceiling *CallerCeiling `yaml:"ceiling,omitempty"`
}
CallerConfig identifies one authenticated submitter (C2). Token is the literal bearer token; TokenEnv reads it from the named environment variable instead (so secrets stay out of the config file). ID is recorded on the caller's jobs.
type CastConfig ¶
type CastConfig struct {
// Enabled turns cast recording on. It defaults to false (opt-in, G023): an
// existing config that never wrote `enabled` decodes to false, records
// nothing and stays zero-regression. It is the single "is recording on"
// predicate (handler sink, prune-loop gate, recording_uri) — RetentionTTLHours
// no longer expresses "disabled".
Enabled bool `yaml:"enabled,omitempty"`
RetentionTTLHours int `yaml:"retention_ttl_hours,omitempty"` // 0=用默认 24(仅 Enabled 时)
Encryption CastEncryptionConfig `yaml:"encryption,omitempty"`
}
func (CastConfig) ResolveCastSecret ¶
func (c CastConfig) ResolveCastSecret() ([]byte, error)
ResolveCastSecret reads and decodes the cast encryption key from its configured env var (Encryption.KeyEnv) at serve start (D-P3-5 / D-P3-4 runtime check). The env value must be a base64- or hex-encoded random key that decodes to at least castMinSecretBytes (256-bit): HKDF is NOT a password KDF, so a short passphrase is rejected here rather than silently stretched. A missing/empty/undecodable or too-short key returns an error so serve fails fast (never half-records). The key itself is never included in the error text or logged (SR403).
type CastEncryptionConfig ¶
type CommentTriggerConfig ¶
type CommentTriggerConfig struct {
// MinIntervalSec is the minimum spacing between two DISPATCHING comments on one
// scope (unset => DefaultCommentTriggerMinIntervalSec). 0 = no interval gate.
MinIntervalSec *int `yaml:"min_interval_sec,omitempty"`
// MaxPerScope caps how many dispatching comments one scope may ever produce
// (unset => DefaultCommentTriggerMaxPerScope). 0 = no cap.
MaxPerScope *int `yaml:"max_per_scope,omitempty"`
}
CommentTriggerConfig is the server.comment_trigger block (MCP-05 阶段 A, design §二.A.4). @-mention dispatch is automatic spending, so it is throttled per scope (the job/plan/todo the comment is written on) and both knobs are POINTERS: unset means the built-in default, while an explicit 0 turns that gate OFF — the same unset-vs-explicit-zero distinction server.stall_timeout_sec makes.
type Config ¶
type Config struct {
// Include lists further files (paths relative to this file's directory, globs
// allowed) that each hold whole top-level sections, e.g. `config.d/*.yaml` with
// agents and projects split out (gofer-arsj). Main file only; a section lives in
// exactly one file. See LoadIncludes.
Include []string `yaml:"include,omitempty"`
Server ServerConfig `yaml:"server,omitempty"`
Log LogConfig `yaml:"log,omitempty"`
Storage StorageConfig `yaml:"storage,omitempty"`
Projects map[string]ProjectConfig `yaml:"projects,omitempty"`
Agents map[string]AgentConfig `yaml:"agents,omitempty"`
Runners map[string]RunnerConfig `yaml:"runners,omitempty"`
// Roles are named E35 role presets (reviewer/bugfix/…): a base agent + a
// resident system_prompt + optional default project/tags. `job run --role` /
// `gofer_run_job(role=)` resolve a role to fill those request fields (design
// §8.5). Rules/context-file mounting is E11 territory, out of scope here.
Roles map[string]RoleConfig `yaml:"roles,omitempty"`
// Leader is the MCP-05 阶段 B "leader round" (design §二.B): when enabled, a member
// job of a plan reaching a FINISHED state wakes a LEADER job that reads the report
// and decides the next step. Nil (or enabled:false) is the default and means the
// whole feature is off — no wake rows, no leader jobs, nothing recorded. It used to
// live under `supervisor.leader`; that old location is no longer read.
Leader *LeaderConfig `yaml:"leader,omitempty"`
// Schedule tunes the AUTO-02 cron schedule sweeper. All fields are optional;
// serve applies conservative defaults when unset.
Schedule ScheduleConfig `yaml:"schedule,omitempty"`
// Wakeup tunes the JOB-09 wakeups (event subscriptions / timers that resume a
// finished job). An absent block keeps the documented default (7 days), so the
// feature is always on and there is no enable switch to get wrong.
Wakeup WakeupConfig `yaml:"wakeup,omitempty"`
// Session tunes the terminal session relay (SESS-01): when a stopping agent
// session is allowed to wait for a web reply without the human flipping its
// switch. See SessionConfig.
Session SessionConfig `yaml:"session,omitempty"`
// Work tunes the work-item overview (W1): the daily digest notification. An absent
// block keeps the defaults (digest at 09:00, on).
Work WorkConfig `yaml:"work,omitempty"`
// Steward tunes the W2b steward: a resident ACP session that only schedules and tidies
// the work items (design 2026-10-05 §9 / §14.4). Off by default.
Steward StewardConfig `yaml:"steward,omitempty"`
// Pty tunes the WEB-03 pty relay's text transcript (PTY-01 §四). An absent
// block keeps the documented 4MB tail cap, so the transcript is always on and
// there is no enable switch to get wrong.
Pty PtyConfig `yaml:"pty,omitempty"`
// Mail tunes the gofer 信箱 server deliverer (wake thresholds, tick, deadline, lease).
// An absent block keeps the design's defaults. See MailConfig.
Mail MailConfig `yaml:"mail,omitempty"`
// Tools are the external tools installed on THIS machine (CFG-16), declared for
// the server-local runner only: an agent job this server runs locally gets them
// listed in its prompt, and /v1/runners shows them on the local row. A worker
// declares its own in worker.yaml (workerConfigToConfig maps them here, so the job
// service reads cfg.Tools the same way on both). Applied on reload; not part of
// the project overlay.
Tools []Tool `yaml:"tools,omitempty"`
// MCPServers is the MCP server registry (MCP-06): declared once here, bound with
// server.mcp / agents.<k>.mcp / projects.<k>.mcp / `job run --mcp`, injected per
// agent type at execution. See mcp.go.
MCPServers map[string]MCPServerConfig `yaml:"mcp_servers,omitempty"`
// Secrets is the job secret registry (JOB-06②): name -> where the executing
// machine reads the value. Values are never stored here; file-only. See secrets.go.
Secrets map[string]SecretConfig `yaml:"secrets,omitempty"`
// Pricing is the model price table (USD per million tokens) used to estimate the
// cost of usage that reports none (gofer-2ldy). Keys are model names or globs.
Pricing map[string]ModelPrice `yaml:"pricing,omitempty"`
// HTTPProxy is the server's outbound proxy for selected sites (file-only). See
// httpproxy.go.
HTTPProxy HTTPProxyConfig `yaml:"http_proxy,omitempty"`
// contains filtered or unexported fields
}
Config is the top-level gofer configuration. Unknown top-level keys present in the source file are preserved on write (see writer.go).
func CanonicalConfig ¶
CanonicalConfig returns the operator-owned projection used when deciding whether a reload changed configuration. Runtime-injected agents, defaults, overlays and serve-only overrides are intentionally excluded.
func Load ¶
Load resolves the config file via the lookup chain, decodes it into the strongly-typed Config, applies defaults and runs basic validation. It returns the loaded config and the resolved absolute path.
Lookup order (§6.1):
- explicitPath (CLI --config)
- env GOFER_CONFIG
- ./.gofer[.local].yaml
- ~/.config/gofer/config.yaml
When no file is found, Load returns a defaulted empty Config and an empty path (no error) so that `project add` can create the first config.
Client mode (GOFER_RUN_MODE=client) stops the chain after step 2: a pure client node has no local gofer config by design, so the AUTO-DISCOVERED locations (./.gofer[.local].yaml, <config-dir>/config.yaml) are never read and an empty defaulted Config comes back with an empty path — a missing local file is the normal state there, not an error. The EXPLICIT tier stays untouched: --config and the GOFER_CONFIG env pointer still name a file the operator asked for.
func LoadWithOverrides ¶ added in v0.142.0
LoadWithOverrides loads the config at path like Load, but reads the files named in overrides (absolute paths) from memory instead of disk. `gofer config lint` uses it to try a config with one key removed without touching the files.
func (*Config) AgentFallbackOnFailure ¶
AgentFallbackOnFailure resolves whether a transient failure is transferred to the next candidate agent. Default ON (design decision 1): a candidate list is the opt-in, and an operator who wrote one wants it used.
func (*Config) AgentFallbackPreDispatch ¶
AgentFallbackPreDispatch resolves whether Submit substitutes a degraded agent before dispatching. Default OFF (design decision 1).
func (*Config) AgentFallbacksFor ¶
AgentFallbacksFor resolves the ordered candidate list for an agent in a project: the project's agent_fallbacks override when it names that agent, else the agent's own fallback_agents. It reads configuration only — whether a candidate is ADMITTED (project allowed_agents) is decided at submit time, where the project and the request are both known.
func (*Config) Clone ¶
Clone returns a copy safe for the P3 copy-on-write write transaction (core.Core.Update / reloadLocked): the struct is shallow-copied, then the Projects, Agents and injectedAgents maps are deep-copied ONE level so a mutation on the clone never touches a map a concurrent reader still holds.
One-level deep is enough because every P3 runtime mutation is a WHOLE-VALUE change: project set/delete (Registry.Add/Remove) replaces or drops a whole ProjectConfig, and agent.Resolve deletes/inserts whole AgentConfig entries on the Agents map — neither edits a value's inner slice in place. So the value structs (and the slices they carry, e.g. AllowedAgents) may stay shared with the source; only the map headers must be private to the clone. The Agents map MUST be deep-copied for the same reason the Projects map is: reloadLocked runs agent.Resolve on the clone, which delete()s the previously-injected keys — on a shallow-shared map that would tear a running Submit's snapshot.
Deliberately NOT deep-copied (D-MED-7): Storage, Runners, Roles, Leader, Schedule. No P3 runtime write path mutates them, so sharing them with the source is safe. Extending the write transaction to any of them REQUIRES widening this Clone first — today it makes a structural guarantee for "project whole-value add/remove" (plus the agent re-resolve that rides every reload) only, not for arbitrary mutation.
The Server block IS deep-copied (one level, same rule) since WEB-04③ V1.1: the console can edit it through Core.Update, so its pointers/slices/maps must be private to the clone like Projects/Agents are — see cloneServer.
func (*Config) ConfiguredSessionStopJobWait ¶ added in v0.158.0
ConfiguredSessionStopJobWait is session.stop_job_wait exactly as the file wrote it ("" when unset). The Stop hook uses this one, not the effective form: an unset local value must let the SERVER's setting decide (it arrives on the session object), so a container hook with no config file still obeys the operator.
func (*Config) DecisionHooksFor ¶ added in v0.149.0
func (c *Config) DecisionHooksFor(point, projectKey string, internal bool) []DecisionHookConfig
DecisionHooksFor returns, in config order, the enabled hooks that answer point for projectKey. internal reports whether the action belongs to one of gofer's own internal jobs, which only include_internal hooks are asked about.
func (*Config) EffectiveAgentHealth ¶
func (c *Config) EffectiveAgentHealth() AgentHealthConfig
EffectiveAgentHealth resolves the health window/thresholds, filling unset fields with the defaults. A non-positive value reads as unset (there is no meaningful "zero-length window" or "zero failures means degraded").
func (*Config) EffectiveApproval ¶
func (c *Config) EffectiveApproval(projectKey, agent string) ApprovalConfig
EffectiveApproval resolves the approval policy that governs a job of this project run by this agent: the project's policy, TIGHTENED — never relaxed — by the agent's acp.permission_policy (design §GATE-01.1). The agent knob therefore has three effects and no others: auto_allow (or unset) leaves the project policy alone, ask raises off to ask, strict raises anything to strict. An unknown project/agent resolves to the default (off) policy.
func (*Config) EffectiveAttachments ¶ added in v0.177.0
func (c *Config) EffectiveAttachments() AttachmentSettings
EffectiveAttachments resolves server.attachments over the defaults.
func (*Config) EffectiveAutoRelayIdleSec ¶
EffectiveAutoRelayIdleSec resolves the keyboard idle threshold (seconds) from the top-level `session.auto_relay_idle_sec` (the only spelling since v0.48; the pre-R2 `server.session_auto_relay_idle_sec` alias is now a load error, see RejectRemovedKeys). Unset keeps the default; 0 = that criterion disabled.
func (*Config) EffectiveAutoRelaySkipWhenSupervising ¶
EffectiveAutoRelaySkipWhenSupervising resolves the SUP-01 D gate: true (the default) keeps the auto rules from arming a session whose caller has live jobs.
func (*Config) EffectiveAutoRelayTurnSec ¶
EffectiveAutoRelayTurnSec resolves the last-human-input fallback threshold (seconds); 0 = that criterion disabled.
func (*Config) EffectiveBudget ¶
EffectiveBudget resolves the job's budget: agent default < project default < the request's own, merged per dimension (see Budget.Over). nil = unlimited.
func (*Config) EffectiveCommentTrigger ¶
EffectiveCommentTrigger resolves the @-mention throttle (MCP-05 阶段 A): the minimum seconds between two DISPATCHING comments on one scope and the lifetime cap of dispatching comments per scope. Either may be 0, which turns that gate off. A nil config (or unset field) yields the defaults above.
func (*Config) EffectiveContinueMaxChain ¶ added in v0.170.0
EffectiveContinueMaxChain resolves the continuation chain limit of a project: its continue_max_chain, else the default. 0 means unlimited. A key the config does not define resolves the default.
func (*Config) EffectiveDirLock ¶
EffectiveDirLock resolves the JOB-11 same-directory serialization switch: an explicit `server.dir_lock` wins, an unset one means ON (a deployment that never mentioned it gets the safe behaviour — adjacent writable agent jobs queue instead of editing one tree at once). Turning it off makes every job shared.
func (*Config) EffectiveDirLockMaxWaitSec ¶
EffectiveDirLockMaxWaitSec resolves how long a job may wait for the same-directory lock, in seconds, or 0 for "no cap":
request (stamped by the submitting hub) → its value server.dir_lock_max_wait_sec → its value, 0 removing the cap otherwise → DefaultDirLockMaxWaitSec
The request layer exists because a job dispatched to a worker/peer executes there: the hub resolves the policy ONCE and the executing machine applies it instead of re-deriving one from its own config (the same rule as server.dir_lock and server.stall_timeout_sec).
func (*Config) EffectiveHoldTimeoutSec ¶ added in v0.137.0
EffectiveHoldTimeoutSec resolves a held job's timeout in seconds from the request's value: 0 takes server.hold.default_timeout_sec, a positive value is used as is, and a negative value or one above server.hold.max_timeout_sec is an error — the request is refused rather than truncated, so a caller never waits less than it asked for without being told.
func (*Config) EffectiveImageInput ¶ added in v0.177.0
EffectiveImageInput resolves how agent key takes an image a message carries: the agent's own `image_input` wins, then the built-in table, then none. path and arg are positive (an image can be delivered); every other value (including a typo that validation would reject) is none.
func (*Config) EffectiveMCP ¶ added in v0.144.0
func (c *Config) EffectiveMCP(projectKey, agentKey string, requested []string, disable bool, agentType string) []string
EffectiveMCP resolves the MCP servers bound to one job: the union of server.mcp, agents.<agent>.mcp, projects.<project>.mcp and the request's names, first appearance first, disabled entries dropped. Like EffectiveSkills, disable (--no-mcp) and an exec agent return nil. Unknown names are kept so the caller can reject them with the name.
func (*Config) EffectiveMail ¶ added in v0.174.0
func (c *Config) EffectiveMail() MailSettings
EffectiveMail resolves the `mail:` block with the defaults applied.
func (*Config) EffectiveMaxTimeout ¶ added in v0.177.0
EffectiveMaxTimeout is EffectiveMaxTimeoutSec plus WHERE the number came from: "project" (projects.<key>.max_timeout_sec) or "server" (server.max_job_timeout_sec, including the built-in default when that is unset).
func (*Config) EffectiveMaxTimeoutSec ¶
EffectiveMaxTimeoutSec resolves the ONE ceiling a job in projectKey is clamped against (bd h-aii-s9ck): the project's max_timeout_sec when set, else the server's max_job_timeout_sec, else DefaultMaxJobTimeoutSec. A project override is a REPLACEMENT rather than a tightening, so it may exceed the server value. Callers: the job submit clamp (and its "clamped" report) and serve's supervisor reconciler — both must see the same number, hence one resolver on *Config.
func (*Config) EffectivePtyTranscriptMaxBytes ¶
EffectivePtyTranscriptMaxBytes resolves the transcript cap in bytes.
func (*Config) EffectiveRetryPolicy ¶
func (c *Config) EffectiveRetryPolicy(projectKey, agentKey string, requested *RetryPolicy) *RetryPolicy
EffectiveRetryPolicy resolves the retry policy that applies to a job, nearest layer first:
requested (JobRequest.Retry) → used as given (an explicit max_attempts:1 = off)
projects.<projectKey>.retry → that project's policy
agents.<agentKey>.retry → that agent's policy
server.retry → the deployment default
otherwise → nil = retry OFF (the default; retry never
turns itself on for a config that never
mentioned it)
The NEAREST layer that says anything wins WHOLESALE: a layer never merges field by field with the one below it, so "half a policy" (one layer's max_attempts with another's backoff table or exit-code filter) cannot be expressed or accidentally inherited. That is also why `max_attempts: 1` at a nearer layer is final — it is the layer's whole answer, not a field an outer layer may top up. A nil pointer at a layer means "this layer says nothing".
agentKey is the RESOLVED agent of the job (a role/template-filled agent resolves on the agent that actually runs), mirroring EffectiveStallTimeoutSec.
func (*Config) EffectiveRules ¶
func (c *Config) EffectiveRules(projectKey, agentKey string, requested []string, disable bool, agentType string) []string
EffectiveRules resolves the MANDATORY rule set bound to one job (JOB-06①, design §一.2): the union of the four binding levels, in the order they are accumulated —
server.rules → the deployment's discipline agents.<agentKey>.rules → this agent's own constraints projects.<projectKey>.rules → this repository's conventions the request's --rule names → this one job
— deduplicated keeping FIRST-appearance order. This is the same function shape as EffectiveSkills (and for the same reason): a rule is accumulated, not a mutually-exclusive policy, so a nearer layer must not be able to unhook a broader one. The repository's own `.gofer/RULES.md` is NOT resolved here: it is a file the job service reads from the project checkout and appends AFTER these bindings as `project:<key>` (it needs the project's exec path, which this package does not resolve).
The two off switches mirror EffectiveSkills:
disable (the request's --no-rules) → nil: an explicit "this job gets no rules" wins over every configured level. Only a user caller may set it (design 决策 4): the HTTP layer refuses a job credential that tries. agentType == "exec" → nil: an exec agent runs a caller-supplied command and has no prompt to inject into, so binding rules to it is meaningless.
A projectKey or agentKey the config does not define is normal, not an error (the worker side of a POLICY-pushed config, or the built-in local runner): the levels that DO exist still apply. Blank/whitespace-only names are dropped, and the result is nil when nothing at all is configured, without allocating — this runs on every submit and the overwhelmingly common answer is "no rules".
func (*Config) EffectiveRulesMaxBytes ¶
EffectiveRulesMaxBytes is the total-rule-text cap for one job (server.rules_max_bytes), with DefaultRulesMaxBytes as the shipped default. 0 (or an absent block) reads as "unset" — the way every other cap in gofer's config behaves — and a negative value is treated as unset too rather than as "reject everything". Read per submit, so a hot edit applies to the NEXT job.
func (*Config) EffectiveSessionOfflineAfterSec ¶
EffectiveSessionOfflineAfterSec resolves the offline threshold in seconds; 0 (or a negative value) disables the sweep.
func (*Config) EffectiveSessionProgressIntervalSec ¶
EffectiveSessionProgressIntervalSec resolves the PostToolUse progress throttle.
func (*Config) EffectiveSessionRelayAutoWaitSec ¶
EffectiveSessionRelayAutoWaitSec resolves session.relay_auto_wait_sec (0 = no cap).
func (*Config) EffectiveSessionRelayOnWaitSec ¶
EffectiveSessionRelayOnWaitSec resolves session.relay_on_wait_sec (0 = no cap).
func (*Config) EffectiveSessionStopJobWait ¶ added in v0.158.0
EffectiveSessionStopJobWait resolves session.stop_job_wait. An unset OR unrecognised value means StopJobWaitAway: the old "always block" behaviour is the one that costs a person their terminal, so a typo must not restore it.
func (*Config) EffectiveSessionSupervisingWindowSec ¶
EffectiveSessionSupervisingWindowSec resolves the gate's look-back window in seconds; 0 = no window (every live job of the caller counts).
func (*Config) EffectiveSessionTakeoverAliveSec ¶
EffectiveSessionTakeoverAliveSec resolves the window in seconds; 0 = guard off.
func (*Config) EffectiveSessionTakeoverInputDelayMs ¶
EffectiveSessionTakeoverInputDelayMs resolves path B's quiet window in milliseconds (see SessionConfig.TakeoverInputDelayMs).
func (*Config) EffectiveSkills ¶
func (c *Config) EffectiveSkills(projectKey, agentKey string, requested []string, disable bool, agentType string) []string
EffectiveSkills resolves the skill set bound to one job (JOB-10, design §一.3): the union of the four binding levels, in the order they are accumulated —
server.skills → the deployment's house rules agents.<agentKey>.skills → this agent's own quirks projects.<projectKey>.skills → this repository's conventions the request's --skill names → this one job
— deduplicated keeping FIRST-appearance order. The order is what the mounted skill list, the prompt's skill section and `job show`'s `skills:` line all present, and it puts the broadest-scope knowledge first: a reader (human or agent) meets the house rules before the job's own.
It is a UNION, deliberately unlike the nearest-layer-wins resolvers next to it (EffectiveRetryPolicy, AgentFallbacksFor, EffectiveApproval). Those resolve a mutually exclusive POLICY, where a nearer layer must be able to say "not this"; skills are additive knowledge, so an agent adding its own skill must not silently unhook the project's. The single off switches are the two below.
Two of the five arguments are off switches, and both return nil rather than an empty slot in the list:
disable (the request's --no-skills) → nil: an explicit "this job reads nothing" must win over every configured level, including the request's own --skill names. agentType == "exec" → nil: an exec agent runs a command; it has no notion of reading a document, so binding skills to it is meaningless.
agentType is passed in rather than looked up here because the caller resolves the agent (role/template/alias) through agent.ResolveAgent, which imports this package.
A projectKey or agentKey the config does not define is normal, not an error: it is the worker side of a POLICY-pushed config, or simply the built-in local runner — the levels that DO exist still apply. Blank/whitespace-only names are dropped (a yaml list of empty strings means "nothing", not a skill called ""), and the result is nil when nothing at all is configured, without allocating: this is called on every submit and the overwhelmingly common answer is "no skills".
func (*Config) EffectiveStallTimeoutSec ¶
func (c *Config) EffectiveStallTimeoutSec(agentKey, agentType string, requested *int, interactive bool) int
EffectiveStallTimeoutSec resolves the AUTO-05 output-stall window in seconds for a job, or 0 for "do not watch it":
interactive job → 0 (a human drives it; silence is normal) request (--stall-timeout) → its value, 0 turning the watchdog off agents.<key>.stall_timeout_sec → its value, 0 turning the watchdog off agentType == "exec" → 0 (builds and test suites are silent by nature) server.stall_timeout_sec → its value, 0 turning the watchdog off otherwise → DefaultStallTimeoutSec
agentType comes from agent.ResolveAgent at the call site (this package cannot import internal/agent without a cycle), and agentKey is the RESOLVED agent of the job so a role/template-filled agent is resolved on the agent that actually runs.
func (*Config) EffectiveVerifyTimeoutSec ¶
EffectiveVerifyTimeoutSec resolves the deadline of a job's verify step for a project: the project's verify_timeout_sec, else the default. A key the config does not define (a worker-only project) resolves the default too — the step never ends instantly for lack of a row.
func (*Config) EventHook ¶ added in v0.140.0
func (c *Config) EventHook(name string) (EventHookConfig, bool)
EventHook returns the configured hook with the given name.
func (*Config) ExecPath ¶
func (c *Config) ExecPath(p ProjectConfig) string
ExecPath returns the GOFER-PROCESS execution-root path for a project — the single source of truth every gofer-side path helper resolves against (E29/D10): when server.path_view is "container" AND the project sets a container_path, that container path is used; otherwise host_path. Default (path_view unset/"host") => host_path, so all existing execution behaviour is unchanged (D9).
NOTE: E21 host-side actions (which run on the host bridge) always use host_path directly and must NOT route through ExecPath.
func (*Config) InjectedAgents ¶
InjectedAgents returns a copy of the runtime-injected agent keys (nil if none). These keys are NOT operator configuration and must never be persisted.
func (*Config) InjectedProjects ¶
InjectedProjects returns a copy of the injected project keys (nil if none).
func (*Config) IsInjectedAgent ¶
IsInjectedAgent reports whether key was materialized from a built-in template rather than declared by the operator.
func (*Config) IsInjectedProject ¶
IsInjectedProject reports whether key is a built-in project the operator did not declare.
func (*Config) JobRecoverWindow ¶
JobRecoverWindow resolves the RECOV-01 recovery window (design §一). Unset (nil) → DefaultJobRecoverWindowSec; an explicit value ≤ 0 → 0, meaning recovery is OFF and a worker disconnect fails its in-flight jobs immediately (the pre-RECOV-01 behaviour). It is the ONE resolver every consumer (hub, serve orphan reconciliation) reads, so the "unset vs 0" distinction lives in a single place instead of being re-derived from a raw int.
func (*Config) LeaderConfig ¶
func (c *Config) LeaderConfig() *LeaderConfig
LeaderConfig returns the top-level leader block, or nil when it is absent — the single nil-safe accessor every reader uses.
func (*Config) LeaderEnabled ¶
LeaderEnabled reports whether the leader round is switched on.
func (*Config) LoadWarnings ¶ added in v0.165.0
LoadWarnings returns the notices collected while decoding the config file(s): retired sections that are ignored. Runtime-only (never written back to the file); nil when there is nothing to report. The returned slice is a copy.
func (*Config) MCPBoundBy ¶ added in v0.144.0
MCPBoundBy reports where registry entry name is bound: server.mcp, and the agents and projects listing it (sorted).
func (*Config) MarkInjectedAgents ¶
MarkInjectedAgents records which Agents keys were materialized at runtime from a built-in template. A nil/empty set clears the mark. agent.Resolve is the only intended caller; it is exported solely because the templates live in another package.
func (*Config) MarkServeRuntimeOverrides ¶
func (c *Config) MarkServeRuntimeOverrides(before ServerConfig)
MarkServeRuntimeOverrides records exactly what mergeServeOpts changed. Save restores these values only while they still match the runtime application; an explicit edit to a different value remains an authored change.
func (*Config) MetricsExposureWarning ¶ added in v0.176.0
MetricsExposureWarning explains why /metrics is readable by anyone who can reach the server: it is enabled, needs no token and server.addr is not a loopback address. The series carry caller / project / agent / runner labels. "" = nothing to warn about.
func (*Config) MutateProjects ¶
func (c *Config) MutateProjects(mut func(map[string]ProjectConfig) error) error
MutateProjects runs a project write on c.Projects (the seam every project add / remove goes through) and then settles the injected marks: an injected project whose entry the write changed is now operator-authored, so it is unmarked and a save writes it into the file ("保存后写入配置成为声明项目"); an unchanged one stays built in. Deleting an injected project is refused — it would only reappear on the next reload.
func (*Config) PolicyRepush ¶
PolicyRepush resolves the finite retry policy used by the worker hub.
func (*Config) PriceFor ¶ added in v0.146.0
func (c *Config) PriceFor(model string) (ModelPrice, bool)
PriceFor finds model's price: an exact key first, else the longest matching glob pattern (`claude-sonnet-*`). Matching is case-insensitive.
func (*Config) ProjectAllowedAgents ¶
ProjectAllowedAgents returns the allowed_agents list for projectKey. The second return is false when the project is not registered. Used by the agent package to enforce the per-project allowlist (plan §11).
func (*Config) ProjectForPath ¶
ProjectForPath resolves cwd to the project whose execution-root (ExecPath) it falls under — the standalone-only fallback source for `--project auto` when the dir has no `.gofer.project.yaml` key: (xu64.15). A project matches when cwd equals its ExecPath or sits below it; on multiple matches the LONGEST prefix wins (nested projects), and two equal-length matches are ambiguous → ("", false) so the caller errors rather than guessing. No match → ("", false). Projects with an empty/"." ExecPath are skipped. The tie test is independent of map iteration order (a strictly-longer match resets any earlier tie).
Note: cfg.Projects is map[string]ProjectConfig, so the key is the map key (ProjectConfig itself carries no Key field). ExecPath honours server.path_view (host_path by default, container_path under path_view=container), matching the path view the rest of the gofer process uses (G002).
func (*Config) ProjectMatchForPath ¶
ProjectMatchForPath is ProjectForPath plus the matched project's exec root (the longest path prefix that decided the match), for messages that must say WHY a directory belongs to a project.
func (*Config) ResolveDBPath ¶
ResolveDBPath returns the SQLite metadata db path. Resolution order (design §11):
- an explicit Storage.DBPath;
- <Storage.Root>/gofer.db when Root is set;
- <config-dir>/gofer.db otherwise.
It is a single global db (one file per bridge process), independent of the per-project log result dirs.
func (*Config) ResolveDBPathChecked ¶
func (*Config) ResolveSecretValue ¶ added in v0.152.0
ResolveSecretValue reads a secret's value from this process's environment. The error names the variable, never a value.
func (*Config) ResolveStorageRoot ¶
func (*Config) ResolveWorkerDBPath ¶
ResolveWorkerDBPath returns a ws-worker's SQLite metadata db path. It mirrors ResolveDBPath but is namespaced by workerID so a worker never collides on a single gofer.db when it shares a config dir with a serve (or with other workers — each gets its own id-named file). Resolution order:
- an explicit Storage.DBPath;
- <Storage.Root>/<workerID>.db when Root is set;
- <config-dir>/worker/<workerID>.db otherwise.
So both the bare default and an explicit Root=<config-dir>/worker converge on <config-dir>/worker/<workerID>.db. jobstore.Open MkdirAll's the parent dir.
func (*Config) ResolvedExchangeSubdir ¶
func (c *Config) ResolvedExchangeSubdir(p ProjectConfig) string
ResolvedExchangeSubdir returns the effective exchange subdir for a project, falling back to the storage default (or the hard default) when unset.
func (*Config) ResolvedResultSubdir ¶
func (c *Config) ResolvedResultSubdir(p ProjectConfig) string
ResolvedResultSubdir returns the effective result subdir for a project, falling back to the storage default (or the hard default) when unset.
func (*Config) SectionFile ¶ added in v0.142.0
SectionFile returns the absolute file holding top-level section key: its fragment, or the main file (also for a section the config does not have yet — that is where a new section is written).
func (*Config) SectionSources ¶ added in v0.142.0
SectionSources maps each top-level section of a split config to the file holding it, as a path relative to the main file's directory. Nil for a one-file config.
func (*Config) SourceFiles ¶ added in v0.142.0
SourceFiles lists the files the config was read from: the main file first, then the included fragments in load order. A config loaded from one file reports just that file; one that was never loaded from disk reports none.
func (*Config) UnmarkInjectedAgent ¶
UnmarkInjectedAgent clears the runtime-injected mark of ONE key, so a definition the operator has just written for that key is treated as configuration and survives the save (config.writer's withoutInjectedAgents strips every marked key).
It is the "declare it explicitly" half of the template escape hatch: editing `claude` from the console must produce a `claude:` block in the file, not a write that looks successful and is stripped again. Only the config write API calls it, on the CLONE it owns.
func (*Config) ValidateDelivery ¶ added in v0.146.0
ValidateDelivery checks every project's delivery block.
func (*Config) ValidateLocalPaths ¶
ValidateLocalPaths checks only paths owned by the local server. It does not rewrite the Config, so Save and the config write API retain authored templates.
func (*Config) ValidateMCPServers ¶ added in v0.144.0
ValidateMCPServers checks the registry and every binding list that names it.
func (*Config) ValidatePricing ¶ added in v0.146.0
ValidatePricing checks the price table.
func (*Config) ValidateSecrets ¶ added in v0.152.0
ValidateSecrets checks the registry and every project allowlist that names it.
type DecisionHookConfig ¶ added in v0.149.0
type DecisionHookConfig struct {
// Name identifies the hook in decisions, events and logs. Required, unique.
Name string `yaml:"name"`
// Points lists the decision points the hook answers. Required.
Points []string `yaml:"points"`
// Command is the argv to run (no shell). Required.
Command []string `yaml:"command"`
// Projects filters the project keys; empty = all projects.
Projects []string `yaml:"projects,omitempty"`
// Dir is the working directory (same rules as an event hook's dir).
Dir string `yaml:"dir,omitempty"`
// Env is layered over the filtered serve environment; values never appear in an
// API view.
Env map[string]string `yaml:"env,omitempty"`
// TimeoutSec bounds one run; 0 = DefaultDecisionHookTimeoutSec, max MaxDecisionHookTimeoutSec.
TimeoutSec int `yaml:"timeout_sec,omitempty"`
// OnError decides what a failed run (cannot start, timeout, non-zero exit,
// unreadable answer, a change it may not make) means: deny (default) or allow.
OnError string `yaml:"on_error,omitempty"`
// IncludeInternal also asks the hook about gofer's own internal jobs (delivery,
// tracker sync, summarizer, steward…), which are skipped by default so that one
// broken rule cannot stop gofer's own machinery.
IncludeInternal bool `yaml:"include_internal,omitempty"`
// Enabled pauses the hook without deleting it (nil = on).
Enabled *bool `yaml:"enabled,omitempty"`
}
DecisionHookConfig is one server.decision_hooks entry. Like event hooks it runs a command on the server host, so it is FILE-ONLY: the config write API refuses `server.decision_hooks` and read views never echo Env values.
func (DecisionHookConfig) EffectiveDir ¶ added in v0.149.0
func (h DecisionHookConfig) EffectiveDir() string
EffectiveDir resolves the working directory like an event hook's.
func (DecisionHookConfig) EffectiveOnError ¶ added in v0.149.0
func (h DecisionHookConfig) EffectiveOnError() string
EffectiveOnError is on_error after defaulting (deny).
func (DecisionHookConfig) EffectiveTimeout ¶ added in v0.149.0
func (h DecisionHookConfig) EffectiveTimeout() time.Duration
EffectiveTimeout is the per-run timeout after defaulting.
func (DecisionHookConfig) EnvKeys ¶ added in v0.149.0
func (h DecisionHookConfig) EnvKeys() []string
EnvKeys returns the env variable names, sorted.
func (DecisionHookConfig) IsEnabled ¶ added in v0.149.0
func (h DecisionHookConfig) IsEnabled() bool
IsEnabled reports whether the hook is active (nil/absent = on).
type DeliveryConfig ¶ added in v0.146.0
type DeliveryConfig struct {
// Mode: none (default) | merge | push | pr. A job may override it (--deliver).
Mode string `yaml:"mode,omitempty" json:"mode,omitempty"`
// AllowPush permits pushing (push / pr, and merge's push_base). Only here — a
// job cannot grant it to itself.
AllowPush bool `yaml:"allow_push,omitempty" json:"allow_push,omitempty"`
// Remote to push to; "" = origin.
Remote string `yaml:"remote,omitempty" json:"remote,omitempty"`
// Branch is the pushed branch name template: {{job_id}} {{short_id}} {{slug}};
// "" = gofer/{{job_id}}.
Branch string `yaml:"branch,omitempty" json:"branch,omitempty"`
// Base is the merge / PR target branch; "" = the main checkout's branch.
Base string `yaml:"base,omitempty" json:"base,omitempty"`
// Draft opens the request as a draft (default true).
Draft *bool `yaml:"draft,omitempty" json:"draft,omitempty"`
// Squash merges as one commit (merge mode).
Squash bool `yaml:"squash,omitempty" json:"squash,omitempty"`
// PushBase pushes the base branch after a merge (needs AllowPush).
PushBase bool `yaml:"push_base,omitempty" json:"push_base,omitempty"`
// Cleanup removes the worktree after a successful delivery.
Cleanup bool `yaml:"cleanup,omitempty" json:"cleanup,omitempty"`
// Labels for the request (where the platform supports them).
Labels []string `yaml:"labels,omitempty" json:"labels,omitempty"`
// Provider: auto (default) | github | gitlab | gitea (Forgejo too).
Provider string `yaml:"provider,omitempty" json:"provider,omitempty"`
// TokenEnv names the environment variable holding the platform token on the
// machine that delivers; "" = the provider's defaults.
TokenEnv string `yaml:"token_env,omitempty" json:"token_env,omitempty"`
// Proxy (http://, https://, socks5://) carries the push and the platform API calls
// of a delivery, for a machine that reaches the platform only through a proxy.
// "" = git's own http.proxy for the remote, then the proxy environment variables.
Proxy string `yaml:"proxy,omitempty" json:"proxy,omitempty"`
// JobLink adds the job's web console link (server.web_base_url) to the request
// body. Off by default: the console is usually on a private address, and the
// request may be public.
JobLink bool `yaml:"job_link,omitempty" json:"job_link,omitempty"`
}
DeliveryConfig is a project's delivery of worktree jobs (GIT-02, design 2026-10-12-delivery-and-cost-estimate-design.md).
func (DeliveryConfig) IsDraft ¶ added in v0.146.0
func (d DeliveryConfig) IsDraft() bool
IsDraft is Draft with its default (true).
type DetectConfig ¶
type DetectConfig struct {
Command string `yaml:"command,omitempty"`
Args []string `yaml:"args,omitempty"`
}
DetectConfig is the agent availability probe. Placeholder in P2, refined P3.
type EventHookConfig ¶ added in v0.140.0
type EventHookConfig struct {
// Name identifies the hook; deliveries target "hook:<name>". Required, unique.
Name string `yaml:"name"`
// Command is the argv to run (no shell). Required.
Command []string `yaml:"command"`
// Events filters the event types; empty = the webhook default trigger set,
// ["*"] = every event.
Events []string `yaml:"events,omitempty"`
// Projects filters the project keys; empty = all projects (an event without a
// project only matches an empty filter).
Projects []string `yaml:"projects,omitempty"`
// Dir is the working directory; empty = the gofer config directory. A relative
// dir is resolved against the config directory.
Dir string `yaml:"dir,omitempty"`
// Env is layered over the filtered serve environment. Values may be secrets, so
// no API view ever shows them (keys only).
Env map[string]string `yaml:"env,omitempty"`
// TimeoutSec bounds one run; 0 = DefaultEventHookTimeoutSec, max MaxEventHookTimeoutSec.
TimeoutSec int `yaml:"timeout_sec,omitempty"`
// MaxAttempts caps the runs per event (first included); 0 = DefaultEventHookMaxAttempts.
MaxAttempts int `yaml:"max_attempts,omitempty"`
// Enabled pauses the hook without deleting it (nil = on).
Enabled *bool `yaml:"enabled,omitempty"`
}
EventHookConfig is one server-side event hook (AUTO-04): when a matching event happens, gofer runs Command on the server host with the generic webhook JSON body on stdin. It is a read-only side channel — the command's output never flows back into gofer — and, because it executes a command on the server, it can only be changed in the config file: the config write API refuses `server.event_hooks` (see fieldPolicies) and read views never echo Env values.
func (EventHookConfig) EffectiveDir ¶ added in v0.140.0
func (h EventHookConfig) EffectiveDir() string
EffectiveDir resolves the hook's working directory: its own dir (relative = under the gofer config directory), else the config directory itself, else "" (the serve process's cwd) when that directory does not exist.
func (EventHookConfig) EffectiveMaxAttempts ¶ added in v0.140.0
func (h EventHookConfig) EffectiveMaxAttempts() int
EffectiveMaxAttempts is the attempt cap after defaulting.
func (EventHookConfig) EffectiveTimeout ¶ added in v0.140.0
func (h EventHookConfig) EffectiveTimeout() time.Duration
EffectiveTimeout is the per-run timeout after defaulting.
func (EventHookConfig) EnvKeys ¶ added in v0.140.0
func (h EventHookConfig) EnvKeys() []string
EnvKeys returns the hook's env variable names, sorted (the only part of Env a read view may show).
func (EventHookConfig) IsEnabled ¶ added in v0.140.0
func (h EventHookConfig) IsEnabled() bool
IsEnabled reports whether the hook is active (nil/absent = on).
func (EventHookConfig) Target ¶ added in v0.140.0
func (h EventHookConfig) Target() string
Target is the delivery target a row for this hook carries.
type FieldPolicy ¶
type FieldPolicy struct {
// Editable: PUT accepts this field.
Editable bool
// RestartRequired: the value is read once at process start (the listen address,
// the storage root) or is secret material, so it can neither be applied by
// Core.Update's hot reload nor safely round-tripped through a request body. It is
// therefore NOT editable through the API and the console shows it as disabled.
// This is the CONSERVATIVE class: a field that is simply not part of the V1.1
// whitelist is classified here rather than guessed at, because "the console says
// 需重启 for something that in fact reloads" costs a needless restart while the
// reverse costs a silent no-op edit.
RestartRequired bool
// HotReload means the running process applies changes on reload, while the
// field remains outside the console write whitelist (for example worker
// bindings contain credential-bearing configuration).
HotReload bool
// SecretRef: the field holds the NAME of an environment variable that carries the
// secret (`token_env`), never the value itself. The distinction is what lets a
// `*_env` name be shown and named while a literal is refused outright.
SecretRef bool
}
FieldPolicy is one config field's write contract for the console (WEB-04③ V1.1, design §一.3): whether the write endpoints accept it, whether a change needs a process restart, and whether the field is a secret REFERENCE (an env-var name) rather than a value.
ONE table, two consumers: the write endpoint refuses a field whose policy is not Editable with `field not editable: <path>`, and GET /v1/config publishes the same table so the console can disable those inputs and badge them. Two hand-maintained lists would drift, and the drift is invisible until an operator edits a field the server then refuses (or, worse, accepts and cannot apply).
func FieldPolicyFor ¶
func FieldPolicyFor(path string) (FieldPolicy, bool)
FieldPolicyFor resolves a dotted config path to its policy. A path that resolves to no entry is a MISS (ok=false) — never a silent "not editable" default, because the write endpoint must be able to tell "you cannot change this" from "there is no such field", and the console from "not classified yet" from "classified read-only".
The agent key is a wildcard: `agents.claude.command` and `agents.*.command` are the same lookup, and a nested path (`agents.claude.acp.modes`) resolves through its longest known prefix (`agents.*.acp`). Caller ids are a wildcard the same way (`server.callers.ci.ceiling` → `server.callers.*.ceiling`), because a caller entry is an operator-chosen key like an agent name.
type GovernanceConfig ¶
type GovernanceConfig struct {
// DefaultCallerMaxConcurrent caps how many jobs a caller may run at once when
// the caller has no own MaxConcurrentJobs. 0 = unlimited.
DefaultCallerMaxConcurrent int `yaml:"default_caller_max_concurrent,omitempty"`
// DefaultRateLimit is the per-second submit rate (token-bucket refill) when the
// caller has no own RateLimit. 0 = unlimited (no rate gating).
DefaultRateLimit float64 `yaml:"default_rate_limit,omitempty"`
// DefaultRateBurst is the token-bucket capacity when the caller has no own
// RateBurst. <= 0 falls back to max(1, ceil(rate)) at use time (CallerRate).
DefaultRateBurst int `yaml:"default_rate_burst,omitempty"`
// RequireAnswerCapability gates interaction answer/punt to callers with
// can_answer:true. false = any authenticated caller may answer (legacy).
//
// DEPRECATED(v0.161): remove in v0.164. The switch only exists while the old
// capability bits do; grant the answer permissions on the web instead and leave
// the switch on (the recommended style: switches on, everything else on the web).
RequireAnswerCapability bool `yaml:"require_answer_capability,omitempty"`
// RequireAdminCapability gates config/project edits to callers with
// can_admin:true. false = any authenticated caller may edit config (legacy).
//
// DEPRECATED(v0.161): remove in v0.164. Root administrators keep the admin
// permissions whatever this switch says, so setting it only matters to the
// capability bits it gates.
RequireAdminCapability bool `yaml:"require_admin_capability,omitempty"`
// RequireAttachCapability gates interactive attach to callers with
// can_attach:true. false = any authenticated caller may attach (legacy).
//
// DEPRECATED(v0.161): remove in v0.164. Grant `job.attach` on the web instead.
RequireAttachCapability bool `yaml:"require_attach_capability,omitempty"`
// RequireTunnelCapability gates tunnels to callers with can_tunnel:true.
//
// DEPRECATED(v0.161): remove in v0.164. Grant `tunnel.open` on the web instead.
RequireTunnelCapability bool `yaml:"require_tunnel_capability,omitempty"`
// AttachOrigins is the Origin allowlist for attach websocket requests.
AttachOrigins []string `yaml:"attach_origins,omitempty"`
}
GovernanceConfig is the E17 global fallback for per-caller quotas (design §7.1). It applies to a caller only when that caller has not set its own override (CallerConfig.MaxConcurrentJobs / RateLimit). All fields default to 0 = unlimited, so a config with no `governance` block keeps the legacy no-throttle behaviour.
type HTTPProxyConfig ¶ added in v0.154.5
type HTTPProxyConfig struct {
// ProxyURL is an http, https or socks5 URL; "" = off.
ProxyURL string `yaml:"proxy_url,omitempty"`
// AllowSites are the hosts that use the proxy: "example.com" matches it and its
// subdomains, "*.example.com" only the subdomains, "*" every host. Empty = every
// host.
AllowSites []string `yaml:"allow_sites,omitempty"`
}
HTTPProxyConfig is the server's outbound proxy (http_proxy): requests to an allowed site go through ProxyURL, everything else keeps the proxy environment variables (HTTPS_PROXY / NO_PROXY). It covers what the server fetches itself — release checks and downloads, skill imports, notification webhooks, Web Push, delivery APIs; a more specific setting (server.update.proxy, a delivery proxy) still wins. File-only: it decides where the server's traffic goes.
func (HTTPProxyConfig) Enabled ¶ added in v0.154.5
func (p HTTPProxyConfig) Enabled() bool
Enabled reports whether a proxy URL is configured.
func (HTTPProxyConfig) Matches ¶ added in v0.154.5
func (p HTTPProxyConfig) Matches(host string) bool
Matches reports whether host (with or without a port) uses the proxy.
func (HTTPProxyConfig) Parsed ¶ added in v0.154.5
func (p HTTPProxyConfig) Parsed() *url.URL
Parsed is ProxyURL as a URL (nil when off or invalid; validate rejects invalid).
type HoldConfig ¶ added in v0.137.0
type HoldConfig struct {
// DefaultTimeoutSec is the hold timeout of a request that names none
// (0/unset => DefaultHoldTimeoutSec).
DefaultTimeoutSec int `yaml:"default_timeout_sec,omitempty"`
// MaxTimeoutSec is the largest hold timeout a request may ask for
// (0/unset => DefaultHoldMaxTimeoutSec). A request above it is refused, never
// silently shortened.
MaxTimeoutSec int `yaml:"max_timeout_sec,omitempty"`
}
HoldConfig is the server.hold block. Zero/unset fields take the defaults above. Both are read per submit (EffectiveHoldTimeoutSec), so a reload applies to the NEXT held job; a job already waiting keeps the deadline fixed when it was submitted.
type LeaderConfig ¶
type LeaderConfig struct {
Enabled bool `yaml:"enabled,omitempty"`
// Agent is the agent (or role) a leader job runs as. Required when enabled.
Agent string `yaml:"agent,omitempty"`
// Scopes lists the comment/plan scopes the leader round runs on. Only "plan" is
// implemented in this phase; an empty list means ["plan"].
Scopes []string `yaml:"scopes,omitempty"`
// OnMemberDone arms the wake on a member job's FINISHED state. It is a POINTER so
// "unset" can default to true: `enabled: true` alone must wake on reports, and an
// explicit `on_member_done: false` is what turns the trigger off.
OnMemberDone *bool `yaml:"on_member_done,omitempty"`
// WakeDelaySec is the window between a member's terminal state and the leader job
// starting: the time a human gets to step in (a user comment inside it cancels the
// round). Unset/<=0 => DefaultLeaderWakeDelaySec (30s).
WakeDelaySec int `yaml:"wake_delay_sec,omitempty"`
// MaxRoundsPerScope caps how many leader jobs one plan may start. Reaching it stops
// the waking and escalates to a human (`plan.leader_exhausted` + a plan decision).
// Unset/<=0 => DefaultLeaderMaxRounds.
MaxRoundsPerScope int `yaml:"max_rounds_per_scope,omitempty"`
}
LeaderConfig is the top-level `leader` block (MCP-05 阶段 B, design §二.B). The leader is a normal job (usage, timeout, AUTO-03 all apply) that may only act through its (whitelisted) MCP tools: comment / move a todo to ready|skipped / arm a wakeup / ask a human. It can never accept or reject — 人工验收 stays a human's call.
The zero value is inert: enabled=false. Every other field has a documented default resolved by the accessors below (so an operator can write just `enabled: true` + `agent:`).
func (*LeaderConfig) MaxRounds ¶
func (l *LeaderConfig) MaxRounds() int
MaxRounds resolves max_rounds_per_scope (<=0/absent => the 6 default).
func (*LeaderConfig) MemberDoneWakes ¶
func (l *LeaderConfig) MemberDoneWakes() bool
MemberDoneWakes reports whether a member job's finished state arms a wake (the on_member_done trigger; unset means yes).
func (*LeaderConfig) ScopeEnabled ¶
func (l *LeaderConfig) ScopeEnabled(scope string) bool
ScopeEnabled reports whether this scope runs leader rounds (an empty scopes list means "plan only", the one scope implemented so far).
func (*LeaderConfig) WakeDelay ¶
func (l *LeaderConfig) WakeDelay() time.Duration
WakeDelay resolves wake_delay_sec (<=0/absent => the 30s default).
type LogConfig ¶
type LogConfig struct {
File string `yaml:"file,omitempty"`
Dir string `yaml:"dir,omitempty"`
MaxSizeMB int `yaml:"max_size_mb,omitempty"`
MaxAgeDays int `yaml:"max_age_days,omitempty"`
MaxBackups int `yaml:"max_backups,omitempty"`
}
LogConfig controls the optional rotating JSONL sink.
type MCPServerConfig ¶ added in v0.144.0
type MCPServerConfig struct {
// Desc is a one-line description shown in lists.
Desc string `yaml:"desc,omitempty" json:"desc,omitempty"`
// Type is stdio (default) or http.
Type string `yaml:"type,omitempty" json:"type,omitempty"`
// Command / Args / Env start a stdio server. Args may reference a secret_env
// variable as {{env:NAME}}.
Command string `yaml:"command,omitempty" json:"command,omitempty"`
Args []string `yaml:"args,omitempty" json:"args,omitempty"`
Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"`
// URL / Headers reach an http server. URL may reference {{env:NAME}} as well.
URL string `yaml:"url,omitempty" json:"url,omitempty"`
Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`
// SecretEnv maps a variable the MCP process sees to the environment variable the
// value is read from (on the executing machine). SecretHeaders does the same for
// http headers.
SecretEnv map[string]string `yaml:"secret_env,omitempty" json:"secret_env,omitempty"`
SecretHeaders map[string]string `yaml:"secret_headers,omitempty" json:"secret_headers,omitempty"`
// Tools optionally limits the tools an agent may call (agents that can express it).
Tools []string `yaml:"tools,omitempty" json:"tools,omitempty"`
// Enabled pauses the entry without deleting it (nil = on). A disabled entry is
// skipped wherever it is bound.
Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`
}
MCPServerConfig is one registry entry.
func (MCPServerConfig) EffectiveType ¶ added in v0.144.0
func (m MCPServerConfig) EffectiveType() string
EffectiveType is Type with the stdio default applied.
func (MCPServerConfig) IsEnabled ¶ added in v0.144.0
func (m MCPServerConfig) IsEnabled() bool
IsEnabled reports whether the entry is on.
func (MCPServerConfig) SecretVars ¶ added in v0.144.0
func (m MCPServerConfig) SecretVars() []string
SecretVars lists the environment variables the entry reads its secrets from, sorted and deduplicated.
type MailAgentConfig ¶ added in v0.185.0
type MailAgentConfig struct {
// Agent is the agent definition the resident session runs (`acp-agent` only).
Agent string `yaml:"agent,omitempty"`
// Args are extra args appended to the agent's own argv.
Args []string `yaml:"args,omitempty"`
// Runner is the job runner; empty = the project's default runner.
Runner string `yaml:"runner,omitempty"`
// IdleMinutes ends the session after that much idle time (default 120; 0 = default).
IdleMinutes int `yaml:"idle_minutes,omitempty"`
// MaxLetters rotates the session after that many letters (default 50; 0 = 不限).
MaxLetters *int `yaml:"max_letters,omitempty"`
// MaxHours rotates the session after that many hours (default 24; 0 = 不限).
MaxHours *int `yaml:"max_hours,omitempty"`
// Prompt is appended to gofer's own opening prompt (optional).
Prompt string `yaml:"prompt,omitempty"`
}
MailAgentConfig is one 收件 agent of the `mail.agents.<名字>` block.
The resident session is an ACP continuous session job (`--session`), so the agent it names has to be an acp-agent; anything else cannot be sent a letter programmatically.
func (MailAgentConfig) EffectiveIdle ¶ added in v0.185.0
func (a MailAgentConfig) EffectiveIdle() time.Duration
EffectiveIdle is idle_minutes with the default applied.
func (MailAgentConfig) EffectiveMaxHours ¶ added in v0.185.0
func (a MailAgentConfig) EffectiveMaxHours() int
EffectiveMaxHours is max_hours (a nil member = default; an explicit 0 = unlimited).
func (MailAgentConfig) EffectiveMaxLetters ¶ added in v0.185.0
func (a MailAgentConfig) EffectiveMaxLetters() int
EffectiveMaxLetters is max_letters (a nil member = default; an explicit 0 = unlimited).
func (MailAgentConfig) Identity ¶ added in v0.185.0
func (a MailAgentConfig) Identity() string
Identity returns the agent definition key, or "" when the block names none.
type MailConfig ¶ added in v0.174.0
type MailConfig struct {
// TickSec is how often the deliverer sweeps (release expired leases, park overdue
// letters, wake idle sessions, deliver to suga / ACP jobs). Default 30.
TickSec int `yaml:"tick_sec,omitempty"`
// WakeIdleSec is how long a session must have been silent (last_seen_at) before an
// idle / offline session with pending letters is woken. Default 300 (5 minutes).
WakeIdleSec int `yaml:"wake_idle_sec,omitempty"`
// WakeIntervalSec is the minimum gap between two wakes of one session. Default 600.
WakeIntervalSec int `yaml:"wake_interval_sec,omitempty"`
// DeliverBySec is the delivery deadline of NEW letters: past it an undelivered letter
// goes to the capture box. Default 86400 (24 hours).
DeliverBySec int `yaml:"deliver_by_sec,omitempty"`
// ClaimLeaseSec is the lease of the deliverer's claims (suga send / job say): a claim not
// confirmed within it returns to pending. Default 60. Hook claims keep the 60 s default.
ClaimLeaseSec int `yaml:"claim_lease_sec,omitempty"`
// BroadcastMaxRecipients is 单次广播最多收件人数 (设计 2026-10-22「D6」). Default 20.
BroadcastMaxRecipients int `yaml:"broadcast_max_recipients,omitempty"`
// BroadcastRate is 广播频率, "<count>/<window>" (default "5/10m"): each caller may send
// that many broadcasts per window, whatever the recipient count.
BroadcastRate string `yaml:"broadcast_rate,omitempty"`
// Agents is 哪些 agent 能收信 (设计 2026-10-22 mail-agent-address「D2」): the key is the name an
// `agent:<name>` address uses, the value is how its resident session is started.
Agents map[string]MailAgentConfig `yaml:"agents,omitempty"`
// AgentsMaxResident is 全局最多同时存在的常驻会话 (default 6; 0 = default).
AgentsMaxResident int `yaml:"agents_max_resident,omitempty"`
}
MailConfig is the top-level `mail:` block: the gofer 信箱 server deliverer's numbers (design 2026-10-16「默认数值」, plan M5). Every key is optional; 0 / unset takes the documented default, and a negative value is a load error. The deliverer reads them at each reload, so an edit applies without a restart (the tick interval from the sweep after the one in flight).
func (MailConfig) Agent ¶ added in v0.185.0
func (m MailConfig) Agent(name string) (MailAgentConfig, bool)
Agent returns one 收件 agent by name (case-insensitively, like a runner name) and whether it is configured.
func (MailConfig) AgentNames ¶ added in v0.185.0
func (m MailConfig) AgentNames() []string
AgentNames lists the configured 收件 agent names, sorted, so an error can say what is可用.
func (MailConfig) EffectiveAgentsMaxResident ¶ added in v0.185.0
func (m MailConfig) EffectiveAgentsMaxResident() int
EffectiveAgentsMaxResident is agents_max_resident with the default applied.
type MailSettings ¶ added in v0.174.0
type MailSettings struct {
Tick time.Duration
WakeIdle time.Duration
WakeInterval time.Duration
DeliverBy time.Duration
Lease time.Duration
// BroadcastMax / BroadcastRate / BroadcastWindow are the broadcast limits (D6).
BroadcastMax int
BroadcastRate int
BroadcastWindow time.Duration
}
MailSettings is MailConfig resolved to durations.
type MetricsConfig ¶
type MetricsConfig struct {
// Enabled gates the /metrics endpoint. Unset (nil) defaults to true; an
// explicit enabled:false drops the route entirely.
Enabled *bool `yaml:"enabled,omitempty"`
// Token, when non-empty, requires `Authorization: Bearer <token>` on /metrics
// (for environments that want authenticated scraping). Empty = no auth.
Token string `yaml:"token,omitempty"`
}
MetricsConfig is the E16 Prometheus /metrics policy (design §6.2). It is a minimal additive block: an existing config with no `metrics` key keeps the endpoint enabled and unauthenticated (IsEnabled defaults nil→true).
func (MetricsConfig) IsEnabled ¶
func (m MetricsConfig) IsEnabled() bool
IsEnabled reports whether the /metrics endpoint should be mounted. Unset (nil) defaults to true; an explicit enabled:false disables it.
type ModelPrice ¶ added in v0.146.0
type ModelPrice struct {
Input float64 `yaml:"input" json:"input"`
Output float64 `yaml:"output" json:"output"`
CacheRead float64 `yaml:"cache_read,omitempty" json:"cache_read,omitempty"`
CacheWrite float64 `yaml:"cache_write,omitempty" json:"cache_write,omitempty"`
}
ModelPrice is a model's price in USD per million tokens (gofer-2ldy). It turns the token counts of a usage that carries no reported cost — terminal session usage, a job whose agent does not report one — into an estimate. Nothing is built in: prices change, so the operator writes the table for what they use.
func (ModelPrice) Estimate ¶ added in v0.146.0
func (p ModelPrice) Estimate(input, output, cacheRead, cacheWrite int64) float64
Estimate prices token counts (USD).
type NotificationConfig ¶
type NotificationConfig struct {
Webhooks []WebhookConfig `yaml:"webhooks,omitempty"`
// MaxTextRunes is the default rune budget for IM message bodies. Values <= 0
// use DefaultMaxTextRunes; a webhook can override it with its own positive value.
MaxTextRunes int `yaml:"max_text_runes,omitempty"`
// IntervalSec controls the delivery sweep cadence. <=0 keeps the existing
// 15-second default and is read by the serve loop on every timer reset.
IntervalSec int `yaml:"interval_sec,omitempty"`
AllowHosts []string `yaml:"allow_hosts,omitempty"` // outbound host allowlist (SR904)
AllowHTTP bool `yaml:"allow_http,omitempty"` // default false => https-only
MaxAttempts int `yaml:"max_attempts,omitempty"` // <= 0 => DefaultMaxAttempts
// Enabled is the master switch for ALL outbound notification (S4, 2026-09-23).
// A POINTER, nil = on: an operator pausing notification keeps the whole webhook
// list in the file (turning it back on restores it), which deleting the list would
// lose. false suppresses ENQUEUE only — deliveries already queued still drain, so
// pausing cannot strand a row in `pending`.
Enabled *bool `yaml:"enabled,omitempty"`
// SessionReplyDelaySec is the quiet period before a continuous session's
// awaiting_input state creates a notification. Nil uses 120 seconds; zero
// disables this reminder.
SessionReplyDelaySec *int `yaml:"session_reply_delay_sec,omitempty"`
}
NotificationConfig is the E14 webhook outbound policy (design §5.5/§5.7). It holds every configured webhook target plus the shared outbound-safety knobs: AllowHosts is the host allowlist a webhook URL must match, AllowHTTP relaxes the https-only default (for local testing only), and MaxAttempts caps the retry backoff. The delivery sweeper only runs when this is non-nil AND has at least one webhook (see serve startDeliveryLoop).
func (*NotificationConfig) EffectiveMaxAttempts ¶
func (n *NotificationConfig) EffectiveMaxAttempts() int
EffectiveMaxAttempts returns the configured retry cap, defaulting to DefaultMaxAttempts when unset (<= 0).
func (*NotificationConfig) EffectiveMaxTextRunes ¶
func (n *NotificationConfig) EffectiveMaxTextRunes() int
func (*NotificationConfig) EffectiveSessionReplyDelaySec ¶
func (n *NotificationConfig) EffectiveSessionReplyDelaySec() int
func (*NotificationConfig) IsEnabled ¶
func (n *NotificationConfig) IsEnabled() bool
IsEnabled reports whether E14 webhook delivery is on for this notification block (nil/absent = on, matching the pointer's meaning).
type PolicyRepushConfig ¶
type PolicyRepushConfig struct {
TimeoutSec int `yaml:"timeout_sec,omitempty"`
MaxAttempts int `yaml:"max_attempts,omitempty"`
}
PolicyRepushConfig is the server-side Applied acknowledgement retry policy. It is read when the worker hub is assembled, so changing it takes effect on the next server start rather than in the middle of an active retry schedule.
type ProjectConfig ¶
type ProjectConfig struct {
HostPath string `yaml:"host_path,omitempty"`
DirLockMode string `yaml:"dir_lock_mode,omitempty"`
ContainerPath string `yaml:"container_path,omitempty"`
ExchangeSubdir string `yaml:"exchange_subdir,omitempty"`
ResultSubdir string `yaml:"result_subdir,omitempty"`
DefaultAgent string `yaml:"default_agent,omitempty"`
AllowedAgents []string `yaml:"allowed_agents,omitempty"`
// Skills are the skills every job of THIS project mounts (JOB-10 §一.3), unioned
// with server.skills, the agent's own list and the job's `--skill` names. This is
// the level that binds a repository's own conventions ("how to edit files in this
// tree") without every caller repeating them, and it is additive like the other
// levels: a project never REMOVES a server-wide skill (`--no-skills` on the job is
// the only off switch). See Config.EffectiveSkills.
Skills []string `yaml:"skills,omitempty"`
// MCP lists the registry MCP servers this project's jobs get (MCP-06), unioned
// with server.mcp, the agent's list and the job's --mcp names.
MCP []string `yaml:"mcp,omitempty"`
// Secrets lists the secrets (top-level `secrets`) this project's jobs may ask for
// with `job run --secret` (JOB-06②). File-only, like the registry.
Secrets []string `yaml:"secrets,omitempty"`
// Delivery hands a worktree job's branch over once it is done (or accepted):
// merge / push / pull request (GIT-02). nil = never (the default).
Delivery *DeliveryConfig `yaml:"delivery,omitempty"`
// Rules are the MANDATORY rules of THIS project (JOB-06①): the constraints that
// only make sense in this repository (its layout, its test command, its review
// etiquette). Unioned with server.rules, the agent's own list and `--rule`; a
// project never removes a server-wide rule (only `--no-rules` turns them off).
// The repository may also carry `.gofer/RULES.md`, which is auto-included as
// `project:<key>` AFTER these bindings — no registration needed. See
// Config.EffectiveRules.
Rules []string `yaml:"rules,omitempty"`
// TrackerPrime (gofer-krzy) decides which tracker the `tracker-prime` rule a job
// is injected with speaks for, and how far the search for it goes:
//
// - "nearest" (the default): the nearest ancestor `.gofer/tracker`, whatever
// repository it sits in. A workspace's projects are related and share the
// workspace tracker's rules and memories; a nested checkout without a
// tracker of its own uses the workspace's;
// - "repo": the tracker of the git repository the job's cwd belongs to — the
// search never leaves that repository, so a nested checkout without a
// `.gofer/tracker` of its own is injected NOTHING from the outer workspace
// (for the few projects that must stay isolated);
// - "off": no tracker-prime section at all. `gofer repo prime` is unaffected:
// that is an explicit command, not an injection.
//
// Inside the tracker that IS used, memories are selected by the job's cwd exactly
// like the session-opening prime (a rule whose `when.paths` do not cover that cwd
// is not injected in full, and the index lists only memories that apply).
// See EffectiveTrackerPrime.
TrackerPrime string `yaml:"tracker_prime,omitempty"`
// AgentFallbacks overrides an agent's fallback_agents list for THIS project
// (SUP-01 P3): keyed by the failing agent, the value is the ordered candidate
// list. A key present here REPLACES the agent-level list (it does not merge), so
// a project can narrow, reorder or disable (empty list) a transfer per agent.
AgentFallbacks map[string][]string `yaml:"agent_fallbacks,omitempty"`
// AllowInteractive is the project's interactive-job switch (AGT-02 §2) and the
// ONLY project-level gate: the removed legacy narrowing list has no successor, and a
// project that wants to exclude an agent simply gives it no interactive mode. It is a
// pointer so "unset" stays distinguishable from an explicit false: an explicit
// allow_interactive:false must keep interactive jobs rejected, and nil (the zero
// value of a project built in code, e.g. by the worker
// policy projection) reads as false, never as "inherit". See IsInteractiveAllowed.
AllowInteractive *bool `yaml:"allow_interactive,omitempty"`
AllowedRunners []string `yaml:"allowed_runners,omitempty"`
AllowExec bool `yaml:"allow_exec,omitempty"`
// JobEnvAllow names environment variables this project's jobs DO inherit, even
// though the server's denylist (SEC-01, server.job_env_denylist + the built-in
// credential keys) would strip them. It is the one deliberate way to keep the old
// "jobs see the process environment" behaviour for a project — a script that needs
// its own credential must be given one explicitly rather than inheriting the
// server's. Every job that actually keeps such a key records `job.env_allowed`,
// so the allowance is visible on the job rather than only in the config file.
JobEnvAllow []string `yaml:"job_env_allow,omitempty"`
// MaxConcurrentJobs caps this project's simultaneously RUNNING jobs (0 = no cap).
MaxConcurrentJobs int `yaml:"max_concurrent_jobs,omitempty"`
// Budget is the default spend ceiling of every job in THIS project (N2 §B GATE-02),
// layered over the agent's own and under the request's. See Config.EffectiveBudget.
Budget *Budget `yaml:"budget,omitempty"`
// MaxTimeoutSec overrides the job-timeout ceiling for THIS project (bd
// h-aii-s9ck). 0/unset => inherit server.max_job_timeout_sec (or its default);
// a non-zero value REPLACES it in EITHER direction — raising it above the
// server value (one project runs 2h builds without lifting the ceiling for
// everyone) or lowering it (a tenant that must not exceed 10m). See
// Config.EffectiveMaxTimeoutSec, the single source of truth for the resolution.
MaxTimeoutSec int `yaml:"max_timeout_sec,omitempty"`
// CaptureDiff controls E12 git-diff capture (job-outcomes-audit, P3). YAML
// accepts auto (the default, represented by nil), on, and off. The legacy bool
// form remains readable for the G032 migration window: true == on, false == off.
CaptureDiff *bool `yaml:"capture_diff,omitempty"`
// OnUncommitted controls the GIT-01 agent-job guard. Empty defaults to warn.
OnUncommitted string `yaml:"on_uncommitted,omitempty"`
// UncommittedIgnore excludes cwd-relative paths from the GIT-01 result.
UncommittedIgnore []string `yaml:"uncommitted_ignore,omitempty"`
// NotifyEnabled gates E14 webhook delivery for this project (design §5.5). It
// is a pointer so "unset" (nil) defaults to ENABLED while an explicit
// notify_enabled:false suppresses all notification for the project's jobs
// (no deliveries are enqueued). nil/true => notification on.
NotifyEnabled *bool `yaml:"notify_enabled,omitempty"`
// WorktreeDefault turns WT-01 managed worktrees ON for every job of this project
// (a per-job --worktree is then redundant). The resolved decision rides the
// request, so a worker executes exactly what the submitter decided.
WorktreeDefault bool `yaml:"worktree_default,omitempty"`
// Worktree tunes the managed worktree itself (WT-01 extension): its directory and
// branch templates ({name} / {job_id}) and the directories to link in from the main
// checkout. Nil = the historical defaults (tmp/gofer/wt/{job_id}, gofer/{job_id},
// no links), so an existing project is unaffected. See ProjectWorktree.
Worktree *ProjectWorktree `yaml:"worktree,omitempty"`
// RequireReview (GATE-01 S3) turns人工验收 ON for every job of this project: a job
// whose agent finishes normally parks in `needs_review` until a human accepts or
// rejects it. A per-job --review is then redundant, and a workflow step may still
// override it explicitly in either direction (StepSpec.Review). Default off, so
// upgrading never strands a project's jobs on a human.
RequireReview bool `yaml:"require_review,omitempty"`
// ScopeDiscipline (gofer-3nxa.3) decides whether a batch agent job of this project
// gets the 「交付约定」 section appended to its prompt (stay in scope; write what
// you found but did not touch into 「## 发现但不碰」): auto (the default) = only
// plan-todo jobs, review-gated jobs and jobs carrying acceptance or scope; on =
// every non-exec batch agent job; off = never. See EffectiveScopeDiscipline.
ScopeDiscipline string `yaml:"scope_discipline,omitempty"`
// KnowledgeCapture (gofer-3nxa.2) decides whether the 「交付约定」 section also asks
// the agent for a 「## 可复用经验」 report section, which the server turns into
// memory candidates a person accepts or rejects. Same modes and the same auto
// coverage as ScopeDiscipline. See EffectiveKnowledgeCapture.
KnowledgeCapture string `yaml:"knowledge_capture,omitempty"`
// Approval is the project's run-time approval gate (GATE-01 §1): how an
// acp-agent's session/request_permission is answered. Nil means the defaults,
// and the default mode is off (= the pre-GATE behaviour: the agent's own
// permission handling decides, gofer auto-allows) so upgrading cannot strand
// existing jobs on a human. See ApprovalPolicy.
Approval *ApprovalConfig `yaml:"approval,omitempty"`
// Verify is the project's DEFAULT verify step (SUP-01 B): an argv run after the
// agent finishes normally, on the executing machine, in the job's cwd/env — the
// machine-checkable acceptance an agent's own report cannot provide. It applies
// to every job of the project unless the caller passes --no-verify, and it needs
// allow_exec (the argv comes from the submitter, the same trust surface as an
// exec job's). Empty = no default. See JobRequest.Verify.
Verify []string `yaml:"verify,omitempty"`
// VerifyTimeoutSec bounds that step (SUP-01 B): 0/unset => DefaultVerifyTimeoutSec.
// It is independent of the job's own timeout — a hung test suite must not be able
// to eat the agent's whole budget — and a step that exceeds it fails the job.
VerifyTimeoutSec int `yaml:"verify_timeout_sec,omitempty"`
// Retry is this project's default job retry policy (R2/AUTO-03, design §二.2): it
// applies to every job of the project, overriding agents.<k>.retry and
// server.retry (a nearer layer still wins: JobRequest.Retry / `job run --retry`).
// Nil = the project says nothing. An explicit `max_attempts: 1` here switches
// retry OFF for the project even when the server default enables it. See
// Config.EffectiveRetryPolicy.
Retry *RetryPolicy `yaml:"retry,omitempty"`
// ContinueMaxChain limits how many times one agent session is handed on from a plan
// item to the next (todo continue_from): when the chain reaches it, the next item
// starts a fresh session. Nil/unset => DefaultContinueMaxChain; 0 => unlimited;
// at most MaxContinueMaxChain. A pointer so "unset" and "0" stay distinct.
ContinueMaxChain *int `yaml:"continue_max_chain,omitempty"`
}
ProjectConfig describes a single registered project. ExchangeSubdir and ResultSubdir may be empty; they fall back to the storage defaults at resolve time (see ResolvedExchangeSubdir/ResolvedResultSubdir).
func DefaultWorkspaceProject ¶
func DefaultWorkspaceProject(hostPath string, agents []string) ProjectConfig
DefaultWorkspaceProject is THE definition of the default-workspace project, shared by `gofer init server` (which writes it into config.yaml) and InjectDefaultProject (which synthesizes it at runtime): the directory itself, the local runner, and the given agents (an EMPTY allowed_agents means "any configured agent", so a host with no CLI installed still gets a usable project).
func MergeProjectConfig ¶
func MergeProjectConfig(base ProjectConfig, ov ProjectOverlay) ProjectConfig
MergeProjectConfig returns base with every non-nil overlay field applied (D8). Slice/准入/注册锚 fields are never touched (they are absent from ProjectOverlay).
func (ProjectConfig) ApprovalPolicy ¶
func (p ProjectConfig) ApprovalPolicy() ApprovalConfig
ApprovalPolicy returns the project's approval policy with the defaults applied (nil block => the default policy).
func (ProjectConfig) EffectiveKnowledgeCapture ¶
func (p ProjectConfig) EffectiveKnowledgeCapture() string
EffectiveKnowledgeCapture is the project's knowledge-capture mode (gofer-3nxa.2; the ScopeDiscipline* values) with the default (auto) applied to an unset value.
func (ProjectConfig) EffectiveScopeDiscipline ¶
func (p ProjectConfig) EffectiveScopeDiscipline() string
EffectiveScopeDiscipline is the project's scope-discipline mode with the default (auto) applied to an unset value.
func (ProjectConfig) EffectiveTrackerPrime ¶ added in v0.157.0
func (p ProjectConfig) EffectiveTrackerPrime() string
EffectiveTrackerPrime is the project's tracker-prime mode with the default (nearest) applied to an unset value.
func (ProjectConfig) IsInteractiveAllowed ¶
func (p ProjectConfig) IsInteractiveAllowed() bool
IsInteractiveAllowed reports whether the project permits interactive (pty) jobs. allow_interactive is the ONLY source: unset (nil) means "no interactive jobs", so the default is closed and a project built in code with no switch set can never open interactive submission by accident. The legacy narrowing list (AGT-02) is gone: a yaml still carrying interactive_allowed_agents fails the load (config.RejectRemovedKeys) rather than being half-read into this switch. It is the shared derivation of server admission (job.validate) and the POLICY push (core.projectToPolicy), which is why it lives on the type, not in a loader.
func (ProjectConfig) IsNotifyEnabled ¶
func (p ProjectConfig) IsNotifyEnabled() bool
IsNotifyEnabled reports whether E14 webhook delivery is enabled for the project. Unset (nil) defaults to true; an explicit notify_enabled:false suppresses it.
func (*ProjectConfig) RenderWorktreeBranch ¶ added in v0.180.0
func (p *ProjectConfig) RenderWorktreeBranch(name, jobID string) string
RenderWorktreeBranch 展开 worktree.branch 模板,口径同 RenderWorktreeDir。
func (*ProjectConfig) RenderWorktreeDir ¶ added in v0.180.0
func (p *ProjectConfig) RenderWorktreeDir(name, jobID string) string
RenderDir 展开 worktree.dir 模板。name 为空时取 jobID(`--worktree-name` 未给)。
func (*ProjectConfig) UnmarshalYAML ¶
func (p *ProjectConfig) UnmarshalYAML(data []byte) error
UnmarshalYAML accepts the string capture_diff modes while keeping the public *bool field and wire/policy compatibility intact. "auto" deliberately maps to nil: absence and explicit auto have the same runtime semantics.
func (*ProjectConfig) WorktreeLinks ¶ added in v0.180.0
func (p *ProjectConfig) WorktreeLinks() []string
WorktreeLinks 返回本项目要在 worktree 里创建的依赖链接(项目内相对路径);没配即为空。
type ProjectOverlay ¶
type ProjectOverlay struct {
// Key is the project's self-identifier (xu64.15): the primary source `--project
// auto` uses to resolve the current dir to a project key WITHOUT a central round
// trip. It is decode-only — never merged into ProjectConfig (a dir 自我标识, not a
// project setting), so MergeProjectConfig ignores it. Not a准入/server key, so it
// is absent from forbiddenOverlayKeys (blacklist) and needs no allow-list entry.
Key *string `yaml:"key"`
ExchangeSubdir *string `yaml:"exchange_subdir"`
ResultSubdir *string `yaml:"result_subdir"`
DefaultAgent *string `yaml:"default_agent"`
MaxConcurrentJobs *int `yaml:"max_concurrent_jobs"`
CaptureDiff *bool `yaml:"capture_diff"`
NotifyEnabled *bool `yaml:"notify_enabled"`
}
ProjectOverlay is the decoded .gofer.project.yaml (D5 白名单). Every field is a pointer so "absent" (nil) is distinguishable from a zero value — only non-nil fields override the global ProjectConfig (D8).
func (*ProjectOverlay) UnmarshalYAML ¶
func (p *ProjectOverlay) UnmarshalYAML(data []byte) error
UnmarshalYAML mirrors ProjectConfig's capture_diff compatibility boundary so a thin project overlay can use auto/on/off as well as the legacy bool form.
type ProjectWorktree ¶ added in v0.180.0
type ProjectWorktree struct {
// Dir is the worktree checkout dir, relative to the repository toplevel, with
// {name} / {job_id} placeholders. Empty = DefaultWorktreeDir.
Dir string `yaml:"dir,omitempty"`
// Branch is the branch template ({name} / {job_id}); `job run --branch` overrides
// it for one job. Empty = DefaultWorktreeBranch.
Branch string `yaml:"branch,omitempty"`
// Links lists project-relative directories to link from the main checkout into
// the fresh worktree (Windows directory junction, elsewhere a symlink), so a job
// in the worktree finds the dependencies it does not commit (e.g. a vendored
// node_modules). A missing source is skipped, not fatal.
Links []string `yaml:"links,omitempty"`
}
ProjectWorktree 是项目配置的 `worktree:` 段(WT-01 扩展)。
type PtyConfig ¶
type PtyConfig struct {
// TranscriptMaxBytes caps the de-ANSI'd text transcript kept for one
// interactive pty session (<result_dir>/pty.txt). It bounds the FILE too, not
// just memory: the sink keeps the tail. 0 / unset => the documented 4MB.
TranscriptMaxBytes int64 `yaml:"transcript_max_bytes,omitempty"`
}
PtyConfig is the pty relay's transcript block (PTY-01 §四).
type PushConfig ¶
type PushConfig struct {
VAPIDSubject string `yaml:"vapid_subject,omitempty"`
}
PushConfig is the small, non-secret Web Push configuration surface.
type ReconnectConfig ¶
type ReconnectConfig struct {
InitialBackoffMS int `yaml:"initial_backoff_ms,omitempty"`
MaxBackoffMS int `yaml:"max_backoff_ms,omitempty"`
PingIntervalSec int `yaml:"ping_interval_sec,omitempty"`
ReadDeadlineSec int `yaml:"read_deadline_sec,omitempty"`
}
ReconnectConfig is the worker's backoff + heartbeat policy for hub reconnection (C7/P3, §4). All fields default when <= 0:
- InitialBackoffMS: first-retry base wait (default 1000 = 1s).
- MaxBackoffMS: backoff cap (default 30000 = 30s); full-jitter strategy is fixed (sleep = rand(0, min(max, initial*2^attempt))), so there is no jitter knob.
- PingIntervalSec: heartbeat ping cadence (default 15s; symmetric with the hub).
- ReadDeadlineSec: single-read deadline / half-open detection (default 45s).
type ReloadResult ¶
type ReloadResult struct {
Rev int64 `json:"rev"`
Path string `json:"path"`
Changed []string `json:"changed"`
RestartRequired []string `json:"restart_required"`
Error string `json:"error,omitempty"`
// Files lists every file the reloaded config was read from (main first) when it
// is split with include; empty for a one-file config.
Files []string `json:"files,omitempty"`
// ReloadedAt is when this receipt was written (RFC3339Nano). Waiters compare
// it with the time they signalled the process, so a server restart that
// resets Rev cannot make a fresh receipt look stale.
ReloadedAt time.Time `json:"reloaded_at"`
}
ReloadResult describes one successful configuration generation swap. Changed contains top-level configuration partitions whose values differ from the previous generation. RestartRequired contains the dotted keys classified by the editable policy as startup-only and changed by this reload.
func ReadReloadResult ¶
func ReadReloadResult(path string) (ReloadResult, error)
type RetentionConfig ¶
type RetentionConfig struct {
// MaxAgeDays, when > 0, prunes terminal jobs older than this many days.
MaxAgeDays int `yaml:"max_age_days,omitempty"`
// MaxCount, when > 0, keeps only the newest MaxCount terminal jobs.
MaxCount int `yaml:"max_count,omitempty"`
// IntervalMinutes is the prune cadence; <= 0 falls back to a default (60m) in
// the serve loop. Only consulted when MaxAgeDays or MaxCount is > 0.
IntervalMinutes int `yaml:"prune_interval_minutes,omitempty"`
// WorkflowMaxAgeDays is the INDEPENDENT workflow retention age (P1, design §5.4
// / D22): when > 0, terminal workflows (done/failed/cancelled) older than this
// many days are pruned along with their step-jobs and workflow_events. When 0 it
// falls back to MaxAgeDays (WorkflowMaxAge), so a single job age policy also
// bounds workflows; set it explicitly to keep workflows longer/shorter than jobs.
WorkflowMaxAgeDays int `yaml:"workflow_max_age_days,omitempty"`
}
RetentionConfig is the YAML form of the job retention policy enforced by the serve prune loop (design §13 SP5). All fields default to 0 (disabled): with no retention configured the server never prunes (zero behaviour change).
func (RetentionConfig) Enabled ¶
func (r RetentionConfig) Enabled() bool
Enabled reports whether any retention bound is set (so the serve prune loop should run). The interval alone does not enable prune. Workflow retention rides the same loop, so WorkflowMaxAgeDays also enables it (a config that only sets workflow retention still runs the prune loop).
func (RetentionConfig) MaxAge ¶
func (r RetentionConfig) MaxAge() time.Duration
MaxAge converts MaxAgeDays into a time.Duration (0 days => 0, i.e. no age bound). The job package maps this onto a jobstore.RetentionPolicy — config stays free of a jobstore dependency so it remains a leaf imported everywhere.
func (RetentionConfig) PruneInterval ¶
func (r RetentionConfig) PruneInterval() time.Duration
PruneInterval returns the prune cadence, defaulting to 60 minutes when the configured interval is <= 0.
func (RetentionConfig) WorkflowMaxAge ¶
func (r RetentionConfig) WorkflowMaxAge() time.Duration
WorkflowMaxAge converts the effective workflow retention age into a Duration: the explicit WorkflowMaxAgeDays when > 0, else a fallback to MaxAgeDays (jobs). 0 days => 0 (no workflow age bound). The job package maps this onto a jobstore.WorkflowRetentionPolicy (config stays jobstore-free).
type RetryPolicy ¶
type RetryPolicy struct {
MaxAttempts int `json:"max_attempts" yaml:"max_attempts"` // >=1 (includes the first run)
BackoffSec BackoffSec `json:"backoff_sec,omitempty" yaml:"backoff_sec,omitempty"` // 默认接 SR606 [30,120,300,900,3600]
OnExitCodes []int `json:"on_exit_codes,omitempty" yaml:"on_exit_codes,omitempty"` // 空=任意非0退出重试
}
RetryPolicy bounds how often a job (or a workflow step) is re-run after a failure, and how long gofer waits before each re-run (R2/AUTO-03, design §二.2; the struct itself is the E24/D16 one, moved here so the config file, the wire (JobRequest.Retry) and the four config layers decode from ONE definition — internal/job aliases it as job.RetryPolicy).
MaxAttempts counts the FIRST run as attempt 1, so MaxAttempts==3 means up to 2 retries, and MaxAttempts<=1 means "no retry" (an explicit `max_attempts: 1` is how a nearer layer switches retry OFF for good). BackoffSec is the退避表 indexed by the just-failed attempt; empty falls back to the built-in table [30,120,300,900,3600]. OnExitCodes, when non-empty, restricts the retry to those exit codes (empty == retry on any non-zero exit).
The SEMANTICS live in internal/job (MaxAttemptsPolicy / BackoffForPolicy / RetryableExitPolicy), which the job-level and step-level retry paths share.
type RoleConfig ¶
type RoleConfig struct {
Agent string `yaml:"agent,omitempty"`
SystemPrompt string `yaml:"system_prompt,omitempty"`
Project string `yaml:"project,omitempty"`
Tags []string `yaml:"tags,omitempty"`
// Env is an OPTIONAL per-role env preset merged into the job's process env
// (JobRequest.Env) at submit time, so `--role supervisor` can inject e.g.
// GOFER_AGENT_ROLE=supervisor into the agent process without a dedicated
// codex-sup agent (the spawned gofer MCP child inherits it and self-registers
// role=supervisor, P3). Role.Env fills DEFAULTS — an explicit per-job env value
// for the same key wins. 勿放 secret:值会随 job.Env 落 request_json(SR403/SR805),
// secret 应走 agent.env / K8s secret(不落 request_json)。
Env map[string]string `yaml:"env,omitempty"`
// CanSubmit / SubmitAgents are the ROLE-level counterparts of the same two
// AgentConfig fields (SEC-01): a job run under this role may submit work when
// either its role or its agent opens the gate. They exist because the natural unit
// for "this role is a supervisor" is the role preset, not the CLI it happens to
// run on. See AgentConfig.CanSubmit for the exact rule.
CanSubmit bool `yaml:"can_submit,omitempty"`
SubmitAgents []string `yaml:"submit_agents,omitempty"`
}
RoleConfig is one named role preset (design §8.5). Agent is the base CLI agent the role runs on; SystemPrompt is injected via the agent's SystemInject template (claude --append-system-prompt). Project/Tags are optional request defaults the role fills when the caller leaves them empty.
type RunnerConfig ¶
type RunnerConfig struct {
Type string `yaml:"type,omitempty"`
BaseURL string `yaml:"base_url,omitempty"`
TokenEnv string `yaml:"token_env,omitempty"`
// WorkerID is the worker this runner dispatches to (type=worker only). It
// must match a server.workers entry.
WorkerID string `yaml:"worker_id,omitempty"`
}
RunnerConfig describes an execution location. peer-http fields are decoded in P2 but only used by the peer runner in P7. For type=worker (ws-worker), the runner targets a single registered worker identified by WorkerID; one worker-runner = one worker (dynamic routing is WP4 scheduling, not WP1).
type RunnerProbeConfig ¶
type RunnerProbeConfig struct {
IntervalSeconds int `yaml:"interval_seconds,omitempty"`
TimeoutSeconds int `yaml:"timeout_seconds,omitempty"`
}
RunnerProbeConfig is the YAML form of the peer-http health-probe policy (C6/P4 §6). Both fields default when <= 0: 30s interval, 5s per-probe timeout. It is a pure additive block — an existing config with no runner_probe key probes at the defaults.
func (RunnerProbeConfig) ProbeInterval ¶
func (p RunnerProbeConfig) ProbeInterval() time.Duration
ProbeInterval returns the peer-http probe cadence, defaulting to 30s when the configured interval is <= 0.
func (RunnerProbeConfig) ProbeTimeout ¶
func (p RunnerProbeConfig) ProbeTimeout() time.Duration
ProbeTimeout returns the per-probe timeout, defaulting to 5s when the configured timeout is <= 0.
type ScheduleConfig ¶
type ScheduleConfig struct {
SweepIntervalSec int `yaml:"sweep_interval_sec,omitempty"`
MissGraceSec int `yaml:"miss_grace_sec,omitempty"`
}
ScheduleConfig controls the AUTO-02 cron sweeper cadence and missed-run policy.
type SecretConfig ¶ added in v0.152.0
type SecretConfig struct {
// Env is the variable of the executing gofer process holding the value (put it in
// <config-dir>/.env to keep it out of the shell). Required.
Env string `yaml:"env"`
// As is the variable name the job sees ("" = the secret name upper-cased, with
// '-' and '.' turned into '_').
As string `yaml:"as,omitempty"`
// Description is for people.
Description string `yaml:"description,omitempty"`
}
SecretConfig is one secrets entry.
func (SecretConfig) JobVar ¶ added in v0.152.0
func (s SecretConfig) JobVar(name string) string
JobVar is the variable the job receives the secret as.
type ServerConfig ¶
type ServerConfig struct {
Addr string `yaml:"addr,omitempty"`
Token string `yaml:"token,omitempty"`
TokenEnv string `yaml:"token_env,omitempty"`
AllowEmptyToken bool `yaml:"allow_empty_token,omitempty"`
// PathView selects which project path the GOFER PROCESS uses as its execution
// root (E29/D10): "host" (default, empty) => host_path; "container" =>
// container_path (falling back to host_path when container_path is empty). It
// is an EXPLICIT operator switch — gofer does NOT self-detect being in a
// container (no /.dockerenv probing). All gofer-process-side paths (SafeJoin /
// ExchangeDir / ResultBaseDir / Validate / overlay read dir) go through
// Config.ExecPath; E21 host-side actions always use host_path (not this).
PathView string `yaml:"path_view,omitempty"`
// Callers is the optional multi-caller auth set (C2): each entry maps a
// bearer token to a caller id stamped onto submitted jobs for audit /
// per-caller filtering. The legacy single Token/TokenEnv stays valid (treated
// as caller id "default"); revocation = remove the caller + reload (C3).
Callers []CallerConfig `yaml:"callers,omitempty"`
// WebEnabled is a pointer so that "unset" (nil) can default to true while an
// explicit web_enabled:false disables the embedded web console (see
// IsWebEnabled and applyDefaults).
WebEnabled *bool `yaml:"web_enabled,omitempty"`
// WebDir 指向磁盘上的 web SPA 构建目录(dev:serve --web-dir)。非空则服务从该目录
// 读取,而非嵌入的 dist;空则用嵌入版。不入持久化配置的常规路径,仅运行期设置。
WebDir string `yaml:"web_dir,omitempty"`
// TLS adds a second HTTPS listener; the existing HTTP listener remains active.
// Nil keeps the historical HTTP-only behaviour.
TLS *TLSConfig `yaml:"tls,omitempty"`
// Workers is the per-worker auth/binding set (ws-worker, §7 / review #1):
// each entry registers a legitimate worker identity keyed by worker_id and
// binds it to a token. A `register` frame whose worker_id does not match the
// presented token's bound worker is rejected (hub.Accept). per-worker token
// is MVP-mandatory: even allow_empty_token does not waive the binding.
Workers map[string]WorkerAuthConfig `yaml:"workers,omitempty"`
// RunnerProbe tunes the peer-http active health probe (C6/P4): how often each
// peer-http runner's /health is polled and the per-probe timeout. Unset =>
// defaults (30s interval / 5s timeout). The probe only runs when at least one
// peer-http runner is configured (zero behaviour change otherwise).
RunnerProbe RunnerProbeConfig `yaml:"runner_probe,omitempty"`
// Notification is the E14 webhook outbound config (design §5.5). It is a
// pointer so "unset" (nil) cleanly disables all notification (the serve
// delivery sweeper does not even start) — zero behaviour change for any config
// without a `notification` block. When present it lists the webhook targets,
// the outbound host allowlist and the retry cap.
Notification *NotificationConfig `yaml:"notification,omitempty"`
// EventHooks are the AUTO-04 server-side event hooks: commands run on this host
// when a matching event happens (the generic webhook JSON on stdin). Separate from
// Notification on purpose — the notification pause switches do not apply to them —
// and FILE-ONLY: the config write API refuses this key (it would be remote command
// execution), see EventHookConfig.
EventHooks []EventHookConfig `yaml:"event_hooks,omitempty"`
// DecisionHooks are the AUTO-04b decision hooks: commands run SYNCHRONOUSLY at a
// decision point (job submit, delivery) whose answer may refuse the action or
// make it more conservative. FILE-ONLY for the same reason as EventHooks.
DecisionHooks []DecisionHookConfig `yaml:"decision_hooks,omitempty"`
// Update is the release check (gofer-6x2n): periodic and on demand, GitHub by
// default or a mirror's latest.yaml. File-only (the server fetches the URLs).
Update UpdateConfig `yaml:"update,omitempty"`
// WorkerEnrollment is the self-service worker registration block (off by default).
WorkerEnrollment WorkerEnrollmentConfig `yaml:"worker_enrollment,omitempty"`
// Push configures the browser Web Push identity. Key material is never stored
// here; it is generated under <config-dir>/push/vapid.json. The optional
// subject is the RFC 8292 contact URI carried by VAPID JWTs.
Push PushConfig `yaml:"push,omitempty"`
// Metrics is the E16 Prometheus /metrics policy (design §6.2). Enabled is a
// pointer so "unset" (nil) defaults to ENABLED (the endpoint is mounted) while
// an explicit enabled:false drops it. Token, when non-empty, re-adds a Bearer
// check on /metrics (default empty = unauthenticated scrape, guarded by the
// intranet admission boundary, SR202).
Metrics MetricsConfig `yaml:"metrics,omitempty"`
// Governance is the E17 per-caller quota / rate-limit global fallback (design
// §7.1). It is a pure additive block: an existing config with no `governance`
// key has all-zero defaults, which means "unlimited" everywhere (向后兼容). A
// per-caller override on a CallerConfig (> 0) takes precedence; otherwise the
// governance default applies (see CallerConcurrencyLimit / CallerRate).
Governance GovernanceConfig `yaml:"governance,omitempty"`
// WebBaseURL is the address a human uses to reach this console from the
// outside (e.g. https://gofer.example.com). Only outbound notifications need
// it — the server cannot derive it from its listen address behind a proxy or
// a LAN IP. Empty = notifications carry no link.
WebBaseURL string `yaml:"web_base_url,omitempty"`
// SessionMessaging controls the web-to-agent session message bridge. It is
// intentionally server-scoped because the messenger job runs on the session's
// registered runner and must use one operator-wide command/timeout policy.
SessionMessaging SessionMessagingConfig `yaml:"session_messaging,omitempty"`
// MaxJobTimeoutSec is the server-wide CEILING on a job's timeout_sec (bd
// h-aii-s9ck). 0/unset => DefaultMaxJobTimeoutSec (1h), which is exactly the
// value this clamp used to be hard-coded to, so every existing config behaves
// as before. It is a ceiling, not a default: a request above it is clamped and
// the clamp is REPORTED (job.JobResult.RequestedTimeoutSec/TimeoutClamped, plus
// a CLI warning) so a long job can no longer be truncated silently. Raise it for
// long-running work; a project overrides it in either direction via
// ProjectConfig.MaxTimeoutSec (see EffectiveMaxTimeoutSec).
MaxJobTimeoutSec int `yaml:"max_job_timeout_sec,omitempty"`
// JobRecoverWindowSec is the RECOV-01 worker reconnect window in seconds: how
// long a worker's in-flight jobs are held in `recovering` after its connection
// drops, before they are failed with worker_lost. It is a POINTER so "unset"
// (nil → DefaultJobRecoverWindowSec, 120s) is distinguishable from an explicit
// `job_recover_window_sec: 0`, which DISABLES recovery entirely (a disconnect
// fails the in-flight jobs at once — the pre-RECOV-01 behaviour). Same
// unset≠zero reasoning as WebEnabled. See Config.JobRecoverWindow.
JobRecoverWindowSec *int `yaml:"job_recover_window_sec,omitempty"`
// PolicyRepush controls the server retry for a policy that stayed pending on
// an online worker. Zero values use the safe defaults (60s and 3 attempts).
PolicyRepush *PolicyRepushConfig `yaml:"policy_repush,omitempty"`
// AutoResumeMax counts automatic session continuations, independently of RetryPolicy.
// Unset defaults to one; an explicit zero disables automatic resume.
AutoResumeMax *int `yaml:"auto_resume_max,omitempty"`
// Retry is the deployment-wide default job retry policy (R2/AUTO-03, design
// §二.2): a failed job is re-run by the serve sweeper after this policy's
// backoff, at most MaxAttempts times. A pointer so an absent block means OFF —
// upgrading gofer never starts re-running anybody's failures (the pre-R2
// behaviour). The nearer layers (projects.<k>.retry, agents.<k>.retry,
// JobRequest.Retry / `job run --retry`) each replace it wholesale; see
// Config.EffectiveRetryPolicy.
Retry *RetryPolicy `yaml:"retry,omitempty"`
// AgentFallback is the SUP-01 P3 failover policy (design §一). A pointer so an
// absent block means the defaults (transfer after a failure ON, submit-time
// substitution OFF) without any behaviour change for a config that never
// mentions it — and so the transfer only ever applies to a job that actually
// resolved a candidate list.
AgentFallback *AgentFallbackConfig `yaml:"agent_fallback,omitempty"`
// AgentHealth is the SUP-01 P3 health window/thresholds (design §一). A pointer;
// an absent block resolves to the documented defaults. It only classifies
// reported health — nothing in the job path consults it unless pre_dispatch is on.
AgentHealth *AgentHealthConfig `yaml:"agent_health,omitempty"`
// Xfer is the XFER-01 transfer policy (design §一.1): the per-transfer byte
// ceiling and how long a staged/finished transfer survives in the staging area.
// An absent block (all zero) keeps the documented defaults (256MB / 24h) — the
// capability is always on, so there is no enable switch to get wrong.
Xfer XferConfig `yaml:"xfer,omitempty"`
// Attachments is the workbench image-attachment policy (upload size, per-message count,
// hourly upload cap). An absent block keeps the defaults; see AttachmentsConfig.
Attachments AttachmentsConfig `yaml:"attachments,omitempty"`
// DirLock is the JOB-11 same-directory serialization switch. A POINTER so an
// explicit `dir_lock: false` (every job shares its working directory — the
// pre-JOB-11 behaviour) is distinguishable from "unset", which defaults to ON
// (see EffectiveDirLock). Turning it off is the operator's escape hatch for a
// deployment where the jobs are known not to touch one tree.
DirLock *bool `yaml:"dir_lock,omitempty"`
// DirLockMaxWaitSec bounds how long a job may WAIT for the same-directory lock
// before it is failed (JOB-11, F12 fix 2026-09-25). A job's own execution timeout
// starts when it starts RUNNING — queuing is not execution — so without this cap a
// job parked behind a wedged holder would wait forever. A POINTER so "unset"
// (→ DefaultDirLockMaxWaitSec, one hour) is distinguishable from an explicit 0,
// which removes the cap (wait until the lock is free or the job is cancelled).
// Read per submit (see EffectiveDirLockMaxWaitSec), so a hot edit applies to the
// NEXT job.
DirLockMaxWaitSec *int `yaml:"dir_lock_max_wait_sec,omitempty"`
// DirLockAllowUnboundedWait controls explicit lock_wait_sec: 0 requests.
// nil defaults to true, preserving the existing unbounded-wait behavior.
DirLockAllowUnboundedWait *bool `yaml:"dir_lock_allow_unbounded_wait,omitempty"`
// StallTimeoutSec is the AUTO-05 output-stall window in seconds: a running
// non-interactive agent job that produces no output for that long is killed and
// failed as stalled. A POINTER so "unset" (→ DefaultStallTimeoutSec, 900s) is
// distinguishable from an explicit 0, which turns the watchdog off everywhere.
// See EffectiveStallTimeoutSec for the full resolution (request > agent > server;
// exec jobs are off unless someone asks for a window).
StallTimeoutSec *int `yaml:"stall_timeout_sec,omitempty"`
// JobEnvDenyList adds to the built-in denylist of environment variables a job
// process does NOT inherit from this gofer process (SEC-01). The built-in three
// (GOFER_TOKEN, GOFER_SERVER_TOKEN, GOFER_WORKER_TOKEN) are always stripped; this
// is for a deployment whose credentials live under other names. A project's
// `job_env_allow` re-admits any of them deliberately, and each job that keeps one
// records `job.env_allowed` so the detail view shows it.
//
// It is read per job spawn, so a reload applies to the NEXT job (nothing caches it).
JobEnvDenyList []string `yaml:"job_env_denylist,omitempty"`
// Skills is the deployment-wide default skill set (JOB-10, design §一.3): the
// skills every job this server dispatches mounts into its own
// `<result_dir>/skills/` before the agent starts, whatever project or agent it
// belongs to. It is one LEVEL of a union rather than an override —
// agents.<key>.skills and projects.<key>.skills add to it and `job run --skill`
// adds one more — because a skill is knowledge, not a mutually exclusive policy
// (contrast server.retry / fallback_agents, which the nearest layer REPLACES).
// See Config.EffectiveSkills for the order and the --no-skills / exec rules.
Skills []string `yaml:"skills,omitempty"`
// MCP lists registry MCP servers every job gets (MCP-06); usually empty — bind at
// agent / project / job level instead. See Config.EffectiveMCP.
MCP []string `yaml:"mcp,omitempty"`
// Rules is the deployment-wide MANDATORY rule set (JOB-06①, design §一.2): the
// discipline every job this server dispatches gets at the TOP of its prompt,
// whatever project or agent it belongs to. It is the same four-level union as
// skills (agents.<key>.rules and projects.<key>.rules add, `job run --rule` adds
// one more) because a rule is an accumulation, not a mutually exclusive policy;
// the single off switch is `job run --no-rules`, which a job credential may not
// use (design 决策 4). See Config.EffectiveRules.
Rules []string `yaml:"rules,omitempty"`
// RulesMaxBytes caps the TOTAL size of the rules injected into one job (design
// 决策 3, default 16KiB). A submit whose rules exceed it is rejected with the
// largest offenders named — rules are meant to be short and hard; long reference
// material belongs in a skill. Read per submit (EffectiveRulesMaxBytes), so a hot
// edit applies to the NEXT job.
RulesMaxBytes int `yaml:"rules_max_bytes,omitempty"`
// SkillLimits bounds what ONE imported skill may contain (JOB-10 §一.2). The
// store owns enforcement and the defaults (2MiB per file / 10MiB total); this
// block only carries an operator's override, so an absent one is not a bug.
SkillLimits SkillLimitsConfig `yaml:"skill_limits,omitempty"`
// CommentTrigger bounds the @-mention dispatch a COMMENT can start (MCP-05 阶段 A,
// design §二.A.4): it is the third gate beside "only a user's comment" and "the
// mentioned agent must be allowed in the project". Both knobs are read per comment
// (see Config.EffectiveCommentTrigger), so a hot edit applies to the NEXT comment —
// nothing derives a cached value from them at startup.
CommentTrigger CommentTriggerConfig `yaml:"comment_trigger,omitempty"`
// Tunnel is the hub-side tunnel VISIBILITY policy (TUN-03). It governs only how
// long a `gofer tun forward` registration is reported on GET
// /v1/tunnels/forwarders; the forwarding itself stays governed by worker.tunnel
// and the caller's can_tunnel. Read per request (see
// ServerTunnelConfig.EffectiveForwarderTTL), so a hot edit applies to the next one.
Tunnel ServerTunnelConfig `yaml:"tunnel,omitempty"`
// Hold is the hold-for-approval timeout policy (gofer-9b1b): the timeout a held job
// gets when its request names none, and the largest one a request may ask for. Read
// per submit (EffectiveHoldTimeoutSec), so a reload applies to the NEXT held job.
Hold HoldConfig `yaml:"hold,omitempty"`
}
ServerConfig holds HTTP server and auth settings.
func (*ServerConfig) CallerCanAdmin ¶
func (sc *ServerConfig) CallerCanAdmin(callerID string) bool
CallerCanAdmin reports whether callerID has the can_admin capability bit. The governance gate itself is checked by callers of this helper.
func (*ServerConfig) CallerCanAnswer ¶
func (sc *ServerConfig) CallerCanAnswer(callerID string) bool
CallerCanAnswer reports whether callerID has the can_answer capability bit. The governance gate itself is checked by callers of this helper.
func (*ServerConfig) CallerCanAttach ¶
func (sc *ServerConfig) CallerCanAttach(callerID string) bool
CallerCanAttach reports whether callerID has the can_attach capability bit. The governance gate itself is checked by callers of this helper.
func (*ServerConfig) CallerCanTunnel ¶
func (sc *ServerConfig) CallerCanTunnel(callerID string) bool
CallerCanTunnel reports whether callerID has tunnel capability.
func (*ServerConfig) CallerCeiling ¶ added in v0.172.0
func (sc *ServerConfig) CallerCeiling(id string) (*CallerCeiling, bool)
CallerCeiling returns the ceiling of callerID and whether it has one. A caller the configuration does not declare, and a declared caller without a `ceiling` block, both answer (nil, false) — "no ceiling" is the state every caller starts in.
Like CallerConcurrencyLimit this is a pure lookup over the caller list (first match wins), so it can be read from a live config snapshot on every judgment.
func (*ServerConfig) CallerConcurrencyLimit ¶
func (sc *ServerConfig) CallerConcurrencyLimit(callerID string) int
CallerConcurrencyLimit resolves the effective per-caller concurrent-jobs cap (E17, design §7.2): the caller's own MaxConcurrentJobs (> 0) wins, else the server.governance default, else 0 (unlimited). An empty callerID skips the per-caller lookup and uses the governance default directly.
func (*ServerConfig) CallerName ¶ added in v0.167.0
func (sc *ServerConfig) CallerName(callerID string) string
CallerName returns the display name of callerID, or "" when it has none.
func (*ServerConfig) CallerNames ¶ added in v0.167.0
func (sc *ServerConfig) CallerNames() map[string]string
CallerNames maps caller id to its display name for every caller that declares one. The main-token caller `default` gets its name from the `id: default` entry like any other. Callers without a name are absent (display falls back to the id).
func (*ServerConfig) CallerRate ¶
func (sc *ServerConfig) CallerRate(callerID string) (rps float64, burst int)
CallerRate resolves the effective per-caller submit rate (E17, design §7.3): the caller's own RateLimit (> 0) wins, else the governance DefaultRateLimit, else 0 (no rate gating). burst follows the same caller→governance precedence; when the resolved burst is <= 0 (and rps > 0) it defaults to max(1, ceil(rps)) so a configured rate always has a usable bucket. An empty callerID uses the governance defaults directly.
func (*ServerConfig) CeilingCallers ¶ added in v0.172.0
func (sc *ServerConfig) CeilingCallers() []string
CeilingCallers returns the ids of the callers that carry a ceiling, sorted. It is what the serve startup log reports ("N restricted caller(s)"), so an operator can see that limits are in force before trusting them.
func (*ServerConfig) EffectiveAutoResumeMax ¶
func (sc *ServerConfig) EffectiveAutoResumeMax() int
EffectiveAutoResumeMax preserves the distinction between omitted and explicit zero.
func (ServerConfig) EffectiveSessionMessaging ¶
func (c ServerConfig) EffectiveSessionMessaging() SessionMessagingConfig
func (*ServerConfig) HasRootAdmin ¶ added in v0.161.0
func (sc *ServerConfig) HasRootAdmin() bool
HasRootAdmin reports whether the deployment has a root administrator at all: a declared caller with `can_admin: true`, or — in a single-token deployment that declares no callers (the `default` caller is the legacy server token) — that implicit one (design §2「根管理员」).
An allow_empty_token deployment that declares no callers has NO root administrator (design §3): the only caller there is the empty anonymous id, which is not an administration identity, so nothing would be able to manage grants (the permission page is read-only). A deployment that declares callers keeps its can_admin root even with the flag set — the flag is ignored once a caller can be resolved, and dropping that root would take the root-only operations away from a deployment that has them today.
This is the rule the loader applies in place of「至少一个调用方带对应能力位」 (design §3「loader 规则」) and the rule authz.Derive derives the root set from.
func (ServerConfig) IsWebEnabled ¶
func (sc ServerConfig) IsWebEnabled() bool
IsWebEnabled reports whether the web console should be mounted. Unset (nil) defaults to true; an explicit web_enabled:false disables it.
func (*ServerConfig) RootAdminCallers ¶ added in v0.161.0
func (sc *ServerConfig) RootAdminCallers() []string
RootAdminCallers returns the caller ids the configuration names as root administrators: every declared user-class caller with `can_admin: true`, in declaration order, without duplicates. It does NOT include the implicit `default` caller of a single-token deployment — HasRootAdmin covers that case, and authz.Derive adds the id when the deployment really has that token.
Root administrator (design §2): holds every permission and is the only subject that may manage grants, independent of the governance switches; the web cannot revoke it. can_admin stays the operator's key for this — it is the one capability bit the permission catalog does not deprecate.
type ServerTunnelConfig ¶
type ServerTunnelConfig struct {
// ForwarderTTLSec is the lifetime of a `gofer tun forward` registration measured
// from its last heartbeat. 0/unset => tunnel.DefaultForwarderTTL (90s), which is
// three heartbeat intervals. Read per request, so a hot edit applies to the next
// registration read or write.
ForwarderTTLSec int `yaml:"forwarder_ttl_sec,omitempty"`
}
ServerTunnelConfig is the server.tunnel block (TUN-03): the hub-side policy of the tunnel VISIBILITY surface. Today it holds one knob — how long a forwarder registration without a heartbeat stays listed.
func (ServerTunnelConfig) EffectiveForwarderTTL ¶
func (t ServerTunnelConfig) EffectiveForwarderTTL() time.Duration
EffectiveForwarderTTL resolves the registered lifetime: the configured seconds, else tunnel.DefaultForwarderTTL. A negative or zero value is the default, never "expire immediately" — a value that would erase every live forwarder is not a useful knob.
type SessionConfig ¶
type SessionConfig struct {
// AutoRelayIdleSec is the keyboard idle threshold in seconds: when the hooks
// report the machine has seen no keyboard/mouse input for at least this
// long, a stopping session waits for a web reply even though nobody flipped
// its switch (and is released as soon as the human is back).
AutoRelayIdleSec *int `yaml:"auto_relay_idle_sec,omitempty"`
// AutoRelayTurnSec is the fallback threshold in seconds measured from the
// session's last HUMAN input: on a terminal whose idle cannot be probed at
// all (a container without X11 keeps reporting idle=-1), a session that has
// seen no human input for this long waits anyway. It exists because the
// keyboard lives on the host while the hook runs in the container.
AutoRelayTurnSec *int `yaml:"auto_relay_turn_sec,omitempty"`
// InjectCommands is the foreground-process whitelist of the tmux delivery
// path (session relay §9.1 A, `gofer session say --deliver`): a reply is typed
// into a pane only when the CLI sitting there is one of these. Empty keeps the
// built-in list (claude|codex|omp|node|gemini|opencode) — the guard exists
// because the human may have that pane in an editor by the time the web sends
// a message.
InjectCommands []string `yaml:"inject_commands,omitempty"`
// TakeoverInputDelayMs is path B's priming delay (design §9.1 B): how long
// the resumed TUI is given to settle — after its FIRST output and then with no
// new output for this long — before the web reply is typed into it. Unset
// keeps the default; 0 types the reply as soon as the TUI has drawn anything.
TakeoverInputDelayMs *int `yaml:"takeover_input_delay_ms,omitempty"`
// AutoRelaySkipWhenSupervising (SUP-01 D, bd h-aii-s2v4) keeps the auto rules
// from arming a session while its caller still has jobs in flight: whoever
// drives that caller is watching a job, not away, and an armed Stop would
// block the hook (and the job's completion notice) until they came back.
// Pointer so unset means ON and an explicit false opts out; it only ever
// applies to `auto` — `on` stays the human's explicit "wait for me".
AutoRelaySkipWhenSupervising *bool `yaml:"auto_relay_skip_when_supervising,omitempty"`
// SupervisingWindowSec is how far back that gate looks for the caller's live
// jobs (default DefaultSessionSupervisingWindowSec; 0 = no window, every live
// job counts). It bounds a stale job no human is actually watching any more.
SupervisingWindowSec *int `yaml:"supervising_window_sec,omitempty"`
// ProgressIntervalSec throttles PostToolUse progress heartbeats from the local
// hook. Zero disables in-progress updates; unset uses the default.
ProgressIntervalSec *int `yaml:"progress_interval_sec,omitempty"`
// OfflineAfterSec marks a session `offline` once it has been silent (no hook
// heartbeat) this long and is not legitimately waiting on a relay turn. A killed or
// crashed agent process never sends SessionEnd, so without this the row reads
// "running" forever. Pointer: unset keeps the default, 0 turns the sweep off.
OfflineAfterSec *int `yaml:"offline_after_sec,omitempty"`
// TakeoverAliveSec guards the web takeover (path B) against two processes writing
// one session: a session whose last hook heartbeat is younger than this is
// considered still alive and the takeover is refused (`session_alive`) — unless
// its agent has a deliver_command, which answers "is the process there" itself
// (exit 3 = not running). Unset = 120; 0 turns the guard off.
TakeoverAliveSec *int `yaml:"takeover_alive_sec,omitempty"`
// RelayOnWaitSec caps how long one Stop blocks for a web reply while the
// session's relay is explicitly `on` (N1 §C): the server hands it to the hook
// as wait_budget_sec and the hook uses min(--wait, budget). Unset = 3600; 0 =
// no server cap (the hook's own --wait decides).
RelayOnWaitSec *int `yaml:"relay_on_wait_sec,omitempty"`
// RelayAutoWaitSec is the same cap for a wait armed by the `auto` rules (idle
// probe / turn age). Unset = 600; 0 = no server cap.
RelayAutoWaitSec *int `yaml:"relay_auto_wait_sec,omitempty"`
// StopJobWait decides whether a Stop hook still blocks the terminal on the
// session's WATCHED JOBS — a plan bound to the main session, or a job carrying
// source_session_id. It is what keeps a person at the keyboard from being locked
// out of their terminal for the length of a job:
//
// away (default) block only when the person is away, judged by the same rule
// the relay itself uses: relay=on, or relay=auto with the keyboard idle
// at least auto_relay_idle_sec seconds. An UNKNOWN idle reading (a
// container with no desktop to probe) counts as "the person is here", and
// so does an explicit relay=off.
// always block whenever a watched job is pending (the behaviour before this key).
// never never block for jobs: the completion notice is caught up by the next
// SessionStart / UserPromptSubmit (catchUp).
//
// A released Stop is not a lost notice — the catch-up path covers all three — so
// `never` is the setting for someone who wants their terminal never held.
StopJobWait string `yaml:"stop_job_wait,omitempty"`
}
SessionConfig tunes the terminal session relay's automatic arming (R2). Both keys are POINTERS so "unset" (nil → the default below) is distinguishable from an explicit `0`, which turns that criterion OFF — the per-session switch is then the only gate for it. Same unset≠zero reasoning as JobRecoverWindowSec.
type SessionMessagingConfig ¶
type SessionMessagingConfig struct {
Enabled *bool `yaml:"enabled,omitempty"`
MessengerCommand string `yaml:"messenger_command,omitempty"`
MessengerTimeoutSec int `yaml:"messenger_timeout_sec,omitempty"`
MessengerIdleSec int `yaml:"messenger_idle_sec,omitempty"`
// MessengerMaxMessages and MessengerMaxAgeSec rotate the resident messenger
// process: once it has handled this many messages (or turns), or lived this
// long, the NEXT message starts a fresh process instead of growing the old
// one's context (gofer-li3t). Both are POINTERS for the same unset≠zero reason
// as JobRecoverWindowSec: an omitted key keeps the shipped default, while an
// explicit 0 disables that limit (no rotation). The rotation never interrupts a
// delivery in flight — it happens between two messages.
MessengerMaxMessages *int `yaml:"messenger_max_messages,omitempty"`
MessengerMaxAgeSec *int `yaml:"messenger_max_age_sec,omitempty"`
}
SessionMessagingConfig controls one-shot Claude SendMessage bridge jobs. Enabled is a pointer so an omitted key keeps the safe shipped default (on) while an explicit false disables the web button.
func (SessionMessagingConfig) MaxAge ¶ added in v0.184.0
func (c SessionMessagingConfig) MaxAge() time.Duration
MaxAge is the effective rotation limit on a resident process's lifetime. Same unset/0 rules as MaxMessages (0 = unlimited).
func (SessionMessagingConfig) MaxMessages ¶ added in v0.184.0
func (c SessionMessagingConfig) MaxMessages() int
MaxMessages is the effective rotation limit on messages a resident process may handle. An unset key (nil) and a negative value mean the shipped default; an explicit 0 means unlimited.
type SkillLimitsConfig ¶
type SkillLimitsConfig struct {
// MaxFileBytes caps ONE file inside a skill (0 => skill.DefaultLimits). An
// entry over it fails the whole import with the offending path named — a
// silently truncated skill would be worse than a refused one.
MaxFileBytes int64 `yaml:"max_file_bytes,omitempty"`
// MaxTotalBytes caps a skill's payload as a whole (0 => skill.DefaultLimits):
// the per-file cap alone would still allow a thousand just-under-the-cap files.
MaxTotalBytes int64 `yaml:"max_total_bytes,omitempty"`
}
SkillLimitsConfig is the server.skill_limits block (JOB-10 §一.2): the import-time size guards that stop one `agent skill import` from filling the config directory. Both fields resolve to internal/skill's defaults when zero, and the resolution lives THERE, not here — internal/skill depends on this package, so this one must not import it back (the same split as server.xfer).
type SplitResult ¶ added in v0.142.0
type SplitResult struct {
Main string // the main config file
Backup string // backup of the main file ("" for a dry run)
Files map[string]string // section -> new fragment file (absolute)
Skipped map[string]string // section -> why it was not moved
Include []string // the main file's include list afterwards
NewMain string // the main file's new text
}
SplitResult describes what SplitConfig did (or, for a dry run, would do).
func SplitConfig ¶ added in v0.142.0
SplitConfig moves top-level sections of the main config into one file each, <dir>/<section>.yaml (dir relative to the main file), and makes the main file include them (gofer-arsj). The text is MOVED, not re-rendered: a section's comments, key order and blank lines travel with it, and the comments above it go along — except a header above the first key of the file, which stays in the main file. The main file is backed up first; an existing target file is never overwritten. Afterwards the config is loaded again and its effective content compared with the original: any difference restores the main file, removes the new files and fails.
type StewardConfig ¶
type StewardConfig struct {
// Enabled switches the steward on. Off by default: it costs model usage.
Enabled bool `yaml:"enabled,omitempty"`
// Agent is the acp-agent that runs the steward session (any installed acp-agent:
// claude-acp, codex-acp, omp-acp, ...). Empty = not chosen yet (the steward cannot
// start). Changing it ends the running session; the next need rebuilds it from the
// prime on the new agent.
Agent string `yaml:"agent,omitempty"`
// Project is the project the session runs in (empty = the built-in `default`
// project, i.e. the server's default workspace).
Project string `yaml:"project,omitempty"`
// ReviewTime is the local wall-clock time ("HH:MM") of the daily review. Empty =
// ReviewLead before the work digest time.
ReviewTime string `yaml:"review_time,omitempty"`
// IdleEndMin is how long the session may sit idle before it ends (default 30).
IdleEndMin int `yaml:"idle_end_min,omitempty"`
// ReviewMaxItems caps the work items one review handles (default 20).
ReviewMaxItems int `yaml:"review_max_items,omitempty"`
// EventWake lets session / due / draft events wake the steward (batched, throttled).
// Off by default: events are then only noted and handled by the next review.
EventWake bool `yaml:"event_wake,omitempty"`
// EventThrottleMin is the minimum gap between two event-driven wakes (default 30).
EventThrottleMin int `yaml:"event_throttle_min,omitempty"`
}
StewardConfig is the top-level `steward:` block (W2b, design 2026-10-05 §9 / §14.4).
The steward is a resident ACP session that only schedules and tidies work items: it reads, notes, reminds, suggests merges and asks sessions to report, but never decides (no done / dropped, no job submit, no config). Everything it needs to carry on lives in the database (work items, journal, request ledger, steward notes), so the session is disposable and `agent` can be switched at any time.
func (StewardConfig) AgentName ¶
func (s StewardConfig) AgentName() string
AgentName is the configured steward agent ("" = none chosen).
func (StewardConfig) EventThrottle ¶
func (s StewardConfig) EventThrottle() time.Duration
EventThrottle is the minimum gap between event-driven wakes.
func (StewardConfig) IdleEnd ¶
func (s StewardConfig) IdleEnd() time.Duration
IdleEnd is how long the session may idle before ending.
func (StewardConfig) MaxReviewItems ¶
func (s StewardConfig) MaxReviewItems() int
MaxReviewItems is the per-review item cap.
func (StewardConfig) ProjectKey ¶
func (s StewardConfig) ProjectKey() string
ProjectKey is the project the steward session runs in.
func (StewardConfig) ReviewClock ¶
func (s StewardConfig) ReviewClock(w WorkConfig) (hour, minute int)
ReviewClock resolves the daily review time of day. An explicit valid review_time wins; otherwise it is ReviewLead before the work digest time (so the review's comment is ready when the digest goes out); a malformed value falls back to the derived one.
type StorageConfig ¶
type StorageConfig struct {
DefaultExchangeSubdir string `yaml:"default_exchange_subdir,omitempty"`
DefaultResultSubdir string `yaml:"default_result_subdir,omitempty"`
Root string `yaml:"root,omitempty"`
// DBPath is the optional explicit path to the SQLite metadata database. When
// empty it is resolved by ResolveDBPath from Root / the config dir.
DBPath string `yaml:"db_path,omitempty"`
// Retention bounds how many terminal jobs (and their logs) are kept; the
// periodic prune in serve enforces it. Unset (all fields <= 0) disables prune.
Retention RetentionConfig `yaml:"retention,omitempty"`
// MailRetentionDays is the mailbox's own 保存期 (设计 2026-10-16「默认数值」): a
// TERMINAL letter (delivered / answered / expired / failed / cancelled) older than
// this is deleted by the serve prune loop; a pending / delivering / held letter is
// kept whatever its age. Unset (0) takes mailRetentionDefaultDays; a negative value
// keeps letters forever.
MailRetentionDays int `yaml:"mail_retention_days,omitempty"`
// AttachmentRetentionDays is how long an uploaded workbench image is kept (sent or not);
// the serve prune loop deletes the expired ones. Unset (0) takes
// DefaultAttachmentRetentionDays (14); a negative value keeps attachments forever.
AttachmentRetentionDays int `yaml:"attachment_retention_days,omitempty"`
Cast CastConfig `yaml:"cast,omitempty"`
}
StorageConfig holds defaults for the per-project exchange/result subdirs and an optional global store root. When Root is empty (default), each project stores results under its own exchange subdir; when Root is set it becomes a global store keyed by project (see ResultBaseDir in internal/project).
func (StorageConfig) AttachmentRetention ¶ added in v0.177.0
func (s StorageConfig) AttachmentRetention() time.Duration
AttachmentRetention converts AttachmentRetentionDays into the retention window: 0 takes the default (14 days), a negative value returns 0 (keep forever).
func (StorageConfig) MailRetention ¶ added in v0.174.0
func (s StorageConfig) MailRetention() time.Duration
MailRetention converts MailRetentionDays into the retention window of the serve prune loop: 0 takes the default (90 days), a negative value disables the sweep (0 duration, keep forever).
type TLSConfig ¶
type TLSConfig struct {
Addr string `yaml:"addr,omitempty"`
CertFile string `yaml:"cert_file,omitempty"`
KeyFile string `yaml:"key_file,omitempty"`
}
TLSConfig configures the optional HTTPS listener and its certificate pair.
type Tool ¶ added in v0.140.0
type Tool struct {
// Name is the name the agent sees; required, unique case-insensitively.
Name string `yaml:"name" json:"name"`
// Desc is a one-line purpose / caveat; optional.
Desc string `yaml:"desc,omitempty" json:"desc,omitempty"`
// Bin is the executable name or absolute path; optional, defaults to Name. It is
// only shown to the agent and checked by validate / doctor.
Bin string `yaml:"bin,omitempty" json:"bin,omitempty"`
}
Tool is one external tool a runner declares as installed on its machine (CFG-16): ffmpeg, docker, an internal CLI... The list is DESCRIPTIVE only — it is rendered into the prompt of an agent job running on that machine and shown on the runners views; it never changes PATH, never calls the tool, and is not a scheduling constraint (labels / projects are). The same shape lives at the top level of config.yaml (the server-local runner) and of worker.yaml (that worker).
func (Tool) EffectiveBin ¶ added in v0.140.0
EffectiveBin is the executable the tool resolves to: Bin, else Name.
type TunnelProfile ¶
type TunnelProfile struct {
Worker string `yaml:"worker"`
Specs []string `yaml:"specs"`
Note string `yaml:"note,omitempty"`
Autostart bool `yaml:"autostart,omitempty"`
}
TunnelProfile is one saved `gofer tunnel forward` invocation: which worker to reach and which ports to forward through it.
func NormalizeTunnelProfile ¶
func NormalizeTunnelProfile(p TunnelProfile) (TunnelProfile, error)
NormalizeTunnelProfile returns p with its rule list flattened by tunnel.SplitSpecs: the comma form is a way to WRITE several rules, never a rule of its own, so it must not reach the local file, the server table or a `tun forward -n` run. Use this before validating a profile that came from a user.
type Tunnels ¶
type Tunnels struct {
Forwards map[string]TunnelProfile `yaml:"forwards"`
}
Tunnels is the whole preset file.
It deliberately lives in its OWN user-level file (<config-dir>/tunnels.yaml, alongside worker.yaml) rather than inside config.yaml: Save() re-emits every managed top-level key wholesale, so writing a preset through it would risk freezing runtime overlays and one-off CLI flags into the user's config, and Config.Clone would have to be widened first (D-MED-7).
func LoadTunnels ¶
LoadTunnels reads the preset file. A missing file is an empty set, not an error: presets are optional and the CLI must work on a machine that never saved one.
DEPRECATED(v0.60.2): remove in v0.63 — TUN-03 moved the source of truth to the server (`gofer tun presets`, the tunnel_presets table); the local file is now read only as a fallback for a preset the server does not have, and as the source `gofer tun presets push` uploads. New code reads the server.
type UpdateConfig ¶ added in v0.153.0
type UpdateConfig struct {
// Enabled runs the periodic check (nil = on). A manual check works either way.
Enabled *bool `yaml:"enabled,omitempty"`
// Interval between periodic checks, a Go duration ("2h"); "" = DefaultUpdateInterval.
Interval string `yaml:"interval,omitempty"`
// Proxy for reaching the source (http / https / socks5 URL); "" = the proxy
// environment variables.
Proxy string `yaml:"proxy,omitempty"`
// Repo is the GitHub owner/name whose latest release is checked ("" = DefaultUpdateRepo).
Repo string `yaml:"repo,omitempty"`
// LatestURL switches to a mirror: the URL of its latest.yaml ({name} placeholder).
LatestURL string `yaml:"latest_url,omitempty"`
// URLTemplate builds the mirror's download link ({name} {os} {arch} {ext} {version}).
URLTemplate string `yaml:"url_template,omitempty"`
}
UpdateConfig is server.update.
func (UpdateConfig) EffectiveInterval ¶ added in v0.153.0
func (u UpdateConfig) EffectiveInterval() time.Duration
EffectiveInterval is the periodic check interval after defaulting.
func (UpdateConfig) EffectiveRepo ¶ added in v0.153.0
func (u UpdateConfig) EffectiveRepo() string
EffectiveRepo is the GitHub repository after defaulting.
func (UpdateConfig) IsEnabled ¶ added in v0.153.0
func (u UpdateConfig) IsEnabled() bool
IsEnabled reports whether the periodic check runs (nil/absent = on).
func (UpdateConfig) UsesMirror ¶ added in v0.153.0
func (u UpdateConfig) UsesMirror() bool
UsesMirror reports whether a mirror replaces GitHub.
type WakeupConfig ¶
type WakeupConfig struct {
// TTLSec is how long a wakeup stays armed before the sweeper disables it
// (0/unset => DefaultWakeupTTLSec, 7 days). A wakeup nobody consumed is a leak
// in the sweeper's query set, so it expires on its own.
TTLSec int `yaml:"ttl_sec,omitempty"`
}
WakeupConfig is the top-level `wakeup:` block (JOB-09, design §五.1). Only the TTL lives here: a wakeup's shape is per-registration, and the sweeper rides the existing `schedule:` cadence rather than owning a second interval.
type WebhookConfig ¶
type WebhookConfig struct {
URL string `yaml:"url,omitempty"`
// MaxTextRunes overrides the notification-wide IM body rune budget when > 0.
MaxTextRunes int `yaml:"max_text_runes,omitempty"`
Events []string `yaml:"events,omitempty"`
// SecretEnv names the env var holding the shared secret. Its meaning follows
// Kind: generic → HMAC of the body in the X-Gofer-Signature header; dingtalk /
// feishu → the bot's 加签 secret (empty when the bot uses keyword or IP
// allow-list security instead).
SecretEnv string `yaml:"secret_env,omitempty"`
Projects []string `yaml:"projects,omitempty"`
// Kind selects the outbound adapter (OBS-07a; see WebhookKind* / ValidWebhookKind): "" / generic keeps the original
// `{event, job}` JSON contract; dingtalk / feishu render the provider's own bot
// message so a group robot shows a readable card.
Kind string `yaml:"kind,omitempty"`
// Enabled pauses ONE target without deleting it (S4, 2026-09-23). A pointer,
// nil = on: pausing a noisy robot keeps its url / secret_env / events, which
// deleting the entry would lose. A paused webhook is skipped at MATCH time
// (notify.MatchWebhooks), so no delivery row is created for it.
Enabled *bool `yaml:"enabled,omitempty"`
}
func (WebhookConfig) EffectiveMaxTextRunes ¶
func (w WebhookConfig) EffectiveMaxTextRunes(global int) int
func (WebhookConfig) IsEnabled ¶
func (w WebhookConfig) IsEnabled() bool
IsEnabled reports whether this webhook target is active (nil/absent = on).
type WorkConfig ¶
type WorkConfig struct {
// DigestTime is the local wall-clock time ("HH:MM") the daily `work.digest`
// notification is sent at. Empty keeps DefaultWorkDigestTime.
DigestTime string `yaml:"digest_time,omitempty"`
// DigestEnabled switches the daily digest off with an explicit false. Pointer:
// unset means ON.
DigestEnabled *bool `yaml:"digest_enabled,omitempty"`
// W2a passive tidy-up (design §14.2). SummarizerAgent is the cli-agent that runs the
// one-shot, read-only, tool-less summarizer job (default DefaultWorkSummarizerAgent);
// SummarizerArgs are its extra argv (default: a cheap-model preset for claude, see
// SummarizerArgsOrDefault); SummarizerProject names the project the job runs in
// (default: the work item's own project when it admits the agent and the local runner, else the built-in `default` project).
SummarizerAgent string `yaml:"summarizer_agent,omitempty"`
SummarizerArgs []string `yaml:"summarizer_args,omitempty"`
SummarizerProject string `yaml:"summarizer_project,omitempty"`
// SummarizerSessionMaxRuns / SummarizerSessionMaxAge rotate the summarizer's own
// agent session: it serves at most this many tidy-ups (default 20) and is replaced
// once it is older than the age (default 24h), so one long-lived session cannot grow
// without bound and does not carry yesterday's work forever.
SummarizerSessionMaxRuns int `yaml:"summarizer_session_max_runs,omitempty"`
SummarizerSessionMaxAge string `yaml:"summarizer_session_max_age,omitempty"`
// SummarizeEnabled switches the automatic tidy-up off with an explicit false
// (pointer: unset = ON). The manual 「整理」 action stays available.
SummarizeEnabled *bool `yaml:"summarize_enabled,omitempty"`
// SummarizeIdleMin is how long a session must be idle before it is tidied up
// (default 15). SummarizeMinIntervalMin is the minimum gap between two tidy-ups of
// one session (default 30). SummarizeDailyLimit caps automatic runs per day
// (default 50; a negative value means unlimited).
SummarizeIdleMin int `yaml:"summarize_idle_min,omitempty"`
SummarizeMinIntervalMin int `yaml:"summarize_min_interval_min,omitempty"`
SummarizeDailyLimit int `yaml:"summarize_daily_limit,omitempty"`
// AutoHandoff turns the automatic hand-over request (when a person parks an item or
// marks it needs_onsite) off with an explicit false (pointer: unset = ON).
AutoHandoff *bool `yaml:"auto_handoff,omitempty"`
// RequestTimeoutMin is how long a report / hand-over request may stay unanswered
// before it expires and the item is tidied up instead (default 30).
RequestTimeoutMin int `yaml:"request_timeout_min,omitempty"`
// NeedsMeNotify turns the `work.needs_me` notification on (pointer: unset = OFF —
// unlike the digest it is chatty, so it is opt-in). NeedsMeThrottleMin is the
// minimum gap between two such notifications for ONE work item (default 30).
NeedsMeNotify *bool `yaml:"needs_me_notify,omitempty"`
NeedsMeThrottleMin int `yaml:"needs_me_throttle_min,omitempty"`
// StallAfter is how long an active work item / running plan may go without journal,
// linked-job or session activity before the Today lane marks it stalled (N3 §3.2), as
// a Go duration ("4h", "90m"). Empty = DefaultWorkStallAfter.
StallAfter string `yaml:"stall_after,omitempty"`
}
WorkConfig is the top-level `work:` block (work items, design 2026-10-05).
func (WorkConfig) AutoHandoffOn ¶
func (w WorkConfig) AutoHandoffOn() bool
AutoHandoffOn reports whether parking / needs_onsite auto-requests a hand-over.
func (WorkConfig) DigestClock ¶
func (w WorkConfig) DigestClock() (hour, minute int)
DigestClock resolves digest_time to (hour, minute); a malformed or empty value falls back to DefaultWorkDigestTime so a typo never silently disables the digest.
func (WorkConfig) NeedsMeNotifyOn ¶
func (w WorkConfig) NeedsMeNotifyOn() bool
NeedsMeNotifyOn reports whether work.needs_me notifications are on (default OFF).
func (WorkConfig) NeedsMeThrottle ¶
func (w WorkConfig) NeedsMeThrottle() time.Duration
NeedsMeThrottle is the per-item minimum gap between two work.needs_me notifications.
func (WorkConfig) RequestTimeout ¶
func (w WorkConfig) RequestTimeout() time.Duration
RequestTimeout is how long a report / hand-over request may stay unanswered.
func (WorkConfig) StallAfterDuration ¶
func (w WorkConfig) StallAfterDuration() time.Duration
StallAfterDuration resolves work.stall_after; a malformed or non-positive value (which validate refuses on load) falls back to the default.
func (WorkConfig) SummarizeDaily ¶
func (w WorkConfig) SummarizeDaily() int
SummarizeDaily is the cap of automatic tidy-ups per day; 0 = unlimited.
func (WorkConfig) SummarizeIdle ¶
func (w WorkConfig) SummarizeIdle() time.Duration
SummarizeIdle is the idle threshold before a session is tidied up.
func (WorkConfig) SummarizeMinInterval ¶
func (w WorkConfig) SummarizeMinInterval() time.Duration
SummarizeMinInterval is the minimum gap between two tidy-ups of one session.
func (WorkConfig) SummarizeOn ¶
func (w WorkConfig) SummarizeOn() bool
SummarizeOn reports whether the automatic tidy-up is on (default true).
func (WorkConfig) SummarizerAgentName ¶
func (w WorkConfig) SummarizerAgentName() string
SummarizerAgentName is the configured summarizer agent or the default.
func (WorkConfig) SummarizerArgsOrDefault ¶
func (w WorkConfig) SummarizerArgsOrDefault() []string
SummarizerArgsOrDefault returns the extra argv of the summarizer job: the configured list, or — for the default claude agent only — a cheap-model, no-tools preset that also leaves no session file behind. Any other agent without args gets none (the operator picks its model).
func (WorkConfig) SummarizerSessionAge ¶ added in v0.184.0
func (w WorkConfig) SummarizerSessionAge() time.Duration
SummarizerSessionAge is how long one summarizer session may be reused (a negative / malformed value falls back to the default; validate refuses it on load).
func (WorkConfig) SummarizerSessionRuns ¶ added in v0.184.0
func (w WorkConfig) SummarizerSessionRuns() int
SummarizerSessionRuns is the number of tidy-ups one summarizer session serves before it is rotated (0 unset = the default; a negative value means never rotate by count).
func (WorkConfig) WorkDigestEnabled ¶
func (w WorkConfig) WorkDigestEnabled() bool
WorkDigestEnabled reports whether the daily digest is on (default true).
type WorkerAuthConfig ¶
type WorkerAuthConfig struct {
Token string `yaml:"token,omitempty"`
TokenEnv string `yaml:"token_env,omitempty"`
Labels []string `yaml:"labels,omitempty"`
}
WorkerAuthConfig registers one legitimate worker identity on the server side (ws-worker §7 / review #1). Token is the literal bearer token; TokenEnv reads it from the named environment variable instead (so the secret stays out of the config file). The worker_id (the map key) is used as the caller id for jobs it runs. Labels are display/scheduling hints only (WP4 auto-scheduling).
type WorkerConfig ¶
type WorkerConfig struct {
WorkerID string `yaml:"worker_id,omitempty"`
ServerLink WorkerServerLink `yaml:"server_link,omitempty"`
Projects map[string]ProjectConfig `yaml:"projects,omitempty"`
Agents map[string]AgentConfig `yaml:"agents,omitempty"`
Runners map[string]RunnerConfig `yaml:"runners,omitempty"`
MaxConcurrent int `yaml:"max_concurrent,omitempty"`
Labels []string `yaml:"labels,omitempty"`
Storage StorageConfig `yaml:"storage,omitempty"`
Log LogConfig `yaml:"log,omitempty"`
// Roots maps server-side logical path prefixes to this machine's host path
// prefixes (P3 T2, design §10). Longest boundary-aligned From wins; see
// MapRoot. Adding a root deliberately widens what this worker can run, so it
// is a local-only knob (never remotely rewritten, never API-exposed, T2-C).
Roots []WorkerRoot `yaml:"roots,omitempty"`
// Guards are opt-in per-worker capability gates (P3 T2-D). See WorkerGuards.
Guards WorkerGuards `yaml:"guards,omitempty"`
Tunnel WorkerTunnelConfig `yaml:"tunnel,omitempty"`
// XferTimeoutSec bounds ONE inbound file transfer on this worker (XFER-01
// protocol v9). 0/unset => DefaultWorkerXferTimeoutSec (10m). It is a
// PROCESS-level setting like the rest of this block: it is read when the worker
// starts serving, not on hot reload (the hub cannot know this worker's budget, so
// the executing machine is the only place it can live).
XferTimeoutSec int `yaml:"xfer_timeout_sec,omitempty"`
// Tools are the external tools installed on this worker machine (CFG-16): listed
// in the prompt of every agent job it runs and reported to the hub with the other
// capabilities (hot-reloaded like labels). See config.Tool.
Tools []Tool `yaml:"tools,omitempty"`
}
WorkerConfig is the top-level config for `gofer worker --config worker.yaml` (ws-worker §6). The worker runs jobs locally with its own project/agent/runner config and bridges log/status/result back over a single WebSocket to the hub.
func DecodeWorkerConfig ¶ added in v0.143.0
func DecodeWorkerConfig(path string, data []byte) (*WorkerConfig, error)
DecodeWorkerConfig decodes and validates a worker.yaml read from path (path only names the file in errors): agent extends, removed keys, local paths, log defaults, tunnel and tools. Shared by the worker command and `gofer config lint`.
func (WorkerConfig) EffectiveXferTimeout ¶
func (w WorkerConfig) EffectiveXferTimeout() time.Duration
EffectiveXferTimeout resolves worker.xfer_timeout_sec, defaulting to DefaultWorkerXferTimeoutSec.
func (*WorkerConfig) MapRoot ¶
func (wc *WorkerConfig) MapRoot(logical string) (host string, ok bool)
MapRoot resolves a server-side logical path to this worker's host path using the longest boundary-aligned roots prefix (design §10-Q1, P3 T2-B). It returns (host, true) only when some root's From is a boundary-aligned prefix of logical (longest wins) AND the mapping does not escape that root on either side.
Normalization: backslashes -> '/', trailing slashes trimmed. Windows-style (drive-letter) From prefixes match case-insensitively (D:/work == d:/work); POSIX From prefixes match case-sensitively.
Boundary alignment: /a/b must NOT match /a/bc — only an exact match or a '/' at logical[len(from)] counts.
Containment (B6) is enforced HERE, not delegated to project.SafeJoin (which is purely lexical Abs/Clean/Rel and does NOT resolve symlinks):
- roots carrying a ".." segment are misconfigured -> reject;
- logical side: after "..", the logical path must still fall under From;
- host side: the joined host must resolve under To both lexically AND through symlinks (EvalSymlinks on the existing prefix, non-existent tail re-appended).
On any miss or containment violation it returns ("", false); it NEVER returns an empty host as "success".
The returned host is slash-normalized (filepath.ToSlash): MapRoot is a logical-path resolver and its output must be identical on every GOOS. Go's file APIs accept forward slashes on Windows, so callers can use the result as a host path directly.
type WorkerEnrollmentConfig ¶ added in v0.169.0
type WorkerEnrollmentConfig struct {
// Enabled accepts new enrollment requests (default false). Turning it off never
// strands requests already in flight: the sweeper still expires them.
Enabled bool `yaml:"enabled,omitempty"`
// DecideSec is how long an administrator has to decide (default 120; 30-600).
DecideSec int `yaml:"decide_sec,omitempty"`
// CollectSec is how long the applicant has to collect its token (default 60; 30-600).
CollectSec int `yaml:"collect_sec,omitempty"`
// PerSourcePerMin caps requests per source address per minute (default 3; 1-60).
PerSourcePerMin int `yaml:"per_source_per_min,omitempty"`
// MaxPending caps open requests server-wide (default 20; 1-200).
MaxPending int `yaml:"max_pending,omitempty"`
// TrustedProxies lists CIDRs of reverse proxies whose forwarded-for header may be
// believed when deriving a request's source address. Empty = the connection address.
TrustedProxies []string `yaml:"trusted_proxies,omitempty"`
}
WorkerEnrollmentConfig is server.worker_enrollment: the self-service worker registration switch and its limits. Zero numeric fields mean the default. The whole block is hot-reloadable and read from the current config snapshot on every request; TrustedProxies is file-only (the console cannot edit it).
func (WorkerEnrollmentConfig) EffectiveCollectSec ¶ added in v0.169.0
func (w WorkerEnrollmentConfig) EffectiveCollectSec() int
EffectiveCollectSec returns the collect window in seconds after defaulting.
func (WorkerEnrollmentConfig) EffectiveDecideSec ¶ added in v0.169.0
func (w WorkerEnrollmentConfig) EffectiveDecideSec() int
EffectiveDecideSec returns the decision window in seconds after defaulting.
func (WorkerEnrollmentConfig) EffectiveMaxPending ¶ added in v0.169.0
func (w WorkerEnrollmentConfig) EffectiveMaxPending() int
EffectiveMaxPending returns the global pending cap after defaulting.
func (WorkerEnrollmentConfig) EffectivePerSourcePerMin ¶ added in v0.169.0
func (w WorkerEnrollmentConfig) EffectivePerSourcePerMin() int
EffectivePerSourcePerMin returns the per-source rate after defaulting.
func (WorkerEnrollmentConfig) TrustedProxyPrefixes ¶ added in v0.169.0
func (w WorkerEnrollmentConfig) TrustedProxyPrefixes() []netip.Prefix
TrustedProxyPrefixes parses TrustedProxies (already validated at load time; entries that fail to parse are skipped).
type WorkerGuards ¶
type WorkerGuards struct {
AllowExec *bool `yaml:"allow_exec,omitempty"`
AllowInteractive *bool `yaml:"allow_interactive,omitempty"`
}
WorkerGuards are opt-in capability gates for the worker (P3 T2-D).
The fields are *bool (not bool) on purpose, diverging from design §6.1's "default false": nil (field absent) means "do NOT tighten" — identical to today's behaviour where no guards exist and every project runs exec/pty. A bare bool zero value would flip to false and reject all exec/pty jobs the instant the binary is upgraded (violates acceptance 1). This mirrors the established *bool idiom in this repo (ProjectConfig.CaptureDiff / NotifyEnabled). Enforcement is therefore opt-in: set the field explicitly to tighten. (worker.example.yaml's explicit guards + doctor WARN are T6.)
func (WorkerGuards) IsExecAllowed ¶
func (g WorkerGuards) IsExecAllowed() bool
IsExecAllowed reports whether exec jobs are permitted. Unset (nil) => allowed (no extra tightening, T2-D); an explicit allow_exec:false rejects them.
func (WorkerGuards) IsInteractiveAllowed ¶
func (g WorkerGuards) IsInteractiveAllowed() bool
IsInteractiveAllowed reports whether interactive/pty jobs are permitted. Unset (nil) => allowed (T2-D); an explicit allow_interactive:false rejects them.
type WorkerRoot ¶
type WorkerRoot struct {
From string `yaml:"from"` // server-side logical path prefix
To string `yaml:"to"` // this machine's host path prefix
}
WorkerRoot maps a server-side logical path prefix (From) onto this worker's host path prefix (To). It is the ONLY declaration a worker needs to expose a tree for execution: matching + containment live in WorkerConfig.MapRoot.
type WorkerServerLink ¶
type WorkerServerLink struct {
URLs []string `yaml:"urls,omitempty"`
TokenEnv string `yaml:"token_env,omitempty"`
Token string `yaml:"token,omitempty"`
Reconnect ReconnectConfig `yaml:"reconnect,omitempty"`
}
WorkerServerLink describes how the worker reaches the hub. URLs may list MULTIPLE hub addresses (redundant entry points: VIPs of one hub, or several independent hubs); the worker rotates through them on a failed connect (C7, §5.2). Token/TokenEnv resolve the Bearer credential. Reconnect tunes the backoff + heartbeat timings (P3 §4).
type WorkerTunnelConfig ¶
type WorkerTunnelConfig struct {
Allow []string `yaml:"allow,omitempty"`
MaxConns int `yaml:"max_conns,omitempty"`
DialTimeoutSec int `yaml:"dial_timeout_sec,omitempty"`
}
WorkerTunnelConfig controls outbound TCP tunnels.
func (WorkerTunnelConfig) DialTimeout ¶
func (t WorkerTunnelConfig) DialTimeout() time.Duration
DialTimeout returns configured timeout or default 5 seconds.
func (WorkerTunnelConfig) EffectiveMaxConns ¶
func (t WorkerTunnelConfig) EffectiveMaxConns() int
EffectiveMaxConns returns configured limit or default 8.
func (WorkerTunnelConfig) Enabled ¶
func (t WorkerTunnelConfig) Enabled() bool
Enabled reports whether any tunnel target is allowed.
type XferConfig ¶
type XferConfig struct {
// MaxBytes caps ONE transfer's payload (0 => 256MB).
MaxBytes int64 `yaml:"max_bytes,omitempty"`
// TTLSec is how long a staged/finished transfer is kept before the prune sweep
// expires it and drops its staging directory (0 => 24h).
TTLSec int `yaml:"ttl_sec,omitempty"`
// CollectMaxBytes caps what ONE JOB's `--collect` brings back in total
// (0 => 1GB). Each collected file is still bounded by MaxBytes: this is the sum,
// so a job cannot fill the server's disk with a hundred just-under-the-cap files.
// Files beyond it are skipped and listed in the job's xfer.skipped.
CollectMaxBytes int64 `yaml:"collect_max_bytes,omitempty"`
}
XferConfig is the server.xfer block (XFER-01, design §一.1/§一.2). Every field is optional and resolved at ASSEMBLY time (core.Build), not here: internal/xfer owns the defaults and depends on this package, so this one must not import it back.
Source Files
¶
- agent_integration.go
- attachments.go
- budget.go
- ceiling.go
- config.go
- decision_hooks.go
- default_project.go
- delivery.go
- dotenv.go
- editable.go
- event_hooks.go
- extends.go
- hold.go
- httpproxy.go
- include.go
- loader.go
- mail.go
- mcp.go
- model.go
- overlay.go
- paths.go
- pricing.go
- project_worktree.go
- readonly.go
- reload.go
- resolve.go
- retry.go
- rules.go
- secrets.go
- skills.go
- split.go
- steward.go
- tools.go
- tunnels.go
- update.go
- worker_decode.go
- worker_enrollment.go
- worker_register.go
- worker_roots.go
- workspace.go
- writer.go