Documentation
¶
Overview ¶
Package sessionrelay is the session-relay domain service (SESS-01): terminal agent-CLI sessions (Claude Code / Codex) register themselves through their hooks, the web observes them, and while a session's relay switch is on the Stop hook posts the agent's last message as a "turn" and blocks until a human answers it on the web — the answer is injected back into the SAME terminal session via the hook's `decision: block` continuation.
Turns are plan_decisions rows (kind='relay', session_id set) so the existing bell / decision card / lazy-expiry machinery serves them unchanged (design D3). The package depends only on jobstore (data layer) and is consumed by httpapi (entry layer), never the other way round (G022).
Index ¶
- Constants
- Variables
- func DefaultInjectCommands() []string
- func DefaultState(event string) string
- func DeliverReason(err error) string
- func EffectiveTopic(a jobstore.AgentSession, roots []string) (topic, source string)
- func EncodeClaudeProjectDir(path string) string
- func ExplainReason(reason string, a jobstore.AgentSession, cause error) string
- func FormatJobEndedNotice(n JobEndedNotice) string
- func InferTopic(a jobstore.AgentSession, roots []string) string
- func IsDeliverableState(st string) bool
- func NormalizeScope(items []string) ([]string, error)
- func ParseQuestionAnswer(answer string, qs []Question) (string, error)
- func PermissionMessage(summary string) string
- func QuestionMessage(q string) string
- func SuggestTerms(text string) []string
- func TranscriptProjectDirName(transcript string) string
- type CommandPlan
- type CwdChoice
- type DeliverResult
- type Detail
- type FindHit
- type FindQuery
- type FindResult
- type HeartbeatInput
- type InjectProbe
- type InjectRequest
- type InjectResult
- type InjectState
- type Injector
- type InjectorFunc
- type JobEndedNotice
- type Messenger
- type MessengerAbandoner
- type Notifier
- type NudgeInput
- type NudgeNotifier
- type PermissionAnswer
- type PermissionDetail
- type PermissionInput
- type PermissionSuggestion
- type Question
- type QuestionOption
- type RawResult
- type RegisterInput
- type ResidentMessenger
- type ResumePlan
- type Service
- func (s *Service) AckTurn(sid, decisionID, by string) (jobstore.PlanDecision, error)
- func (s *Service) AddJobWatch(sid, jobID string) (jobstore.SessionJobWatch, error)
- func (s *Service) AnswerPermission(sid, id, answer, by string) (jobstore.PlanDecision, error)
- func (s *Service) AutoArmed(a jobstore.AgentSession) bool
- func (s *Service) CheckDeliverable(sid string) error
- func (s *Service) ClaimSupervisedJobs(a jobstore.AgentSession)
- func (s *Service) CompleteMailTurn(sid, turnID string, opts jobstore.TakeMailOpts) (bool, []jobstore.TakenMail, error)
- func (s *Service) CompleteWatchedJobs(sid string, jobIDs []string) (bool, error)
- func (s *Service) CompleteWatchedTurn(sid, turnID string, jobIDs []string) (bool, error)
- func (s *Service) ConfigureMessaging(enabled bool, command string, timeout, idle time.Duration)
- func (s *Service) CreateNudge(sid string, in NudgeInput) (jobstore.SessionNudge, error)
- func (s *Service) Delete(sid string) error
- func (s *Service) Deliver(ctx context.Context, sid, text, by, origin string, allowTakeover bool) (DeliverResult, error)
- func (s *Service) DeliverLetter(ctx context.Context, sid, text, by, origin string) (RawResult, error)
- func (s *Service) Find(q FindQuery) ([]FindResult, error)
- func (s *Service) FollowWeb(sid, actor string)
- func (s *Service) Get(sid string, turnLimit int, before string) (Detail, error)
- func (s *Service) Heartbeat(sid string, in HeartbeatInput) (jobstore.AgentSession, error)
- func (s *Service) HeartbeatForOwner(sid string, in HeartbeatInput) (jobstore.AgentSession, error)
- func (s *Service) IsServerLocalRunner(label string) bool
- func (s *Service) JobWatches(sid string) ([]jobstore.SessionJobWatch, error)
- func (s *Service) List(opts jobstore.ListSessionsOpts) ([]jobstore.AgentSession, error)
- func (s *Service) NotifyJobEnded(ctx context.Context, n JobEndedNotice) error
- func (s *Service) Nudge(id string) (jobstore.SessionNudge, error)
- func (s *Service) Nudges(sid string, includeEnded bool) ([]jobstore.SessionNudge, error)
- func (s *Service) OnAnswered(d jobstore.PlanDecision)
- func (s *Service) OpenPermission(sid string, in PermissionInput) (jobstore.PlanDecision, error)
- func (s *Service) OpenTurn(sid, body string, timeoutSec int64) (jobstore.PlanDecision, error)
- func (s *Service) PauseNudge(id string) (jobstore.SessionNudge, error)
- func (s *Service) PermissionWaitReason(a jobstore.AgentSession) string
- func (s *Service) PlanResume(sid string) (ResumePlan, error)
- func (s *Service) PlanResumeFor(a jobstore.AgentSession) ResumePlan
- func (s *Service) ReconcileDeliveries(sid string) error
- func (s *Service) ReconcileDeliveryJob(jobID string) (bool, error)
- func (s *Service) RecordMessengerReply(runner, peerName, from, body string) (jobstore.SessionMessage, bool, error)
- func (s *Service) RecordReply(sid, text, peer, source, caller string) (m jobstore.SessionMessage, created bool, err error)
- func (s *Service) Register(in RegisterInput) (jobstore.AgentSession, error)
- func (s *Service) RegisterForOwner(in RegisterInput) (jobstore.AgentSession, bool, error)
- func (s *Service) RelayDemotedAt(a jobstore.AgentSession) int64
- func (s *Service) ReleaseTakeover(ctx context.Context, sid string) (jobstore.AgentSession, error)
- func (s *Service) ReleaseTakeoverForJob(ctx context.Context, jobID string) (bool, error)
- func (s *Service) ReleaseTurn(sid, turnID string, idleSec int64) (bool, error)
- func (s *Service) RemoveJobWatch(sid, jobID string) (bool, error)
- func (s *Service) RemoveNudge(id string) error
- func (s *Service) Resolve(cwd string) ([]jobstore.AgentSession, error)
- func (s *Service) ResolvePermissions(sid, fp string) (int, error)
- func (s *Service) Resume(ctx context.Context, sid, initialInput, by, origin string) (DeliverResult, error)
- func (s *Service) ResumeNudge(id string) (jobstore.SessionNudge, error)
- func (s *Service) Say(sid, answer, by string) (jobstore.PlanDecision, error)
- func (s *Service) SendMessage(ctx context.Context, sid, text, operator, origin string) (jobstore.SessionMessage, error)
- func (s *Service) Session(sid string) (jobstore.AgentSession, error)
- func (s *Service) SetAgentInjectLookup(fn func(agentKey string) []string)
- func (s *Service) SetDeliverPlanner(fn func(agentKey, sessionID, text string) CommandPlan)
- func (s *Service) SetInjectCommands(cmds []string)
- func (s *Service) SetInjectProbe(p InjectProbe)
- func (s *Service) SetInjector(i Injector)
- func (s *Service) SetMessenger(m Messenger)
- func (s *Service) SetNotifier(n Notifier)
- func (s *Service) SetPollInterval(d time.Duration)
- func (s *Service) SetRelayMode(sid, mode string) (jobstore.AgentSession, error)
- func (s *Service) SetRelayModeBy(sid, mode, actor string) (jobstore.AgentSession, error)
- func (s *Service) SetRestrictedCallers(fn func() bool)
- func (s *Service) SetSessionOwner(sid, callerID, by string) (a jobstore.AgentSession, from string, err error)
- func (s *Service) SetTakeoverAliveSec(sec int)
- func (s *Service) SetTakeoverer(t Takeoverer)
- func (s *Service) SetTopic(sid string, topic *string, scope *[]string, source string) (jobstore.AgentSession, error)
- func (s *Service) SetWaitBudgets(onSec, autoSec int)
- func (s *Service) SetWorkHook(h WorkHook)
- func (s *Service) SubagentCount(sid string) int
- func (s *Service) Suggest(q SuggestQuery) ([]SuggestResult, error)
- func (s *Service) SweepNudges(ctx context.Context, now int64) int
- func (s *Service) UnackTurn(sid, decisionID string) (jobstore.PlanDecision, error)
- func (s *Service) WaitBudgetSec(reason string) int
- func (s *Service) WaitDecision(a jobstore.AgentSession) (reason, detail string)
- func (s *Service) WaitReason(a jobstore.AgentSession) string
- func (s *Service) WaitTurn(ctx context.Context, sid, decisionID string, wait time.Duration) (TurnStatus, error)
- func (s *Service) Wake(ctx context.Context, sid, text, by, origin string) (RawResult, error)
- type SuggestQuery
- type SuggestResult
- type TakeoverPlan
- type TakeoverRequest
- type TakeoverResult
- type Takeoverer
- type TurnStatus
- type UndeliverableError
- type WorkHook
Constants ¶
const ( // PathTurn is phase 1: the reply answers the session's OPEN turn and the // blocked Stop hook injects it back into the same terminal. PathTurn = "turn" // PathTmux is path A: the session is idle at its prompt, so the reply is // typed into its tmux pane by an internal exec job. PathTmux = "tmux" // PathTakeover is path B: the session had no usable tmux pane, so an // interactive pty job continues it (`--resume`) and the reply is primed into // that new terminal. PathTakeover = "takeover" // PathCommand is path C: the session's agent declares a deliver_command, which is // run on the session's runner and hands the text to the LIVE agent process (the // agent owns its own local inter-process channel; gofer only runs the command). PathCommand = "command" )
Delivery paths reported by DeliverResult.Path (design §9.1 选路).
const ( // ReasonNotRunning: the deliver_command ran and reported (exit 3) that no process // of this session is running. Delivery continues down the ladder (tmux, takeover). ReasonNotRunning = "not_running" // DeliverFailedPrefix introduces a deliver_command failure (any other exit code, // or the job could not run); the remainder is the command's stderr / job error. // Delivery STOPS here — falling through to tmux could type the message twice. DeliverFailedPrefix = "deliver_failed:" // ReasonSessionAlive: a takeover was refused because the original process still // looks alive (a recent hook heartbeat, or — with a deliver_command — never // reported not_running), and two processes writing one session would fork it. ReasonSessionAlive = "session_alive" )
Path C outcomes besides success (the deliver_command's exit code contract).
const ( // ReasonNoRunner: the session never registered an execution machine, so // there is nothing to dispatch to (a container session needs a gofer worker // in the container and GOFER_HOOK_RUNNER pointing at it). ReasonNoRunner = "no_runner" // ReasonNoTmux: no tmux pane was registered — the session cannot be typed // into (path B, `--resume` takeover, is the fallback for those). ReasonNoTmux = "no_tmux" // ReasonNoProject / ReasonNoMessenger: the messenger path's preconditions (CheckDeliverable). ReasonNoProject = "no_project" ReasonNoMessenger = "no_messenger" // ReasonEnded: the CLI session is over. ReasonEnded = "ended" // InjectFailedPrefix introduces a failure of an ATTEMPTED injection; the // remainder is pane_missing, pane_busy:<cmd> or runner_error. InjectFailedPrefix = "inject_failed:" // ReasonNoResumeTemplate: path B's precondition — the session's agent is not a // cli-agent with an interactive resume template (`--resume <sid>`), so there is // no argv that would continue the conversation. ReasonNoResumeTemplate = "no_resume_template" // ReasonInteractiveNotAllowed: path B's precondition — the session's project // does not allow interactive (pty) jobs, so gofer will not start one. ReasonInteractiveNotAllowed = "interactive_not_allowed" // ReasonCwdOutsideProject: path B's precondition — the session's cwd cannot be // expressed relative to the project root the RUNNER sees, so the resumed // process would start in the wrong directory (a real possibility when POLICY // root mapping gives a worker a different absolute path than the hub's). ReasonCwdOutsideProject = "cwd_outside_project" // NotDeliveredPrefix introduces the failure of a delivery that provably never // reached the session: the internal job behind it had NOT STARTED when gofer's // wait window elapsed (an update pausing new jobs, a backlog on the runner) and // gofer cancelled it, so nothing will arrive later. The remainder is the job's // status; the message text says why the machine was not running it, because an // exit code nobody produced answers nothing. A message recorded with this reason // is safe to RETRY (see deliveryNeverStarted). NotDeliveredPrefix = "not_delivered:" // HandedOffPrefix introduces path B's "already taken over" reason: the session // is held by the job named after the prefix, and that job must be released // before anything else may speak to this session. HandedOffPrefix = "handed_off:" )
Why a delivery could not even be attempted (design §9.1 v0.5 failure codes). An injection that was attempted but failed reports InjectFailedPrefix plus the pane check's own code instead.
const ( HitScope = "scope" // a scope equals the query path or is an ancestor of it (strong) HitScopeWeak = "scope_weak" // the query path is an ancestor of a scope (weak) HitTopic = "topic" HitPeerName = "peer_name" HitProject = "project" )
Hit kinds (FindHit.Kind).
const ( CwdSourceTranscript = "transcript" // verified against the transcript's directory name CwdSourceRegistered = "registered" // the cwd the session registered CwdSourceProjectRoot = "project_root" // the project root as the runner sees it )
Wake-up directory sources (CwdChoice.Source).
const ( // ReleaseByTerminal: the prompt was settled in the terminal (the tool ran, the // person answered No / Esc — the hook reports it when Claude Code SIGTERMs it —, // typed a new prompt, the turn stopped or was interrupted). ReleaseByTerminal = "terminal" // ReleaseBySuperseded: a newer prompt of the same session replaced it. ReleaseBySuperseded = "superseded" )
Release tags of a permission decision closed without a web answer.
const ( PermissionAllow = "allow" PermissionDeny = "deny" PermissionAlwaysPrefix = "always:" )
Permission answers stored on the decision (and accepted by AnswerPermission).
const ( EventSessionStart = "SessionStart" EventUserPromptSubmit = "UserPromptSubmit" EventStop = "Stop" EventSessionEnd = "SessionEnd" EventNotification = "Notification" EventInterrupt = "Interrupt" )
Hook event names shared by Claude Code and Codex (the hook stdin `hook_event_name`). Notification / Interrupt are agent-specific.
const ( TurnOpen = "open" // still waiting (the wait window elapsed) TurnAnswered = "answered" // a human answered; Decision.Answer holds the reply TurnExpired = "expired" // decision timeout hit (lazy expiry) TurnRelayOff = "relay_off" // relay switched off while waiting → hook must release )
Turn outcomes reported by WaitTurn.
const ( AuditRelayAutoDemoted = "session.relay_auto_demoted" AuditRelaySet = "session.relay_set" )
Audit kinds of the relay switch: an automatic on → auto demotion (the human typed in the terminal) and an explicit set from the CLI / web. RelayDemotedAt compares them.
const ( // WaitModeOn is the human's explicit switch: every Stop waits. WaitModeOn = "mode_on" // WaitIdleProbe is the keyboard idle rule: the hook's system input reading // reached the threshold, and the wait is released when it drops back. WaitIdleProbe = "idle_probe" // WaitTurnAge is the fallback for a terminal that cannot be probed at all // (containers without X11): enough time passed since the last HUMAN input in // this session, and the wait is released by the next human-input event // (Esc / typing) rather than by a reading. WaitTurnAge = "turn_age" )
Wait reasons: why a Stop waits for a web reply, reported to the hook so it can log/pick its poll cadence (R2). "" = it does not wait at all.
const ( EventSubagentStart = "SubagentStart" EventSubagentStop = "SubagentStop" )
Sub-agent awareness (N1 §C, SESS-10). Claude Code raises SubagentStart / SubagentStop hooks around every sub-agent; the hook reports them as heartbeat events with a +1/-1 delta and the sub-agent's id. A session with sub-agents in flight is being supervised just like one with live jobs (SUP-01 D): `auto` does not arm, and when the last sub-agent finishes while a Stop hook is already blocked on an auto-armed wait, that wait is released so the main agent can consume the result.
const AuditPermissionAnswered = "session.permission_answered"
AuditPermissionAnswered records who answered a permission prompt from the web.
const AuditRelayFollowWeb = "session.relay_follow_web"
AuditRelayFollowWeb records a session switched to the web because a person reached it from there (FollowWeb).
const (
// DefaultSuggestLimit is the number of candidates the capture box offers (decision 10).
DefaultSuggestLimit = 3
)
const EventPermissionRequest = "PermissionRequest"
EventPermissionRequest is Claude Code's permission-prompt hook event.
const InjectPrefix = "[gofer web 回复] "
InjectPrefix marks the text path A types into the terminal (design D7). The hook keys on it to recognise its own input: it MUST stay identical to hookrelay.ReplyPrefix, which a test in that package pins.
const JobDoneTag = "[gofer job 完成]"
JobDoneTag opens every "your job finished" notice — this package's and the Stop hook's catch-up line alike (hookrelay.JobDoneTag aliases it, and its tests count the tag). One spelling means a session recognises both as the same message.
const MaxDeliverText = 8 * 1024
MaxDeliverText caps a reply delivered to a session (bytes). The tmux path types it into a live terminal, so it is capped well below the hook's own message limits (design §9.1 A: 8KB).
const MessengerSessionName = "gofer-web"
MessengerSessionName is the Claude Code session name the messenger runs under, so the receiving session sees a web message as coming from "gofer-web" — the person on the web — rather than from an auto-named session of the target's directory (gofer-02fu).
const NudgeMaxFailures = 3
NudgeMaxFailures is how many CONSECUTIVE failed deliveries pause a nudge: a session that cannot be reached must not be hammered every interval, and the person is told.
const OperatorGofer = "gofer"
OperatorGofer is the operator (the message's source, as the outbox and the receiving session see it) of a gofer SYSTEM notice. It is what tells a notice apart from a person's message ("web", a user name): web messages arrive as "[来自 web,<user>] …" while this one is sent as gofer itself.
const PathMessenger = messengerChannel
Delivery channels reported by RawResult.Path besides PathCommand and PathTmux.
const QuestionAnswerPrefix = "answers:"
QuestionAnswerPrefix starts the answer to a question card: answers:<JSON object mapping each question text to its answer>.
const ReasonNoDeliverCommand = "no_deliver_command"
ReasonNoDeliverCommand: DeliverLetter was asked for an agent that declares no deliver_command.
const RefusedLogWindow = 10 * time.Minute
RefusedLogWindow is how often one (session, refused caller) pair is reported on the server log. The refusal itself is recorded on the session every time — this only bounds the log noise while the operator fixes the token.
const ReleaseByAutoRule = "auto_rule"
ReleaseByAutoRule tags a turn closed because the auto rule that armed the wait stopped applying while the hook was blocked (readTurn reports relay_off).
const ReleaseByInterrupted = "interrupted"
ReleaseByInterrupted tags a turn closed because the terminal aborted the Stop hook that was blocking on it (Esc while "hook running"): nobody is waiting for the answer any more, whatever the relay switch says.
const ReleaseBySubagentDone = "subagent_done"
ReleaseBySubagentDone tags a turn closed without an answer because the session's last running sub-agent finished (the blocked Stop hook lets the main agent go on).
const ReleaseByUserReturned = "user_returned"
ReleaseByUserReturned tags a turn closed without an answer because the hook saw the human come back to the keyboard (SR-A5 idle auto-arm).
const SubagentExpiry = 2 * time.Hour
SubagentExpiry is how long a sub-agent counts as running without any further event for it: a lost SubagentStop must not keep a session unarmed forever.
const TagRelayDeliver = "relay-deliver"
TagRelayDeliver labels path C's internal exec jobs (`gofer job ls --tag relay-deliver`).
const TagRelayInject = "relay-inject"
TagRelayInject labels the internal exec jobs path A dispatches, so they can be told apart from human-submitted jobs in `gofer job ls --tag`.
const TagRelayTakeover = "relay-takeover"
TagRelayTakeover labels path B's interactive pty jobs (the same tagging idea as TagRelayInject: `gofer job ls --tag relay-takeover` lists every session a web user has taken over).
const TopicSourceInferred = topicInferred
TopicSourceInferred is the TopicSource a view reports for a topic derived at read time.
const WebMessagePrefix = "[来自 web"
WebMessagePrefix opens every message the messenger delivers ("[来自 web,<用户>] …"). The target's hook uses it to recognise a SendMessage that answers one.
Variables ¶
var ( ErrUnknownSession = errors.New("sessionrelay: unknown session") ErrSessionHeartbeatOwner = errors.New("sessionrelay: session heartbeat caller is not the registered owner") ErrUnknownTurn = errors.New("sessionrelay: unknown turn") ErrNoOpenTurn = errors.New("sessionrelay: session has no open turn") ErrRelayOff = errors.New("sessionrelay: relay is off") ErrInvalidInput = errors.New("sessionrelay: invalid input") // ErrNotHandedOff reports a release of a session that is not (or no longer) // taken over by a pty job: the takeover button is shown only while it is, so // this is a stale request rather than a no-op to hide. ErrNotHandedOff = errors.New("sessionrelay: session is not handed off") )
Sentinel errors mapped to HTTP statuses by the entry layer.
var ErrNoCeilingOwner = errors.New("sessionrelay: cannot determine the caller that owns this delivery")
ErrNoCeilingOwner reports a relay delivery whose caller-scope ceiling owner cannot be named while the server restricts some caller. The delivery is refused rather than run unbounded.
var ErrNudgeNotFound = errors.New("sessionrelay: unknown session nudge")
ErrNudgeNotFound is returned for an unknown nudge id.
var ErrSessionEnded = fmt.Errorf("sessionrelay: session has ended")
ErrSessionEnded reports an edit of a session that has already ended: a finished session is no longer a delivery target, so its topic is not edited (HTTP 409).
var ErrUndeliverable = errors.New("sessionrelay: session cannot be delivered to")
ErrUndeliverable reports that a session cannot receive a message right now. The concrete reason is on UndeliverableError (see DeliverReason); this sentinel is what callers match with errors.Is.
Functions ¶
func DefaultInjectCommands ¶
func DefaultInjectCommands() []string
DefaultInjectCommands returns a copy of the built-in whitelist.
func DefaultState ¶
DefaultState maps a hook event to the session state it implies when the caller does not choose one. Unknown events keep the current state ("").
func DeliverReason ¶
DeliverReason extracts the reason code from a Deliver error ("" when err is not an undeliverable error). The entry layer maps the code to its HTTP status.
func EffectiveTopic ¶ added in v0.166.0
func EffectiveTopic(a jobstore.AgentSession, roots []string) (topic, source string)
EffectiveTopic is the topic a view shows and the finder matches: the stored one with its source, or — when the session has none — the inferred value marked TopicSourceInferred (never stored). roots are the session project's roots (host_path / container_path); both may be empty, in which case only peer_name feeds the inference. An empty topic and source mean there is nothing to show.
func EncodeClaudeProjectDir ¶
EncodeClaudeProjectDir is how Claude Code names a project's directory under ~/.claude/projects: every character that is not an ASCII letter or digit becomes "-" (one per UTF-16 code unit, as the JS regex it uses does), so "/d/work/a.b" is "-d-work-a-b" and "D:\work\x" is "D--work-x".
func ExplainReason ¶
func ExplainReason(reason string, a jobstore.AgentSession, cause error) string
ExplainReason turns a delivery/takeover failure code into a plain Chinese sentence for the web. cause is the original error (its text is only quoted for codes that carry no other information, such as a runner-side failure).
func FormatJobEndedNotice ¶ added in v0.160.0
func FormatJobEndedNotice(n JobEndedNotice) string
FormatJobEndedNotice renders the one-line notice. It starts with JobDoneTag and states the job's identity, its outcome and where to look next; it says out loud that it is a system notification, because the receiving session cannot tell a gofer notice from a person's message otherwise.
func InferTopic ¶ added in v0.166.0
func InferTopic(a jobstore.AgentSession, roots []string) string
InferTopic derives a display-only topic: the path of the session's last_cwd (cwd when it never reported one) relative to its project root, then its peer_name. The root is whichever of the project's roots is a prefix of that path (G002: the session's cwd is a path on the machine it runs on — host or container — so the project's root on that same side is the one that matches; the longest wins).
func IsDeliverableState ¶ added in v0.166.0
IsDeliverableState reports whether a session in state st can still receive something: the live states plus offline (a guess, flagged in the result).
func NormalizeScope ¶ added in v0.166.0
NormalizeScope validates a scope list and returns it normalised: every item a project-root-relative slash path, cleaned, deduplicated in order. Absolute paths (POSIX, UNC-ish backslash and drive-letter forms), any `..` segment, the project root itself ("." / empty) and control characters are refused with ErrInvalidInput.
func ParseQuestionAnswer ¶ added in v0.145.0
ParseQuestionAnswer validates the answer to a question card: every question has a non-empty answer (an offered label, several labels for multiSelect, or free text). It returns the canonical stored form.
func PermissionMessage ¶
PermissionMessage is the session's last message while a prompt is pending.
func QuestionMessage ¶ added in v0.145.0
QuestionMessage is the session's last message while a question waits for an answer.
func SuggestTerms ¶ added in v0.166.0
SuggestTerms splits free text into match keywords: lower-cased words of letters and digits (at least two characters), and for each run of CJK characters the run itself (when short) plus its overlapping two-character pieces.
func TranscriptProjectDirName ¶
TranscriptProjectDirName extracts the directory name a transcript path lives in (".../projects/<name>/<id>.jsonl" → name). The path is as the REGISTERING machine saw it, so both separators are understood. "" when the path has no such shape.
Types ¶
type CommandPlan ¶
type CommandPlan struct {
Argv []string
Stdin string
// OfflineMatch (nil = none): a non-zero exit whose output matches it counts as
// exit 3 (not running). Judged here on the server from the finished job's result,
// so it covers remote workers without any protocol change.
OfflineMatch *regexp.Regexp
}
CommandPlan is what the host rendered from an agent's deliver_command for one message: the full argv (agent command first) and the stdin text. Empty Argv = the agent has no deliver_command. The relay cannot read agent config (G022), so the host renders the template.
type CwdChoice ¶
type CwdChoice struct {
// Rel is project-RELATIVE (what the job service SafeJoins on the runner).
Rel string
// Abs is Rel resolved against the runner's project root.
Abs string
// Source is one of the CwdSource* constants.
Source string
// Reason is the plain-language (Chinese) explanation of the choice.
Reason string
}
CwdChoice is the directory a wake-up process will start in, and why.
func ChooseResumeCwd ¶
func ChooseResumeCwd(a jobstore.AgentSession, plan TakeoverPlan) (CwdChoice, bool)
ChooseResumeCwd decides where a wake-up process starts (see the file comment):
- a directory VERIFIED by the transcript's directory name — candidates are the registered cwd and its ancestors, then the project root views — that is under the project and (where the runner can be asked) still exists;
- the registered cwd, when it is under the project and exists;
- the project root as the runner sees it, when the registered cwd was in the project but is gone.
ok is false when the registered cwd is not under the project at all and nothing verified (the relay refuses with cwd_outside_project rather than guess).
type DeliverResult ¶
type DeliverResult struct {
Path string
// JobID is the internal exec job of PathTmux ("" on the turn path) or the
// interactive pty job of PathTakeover.
JobID string
// DecisionID is the answered turn of PathTurn, or the audit row of the
// terminal paths.
DecisionID string
// Delivering means the text was handed to an internal job that had BEGUN but had
// not finished when gofer's wait window elapsed: it is on its way and may still
// fail, so the caller records 「送达中」 and learns the outcome when the job ends
// (ReconcileDeliveries). JobID is that job; there is no audit row yet, because
// nothing is known to have landed.
Delivering bool
}
DeliverResult is where a delivered message ended up.
type Detail ¶
type Detail struct {
Session jobstore.AgentSession
Turns []*jobstore.PlanDecision
HasMore bool
NextBefore string
}
Detail is a session plus its recent turns (newest first).
type FindHit ¶ added in v0.166.0
type FindHit struct {
Kind string `json:"kind"`
Match string `json:"match,omitempty"`
Source string `json:"source,omitempty"`
}
FindHit says why a session matched. Source is the topic's source (self | human | inferred) for topic and scope hits.
type FindQuery ¶ added in v0.166.0
type FindQuery struct {
Q string
Path string
Project string
Limit int
// Visible narrows the candidates BEFORE ranking (the caller's session.read.others
// filter). nil = everything.
Visible func(jobstore.AgentSession) bool
// Roots returns a project's root paths (host_path / container_path); nil = none.
Roots func(projectKey string) []string
}
FindQuery is one search. Q is split on whitespace and every term must match the topic, the peer name or the project of a session; Path (project-relative, or absolute under the session's project root) must hit a scope. Giving both requires both.
type FindResult ¶ added in v0.166.0
type FindResult struct {
Session jobstore.AgentSession
// Topic / TopicSource are the effective ones (an inferred value is marked).
Topic string
TopicSource string
Hits []FindHit
Rank int
// MaybeOffline marks an `offline` session: it stopped heart-beating, so it may be gone.
MaybeOffline bool
}
FindResult is one ranked session.
type HeartbeatInput ¶
type HeartbeatInput struct {
Event string
State string
LastMessage string
Title string
// Injected marks a UserPromptSubmit raised by the relay's own continuation
// (the hook recognises its ReplyPrefix): it must NOT auto-off relay — the
// human is still on the web, not at the keyboard.
Injected bool
// IdleSec is the hook's system input idle reading (SR-A5, -1 = unknown). nil
// = this event carried none, so the stored reading stays.
IdleSec *int64
// CallerID is the authenticated caller of this beat. It FILLS an owner-less
// session (registered by a hook that predates the column, or before a token
// was configured) on the same write; a session that already has an owner keeps
// it — ownership is decided at first contact, never taken over by a later beat.
CallerID string
PeerName string
PeerNameSource string
PeerStatus string
PeerMessaging *bool
ProgressText string
ProgressAt int64
ClearProgress bool
// Cwd is the hook's current directory, recorded as last_cwd for display only.
Cwd string
// SubagentID / SubagentDelta ride SubagentStart (+1) / SubagentStop (-1)
// beats: the sub-agent's id (dedupe key, may be empty) and the count change.
SubagentID string
SubagentDelta int
// UsageDelta is the token usage read from the transcript since the hook's last
// report (N2 §A); it is ADDED to the session's total.
UsageDelta *runner.SessionUsage
}
HeartbeatInput is a per-event update. State "" derives from Event via DefaultState; LastMessage is the agent's last assistant text (Stop).
type InjectProbe ¶ added in v0.163.0
type InjectProbe interface {
InjectJob(jobID string) (InjectState, error)
}
InjectProbe answers what an injection job is doing NOW, so a delivery that outlived the synchronous wait window can be resolved later: the host knows its jobs, the relay knows what the delivery meant.
The relay can do without it (no probe wired): it then records the 「送达中」 state and never writes back, which is truthful but not useful, so a server that runs path A/C must wire it.
type InjectRequest ¶
type InjectRequest struct {
// ProjectKey is the session's project: the job runs in that project's tree.
ProjectKey string
// Runner is the machine the session registered (agent_sessions.runner); the
// host maps its own vocabulary (the server's label is its local runner).
Runner string
// Cwd is project-relative; the injection only needs tmux, so "." is fine.
Cwd string
Title string
Tags []string
TimeoutSec int
// Cmd is the argv to run: ONE shell invocation carrying the inject script.
Cmd []string
// Stdin is piped to Cmd's standard input (path C with deliver_stdin).
Stdin string
// SourceAgent, when set, runs Cmd as that agent's own command: admission is
// judged on the agent (not the broad allow_exec) and its configured env applies
// (path C — the same carrier identity a takeover / resume uses).
SourceAgent string
// UpdateExempt marks this job as gofer's own short control-plane work, which must
// keep running while a server update waits for the machine to go idle
// (job.JobRequest.UpdateExempt). The relay OWNS this flag: every internal job it
// dispatches is a delivery somebody is waiting on, and parking it would lose
// exactly what the pause protects.
UpdateExempt bool
// OriginCaller is the caller whose request caused this injection (the `by` of the
// delivery): the host stamps it as the job's ceiling owner, so a restricted caller's
// relay job is bounded by its ceiling. Empty = no caller (a timer-driven delivery that
// names none).
OriginCaller string
}
InjectRequest is the internal exec job behind path A (design §9.1 A). It is a value type owned by this package so the host (job.Service) can be injected without the relay importing the job layer (G022).
type InjectResult ¶
type InjectResult struct {
JobID string
// ExitCode is the script's exit code: 0 = typed into the pane. A job that
// never ran (or did not finish) is reported non-zero by the host, so 0 always
// means "the pane got the text".
ExitCode int
// Output is the stdout tail; the pane check prints its reason code there
// (pane_missing / pane_busy:<cmd>).
Output string
// Status is the job's status at the moment the host gave up waiting for it — ""
// when the job ended inside the wait window, so ExitCode and Output are its own.
// A non-empty Status means the wait window elapsed first, and Running says which
// of the two cases that is:
// - Running: the job had begun, so the text may still land. The host keeps the
// job and reports its terminal outcome through InjectProbe; the caller records
// the delivery as 「送达中」.
// - not Running: the job had NOT begun (an update paused new jobs, a backlog).
// The host CANCELLED it, so nothing was delivered and nothing will arrive
// later: the caller reports NotDeliveredPrefix + Status and may offer a retry.
Status string
// Running reports that the job was running when the wait window elapsed (see
// Status).
Running bool
// StatusDetail is the host's one-line explanation of an unstarted job's status in
// the human's language ("升级等待(新任务暂停启动)"): the reason a delivery did not
// happen is what the reader needs, not an exit code nobody produced.
StatusDetail string
}
InjectResult is the host's report of one injection job.
type InjectState ¶ added in v0.163.0
type InjectState struct {
// Known is false when the job record is gone (a restarted server whose job was
// never persisted, or one already cleaned up): the delivery then cannot be
// confirmed any more and is reported as a failure instead of staying 「送达中」
// for ever.
Known bool
// Done reports that the job's PROCESS is over, so Status/ExitCode/Output are its
// terminal snapshot and nothing else will happen.
Done bool
// Status is the job's status ("running" while Done is false).
Status string
// ExitCode and Output are the terminal exit code and the captured output tail
// (Done only).
ExitCode int
Output string
}
InjectState is one injection job's current state as InjectProbe reports it.
type Injector ¶
type Injector interface {
InjectSession(ctx context.Context, req InjectRequest) (InjectResult, error)
}
Injector runs one internal injection job SYNCHRONOUSLY and reports its result. The host owns job submission, runner resolution and log access; the relay owns the policy (what to run, and what the exit code means).
type InjectorFunc ¶
type InjectorFunc func(ctx context.Context, req InjectRequest) (InjectResult, error)
InjectorFunc adapts a function to Injector.
func (InjectorFunc) InjectSession ¶
func (f InjectorFunc) InjectSession(ctx context.Context, req InjectRequest) (InjectResult, error)
InjectSession implements Injector.
type JobEndedNotice ¶ added in v0.160.0
type JobEndedNotice struct {
// TargetSession is the session to tell; empty is an error (a caller without a
// target must not call this at all).
TargetSession string
JobID string
Title string
Status string
ExitCode int
// Duration is the job's wall-clock run time (0 when either stamp is missing).
Duration time.Duration
// WrapUp is the agent's OWN reason for ending early ("max_steps" / "max_tokens"
// / "timeout"); "" drops the field (the agent answered).
WrapUp string
}
JobEndedNotice is the terminal snapshot one notice is rendered from. It is the narrow projection the relay needs — the caller (the assembled hub, holding a finished job) owns the job's full state.
type Messenger ¶
type Messenger interface {
SubmitMessenger(projectKey, runner, cwd string, command []string, title, caller string) (string, error)
MessengerJob(jobID string) (done bool, status string, exitCode int, output string, err error)
}
Messenger is the narrow seam for a one-shot SendMessage job. The relay owns ordering and delivery semantics; the job/http assembly layer owns how a job is submitted and how its bounded output is read.
type MessengerAbandoner ¶ added in v0.168.0
type MessengerAbandoner interface {
AbandonMessengerJob(jobID string) (InjectResult, error)
}
MessengerAbandoner is the optional half of the one-shot messenger seam that settles a job gofer stops waiting for (gofer-kx53), the same question InjectResult answers for path A/C: when messengerTimeout elapses, did the text start on its way? The host re-reads the job and answers with the InjectResult vocabulary:
- Running: the job had begun, so the message may still land (「送达中」, written back at the job's terminal state through InjectProbe);
- a non-empty Status without Running: the job had NOT begun and the host cancelled it, so nothing arrives late (「未送达」, safe to retry);
- neither: the job ended meanwhile, and ExitCode/Output are its own.
A messenger without it keeps the old behaviour (the timeout is a failure).
type Notifier ¶
type Notifier interface {
NotifySessionWaiting(sessionID, projectKey, title, lastMessage string, turn int64)
NotifySessionAttention(sessionID, projectKey, title, detail string)
// NotifySessionHandedOff is path B (design §9.1 B): the session was taken over
// by a pty job, so the conversation continues there — the human who was about
// to answer on their phone needs the new address, not another reply box.
NotifySessionHandedOff(sessionID, projectKey, title, jobID string)
// NotifySessionTakeoverReleased is its DUAL (SUP-02 R1): the takeover job
// reached a terminal state and the session is back with its original terminal.
// reason says why the job ended ("job_done" / "job_failed" / …), so a human
// who was told the conversation had moved learns it can come back.
NotifySessionTakeoverReleased(sessionID, projectKey, title, jobID, reason string)
}
Notifier is the outbound-notification seam (OBS-07a). The relay knows WHEN a human is needed; it must not know about webhooks, IM adapters or config — the entry layer injects an implementation (job.Service). nil = no notification.
type NudgeInput ¶
type NudgeInput struct {
Kind string // jobstore.NudgeEvery | jobstore.NudgeStalled
Interval time.Duration
Text string
UntilAt int64 // unix seconds; 0 = no end
By string
}
NudgeInput is the creation request of one nudge.
type NudgeNotifier ¶
type NudgeNotifier interface {
NotifySessionNudgePaused(sessionID, projectKey, title, nudgeID, reason string)
}
NudgeNotifier is the optional notification seam for a nudge that paused itself after repeated delivery failures. The Notifier the service holds implements it when it can (job.Service does); otherwise the pause is only logged and visible in the nudge row.
type PermissionAnswer ¶
type PermissionAnswer struct {
Behavior string // allow | deny
// Suggestion is the permission_suggestions index of an allow-always, else -1.
Suggestion int
Message string // deny reason (optional)
}
PermissionAnswer is a parsed answer.
func ParsePermissionAnswer ¶
func ParsePermissionAnswer(answer string, suggestions int) (PermissionAnswer, error)
ParsePermissionAnswer validates an answer against a prompt that offered suggestions "always allow" choices: allow | always:<i> | deny | deny:<reason>.
func (PermissionAnswer) String ¶
func (a PermissionAnswer) String() string
String renders the canonical stored form.
type PermissionDetail ¶
type PermissionDetail struct {
ToolName string `json:"tool_name"`
Summary string `json:"summary"`
Input string `json:"input,omitempty"`
Suggestions []PermissionSuggestion `json:"suggestions,omitempty"`
Questions []Question `json:"questions,omitempty"`
// Fingerprint identifies the tool call (tool name + canonical input) so the
// PostToolUse of THAT call — not of a parallel one — settles the prompt.
Fingerprint string `json:"fp,omitempty"`
}
PermissionDetail is the decision's detail JSON of a permission prompt. A prompt with Questions is an AskUserQuestion relayed to the web (gofer-02fu): it is answered with QuestionAnswerPrefix + the answers, not allow / deny.
func ParsePermissionDetail ¶
func ParsePermissionDetail(raw string) PermissionDetail
ParsePermissionDetail reads a permission decision's detail JSON (zero value on a malformed blob).
type PermissionInput ¶
type PermissionInput struct {
PermissionDetail
TimeoutSec int64
}
PermissionInput opens a permission decision.
type PermissionSuggestion ¶
type PermissionSuggestion struct {
Label string `json:"label"`
}
PermissionSuggestion is one "always allow" choice Claude Code offered (permission_suggestions[i]); only its human label travels — the hook keeps the raw entry and returns it as updatedPermissions when the person picks it.
type Question ¶ added in v0.145.0
type Question struct {
Question string `json:"question"`
Header string `json:"header,omitempty"`
Options []QuestionOption `json:"options,omitempty"`
MultiSelect bool `json:"multiSelect,omitempty"`
}
Question is one question of a Claude Code AskUserQuestion call relayed to the web (gofer-02fu); its answer is one option label (several, comma-separated, for multiSelect) or free text.
type QuestionOption ¶ added in v0.145.0
type QuestionOption struct {
Label string `json:"label"`
Description string `json:"description,omitempty"`
}
QuestionOption is one offered answer.
type RawResult ¶ added in v0.174.0
type RawResult struct {
// Path is PathCommand, PathTmux or PathMessenger.
Path string
// JobID is the internal job that carried the text ("" when none was needed).
JobID string
}
RawResult is where a raw delivery went.
type RegisterInput ¶
type RegisterInput struct {
SessionID string
Agent string
ProjectKey string
Runner string
Cwd string
Title string
Transcript string
TmuxPane string
Event string
// CallerID is the authenticated caller the entry layer stamped on this
// request (SUP-01 D / bd h-aii-esus): the session's owner. "" when the server
// has no token configured. It is recorded on first contact and never
// overwritten by a later registration or beat.
CallerID string
PeerName string
PeerNameSource string
PeerStatus string
PeerMessaging bool
}
RegisterInput is the SessionStart / first-contact registration.
type ResidentMessenger ¶
type ResidentMessenger interface {
SendMessengerResident(ctx context.Context, runner, cwd, target string, command []string) (string, error)
}
ResidentMessenger is an optional same-runner stream bridge. Implementations may keep one process per runner and must serialize requests; callers fall back to Messenger's one-shot job path when this capability is absent.
type ResumePlan ¶
type ResumePlan struct {
// Can is true when Resume would start a process now.
Can bool `json:"can"`
// Reason is the machine-readable code when !Can (see the Reason* constants and
// HandedOffPrefix); "" when Can.
Reason string `json:"reason,omitempty"`
// Message is the plain-language (Chinese) explanation: why not, or what will happen.
Message string `json:"message"`
// Warning is non-empty when waking is possible but worth a second look (the
// terminal may still be open).
Warning string `json:"warning,omitempty"`
State string `json:"state"`
Ended bool `json:"ended"`
// What would run: the machine, the agent, the project, the project-relative
// directory and the resume command line. Empty when it could not be planned.
Runner string `json:"runner,omitempty"`
Agent string `json:"agent,omitempty"`
ProjectKey string `json:"project_key,omitempty"`
Cwd string `json:"cwd,omitempty"`
Command []string `json:"command,omitempty"`
// CwdAbs is Cwd resolved against the runner's project root; CwdSource is
// transcript | registered | project_root, and CwdReason says in plain Chinese
// why that directory was chosen (M8: the original start directory is verified
// from the transcript path, see ChooseResumeCwd).
CwdAbs string `json:"cwd_abs,omitempty"`
CwdSource string `json:"cwd_source,omitempty"`
CwdReason string `json:"cwd_reason,omitempty"`
}
ResumePlan answers "can this session be woken up, and how" for the web's wake-up button. It is the dry run of Resume: the same preconditions as path B, none of the side effects.
type Service ¶
type Service struct {
// AutoOffOnPrompt drops an explicit `on` switch back to `auto` when the
// human types in the terminal (UserPromptSubmit): they are back at the
// keyboard (design D6, R1). A reply injected by the hook does NOT raise a
// human UserPromptSubmit, so web replies never trip it. Default true.
AutoOffOnPrompt bool
// AutoArmIdleSec is the keyboard idle auto-arm threshold in seconds
// (session.auto_relay_idle_sec, SR-A5): a session whose last reported system
// input idle is at least this long behaves as if its relay switch were on,
// even though the human never flipped it. 0 = this criterion disabled. Set
// once at construction from config.
AutoArmIdleSec int
// AutoArmTurnSec is the turn-age fallback threshold in seconds
// (session.auto_relay_turn_sec, R2): on a terminal where the idle probe does
// not work at all (idle_sec stays -1 — a Linux container with no X11), a
// session that has seen no HUMAN input for this long waits anyway. 0 = this
// criterion disabled. Set once at construction from config.
AutoArmTurnSec int
// SkipWhenSupervising is the SUP-01 D gate
// (session.auto_relay_skip_when_supervising): while the session's caller has
// jobs in flight, `auto` does not arm the relay at all — the person behind
// that caller is watching the job, and an armed Stop would block the hook (and
// the job's completion notice) until they came back. False (the zero value)
// keeps the pre-D behaviour; config turns it ON by default. `on`/`off` are
// never affected. Set once at construction from config.
SkipWhenSupervising bool
// SupervisingWindowSec is how far back the gate looks for the caller's live
// jobs (session.supervising_window_sec); 0 = no window. Set with
// SkipWhenSupervising.
SupervisingWindowSec int
// StopJobWait is session.stop_job_wait (gofer-rhux): what a Stop hook does about
// the session's WATCHED JOBS — away (default) / always / never. It is carried
// here only to reach the hook: the hook decides (it owns the keyboard reading),
// the field travels on every session response so a container hook with no config
// file of its own still obeys the operator's setting. Set once at construction
// from config, hot-reloaded through the same setter as the rest of the block.
StopJobWait string
// contains filtered or unexported fields
}
Service owns the relay rules on top of the store.
func NewService ¶
NewService builds the relay service over the shared job store.
func (*Service) AckTurn ¶
func (s *Service) AckTurn(sid, decisionID, by string) (jobstore.PlanDecision, error)
AckTurn marks one OPEN relay turn as read without answering it. The turn remains OPEN so the hook keeps waiting and Say can answer it later.
func (*Service) AddJobWatch ¶
func (s *Service) AddJobWatch(sid, jobID string) (jobstore.SessionJobWatch, error)
AddJobWatch records a job emitted by this terminal session. The store keeps only the relation; job visibility is checked by the HTTP entry point.
func (*Service) AnswerPermission ¶
func (s *Service) AnswerPermission(sid, id, answer, by string) (jobstore.PlanDecision, error)
AnswerPermission records the person's web answer to a pending prompt. The entry layer has already checked that the caller is the session's owner; here the prompt must belong to sid, be OPEN, and the answer must be one it offered.
func (*Service) AutoArmed ¶
func (s *Service) AutoArmed(a jobstore.AgentSession) bool
AutoArmed reports whether the KEYBOARD IDLE rule alone arms this session (the human has been away for >= AutoArmIdleSec, measured by the last reading the hook reported). It is the `auto_armed` the web renders as "auto (idle 12m)".
func (*Service) CheckDeliverable ¶ added in v0.177.1
CheckDeliverable reports, without sending anything, whether SendMessage (the call behind the session drawer's web message) has a path to the session. It mirrors SendMessage's routing: an ended session or disabled messaging is refused; a session waiting for a reply is answered; a session with a Claude SendMessage address goes through the messenger (needs a project, a messenger executor and an execution machine); every other session takes the Deliver ladder (an open turn, the agent's deliver_command, or a tmux pane — never a takeover). The errors are the ones the real send would produce, so a caller can refuse BEFORE doing expensive work for the message (the workbench places attachment files first).
func (*Service) ClaimSupervisedJobs ¶
func (s *Service) ClaimSupervisedJobs(a jobstore.AgentSession)
ClaimSupervisedJobs gives a Stop-ing session only its own source_session_id jobs (SUP-01 D gate) that match its authenticated owner and execution context. This supplies the completion channel for jobs submitted through MCP or other tools without allowing another session owned by the same caller to claim them.
func (*Service) CompleteMailTurn ¶ added in v0.173.0
func (s *Service) CompleteMailTurn(sid, turnID string, opts jobstore.TakeMailOpts) (bool, []jobstore.TakenMail, error)
CompleteMailTurn is the Stop delivery of mailbox letters for a relay turn that is already open (design 「投递语义」: Stop 送达): in one arbitration it closes the turn AND takes the session's letters, so a concurrent web reply and the letters can never both win. The letters are claimed first, then the turn is closed by the same compare-and-set a web answer races on (ReleaseDecision); a lost race gives the claims back to pending and the hook consumes the web answer instead. Only after the turn is closed are the letters confirmed, so the hook injects confirmed letters only (at most once). completed=false with no letters means nothing was pending or the turn was no longer open; the turn is left untouched whenever there is nothing to deliver.
func (*Service) CompleteWatchedJobs ¶
CompleteWatchedJobs marks terminal watched jobs as delivered WITHOUT a relay turn: the Stop hook of a session whose relay is off (or the UserPromptSubmit / SessionStart catch-up) is about to inject the completion notice itself. It returns true only when this call actually removed at least one watch row, so two concurrent hooks never both deliver the same notice.
func (*Service) CompleteWatchedTurn ¶
CompleteWatchedTurn settles the open relay turn before the hook injects a terminal-job notice. If a web answer won the race, it returns false and the hook must consume that answer instead.
func (*Service) ConfigureMessaging ¶
ConfigureMessaging applies the server-scoped message bridge policy.
func (*Service) CreateNudge ¶
func (s *Service) CreateNudge(sid string, in NudgeInput) (jobstore.SessionNudge, error)
CreateNudge arms a nudge on a live session. An ended or handed-off session is refused: there is nobody the text could reach and the nudge would end at its first sweep.
func (*Service) Deliver ¶
func (s *Service) Deliver(ctx context.Context, sid, text, by, origin string, allowTakeover bool) (DeliverResult, error)
Deliver routes a reply to a session (design §9.1 选路): an OPEN turn is answered exactly as Say does (phase 1 — the blocked hook injects it into the same terminal), otherwise the reply is typed into the session's tmux pane (path A), and — only when the caller explicitly allows it (allowTakeover, the web's confirmation) and A has no usable pane — a NEW interactive pty job continues the session with `--resume` and gets the reply as its first input (path B). Say itself keeps its old turn-only semantics.
by is the display label of the speaker ("web", a user name, "gofer"); origin is the caller-scope ceiling owner of the delivery — the caller whose request caused it (see ceiling_origin.go). The two are separate on purpose: `by` may be a gofer label nobody holds a ceiling for, while the internal jobs the delivery dispatches must stay bounded by the caller that asked for it. An owner that cannot be named is refused while the server restricts callers (ErrNoCeilingOwner).
Failures carry a reason code (see DeliverReason): no_runner, no_tmux, ended, handed_off:<job>, inject_failed:<...>, no_resume_template, interactive_not_allowed, cwd_outside_project. An over-long or empty reply is ErrInvalidInput.
func (*Service) DeliverLetter ¶ added in v0.174.0
func (s *Service) DeliverLetter(ctx context.Context, sid, text, by, origin string) (RawResult, error)
DeliverLetter hands text to the LIVE process of a session through its agent's deliver_command (path C: `suga send`, `codex queue`) and nothing else. text goes through verbatim. The failure vocabulary is Deliver's: ReasonNotRunning (exit 3 — the process is not there, the caller leaves the letter pending), DeliverFailedPrefix…, NotDeliveredPrefix…; an agent without a deliver_command is ReasonNoDeliverCommand. A job that outlived the wait window counts as delivered (it is on its way; the mailbox is at-least-once).
by is the display label of the delivery ("gofer-mail"); origin is its ceiling owner — the letter's sender — so the internal job stays bounded by that caller (see ceiling_origin.go).
func (*Service) Find ¶ added in v0.166.0
func (s *Service) Find(q FindQuery) ([]FindResult, error)
Find matches, ranks and then truncates. ErrInvalidInput when neither Q nor Path is given.
func (*Service) FollowWeb ¶ added in v0.147.0
FollowWeb moves the conversation to the web after a person's message from there reached the session: an `auto` session becomes `on`, so its next stops wait for the web instead of the terminal, until the person types in the terminal again (which drops `on` back to `auto`). An explicit `off` is the person's own choice and stays; `on` already waits. Best effort: a failure leaves the mode as it was.
func (*Service) Heartbeat ¶
func (s *Service) Heartbeat(sid string, in HeartbeatInput) (jobstore.AgentSession, error)
Heartbeat applies a hook event to the session and returns the updated row (its WaitReason is what the Stop hook keys on). A UserPromptSubmit typed by a HUMAN demotes an explicit `on` switch back to `auto` when AutoOffOnPrompt is set, and releases any wait the automatic rules had armed (R1/R2). Unknown session → ErrUnknownSession (the hook then registers and retries; hooks may start mid-session after an upgrade).
func (*Service) HeartbeatForOwner ¶
func (s *Service) HeartbeatForOwner(sid string, in HeartbeatInput) (jobstore.AgentSession, error)
HeartbeatForOwner is the authenticated HTTP hook path. It pins an ownerless legacy row before any event side effect, and rejects caller-less / foreign beats. Trusted in-process Heartbeat keeps its historical behavior.
func (*Service) IsServerLocalRunner ¶
IsServerLocalRunner reports whether a session's runner label means the server's own machine. A hook-registered session carries "server" (the CLI spelling, see resolveHookRunner) while jobs and /v1/runners say "local" (G043): both are the same runner — and so is a stored label from before registration normalized it — so every comparison goes through here instead of matching one literal.
func (*Service) JobWatches ¶
func (s *Service) JobWatches(sid string) ([]jobstore.SessionJobWatch, error)
JobWatches lists the jobs currently awaiting a Stop-hook completion notice.
func (*Service) List ¶
func (s *Service) List(opts jobstore.ListSessionsOpts) ([]jobstore.AgentSession, error)
List lists sessions (see jobstore.ListSessionsOpts).
func (*Service) NotifyJobEnded ¶ added in v0.160.0
func (s *Service) NotifyJobEnded(ctx context.Context, n JobEndedNotice) error
NotifyJobEnded tells a session that a job ended, through the messenger.
Delivery is at-most-once per (session, job) and survives a server restart, because the durable record is the session's job WATCH — the row the Stop hook and its catch-up read:
- the watch is claimed by deleting it (Submit registered it when the notification was requested); a claim that removes nothing means somebody else already delivered this notice — the hook, an earlier ended-hook, or the same event before a restart — and nothing is sent;
- the message is sent only after the claim, so a duplicate terminal event (a needs_review job later accepted) can never send a second notice even though the ended-hook runs again;
- a FAILED delivery puts the watch back, so the existing Stop-hook / catch-up path still delivers it the next time that session stops. Losing the notice silently is the one outcome worth avoiding.
Every outcome is logged, never returned to the job: a notification is a side channel and must not influence how the job ended.
func (*Service) Nudge ¶
func (s *Service) Nudge(id string) (jobstore.SessionNudge, error)
Nudge reads one nudge.
func (*Service) OnAnswered ¶
func (s *Service) OnAnswered(d jobstore.PlanDecision)
OnAnswered is the post-answer hook shared with the generic decision endpoint (POST /v1/decisions/{id}/answer answering a relay turn from the bell): a waiting session goes back to running. Non-relay decisions are ignored.
func (*Service) OpenPermission ¶
func (s *Service) OpenPermission(sid string, in PermissionInput) (jobstore.PlanDecision, error)
OpenPermission posts a permission prompt the hook will wait on. Like OpenTurn the session must currently wait for the web (PermissionWaitReason) — else ErrRelayOff and the hook leaves the prompt to the terminal. An older still-open prompt of the session is released first (only one dialog is on screen at a time).
func (*Service) OpenTurn ¶
OpenTurn posts the agent's last message as a relay turn: bumps turn_no, inserts an OPEN decision (kind=relay, free-text answer) and marks the session waiting_reply. timeoutSec is the hook's remaining budget (clamped by the store). The session must currently wait — explicitly (`on`), or through one of the auto rules (WaitReason) — else ErrRelayOff (the hook re-checks the switch through Heartbeat first, this guards the race).
func (*Service) PauseNudge ¶
func (s *Service) PauseNudge(id string) (jobstore.SessionNudge, error)
PauseNudge / ResumeNudge flip a nudge by hand; both are idempotent-safe (a nudge in the wrong state answers ErrInvalidInput so the caller sees why nothing changed).
func (*Service) PermissionWaitReason ¶
func (s *Service) PermissionWaitReason(a jobstore.AgentSession) string
PermissionWaitReason is WaitReason for a terminal PERMISSION prompt: the same rules minus the SUP-01 D supervising gate. That gate keeps a Stop from parking while the caller watches live jobs / sub-agents; a permission dialog already blocks the terminal whatever we decide, so mirroring it to the web (and waiting on it) costs the supervisor nothing and is the only way they can answer it while away. Used on every permission path: open, wait (readTurn) and the idle-probe release.
func (*Service) PlanResume ¶
func (s *Service) PlanResume(sid string) (ResumePlan, error)
PlanResume reports whether Resume would work for sid, without doing it. An unknown session is ErrUnknownSession; every other "no" is a normal answer (Can=false with a reason), not an error.
func (*Service) PlanResumeFor ¶
func (s *Service) PlanResumeFor(a jobstore.AgentSession) ResumePlan
PlanResumeFor is PlanResume for a session row already in hand (the session list annotates every row with it, so it must not touch the store).
func (*Service) ReconcileDeliveries ¶ added in v0.163.0
ReconcileDeliveries writes back every outbox record of this session that is still marked 「送达中」: the message asked a job to carry it, and the job's own answer now decides whether it arrived. Records whose job is still running are left alone.
It is called both when the job ends and on the outbox READ path, which is what makes the state self-healing: a write-back lost with a server restart — the delivery job dies with the old process — is resolved by the next read instead of leaving a message 「送达中」 for ever.
func (*Service) ReconcileDeliveryJob ¶ added in v0.163.0
ReconcileDeliveryJob resolves ONE finished injection job (the assembly's terminal hook, which knows the job id but not the session). It reports whether a pending delivery was waiting on that job; an ordinary job — or a delivery already resolved — is simply not its business.
func (*Service) RecordMessengerReply ¶ added in v0.135.0
func (s *Service) RecordMessengerReply(runner, peerName, from, body string) (jobstore.SessionMessage, bool, error)
RecordMessengerReply is the fallback path: a resident messenger on runner received a message from the Claude session named peerName. It is stored as that session's reply when exactly one live gofer session on that runner has that name (a name is only unique among the sessions alive at one time).
func (*Service) RecordReply ¶ added in v0.135.0
func (s *Service) RecordReply(sid, text, peer, source, caller string) (m jobstore.SessionMessage, created bool, err error)
RecordReply stores a session's own answer to a web message in its outbox, where the web conversation shows it as the session's reply (gofer-6er0). source is a jobstore.SessionReplySource*; peer is the address it was sent to. A session- sourced reply must come from the session's owner (same rule as a heartbeat). An identical text recorded in the last replyDedupeWindow is the same reply: nothing new is stored (a session-sourced report upgrades a messenger-sourced one). created reports whether a new record was written.
func (*Service) Register ¶
func (s *Service) Register(in RegisterInput) (jobstore.AgentSession, error)
Register upserts a session (see jobstore.UpsertAgentSession for the merge rules). Agent is required on first contact. A SessionStart stamps last_human_at: launching the agent is a human act, and it is the anchor the turn-age fallback measures from (R2).
func (*Service) RegisterForOwner ¶
func (s *Service) RegisterForOwner(in RegisterInput) (jobstore.AgentSession, bool, error)
RegisterForOwner is the HTTP hook path: an existing non-empty owner can only refresh its own registration. The store performs this check atomically with the upsert so two first registrations cannot race to transfer a session.
func (*Service) RelayDemotedAt ¶
func (s *Service) RelayDemotedAt(a jobstore.AgentSession) int64
RelayDemotedAt is when the session's `on` switch last fell back to `auto` because the human typed in the terminal, or 0 when that is not the current story: the mode is not auto, there was no demotion, or someone set the switch explicitly afterwards.
func (*Service) ReleaseTakeover ¶
ReleaseTakeover undoes path B's takeover (design §9.1 B): the takeover job is cancelled FIRST — while it runs, IT owns the CLI session, and releasing the original terminal into a session two processes are writing would diverge it — and only then does the session return to idle with handed_off_* cleared, so the terminal that registered it relays again.
A cancel failure is reported rather than swallowed: the caller asked for the session back, and the one thing we must not do is pretend they have it while a live process continues to hold it.
func (*Service) ReleaseTakeoverForJob ¶
ReleaseTakeoverForJob is the AUTOMATIC release (SUP-02 R1): the pty job that holds a session reached a terminal state, so the session no longer has an owner and goes back to idle — the alternative is a session nobody can speak to, since new turns are refused while it is handed off and the process that held it is gone.
Unlike the manual release this does NOT cancel the job (there is nothing left to stop — its row only supplies the reason code) and it is a silent no-op for every job that is not a takeover (false). Callers run it from the job service's terminal hook, where a failure is logged rather than surfaced: released reports whether a session was actually handed back.
func (*Service) ReleaseTurn ¶
ReleaseTurn closes an OPEN turn because the hook's FRESH idle reading shows the human is back at the keyboard (SR-A5 item 3): the wait was armed by the keyboard idle rule (WaitIdleProbe), not by an explicit switch, and the new reading is below the threshold. The turn ends EXPIRED tagged released_by=user_returned and the session goes idle, so the agent stops normally at its prompt. The turn-age fallback has no probe: its release arrives as a human-input event instead (see releaseAutoTurns).
released=false means "keep waiting": still away (idle above the threshold or unreadable), an explicitly switched-on relay (that one is only ever turned off by the human — typing in the terminal or the web /off), or a turn that already settled (an answer that beat the release wins).
func (*Service) RemoveJobWatch ¶
RemoveJobWatch removes one completion notice after it has been injected.
func (*Service) RemoveNudge ¶
RemoveNudge deletes a nudge.
func (*Service) Resolve ¶
func (s *Service) Resolve(cwd string) ([]jobstore.AgentSession, error)
Resolve picks the session `gofer session relay on` (run without --session) means: the live sessions whose cwd equals or contains cwd, most recent first. The caller disambiguates when more than one comes back.
func (*Service) ResolvePermissions ¶
ResolvePermissions closes the session's pending prompts that were settled in the terminal: fp "" = all of them, else only the prompt of that tool call. It returns how many it closed; the session leaves needs_attention when it did.
func (*Service) Resume ¶
func (s *Service) Resume(ctx context.Context, sid, initialInput, by, origin string) (DeliverResult, error)
Resume starts a new interactive process that continues the session (`--resume <sid>`), whether or not the session has ended — waking a closed terminal is the main reason to call it. initialInput is optional: with one the new terminal's first input is that text, without it the terminal just opens on the resumed conversation. The session becomes handed_off until the process ends (or is released), and an ended session returns to ended then.
Failures are *UndeliverableError with a reason code (see DeliverReason); their wrapped error is the Chinese explanation. by is the display label, origin the caller-scope ceiling owner of the takeover job (see ceiling_origin.go).
func (*Service) ResumeNudge ¶
func (s *Service) ResumeNudge(id string) (jobstore.SessionNudge, error)
ResumeNudge re-arms a paused nudge (failure count cleared, timers restart now). A nudge whose session already ended cannot come back.
func (*Service) Say ¶
func (s *Service) Say(sid, answer, by string) (jobstore.PlanDecision, error)
Say answers the session's newest OPEN turn (the web input box / `gofer session say`). ErrNoOpenTurn when nothing is waiting.
func (*Service) SendMessage ¶
func (s *Service) SendMessage(ctx context.Context, sid, text, operator, origin string) (jobstore.SessionMessage, error)
SendMessage chooses relay for a waiting turn and a messenger job otherwise. It records every transition in the session outbox before returning, making the web view truthful even when a runner goes offline between two requests.
operator is the display label of the speaker (who the outbox and the messenger prompt say the message came from); origin is the caller-scope ceiling owner behind it (see ceiling_origin.go). A messenger / delivery job gofer runs for this message carries origin, never the label.
func (*Service) Session ¶
func (s *Service) Session(sid string) (jobstore.AgentSession, error)
Session returns one session row without its turns. The entry layer needs it before dispatching to Say/Deliver/SetRelayMode: the owner check (SUP-01 D) is about WHO is calling, which only the entry layer knows, while the row itself is the domain service's to fetch.
func (*Service) SetAgentInjectLookup ¶
SetAgentInjectLookup wires the per-agent extra foreground-process names (agent config `inject_process`). The lookup is consulted per session with that session's registered agent key, so the extras widen the whitelist ONLY for sessions that really are that agent (a global widening would let any session's pane be typed into whenever some agent's process name happened to be in the pane).
func (*Service) SetDeliverPlanner ¶
func (s *Service) SetDeliverPlanner(fn func(agentKey, sessionID, text string) CommandPlan)
SetDeliverPlanner wires the per-agent deliver_command renderer (path C). nil = no agent has one.
func (*Service) SetInjectCommands ¶
SetInjectCommands overrides the foreground-process whitelist of path A (session.inject_commands). Empty keeps the built-in list (DefaultInjectCommands).
func (*Service) SetInjectProbe ¶ added in v0.163.0
func (s *Service) SetInjectProbe(p InjectProbe)
SetInjectProbe wires the asynchronous half of the injection seam (see InjectProbe).
func (*Service) SetInjector ¶
SetInjector wires the internal-job executor for path A. Without one (a server built with no job service, or a test) Deliver reports no_runner rather than pretending to have typed anything.
func (*Service) SetMessenger ¶
func (*Service) SetNotifier ¶
SetNotifier injects the outbound notifier (see Notifier). Safe to leave unset: the relay then simply sends no notifications.
func (*Service) SetPollInterval ¶
SetPollInterval overrides the WaitTurn re-read cadence (tests).
func (*Service) SetRelayMode ¶
func (s *Service) SetRelayMode(sid, mode string) (jobstore.AgentSession, error)
SetRelayMode stores the session's three-state switch (auto | on | off, R1). A change that ends a wait — `off` (never waits), or dropping an explicit `on` back to `auto` — also expires any OPEN turn and moves a waiting session to idle, so a hook blocked on it releases.
func (*Service) SetRelayModeBy ¶
func (s *Service) SetRelayModeBy(sid, mode, actor string) (jobstore.AgentSession, error)
SetRelayModeBy is SetRelayMode for an explicit CLI / web request: it also records who set it, which ends any "fell back to auto" note (RelayDemotedAt).
func (*Service) SetRestrictedCallers ¶ added in v0.178.0
SetRestrictedCallers wires the predicate answering "does this deployment give any caller a ceiling" (config.ServerConfig.CeilingCallers() non-empty). nil — the zero value behind a bare service — means no caller is restricted, so an empty owner is allowed.
func (*Service) SetSessionOwner ¶ added in v0.155.1
func (s *Service) SetSessionOwner(sid, callerID, by string) (a jobstore.AgentSession, from string, err error)
SetSessionOwner hands a session to another authenticated caller (gofer-eh53): the admin's way out of the token split, where a terminal's hook now reports as a caller the session never belonged to. The entry layer decides WHO may do it; the store does the write atomically — the hand-over and the revoke of the session's own grants happen in ONE transaction (design §4). from names the previous owner ("" = ownerless); by names the caller performing the hand-over.
func (*Service) SetTakeoverAliveSec ¶
SetTakeoverAliveSec sets the liveness window of the takeover guard (session .takeover_alive_sec); <= 0 turns the heartbeat guard off.
func (*Service) SetTakeoverer ¶
func (s *Service) SetTakeoverer(t Takeoverer)
SetTakeoverer wires path B's planner/submitter. Without one (a server built with no job service, or a test) a takeover reports no_runner rather than dispatching nothing and claiming success.
func (*Service) SetTopic ¶ added in v0.166.0
func (s *Service) SetTopic(sid string, topic *string, scope *[]string, source string) (jobstore.AgentSession, error)
SetTopic stores a session's topic and/or scope. topic / scope nil keep that part; source is jobstore.SessionTopicSelf (the session itself) or SessionTopicHuman (anybody else). ErrUnknownSession for no such session, ErrSessionEnded for a finished one, ErrInvalidInput for a bad value (including nothing to set).
func (*Service) SetWaitBudgets ¶
SetWaitBudgets sets the Stop-wait budgets handed to the hook as wait_budget_sec: onSec for an explicit `on` switch, autoSec for an auto-armed wait (0 = no cap).
func (*Service) SetWorkHook ¶
SetWorkHook injects the work-item hook (see WorkHook). Safe to leave unset.
func (*Service) SubagentCount ¶
SubagentCount is the number of sub-agents currently running in the session.
func (*Service) Suggest ¶ added in v0.166.0
func (s *Service) Suggest(q SuggestQuery) ([]SuggestResult, error)
Suggest returns the best candidate sessions for q, at most q.Limit (default 3).
func (*Service) SweepNudges ¶
SweepNudges runs one pass over the active nudges at now and returns how many were delivered. Ended / handed-off sessions and expired nudges are closed first; an offline session is skipped (not a failure: it is not reachable and will beat when it is back).
func (*Service) UnackTurn ¶
func (s *Service) UnackTurn(sid, decisionID string) (jobstore.PlanDecision, error)
func (*Service) WaitBudgetSec ¶
WaitBudgetSec is the budget for a wait of the given reason (see WaitReason): 0 when the session does not wait or no cap is configured.
func (*Service) WaitDecision ¶
func (s *Service) WaitDecision(a jobstore.AgentSession) (reason, detail string)
WaitDecision is WaitReason plus the one-line explanation of a NON-waiting session ("supervising 2 jobs"): the web shows it next to the relay switch, and the hook logs it, so "why did my Stop not wait" is answerable without reading the store. One lookup, so a caller that needs both does not count jobs twice.
func (*Service) WaitReason ¶
func (s *Service) WaitReason(a jobstore.AgentSession) string
WaitReason answers "does a Stop on this session wait for a web reply, and why" — the single place the relay's rules live (R1/R2). "" means it does not wait; otherwise the value is one of WaitModeOn / WaitIdleProbe / WaitTurnAge.
- `on`: the human's explicit switch, authoritative over every rule below.
- `off`: never.
- `auto`: nothing at all while the caller still has live jobs (SUP-01 D, see SkipWhenSupervising); else the idle probe when it WORKED (idle >= 0) — a machine where the human is demonstrably at the keyboard or away is not second-guessed by the turn-age clock — else, on a terminal that cannot be probed at all (containers without X11 keep reporting -1), the time since the last HUMAN input in this session: last_human_at == 0 means no human was ever seen and is not evidence of absence.
func (*Service) WaitTurn ¶
func (s *Service) WaitTurn(ctx context.Context, sid, decisionID string, wait time.Duration) (TurnStatus, error)
WaitTurn blocks up to wait (0 = single read) until the turn is answered, expired, or the session's relay is switched off; it then reports the outcome. ctx cancellation ends the wait early with the last observed status.
func (*Service) Wake ¶ added in v0.174.0
Wake sends the mailbox's wake prompt to a session whose process is idle, so a new turn starts and the hook injects the pending letters at its beginning. Transports, in order: the agent's deliver_command (codex queue), the Claude SendMessage messenger (one-shot job), the tmux pane. text goes through verbatim — no web prefix — and whatever the target answers to a messenger wake is dropped: the one-shot messenger is not a resident listener, and the target's hook only records a reply to a message that starts with the web prefix, which the wake does not have. A failure of the first transport that actually ran ends the ladder (a second one could type the prompt twice); transports that did not apply (no deliver_command, no peer address, no pane) fall through.
by is the display label of the wake ("gofer-mail"); origin is the ceiling owner behind the letters that caused it (see ceiling_origin.go).
type SuggestQuery ¶ added in v0.166.0
type SuggestQuery struct {
// Text is the item's text; Project is the item's project key (may be empty).
Text string
Project string
Limit int
// Visible narrows the candidates BEFORE ranking (session.read.others). nil = everything.
Visible func(jobstore.AgentSession) bool
// Roots returns a project's root paths; nil = none.
Roots func(projectKey string) []string
}
SuggestQuery is one recommendation request.
type SuggestResult ¶ added in v0.166.0
type SuggestResult struct {
FindResult
Score int
}
SuggestResult is a ranked candidate with the combined score.
type TakeoverPlan ¶
type TakeoverPlan struct {
Argv []string
AllowInteractive bool
ExecRoot string
// AltRoots are the project root's OTHER spellings (host path / container path):
// a session's cwd or transcript may have been recorded in a different view than
// the one the runner executes in, and is mapped onto ExecRoot through these.
AltRoots []string
// DirExists reports whether an ExecRoot-view directory exists on the runner.
// nil — or known=false — means the runner cannot be asked (a worker): the wake-up
// directory is then chosen by string inference only (ChooseResumeCwd says so).
DirExists func(path string) (exists, known bool)
}
TakeoverPlan is what the host knows about continuing a session's CLI interactively (design §9.1 B). The relay owns the routing policy and the failure reason codes, but it neither reads agent config nor project config, so the host resolves the three facts it needs and answers them here:
- Argv: the interactive resume command for this agent and session ([agent command] + rendered SessionResumeInteractive), empty when the agent has none — the relay then reports no_resume_template.
- AllowInteractive: the project's allow_interactive switch.
- ExecRoot: the project root AS THE RUNNER SEES IT (the server's own execution path view for a server-run session, the host path for a worker), against which the relay converts the session's absolute cwd into a relative one. Empty when the project is unknown.
type TakeoverRequest ¶
type TakeoverRequest struct {
ProjectKey string
Runner string
// Cmd is the argv that continues the session (TakeoverPlan.Argv).
Cmd []string
// Cwd is project-RELATIVE (the job service SafeJoins it on the runner), so the
// resumed process opens in the session's own directory.
Cwd string
Title string
Tags []string
// Cols/Rows are the new terminal's initial size.
Cols, Rows int
TimeoutSec int
// SessionID is the CLI session the takeover continues; ResumeSourceAgent is the
// agent that owns it (the exec carrier's access-control identity).
SessionID string
ResumeSourceAgent string
// InitialInput is the reply, prefixed and Enter-terminated: the pty runner
// types it once the resumed TUI has settled (see runner.Request.InitialInput).
InitialInput string
CallerID string
// OriginCaller is the ceiling owner of the takeover job (the caller that asked for it).
OriginCaller string
}
TakeoverRequest is path B's interactive pty job (design §9.1 B): a value type owned by this package so the host can submit it without the relay importing the job layer (G022). The host maps it onto its own request (an interactive exec job carrying the resume argv, authorised as the SOURCE agent so it does not need the broad allow_exec — the same rule as a job resume).
type TakeoverResult ¶
type TakeoverResult struct {
// JobID is the interactive pty job the web attaches to.
JobID string
}
TakeoverResult is the host's report of one takeover job.
type Takeoverer ¶
type Takeoverer interface {
// PlanTakeover answers what continuing this session would take (see TakeoverPlan).
// A zero plan (no argv, no admission) is a legitimate answer, not an error.
PlanTakeover(agentKey, projectKey, runner, sessionID string) TakeoverPlan
// TakeoverSession submits the interactive resume job and returns its id. It
// returns as soon as the job is ACCEPTED — the job runs for as long as the human
// keeps talking.
TakeoverSession(ctx context.Context, req TakeoverRequest) (TakeoverResult, error)
// CancelTakeover stops a takeover job that is still running. A job that already
// ended (or is not known any more) is NOT an error: the caller wants the session
// back, and a process that is gone holds nothing.
CancelTakeover(ctx context.Context, jobID string) error
}
Takeoverer is path B's host seam. The host owns agent/project config resolution and job submission; the relay owns when a takeover is allowed and what each failure means.
type TurnStatus ¶
type TurnStatus struct {
Outcome string
// Relay reports that the session currently waits for a reply (see WaitReason
// for the vocabulary); Reason is WHY — it is how the hook picks its poll
// cadence and what it logs. Detail explains a NON-waiting session (SUP-01 D:
// "supervising 2 jobs"), so a hook released by the supervision gate can say so.
Relay bool
Reason string
Detail string
Decision jobstore.PlanDecision
}
TurnStatus is WaitTurn's answer: the current decision row, whether the session still waits (and why) and the derived Outcome.
type UndeliverableError ¶
UndeliverableError carries the machine-readable reason code behind ErrUndeliverable (design §9.1 v0.5: no_runner | no_tmux | ended | inject_failed:<pane_missing|pane_busy:<cmd>|runner_error>).
func (*UndeliverableError) Error ¶
func (e *UndeliverableError) Error() string
func (*UndeliverableError) Is ¶
func (e *UndeliverableError) Is(target error) bool
Is makes errors.Is(err, ErrUndeliverable) hold for every reason.
func (*UndeliverableError) Unwrap ¶
func (e *UndeliverableError) Unwrap() error
Unwrap exposes the underlying cause (injector / configuration error).
type WorkHook ¶
type WorkHook interface {
OnHumanPrompt(a jobstore.AgentSession, prompt string)
// OnSessionBeat reports an applied hook heartbeat: the store does not announce those,
// yet a Stop / prompt beat changes whether the person is being waited for.
OnSessionBeat(a jobstore.AgentSession)
}
WorkHook is the work-item seam (W1): the relay knows when a HUMAN typed a prompt in a session, the work service turns the first one into an auto draft work item. nil = no work items. It must not block or fail the hook call.