Documentation
¶
Overview ¶
Package workbench projects persisted jobs and relay sessions into the conversation-first WEB-11 model. It owns projection and dispatch only; job and sessionrelay remain authoritative for execution and replies.
Index ¶
- Constants
- Variables
- func JobThreadID(jobID, sessionID string) string
- func PromptRef(jobID string, n int) string
- func TerminalNeedsReview(status, agent string, hasChanges, seen bool) bool
- func ValidSource(v string) bool
- type AttachMode
- type AttachmentDeps
- type AttachmentFiles
- type AttachmentStore
- type AttentionAction
- type AttentionItem
- type Counts
- type DiffSource
- type ImageJobs
- type JobTurn
- type Jobs
- type Layout
- type LayoutVersionConflict
- type OwnDirPlacer
- type PatchInput
- type Placer
- type ProjectGroup
- type Query
- type Relay
- type RelayDeliveryError
- type RelayImageMessenger
- type RelayMessenger
- type RelaySessions
- type RelaySummary
- type Response
- type ReviewComment
- type ReviewInput
- type ReviewSide
- type Route
- type RouteInput
- type Service
- func (s *Service) Diff(threadID string) (ThreadDiff, error)
- func (s *Service) DiffIn(lang i18n.Lang, threadID string) (ThreadDiff, error)
- func (s *Service) GetLayout(callerID string) (Layout, error)
- func (s *Service) List(callerID string, query Query) (Response, error)
- func (s *Service) Patch(callerID, threadID string, input PatchInput) (jobstore.WorkbenchThreadPref, error)
- func (s *Service) PutLayout(callerID string, expectedVersion int64, body json.RawMessage) (Layout, error)
- func (s *Service) Review(callerID, threadID string, input ReviewInput) (TurnResult, error)
- func (s *Service) SeenAll(callerID string) (int64, error)
- func (s *Service) SetAttachments(d AttachmentDeps)
- func (s *Service) Turn(callerID, threadID, text string) (TurnResult, error)
- func (s *Service) TurnWithAttachments(callerID, threadID, text string, attachmentIDs []string) (TurnResult, error)
- type Status
- type Store
- type Supervising
- type Thread
- type ThreadDiff
- type ThreadDiffFile
- type ThreadKind
- type ThreadSourceCounts
- type TurnResult
- type Usage
Constants ¶
const ( RefKindPrompt = "prompt" RefKindDecision = "decision" // RefKindMessage: a message to a terminal session (ref = its session outbox id). RefKindMessage = "message" )
RefKindPrompt / RefKindDecision are the attachment ref kinds a send records.
const ( SourceACP = "acp" SourcePTY = "pty" SourceRelay = "relay" )
Thread source filter values (Query.Source). Empty means no source filter.
const ( MaxReviewComments = 50 MaxReviewCommentRunes = 4000 )
const MaxLayoutBodyBytes = 64 * 1024
Variables ¶
var ( // ErrAttachmentForbidden: an attachment is unknown or belongs to another caller (the // two are indistinguishable to the caller, so ids do not leak). ErrAttachmentForbidden = errors.New("workbench: attachment not available to this caller") // ErrAttachmentSent: the attachment was already sent with another message, or expired. ErrAttachmentSent = errors.New("workbench: attachment already sent or expired") // ErrTooManyAttachments: more attachments than server.attachments.max_per_message. ErrTooManyAttachments = errors.New("workbench: too many attachments") // ErrAttachmentsUnsupported: the receiver takes no images (the reason follows). ErrAttachmentsUnsupported = errors.New("workbench: thread does not accept attachments") // ErrAttachmentDelivery: placing the images on the executing machine failed; nothing // was sent (design decision 6). ErrAttachmentDelivery = errors.New("workbench: attachment delivery failed") )
Attachment errors; the HTTP layer maps them (403 / 409 / 400 / 502).
var ( ErrInvalidThreadID = errors.New("workbench: invalid thread id") ErrUnknownThread = errors.New("workbench: unknown thread") ErrNotResumable = errors.New("workbench: thread is not resumable") ErrEmptyTurn = errors.New("workbench: turn text is required") ErrInvalidLayout = errors.New("workbench: invalid layout") ErrLayoutTooLarge = errors.New("workbench: layout body exceeds 64 KiB") ErrMissingDiffBase = errors.New("workbench: first turn has no git diff base") ErrDiffTimeout = errors.New("workbench: thread diff timed out") ErrInvalidReview = errors.New("workbench: invalid review") ErrInvalidCursor = errors.New("workbench: invalid cursor") )
var ErrRelayDelivery = errors.New("workbench: session message not delivered")
ErrRelayDelivery wraps a failed message to a terminal session (the outbox already holds the failed record); the HTTP layer answers it as 409 with a readable reason.
Functions ¶
func JobThreadID ¶
JobThreadID is the canonical job-event to workbench-thread mapping. A captured agent session groups every resume turn; a one-shot job stands alone.
func PromptRef ¶ added in v0.177.0
PromptRef is the attachment ref of the prompt number n (1-based) of job id: the key the ACP history joins on (the n-th prompt event of the job's structured record).
func TerminalNeedsReview ¶
TerminalNeedsReview is F16's single review predicate, shared by the workbench projection and Web Push dispatcher.
func ValidSource ¶ added in v0.213.0
ValidSource reports whether v is an accepted Query.Source value ("" included).
Types ¶
type AttachMode ¶ added in v0.177.0
type AttachMode string
AttachMode is how the images of a message reach the receiver.
const ( // AttachInline: ACP image content blocks (the session advertised promptCapabilities.image). AttachInline AttachMode = "inline" // AttachFile: the images are placed on the executing machine and the message names // their absolute paths; the agent opens them itself. AttachFile AttachMode = "file" // AttachArg: the images are placed on the executing machine and each absolute path rides // the ARGV of the job that carries the message (the agent's image_args template), so the // text stays clean — no `[附图 n]` line. AttachArg AttachMode = "arg" // AttachNone: the receiver cannot take images; Reason says why. AttachNone AttachMode = "none" )
type AttachmentDeps ¶ added in v0.177.0
type AttachmentDeps struct {
Store AttachmentStore
Files AttachmentFiles
Xfer Placer
Jobs ImageJobs
Config func() *config.Config
MaxPerMessage func() int
}
AttachmentDeps wires the send path; without Store/Files the service accepts no attachments and reports no capability bit.
type AttachmentFiles ¶ added in v0.177.0
type AttachmentFiles interface {
Read(rec jobstore.Attachment) ([]byte, error)
AbsPath(rec jobstore.Attachment) (string, error)
}
AttachmentFiles reads the stored originals (attachment.Service).
type AttachmentStore ¶ added in v0.177.0
type AttachmentStore interface {
GetAttachment(id string) (jobstore.Attachment, bool, error)
BindAttachment(id, threadID, refKind, refID string) error
UnbindAttachment(id, threadID string) error
ListAttachmentsByThread(threadID string) ([]jobstore.Attachment, error)
}
AttachmentStore is the slice of jobstore.Store the send path uses.
type AttentionAction ¶
type AttentionAction string
const ( ActionAnswer AttentionAction = "answer" ActionReview AttentionAction = "review" ActionReply AttentionAction = "reply" )
type AttentionItem ¶
type AttentionItem struct {
ThreadID string `json:"thread_id"`
ProjectKey string `json:"project_key"`
Title string `json:"title"`
Status Status `json:"status"`
Action AttentionAction `json:"action"`
WaitingSince int64 `json:"waiting_since"`
JobID string `json:"job_id,omitempty"`
InteractionID string `json:"interaction_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
DecisionID string `json:"decision_id,omitempty"`
}
type DiffSource ¶
type DiffSource string
const ( DiffSourceLive DiffSource = "live" DiffSourceCaptured DiffSource = "captured" )
type ImageJobs ¶ added in v0.177.0
type ImageJobs interface {
SessionAcceptsImages(jobID string) (bool, error)
SaySessionBlocks(jobID, text string, images []job.ImageInput) error
}
ImageJobs is the image-carrying side of the job service.
type Jobs ¶
type Jobs interface {
ResumeJob(jobID, prompt, runner, callerID string) (job.JobResult, error)
// ResumeJobWithImages continues a session with image paths riding the continuation's
// argv (image_input: arg).
ResumeJobWithImages(jobID, prompt, runner, callerID string, imagePaths []string) (job.JobResult, error)
SaySession(jobID, message string) error
}
type Layout ¶
type Layout struct {
Version int64 `json:"version"`
Body json.RawMessage `json:"body"`
}
type LayoutVersionConflict ¶
type LayoutVersionConflict struct {
Current Layout
}
LayoutVersionConflict carries the server value a client must adopt after a stale optimistic write.
func (*LayoutVersionConflict) Error ¶
func (e *LayoutVersionConflict) Error() string
type OwnDirPlacer ¶ added in v0.201.0
type OwnDirPlacer interface {
PutAttachmentsAndWait(ctx context.Context, caller, runner, srcPath, dest string, timeout time.Duration) (string, error)
OwnAttachmentsSupported(runner string) bool
}
OwnDirPlacer is the optional half of Placer for a session that belongs to no project: it places into the EXECUTING machine's own attachment directory and answers whether that machine can take one at all (xfer.Manager.PutAttachmentsAndWait / OwnAttachmentsSupported). A Placer that does not implement it cannot deliver to a project-less session, which is exactly what the route's refusal says.
type PatchInput ¶
type Placer ¶ added in v0.177.0
type Placer interface {
PutAndWait(ctx context.Context, caller, runner, projectKey, srcPath, dest string, timeout time.Duration) (string, error)
}
Placer puts a local file onto the executing machine (xfer.Manager.PutAndWait).
type ProjectGroup ¶
type Query ¶
type Query struct {
// Lang is the language of the display text of the threads (the request language;
// zero = the default language).
Lang i18n.Lang
Project string
Status Status
Q string
Since int64
// ActiveWithin is a relative activity window in seconds (an alternative to Since;
// Since wins when both are set).
ActiveWithin int64
// Limit > 0 or a Cursor switches to paged mode: a keyset page of Limit ordinary
// threads (default 50, at most 500) ordered by activity, newest first. Live and pinned
// threads ride along on the first page whatever their age and do not count to Limit.
// Cursor is a previous response's NextCursor; a cursor request has no window unless
// Since / ActiveWithin is set explicitly.
Limit int
Cursor string
// Keep, when set, is an extra visibility filter (the caller's ownership / ceiling)
// applied before a page is cut, so a page fills with visible threads only.
Keep func(Thread) bool
// Source narrows to one thread source (SourceACP / SourcePTY / SourceRelay; "" = all).
Source string
// Agent and Runner narrow to threads whose agent / runner matches exactly ("" = any).
Agent string
Runner string
// Counts asks for the per-source counts of the threads that pass every filter EXCEPT
// Source, so a source tab can show how many threads each other tab holds. The counts
// cover the whole time window of the request, not the page: paging and Source leave
// them unchanged.
Counts bool
// Live keeps only threads with something running; in paged mode it is a single first
// page (no cursor, HasMore=false).
Live bool
// Include lists thread ids that ride along on the first page like pinned ones (they
// still pass every other filter). Ignored with a cursor and by the unpaged listing.
Include []string
// IncludeInternal also lists web session-messenger delivery jobs (all=1).
IncludeInternal bool
}
type Relay ¶
type Relay interface {
Say(sessionID, answer, callerID string) (jobstore.PlanDecision, error)
}
type RelayDeliveryError ¶ added in v0.177.1
type RelayDeliveryError struct{ Err error }
RelayDeliveryError is the cause of a failed terminal-session message; it matches ErrRelayDelivery and unwraps to the relay's own error (so sessionrelay.DeliverReason works).
func (*RelayDeliveryError) Error ¶ added in v0.177.1
func (e *RelayDeliveryError) Error() string
func (*RelayDeliveryError) Is ¶ added in v0.177.1
func (e *RelayDeliveryError) Is(target error) bool
func (*RelayDeliveryError) Unwrap ¶ added in v0.177.1
func (e *RelayDeliveryError) Unwrap() error
type RelayImageMessenger ¶ added in v0.204.0
type RelayMessenger ¶ added in v0.177.1
type RelayMessenger interface {
// SendMessage takes the display label (operator) and the caller-scope ceiling owner of the
// message (origin) separately; see sessionrelay's ceiling_origin.go.
SendMessage(ctx context.Context, sid, text, operator, origin string) (jobstore.SessionMessage, error)
CheckDeliverable(sid string) error
FollowWeb(sid, actor string)
}
RelayMessenger is what the session drawer's web message calls (sessionrelay.Service): a session waiting for a reply is answered, one with a Claude SendMessage address goes through the messenger, any other takes the deliver_command / tmux ladder. A Relay that has it is used for workbench turns instead of Say, which only answers an OPEN turn.
type RelaySessions ¶ added in v0.177.0
type RelaySessions interface {
Session(sid string) (jobstore.AgentSession, error)
}
RelaySessions is the optional lookup of a terminal session's executor.
type RelaySummary ¶
type Response ¶
type Response struct {
Projects []ProjectGroup `json:"projects"`
Attention []AttentionItem `json:"attention"`
Total int `json:"total"`
Since int64 `json:"since"`
// Counts is set when the caller asked for it (Query.Counts): the threads per source
// under every filter but the source one. See ThreadSourceCounts.
Counts *ThreadSourceCounts `json:"counts,omitempty"`
// HasMore / NextCursor are set in paged mode: older threads can be fetched by passing
// NextCursor back as the cursor. HasMore may be true while the next page comes back
// empty (the older threads are all filtered out).
HasMore bool `json:"has_more,omitempty"`
NextCursor string `json:"next_cursor,omitempty"`
}
func (Response) Summary ¶ added in v0.176.0
Summary returns a copy of the response whose threads carry only the fields a list view reads: the heavy per-thread parts (jobs, pending_interactions, cwd, interactive and the relay's last event / message) are left out. job_ids stays (a few bytes per thread; the web maps a freshly launched job back to its thread with it). Threads whose id is in full are kept complete. Counts, attention and everything else are unchanged. The receiver is not modified.
type ReviewComment ¶
type ReviewComment struct {
Path string `json:"path"`
Line int `json:"line"`
Side ReviewSide `json:"side"`
Text string `json:"text"`
}
type ReviewInput ¶
type ReviewInput struct {
Summary string `json:"summary,omitempty"`
Comments []ReviewComment `json:"comments,omitempty"`
}
type ReviewSide ¶
type ReviewSide string
const ( ReviewSideNew ReviewSide = "new" ReviewSideOld ReviewSide = "old" )
type Route ¶ added in v0.177.0
type Route struct {
Mode AttachMode
Reason string
}
Route is the delivery decision; Reason is set only for AttachNone.
func RouteAttachments ¶ added in v0.177.0
func RouteAttachments(in RouteInput) Route
RouteAttachments is the pure delivery-mode table:
pty job -> none ("pty 会话不支持附图")
live ACP session accepting images -> inline
agent cannot take images at all -> none ("<agent> 暂不支持读取图片")
no runner to place onto -> none ("会话没有执行机信息")
no project and no own attachment dir -> none (a hint to upgrade the worker)
agent takes images as argv flags (arg) -> arg
otherwise -> file
The project-less case is what OwnDir is for: with no project there is no project root to hang the placement under, so the images go to the executing machine's own attachment directory — which the server always has, a worker only when it declared wsproto.WorkerAttachMinProtocolVersion. An old worker is refused with the upgrade named instead of a placement it would drop.
type RouteInput ¶ added in v0.177.0
type RouteInput struct {
Kind ThreadKind
Agent string
Runner string
Project string
// Pty marks an interactive pty job: it takes no images at all.
Pty bool
// ACPAccepts: the thread is a live resident ACP session whose agent advertised
// promptCapabilities.image (job.SessionAcceptsImages).
ACPAccepts bool
// FilePath: the agent can read an image by absolute path (config image_input = path).
FilePath bool
// Arg: the agent takes an image path as an argv flag (config image_input = arg, agent
// image_args), so the placement result rides the next job's argv instead of the text.
Arg bool
// OwnDir: the executing machine can take the images into its OWN attachment directory
// (<config-dir>/run/attachments/<date>/), which is what a session that belongs to no
// project of that machine needs. True for the server itself and for a remote worker that
// declared the capability (xfer.Manager.OwnAttachmentsSupported).
OwnDir bool
// Lang is the language of the reasons (zero = the default language).
Lang i18n.Lang
}
RouteInput is everything RouteAttachments decides on; the callers fill it from a thread (List) or from the concrete target of a Turn.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
func (*Service) Diff ¶
func (s *Service) Diff(threadID string) (ThreadDiff, error)
Diff returns the changes made by a thread since its recorded Git base — the first turn's, or the latest turn's own baseline when it is a continuation (see threadDiffBase). Git is consulted only for a server-local latest turn whose cwd still exists; remote and vanished working directories use the latest captured artifact.
func (*Service) DiffIn ¶ added in v0.207.0
DiffIn is Diff with the diff's notice in lang (the request language).
func (*Service) Patch ¶
func (s *Service) Patch(callerID, threadID string, input PatchInput) (jobstore.WorkbenchThreadPref, error)
func (*Service) Review ¶
func (s *Service) Review(callerID, threadID string, input ReviewInput) (TurnResult, error)
Review converts structured inline comments into one ordinary workbench turn. Turn remains the only dispatch owner, so its session, runner, and state gates apply unchanged to review continuations.
func (*Service) SetAttachments ¶ added in v0.177.0
func (s *Service) SetAttachments(d AttachmentDeps)
SetAttachments injects the attachment dependencies (the server wires them once its attachment store and transfer manager exist).
func (*Service) TurnWithAttachments ¶ added in v0.177.0
func (s *Service) TurnWithAttachments(callerID, threadID, text string, attachmentIDs []string) (TurnResult, error)
TurnWithAttachments is Turn with images: attachmentIDs are uploaded attachments of callerID that were not sent yet. They are delivered inline or by file (see RouteAttachments) or, when the receiver takes no images, the whole send is refused with ErrAttachmentsUnsupported; a failed placement sends nothing (ErrAttachmentDelivery).
type Store ¶
type Store interface {
LoadWorkbenchSnapshot(callerID string, since int64, includeInternal bool) (jobstore.WorkbenchSnapshot, error)
LoadWorkbenchPage(callerID string, q jobstore.WorkbenchPageQuery) (jobstore.WorkbenchPage, error)
ListWorkbenchThreadPrefs(callerID string) ([]jobstore.WorkbenchThreadPref, error)
UpsertWorkbenchThreadPref(pref jobstore.WorkbenchThreadPref) error
GetOrCreateWorkbenchSeenBaseline(callerID string, observedAt int64) (int64, error)
SetWorkbenchSeenBaseline(callerID string, observedAt int64) (int64, error)
GetWorkbenchLayout(callerID string) (jobstore.WorkbenchLayout, bool, error)
PutWorkbenchLayout(callerID string, expectedVersion int64, bodyJSON string, updatedAt int64) (jobstore.WorkbenchLayout, bool, error)
ListJobs(query jobstore.ListQuery) ([]jobstore.JobRecord, error)
GetJob(id string) (jobstore.JobRecord, bool, error)
}
type Supervising ¶ added in v0.213.0
type Supervising struct {
Jobs int `json:"jobs,omitempty"`
Subagents int `json:"subagents,omitempty"`
Watches int `json:"watches,omitempty"`
}
Supervising says a relay session is being watched by other work (jobs in flight, running sub-agents, watched jobs), so its open turn is not waiting for a person.
type Thread ¶
type Thread struct {
ID string `json:"id"`
Kind ThreadKind `json:"kind"`
Status Status `json:"status"`
RawStatus string `json:"raw_status,omitempty"`
Stalled bool `json:"stalled,omitempty"`
Title string `json:"title"`
ProjectKey string `json:"project_key"`
Agent string `json:"agent,omitempty"`
Runner string `json:"runner,omitempty"`
Cwd string `json:"cwd,omitempty"`
Interactive bool `json:"interactive,omitempty"`
Resumable bool `json:"resumable"`
Pinned bool `json:"pinned,omitempty"`
SeenAt int64 `json:"seen_at,omitempty"`
StartedAt int64 `json:"started_at"`
UpdatedAt int64 `json:"updated_at"`
WaitingSince int64 `json:"waiting_since,omitempty"`
Turns int `json:"turns"`
Usage *Usage `json:"usage,omitempty"`
LatestJobID string `json:"latest_job_id,omitempty"`
JobIDs []string `json:"job_ids,omitempty"`
Jobs []JobTurn `json:"jobs,omitempty"`
PendingInteractions []job.Interaction `json:"pending_interactions,omitempty"`
Relay *RelaySummary `json:"relay,omitempty"`
// Supervising is set on a relay thread shown as working because something supervises it.
Supervising *Supervising `json:"supervising,omitempty"`
// Attachments is how images sent to this thread would be delivered (inline | file |
// none); AttachmentsReason says why when it is none. Both are absent while the
// attachment store is not wired.
Attachments AttachMode `json:"attachments,omitempty"`
AttachmentsReason string `json:"attachments_reason,omitempty"`
}
type ThreadDiff ¶
type ThreadDiff struct {
Source DiffSource `json:"source"`
Base string `json:"base"`
Head string `json:"head,omitempty"`
Files []ThreadDiffFile `json:"files"`
Patch string `json:"patch"`
Truncated bool `json:"truncated"`
Commits []job.Commit `json:"commits,omitempty"`
Notice string `json:"notice,omitempty"`
}
ThreadDiff is the conversation-level review snapshot. Captured responses are explicitly scoped to the latest turn; live responses span base..working-tree.
type ThreadDiffFile ¶
type ThreadDiffFile struct {
Path string `json:"path"`
Status string `json:"status"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
Binary bool `json:"binary"`
}
ThreadDiffFile is one path changed since the thread's first Git baseline. Untracked files use status "?" and deliberately carry no content or line counts.
type ThreadKind ¶
type ThreadKind string
const ( KindAgent ThreadKind = "agent" KindJob ThreadKind = "job" KindRelay ThreadKind = "relay" )
func ParseThreadID ¶
func ParseThreadID(id string) (ThreadKind, string, error)
type ThreadSourceCounts ¶ added in v0.215.0
type ThreadSourceCounts struct {
ACP int `json:"acp"`
PTY int `json:"pty"`
Relay int `json:"relay"`
All int `json:"all"`
}
ThreadSourceCounts is how many threads each source holds under the current filters (Query.Counts): the source filter itself is not applied, so the numbers are stable while a caller switches tabs, and All is their sum.
type TurnResult ¶
type TurnResult struct {
ThreadID string `json:"thread_id"`
JobID string `json:"job_id,omitempty"`
DecisionID string `json:"decision_id,omitempty"`
// MessageID is the session outbox message a terminal (relay) thread's turn recorded.
MessageID string `json:"message_id,omitempty"`
// Path is how a message to a terminal (relay) thread was delivered: turn | command |
// tmux | takeover (sessionrelay.Path*). Empty for every other thread kind.
Path string `json:"path,omitempty"`
// Delivering: the text was handed to an internal job that was still on its way when the
// wait window elapsed (the session outbox says how it ended).
Delivering bool `json:"delivering,omitempty"`
}
type Usage ¶
type Usage struct {
InputTokens int64 `json:"input_tokens,omitempty"`
OutputTokens int64 `json:"output_tokens,omitempty"`
CacheReadTokens int64 `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int64 `json:"cache_write_tokens,omitempty"`
TotalTokens int64 `json:"total_tokens,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
}