Documentation
¶
Index ¶
- Constants
- Variables
- func AttachmentsRootForTask(dataHome, taskID string) string
- func DeriveProjectIDFromURL(normalizedURL string) (string, error)
- func EnsureAttachmentsDir(dataHome, taskID string) (string, error)
- func FormatAbortReason(o TaskOutcome) string
- func JobLogNoRuntimeMessage(id string, status JobStatus) string
- func JobLogNoSuchJobMessage(id string) string
- func JobLogTranscriptGoneMessage(runtimeID string) string
- func ListAttachments(dataHome, taskID string) ([]string, error)
- func ReadAttachment(dataHome, taskID, name string) ([]byte, error)
- func ResolveJSONField(raw json.RawMessage, path string) (string, error)
- func ResolveTaskField(task *orchestrator.Task, actions orchestrator.LifecycleStore, path string) (string, error)
- func SanitizeAttachmentName(raw string) (string, error)
- func SaveMultipartAttachments(dataHome, taskID string, files []*multipart.FileHeader) ([]string, error)
- func ValidateAttachmentHeaders(files []*multipart.FileHeader) error
- func ValidateHarnessType(harness string) string
- type AckSignalsRequest
- type AckSignalsResponse
- type ActionApplication
- type ActionHandler
- type ActionListResult
- type ActionListStore
- type ActionStore
- type AnswerSuggestionRequest
- type AnswerTaskRequest
- type ApplyActionRequest
- type BlockingAskRegistry
- func (r *BlockingAskRegistry) Cancel(qid string)
- func (r *BlockingAskRegistry) Has(qid string) bool
- func (r *BlockingAskRegistry) Notify(qid, answer string) bool
- func (r *BlockingAskRegistry) Register(taskID, qid string) error
- func (r *BlockingAskRegistry) Wait(ctx context.Context, qid string) (string, error)
- type BrokerHandler
- type BrokerRegisterRequest
- type BrokerRegisterResponse
- type BrokerRegistry
- type CardActivityStore
- type CardCommandLauncherStore
- type CardCommandOption
- type CardCommandRunService
- type CardCommandWebService
- type CardHandler
- type CardReadService
- type CardRequestDispatchLoop
- type CardRequestDispatchStore
- type CardRequestHandler
- type CardRequestReleaseStore
- type CardRequestTaskLinker
- type CardStore
- type CardTimelineStore
- type CardView
- type ConfigApplyResult
- type ConfigHandler
- func (h *ConfigHandler) Apply(w http.ResponseWriter, r *http.Request)
- func (h *ConfigHandler) Get(w http.ResponseWriter, r *http.Request)
- func (h *ConfigHandler) KitsDir(w http.ResponseWriter, r *http.Request)
- func (h *ConfigHandler) Mutate(w http.ResponseWriter, r *http.Request)
- func (h *ConfigHandler) Routes() chi.Router
- type ConfigMutateOp
- type ConfigMutateRequest
- type ConfigMutateResult
- type ConfigService
- type ConnectorRef
- type CreateProjectFromGitURLRequest
- type CreateProjectRequest
- type CreateTaskRequest
- type DeviceAuthHandler
- type DeviceGCStore
- type DispatchCoordinator
- type DuplicateTaskRequest
- type ExecDispatcher
- type FoldedSiblingSummary
- type GCAppService
- type GCHandler
- type GCService
- type GCStore
- type GlobalJobStore
- type HookService
- type HostCommandsHandler
- type HostCommandsProvider
- type HostCommandsService
- type ImportError
- type ImportResult
- type Job
- type JobCompletion
- type JobDoneRequest
- type JobHandler
- func (h *JobHandler) AgentStop(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Done(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Get(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Log(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Patch(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Routes() chi.Router
- type JobLifecycle
- type JobListFilter
- type JobLogReader
- type JobLogSSEHandler
- type JobStatus
- type JobStore
- type JobWithContext
- type ListSignalsResponse
- type LoginHandler
- type MetaStore
- type Notifier
- type NotifyTaskRequest
- type OAuthLoginHandler
- type OAuthLoginService
- type OAuthLoginStart
- type OperationResultStore
- type Pairer
- type ProjectAppService
- func (s *ProjectAppService) ApplyWorkspace(apply *orchestrator.WorkspaceEnvelopeApply, dryRun bool) (*orchestrator.WorkspaceApplyResult, error)
- func (s *ProjectAppService) CreateProject(workDir string, requestedPerm string) (*orchestrator.Project, error)
- func (s *ProjectAppService) CreateProjectFromGitURL(ctx context.Context, gitURL, workspaceSlug, nameOverride string, ...) (*orchestrator.Project, error)
- func (s *ProjectAppService) CreateWorkspace(slug string, meta *orchestrator.WorkspaceMeta) (*WorkspaceDetail, error)
- func (s *ProjectAppService) DeleteProject(id string) error
- func (s *ProjectAppService) ExplainProject(id string) (*orchestrator.ProjectExplain, error)
- func (s *ProjectAppService) ExportWorkspaceEnvelopes(slugs []string) ([]byte, error)
- func (s *ProjectAppService) GetProject(id string) (*orchestrator.Project, error)
- func (s *ProjectAppService) GetWorkspace(slug string) (*WorkspaceDetail, error)
- func (s *ProjectAppService) GetWorkspaceInitScript(slug string) (*WorkspaceInitScript, error)
- func (s *ProjectAppService) GetWorkspaceRuntimeMeta(ctx context.Context, workspaceID string) (*orchestrator.ProjectMeta, error)
- func (s *ProjectAppService) ListProjects(workspaceID string) ([]*orchestrator.Project, error)
- func (s *ProjectAppService) ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
- func (s *ProjectAppService) RemoveWorkspace(slug string) (*WorkspaceRemoval, error)
- func (s *ProjectAppService) ResolveProjectRef(ref string) ([]*orchestrator.Project, error)
- func (s *ProjectAppService) SetProjectPerm(id, perm string) (*orchestrator.Project, error)
- func (s *ProjectAppService) SetProjectWorkspace(id, workspaceID string) (*orchestrator.Project, error)
- func (s *ProjectAppService) SetWorkspaceInitScript(slug string, content []byte, ifMatch string, force bool) (*WorkspaceInitScriptResult, error)
- func (s *ProjectAppService) UpdateWorkspace(slug string, meta *orchestrator.WorkspaceMeta, ifMatch string, force bool) (*WorkspaceDetail, error)
- func (s *ProjectAppService) WithProjectLock(fn func() error) error
- type ProjectHandler
- func (h *ProjectHandler) Create(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) CreateFromGitURL(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Delete(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Explain(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Get(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Routes() chi.Router
- func (h *ProjectHandler) RunTrigger(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) SetPerm(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) SetWorkspace(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) StartExec(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) StartSession(w http.ResponseWriter, r *http.Request)
- type ProjectRepository
- type ProjectService
- type ProjectWorkDirLookup
- type QueueSweepLoop
- type QueueSweepStore
- type ReleaseResult
- type ReopenTaskRequest
- type ReplayHookRequest
- type ReplayHookResult
- type RerunTaskRequest
- type ResolveOrCaptureRequest
- type ResolveOrCaptureResult
- type RunCardCommandResult
- type SecretHandler
- func (h *SecretHandler) Delete(w http.ResponseWriter, r *http.Request)
- func (h *SecretHandler) GetValue(w http.ResponseWriter, r *http.Request)
- func (h *SecretHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *SecretHandler) Routes() chi.Router
- func (h *SecretHandler) Set(w http.ResponseWriter, r *http.Request)
- type SecretStore
- type SessionDispatcher
- type SessionHandler
- type SetProjectWorkspaceRequest
- type SettingsConfigService
- type Signal
- type SignalHandler
- type SignalSource
- type SignalStore
- type StartExecRequest
- type StartExecResult
- type StartSessionRequest
- type StartSessionResult
- type StatusError
- type TaskAnswerService
- type TaskAppService
- func (s *TaskAppService) AnswerTask(ctx context.Context, taskID, questionID, answer string) error
- func (s *TaskAppService) AskTaskBlocking(ctx context.Context, taskID, question string) (string, error)
- func (s *TaskAppService) CreateTask(ctx context.Context, req CreateTaskRequest) (*orchestrator.Task, error)
- func (s *TaskAppService) DeleteTask(id string, force bool) error
- func (s *TaskAppService) DuplicateTask(ctx context.Context, sourceID string, autoStart bool) (*orchestrator.Task, error)
- func (s *TaskAppService) GetInstructions(id string) ([]orchestrator.RoutedInstruction, error)
- func (s *TaskAppService) GetInstructionsField(id, path string) (string, error)
- func (s *TaskAppService) GetTask(id string) (*orchestrator.Task, error)
- func (s *TaskAppService) GetTaskCurrent(id string) (*orchestrator.TaskSnapshot, error)
- func (s *TaskAppService) GetTaskCurrentField(id, path string) (string, error)
- func (s *TaskAppService) GetTaskDetail(id string) (*TaskDetailView, error)
- func (s *TaskAppService) GetTaskField(id, path string) (string, error)
- func (s *TaskAppService) ImportTasks(ctx context.Context, reqs []CreateTaskRequest) (*ImportResult, error)
- func (s *TaskAppService) LinkIdentity(ctx context.Context, projectID, identity, taskID string) error
- func (s *TaskAppService) LinkIdentityInScope(ctx context.Context, scope orchestrator.IdentityScope, identity, taskID string, ...) error
- func (s *TaskAppService) LinkIdentityWithMetadata(ctx context.Context, projectID, identity, taskID string, ...) error
- func (s *TaskAppService) LinkWorkspaceIdentity(ctx context.Context, workspaceID, identity, taskID string) error
- func (s *TaskAppService) ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
- func (s *TaskAppService) NotifyTask(ctx context.Context, ...) error
- func (s *TaskAppService) RerunTask(id string, req RerunTaskRequest) (*orchestrator.Task, error)
- func (s *TaskAppService) ResolveIdentity(projectID, identity string) (*orchestrator.Task, error)
- func (s *TaskAppService) ResolveIdentityInScope(scope orchestrator.IdentityScope, identity string) (*orchestrator.Task, error)
- func (s *TaskAppService) ResolveWorkspaceIdentity(workspaceID, identity string) (*orchestrator.Task, error)
- func (s *TaskAppService) UnlinkIdentity(ctx context.Context, projectID, identity string) error
- func (s *TaskAppService) UnlinkIdentityInScope(ctx context.Context, scope orchestrator.IdentityScope, identity string) error
- func (s *TaskAppService) UnlinkWorkspaceIdentity(ctx context.Context, workspaceID, identity string) error
- func (s *TaskAppService) UpdateTask(ctx context.Context, id string, req UpdateTaskRequest) (*orchestrator.Task, error)
- func (s *TaskAppService) UpdateTaskPayloadPatch(jobID string, patch json.RawMessage, allowedTraits []orchestrator.TraitType) (*orchestrator.Task, error)
- func (s *TaskAppService) WaitTaskTerminal(ctx context.Context, taskID string) (TaskOutcome, error)
- type TaskCreator
- type TaskDetailView
- type TaskEvent
- type TaskEventHub
- type TaskHandler
- func (h *TaskHandler) Answer(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Create(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Delete(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Detail(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Duplicate(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Field(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Get(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Identity(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Import(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) ListHooks(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Notify(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Patch(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) ReplayHook(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Rerun(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) ResolveOrCapture(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Routes() chi.Router
- type TaskIdentityRequest
- type TaskIdentityStore
- type TaskNotifyService
- type TaskOutcome
- type TaskService
- type TaskStatusReader
- type TaskStore
- type TaskUpdatedAtToucher
- type TaskWaitRegistry
- type TaskWorkflowService
- func (s *TaskWorkflowService) ApplyAction(ctx context.Context, taskID string, req ApplyActionRequest) (*ActionApplication, error)
- func (s *TaskWorkflowService) CardCommandOptionsForProject(ctx context.Context, projectID string) []CardCommandOption
- func (s *TaskWorkflowService) CardCommandOptionsForWorkspace(ctx context.Context, workspaceID string) []CardCommandOption
- func (s *TaskWorkflowService) CompleteJob(ctx context.Context, jobID string, req JobDoneRequest) (*Job, error)
- func (s *TaskWorkflowService) GetCard(taskID string) (*CardView, error)
- func (s *TaskWorkflowService) InitDispatch(ctx context.Context)
- func (s *TaskWorkflowService) ListActions(filter orchestrator.ActionListFilter) (*ActionListResult, error)
- func (s *TaskWorkflowService) ListCards(filter orchestrator.TaskFilter) ([]*CardView, error)
- func (s *TaskWorkflowService) ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
- func (s *TaskWorkflowService) ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
- func (s *TaskWorkflowService) ResolveOrCapture(ctx context.Context, req ResolveOrCaptureRequest) (*ResolveOrCaptureResult, error)
- func (s *TaskWorkflowService) RunCardCommandAsHuman(ctx context.Context, cardID, commandKey, instruction string) (*RunCardCommandResult, error)
- func (s *TaskWorkflowService) RunTriggerNow(ctx context.Context, projectID, triggerName string) (*TriggerRunNowResult, error)
- func (s *TaskWorkflowService) RunWorkspaceTriggerNow(ctx context.Context, workspaceID, triggerName string) (*TriggerRunNowResult, error)
- func (s *TaskWorkflowService) Shutdown()
- func (s *TaskWorkflowService) StopAgent(runtimeID string)
- func (s *TaskWorkflowService) SweepQueuedCardRequests(ctx context.Context, _ time.Time) ([]string, error)
- func (s *TaskWorkflowService) SweepReconcileChildren(ctx context.Context, _ time.Time) error
- func (s *TaskWorkflowService) SweepTriggers(ctx context.Context, now time.Time) (TriggerSweepResult, error)
- func (s *TaskWorkflowService) SweepWake(ctx context.Context, now time.Time) (woken []string, err error)
- type Transactor
- type TriggerCompletionResult
- type TriggerFireResult
- type TriggerKey
- type TriggerLoop
- type TriggerLoopStore
- type TriggerRunNowResult
- type TriggerRunStore
- type TriggerRunner
- type TriggerSkip
- type TriggerSweepResult
- type TxStore
- type UpdateJobRequest
- type UpdateTaskRequest
- type WSAttachHandler
- type WebAppService
- func (s *WebAppService) AnswerSuggestion(taskID string, req AnswerSuggestionRequest) error
- func (s *WebAppService) AnswerSuggestionWithResult(taskID string, req AnswerSuggestionRequest) (*ActionApplication, error)
- func (s *WebAppService) AnswerTask(ctx context.Context, taskID, questionID, answer string) error
- func (s *WebAppService) ApplyAction(taskID string, actionType string) error
- func (s *WebAppService) ApplyActionWithResult(taskID string, actionType string) (*ActionApplication, error)
- func (s *WebAppService) CardCommandOptionsForProject(ctx context.Context, projectID string) []CardCommandOption
- func (s *WebAppService) CardCommandOptionsForWorkspace(ctx context.Context, workspaceID string) []CardCommandOption
- func (s *WebAppService) CreateTask(ctx context.Context, req CreateTaskRequest) (*orchestrator.Task, error)
- func (s *WebAppService) DeleteTask(id string, force bool) error
- func (s *WebAppService) DuplicateTask(ctx context.Context, id string) (string, error)
- func (s *WebAppService) GetJob(id string) (*JobWithContext, error)
- func (s *WebAppService) GetProjectByID(id string) (*orchestrator.Project, error)
- func (s *WebAppService) GetTaskDetail(id string) (*TaskDetailView, error)
- func (s *WebAppService) ListBehaviors() ([]string, error)
- func (s *WebAppService) ListCardProjects() ([]*orchestrator.Project, error)
- func (s *WebAppService) ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
- func (s *WebAppService) ListJobs(status string) ([]JobWithContext, error)
- func (s *WebAppService) ListProjects() ([]*orchestrator.Project, error)
- func (s *WebAppService) ListSessions() ([]JobWithContext, error)
- func (s *WebAppService) ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
- func (s *WebAppService) ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
- func (s *WebAppService) ReopenTask(id string, req ReopenTaskRequest) error
- func (s *WebAppService) ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
- func (s *WebAppService) RerunTask(id string, req RerunTaskRequest) error
- func (s *WebAppService) RunCardCommandAsHuman(ctx context.Context, cardID, commandKey, instruction string) (*RunCardCommandResult, error)
- func (s *WebAppService) UpdateTask(ctx context.Context, id string, req UpdateTaskRequest) error
- type WebHandler
- func (h *WebHandler) GetTaskEdit(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) HookReplayList(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) JobDetail(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) JobTerminal(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostAction(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostAnswer(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostAnswerSuggestion(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostCardCommand(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostDelete(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostDuplicate(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostEdit(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostHookReplay(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostReopen(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostRerun(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostStartSession(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostTaskCreate(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) QuestionPage(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) ReopenForm(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) Routes() chi.Router
- func (h *WebHandler) SessionList(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) SessionNew(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) Settings(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskCardTimelineHead(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskCardTimelineOlder(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskChildDetail(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskDetail(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskDetailFragment(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskEvents(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskList(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskNew(w http.ResponseWriter, r *http.Request)
- type WebManagementHandler
- func (h *WebManagementHandler) DeleteAllDevices(w http.ResponseWriter, r *http.Request)
- func (h *WebManagementHandler) DeleteDevice(w http.ResponseWriter, r *http.Request)
- func (h *WebManagementHandler) GetDevices(w http.ResponseWriter, r *http.Request)
- func (h *WebManagementHandler) PostPair(w http.ResponseWriter, r *http.Request)
- func (h *WebManagementHandler) Routes() chi.Router
- type WebService
- type WorkflowService
- type WorkspaceDetail
- type WorkspaceHandler
- func (h *WorkspaceHandler) Apply(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Create(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) ExportEnvelope(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) GetInitScript(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) ImportHome(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) PutInitScript(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Remove(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Routes() chi.Router
- func (h *WorkspaceHandler) RunTrigger(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Show(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Update(w http.ResponseWriter, r *http.Request)
- type WorkspaceHomeImportResponse
- type WorkspaceHomeImporter
- type WorkspaceHomeSize
- type WorkspaceHomeStore
- type WorkspaceInitScript
- type WorkspaceInitScriptResult
- type WorkspaceInitScriptStore
- type WorkspaceRemoval
- type WorkspaceRemoveResponse
- type WorkspaceSlugLister
- type WorkspaceStore
- type WorkspaceTriggerRunner
Constants ¶
const ( AttachmentMaxFileBytes int64 = 10 * 1024 * 1024 // 10 MB per file AttachmentMaxTotalBytes int64 = 30 * 1024 * 1024 // 30 MB per task dir AttachmentMaxNameBytes = 255 )
Attachment-related constants. Values are also enforced client-side in web/static/boid-paste-attach.js; keep the two in sync.
const ( TriggerStuckOverrunMultiplier = 1.5 TriggerStuckFailStreakThreshold = 3 )
TriggerStuckOverrunMultiplier: a run is "stuck" once it has been continuously in flight for longer than TriggerStuckOverrunMultiplier × its own `every`, scaling the threshold to each trigger's own schedule rather than counting raw sweep ticks (see TriggerLoop.trackSkipStreak).
TriggerStuckFailStreakThreshold counts consecutive completed runs with a non-zero exit code, one data point per actual execution.
const ConfigMutateSet = apiwire.ConfigMutateSet
const ConfigMutateUnset = apiwire.ConfigMutateUnset
const JobStatusCompleted = apiwire.JobStatusCompleted
const JobStatusFailed = apiwire.JobStatusFailed
const JobStatusRunning = apiwire.JobStatusRunning
const TriggerDispatchFailureExitCode = -2
TriggerDispatchFailureExitCode is the sentinel SweepTriggers reports in TriggerSweepResult.Completed for a StartExec (dispatch) failure — distinct from TriggerRunSelfHealExitCode so the two failure classes stay distinguishable (self-heal = a job was dispatched but its outcome was never observed; this = the job was never dispatched at all).
const TriggerRunSelfHealExitCode = -1
TriggerRunSelfHealExitCode is the sentinel CompleteTriggerRun records for a self-healed row — counts toward trackFailStreak like any other non-zero exit code. Outside the real 0-255 exit code range so it reads unambiguously in logs/notifications.
const TriggerRunSelfHealGrace = 3 * time.Minute
TriggerRunSelfHealGrace bounds how long a trigger_runs row may sit in-flight without resolving to a real job's terminal state before reconcileInFlight force-closes it — otherwise a vanished job row (e.g. swept by GC) would wedge single-flight for that (project, trigger) forever. Expressed as wall-clock time rather than a tick count because reconcileInFlight also runs from RunTriggerNow's own goroutine.
const TriggerTimeoutExitCode = -3
TriggerTimeoutExitCode is the sentinel SweepTriggers records for a run ended by its trigger's own `timeout` — distinct from the other two (self-heal = dispatched but unobserved; dispatch failure = never dispatched; this = ran too long).
const WorkspaceInitScriptAbsentRevision = apiwire.WorkspaceInitScriptAbsentRevision
const WorkspaceInitScriptCleared = apiwire.WorkspaceInitScriptCleared
const WorkspaceInitScriptContentType = apiwire.WorkspaceInitScriptContentType
from internal/api/workspace_init_script.go
const WorkspaceInitScriptUnchanged = apiwire.WorkspaceInitScriptUnchanged
const WorkspaceInitScriptWritten = apiwire.WorkspaceInitScriptWritten
Variables ¶
var AttachmentAllowedExts = map[string]bool{ ".png": true, ".jpg": true, ".jpeg": true, ".webp": true, ".txt": true, ".md": true, ".json": true, ".log": true, }
AttachmentAllowedExts is the file-extension allowlist for uploads. Both images (for screenshot paste) and a few text formats (for logs / json snippets) are accepted.
var ErrAskPending = errors.New("task_ask: another question is pending")
ErrAskPending is returned by BlockingAskRegistry.Register when the task already has an outstanding blocking ask: a second concurrent `boid task ask` for the same task fails immediately rather than queueing behind the first.
var SideEffectConsumesPayload = map[string]bool{ "park": true, "attrs_set": true, "child_added": true, "child_specced": true, "child_dropped": true, "noted": true, }
SideEffectConsumesPayload names the action types whose own side effect already consumes the action payload, so ApplyAction must NOT additionally merge that payload into the task's own — see the merge site below for what the pollution looks like.
Exported, and a package-level var rather than a literal inside ApplyAction, so a test can compare it against the copy of this set the boid-metaproject skill's python client carries (boid_store.py's PAYLOAD_CONSUMING) — that client refuses to send a payload with a type that would be merged and cannot ask the daemon at call time, so the two sides must be kept in sync; TestSideEffectConsumesPayload_MatchesMetaprojectClient is what enforces it.
Functions ¶
func AttachmentsRootForTask ¶ added in v0.0.7
AttachmentsRootForTask resolves the on-disk attachments directory for the given task. dataHome is the data root (e.g. filepath.Dir(cfg.DBPath)), the same convention as runtimesDirFor.
taskID must be a single canonical path component: the broker (internal/sandbox/broker.go) authorizes attachments ops by comparing the *raw* TaskID string against the token's own context, never a resolved filesystem path — so a task literally IDed "alias/../<victim-id>" would pass that check trivially while filepath.Join here silently collapsed it to the victim's real attachments directory. Rejecting a non-canonical taskID here (returning "") protects every caller uniformly: both the write path (EnsureAttachmentsDir, SaveMultipartAttachments) and the read path (ListAttachments, ReadAttachment) resolve through this function.
func DeriveProjectIDFromURL ¶ added in v0.1.0
func EnsureAttachmentsDir ¶ added in v0.0.7
EnsureAttachmentsDir creates the per-task attachments directory if it does not already exist. Used by handlers right after task creation / before accepting answer attachments so the bind mount has a non-empty source.
func FormatAbortReason ¶ added in v0.4.0
func FormatAbortReason(o TaskOutcome) string
FormatAbortReason renders an outcome's abort reason as one human line, or "" when there is nothing to say — which is the common case for a failure inside the agent's own session, since job_failed records no payload.
func JobLogNoRuntimeMessage ¶ added in v0.1.0
func JobLogNoSuchJobMessage ¶ added in v0.1.0
JobLogNoSuchJobMessage, JobLogNoRuntimeMessage and JobLogTranscriptGoneMessage are the three explanations above, exported so the sandbox-side `boid job log` builtin (internal/server's boidBuiltinExecutor) answers with the same words as the REST endpoint. An agent reading a log inside a sandbox and an operator reading one at a terminal are diagnosing the same thing; having the two surfaces drift into separate vocabularies for it is how "log not available" became meaningless in the first place.
func JobLogTranscriptGoneMessage ¶ added in v0.1.0
func ListAttachments ¶ added in v0.0.13
ListAttachments returns the basenames of the regular files directly under the task's attachments directory, sorted. Subdirectories are never recursed into — attachments are a flat namespace. A task that has never received an attachment (missing directory) returns an empty, non-nil slice rather than an error, matching the RPC's "no data" convention (JSON `[]`, not `null`).
Every symlink and non-regular entry (FIFO, socket, device) is excluded: ReadAttachment rejects every symlink categorically (via openat2 RESOLVE_NO_SYMLINKS on Linux), so list's admission criteria must exactly match what get can actually serve.
func ReadAttachment ¶ added in v0.0.13
ReadAttachment returns the bytes of one attachment, addressed by its exact basename. name must be a single canonical path component: a traversal or absolute-path attempt ("../../etc/passwd", "/etc/passwd") is rejected by validateAttachmentLookupName before any path is constructed, rather than silently coerced into some *other* file. The actual open+read (readAttachmentBytes, platform-specific — see attachment_read_linux.go) opens the file exactly once and reuses that descriptor for both the containment/type check and the capped read, closing the TOCTOU window a separate check-then-reopen sequence would leave.
func ResolveJSONField ¶ added in v0.0.13
func ResolveJSONField(raw json.RawMessage, path string) (string, error)
ResolveJSONField resolves a dotted path against arbitrary already-marshaled JSON data, using the same segment-traversal / value-formatting rules as ResolveTaskField (missing path → "", scalar → unquoted/stringified, object/array → compact JSON, traversing into a scalar → error). Unlike ResolveTaskField it does no task-specific implicit `payload.` prefixing or `lifecycle` injection — every other task-context RPC (`boid task current` / `instructions` / `env` / `payload`) shares this generic core so `--field` behaves identically everywhere task_get already established the contract.
func ResolveTaskField ¶
func ResolveTaskField(task *orchestrator.Task, actions orchestrator.LifecycleStore, path string) (string, error)
ResolveTaskField returns the value at the given dotted path against the task.
Path resolution:
- Each dot-separated segment is a JSON key.
- The first segment is matched against top-level Task fields (via JSON tags). When it doesn't match, the path is implicitly resolved inside `payload`, so traits like `awaiting.question`, `artifact.report`, and `lifecycle.abort.message` work without an explicit `payload.` prefix.
- `lifecycle` is a computed trait derived from action history. When lifecycle is referenced, ResolveTaskField calls DeriveLifecycle (when actions is non-nil) and injects the result under `payload.lifecycle` before traversal.
Output format:
- Strings: returned unquoted.
- Numbers and booleans: stringified.
- Objects and arrays: compact JSON.
- Missing path: returns "" with no error.
- Traversing into a scalar with remaining path segments: error.
func SanitizeAttachmentName ¶ added in v0.0.7
SanitizeAttachmentName validates a user-supplied filename and returns the cleaned basename. It rejects anything that doesn't match attachmentNameRe, exceeds the byte cap, has a disallowed extension, or contains only a dot prefix (".env" etc., which the regex would otherwise allow).
func SaveMultipartAttachments ¶ added in v0.0.7
func SaveMultipartAttachments(dataHome, taskID string, files []*multipart.FileHeader) ([]string, error)
SaveMultipartAttachments persists every file under the multipart form field "attachments" into the task-scoped attachments directory. It enforces:
- per-file size cap (AttachmentMaxFileBytes)
- aggregate task-dir size cap (AttachmentMaxTotalBytes)
- filename sanitization (SanitizeAttachmentName)
On success it returns the list of saved basenames. On any error it removes the files it had partially written during this call so the caller can surface the error without leaving orphans behind.
func ValidateAttachmentHeaders ¶ added in v0.0.7
func ValidateAttachmentHeaders(files []*multipart.FileHeader) error
ValidateAttachmentHeaders runs the size + name checks that SaveMultipartAttachments would apply, without touching the filesystem. Web handlers call this *before* creating the task so a bad upload (oversized, bad extension, disallowed name) doesn't leave a half-created task behind.
func ValidateHarnessType ¶ added in v0.5.0
ValidateHarnessType returns "" when harness is allowed for a session, or the bad-request message otherwise. Only the agent harnesses are accepted; the historical "shell" session variant was retired after the git gateway cutover — use `boid exec -p <project> -- bash` for a shell inside the project sandbox.
Types ¶
type AckSignalsRequest ¶ added in v0.4.0
type AckSignalsRequest = apiwire.AckSignalsRequest
type AckSignalsResponse ¶ added in v0.4.0
type AckSignalsResponse = apiwire.AckSignalsResponse
type ActionApplication ¶
type ActionApplication = apiwire.ActionApplication
from internal/api/service.go
type ActionHandler ¶
type ActionHandler struct {
Service WorkflowService
}
func (*ActionHandler) Apply ¶
func (h *ActionHandler) Apply(w http.ResponseWriter, r *http.Request)
func (*ActionHandler) Routes ¶
func (h *ActionHandler) Routes() chi.Router
type ActionListResult ¶ added in v0.4.0
type ActionListResult struct {
Actions []*orchestrator.Action `json:"actions"`
NextCursor string `json:"next_cursor"`
}
ActionListResult is ListActions' return shape: the matching actions plus the cursor a follow-up call should pass as filter.Since.
type ActionListStore ¶ added in v0.4.0
type ActionListStore interface {
// ListActionsSince returns the actions matching filter (oldest first)
// plus the next cursor. See orchestrator.ListActionsSince's own doc
// comment for the pagination/scoping contract.
ListActionsSince(filter orchestrator.ActionListFilter) ([]*orchestrator.Action, string, error)
}
ActionListStore provides the workspace-scoped read backing BoidOpActionList. Deliberately separate from ActionStore (ListActionsByTask, per-task, embedded in TxStore) for the same reason CardStore/TaskIdentityStore are their own interfaces: this is a non-transactional READ used outside WithinTx — the same "TaskWorkflowService.TaskTriage CardStore" narrowing pattern (workflow.go), not TxStore.
type ActionStore ¶
type ActionStore interface {
// CreateAction takes ctx so the card-event ingest step it performs
// can see the write's origin project via
// orchestrator.WriterProjectIDFromContext when this
// call was routed through internal/server/boid_executor.go's
// ExecuteBoidBuiltin (the only place that ever stamps it) — never
// consulted for anything else CreateAction does.
CreateAction(ctx context.Context, action *orchestrator.Action) error
ListActionsByTask(taskID string) ([]*orchestrator.Action, error)
}
type AnswerSuggestionRequest ¶ added in v0.4.0
type AnswerSuggestionRequest struct {
Answer string `json:"answer"`
Verb string `json:"verb,omitempty"`
Basis string `json:"basis,omitempty"`
}
AnswerSuggestionRequest is the Web UI's accept/reject form payload for a task_triage suggestion. Answer is required; Verb/Basis are optional (recorded, never validated by the daemon — see answeredPayload's own doc comment).
type AnswerTaskRequest ¶
type AnswerTaskRequest = apiwire.AnswerTaskRequest
type ApplyActionRequest ¶
type ApplyActionRequest = apiwire.ApplyActionRequest
from internal/api/action.go
type BlockingAskRegistry ¶ added in v0.0.6
type BlockingAskRegistry struct {
// contains filtered or unexported fields
}
BlockingAskRegistry coordinates harness-independent blocking Q&A. When an agent calls `boid task ask`, the broker holds the RPC connection open and the server-side handler blocks in Wait until the user/supervisor answers (via TaskHandler.Answer → AnswerTask → Notify) or the context is cancelled (daemon shutdown / agent disconnect).
The registry is purely in-memory: a daemon restart drops every pending ask. That is consistent — the sandbox process backing the blocked RPC dies with the daemon too, so there is nothing to resume.
func NewBlockingAskRegistry ¶ added in v0.0.6
func NewBlockingAskRegistry() *BlockingAskRegistry
NewBlockingAskRegistry returns an initialised registry.
func (*BlockingAskRegistry) Cancel ¶ added in v0.0.6
func (r *BlockingAskRegistry) Cancel(qid string)
Cancel removes the registration for qid (and the task it belongs to). It does not unblock Wait by itself — a blocked Wait observes ctx cancellation — but it frees the B1 slot so the task can ask again. Idempotent and safe to defer.
func (*BlockingAskRegistry) Has ¶ added in v0.0.6
func (r *BlockingAskRegistry) Has(qid string) bool
Has reports whether qid currently has a registration. Intended for tests and diagnostics.
func (*BlockingAskRegistry) Notify ¶ added in v0.0.6
func (r *BlockingAskRegistry) Notify(qid, answer string) bool
Notify delivers answer to the waiter registered for qid. It returns true when a registration exists and the answer was accepted, false when no waiter is registered (e.g. the agent already disconnected and Cancel ran) or an answer was already delivered. The send is non-blocking thanks to the buffered channel, so Notify never blocks even if Wait has not yet been scheduled.
func (*BlockingAskRegistry) Register ¶ added in v0.0.6
func (r *BlockingAskRegistry) Register(taskID, qid string) error
Register reserves the answer channel for (taskID, qid). It MUST be called before the task transitions to awaiting so an answer that arrives immediately afterwards is never dropped. The check-and-insert is atomic under the registry lock, so two concurrent asks for the same task can never both succeed.
A second pending ask for the same task fails with ErrAskPending ONLY when it carries a DIFFERENT question id. Re-registering the SAME qid is a re-attach — an agent whose `boid task ask` was killed by a harness command-timeout retrying the identical question — and is allowed. The re-attach installs a fresh channel; any prior waiter is already tearing down on its cancelled context. (Even if its deferred Cancel later clobbers this channel, the durable PendingAnswer path backstops delivery, so at worst the fast path degrades to one extra ask round-trip.)
func (*BlockingAskRegistry) Wait ¶ added in v0.0.6
Wait blocks until an answer is delivered for qid via Notify or ctx is cancelled. qid must have been registered; an unknown qid is a programming error and returns immediately. The caller is responsible for Cancel(qid) cleanup (typically via defer) on every exit path.
type BrokerHandler ¶
type BrokerHandler struct {
Registry BrokerRegistry
}
func (*BrokerHandler) Register ¶
func (h *BrokerHandler) Register(w http.ResponseWriter, r *http.Request)
func (*BrokerHandler) Routes ¶
func (h *BrokerHandler) Routes() chi.Router
type BrokerRegisterRequest ¶
type BrokerRegisterRequest struct {
Commands map[string]orchestrator.HostCommandSpec `json:"commands"`
BuiltinPolicies map[string]sandbox.BuiltinPolicy `json:"builtin_policies,omitempty"`
ProjectID string `json:"project_id,omitempty"`
}
type BrokerRegisterResponse ¶
type BrokerRegisterResponse struct {
Token string `json:"token"`
Socket string `json:"socket"`
// ResolvedHostCommands is no longer read by any client; kept as
// omitempty for one release so a stale caller decoding this response
// doesn't break on a missing key.
ResolvedHostCommands map[string]orchestrator.CommandDef `json:"resolved_host_commands,omitempty"`
}
type BrokerRegistry ¶
type BrokerRegistry interface {
RegisterBrokerCommands(commands map[string]orchestrator.HostCommandSpec, builtinPolicies map[string]sandbox.BuiltinPolicy, projectID string) (*BrokerRegisterResponse, error)
}
type CardActivityStore ¶ added in v0.5.0
type CardActivityStore interface {
// CardExecutionStatesByIDs resolves slot occupancy and input requests
// across all descendants in one batched read for the card list.
CardExecutionStatesByIDs(cardIDs []string) (map[string]orchestrator.CardExecutionState, error)
// ActiveCardRequestsByCardIDs returns, for each id in cardIDs with a
// currently queued/launching/attached row, the single highest-priority
// one (orchestrator.PickActiveCardRequest chooses attached > launching >
// queued) — a cardID with none is simply absent from the result.
ActiveCardRequestsByCardIDs(cardIDs []string) (map[string]*orchestrator.CardRequest, error)
// TaskStatusesByIDs batch-resolves task ids (a card's sole dispatched
// work child's TaskRef) to their live status — an id with no live row
// is simply absent from the result.
TaskStatusesByIDs(taskIDs []string) (map[string]orchestrator.TaskStatus, error)
}
CardActivityStore backs list execution state and detail activity. Reads are batched (chunked only past a SQL variable ceiling).
type CardCommandLauncherStore ¶ added in v0.5.0
type CardCommandLauncherStore interface {
CountActiveCardRequests(cardID string) (int, error)
ListCardRequestsByCard(cardID string) ([]*orchestrator.CardRequest, error)
CreateCardRequest(req *orchestrator.CardRequest) error
FailCardRequest(id, errText string) error
// ClaimQueuedCardRequestsForDispatch / PeekOldestQueuedCardRequest /
// ListCardIDsWithQueuedCardRequests back the automatic card-request
// dispatcher (card_request_auto_dispatch.go) — the queued->launching
// claim path for internal-event-originated requests, distinct from a
// human command's/Go's direct CreateCardRequest(status=launching).
ClaimQueuedCardRequestsForDispatch(cardID, launcherJobID, expectedCommandKey string, def orchestrator.CardRequestDefinition) (*orchestrator.CardRequest, []*orchestrator.CardRequest, error)
PeekOldestQueuedCardRequest(cardID string) (id, commandKey string, err error)
ListCardIDsWithQueuedCardRequests() ([]string, error)
// ClearCardForceReleaseBarrier ends automatic-dispatch suppression for a
// card once a human operation (here: a card command) touches it again.
ClearCardForceReleaseBarrier(cardID string) error
}
CardCommandLauncherStore is the card_requests persistence surface a manual card command launch needs. Satisfied by *orchestrator.TaskRepository.
type CardCommandOption ¶ added in v0.5.0
CardCommandOption is one workspace configuration card_commands entry resolved to its declared label, for the Web UI's command button row. Key is the wire command_key a button posts back; Label is exactly what the workspace wrote — the daemon never invents a gloss for it.
type CardCommandRunService ¶ added in v0.5.0
type CardCommandRunService interface {
RunCardCommandAsHuman(ctx context.Context, cardID, commandKey, instruction string) (*RunCardCommandResult, error)
}
CardCommandRunService is the manual card-command launch surface CardHandler needs — narrowed from *TaskWorkflowService.
type CardCommandWebService ¶ added in v0.5.0
type CardCommandWebService interface {
CardCommandRunService
CardCommandOptionsForProject(ctx context.Context, projectID string) []CardCommandOption
}
CardCommandWebService is the card-command surface the Web UI needs: launching one as a human (CardCommandRunService) plus listing a project's declared commands in order for the input+buttons section. Narrowed from *TaskWorkflowService the same way CardCommandRunService already is for CardHandler.
type CardHandler ¶ added in v0.4.0
type CardHandler struct {
Service CardReadService
// Commands is optional; nil disables the run-command route with a 501.
Commands CardCommandRunService
}
CardHandler serves the card read surface.
Mounted at its own /api/cards root rather than as /api/tasks/{id}/cards + a sibling list route: the listing needs a collection endpoint of its own, and hanging it off /api/tasks would put a static segment in the same position as the {id} wildcard.
func (*CardHandler) Get ¶ added in v0.4.0
func (h *CardHandler) Get(w http.ResponseWriter, r *http.Request)
Get returns one triage task's full projection (stored columns + the actions-derived parked_from + the opaque detail blob).
func (*CardHandler) List ¶ added in v0.4.0
func (h *CardHandler) List(w http.ResponseWriter, r *http.Request)
List returns the projections of the triage tasks matching the query filters. project_id and status are passed straight through to the same orchestrator.TaskFilter the task listing uses, so "cards_live" ("triage" is still accepted as a compatibility alias) and any concrete status value all work here too. "queue_next" is ALSO still a valid string to pass, but it has no special membership predicate anymore — it falls through to a literal `t.status = 'queue_next'` match, which can never match a real row, so it deterministically returns an empty list rather than an error (store.go's own doc comment).
func (*CardHandler) Routes ¶ added in v0.4.0
func (h *CardHandler) Routes() chi.Router
func (*CardHandler) RunCommand ¶ added in v0.5.0
func (h *CardHandler) RunCommand(w http.ResponseWriter, r *http.Request)
RunCommand handles POST /api/cards/{id}/commands/{key}: fires a workspace configuration-declared card_commands entry as a human command launcher. A missing/malformed body is treated as an empty instruction, not a 400 — an empty instruction is allowed.
type CardReadService ¶ added in v0.4.0
type CardReadService interface {
GetCard(taskID string) (*CardView, error)
ListCards(filter orchestrator.TaskFilter) ([]*CardView, error)
}
CardReadService is the read surface CardHandler needs — narrowed from *TaskWorkflowService so the handler can be tested against a fake.
type CardRequestDispatchLoop ¶ added in v0.5.0
type CardRequestDispatchLoop struct {
Store CardRequestDispatchStore
Interval time.Duration
InitialDelay time.Duration
}
CardRequestDispatchLoop mirrors TriggerLoop's shape: InitialDelay then Interval, Run(ctx) blocks until ctx is done, a sweep error is logged and never stops the loop.
func (*CardRequestDispatchLoop) Run ¶ added in v0.5.0
func (l *CardRequestDispatchLoop) Run(ctx context.Context)
Run blocks until ctx is done. It waits InitialDelay before the first sweep, then calls Store.SweepQueuedCardRequests every Interval.
type CardRequestDispatchStore ¶ added in v0.5.0
type CardRequestDispatchStore interface {
SweepQueuedCardRequests(ctx context.Context, now time.Time) ([]string, error)
}
CardRequestDispatchStore is CardRequestDispatchLoop's dependency, narrowed from *TaskWorkflowService — same idiom as TriggerLoopStore.
type CardRequestHandler ¶ added in v0.5.0
type CardRequestHandler struct {
Store CardRequestReleaseStore
}
func (*CardRequestHandler) List ¶ added in v0.5.0
func (h *CardRequestHandler) List(w http.ResponseWriter, r *http.Request)
List handles GET /api/card-requests?card_id=<id>, oldest first (matches ListCardRequestsByCard's own order). Omitting card_id switches to bulk mode: every currently launching/attached row across EVERY card, in one query — `boid task diagnose-cards` uses this instead of issuing one GET per card.
func (*CardRequestHandler) Release ¶ added in v0.5.0
func (h *CardRequestHandler) Release(w http.ResponseWriter, r *http.Request)
Release handles POST /api/card-requests/{id}/release. Its response shape is ReleaseResult (apiwire_aliases.go) — a daemon↔client wire type, so `boid task release-card-request` decodes straight into the SAME type via apiwire instead of keeping its own hand-duplicated copy. Body is optional; an empty/missing reason falls back to ForceReleaseCardRequest's own default message.
func (*CardRequestHandler) Routes ¶ added in v0.5.0
func (h *CardRequestHandler) Routes() chi.Router
type CardRequestReleaseStore ¶ added in v0.5.0
type CardRequestReleaseStore interface {
ForceReleaseCardRequest(id, reason string) ([]orchestrator.ForceReleasedSibling, error)
ListCardRequestsByCard(cardID string) ([]*orchestrator.CardRequest, error)
// ListActiveCardRequests backs List's bulk mode (no card_id query
// param): every launching/attached row across every card in one query,
// so a caller checking many cards (`boid task diagnose-cards`) avoids
// one GET per card.
ListActiveCardRequests() ([]*orchestrator.CardRequest, error)
// GetCardRequest backs Release's pre-release read (see Release's own
// doc comment for why it needs the row's target BEFORE releasing it).
GetCardRequest(id string) (*orchestrator.CardRequest, error)
}
CardRequestReleaseStore is the persistence surface CardRequestHandler needs.
type CardRequestTaskLinker ¶ added in v0.5.0
type CardRequestTaskLinker interface {
CreateTaskLinkedToCardRequest(t *orchestrator.Task, requestID, ownerJobID string) error
}
CardRequestTaskLinker is the single-method surface createExecutionTask needs to attach a fresh task to its originating card_requests row inside the SAME transaction as the task's own INSERT. Satisfied by *orchestrator.TaskRepository. ownerJobID is the caller-claimed launcher job id (CreateTaskRequest.CardRequestOwnerJobID), re-asserted in the attach's own write instead of trusted from an earlier read — see orchestrator.AttachCardRequestOwned's doc comment.
type CardStore ¶ added in v0.4.0
type CardStore interface {
UpsertTaskTriage(tt *orchestrator.CardAttrs) error
GetTaskTriage(taskID string) (*orchestrator.CardAttrs, error)
// ListTaskTriageByTaskIDs batch-fetches sidecar rows for a set of task
// IDs in O(chunks) queries instead of O(N) GetTaskTriage calls — see
// orchestrator.ListTaskTriageByTaskIDs's doc comment for
// the chunking rationale and the "batch replaces per-row error
// tolerance" tradeoff. A taskID with no sidecar row is simply absent
// from the returned map, never an error.
ListTaskTriageByTaskIDs(taskIDs []string) (map[string]*orchestrator.CardAttrs, error)
DeleteTaskTriage(taskID string) error
// ParkedFrom derives which status (triaged/ready/working) a parked task
// was parked from, from the actions log (not a stored column).
ParkedFrom(taskID string) (orchestrator.TaskStatus, error)
}
CardStore provides access to a card's CardAttrs columns (kind/urgency/ wake_at/wake_task_id/suggestion_verb/detail). These columns live on the same tasks row (filtered to type='card'), with Task exposing them as a nested `card` JSON key — this interface's shape is kept stable so the many card-lifecycle call sites (workflow_card.go et al.) do not need to change, only what backs them.
A card is type='card' from the moment CreateTask makes it, so there is no separate act of "seeding" a row after the fact.
type CardTimelineStore ¶ added in v0.5.0
type CardTimelineStore interface {
BuildCardTimeline(cardID, cursor string, limit int) (*timeline.CardTimelinePage, error)
CardPinnedItems(cardID string) ([]timeline.CardItem, error)
}
CardTimelineStore backs the card detail page's timeline read model (internal/timeline.BuildCardTimeline / CardPinnedItems), which reads a card's full action log directly via db.DBTX rather than through ActionStore's narrower ListActionsByTask.
type CardView ¶ added in v0.4.0
type CardView struct {
TaskID string `json:"task_id"`
ProjectID string `json:"project_id"`
Title string `json:"title,omitempty"`
Status orchestrator.TaskStatus `json:"status"`
// Description is the task row's body — a caller rendering the card
// needs both Title and Description.
Description string `json:"description,omitempty"`
Kind string `json:"kind,omitempty"`
Urgency string `json:"urgency,omitempty"`
WakeAt *time.Time `json:"wake_at,omitempty"`
WakeTaskID string `json:"wake_task_id,omitempty"`
// SuggestionVerb mirrors Kind/Urgency: carried through verbatim so a
// caller reading this view need not re-parse Detail's blob to learn
// what store.go's own queue predicate already keys on.
SuggestionVerb string `json:"suggestion_verb,omitempty"`
// ParkedFrom is only populated for a parked task: it answers "which side
// will this wake back to (triaged, ready, or working)". Deliberately
// left empty for every other status rather than reporting the most
// recent historical park — a stale origin on a task that is no longer
// parked would be actively misleading to a caller deciding whether Go
// has already been given. A consumer branching on this field must
// handle "working" as a valid third value, not just triaged/ready.
ParkedFrom orchestrator.TaskStatus `json:"parked_from,omitempty"`
Detail json.RawMessage `json:"detail,omitempty"`
}
CardView is the read-side projection of a triage task: the daemon is the sole source of truth for a triage task's state, so a workspace-side reader must be able to read that state back completely — including the fields that are derived rather than stored, not just the raw sidecar columns.
The view unions three sources:
- the task row (status/project/title/description) — state itself lives here, not in the sidecar
- the task_triage columns (kind/urgency/wake_at/wake_task_id)
- ParkedFrom, DERIVED from the actions log and stored nowhere
Detail is passed through verbatim as an opaque blob. The daemon does not interpret its keys — channel-specific knowledge stays on the workspace side — so neither does this projection.
type ConfigApplyResult ¶ added in v0.1.0
type ConfigApplyResult = apiwire.ConfigApplyResult
from internal/api/config.go
type ConfigHandler ¶ added in v0.0.13
type ConfigHandler struct {
Service ConfigService
}
func (*ConfigHandler) Apply ¶ added in v0.1.0
func (h *ConfigHandler) Apply(w http.ResponseWriter, r *http.Request)
Apply handles POST /api/config[?force=true]: `boid config apply -f`/ `edit`'s whole-document replace, gated by If-Match unless ?force=true is passed — the same convention PUT /api/workspaces/{slug} already established (internal/api/workspace.go's Update). See ConfigService.ApplyConfigYAML's doc comment for the validate-persist- reload-and-revision-check contract.
func (*ConfigHandler) Get ¶ added in v0.1.0
func (h *ConfigHandler) Get(w http.ResponseWriter, r *http.Request)
Get handles GET /api/config: the daemon's current effective config.yaml, verbatim, as application/yaml, with an ETag response header mirroring the revision so a caller can round-trip it straight into a subsequent POST's If-Match. `boid config get`/`apply`/`edit` all fetch this first as their working copy (`set`/`unset` route through POST /api/config/mutate instead — see Mutate).
func (*ConfigHandler) KitsDir ¶ added in v0.0.13
func (h *ConfigHandler) KitsDir(w http.ResponseWriter, r *http.Request)
KitsDir handles GET /api/config/kits-dir: the daemon's effective KitsDir, so a CLI client-side helper (cmd/workspace.go's ensureWorkspaceExistsForAssign) can resolve a legacy workspace.yaml's `kits:` references against the *running daemon's* kits directory instead of independently re-deriving a default that silently disagrees with it whenever the daemon was started with a custom --kits-dir.
func (*ConfigHandler) Mutate ¶ added in v0.1.0
func (h *ConfigHandler) Mutate(w http.ResponseWriter, r *http.Request)
Mutate handles POST /api/config/mutate: `boid config set/unset`'s single dotted-path operation, performed server-side as one atomic read-modify-write. See ConfigService.MutateConfig's doc comment.
func (*ConfigHandler) Routes ¶ added in v0.0.13
func (h *ConfigHandler) Routes() chi.Router
type ConfigMutateOp ¶ added in v0.1.0
type ConfigMutateOp = apiwire.ConfigMutateOp
type ConfigMutateRequest ¶ added in v0.1.0
type ConfigMutateRequest = apiwire.ConfigMutateRequest
type ConfigMutateResult ¶ added in v0.1.0
type ConfigMutateResult = apiwire.ConfigMutateResult
type ConfigService ¶ added in v0.0.13
type ConfigService interface {
// KitsDir returns the daemon's effective base directory for installed
// kits (server.Config.KitsDir, resolved once at startup — see
// cmd/start.go's defaultKitsDir()/--kits-dir flag).
KitsDir() string
// ConfigYAML returns the daemon's current effective config.yaml
// document, alongside its current revision — the same bytes `boid
// config get` (no key) prints verbatim, and what every `boid config
// get/apply/edit` invocation fetches first as its "before" snapshot.
// revision is the same value GET /api/config's ETag response header
// carries; round-tripping it into a later POST's If-Match is the
// optimistic-concurrency guard.
ConfigYAML() (data []byte, revision string, err error)
// ApplyConfigYAML validates a full replacement config.yaml document
// (internal/config.ValidateYAML), and on success atomically persists
// it and hot-applies whichever changed keys the daemon can apply live,
// returning operator-facing warning lines for anything that could not
// be hot-applied (gateway.forges.* — restart required; sandbox.backend
// — retirement notice). A validation failure leaves the daemon's live
// config and on-disk config.yaml untouched.
//
// Unless force is true, ifMatch must be non-empty and equal the
// current revision — the same ETag/If-Match convention `boid workspace
// edit` already established (see UpdateWorkspace) — otherwise the call
// fails with a *StatusError (428 Precondition Required when ifMatch is
// empty, 412 Precondition Failed when it is stale) and neither
// validates nor persists data.
ApplyConfigYAML(data []byte, ifMatch string, force bool) (ConfigApplyResult, error)
// MutateConfig performs one or more dotted-path set/unset operations as
// a single atomic, server-side read-modify-write — `boid config
// set/unset` route here instead of a client-side GET → mutate → POST
// round trip, which left a window for two concurrent calls to silently
// lose one's change. Multiple operations (ConfigMutateRequest.Ops) are
// applied to the same document before it is validated once, so a
// structural, multi-leaf change (e.g. a brand-new gateway.forges.<id>
// entry) can be created in one call. See
// internal/server/config_edit.go's MutateConfig doc comment for the
// full rationale.
MutateConfig(req ConfigMutateRequest) (ConfigMutateResult, error)
}
ConfigService is the daemon-side dependency behind /api/config: a read-only KitsDir surface plus a full read+validate+persist+hot-reload surface for `boid config get/set/unset/apply/edit`, including a server-side mutate endpoint and ETag/If-Match concurrency on the full-document endpoints. Implemented directly by *server.Server — no adapter type is needed, mirroring HostCommandsService's own convention in this package.
type ConnectorRef ¶ added in v0.4.0
type ConnectorRef = apiwire.ConnectorRef
type CreateProjectFromGitURLRequest ¶ added in v0.1.0
type CreateProjectFromGitURLRequest struct {
Perm string `json:"perm,omitempty"`
URL string `json:"url"`
Workspace string `json:"workspace"`
Name string `json:"name,omitempty"`
}
CreateProjectFromGitURLRequest is POST /api/projects/git's body (`boid project add <git-url> --workspace=<name> [--name=<project-name>]`). Workspace is required; Name empty derives the project name from URL's last path component.
type CreateProjectRequest ¶
type CreateTaskRequest ¶
type CreateTaskRequest = apiwire.CreateTaskRequest
type DeviceAuthHandler ¶ added in v0.0.13
type DeviceAuthHandler struct {
Pairing loginPairing
Store deviceAuthStore
Limiter loginRateLimiter
Registry *auth.ConnectionRegistry
PublicURL string
}
DeviceAuthHandler serves the Bearer device-auth endpoints used by remote CLI clients:
- POST /api/auth/device — public, rate-limited. Redeems a pairing code (the same one `boid web pair` issues for the cookie flow) for a long-lived Bearer device token.
- DELETE /api/auth/devices/{id} — Bearer-authenticated, self-revoke only.
It is a separate surface from WebManagementHandler (mounted at /api/web/*, UNIX-socket-only, trusted local-admin surface with no ownership check) — this handler is reachable over TCP by a caller who starts out holding nothing but a valid pairing code, so PostDevice carries its own rate limiting and DeleteDevice enforces "only revoke yourself".
func (*DeviceAuthHandler) DeleteDevice ¶ added in v0.0.13
func (h *DeviceAuthHandler) DeleteDevice(w http.ResponseWriter, r *http.Request)
DeleteDevice revokes the caller's own device only, and only when the caller authenticated via Bearer token. The {id} path param must match the Bearer-authenticated device ID the auth middleware placed in the request context (auth.DeviceIDFromContext + auth.AuthMethodFromContext).
The auth-method check exists because a session-cookie caller has other, richer paths for managing their own devices (the WebManagementHandler /api/web/devices UNIX-socket surface used by `boid web revoke`) — this endpoint is explicitly the *Bearer* self-revoke path used by `boid logout`, and mixing the two auth models on the same route would muddle the responsibility split.
This is intentionally stricter than WebManagementHandler.DeleteDevice (UNIX-socket-only local admin, no ownership check) — this endpoint is reachable by any Bearer-holding remote caller, so it must not let one device revoke another's token.
func (*DeviceAuthHandler) PostDevice ¶ added in v0.0.13
func (h *DeviceAuthHandler) PostDevice(w http.ResponseWriter, r *http.Request)
PostDevice redeems a one-time pairing code (auth.PairingManager — the same manager instance the cookie-based /login and /auth flows share) for a long-lived Bearer device token. Unlike those flows, no session cookie is ever set here: the raw token is returned exactly once, in the response body, and only its SHA-256 hash (auth.HashToken) is ever persisted (Store.InsertDeviceToken).
func (*DeviceAuthHandler) Routes ¶ added in v0.0.13
func (h *DeviceAuthHandler) Routes() chi.Router
type DeviceGCStore ¶
type DispatchCoordinator ¶
type DispatchCoordinator interface {
DispatchAndAdvance(ctx context.Context, task *orchestrator.Task, meta *orchestrator.ProjectMeta, sm *orchestrator.StateMachine) (*orchestrator.DispatchResult, error)
ReplayHook(ctx context.Context, task *orchestrator.Task, meta *orchestrator.ProjectMeta, sm *orchestrator.StateMachine, hookID string) (*orchestrator.ReplayResult, error)
}
type DuplicateTaskRequest ¶
type DuplicateTaskRequest = apiwire.DuplicateTaskRequest
type ExecDispatcher ¶ added in v0.0.10
type ExecDispatcher interface {
StartExec(ctx context.Context, req StartExecRequest) (*StartExecResult, error)
}
ExecDispatcher launches a JobKindExec job (arbitrary argv, shell harness, no HarnessAdapter agent) through Runner.Dispatch() and returns the runtime job id. Implemented by internal/server's sessionDispatcherAdapter.
type FoldedSiblingSummary ¶ added in v0.5.0
type FoldedSiblingSummary = apiwire.FoldedSiblingSummary
type GCAppService ¶
type GCAppService struct {
Store GCStore
DeviceStore DeviceGCStore // optional; deletes revoked devices on GC
}
func (*GCAppService) GC ¶
func (s *GCAppService) GC(olderThan time.Duration, dryRun bool) (*orchestrator.GCResult, error)
GC implements orchestrator.GCStore so GCAppService can be passed to GCLoop.
func (*GCAppService) Run ¶
func (s *GCAppService) Run(olderThan time.Duration, dryRun bool) (*orchestrator.GCResult, error)
type GCHandler ¶
type GCHandler struct {
Service GCService
// Homes, when non-nil, is the engine-backed view of workspace HOME
// volumes used to list them and their sizes in the response (visibility
// only, no auto-prune). Left nil, the response omits workspace_homes
// entirely — no size listing, and no home is ever deleted by GC either
// way. See WorkspaceHomeStore's doc comment for why the engine handle,
// rather than a runtimes directory, is the gate.
Homes WorkspaceHomeStore
// Workspaces, when set, is consulted to flag orphaned homes (a workspace
// HOME volume with no corresponding workspace row) in the
// workspace_homes listing. Optional: a nil Workspaces just means every
// entry reports orphan=true (ListWorkspaceHomeSizes's degrade-gracefully
// path — see its doc comment).
Workspaces WorkspaceSlugLister
}
type GlobalJobStore ¶
type GlobalJobStore interface {
ListJobsWithContext(filter JobListFilter) ([]JobWithContext, error)
}
GlobalJobStore supports cross-task job listing with context (task title, project name).
type HookService ¶
type HookService interface {
ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
}
HookService provides hook replay and hook listing operations.
type HostCommandsHandler ¶ added in v0.0.13
type HostCommandsHandler struct {
Service HostCommandsService
}
func (*HostCommandsHandler) List ¶ added in v0.0.13
func (h *HostCommandsHandler) List(w http.ResponseWriter, r *http.Request)
List handles GET /api/host_commands: returns the sorted list of host_commands names known to the daemon, for Web UI / CLI (`boid host-commands list`) validation of a workspace's host_commands references.
func (*HostCommandsHandler) Reload ¶ added in v0.0.13
func (h *HostCommandsHandler) Reload(w http.ResponseWriter, r *http.Request)
Reload handles POST /api/host_commands/reload: re-reads the aggregated config from disk after a hand edit.
func (*HostCommandsHandler) Routes ¶ added in v0.0.13
func (h *HostCommandsHandler) Routes() chi.Router
type HostCommandsProvider ¶ added in v0.0.13
type HostCommandsProvider interface {
HostCommands() map[string]orchestrator.HostCommandSpec
}
HostCommandsProvider exposes the daemon's live aggregated host_commands snapshot (name -> spec) for reference-name validation on workspace create/update: an unresolvable meta.HostCommands reference must be rejected with 400 at write time rather than silently persisted and later warned-about + skipped at dispatch. Implemented by *server.Server, which already exposes this exact method for HostCommandsService above.
type HostCommandsService ¶ added in v0.0.13
type HostCommandsService interface {
// HostCommands returns a snapshot of the daemon's aggregated
// host_commands config (raw/unexpanded — see
// orchestrator.ExpandHostCommandsForDispatch's doc comment for why).
HostCommands() map[string]orchestrator.HostCommandSpec
// ReloadHostCommands re-reads ~/.config/boid/host_commands.yaml from
// disk and swaps it in, live, without a daemon restart.
ReloadHostCommands() error
}
HostCommandsService is the daemon-side dependency behind GET /api/host_commands and POST /api/host_commands/reload. Implemented directly by *server.Server.
type ImportError ¶
type ImportError = apiwire.ImportError
type ImportResult ¶
type ImportResult = apiwire.ImportResult
type JobCompletion ¶
type JobDoneRequest ¶
type JobHandler ¶
type JobHandler struct {
Jobs JobStore
Global GlobalJobStore // optional: enables cross-task listing when task_id is absent
Service WorkflowService
LogReader JobLogReader // optional: enables static GET /{id}/log
SSEHandler http.Handler // optional: enables SSE streaming for GET /{id}/log?follow=true
}
func (*JobHandler) AgentStop ¶
func (h *JobHandler) AgentStop(w http.ResponseWriter, r *http.Request)
AgentStop asks the daemon to deliver SIGUSR1 to the runtime pgrp. claude.Adapter.Run() catches the signal and forwards SIGTERM to the claude child while the surrounding runner-inner-child keeps running and posts `boid job done --output-file payload_patch.json` through the broker — that callback remains the canonical CompleteJob caller, preserving the agent's session id without racing against UnregisterJob. See WorkflowService.StopAgent for the lifecycle rationale.
func (*JobHandler) Done ¶
func (h *JobHandler) Done(w http.ResponseWriter, r *http.Request)
func (*JobHandler) Get ¶
func (h *JobHandler) Get(w http.ResponseWriter, r *http.Request)
func (*JobHandler) List ¶
func (h *JobHandler) List(w http.ResponseWriter, r *http.Request)
func (*JobHandler) Log ¶
func (h *JobHandler) Log(w http.ResponseWriter, r *http.Request)
func (*JobHandler) Patch ¶ added in v0.0.4
func (h *JobHandler) Patch(w http.ResponseWriter, r *http.Request)
func (*JobHandler) Routes ¶
func (h *JobHandler) Routes() chi.Router
type JobLifecycle ¶
type JobLifecycle interface {
CompleteJob(jobID string, result JobCompletion)
UnregisterJob(jobID string)
CleanupTaskWindow(taskID string)
StopJobRuntime(runtimeID string)
// SignalJobRuntime delivers a single Unix signal to the runtime's process
// group. Used to graceful-stop the agent (SIGUSR1) without
// tearing down the surrounding sandbox runtime: claude.Adapter.Run() has a
// signal.Notify(SIGUSR1) handler that translates the group signal into a
// SIGTERM toward the claude child, then normalises the resulting exit
// status into Result.StoppedByDaemon=true.
SignalJobRuntime(runtimeID string, sig syscall.Signal)
}
type JobListFilter ¶
type JobListFilter = apiwire.JobListFilter
type JobLogReader ¶
type JobLogReader interface {
ReadJobLog(runtimeID string) ([]byte, error)
StatJobLog(runtimeID string) (size int64, mtime time.Time, err error)
}
JobLogReader reads the transcript log for a given runtime.
type JobLogSSEHandler ¶
type JobLogSSEHandler struct {
Subscriber dispatcher.RuntimeSubscriber
Registry *auth.ConnectionRegistry
}
JobLogSSEHandler streams live job output as Server-Sent Events on GET /{id}/log?follow=true.
func (*JobLogSSEHandler) ServeHTTP ¶
func (h *JobLogSSEHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type JobWithContext ¶
type JobWithContext = apiwire.JobWithContext
type ListSignalsResponse ¶ added in v0.4.0
type ListSignalsResponse = apiwire.ListSignalsResponse
type LoginHandler ¶
type LoginHandler struct {
Pairing loginPairing
Signer loginSigner
Store loginDeviceStore
Limiter loginRateLimiter
}
LoginHandler handles /login and /auth.
func (*LoginHandler) GetAuth ¶
func (h *LoginHandler) GetAuth(w http.ResponseWriter, r *http.Request)
GetAuth renders the confirmation page for a magic link / QR scan. It is deliberately side-effect free — it does NOT redeem the token, since GET requests get issued by browser preloading, QR-scanner previews, and in-app-browser prefetching, any of which would burn a single-use code before the human's real navigation. Consuming a one-time credential is a state change, so it belongs behind the POST that PostAuth serves.
func (*LoginHandler) GetLogin ¶
func (h *LoginHandler) GetLogin(w http.ResponseWriter, r *http.Request)
func (*LoginHandler) PostAuth ¶ added in v0.1.0
func (h *LoginHandler) PostAuth(w http.ResponseWriter, r *http.Request)
PostAuth redeems the token carried by the confirmation page's form. This is the only path that spends a pairing code from the browser flow.
func (*LoginHandler) PostLogin ¶
func (h *LoginHandler) PostLogin(w http.ResponseWriter, r *http.Request)
type MetaStore ¶
type MetaStore interface {
Get(id string) (*orchestrator.ProjectMeta, bool)
// GetWithWorkspace returns the project meta with workspace.yaml (kits,
// env, capabilities) hydrated in. Use this whenever the caller dispatches
// hooks or otherwise needs the resolved runtime view.
GetWithWorkspace(ctx context.Context, projectID string) (*orchestrator.ProjectMeta, error)
}
type Notifier ¶
Notifier sends an agent-driven notification for a task. Implementations typically exec a user-configured command. nil-safe at the call site: TaskAppService.NotifyTask returns an error when Notify is unset.
type NotifyTaskRequest ¶
type NotifyTaskRequest = apiwire.NotifyTaskRequest
from internal/api/task.go
type OAuthLoginHandler ¶ added in v0.1.0
type OAuthLoginHandler struct {
Service OAuthLoginService
}
OAuthLoginHandler serves `boid secret oauth login <service>`'s three daemon endpoints under whatever prefix internal/server/wire.go mounts it at (POST .../login, GET .../login/{id}, POST .../login/{id}/complete).
func (*OAuthLoginHandler) Complete ¶ added in v0.1.0
func (h *OAuthLoginHandler) Complete(w http.ResponseWriter, r *http.Request)
Complete implements POST .../login/{id}/complete — the loopback flow's browser-callback code (forwarded by the CLI's local listener) or the manual flow's user-pasted OOB code. Every CompleteLogin failure (unknown/expired/already-completed session, state mismatch, upstream exchange failure, ...) is reported as 400 — see Start's own doc comment for why this handler does not attempt to distinguish these from LoginManager's plain error strings.
func (*OAuthLoginHandler) Routes ¶ added in v0.1.0
func (h *OAuthLoginHandler) Routes() chi.Router
func (*OAuthLoginHandler) Start ¶ added in v0.1.0
func (h *OAuthLoginHandler) Start(w http.ResponseWriter, r *http.Request)
Start implements POST .../login. Every failure here is reported as 400 (the request as given cannot be satisfied right now — an unrecognized flow config, a device_authorization_endpoint call failing, ...) except two structurally-derivable cases: h.Service == nil (503 — the daemon has no secret store/OAuth2 machinery configured at all, mirroring SecretHandler's own systemic-unavailability convention) and ProviderForService reporting ok=false (404 — service is genuinely unknown or not an oauth2-kind service, a structural fact this handler can check without parsing any error string).
func (*OAuthLoginHandler) Status ¶ added in v0.1.0
func (h *OAuthLoginHandler) Status(w http.ResponseWriter, r *http.Request)
Status implements GET .../login/{id} — the CLI's device-flow poll: the daemon polls the real provider in the background; the CLI only ever polls THIS cheap, local, daemon-session check. 404 when the session id is unknown — ok=false is a structural fact from LoginStatus, never a parsed error string.
type OAuthLoginService ¶ added in v0.1.0
type OAuthLoginService interface {
// ProviderForService resolves a config.yaml services.<name> entry to
// the oauth_providers.<name> its auth.kind: oauth2 config references.
// ok is false when service is unknown OR configured with any auth.kind
// other than oauth2 (mirrors apigateway.CredentialProvider.
// OAuth2ProviderFor exactly — the adapter just forwards to it).
ProviderForService(service string) (provider string, ok bool)
// KnowsProvider reports whether name is itself a configured
// oauth_providers.<name> entry. Start uses it as a fallback when the
// argument does not name a service — see its own doc comment for why
// naming the provider directly is legitimate rather than a typo to
// reject.
KnowsProvider(name string) bool
// StartLogin begins a new login session — see
// apigateway.LoginManager.StartLogin's own doc comment for the full
// per-flow contract (redirectURI is only meaningful for the loopback
// flow; the CLI always supplies it regardless of which flow the
// service turns out to use). account is the optional credential-account
// qualifier — "" means unqualified, byte-identical to every call site
// that predates this parameter.
StartLogin(namespace, provider, redirectURI, account string) (*OAuthLoginStart, error)
// CompleteLogin finishes a loopback or manual session — see
// apigateway.LoginManager.CompleteLogin's own doc comment (state is
// ignored for manual, which never had one to check).
CompleteLogin(sessionID, code, state string) error
// LoginStatus reports a session's current lifecycle state — ok is
// false when sessionID is unknown.
LoginStatus(sessionID string) (status, errMsg string, ok bool)
}
OAuthLoginService is the daemon-side surface `boid secret oauth login <service>` drives, implemented by internal/server/wire.go's adapter over apigateway.CredentialProvider (the service->provider lookup) and apigateway.LoginManager (the actual device/loopback/manual flow machinery) — kept as a narrow interface (mirroring api.SecretStore/api.WorkspaceHomeStore's existing convention) so this handler's own tests can substitute a fake without a real OAuth2 token endpoint or secret store.
Every method's return shape is deliberately untyped-error-only (a plain string, no distinguishable error codes) except where a boolean "ok" is structurally derivable without string sniffing (ProviderForService, LoginStatus) — see each handler method's own comment for how that maps to HTTP status codes.
type OAuthLoginStart ¶ added in v0.1.0
type OAuthLoginStart struct {
SessionID string
Flow string
// Account mirrors apigateway.LoginStart.Account — see that field's own
// doc comment for why it exists (version-skew detection).
Account string
AuthorizeURL string
UserCode string
VerificationURI string
VerificationURIComplete string
IntervalSeconds int
ExpiresInSeconds int
}
OAuthLoginStart is the internal/api-owned mirror of apigateway.LoginStart — internal/api deliberately does not import internal/apigateway's own type here (this package's DTOs are the wire contract; the adapter in internal/server/wire.go is what actually touches apigateway types), keeping this handler's own tests free of any apigateway/oauth2-endpoint dependency, the same "handler depends on a narrow service interface with its own DTOs, not a concrete backend package's types" convention api.SecretHandler/api.WorkspaceHandler follow.
type OperationResultStore ¶ added in v0.5.0
type OperationResultStore interface {
CreateOperationResult(result *orchestrator.OperationResult) error
UpdateOperationResult(result *orchestrator.OperationResult) error
ListOperationResults(taskID string, limit int) ([]*orchestrator.OperationResult, error)
GetOperationResult(taskID, id string) (*orchestrator.OperationResult, error)
}
type Pairer ¶
WebManagementHandler serves the CLI management API at /api/web/*. All routes are accessible only via UNIX socket (CLI control plane). Pairer issues pairing codes.
type ProjectAppService ¶
type ProjectAppService struct {
Projects ProjectRepository
Meta interface {
Get(id string) (*orchestrator.ProjectMeta, bool)
Remove(id string)
LoadAll(projects []*orchestrator.Project) []error
SetWorkspaceID(projectID, workspaceID string)
Status(id string) orchestrator.ProjectStatus
MarkDegraded(id, message string)
SetSynthesizedMeta(id string, meta *orchestrator.ProjectMeta)
// Explain returns id's field-provenance view — see
// orchestrator.ProjectStore.Explain's own doc comment.
Explain(id string) (*orchestrator.ProjectExplain, error)
}
Hydrator orchestrator.MetaHydrator
Workspaces WorkspaceStore
HostCommands func() map[string]orchestrator.HostCommandSpec
WorkspacesConn *sql.DB
InitScripts WorkspaceInitScriptStore
// contains filtered or unexported fields
}
func (*ProjectAppService) ApplyWorkspace ¶ added in v0.1.0
func (s *ProjectAppService) ApplyWorkspace(apply *orchestrator.WorkspaceEnvelopeApply, dryRun bool) (*orchestrator.WorkspaceApplyResult, error)
func (*ProjectAppService) CreateProject ¶
func (s *ProjectAppService) CreateProject(workDir string, requestedPerm string) (*orchestrator.Project, error)
func (*ProjectAppService) CreateProjectFromGitURL ¶ added in v0.1.0
func (s *ProjectAppService) CreateProjectFromGitURL(ctx context.Context, gitURL, workspaceSlug, nameOverride string, requestedPerm string) (*orchestrator.Project, error)
func (*ProjectAppService) CreateWorkspace ¶ added in v0.0.13
func (s *ProjectAppService) CreateWorkspace(slug string, meta *orchestrator.WorkspaceMeta) (*WorkspaceDetail, error)
func (*ProjectAppService) DeleteProject ¶
func (s *ProjectAppService) DeleteProject(id string) error
func (*ProjectAppService) ExplainProject ¶ added in v0.1.0
func (s *ProjectAppService) ExplainProject(id string) (*orchestrator.ProjectExplain, error)
func (*ProjectAppService) ExportWorkspaceEnvelopes ¶ added in v0.1.0
func (s *ProjectAppService) ExportWorkspaceEnvelopes(slugs []string) ([]byte, error)
func (*ProjectAppService) GetProject ¶
func (s *ProjectAppService) GetProject(id string) (*orchestrator.Project, error)
func (*ProjectAppService) GetWorkspace ¶ added in v0.0.13
func (s *ProjectAppService) GetWorkspace(slug string) (*WorkspaceDetail, error)
func (*ProjectAppService) GetWorkspaceInitScript ¶ added in v0.1.0
func (s *ProjectAppService) GetWorkspaceInitScript(slug string) (*WorkspaceInitScript, error)
GetWorkspaceInitScript implements ProjectService.GetWorkspaceInitScript.
The workspace row is checked FIRST, so a typo'd slug is a 404 rather than "this workspace has no init.sh" — the two are indistinguishable to a reader of the second message and only one of them is worth acting on.
func (*ProjectAppService) GetWorkspaceRuntimeMeta ¶ added in v0.6.0
func (s *ProjectAppService) GetWorkspaceRuntimeMeta(ctx context.Context, workspaceID string) (*orchestrator.ProjectMeta, error)
GetWorkspaceRuntimeMeta resolves repository-free exec configuration.
func (*ProjectAppService) ListProjects ¶
func (s *ProjectAppService) ListProjects(workspaceID string) ([]*orchestrator.Project, error)
func (*ProjectAppService) ListWorkspaces ¶
func (s *ProjectAppService) ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
func (*ProjectAppService) RemoveWorkspace ¶ added in v0.0.13
func (s *ProjectAppService) RemoveWorkspace(slug string) (*WorkspaceRemoval, error)
func (*ProjectAppService) ResolveProjectRef ¶
func (s *ProjectAppService) ResolveProjectRef(ref string) ([]*orchestrator.Project, error)
func (*ProjectAppService) SetProjectPerm ¶ added in v0.6.0
func (s *ProjectAppService) SetProjectPerm(id, perm string) (*orchestrator.Project, error)
SetProjectPerm changes a repository's permission for subsequent task creation and dispatch.
func (*ProjectAppService) SetProjectWorkspace ¶
func (s *ProjectAppService) SetProjectWorkspace(id, workspaceID string) (*orchestrator.Project, error)
func (*ProjectAppService) SetWorkspaceInitScript ¶ added in v0.1.0
func (s *ProjectAppService) SetWorkspaceInitScript(slug string, content []byte, ifMatch string, force bool) (*WorkspaceInitScriptResult, error)
SetWorkspaceInitScript implements ProjectService.SetWorkspaceInitScript.
The If-Match check and the write run under s.mu, the same mutex every other workspace-mutating entry point takes — closing the read-then-write window against another caller of this daemon (not against a hand-edit of the file inside the container, which is exactly the workflow this endpoint exists to replace).
It does not exclude a concurrent dispatch, deliberately: resolveWorkspaceHome re-reads and re-hashes the script under its own flock before running it, so a write landing mid-init is either picked up in full or missed entirely — never half-applied.
func (*ProjectAppService) UpdateWorkspace ¶ added in v0.0.13
func (s *ProjectAppService) UpdateWorkspace(slug string, meta *orchestrator.WorkspaceMeta, ifMatch string, force bool) (*WorkspaceDetail, error)
func (*ProjectAppService) WithProjectLock ¶ added in v0.1.0
func (s *ProjectAppService) WithProjectLock(fn func() error) error
WithProjectLock serializes project registry reads with lifecycle mutations.
type ProjectHandler ¶
type ProjectHandler struct {
Service ProjectService
SessionDispatcher SessionDispatcher // optional; nil disables the start-session endpoint
ExecDispatcher ExecDispatcher // optional; nil disables the exec endpoint
// TriggerRunner backs POST /api/projects/{id}/triggers/{name}/run
// (`boid trigger run`). Optional; nil disables the endpoint, same
// convention as SessionDispatcher/ExecDispatcher above.
TriggerRunner TriggerRunner
}
func (*ProjectHandler) Create ¶
func (h *ProjectHandler) Create(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) CreateFromGitURL ¶ added in v0.1.0
func (h *ProjectHandler) CreateFromGitURL(w http.ResponseWriter, r *http.Request)
CreateFromGitURL handles POST /api/projects/git (`boid project add <git-url> --workspace=<name>`).
func (*ProjectHandler) Delete ¶
func (h *ProjectHandler) Delete(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) Explain ¶ added in v0.1.0
func (h *ProjectHandler) Explain(w http.ResponseWriter, r *http.Request)
Explain handles GET /api/projects/{id}/explain (`boid project show --explain`).
func (*ProjectHandler) Get ¶
func (h *ProjectHandler) Get(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) List ¶
func (h *ProjectHandler) List(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) Routes ¶
func (h *ProjectHandler) Routes() chi.Router
func (*ProjectHandler) RunTrigger ¶ added in v0.4.0
func (h *ProjectHandler) RunTrigger(w http.ResponseWriter, r *http.Request)
RunTrigger handles POST /api/projects/{id}/triggers/{name}/run. The project is resolved from the URL ref the same way every other project route does; {name} is the trigger's workspace configuration `name:`.
{name} can contain a "/" — a signal-derived trigger is named "signal:<pack>/<connector>" (signal_trigger_derive.go) — so cmd/trigger.go url.PathEscape's it before sending. chi matches routes against the request's ESCAPED path (the same contract SecretHandler's key param already documents/handles, secret.go), so chi.URLParam hands this handler the still-escaped "signal:jira-cloud%2Fassigned-issues" form, not the literal trigger name — url.PathUnescape here mirrors SecretHandler's own.
func (*ProjectHandler) SetPerm ¶ added in v0.6.0
func (h *ProjectHandler) SetPerm(w http.ResponseWriter, r *http.Request)
SetPerm updates the permission of a resolved project reference.
func (*ProjectHandler) SetWorkspace ¶
func (h *ProjectHandler) SetWorkspace(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) StartExec ¶ added in v0.0.10
func (h *ProjectHandler) StartExec(w http.ResponseWriter, r *http.Request)
StartExec handles POST /api/projects/{id}/exec. The project is resolved from the URL ref the same way every other project route does; the body specifies argv and the optional readonly / interactive / display_name knobs. Unlike StartSession there is no top-level /api/exec — every exec is project-scoped by construction (`boid exec -p <ref> -- argv...`).
func (*ProjectHandler) StartSession ¶ added in v0.0.6
func (h *ProjectHandler) StartSession(w http.ResponseWriter, r *http.Request)
StartSession handles POST /api/projects/{id}/sessions. The project is resolved from the URL ref (so refs like a name or short id work the same way other project routes do); the body specifies harness_type and the optional knobs (instruction / readonly / model / session_id / display_name).
type ProjectRepository ¶
type ProjectRepository interface {
CreateProject(project *orchestrator.Project) error
GetProject(id string) (*orchestrator.Project, error)
ListProjects() ([]*orchestrator.Project, error)
SetProjectWorkspace(projectID, workspaceID string) error
SetProjectPerm(id, perm string) error
ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
DeleteProject(id string) error
// WorkspaceExists reports whether workspaceID refers to an existing
// workspaces table row. Used by ProjectAppService.SetProjectWorkspace to
// reject assignment to a nonexistent slug.
WorkspaceExists(workspaceID string) (bool, error)
// AssignWorkspaceIfExists atomically checks-then-assigns in a single DB
// transaction, replacing the WorkspaceExists+SetProjectWorkspace two-step
// ProjectAppService.SetProjectWorkspace used before: a DELETE landing
// between those two separate calls could leave a dangling
// project_workspaces reference. Returns an error wrapping os.ErrNotExist
// when workspaceID has no corresponding row (DefaultWorkspaceSlug and ""
// are exempt from the check — see the implementation's doc comment).
AssignWorkspaceIfExists(projectID, workspaceID string) error
// GetWorkspaceSummary returns a single workspace's project count and
// revision, or an error wrapping os.ErrNotExist. Used by the workspace
// CRUD handlers to build responses and to read the current revision for
// the PUT If-Match check.
GetWorkspaceSummary(slug string) (*orchestrator.WorkspaceSummary, error)
}
type ProjectService ¶
type ProjectService interface {
CreateProject(workDir string, perm string) (*orchestrator.Project, error)
// CreateProjectFromGitURL registers a remote URL without accessing the repository.
CreateProjectFromGitURL(ctx context.Context, gitURL, workspaceSlug, nameOverride string, perm string) (*orchestrator.Project, error)
ListProjects(workspaceID string) ([]*orchestrator.Project, error)
ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
GetProject(id string) (*orchestrator.Project, error)
SetProjectWorkspace(id, workspaceID string) (*orchestrator.Project, error)
SetProjectPerm(id, perm string) (*orchestrator.Project, error)
DeleteProject(id string) error
// ResolveProjectRef resolves a ref string to one or more matching projects.
// Priority: id exact match > name exact match > name substring match (case-insensitive).
// Returns 1 project on unambiguous match, multiple on ambiguous match, StatusError{404} on no match.
ResolveProjectRef(ref string) ([]*orchestrator.Project, error)
// ExplainProject returns id's field-provenance view (GET
// /api/projects/{id}/explain — `boid project show --explain`): for each of the 4
// workspace-default-mergeable fields, whether the effective value came
// from the linked workspace or built-in defaults. *StatusError{404} for an unknown id.
ExplainProject(id string) (*orchestrator.ProjectExplain, error)
// CreateWorkspace inserts a brand-new workspace (POST /api/workspaces).
// Returns a *StatusError{409} when slug already has a row, {400} for an
// invalid slug.
CreateWorkspace(slug string, meta *orchestrator.WorkspaceMeta) (*WorkspaceDetail, error)
// GetWorkspace returns slug's meta, revision, and assigned project ids
// (GET /api/workspaces/{slug}). *StatusError{404} when slug is unknown.
GetWorkspace(slug string) (*WorkspaceDetail, error)
// UpdateWorkspace replaces slug's meta wholesale (PUT
// /api/workspaces/{slug}), enforcing optimistic concurrency via ifMatch
// against the workspace's current revision unless force is true.
// *StatusError{428} missing ifMatch, {412} stale ifMatch, {404} unknown
// slug.
UpdateWorkspace(slug string, meta *orchestrator.WorkspaceMeta, ifMatch string, force bool) (*WorkspaceDetail, error)
// RemoveWorkspace deletes slug's row AND its init.sh (DELETE
// /api/workspaces/{slug}), reporting what became of the latter.
// *StatusError{400} for the reserved default slug, {404} unknown slug.
//
// The two deletions are one operation because they have to be excluded
// from a concurrent apply together — see ProjectAppService.RemoveWorkspace.
// They are still not atomic with each
// other, hence the result: an error inside it means the row is gone and
// the script is not.
RemoveWorkspace(slug string) (*WorkspaceRemoval, error)
// ApplyWorkspace upserts one boid.dev/v1 Workspace envelope document's
// metadata and (when apply.FieldsPresent["projects"] is true) project
// assignments atomically, in a single DB transaction (POST
// /api/workspaces/apply). dryRun exercises the same validation/DB
// statements but rolls back instead of committing.
ApplyWorkspace(apply *orchestrator.WorkspaceEnvelopeApply, dryRun bool) (*orchestrator.WorkspaceApplyResult, error)
// ExportWorkspaceEnvelopes returns one or more boid.dev/v1 Workspace
// yaml documents ("---"-separated when more than one), built from a
// single atomic DB snapshot (GET /api/workspaces/export?all=true or
// ?name=<slug>). slugs nil/empty exports every workspace; otherwise
// exactly the given slugs. *StatusError{404} when a requested slug does
// not exist. Each document carries the workspace's init.sh in
// spec.init_script — an export without it is not a restorable backup.
ExportWorkspaceEnvelopes(slugs []string) ([]byte, error)
// GetWorkspaceInitScript returns slug's init.sh (GET
// /api/workspaces/{slug}/init-script). A workspace
// with no script is NOT an error: the result carries Exists=false and
// Revision=WorkspaceInitScriptAbsentRevision, and the handler turns that
// into a 404 with the sentinel ETag. *StatusError{400} for an invalid
// slug, {404} for an unknown workspace, {501} when the daemon has no init
// script store wired.
GetWorkspaceInitScript(slug string) (*WorkspaceInitScript, error)
// SetWorkspaceInitScript replaces slug's init.sh with content (PUT
// /api/workspaces/{slug}/init-script), enforcing optimistic concurrency
// via ifMatch against the current revision unless force is true — the
// same 428/412 contract UpdateWorkspace and ApplyConfigYAML use. An
// EMPTY content clears the script (see
// workspaceInitScriptContentIsAbsent). *StatusError{400} for an invalid
// slug or a script containing a NUL byte, {404} unknown workspace,
// {428} missing ifMatch, {412} stale ifMatch, {501} no store wired.
SetWorkspaceInitScript(slug string, content []byte, ifMatch string, force bool) (*WorkspaceInitScriptResult, error)
}
type ProjectWorkDirLookup ¶
type ProjectWorkDirLookup interface {
GetProject(id string) (*orchestrator.Project, error)
}
ProjectWorkDirLookup provides read access to a project's working directory.
type QueueSweepLoop ¶ added in v0.2.4
type QueueSweepLoop struct {
Store QueueSweepStore
Interval time.Duration
InitialDelay time.Duration
}
QueueSweepLoop periodically calls SweepWake, mirroring orchestrator.GCLoop's shape (internal/orchestrator/gc_loop.go) — same InitialDelay-then-Interval idiom, errors logged and never fatal to the loop.
func (*QueueSweepLoop) Run ¶ added in v0.2.4
func (l *QueueSweepLoop) Run(ctx context.Context)
Run blocks until ctx is done. It waits InitialDelay before the first sweep, then calls Store.SweepWake every Interval.
type QueueSweepStore ¶ added in v0.2.4
type QueueSweepStore interface {
SweepWake(ctx context.Context, now time.Time) ([]string, error)
SweepReconcileChildren(ctx context.Context, now time.Time) error
}
QueueSweepStore is the interface QueueSweepLoop needs — narrowed from *TaskWorkflowService so the loop can be unit tested against a fake.
SweepTriage and SweepReopen are gone as of card machine v2: both were machine-driven transitions (auto-done, auto-reopen) the redesign retires entirely. done/reopen are now suggested by khi and applied only by a human's accept, through the ordinary ApplyAction/accept(verb) path — there is nothing left for a periodic sweep to decide on their behalf. SweepReconcileChildren (above) is not one of those transitions — it survives because it never touches task.Status.
type ReleaseResult ¶ added in v0.5.0
type ReleaseResult = apiwire.ReleaseResult
from internal/api/card_request_release_handler.go
type ReopenTaskRequest ¶
type ReopenTaskRequest struct {
Message string `json:"message,omitempty"`
}
type ReplayHookRequest ¶
type ReplayHookRequest struct {
HookID string
Status string // optional: override task.Status before replay
}
ReplayHookRequest is the input for hook replay.
type RerunTaskRequest ¶
type RerunTaskRequest = apiwire.RerunTaskRequest
type ResolveOrCaptureRequest ¶ added in v0.4.0
type ResolveOrCaptureRequest = apiwire.ResolveOrCaptureRequest
type ResolveOrCaptureResult ¶ added in v0.4.0
type ResolveOrCaptureResult = apiwire.ResolveOrCaptureResult
type RunCardCommandResult ¶ added in v0.5.0
type RunCardCommandResult struct {
// Occupied is true when the card's execution slot was already taken —
// no new request was created; TargetKind/TargetID point at the current
// occupant instead, when a real followable one is known (see
// cardWorkChildOccupantTx's own doc comment for when it isn't).
Occupied bool `json:"occupied"`
// RequestID is the card_requests row this call created (Occupied=false)
// or the currently-occupying row, when the occupant IS a card_requests
// row (Occupied=true via ErrCardRequestSlotOccupied). Empty when the
// occupant is instead a live/JSON work child with no card_requests row
// of its own (Occupied=true via cardWorkChildOccupantTx).
RequestID string `json:"request_id,omitempty"`
// LauncherJobID is THIS call's own launcher exec job (Occupied=false
// only) — never the continuation/target job, which TargetKind/TargetID
// point at instead. Named launcher_job_id (not job_id) so a caller
// cannot mistake it for the continuation's own job id.
LauncherJobID string `json:"launcher_job_id,omitempty"`
// TargetKind/TargetID name the occupying continuation's REAL task id
// (never a task_triage.detail.children JSON child id, which is not a
// task id and 404s on GET /api/tasks/<id>) — only set when Occupied and
// a live task row actually exists to point at.
TargetKind string `json:"target_kind,omitempty"`
TargetID string `json:"target_id,omitempty"`
// Instruction echoes back the caller's own submitted instruction on an
// Occupied response, so an occupied call never silently drops what the
// caller typed. Empty on success (Occupied=false): the instruction was
// already persisted onto the new card_requests row itself.
Instruction string `json:"instruction,omitempty"`
}
RunCardCommandResult is RunCardCommandAsHuman's response shape.
type SecretHandler ¶
type SecretHandler struct {
Store SecretStore
}
func (*SecretHandler) Delete ¶
func (h *SecretHandler) Delete(w http.ResponseWriter, r *http.Request)
func (*SecretHandler) GetValue ¶
func (h *SecretHandler) GetValue(w http.ResponseWriter, r *http.Request)
func (*SecretHandler) List ¶
func (h *SecretHandler) List(w http.ResponseWriter, r *http.Request)
func (*SecretHandler) Routes ¶
func (h *SecretHandler) Routes() chi.Router
func (*SecretHandler) Set ¶
func (h *SecretHandler) Set(w http.ResponseWriter, r *http.Request)
type SecretStore ¶
type SessionDispatcher ¶ added in v0.0.6
type SessionDispatcher interface {
StartSession(ctx context.Context, req StartSessionRequest) (*StartSessionResult, error)
}
SessionDispatcher launches a session job (claude / codex / opencode under a HarnessAdapter) and returns the runtime job id.
type SessionHandler ¶ added in v0.0.6
type SessionHandler struct {
Service ProjectService
Dispatcher SessionDispatcher
}
SessionHandler exposes the POST /api/sessions surface (and the project-scoped /api/projects/{id}/sessions variant mounted by ProjectHandler). Sessions are a first-class JobKind alongside hook and exec so user-initiated agent runs (WebUI [New Session] / `boid agent`) need not piggyback on the project command path.
func (*SessionHandler) Routes ¶ added in v0.0.6
func (h *SessionHandler) Routes() chi.Router
func (*SessionHandler) Start ¶ added in v0.0.6
func (h *SessionHandler) Start(w http.ResponseWriter, r *http.Request)
Start handles POST /api/sessions. The request body must specify project_id. Use the project-scoped variant when the project is implied by the URL.
Session-id resume was removed: every Start launches a fresh agent process, so there is no `/api/sessions/{id}/resume` companion route anymore.
type SetProjectWorkspaceRequest ¶
type SetProjectWorkspaceRequest struct {
WorkspaceID string `json:"workspace_id"`
}
type SettingsConfigService ¶ added in v0.1.0
type SettingsConfigService interface {
// ConfigYAML returns the daemon's current effective config.yaml document
// and its revision; same contract as api.ConfigService.ConfigYAML.
ConfigYAML() (data []byte, revision string, err error)
}
SettingsConfigService is the read surface WebHandler.Settings needs to prefill /settings' initial render. Deliberately narrower than the full api.ConfigService — Apply/Mutate are reached directly by the page's own client-side JS, never through this Go handler.
type SignalHandler ¶ added in v0.4.0
type SignalHandler struct {
Store SignalStore
}
SignalHandler serves the host API: GET /api/signals (list) and POST /api/signals/ack. Store is SignalStore (internal/api/store.go); wire.go mounts this handler directly against runtime.taskRepo, which already implements it — no separate service type is needed here, unlike CardHandler's CardReadService.
func (*SignalHandler) Ack ¶ added in v0.4.0
func (h *SignalHandler) Ack(w http.ResponseWriter, r *http.Request)
Ack handles POST /api/signals/ack. Body: AckSignalsRequest ({"workspace_id": "...", "ids": [...]}); workspace_id defaults the same way List's query param does.
AckSignals is itself idempotent (re-acking an id is a no-op, not an error), so this handler adds no extra dedup check of its own. The only validation here is "ids must not be empty".
func (*SignalHandler) List ¶ added in v0.4.0
func (h *SignalHandler) List(w http.ResponseWriter, r *http.Request)
List handles GET /api/signals?workspace_id=&source=&service=&state=&limit=. workspace_id defaults to orchestrator.DefaultWorkspaceSlug when omitted, so any direct API caller gets the same behavior as the CLI. source maps to SignalFilter.Connector unchanged (the stored composite "<pack>/<connector>" string) — only the response envelope splits it back apart, in toWireSignals below.
func (*SignalHandler) Routes ¶ added in v0.4.0
func (h *SignalHandler) Routes() chi.Router
type SignalSource ¶ added in v0.4.0
type SignalSource = apiwire.SignalSource
from internal/api/signal_handler.go
type SignalStore ¶ added in v0.4.0
type SignalStore interface {
IngestSignals(workspaceID, service, connector string, rows []orchestrator.SignalIngestRow) error
GetSignalCursor(workspaceID, service, connector string) (string, error)
ListSignals(filter orchestrator.SignalFilter) ([]*orchestrator.Signal, error)
ClaimSignals(workspaceID string, limit, maxAttempts int) ([]*orchestrator.Signal, error)
// ClaimSignalIDs charges one attempt against exactly the ids named — the
// explicit half of the read/claim split (orchestrator.ClaimSignalIDs).
ClaimSignalIDs(workspaceID string, ids []string) error
AckSignals(workspaceID string, ids []string) error
HasPendingSignals(workspaceID string, maxAttempts int) (bool, error)
}
SignalStore backs the inbox store (internal/orchestrator/signal_store.go) — narrowed from *orchestrator.TaskRepository the same way TriggerRunStore is. See the var _ assertion below for what proves TaskRepository actually satisfies this shape today.
GCSignals is deliberately NOT part of this interface: it is called directly as a package function from within TaskGCStore.GC's existing transaction (repository.go), the same way GCTriggerRuns is — not through a per-workspace narrow interface like the methods above.
type StartExecRequest ¶ added in v0.0.10
type StartExecRequest = apiwire.StartExecRequest
type StartExecResult ¶ added in v0.0.10
type StartExecResult = apiwire.StartExecResult
type StartSessionRequest ¶ added in v0.0.6
type StartSessionRequest = apiwire.StartSessionRequest
type StartSessionResult ¶ added in v0.0.6
type StartSessionResult = apiwire.StartSessionResult
type StatusError ¶
type StatusError struct {
Code int
Message string
OperationReason string
TargetRequestID string
TargetKind string
TargetID string
TargetTaskID string
}
func (*StatusError) Error ¶
func (e *StatusError) Error() string
type TaskAnswerService ¶
type TaskAnswerService interface {
AnswerTask(ctx context.Context, taskID, questionID, answer string) error
}
TaskAnswerService records a user reply to a pending Q&A question and transitions the task back to executing.
type TaskAppService ¶
type TaskAppService struct {
VerifyRelease func(context.Context, *orchestrator.Project, string, string) (bool, error)
Tasks TaskStore
Actions ActionStore
Jobs JobStore
Meta MetaStore
Workflow WorkflowService
Projects ProjectWorkDirLookup
RuntimesDir string
Notify Notifier
// BlockingAsk coordinates harness-independent blocking Q&A (boid task ask).
// Shared with the sandbox boid builtin executor (which calls AskTaskBlocking)
// and the answer path (AnswerTask), so both halves of a blocking ask use the
// same in-memory registry. Nil disables blocking ask (notify --ask still works).
BlockingAsk *BlockingAskRegistry
// AskDisconnectGrace is how long an awaiting task may sit with no live agent
// parked before the daemon reclaims it (a blocking ask whose foreground
// command was killed by a harness command-timeout). Zero falls back to
// defaultAskDisconnectGrace.
AskDisconnectGrace time.Duration
// TaskWaits is the registry the brokered task_wait op records itself in
// while parked, so the trigger sweep can tell which task a job is waiting
// on. Shared with TaskWorkflowService (wire.go builds one). Nil disables the
// attribution; the wait itself still works.
TaskWaits *TaskWaitRegistry
// WaitPollInterval is how often WaitTaskTerminal re-reads a task row while
// blocked on it. Zero falls back to defaultWaitPollInterval — same
// convention as AskDisconnectGrace above.
WaitPollInterval time.Duration
// Identities backs the identity index — the non-transactional path the
// brokered task_identity_link / _unlink / _resolve ops (boid_executor.go)
// call through. The drop side effect instead goes through
// TxStore.UnlinkAllForTask inside
// TaskWorkflowService.ApplyAction's own transaction; this field is only
// for the standalone ops, which have no transaction of their own to join.
// Nil disables the three ops with an "unavailable" error, same convention
// as every other optional dependency here.
Identities TaskIdentityStore
// CardRequestLinker backs a card-command launcher's atomic task
// creation + card_requests attach (see CreateTaskRequest.CardRequestID).
// Nil falls back to the ordinary s.Tasks.CreateTask path.
CardRequestLinker CardRequestTaskLinker
// CardRequests backs cardSlotConflictWithRequests' check for an active
// (launching/attached) card_requests row — a command launcher or Go call
// that has claimed the slot but not yet created its continuation. Nil is
// tolerated (same posture as CardRequestLinker): the additional check is
// simply skipped.
CardRequests CardCommandLauncherStore
// Tx lets createExecutionTask close the direct-`--parent <card>`-create
// TOCTOU for ANY direct task creation under a card — both a
// CardRequestID-less create and a CardRequestID-carrying one (e.g.
// acceptGo's own CreateTask call): atomicCardCheck re-reads the card
// fresh and does the INSERT inside one WithinTx call instead of a
// separate pre-check followed by a write — see createExecutionTask's own
// comment. Nil is tolerated: both cases fall back to the prior
// non-transactional read-then-write.
Tx Transactor
// Hub broadcasts NotifyTask's progress/done_request/fail_request writes
// over SSE. Nil disables broadcasting; the writes themselves still happen.
Hub *TaskEventHub
}
func (*TaskAppService) AnswerTask ¶
func (s *TaskAppService) AnswerTask(ctx context.Context, taskID, questionID, answer string) error
AnswerTask saves the user's reply and transitions the task awaiting → executing.
func (*TaskAppService) AskTaskBlocking ¶ added in v0.0.6
func (s *TaskAppService) AskTaskBlocking(ctx context.Context, taskID, question string) (string, error)
AskTaskBlocking implements the harness-independent blocking Q&A RPC behind `boid task ask <question>`. The agent stays alive and blocks inside this call until the user/supervisor answers, so the round-trip works for every harness uniformly — there is no session-resume path anywhere in boid (the legacy `notify --ask` → `claude --resume` flow was removed).
The call is disconnect-resilient and idempotent across re-asks. Harnesses kill long-running shell commands on a command-timeout (claude-code / opencode at ~120s), which severs the held connection. When that happens the model retries the identical `boid task ask`; this handler recognises the retry and recovers instead of treating it as a fresh question:
- executing → fresh ask: register the answer channel, transition executing → awaiting via ApplyAction("ask"), fire the user notification (root tasks only; child tasks are seen by their supervisor's monitor loop), then block in Wait.
- awaiting → re-ask: if an answer was parked durably while the agent was disconnected (PendingAnswer), consume it immediately and flip back to executing. Otherwise re-attach to the SAME question id and block again — no second "ask" transition, no new notification.
Register happens before the awaiting transition so an answer that races in immediately afterwards is never dropped. A concurrent ask carrying a DIFFERENT question id still fails with ErrAskPending; a re-ask of the same question is a re-attach and is allowed.
func (*TaskAppService) CreateTask ¶
func (s *TaskAppService) CreateTask(ctx context.Context, req CreateTaskRequest) (*orchestrator.Task, error)
func (*TaskAppService) DeleteTask ¶
func (s *TaskAppService) DeleteTask(id string, force bool) error
func (*TaskAppService) DuplicateTask ¶
func (s *TaskAppService) DuplicateTask(ctx context.Context, sourceID string, autoStart bool) (*orchestrator.Task, error)
func (*TaskAppService) GetInstructions ¶ added in v0.0.13
func (s *TaskAppService) GetInstructions(id string) ([]orchestrator.RoutedInstruction, error)
GetInstructions returns the task's "active" routed instruction — the entry orchestrator.CurrentInstructions derives from the last entry in the task's instruction history.
NOT the `boid task instructions` RPC's data source: a task row can't tell which job is asking, and two agent-kind hooks can fire from the same task in one round, so this could hand one job's caller the other's instruction. Kept for callers that want the task's routing state independent of any specific job. Returns an empty (non-nil) slice when the task has no active instruction.
func (*TaskAppService) GetInstructionsField ¶ added in v0.0.13
func (s *TaskAppService) GetInstructionsField(id, path string) (string, error)
GetInstructionsField resolves a dotted path against the []RoutedInstruction list returned by GetInstructions, mirroring GetTaskField's --field contract.
func (*TaskAppService) GetTask ¶
func (s *TaskAppService) GetTask(id string) (*orchestrator.Task, error)
func (*TaskAppService) GetTaskCurrent ¶ added in v0.0.13
func (s *TaskAppService) GetTaskCurrent(id string) (*orchestrator.TaskSnapshot, error)
GetTaskCurrent returns the task's business-metadata snapshot (the payload of `boid task current`), re-derived live from the task row on every call.
func (*TaskAppService) GetTaskCurrentField ¶ added in v0.0.13
func (s *TaskAppService) GetTaskCurrentField(id, path string) (string, error)
GetTaskCurrentField resolves a dotted path against the task-current snapshot, mirroring GetTaskField's semantics for `--field` (missing path → "", scalar → unquoted/stringified, object/array → compact JSON).
func (*TaskAppService) GetTaskDetail ¶
func (s *TaskAppService) GetTaskDetail(id string) (*TaskDetailView, error)
func (*TaskAppService) GetTaskField ¶
func (s *TaskAppService) GetTaskField(id, path string) (string, error)
GetTaskField resolves a dotted field path against the task. See ResolveTaskField for the path syntax (top-level fields, payload traits, computed lifecycle).
func (*TaskAppService) ImportTasks ¶
func (s *TaskAppService) ImportTasks(ctx context.Context, reqs []CreateTaskRequest) (*ImportResult, error)
func (*TaskAppService) LinkIdentity ¶ added in v0.4.0
func (s *TaskAppService) LinkIdentity(ctx context.Context, projectID, identity, taskID string) error
LinkIdentity binds identity to taskID within projectID's scope. See TaskIdentityStore.LinkIdentity for the idempotent-same-task / ErrIdentityConflict-different-task contract.
A binding change onto a card is recorded in the same transaction. The binding is read first: the store's return value cannot distinguish a write from an idempotent repeat, which records nothing.
func (*TaskAppService) LinkIdentityInScope ¶ added in v0.6.0
func (s *TaskAppService) LinkIdentityInScope(ctx context.Context, scope orchestrator.IdentityScope, identity, taskID string, url, displayName *string) error
LinkIdentityInScope binds an identity and metadata atomically within its namespace.
func (*TaskAppService) LinkIdentityWithMetadata ¶ added in v0.5.0
func (s *TaskAppService) LinkIdentityWithMetadata(ctx context.Context, projectID, identity, taskID string, url, displayName *string) error
LinkIdentityWithMetadata links an identity and applies explicitly supplied metadata.
func (*TaskAppService) LinkWorkspaceIdentity ¶ added in v0.6.0
func (s *TaskAppService) LinkWorkspaceIdentity(ctx context.Context, workspaceID, identity, taskID string) error
func (*TaskAppService) ListTasks ¶
func (s *TaskAppService) ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
func (*TaskAppService) NotifyTask ¶
func (s *TaskAppService) NotifyTask(ctx context.Context, taskID, message, ask, questionID, progress, done, fail string) error
NotifyTask invokes the configured notify command for taskID. Returns 501 when no notifier is wired and ask is empty. With ask set, the task transitions to awaiting (notification is best-effort); questionID identifies the Q&A turn (generated when empty). With progress set, only a progress Action is written — no hook fires, no state transition. ask and progress are mutually exclusive.
ask does NOT spawn a resume dispatch when the user replies — only the blocking `boid task ask` RPC can deliver an answer back to a live agent.
Every Action this writes is stamped orchestrator.ActorTask(taskID), even when called from the host-side HTTP route by a human operator: this call always represents the task's own self-report.
func (*TaskAppService) RerunTask ¶
func (s *TaskAppService) RerunTask(id string, req RerunTaskRequest) (*orchestrator.Task, error)
func (*TaskAppService) ResolveIdentity ¶ added in v0.4.0
func (s *TaskAppService) ResolveIdentity(projectID, identity string) (*orchestrator.Task, error)
ResolveIdentity looks up the task bound to (projectID, identity). Returns orchestrator.ErrTaskNotFound when no binding exists.
func (*TaskAppService) ResolveIdentityInScope ¶ added in v0.6.0
func (s *TaskAppService) ResolveIdentityInScope(scope orchestrator.IdentityScope, identity string) (*orchestrator.Task, error)
func (*TaskAppService) ResolveWorkspaceIdentity ¶ added in v0.6.0
func (s *TaskAppService) ResolveWorkspaceIdentity(workspaceID, identity string) (*orchestrator.Task, error)
func (*TaskAppService) UnlinkIdentity ¶ added in v0.4.0
func (s *TaskAppService) UnlinkIdentity(ctx context.Context, projectID, identity string) error
UnlinkIdentity removes one (projectID, identity) binding, if any.
func (*TaskAppService) UnlinkIdentityInScope ¶ added in v0.6.0
func (s *TaskAppService) UnlinkIdentityInScope(ctx context.Context, scope orchestrator.IdentityScope, identity string) error
func (*TaskAppService) UnlinkWorkspaceIdentity ¶ added in v0.6.0
func (s *TaskAppService) UnlinkWorkspaceIdentity(ctx context.Context, workspaceID, identity string) error
func (*TaskAppService) UpdateTask ¶
func (s *TaskAppService) UpdateTask(ctx context.Context, id string, req UpdateTaskRequest) (*orchestrator.Task, error)
func (*TaskAppService) UpdateTaskPayloadPatch ¶ added in v0.0.13
func (s *TaskAppService) UpdateTaskPayloadPatch(jobID string, patch json.RawMessage, allowedTraits []orchestrator.TraitType) (*orchestrator.Task, error)
UpdateTaskPayloadPatch applies patch to the task owning jobID using the SAME merge semantics the file-based payload_patch.json → job_done → Coordinator pipeline has always applied (orchestrator.MergePayloadPatch, gated by the trait allowlist the firing hook itself declares via Traits.Produces). This is deliberately NOT UpdateTask's simpler top-level shallow merge (used by --payload-file): UpdateTask has no notion of a "firing hook", so it can't reproduce this gate.
jobID (not taskID) is the identity this method resolves from, because the allowedTraits gate is keyed off the CALLING job's own HandlerID — the specific hook that was dispatched to produce this job, which may differ from other jobs the same task has had or will have.
allowedTraits is supplied by the CALLER as the value captured AT DISPATCH TIME (dispatcher.JobContextSnapshot.PayloadPatchAllowedTraits), never re-derived here from a live project-meta lookup: a live lookup done inside this call would apply the WRONG (post-edit) trait list, or fall back to unrestricted, if workspace configuration changed between dispatch and this call. Accepting the dispatch-time value as a parameter makes that staleness structurally impossible. nil means unrestricted — see JobSpec.HookTraitsProduces's own doc comment for when that applies.
The GetTask -> MergePayloadPatch -> UpdateTask sequence below is serialized per task id (payloadPatchLockFor) so two concurrent calls for the same task — e.g. two hooks in the same readonly task's parallel dispatch round, each patching a different trait — cannot race a read-modify-write and silently lose one of their writes.
func (*TaskAppService) WaitTaskTerminal ¶ added in v0.4.0
func (s *TaskAppService) WaitTaskTerminal(ctx context.Context, taskID string) (TaskOutcome, error)
WaitTaskTerminal blocks until taskID reaches a terminal status and reports how it ended.
This is the daemon half of `boid task wait <id>`, which exists so a trigger's `run:` command can live exactly as long as the task it started. That single change makes the trigger's own machinery cover the task: single-flight stops measuring a launcher that exits in seconds and starts measuring the work, and a failed round arrives at TriggerLoop.trackFailStreak as an ordinary non-zero exit instead of having to be re-derived by the workspace from the action log.
Only ctx cancellation ends the wait early. The broker gives a blocking op a context tied to its connection (sandbox.isBlockingBoidRequest — task_wait must stay listed there or an abandoned wait runs until daemon shutdown), so a sandbox that dies unblocks this. It is NOT a timeout: a task that parks in a non-terminal resting state (`awaiting` on a question nobody answers, `pending` with auto_start off) waits indefinitely. Bounding a round's total duration is the trigger's job, not this call's.
type TaskCreator ¶ added in v0.2.4
type TaskCreator interface {
CreateTask(ctx context.Context, req CreateTaskRequest) (*orchestrator.Task, error)
}
TaskCreator is the slice of TaskAppService that TaskWorkflowService.Dispatch needs to task-ify a triage task's specced children. Implemented by TaskAppService and wired in after TaskAppService itself is constructed (wire.go creates TaskWorkflowService first, TaskAppService second, so this mirrors the same late-binding idiom the reverse direction already uses — see WorkflowService/TaskAppService.Workflow above) to avoid a literal struct-construction cycle between the two services.
type TaskDetailView ¶
type TaskDetailView = apiwire.TaskDetailView
type TaskEventHub ¶
type TaskEventHub struct {
// contains filtered or unexported fields
}
TaskEventHub は taskID ごとに複数の subscriber へイベントを配送する pub-sub ハブ。
func (*TaskEventHub) Broadcast ¶
func (h *TaskEventHub) Broadcast(taskID string, ev TaskEvent)
Broadcast は taskID の全 subscriber に ev を非ブロッキングで配送する。 チャネルが満杯の subscriber はドロップする(hub 全体を止めない)。
type TaskHandler ¶
type TaskHandler struct {
Identities *TaskAppService
Capture interface {
ResolveOrCapture(context.Context, ResolveOrCaptureRequest) (*ResolveOrCaptureResult, error)
}
Service TaskService
Hooks HookService // optional: enables hook replay/list when set
Notifier TaskNotifyService // optional: enables POST /{id}/notify when set
Answerer TaskAnswerService // optional: enables POST /{id}/answer when set
}
func (*TaskHandler) Answer ¶
func (h *TaskHandler) Answer(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Create ¶
func (h *TaskHandler) Create(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Delete ¶
func (h *TaskHandler) Delete(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Detail ¶
func (h *TaskHandler) Detail(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Duplicate ¶
func (h *TaskHandler) Duplicate(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Field ¶
func (h *TaskHandler) Field(w http.ResponseWriter, r *http.Request)
Field returns a single dotted-path value extracted from the task. The response is text/plain so it can be consumed directly by shell scripts (e.g. `STATUS=$(boid task show $ID --field status)`).
func (*TaskHandler) Get ¶
func (h *TaskHandler) Get(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Identity ¶ added in v0.6.0
func (h *TaskHandler) Identity(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Import ¶
func (h *TaskHandler) Import(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) List ¶
func (h *TaskHandler) List(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) ListHooks ¶
func (h *TaskHandler) ListHooks(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Notify ¶
func (h *TaskHandler) Notify(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Patch ¶
func (h *TaskHandler) Patch(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) ReplayHook ¶
func (h *TaskHandler) ReplayHook(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Rerun ¶
func (h *TaskHandler) Rerun(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) ResolveOrCapture ¶ added in v0.6.0
func (h *TaskHandler) ResolveOrCapture(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Routes ¶
func (h *TaskHandler) Routes() chi.Router
type TaskIdentityRequest ¶ added in v0.6.0
type TaskIdentityRequest = apiwire.TaskIdentityRequest
type TaskIdentityStore ¶ added in v0.4.0
type TaskIdentityStore interface {
// LinkIdentity binds identity to taskID within projectID's scope.
// Re-linking the same task is idempotent; linking a DIFFERENT task
// already bound to identity returns orchestrator.ErrIdentityConflict.
LinkIdentity(projectID, identity, taskID string) error
// UnlinkIdentity removes one binding, if any (idempotent — not found is
// not an error).
UnlinkIdentity(projectID, identity string) error
// UnlinkAllForTask releases every identity bound to taskID (called from
// the drop side effect — see TaskWorkflowService.ApplyAction).
UnlinkAllForTask(taskID string) error
// ResolveIdentity looks up the task bound to (projectID, identity).
// Returns orchestrator.ErrTaskNotFound when no binding exists.
ResolveIdentity(projectID, identity string) (*orchestrator.Task, error)
// ListIdentitiesByTask returns every identity bound to taskID.
ListIdentitiesByTask(taskID string) ([]string, error)
}
TaskIdentityStore provides access to the identity index (task_identities table): external key -> task, scoped per project. Deliberately separate from TaskStore for the same reason CardStore is: identity bindings are not part of orchestrator.Task's own JSON shape.
type TaskNotifyService ¶
type TaskNotifyService interface {
NotifyTask(ctx context.Context, taskID, message, ask, questionID, progress, done, fail string) error
}
TaskNotifyService dispatches an agent-driven notification for a task. Wired to *TaskAppService at runtime; left optional on TaskHandler so existing tests do not need to satisfy this interface. ask/questionID are optional Q&A fields: when ask is non-empty the task is transitioned to awaiting after the notification is sent. The session-id resume path was removed, so an answer can only reach an agent that is still alive inside a blocking `boid task ask` RPC. progress is a no-state-change progress note (timeline action only). done / fail are agent self-completion / self-failure: they transition the task to done / aborted respectively and SIGTERM running hook runtimes — the parent supervisor's polling drives the response (verify + optional reopen). ask/progress/done/fail are mutually exclusive.
type TaskOutcome ¶ added in v0.4.0
type TaskOutcome struct {
// ID is the resolved task id (WaitTaskTerminal accepts the same id prefixes
// orchestrator.GetTask does).
ID string
Status orchestrator.TaskStatus
AbortCode string
AbortMessage string
}
TaskOutcome is how a waited-on task ended. AbortCode/AbortMessage carry the abort action's payload and are set only when Status is aborted: abortOnDispatchError writes "dispatch_error" / "daemon_shutdown", while an abort recorded without a payload (job_failed, i.e. a failure inside the agent's own session) leaves both empty. Neither is a closed vocabulary — read them as decoration for a human, never as a branch condition.
func (TaskOutcome) Succeeded ¶ added in v0.4.0
func (o TaskOutcome) Succeeded() bool
Succeeded reports whether the task ended the way the caller wanted. Only `done` counts — every other terminal status, including `dropped`, is a failure. This is what `boid task wait`'s exit code is derived from, and a trigger script's contract is "fail if the task you started did not succeed".
type TaskService ¶
type TaskService interface {
CreateTask(ctx context.Context, req CreateTaskRequest) (*orchestrator.Task, error)
ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
GetTask(id string) (*orchestrator.Task, error)
GetTaskDetail(id string) (*TaskDetailView, error)
GetTaskField(id, path string) (string, error)
UpdateTask(ctx context.Context, id string, req UpdateTaskRequest) (*orchestrator.Task, error)
DeleteTask(id string, force bool) error
ImportTasks(ctx context.Context, reqs []CreateTaskRequest) (*ImportResult, error)
DuplicateTask(ctx context.Context, sourceID string, autoStart bool) (*orchestrator.Task, error)
RerunTask(id string, req RerunTaskRequest) (*orchestrator.Task, error)
}
CreateTask/UpdateTask take ctx: the card records they write read the writer off it.
type TaskStatusReader ¶ added in v0.4.0
type TaskStatusReader interface {
GetTaskStatus(id string) (orchestrator.TaskStatus, error)
}
TaskStatusReader is the narrow re-read WaitTaskTerminal polls with, kept separate from TaskStore so adding it did not have to touch every implementation of that much larger interface.
*orchestrator.TaskRepository is the production implementation and the compile-time assertion below pins that, rather than leaving it to a runtime type check that would silently degrade to the expensive path if the real wired type ever stopped satisfying it: every unit test would still pass against a hand-built double while production never picked the interface up at all.
type TaskStore ¶
type TaskStore interface {
CreateTask(task *orchestrator.Task) error
GetTask(id string) (*orchestrator.Task, error)
ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
UpdateTask(task *orchestrator.Task) error
DeleteTask(id string) error
FindTaskByRemote(remoteID string) (*orchestrator.Task, error)
// FindTaskByRef looks up an existing task by ref, scoped to BOTH
// parentID ("" for a root task) and projectID — see
// orchestrator.FindTaskByRef's doc comment for why
// projectID scoping is required, not optional.
FindTaskByRef(ref, parentID, projectID string) (*orchestrator.Task, error)
// FindTaskByIdempotencyKey looks up an existing task by idempotency_key,
// scoped to (projectID, parentID) — the Ref get-or-create's counterpart.
FindTaskByIdempotencyKey(projectID, parentID, idempotencyKey string) (*orchestrator.Task, error)
// ListChildren returns direct children (one level only) of the given parent
// task, ordered by created_at ASC. Returns an empty slice (not nil) when the
// task has no children. Used by finalizeTerminal to sweep boid/<id8> branches
// once a supervisor reaches a terminal state.
ListChildren(parentID string) ([]*orchestrator.Task, error)
}
type TaskUpdatedAtToucher ¶ added in v0.4.0
TaskUpdatedAtToucher backs a single-column `UPDATE tasks SET updated_at = ? WHERE id = ?` that carries NO status. Deliberately its own interface, not folded into TaskStore — TaskStore.UpdateTask does a blanket rewrite of every column from a caller-held Task snapshot, which is exactly the stale-snapshot race workflow_action.go's skipTaskUpdate guard exists to avoid for attrs_set/child_added/child_specced/child_dropped/noted (see that variable's own doc comment). TouchTaskUpdatedAt carries no status at all, so calling it alongside those actions' own non-transitioning side effects — in the same Tx — cannot stomp a concurrently-committed transition the way an unconditional UpdateTask(stale snapshot) would.
type TaskWaitRegistry ¶ added in v0.4.0
type TaskWaitRegistry struct {
// contains filtered or unexported fields
}
TaskWaitRegistry records which task each in-flight `boid task wait` is parked on, keyed by the waiting job — so a trigger-timeout sweep can abort the task itself rather than just killing the launching job. In-memory only (like BlockingAskRegistry): a lost entry just means the abort is skipped, never that the wrong task gets aborted.
func NewTaskWaitRegistry ¶ added in v0.4.0
func NewTaskWaitRegistry() *TaskWaitRegistry
NewTaskWaitRegistry returns an initialised registry.
func (*TaskWaitRegistry) Register ¶ added in v0.4.0
func (r *TaskWaitRegistry) Register(jobID, taskID string) (release func())
Register records that jobID is waiting on taskID and returns the release to call when the wait ends. A nil registry or empty jobID is tolerated and returns a no-op release. A second Register for the same job overwrites the first — the newer wait is the one actually parked.
type TaskWorkflowService ¶
type TaskWorkflowService struct {
Tasks TaskStore
Jobs JobStore
Projects ProjectRepository
Tx Transactor
Meta MetaStore
Coordinator DispatchCoordinator
Lifecycle JobLifecycle
Hub *TaskEventHub
// TaskTriage provides non-transactional (pre-tx-open) read access to the
// task_triage sidecar for TaskWorkflowService.Dispatch's pre-check /
// children read. TxStore already embeds CardStore for the in-transaction
// writes Dispatch and applyParkSideEffect need — this field is only for
// the read that has to happen BEFORE opening a transaction (see
// Dispatch's own doc comment for why child-task creation can't run
// nested inside one). Nil is tolerated (treated as "no children");
// wire.go always sets this.
TaskTriage CardStore
// Actions provides the workspace-scoped BoidOpActionList read — same
// "narrower interface over the same underlying taskRepo value" pattern
// as TaskTriage above. Nil is tolerated (ListActions returns an
// "unavailable" error), matching every other optional dependency's
// convention in this file.
Actions ActionListStore
// TaskCreator creates the real boid tasks Dispatch task-ifies specced
// children into. Nil is tolerated as long as there are no specced
// children to dispatch — see Dispatch's own doc comment.
TaskCreator TaskCreator
// Adapter is the harness adapter used to query post-run usage. Graceful
// stop is delivered separately, as a SIGUSR1 directly via
// Lifecycle.SignalJobRuntime, which claude.Adapter.Run()'s
// signal.Notify handler intercepts. Adapter remains optional; when nil,
// usage / future per-harness queries become no-ops.
Adapter adapters.HarnessAdapter
// Notifier fires a notify rule whenever a suggestion attaches to a card
// — see notifySuggestionArrived in queue_notify.go. Nil is tolerated
// (no-op), same as TaskAppService.Notify's contract.
Notifier Notifier
// TaskWaits is the shared registry recording which task each in-flight
// `boid task wait` is parked on (see TaskWaitRegistry). SweepTriggers reads
// it to know WHAT to end when a round outruns its trigger's `timeout` — the
// task doing the work, not just the job that launched it. Nil is tolerated
// (a timed-out round then only has its job stopped), same convention as
// every other optional dependency here.
TaskWaits *TaskWaitRegistry
// Triggers backs trigger_runs' single-flight/execution-record read+write
// (SweepTriggers/RunTriggerNow, trigger_loop.go). Nil is tolerated —
// SweepTriggers/RunTriggerNow no-op (matching Notifier/TaskCreator's own
// convention above) rather than panicking, since a daemon built without
// this dependency wired should simply run no triggers, not crash.
Triggers TriggerRunStore
// Exec dispatches the exec job (api.ExecDispatcher.StartExec) a due
// trigger's `run` command executes as — the daemon starts an exec job
// through the same Runner.Dispatch() path `boid exec` uses. Nil is
// tolerated the same way Triggers above is, as a general defensive
// convention rather than an expected runtime state — wire.go's
// buildRuntime assigns this as soon as the TaskWorkflowService and its
// sessionDispatcherAdapter both exist.
Exec ExecDispatcher
// Signals backs the `on: signals` trigger predicate's HasPendingSignals
// read (SweepTriggers/signalsPendingForTrigger, trigger_loop.go). Nil
// is tolerated the same way Triggers/Exec above are: an on:signals
// trigger simply never becomes due (fail-closed, not a panic) when no
// SignalStore is wired — a plain schedule (on=""/on:schedule) trigger
// is entirely unaffected either way.
Signals SignalStore
// CardRequests backs RunCardCommandAsHuman's card_requests slot claim/release
// (card_command_launcher.go). Nil is tolerated the same way Triggers/
// Exec/Signals above are — RunCardCommandAsHuman returns "not configured"
// rather than panicking when unwired.
CardRequests CardCommandLauncherStore
// contains filtered or unexported fields
}
func (*TaskWorkflowService) ApplyAction ¶
func (s *TaskWorkflowService) ApplyAction(ctx context.Context, taskID string, req ApplyActionRequest) (*ActionApplication, error)
func (*TaskWorkflowService) CardCommandOptionsForProject ¶ added in v0.5.0
func (s *TaskWorkflowService) CardCommandOptionsForProject(ctx context.Context, projectID string) []CardCommandOption
CardCommandOptionsForProject lists projectID's card_commands in workspace configuration declaration order (meta.CardCommandsOrder), or nil when the project declares none — the Web UI's signal to render no command section at all.
func (*TaskWorkflowService) CardCommandOptionsForWorkspace ¶ added in v0.6.0
func (s *TaskWorkflowService) CardCommandOptionsForWorkspace(ctx context.Context, workspaceID string) []CardCommandOption
func (*TaskWorkflowService) CompleteJob ¶
func (s *TaskWorkflowService) CompleteJob(ctx context.Context, jobID string, req JobDoneRequest) (*Job, error)
func (*TaskWorkflowService) GetCard ¶ added in v0.4.0
func (s *TaskWorkflowService) GetCard(taskID string) (*CardView, error)
GetCard returns the read-side projection of one triage task.
A missing TASK is an error (404). A missing SIDECAR ROW is not: the task's status is the single most important piece of state, and a triage task can legitimately exist without a sidecar row (one whose first side-effect action has not landed yet). Reporting 404 for those would tell the caller "this task does not exist" about a task that plainly does — the same fail-open posture Dispatch already takes when it treats a missing row as "no children".
func (*TaskWorkflowService) InitDispatch ¶
func (s *TaskWorkflowService) InitDispatch(ctx context.Context)
InitDispatch initialises the lifecycle context used by dispatch-loop goroutines. Must be called before the first action is applied. The returned cancel is stored internally; call Shutdown to invoke it.
func (*TaskWorkflowService) ListActions ¶ added in v0.4.0
func (s *TaskWorkflowService) ListActions(filter orchestrator.ActionListFilter) (*ActionListResult, error)
ListActions returns the actions matching filter (already scoped by the caller) plus the next cursor. See orchestrator.ListActionsSince's own doc comment for the pagination contract.
func (*TaskWorkflowService) ListCards ¶ added in v0.4.0
func (s *TaskWorkflowService) ListCards(filter orchestrator.TaskFilter) ([]*CardView, error)
ListCards returns the projections of every TRIAGE task matching filter.
The discriminator is "has a task_triage row" rather than "has a triage-shaped status". Status alone cannot decide it: `done` is shared with ordinary tasks (a done triage task and a done executor task are indistinguishable by status — the same limitation that forces the reopen guard into the service layer), and a meta project holds plenty of ordinary tasks (the ingest/sweep executor tasks) that must not appear in a triage listing. CreateTask seeds the row for every pre-execution task (task_create.go), which is what makes this predicate reliable from birth.
A task whose sidecar lookup fails for a reason OTHER than "no row" is skipped rather than aborting the whole listing: one malformed row must not make the entire queue unreadable (same posture as SweepWake).
func (*TaskWorkflowService) ListHooksForStatus ¶
func (s *TaskWorkflowService) ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
ListHooksForStatus returns hooks that match the given status for the task. If status is empty, the task's current status is used.
func (*TaskWorkflowService) ReplayHook ¶
func (s *TaskWorkflowService) ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
ReplayHook replays a single hook for the given task. If req.Status is non-empty the task's status is overwritten before dispatch. Running jobs on the same task cause a 409 Conflict.
func (*TaskWorkflowService) ResolveOrCapture ¶ added in v0.4.0
func (s *TaskWorkflowService) ResolveOrCapture(ctx context.Context, req ResolveOrCaptureRequest) (*ResolveOrCaptureResult, error)
ResolveOrCapture resolves Identity (scoped to ProjectID) to an existing task, or — when unresolved — atomically creates a new `parked` card (the daemon never advances a card past capture) and links Identity to it.
Invariants pinned by task_resolve_or_capture_test.go:
- resolve-then-create-and-link happens inside a single Transactor.WithinTx call, so a create that isn't followed by a successful link never commits (no orphan captured task without an identity binding)
- a genuine identity conflict (LinkIdentity finding Identity already bound to a DIFFERENT task) surfaces orchestrator.ErrIdentityConflict UNWRAPPED so callers can errors.Is() it — same convention as api/task_identity.go's methods
- description is subject to the same size cap as every other content entry point (orchestrator.ValidateContentSize)
func (*TaskWorkflowService) RunCardCommandAsHuman ¶ added in v0.5.0
func (s *TaskWorkflowService) RunCardCommandAsHuman(ctx context.Context, cardID, commandKey, instruction string) (*RunCardCommandResult, error)
RunCardCommandAsHuman fires cardID's commandKey card_commands entry as a human (cause_id empty) command launcher: a short-lived readonly exec job that runs the workspace configuration `run:` command with card/request context in its broker token, expected to call `boid task create` or `boid agent start` exactly once to produce this request's continuation.
When the slot is already occupied, this does not queue — it returns a link to the current execution instead; the caller's own UI keeps the typed instruction around.
func (*TaskWorkflowService) RunTriggerNow ¶ added in v0.4.0
func (s *TaskWorkflowService) RunTriggerNow(ctx context.Context, projectID, triggerName string) (*TriggerRunNowResult, error)
RunTriggerNow fires projectID's triggerName trigger immediately, ignoring the `every` elapsed check but not single-flight — the manual debugging entry point behind `boid trigger run <name>`.
func (*TaskWorkflowService) RunWorkspaceTriggerNow ¶ added in v0.6.0
func (s *TaskWorkflowService) RunWorkspaceTriggerNow(ctx context.Context, workspaceID, triggerName string) (*TriggerRunNowResult, error)
RunWorkspaceTriggerNow manually fires a repository-free workspace trigger.
func (*TaskWorkflowService) Shutdown ¶
func (s *TaskWorkflowService) Shutdown()
Shutdown cancels the dispatch context and blocks until all in-flight dispatch loops have returned. Call this before closing the database.
func (*TaskWorkflowService) StopAgent ¶
func (s *TaskWorkflowService) StopAgent(runtimeID string)
StopAgent gracefully stops the agent backing runtimeID by delivering SIGUSR1 to its process group. claude.Adapter.Run()'s signal.Notify(SIGUSR1) handler forwards a SIGTERM to the claude child and returns Result.StoppedByDaemon=true, so the surrounding sandbox runtime survives long enough to post `boid job done` through the broker normally. No-op when runtimeID is empty or no JobLifecycle has been configured.
func (*TaskWorkflowService) SweepQueuedCardRequests ¶ added in v0.5.0
func (s *TaskWorkflowService) SweepQueuedCardRequests(ctx context.Context, _ time.Time) ([]string, error)
SweepQueuedCardRequests is CardRequestDispatchLoop's per-tick work: the periodic recovery fallback for a missed immediate dispatch attempt. Returns the card ids a launcher was actually started for.
func (*TaskWorkflowService) SweepReconcileChildren ¶ added in v0.4.0
SweepReconcileChildren re-checks every dispatched child of every working card against its real current task status, self-healing any whose task_triage.detail entry still says "dispatched" after the real task already reached done/aborted. This is bare bookkeeping over detail.children[].status, NOT a card transition — it never touches task.Status.
Without this periodic re-check, a "dispatched" entry that never gets its child_closed self-record (a transient DB error, or a child GC'd out from under it) would stick forever, and khi would read "a child is still running" off that stale entry and never suggest "done" for a card that has, in reality, already finished.
A failure evaluating one task is logged and does not abort the sweep.
func (*TaskWorkflowService) SweepTriggers ¶ added in v0.4.0
func (s *TaskWorkflowService) SweepTriggers(ctx context.Context, now time.Time) (TriggerSweepResult, error)
SweepTriggers is TriggerLoop's per-tick work: reconcile in-flight runs, then evaluate every project's triggers[] and fire whichever are due and not single-flight-blocked. Tolerant of partial failures — one project's or trigger's error is logged and does not abort the sweep for any other.
Nil Triggers/Projects/Meta/Jobs makes this a no-op: a daemon built without trigger support wired in simply runs no triggers. s.Exec is deliberately not part of this guard — its absence is already handled per-trigger by the fail-open dispatch-failure path below, and folding it in here would also skip reconcileInFlight, which stays useful (closing out already-in-flight rows) even when nothing new can be dispatched.
func (*TaskWorkflowService) SweepWake ¶ added in v0.2.4
func (s *TaskWorkflowService) SweepWake(ctx context.Context, now time.Time) (woken []string, err error)
SweepWake is a periodic, decision-only sweep (clock + task DB only, no agent judgment) that only records that orchestrator.ShouldWake fired (recordWakeDue) — a wake_due action, no transition, no suggestion. khi reads wake_due off the action log and decides what (if anything) to suggest. Card machine v2 has exactly one park origin (working) and no wake_* rules at all, so there is nothing for this sweep to resolve beyond recording the fact.
A failure evaluating or recording one task is logged and does not abort the sweep. Returns the ids of tasks wake_due was recorded for this tick.
type Transactor ¶
type TriggerCompletionResult ¶ added in v0.4.0
type TriggerCompletionResult struct {
TriggerKey
ExitCode int
}
TriggerCompletionResult records one trigger_runs row a sweep reconciled (its job reached a terminal status this tick).
type TriggerFireResult ¶ added in v0.4.0
type TriggerFireResult struct {
TriggerKey
JobID string
}
TriggerFireResult records one trigger a sweep actually dispatched.
type TriggerKey ¶ added in v0.4.0
TriggerKey identifies a trigger within a project or a repository-free workspace — the single-flight and elapsed-time scoping unit.
func (TriggerKey) String ¶ added in v0.6.0
func (key TriggerKey) String() string
type TriggerLoop ¶ added in v0.4.0
type TriggerLoop struct {
Store TriggerLoopStore
Interval time.Duration
InitialDelay time.Duration
// Notifier is optional (nil disables stuck/failure notifications).
Notifier Notifier
// contains filtered or unexported fields
}
TriggerLoop periodically calls SweepTriggers, mirroring QueueSweepLoop's shape: InitialDelay then Interval, Run(ctx) blocks until ctx is done, a sweep error is logged and never stops the loop.
skipStreak/failStreak (stuck/failure-streak notification bookkeeping) are kept in-memory, not persisted — a daemon restart resets the streak count to zero, at worst costing one missed or duplicated notification around a restart; trigger_runs itself (the single-flight source of truth) is unaffected.
func (*TriggerLoop) Run ¶ added in v0.4.0
func (l *TriggerLoop) Run(ctx context.Context)
Run blocks until ctx is done. It waits InitialDelay before the first sweep, then calls Store.SweepTriggers every Interval.
type TriggerLoopStore ¶ added in v0.4.0
type TriggerLoopStore interface {
SweepTriggers(ctx context.Context, now time.Time) (TriggerSweepResult, error)
}
TriggerLoopStore is TriggerLoop's dependency, narrowed from *TaskWorkflowService — same idiom as QueueSweepStore (queue_sweep.go).
type TriggerRunNowResult ¶ added in v0.4.0
type TriggerRunNowResult struct {
// Skipped is true when single-flight blocked this manual run (a prior
// run for the same (project, trigger) is still in flight). A manual run
// bypasses only the `every` elapsed check, never single-flight.
Skipped bool `json:"skipped"`
Reason string `json:"reason,omitempty"`
JobID string `json:"job_id,omitempty"`
}
TriggerRunNowResult is RunTriggerNow's / `boid trigger run`'s response shape.
type TriggerRunStore ¶ added in v0.4.0
type TriggerRunStore interface {
CreateTriggerRun(run *orchestrator.TriggerRun) error
CompleteTriggerRun(id string, finishedAt time.Time, exitCode int) error
ListInFlightTriggerRuns() ([]*orchestrator.TriggerRun, error)
LatestTriggerRun(projectID, triggerName string) (*orchestrator.TriggerRun, error)
// SetTriggerRunJobID / DeleteTriggerRun back the insert-then-dispatch
// split — see orchestrator.CreateTriggerRun's own doc comment for the
// full sequence.
SetTriggerRunJobID(id, jobID string) error
DeleteTriggerRun(id string) error
}
TriggerRunStore backs the trigger_runs ledger read/writes — narrowed from *orchestrator.TaskRepository the same way ActionListStore/CardStore are (workflow.go). Deliberately non-transactional (unlike TxStore's WithinTx-scoped methods): each call is a standalone statement, matching this table's actual access pattern in trigger_loop.go (a trigger_runs row's create and its later complete are two separate ticks by construction, so there is nothing to wrap in one transaction).
type TriggerRunner ¶ added in v0.4.0
type TriggerRunner interface {
RunTriggerNow(ctx context.Context, projectID, triggerName string) (*TriggerRunNowResult, error)
}
TriggerRunner fires one workspace configuration trigger immediately, bypassing the `every` elapsed check but NOT single-flight. Implemented by *api.TaskWorkflowService.RunTriggerNow (trigger_loop.go).
type TriggerSkip ¶ added in v0.4.0
type TriggerSkip struct {
TriggerKey
// Since is the blocking run's StartedAt.
Since time.Time
// Every is trigger.Every, parsed; zero only if the blocking run's own
// trigger definition failed to parse (should not happen —
// ValidateTriggers rejects that at load time).
Every time.Duration
// Timeout is the trigger's declared round bound, zero if undeclared.
// trackSkipStreak prefers it over guessing from Every.
Timeout time.Duration
}
TriggerSkip records one trigger that was due this tick but single-flight blocked it.
type TriggerSweepResult ¶ added in v0.4.0
type TriggerSweepResult struct {
// Fired lists triggers this sweep actually dispatched.
Fired []TriggerFireResult
// Skipped lists triggers that were due but single-flight blocked them
// this tick — not a trigger that simply hasn't reached its next `every`.
Skipped []TriggerSkip
// Completed lists trigger_runs rows this sweep newly marked finished.
Completed []TriggerCompletionResult
}
TriggerSweepResult is SweepTriggers' return shape, used by TriggerLoop for stuck/failure-streak bookkeeping and by tests to pin behavior.
type TxStore ¶
type TxStore interface {
TaskStore
ActionStore
CardStore
JobStore
// TaskIdentityStore is embedded so the drop side effect (I-6:
// TaskWorkflowService.ApplyAction's WithinTx switch) can release a
// dropped task's identity bindings atomically with the drop transition
// itself, the same way park/attrs_set/child_added/child_specced apply
// their own sidecar side effects inside the same transaction.
TaskIdentityStore
TaskUpdatedAtToucher
// CountActiveCardRequests backs cardSlotOccupied's OR-with-card_requests
// check (workflow_card.go) — see that function's own doc comment.
CountActiveCardRequests(cardID string) (int, error)
// CreateCardRequest / FailCardRequest / ListCardRequestsByCard let a
// slot claim (RunCardCommandAsHuman, acceptGo) read the card's current
// occupancy and reserve the slot in the SAME transaction, closing the
// TOCTOU window a separate non-transactional read-then-CreateCardRequest
// call would otherwise leave open.
CreateCardRequest(req *orchestrator.CardRequest) error
FailCardRequest(id, errText string) error
ListCardRequestsByCard(cardID string) ([]*orchestrator.CardRequest, error)
// ReleaseCardRequestForTerminalTargetWithCard backs finalizeTerminal's
// immediate slot release the instant a task reaches a terminal state,
// instead of waiting for the periodic ReconcileCardRequestSlots tick —
// and the released card_id it returns is what lets the caller attempt
// an immediate re-dispatch of that card's queued backlog right after.
ReleaseCardRequestForTerminalTargetWithCard(targetKind, targetID string, success bool) (found bool, cardID string, err error)
// ClearCardForceReleaseBarrier ends automatic-dispatch suppression for a
// card the instant a human operation (RunCardCommandAsHuman, Go) claims
// its slot again — run inside the SAME transaction as that claim.
ClearCardForceReleaseBarrier(cardID string) error
// CreateTaskLinkedToCardRequest lets a caller already inside a
// WithinTx close its own read-then-write gap around a card_requests
// launcher continuation: TaskRepository's own dbtx type-switch means a
// tx-bound call here does not open a nested transaction. ownerJobID —
// see CardRequestTaskLinker's matching doc comment (task_service.go).
CreateTaskLinkedToCardRequest(t *orchestrator.Task, requestID, ownerJobID string) error
}
type UpdateJobRequest ¶ added in v0.0.4
type UpdateJobRequest struct {
DisplayName *string `json:"display_name"`
}
type UpdateTaskRequest ¶
type UpdateTaskRequest = apiwire.UpdateTaskRequest
type WSAttachHandler ¶
type WSAttachHandler struct {
Subscriber dispatcher.RuntimeSubscriber
Writer dispatcher.RuntimeInputWriter
PublicURL string
Registry *auth.ConnectionRegistry
// Bearer verifies an `Authorization: Bearer <token>` header carried on
// the WS handshake request. When present, it is checked before
// auth.DeviceIDFromContext — see authenticateDevice's doc comment for
// the precedence rule. This handler's mount point (internal/server/
// wire.go) sits outside the cookie-only WebAuthMiddleware Group so a
// Bearer-only caller (the CLI's WS-based AttachJob) can reach this route
// end-to-end over TCP.
Bearer *auth.BearerVerifier
// KeepalivePeriod overrides how often an idle connection is pinged.
// Zero means defaultWSKeepalivePeriod; tests set it short.
KeepalivePeriod time.Duration
}
WSAttachHandler handles WebSocket connections for interactive PTY attach. Route: GET /api/jobs/{id}/attach/ws
func (*WSAttachHandler) ServeHTTP ¶
func (h *WSAttachHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type WebAppService ¶
type WebAppService struct {
Tasks TaskStore
Actions ActionStore
Jobs JobStore
GlobalJobs GlobalJobStore
Projects ProjectRepository
Meta MetaStore
Workflow WorkflowService
TaskSvc TaskService
Hooks HookService
Answerer TaskAnswerService // optional: enables POST /tasks/{id}/answer
// Commands backs the card detail page's instruction textarea +
// card_commands buttons — nil-safe: a nil Commands makes
// RunCardCommandAsHuman a 501 and CardCommandOptionsForProject report no
// declared commands, same posture as CardHandler.Commands == nil.
Commands CardCommandWebService
}
func (*WebAppService) AnswerSuggestion ¶ added in v0.4.0
func (s *WebAppService) AnswerSuggestion(taskID string, req AnswerSuggestionRequest) error
AnswerSuggestion sends an "answered" action for taskID, recording the user's accept/reject of the currently-shown suggestion — a dedicated method rather than routing through the generic ApplyAction, mirroring ReopenTask's own instruction-payload pattern just above.
func (*WebAppService) AnswerSuggestionWithResult ¶ added in v0.5.0
func (s *WebAppService) AnswerSuggestionWithResult(taskID string, req AnswerSuggestionRequest) (*ActionApplication, error)
func (*WebAppService) AnswerTask ¶
func (s *WebAppService) AnswerTask(ctx context.Context, taskID, questionID, answer string) error
func (*WebAppService) ApplyAction ¶
func (s *WebAppService) ApplyAction(taskID string, actionType string) error
func (*WebAppService) ApplyActionWithResult ¶ added in v0.5.0
func (s *WebAppService) ApplyActionWithResult(taskID string, actionType string) (*ActionApplication, error)
func (*WebAppService) CardCommandOptionsForProject ¶ added in v0.5.0
func (s *WebAppService) CardCommandOptionsForProject(ctx context.Context, projectID string) []CardCommandOption
func (*WebAppService) CardCommandOptionsForWorkspace ¶ added in v0.6.0
func (s *WebAppService) CardCommandOptionsForWorkspace(ctx context.Context, workspaceID string) []CardCommandOption
func (*WebAppService) CreateTask ¶
func (s *WebAppService) CreateTask(ctx context.Context, req CreateTaskRequest) (*orchestrator.Task, error)
func (*WebAppService) DeleteTask ¶
func (s *WebAppService) DeleteTask(id string, force bool) error
DeleteTask delegates to the shared TaskService so the web UI uses the same delete semantics as the JSON API and TUI.
func (*WebAppService) DuplicateTask ¶
DuplicateTask delegates to the shared TaskService so the Web UI uses the same duplication semantics as the JSON API: a fresh task is created via CreateTask + resolveBehavior so that Instructions and Payload come from the behavior's DefaultInstruction / DefaultPayload, not from the source task's runtime state. Without this delegation the duplicate inherited the source's runtime payload (awaiting trait and harness session state) and missing Instructions caused the hook evaluator to skip the agent hook, so no hook fired on Start.
The Web UI button does not auto-start the duplicate; the user clicks Start separately.
func (*WebAppService) GetJob ¶
func (s *WebAppService) GetJob(id string) (*JobWithContext, error)
func (*WebAppService) GetProjectByID ¶
func (s *WebAppService) GetProjectByID(id string) (*orchestrator.Project, error)
func (*WebAppService) GetTaskDetail ¶
func (s *WebAppService) GetTaskDetail(id string) (*TaskDetailView, error)
func (*WebAppService) ListBehaviors ¶
func (s *WebAppService) ListBehaviors() ([]string, error)
func (*WebAppService) ListCardProjects ¶ added in v0.5.0
func (s *WebAppService) ListCardProjects() ([]*orchestrator.Project, error)
func (*WebAppService) ListHooksForStatus ¶
func (s *WebAppService) ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
func (*WebAppService) ListJobs ¶
func (s *WebAppService) ListJobs(status string) ([]JobWithContext, error)
func (*WebAppService) ListProjects ¶
func (s *WebAppService) ListProjects() ([]*orchestrator.Project, error)
func (*WebAppService) ListSessions ¶ added in v0.0.2
func (s *WebAppService) ListSessions() ([]JobWithContext, error)
func (*WebAppService) ListTasks ¶
func (s *WebAppService) ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
func (*WebAppService) ListWorkspaces ¶
func (s *WebAppService) ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
func (*WebAppService) ReopenTask ¶
func (s *WebAppService) ReopenTask(id string, req ReopenTaskRequest) error
func (*WebAppService) ReplayHook ¶
func (s *WebAppService) ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
func (*WebAppService) RerunTask ¶
func (s *WebAppService) RerunTask(id string, req RerunTaskRequest) error
func (*WebAppService) RunCardCommandAsHuman ¶ added in v0.5.0
func (s *WebAppService) RunCardCommandAsHuman(ctx context.Context, cardID, commandKey, instruction string) (*RunCardCommandResult, error)
func (*WebAppService) UpdateTask ¶
func (s *WebAppService) UpdateTask(ctx context.Context, id string, req UpdateTaskRequest) error
type WebHandler ¶
type WebHandler struct {
Service WebService
Hub *TaskEventHub
SessionDispatcher SessionDispatcher
Registry *auth.ConnectionRegistry
// AttachmentsRoot is the data-home directory under which per-task
// attachments (`tasks/<id>/attachments`) are persisted. When empty (e.g.
// :memory: DB during tests) the multipart code path falls back to
// rejecting attachments while still accepting plain form-urlencoded
// submissions.
AttachmentsRoot string
// ConfigService backs GET /settings — nil in any test/wiring that never
// registers the /settings route.
ConfigService SettingsConfigService
// TaskTriage backs the list row's suggestion/summary enrichment.
// Nil-safe: when unset, every row renders with no suggestion edge/
// summary badge instead of failing the whole list.
TaskTriage CardStore
// CardActivity backs the list's execution state and the detail page's
// work/command activity. Nil disables the optional activity projection.
CardActivity CardActivityStore
// CardTimeline backs the card detail page's pinned items and timeline
// history (internal/timeline.BuildCardTimeline/CardPinnedItems). Nil-safe:
// when unset, a card detail page renders with an empty timeline instead of
// failing the whole page.
CardTimeline CardTimelineStore
// OperationResults keeps human operation outcomes visible across reloads.
OperationResults OperationResultStore
}
func (*WebHandler) GetTaskEdit ¶
func (h *WebHandler) GetTaskEdit(w http.ResponseWriter, r *http.Request)
func (*WebHandler) HookReplayList ¶
func (h *WebHandler) HookReplayList(w http.ResponseWriter, r *http.Request)
func (*WebHandler) JobDetail ¶
func (h *WebHandler) JobDetail(w http.ResponseWriter, r *http.Request)
func (*WebHandler) JobTerminal ¶
func (h *WebHandler) JobTerminal(w http.ResponseWriter, r *http.Request)
JobTerminal redirects legacy deep-links (/jobs/{id}/terminal) to the job detail page (/jobs/{id}), which now renders the terminal inline.
func (*WebHandler) PostAction ¶
func (h *WebHandler) PostAction(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostAnswer ¶
func (h *WebHandler) PostAnswer(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostAnswerSuggestion ¶ added in v0.4.0
func (h *WebHandler) PostAnswerSuggestion(w http.ResponseWriter, r *http.Request)
PostAnswerSuggestion handles the task detail page's Accept/Reject buttons on a task_triage suggestion card. answer is required ("accept"/"reject" — validated downstream by answeredPayload); verb/basis are optional and forwarded verbatim from hidden form fields populated from the suggestion currently shown.
func (*WebHandler) PostCardCommand ¶ added in v0.5.0
func (h *WebHandler) PostCardCommand(w http.ResponseWriter, r *http.Request)
PostCardCommand handles the card detail page's command form: the shared instruction textarea plus one submit button per declared card_commands entry (the clicked button's own name="key" value identifies which command to run).
On success it redirects to the card's own page — never a guessed continuation URL — and lets the pinned section resolve and link the new request's continuation once one exists. On Occupied it renders the same page directly instead of redirecting, echoing the just-submitted instruction back into the form: a redirect would have to round-trip a possibly large instruction through a URL, and the caller's typed text must survive an occupied response regardless.
func (*WebHandler) PostDelete ¶
func (h *WebHandler) PostDelete(w http.ResponseWriter, r *http.Request)
PostDelete deletes the task and redirects to the task list. Errors are surfaced via ?error= on the same task page so the user sees the reason (e.g. dependents exist).
func (*WebHandler) PostDuplicate ¶
func (h *WebHandler) PostDuplicate(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostEdit ¶
func (h *WebHandler) PostEdit(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostHookReplay ¶
func (h *WebHandler) PostHookReplay(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostReopen ¶
func (h *WebHandler) PostReopen(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostRerun ¶
func (h *WebHandler) PostRerun(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostStartSession ¶ added in v0.0.6
func (h *WebHandler) PostStartSession(w http.ResponseWriter, r *http.Request)
PostStartSession launches a HarnessAdapter-backed session for the project from the Web UI's [New Session] dialog.
func (*WebHandler) PostTaskCreate ¶
func (h *WebHandler) PostTaskCreate(w http.ResponseWriter, r *http.Request)
func (*WebHandler) QuestionPage ¶
func (h *WebHandler) QuestionPage(w http.ResponseWriter, r *http.Request)
QuestionPage renders the dedicated Q&A turn page at `/tasks/{id}/questions/{question_id}`. The notification deep-link from `boid task notify --ask` lands here. The page shows the question and either an answer form (when this is the active awaiting turn) or the recorded answer (when an answer action exists for the same question_id).
func (*WebHandler) ReopenForm ¶
func (h *WebHandler) ReopenForm(w http.ResponseWriter, r *http.Request)
func (*WebHandler) Routes ¶
func (h *WebHandler) Routes() chi.Router
func (*WebHandler) SessionList ¶ added in v0.0.2
func (h *WebHandler) SessionList(w http.ResponseWriter, r *http.Request)
func (*WebHandler) SessionNew ¶ added in v0.0.2
func (h *WebHandler) SessionNew(w http.ResponseWriter, r *http.Request)
func (*WebHandler) Settings ¶ added in v0.1.0
func (h *WebHandler) Settings(w http.ResponseWriter, r *http.Request)
Settings handles GET /settings: fetches the daemon's current config.yaml (the same document `boid config get` prints), derives the form-editor fields from it, and renders both the form and raw-YAML tabs from that one snapshot.
func (*WebHandler) TaskCardTimelineHead ¶ added in v0.5.0
func (h *WebHandler) TaskCardTimelineHead(w http.ResponseWriter, r *http.Request)
TaskCardTimelineHead re-renders a card's history from the top down through (and including) the item at frontier, as a flat item list with no Load-older control — lets a caller safely replace its own already-loaded head range in place, since an item excluded from that range when it was first loaded can later reappear anywhere within it. frontier empty means walk until history is exhausted.
func (*WebHandler) TaskCardTimelineOlder ¶ added in v0.5.0
func (h *WebHandler) TaskCardTimelineOlder(w http.ResponseWriter, r *http.Request)
TaskCardTimelineOlder returns the next page of a card's timeline history as an HTML fragment ("Load older"): the older items plus a fresh Load-older control, or none once exhausted. Appended by the client (hx-swap="outerHTML" on the button that requested it), never replacing what is already on the page, so earlier pages already loaded survive.
func (*WebHandler) TaskChildDetail ¶ added in v0.5.0
func (h *WebHandler) TaskChildDetail(w http.ResponseWriter, r *http.Request)
TaskChildDetail is the stable entry point for a card child. It resolves to the execution task once one exists; before dispatch (or after task GC) it renders the specification that remains on the parent card.
func (*WebHandler) TaskDetail ¶
func (h *WebHandler) TaskDetail(w http.ResponseWriter, r *http.Request)
func (*WebHandler) TaskDetailFragment ¶
func (h *WebHandler) TaskDetailFragment(w http.ResponseWriter, r *http.Request)
TaskDetailFragment returns a partial HTML fragment for the task detail page. The `kind` query parameter selects which section to render:
- "timeline": action history section (shared by both entity layouts)
- "status": the meta strip — card or execution variant, by task.Type
- "pinned": a card's pinned items only (#task-pinned) — no-op (empty body) for an execution task, which has no such section
func (*WebHandler) TaskEvents ¶
func (h *WebHandler) TaskEvents(w http.ResponseWriter, r *http.Request)
TaskEvents streams Server-Sent Events for a specific task. Subscribes to the TaskEventHub and forwards events until the client disconnects or the device is revoked.
func (*WebHandler) TaskList ¶
func (h *WebHandler) TaskList(w http.ResponseWriter, r *http.Request)
func (*WebHandler) TaskNew ¶
func (h *WebHandler) TaskNew(w http.ResponseWriter, r *http.Request)
type WebManagementHandler ¶
type WebManagementHandler struct {
Pairing Pairer
Store *auth.Store
PublicURL string
Registry *auth.ConnectionRegistry
}
func (*WebManagementHandler) DeleteAllDevices ¶
func (h *WebManagementHandler) DeleteAllDevices(w http.ResponseWriter, r *http.Request)
func (*WebManagementHandler) DeleteDevice ¶
func (h *WebManagementHandler) DeleteDevice(w http.ResponseWriter, r *http.Request)
func (*WebManagementHandler) GetDevices ¶
func (h *WebManagementHandler) GetDevices(w http.ResponseWriter, r *http.Request)
func (*WebManagementHandler) PostPair ¶
func (h *WebManagementHandler) PostPair(w http.ResponseWriter, r *http.Request)
func (*WebManagementHandler) Routes ¶
func (h *WebManagementHandler) Routes() chi.Router
type WebService ¶
type WebService interface {
ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
GetTaskDetail(id string) (*TaskDetailView, error)
ListProjects() ([]*orchestrator.Project, error)
ListBehaviors() ([]string, error)
ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
ApplyAction(taskID string, actionType string) error
DuplicateTask(ctx context.Context, id string) (string, error)
DeleteTask(id string, force bool) error
ListJobs(status string) ([]JobWithContext, error)
ListSessions() ([]JobWithContext, error)
GetJob(id string) (*JobWithContext, error)
CreateTask(ctx context.Context, req CreateTaskRequest) (*orchestrator.Task, error)
UpdateTask(ctx context.Context, id string, req UpdateTaskRequest) error
RerunTask(id string, req RerunTaskRequest) error
ReopenTask(id string, req ReopenTaskRequest) error
AnswerTask(ctx context.Context, taskID, questionID, answer string) error
// AnswerSuggestion backs the accept/reject buttons on the task_triage
// suggestion card. A dedicated method rather than routing through
// ApplyAction (like ReopenTask above): the generic
// WebService.ApplyAction(taskID, actionType) signature has no payload
// parameter, and `answered` needs one ({answer, verb, basis}).
AnswerSuggestion(taskID string, req AnswerSuggestionRequest) error
ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
GetProjectByID(id string) (*orchestrator.Project, error)
// RunCardCommandAsHuman / CardCommandOptionsForProject back the card
// detail page's shared instruction textarea + declared card_commands
// buttons — see CardCommandWebService's own doc comment.
RunCardCommandAsHuman(ctx context.Context, cardID, commandKey, instruction string) (*RunCardCommandResult, error)
CardCommandOptionsForProject(ctx context.Context, projectID string) []CardCommandOption
}
type WorkflowService ¶
type WorkflowService interface {
ApplyAction(ctx context.Context, taskID string, req ApplyActionRequest) (*ActionApplication, error)
// GetCard / ListCards are the task_triage read surface (card_read.go).
// Part of WorkflowService because the brokered ops that
// expose them to the sandbox reach the daemon through this same interface.
GetCard(taskID string) (*CardView, error)
ListCards(filter orchestrator.TaskFilter) ([]*CardView, error)
CompleteJob(ctx context.Context, jobID string, req JobDoneRequest) (*Job, error)
// StopAgent asks the agent backing runtimeID to terminate gracefully,
// without tearing down the surrounding runner-inner-child. The broker's
// `boid job done` call still fires normally, preserving any payload
// patch the agent wrote up to that point. NotifyTask calls this after
// `ApplyAction("ask")` so the awaiting transition does not race with
// payload_patch capture. No-op when runtimeID is empty.
StopAgent(runtimeID string)
}
type WorkspaceDetail ¶ added in v0.0.13
type WorkspaceDetail = apiwire.WorkspaceDetail
type WorkspaceHandler ¶
type WorkspaceHandler struct {
TriggerRunner WorkspaceTriggerRunner
Service ProjectService
// Homes, when non-nil, is the engine-backed view of workspace HOME
// volumes used for Show's size reporting and Remove's home deletion.
// Left nil, both features degrade gracefully: Show omits
// WorkspaceDetail.Home, Remove reports home_deleted=false.
Homes WorkspaceHomeStore
// HomeImporter, when non-nil, serves
// POST /api/workspaces/{slug}/home/import, migrating a pre-existing host
// home directory into the workspace's HOME volume. Left nil, the route
// answers 501.
HomeImporter WorkspaceHomeImporter
}
func (*WorkspaceHandler) Apply ¶ added in v0.1.0
func (h *WorkspaceHandler) Apply(w http.ResponseWriter, r *http.Request)
Apply handles POST /api/workspaces/apply?dry_run=<bool>: the body is exactly one apiVersion:boid.dev/v1 kind:Workspace yaml document (a multi-document body is rejected; `boid workspace apply` sends one request per document, giving each its own all-or-nothing DB transaction). dry_run=true runs every read/write a real apply would but rolls back instead of committing.
dry_run is parsed carefully because a permissive parse here would silently turn into a real commit instead of the requested preview:
- strconv.ParseBool rejects an unparseable value with 400 rather than defaulting to mutation.
- Presence (url.Values.Has), not non-emptiness, gates parsing, so `?dry_run=` or `?dry_run` (no value) is rejected rather than treated as absent.
- The query string is parsed explicitly via url.ParseQuery rather than r.URL.Query(), which silently takes only the first value of a repeated key and swallows a malformed-query error — both now surface as 400 instead of falling through to a real commit.
Which mode ran is always logged at INFO so a caller can confirm from the server log which path a given request actually took.
func (*WorkspaceHandler) Create ¶ added in v0.0.13
func (h *WorkspaceHandler) Create(w http.ResponseWriter, r *http.Request)
Create handles POST /api/workspaces. The body is a yaml document with the target slug inlined (`slug: foo`) alongside the workspace meta fields — there is no URL parameter for the new slug, since the daemon does not yet know it.
func (*WorkspaceHandler) ExportEnvelope ¶ added in v0.1.0
func (h *WorkspaceHandler) ExportEnvelope(w http.ResponseWriter, r *http.Request)
ExportEnvelope handles GET /api/workspaces/export?all=true or ?name=<slug>: returns one or more apiVersion:boid.dev/v1 kind:Workspace yaml documents built from a single atomic DB snapshot (ProjectAppService.ExportWorkspaceEnvelopes), "---"-separated when more than one.
func (*WorkspaceHandler) GetInitScript ¶ added in v0.1.0
func (h *WorkspaceHandler) GetInitScript(w http.ResponseWriter, r *http.Request)
GetInitScript handles GET /api/workspaces/{slug}/init-script: the workspace's init.sh verbatim, with an ETag.
A workspace with no init.sh answers 404 — and still sets the ETag, to the absent sentinel. See WorkspaceInitScriptAbsentRevision for why the sentinel exists, and TestWorkspaceHandler_GetInitScript_AbsentIs404WithTheAbsentETag for why absence cannot be a 200 with an empty body.
func (*WorkspaceHandler) ImportHome ¶ added in v0.1.0
func (h *WorkspaceHandler) ImportHome(w http.ResponseWriter, r *http.Request)
ImportHome handles POST /api/workspaces/{slug}/home/import: replace slug's HOME volume with the tar stream on the request body.
Order of the checks is the contract, not a style choice. Everything that can refuse WITHOUT side effects happens first — media type, workspace row, importer wired — because the first thing the daemon does once past them is destroy the existing home volume.
func (*WorkspaceHandler) List ¶
func (h *WorkspaceHandler) List(w http.ResponseWriter, r *http.Request)
func (*WorkspaceHandler) PutInitScript ¶ added in v0.1.0
func (h *WorkspaceHandler) PutInitScript(w http.ResponseWriter, r *http.Request)
PutInitScript handles PUT /api/workspaces/{slug}/init-script[?force=true]: replace the workspace's init.sh with the request body, gated by If-Match unless force is set — the same convention PUT /api/workspaces/{slug} and POST /api/config already established (428 when If-Match is missing, 412 when it is stale).
An EMPTY body clears the script rather than storing zero bytes; see workspaceInitScriptContentIsAbsent.
func (*WorkspaceHandler) Remove ¶ added in v0.0.13
func (h *WorkspaceHandler) Remove(w http.ResponseWriter, r *http.Request)
Remove handles DELETE /api/workspaces/{slug}. The reserved default slug and re-assignment of any still-assigned project are enforced at the service/repository layer (ProjectAppService.RemoveWorkspace → orchestrator.WorkspaceRepository.Remove's transaction).
The workspace row is removed first (h.Service.RemoveWorkspace); only then does this attempt to delete the workspace's home volume — trusted-side, since only the daemon can reach its own docker socket. A home-deletion failure (e.g. the engine's 409 for a volume a running job still holds) is reported in the response rather than turned into an error: the row is already gone, and a part-completed outcome here is an accepted tradeoff over trying to make the two deletions atomic.
Both deletions run inside the exclusion held below so they cannot interleave with `boid workspace import-home`, which would otherwise leave a volume full of credentials that no dispatch can mount and this endpoint can no longer target.
The workspace's init.sh is a third piece, deleted by RemoveWorkspace itself (not here) under the service's own mutex, so it can't be inherited by a later workspace created under the same slug before cleanup runs.
func (*WorkspaceHandler) Routes ¶
func (h *WorkspaceHandler) Routes() chi.Router
func (*WorkspaceHandler) RunTrigger ¶ added in v0.6.0
func (h *WorkspaceHandler) RunTrigger(w http.ResponseWriter, r *http.Request)
RunTrigger handles POST /api/workspaces/{slug}/triggers/{name}/run.
func (*WorkspaceHandler) Show ¶ added in v0.0.13
func (h *WorkspaceHandler) Show(w http.ResponseWriter, r *http.Request)
Show handles GET /api/workspaces/{slug} (Step D): meta + summary (revision, assigned project ids), with an ETag response header mirroring the revision so a client can round-trip it straight into a subsequent PUT's If-Match.
func (*WorkspaceHandler) Update ¶ added in v0.0.13
func (h *WorkspaceHandler) Update(w http.ResponseWriter, r *http.Request)
Update handles PUT /api/workspaces/{slug}: whole-document replace, gated by If-Match unless ?force=true is passed. See ProjectAppService.UpdateWorkspace for the exact status code contract (428 missing If-Match, 412 stale If-Match).
type WorkspaceHomeImportResponse ¶ added in v0.1.0
type WorkspaceHomeImportResponse struct {
Status string `json:"status"`
// Slug is the NORMALIZED workspace slug the daemon migrated — not
// necessarily the one in the URL, since an empty workspace id normalizes to
// the default workspace.
Slug string `json:"slug"`
// Volume is the home volume that now holds the imported contents,
// dockerres.WorkspaceHomeVolumeName(installID, slug) — the same name
// `boid workspace show` reports and `docker volume rm` takes.
Volume string `json:"volume"`
// HomeID is the identity the NEW incarnation of that volume carries. It
// differs from whatever the replaced one had; that difference is what
// makes the completion marker stale and forces the re-init.
HomeID string `json:"home_id,omitempty"`
// PreviousExisted reports whether there was a home volume to replace.
// false means the workspace had never been dispatched into — the
// init-on-first-dispatch contract, not an error.
PreviousExisted bool `json:"previous_existed"`
// MarkerRemoved / MarkerRemoveError report the deletion of
// <dataHome>/homes-meta/<slug>.init.json. A failure is not fatal (the
// new volume identity already forces the re-init) and is reported anyway.
MarkerRemoved bool `json:"marker_removed"`
MarkerRemoveError string `json:"marker_remove_error,omitempty"`
// MigrationRecordRemoveError is non-empty when the migration succeeded but
// the daemon could not delete the in-progress record it wrote before
// starting (dispatcher's workspace_home_migration_sentinel.go). On the
// wire rather than only in the daemon log because the operator at the
// terminal is the one who can act on it.
MigrationRecordRemoveError string `json:"migration_record_remove_error,omitempty"`
// MigrationRecordDiscardsHome says whether that leftover record still
// authorizes the next daemon start to DESTROY this home. Meaningful only
// alongside MigrationRecordRemoveError.
//
// false is the ordinary case and needs no action: the record was moved
// into its "the home was rebuilt" phase before the deletion failed, so
// recovery only deletes the file. true means it was not, and the next
// daemon start discards this workspace's freshly imported home and
// re-initializes it — the error names the file, so deleting it before
// restarting saves re-doing a multi-GB import.
//
// A separate field rather than something the CLI infers, since both
// failures arrive as "the record could not be removed" and only the
// daemon knows how far it got before that.
MigrationRecordDiscardsHome bool `json:"migration_record_discards_home,omitempty"`
}
WorkspaceHomeImportResponse is the response body for a completed migration.
PreviousExisted and MarkerRemoved are both on the wire rather than folded into a single "ok" because they are two independent re-init legs, and the CLI says something different when only one of them fired: with the marker still in place the re-init rests entirely on the new volume identity, which is true but worth telling an operator about.
type WorkspaceHomeImporter ¶ added in v0.1.0
type WorkspaceHomeImporter interface {
ImportWorkspaceHome(ctx context.Context, slug string, tarStream io.Reader) (dispatcher.WorkspaceHomeImportResult, error)
// BeginWorkspaceHomeRemoval excludes a migration of slug's HOME volume until
// the returned function is called. WorkspaceHandler.Remove brackets BOTH of
// its deletions (the row, then the volume) with it.
//
// The only error it returns wraps dispatcher.ErrWorkspaceHomeBusy, so there
// is exactly one thing to map (409) and the refusal always means "a migration
// of this workspace is running; nothing has been changed".
BeginWorkspaceHomeRemoval(slug string) (done func(), err error)
}
WorkspaceHomeImporter is the daemon-side capability POST /api/workspaces/{slug}/home/import needs. *dispatcher.Runner is the only implementation.
Declared here, on the consumer side, and typed in terms of the plain dispatcher.WorkspaceHomeImportResult struct so this package need not grow moby types, and a test can stub it without an engine.
A nil value is the feature's OFF switch, exactly as a nil WorkspaceHandler.Homes is: server/wire.go leaves it nil when there is no runner to serve it, and the handler answers 501 rather than panicking.
BeginWorkspaceHomeRemoval lives on this same interface, not a field of its own, because the mutual exclusion between removal and migration only works if the object that registers a removal is the SAME object that registers a migration — one interface, one field, one instance, and the compiler enforces it.
type WorkspaceHomeSize ¶ added in v0.0.13
type WorkspaceHomeSize = apiwire.WorkspaceHomeSize
from internal/api/workspace_homes.go
func ListWorkspaceHomeSizes ¶ added in v0.0.13
func ListWorkspaceHomeSizes(ctx context.Context, store WorkspaceHomeStore, lister WorkspaceSlugLister) (homes []WorkspaceHomeSize, listErr string, err error)
ListWorkspaceHomeSizes enumerates every workspace HOME volume belonging to this install and reports each one's size, flagging the ones with no corresponding workspace row as orphans (a workspace.yaml removed while its home volume remains).
Orphan detection depends on a successful WorkspaceSlugLister call. A lister failure means orphan status is simply unknowable for every entry — rather than marking every entry Orphan=true (which would misreport every real workspace's home as an "orphan" on a merely transient DB hiccup), a lister failure omits the listing outright: homes comes back an empty (non-nil) slice, and listErr carries the lister's error message so a caller can render "size listing unavailable: <reason>" instead of trusting bogus per-entry orphan flags. This preserves the invariant "every WorkspaceHomeSize actually returned has a trustworthy Orphan flag".
err (the third return) is reserved for a genuine enumeration failure — the engine's volume listing failing. Unlike listErr, a non-nil err means the whole call failed, not just orphan detection; GC's own record-deletion work does not depend on workspace-home reporting succeeding, so callers should still treat a non-nil err as non-fatal to the rest of their own response.
A sizing failure is neither of those: the store still returns the listing, with SizeError set per entry, because the listing is what drives orphan detection and losing it over a busy disk-usage call would be a much worse trade than an entry rendering "?".
type WorkspaceHomeStore ¶ added in v0.1.0
type WorkspaceHomeStore interface {
Get(ctx context.Context, slug string) dispatcher.WorkspaceHomeVolume
List(ctx context.Context) ([]dispatcher.WorkspaceHomeVolume, error)
Remove(ctx context.Context, slug string) (dispatcher.WorkspaceHomeVolume, bool, error)
}
WorkspaceHomeStore is the engine-backed view of workspace HOME volumes. *dispatcher.WorkspaceHomeVolumeStore is the only implementation; server/wire.go builds one from the single docker client buildRuntime already has and hands it to WorkspaceHandler.Homes / GCHandler.Homes.
Declared here, on the consumer side, so this package can be tested with a map-backed stub — and typed in terms of dispatcher.WorkspaceHomeVolume rather than moby's volume.Volume so no moby type reaches internal/api. internal/api already imports internal/dispatcher; the reverse edge does not exist and must not be created, which is why the data type lives on the dispatcher side.
A nil WorkspaceHomeStore is the feature's OFF switch: server/wire.go leaves the field nil exactly when it has no docker client (the test/DI path), and both handlers then omit home information entirely. A nil interface is also the only form of "off" that cannot be faked by a typed-nil *client.Client, which is why wire.go assigns the field rather than always constructing a store.
type WorkspaceInitScript ¶ added in v0.1.0
type WorkspaceInitScript struct {
Slug string
// Exists is false for a workspace in the pass-through class (no init.sh).
// Content is then empty and Revision is WorkspaceInitScriptAbsentRevision.
Exists bool
Content []byte
// Revision is the ETag: a content hash, or the absent sentinel.
Revision string
// Path is where the DAEMON keeps it.
Path string
}
WorkspaceInitScript is one workspace's init.sh as the API sees it.
type WorkspaceInitScriptResult ¶ added in v0.1.0
type WorkspaceInitScriptResult = apiwire.WorkspaceInitScriptResult
type WorkspaceInitScriptStore ¶ added in v0.1.0
type WorkspaceInitScriptStore interface {
// Path returns the absolute path of slug's init.sh ON THE DAEMON. It is
// reported to the operator, whose editor may well be on a different
// machine; see the CLI's output for how it is labelled.
Path(slug string) (string, error)
// Read returns slug's init.sh, with exists=false and no error when the
// workspace has none.
Read(slug string) (data []byte, exists bool, err error)
// Write publishes data as slug's init.sh, atomically.
Write(slug string, data []byte) error
// Remove deletes slug's init.sh, reporting whether there was one.
Remove(slug string) (removed bool, err error)
}
WorkspaceInitScriptStore is the daemon-side capability the init-script surface needs: read, write and remove a workspace's init.sh at the path the dispatcher reads it from.
Declared here, on the consumer side, and implemented by dispatcher.WorkspaceInitScriptStore — the same split WorkspaceHomeStore/WorkspaceHomeImporter use: the mechanism (where the file is, how it is published) lives with the code that reads it, the policy (If-Match, the cap, the NUL refusal, empty-means-absent) lives here with the workspace rows.
A nil value turns the feature off — the route answers 501 and `apply` warns rather than silently dropping a spec.init_script — for the DI/test daemons that have no dispatcher wiring.
type WorkspaceRemoval ¶ added in v0.1.0
type WorkspaceRemoval struct {
// InitScriptDeleted is true only when the workspace HAD an init.sh and it
// was removed. false covers a workspace that never had one, a daemon with
// no init script store wired, and a failed deletion.
InitScriptDeleted bool
// InitScriptError is the unlink failure, if any. Deliberately NOT a
// *StatusError: the row removal has already committed, so this must not
// become the response's status — see
// WorkspaceRemoveResponse.InitScriptDeleteError. The message carries the
// daemon-side path, which is what an operator needs to clean up by hand.
InitScriptError error
}
WorkspaceRemoval reports what RemoveWorkspace did to the half of a workspace that is not a row.
It exists because a file unlink and a database transaction cannot commit together: by the time the script is touched the row is already gone, so a failure has to be described rather than rolled back or raised. The handler copies both fields into WorkspaceRemoveResponse, which is where their operator-facing meaning is documented.
type WorkspaceRemoveResponse ¶ added in v0.0.13
type WorkspaceRemoveResponse = apiwire.WorkspaceRemoveResponse
type WorkspaceSlugLister ¶ added in v0.0.13
type WorkspaceSlugLister interface {
ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
}
WorkspaceSlugLister exposes the set of currently known workspace slugs, used to flag orphaned home volumes (a workspace HOME volume with no corresponding workspace row). *ProjectAppService already satisfies this via its existing ListWorkspaces method — no new implementation is needed, only threading it through as this narrower interface at the handler construction site (server/wire.go) so GCHandler does not need the whole ProjectService surface.
type WorkspaceStore ¶ added in v0.0.13
type WorkspaceStore interface {
Load(slug string) (*orchestrator.WorkspaceMeta, error)
Save(slug string, meta *orchestrator.WorkspaceMeta) error
// Create is insert-only: an error wrapping os.ErrExist when slug already
// has a row (see orchestrator.WorkspaceRepository.Create).
Create(slug string, meta *orchestrator.WorkspaceMeta) error
Remove(slug string) error
// LoadWithRevision returns meta and its revision from a single atomic
// snapshot, used by GET /api/workspaces/{slug} so meta and revision can
// never straddle a concurrent write. See
// orchestrator.WorkspaceRepository.LoadWithRevision's doc comment.
LoadWithRevision(slug string) (*orchestrator.WorkspaceMeta, string, error)
// UpdateIfRevisionMatches performs a compare-and-swap update: meta is
// written only if slug's current revision equals expectedRevision,
// atomically with the check. matched=false covers both "no such slug"
// and "revision mismatch" — see
// orchestrator.WorkspaceRepository.UpdateIfRevisionMatches's doc comment.
UpdateIfRevisionMatches(slug string, expectedRevision string, meta *orchestrator.WorkspaceMeta) (newRevision string, matched bool, err error)
}
WorkspaceStore provides direct CRUD over a single workspace's WorkspaceMeta, independent of the project-assignment bookkeeping that lives on ProjectRepository below. Implemented by *orchestrator.WorkspaceStore (via ProjectStore.WorkspaceStore()), wired in internal/server/wire.go.
type WorkspaceTriggerRunner ¶ added in v0.6.0
Source Files
¶
- action.go
- action_list_read.go
- apiwire_aliases.go
- attachment_read_linux.go
- attachments.go
- attrs_set_done.go
- blocking_ask_registry.go
- broker.go
- card_child_fanout.go
- card_command_launcher.go
- card_handler.go
- card_read.go
- card_request_auto_dispatch.go
- card_request_dispatch_loop.go
- card_request_release_handler.go
- config.go
- device_auth.go
- events_handler.go
- gc.go
- helpers.go
- host_commands.go
- job.go
- job_log_sse.go
- job_model.go
- machine_select.go
- oauth_login.go
- payload_patch_lock.go
- project.go
- project_identity.go
- project_service.go
- project_service_init_script.go
- queue_notify.go
- queue_sweep.go
- secret.go
- service.go
- session.go
- signal_handler.go
- store.go
- suggestion_accept.go
- task.go
- task_ask.go
- task_context.go
- task_create.go
- task_event_hub.go
- task_field.go
- task_identity.go
- task_identity_handler.go
- task_notify.go
- task_resolve_or_capture.go
- task_service.go
- task_wait.go
- task_wait_registry.go
- trigger_loop.go
- web.go
- web_card_create.go
- web_service.go
- web_settings.go
- workflow.go
- workflow_action.go
- workflow_card.go
- workflow_job.go
- workflow_replay.go
- workspace.go
- workspace_home_import.go
- workspace_homes.go
- workspace_init_script.go
- ws_attach.go