Documentation
¶
Overview ¶
Package protocol — approval lifecycle wire protocol (feature 193).
This file defines the daemon→PWA wire constants and payloads added in feature 193 to fix approval gates re-appearing after approve/reject. The fix introduces two new wire types:
MsgApprovalResolved: tombstone broadcast on every approval terminal state (allow / allow_session / deny / timeout / canceled / superseded). Drives live multi-client convergence (Slack chat.update / GitHub waiting-deployments / Buildkite block-step pattern). PWA dismisses the ApprovalGate modal upon receipt; ANY client that decided AND any other client showing the same approval converges via this single signal.
MsgPendingApprovalState: control-state signal emitted during reconnect metadata bootstrap. Triggers setPendingApproval on the PWA WITHOUT entering chat history. Reuses the existing ApprovalPayload struct shape (defined in agentd/internal/session/types.go); only the outer wire-type constant differs from MsgApproval. The daemon re-stamps `ts` per emission so the PWA's seenMessageKeys dedup key changes — bypasses the existing dedupe naturally without weakening it.
The DAEMON is the source of truth for the Msg* constants in this file. Matching constants live in agentd/internal/session/wsserver.go (planned for feature 193 implementation) with init() panic cross-checks at daemon startup — same drift-prevention pattern as agentd-protocol/history.go ↔ agentd/internal/session/wsserver_history.go.
Package protocol — bidirectional Claude↔Codex governed delegation wire protocol (delegation feature, Phase 1).
This file defines the delegation MessageType payloads, the engine and lifecycle string constants, the additive approval-attribution fields, and the durable delegation-link schema replayed across daemon restarts.
These wire types are MessageType frames (the outer AgentMessage.Type), NOT ControlType frames. The relay forwards them opaquely; the daemon and PWA discriminate by the outer AgentMessage.Type. They follow the same daemon-is-source-of-truth convention as the approval wire types in approval.go: matching constants live in the daemon's agentd/internal/session/ with init() panic cross-checks at startup (Phase 3).
Engine values are the stable wire strings "claude" | "codex". All optional fields use json:",omitempty" so older producers/consumers stay byte compatible (backward compatible per CLAUDE.md "Backward Compatible").
Package protocol defines the shared wire protocol types for the AgentD relay system. Both the daemon (agentd) and relay server (agentd-relay) import this module to guarantee type identity across the WebSocket JSON contract.
This module has zero external dependencies — only encoding/json, time, crypto/rand, and encoding/hex.
Package protocol — git sync wire protocol (feature 172).
This file defines the request/response types, streaming progress events, and classified error codes for the git sync action family (branch list, branch switch, fetch, pull, push, cancel, stash management) introduced in feature 172 and extended in feature 206.
The DAEMON is the source of truth for every Msg* constant in this file. A matching constant block lives in agentd/internal/session/wsserver_gitsync.go with an init() panic that cross-checks equality at daemon startup — the explicit drift prevention for the feature 170 incident class.
Package protocol - selected-session transcript history paging wire protocol.
Package protocol — git worktrees wire protocol (feature 173).
This file defines the request/response types, streaming progress events, broadcast payloads, and classified error codes for the git worktree management family (list, add, remove, lock/unlock, prune, session switch) introduced in feature 173.
The DAEMON is the source of truth for every Msg* constant in this file. A matching constant block lives in agentd/internal/session/wsserver_worktrees.go (added in a later phase) with an init() panic that cross-checks equality at daemon startup — the explicit drift prevention for the feature 170 incident class (see specs/170-fix-mcp-wire-drift/spec.md).
Index ¶
- Constants
- Variables
- func IsJSONRPCRequest(data []byte) bool
- func IsKnownCodexSandboxMode(mode CodexSandboxMode) bool
- func IsKnownCommandReceiptReasonCode(code CommandReceiptReasonCode) bool
- func IsKnownCommandReceiptStage(stage CommandReceiptStage) bool
- func IsKnownEngine(engine string) bool
- func IsKnownSessionFeatureReasonCode(code SessionFeatureReasonCode) bool
- func IsKnownSessionFeatureState(state SessionFeatureState) bool
- func KnownEngines() []string
- func NewSupportBundleID(unixMS int64, counter uint64) string
- func NewTraceID() string
- func StartDelegationAwaitOrDefault(raw json.RawMessage) bool
- func ValidTraceID(s string) bool
- func Validate(cfg *MCPServerConfig) error
- func ValidateCommandReceipt(r CommandReceiptPayload) error
- func ValidateName(name string) error
- func ValidateRemote(cfg *MCPServerConfig) error
- func ValidateScope(scope MCPServerScope) error
- func ValidateStdio(cfg *MCPServerConfig) error
- func ValidateTransport(transport string) error
- type AckPayload
- type AgentCapability
- type AgentDErrorData
- type AgentDEventEnvelope
- type AgentExtensionDef
- type AgentExtensionInvocation
- type AgentExtensionKind
- type AgentExtensionScope
- type ApprovalAttribution
- type ApprovalResolvedPayload
- type AuditEntryPayload
- type ClientConnectedPayload
- type ClientCountPayload
- type CodexSandboxMode
- type CommandReceiptPayload
- type CommandReceiptReasonCode
- type CommandReceiptStage
- type ConnectionPhase
- type ControlMessage
- type ControlType
- type CostPayload
- type DeactivateDeveloperPayload
- type DelegationCancelAckPayload
- type DelegationCancelPayload
- type DelegationForceAbortPayload
- type DelegationLinkPayload
- type DelegationResultPayload
- type DelegationStatusPayload
- type EntitlementUpdatePayload
- type EntitlementViolationPayload
- type ErrorPayload
- type EventType
- type GitBranch
- type GitBranchListRequest
- type GitBranchListResponse
- type GitBranchSwitchRequest
- type GitBranchSwitchResponse
- type GitDiffRequest
- type GitDiffResponse
- type GitFetchRequest
- type GitFetchResponse
- type GitFileStatus
- type GitNotAvailablePayload
- type GitPullRequest
- type GitPullResponse
- type GitPushRequest
- type GitPushResponse
- type GitStashApplyRequest
- type GitStashApplyResponse
- type GitStashDropRequest
- type GitStashDropResponse
- type GitStashEntry
- type GitStashListRequest
- type GitStashListResponse
- type GitStashPopRequest
- type GitStashPopResponse
- type GitStashPushRequest
- type GitStashPushResponse
- type GitStatusPayload
- type GitStatusRequest
- type GitSyncCancelRequest
- type GitSyncCancelResponse
- type GitSyncProgressPayload
- type GitWorktreeAddRequest
- type GitWorktreeAddResponse
- type GitWorktreeAddedPayload
- type GitWorktreeListRequest
- type GitWorktreeListResponse
- type GitWorktreeLockRequest
- type GitWorktreeLockResponse
- type GitWorktreeProgressPayload
- type GitWorktreePruneRequest
- type GitWorktreePruneResponse
- type GitWorktreeRemoveRequest
- type GitWorktreeRemoveResponse
- type GitWorktreeRemovedPayload
- type GitWorktreeUnlockRequest
- type GitWorktreeUnlockResponse
- type GitWorktreeUpdatedPayload
- type HistoryPagePayload
- type HistoryPageRequest
- type InteractivePromptResolvedPayload
- type JSONRPCError
- type JSONRPCID
- type JSONRPCRequest
- type JSONRPCResponse
- type JoinPayload
- type KeyRotatePayload
- type MCPListPayload
- type MCPListResponse
- type MCPMutationPayload
- type MCPMutationResponse
- type MCPReconnectPayload
- type MCPRemovePayload
- type MCPServerConfig
- type MCPServerScope
- type MCPServerStatusEntry
- type MCPServersChangedPayload
- type MCPTogglePayload
- type Method
- type NormalizedSupportBundleParams
- type PersistedDelegationLink
- type PolicyJSON
- type PolicyMatchJSON
- type ProtocolHelloOffer
- type ProtocolHelloParams
- type ProtocolHelloResult
- type ProviderCapabilityContract
- type ProviderCapabilitySource
- type ProviderCapabilitySupport
- type ProviderCommandArgumentRequirement
- type ProviderCommandDescriptor
- type ProviderCommandLifecycle
- type ProviderCommandStatusAfterDispatch
- type ProviderFeatureDescriptor
- type PushNotifyPayload
- type PushNotifyResultPayload
- type RateLimitBucket
- type RateLimitsUpdatedPayload
- type RegisterPayload
- type RelayEnvelope
- type RouteReceiptPayload
- type SessionFeature
- type SessionFeatureReasonCode
- type SessionFeatureState
- type SessionFeatureStatusPayload
- type SessionHeadPayload
- type SessionInfo
- type SessionRecoveryAction
- type SessionRecoveryInfo
- type SessionRecoveryReason
- type SessionWorktreeChangedPayload
- type SessionWorktreeSwitchRequest
- type SessionWorktreeSwitchResponse
- type StartDelegationPayload
- type StatusPayload
- type StatusUpdatePayload
- type SupportBundle
- type SupportBundleClient
- type SupportBundleContext
- type SupportBundleDaemon
- type SupportBundleParams
- type SupportBundleTransport
- type SupportClientDiagnostics
- type SupportConfigSourceKind
- type SupportConfigSourceSummary
- type SupportErrorRef
- type SupportEventEntry
- type SupportHistoryHydrationState
- type SupportPartialReason
- type SupportRedaction
- type SupportRelayDiagnostics
- type SupportRelayURLCategory
- type SyncPoliciesPayload
- type TerminateSessionAckPayload
- type TerminateSessionPayload
- type TransportKind
- type TransportPingParams
- type TransportPongResult
- type Worktree
Constants ¶
const ( // MsgApprovalResolved is the daemon→PWA tombstone broadcast on every // approval terminal state. Carries the approval_id, session_id, the // terminal decision string, and the resolution timestamp. MsgApprovalResolved = "approval_resolved" // MsgPendingApprovalState is the daemon→PWA control-state signal // emitted during bootstrap for any approval still pending in the // daemon's pendingApprovals map. Reuses the ApprovalPayload struct // shape; only the wire-type constant differs from MsgApproval. PWA // handler MUST early-return BEFORE addMessage so the state frame does not // duplicate chat-history bubbles (see ChatView.tsx filter // behavior — approvals render as bubbles by default). MsgPendingApprovalState = "pending_approval_state" )
Message-type constants — DAEMON-side source of truth. Mirrors MUST exist in agentd/internal/session/ with init() panic cross-check that the values agree at daemon startup.
const ( // ApprovalDecisionAllow — user approved (or auto-allowed by policy). ApprovalDecisionAllow = "allow" // ApprovalDecisionAllowSession — user approved with session-scoped // trust for the exact tool+command tuple. ApprovalDecisionAllowSession = "allow_session" // ApprovalDecisionDeny — user denied (or auto-denied by policy). ApprovalDecisionDeny = "deny" // ApprovalDecisionTimeout — TTL elapsed without a user decision. // Daemon emits this only for approvals with a positive configured timeout. ApprovalDecisionTimeout = "timeout" // ApprovalDecisionCanceled — SDK outer context was canceled (e.g. // session stopped, agent crashed) while the approval was pending. // Without this signal the modal would orphan on the PWA until the // next terminal status. See feature 193 spec User Story 5. ApprovalDecisionCanceled = "canceled" // ApprovalDecisionSuperseded is retained as a stable wire value for // backward compatibility with daemons that emitted synthetic denies before // same-session approvals were queued independently. Current daemons should // leave each approval_id pending until its own user decision, timeout, or // cancellation. ApprovalDecisionSuperseded = "superseded" )
ApprovalDecision values used in ApprovalResolvedPayload.Decision. These string constants document the canonical values; the daemon and PWA both serialize/deserialize from this set. Values are stable wire strings — changing them is a breaking change requiring all 3 repos to update in lockstep.
const ( // MsgPing and MsgPong are application-level liveness probes forwarded over // local and encrypted relay session transports. MsgPing = "ping" MsgPong = "pong" // MsgJSONRPCResponse is a migration bridge for encrypted relay responses. // Local v2 transports may send JSON-RPC responses as raw frames; relay // dispatch historically emits AgentMessage envelopes, so this type carries a // JSON-RPC response payload without exposing decrypted content to the relay. MsgJSONRPCResponse = "jsonrpc_response" )
const ( PushNotifyStatusAccepted = "accepted" PushNotifyStatusRetryable = "retryable" PushNotifyStatusPermanent = "permanent" )
const ( // EngineClaude identifies a Claude Code agent endpoint. EngineClaude = "claude" // EngineCodex identifies an OpenAI Codex agent endpoint. EngineCodex = "codex" )
Engine values identify which underlying AI agent owns a delegation endpoint. These are stable wire strings shared by every delegation payload's *Engine field; changing either is a breaking change across all 3 repos.
const ( // MsgDelegationLink is sent by the source to the delegate over the relay // when a delegation begins. Carries both session identities and engines. MsgDelegationLink = "delegation_link" // MsgDelegationStatus is sent by the delegate to the source over the relay // to report link state changes (pending → active → completed → cancelled). MsgDelegationStatus = "delegation_status" // MsgDelegationResult is sent by the delegate to the source when the // delegation reaches a terminal status. Carries the final status, a // human-readable summary, and an optional pass/fail classification. MsgDelegationResult = "delegation_result" // MsgDelegationCancel is sent by the source to the delegate to terminate // an active link. MsgDelegationCancel = "delegation_cancel" // MsgDelegationCancelAck is sent by the daemon to the PWA acknowledging // receipt of a MsgDelegationCancel: the cancel was accepted and graceful // teardown has begun (the source delegation moves to DelegationStateCancelling). // Modeled on the GitSyncCancelResponse ack→terminal split (gitsync.go): this // ACK confirms receipt; the canonical terminal // delegation_result{status:"cancelled"} follows when teardown completes. It // carries ONLY session IDs + the request ID (+ a redacted reason on reject) — // never any delegate output or inherited content. MsgDelegationCancelAck = "delegation_cancel_ack" // MsgDelegationForceAbort is sent by the PWA to the daemon to ESCALATE a // stalled cancel to a hard stop — the named UX escape after the daemon // reports DelegationStateCancelStalled. The daemon hard-stops the delegate // (DelegationStateForceKilled) and still emits the canonical terminal // delegation_result{status:"cancelled"} so old PWAs self-heal. Carries ONLY // the delegate session ID + the request ID. MsgDelegationForceAbort = "delegation_force_abort" // MsgStartDelegation is sent by the PWA to the daemon to USER-initiate a // delegation (the "hand off" trigger): the daemon parks the named source // session (when Await) and spawns a delegate of ToEngine in the source's // working directory. This is the user-initiated counterpart to the // agent-autonomous MCP `delegate` tool path; both converge on the same // daemon spawn machinery. PWA→daemon command frame, forwarded opaquely by // the relay, discriminated by the outer AgentMessage.Type — same convention // as the other four delegation frames. MsgStartDelegation = "start_delegation" )
const ( DelegationStatePending = "pending" DelegationStateActive = "active" DelegationStateCompleted = "completed" DelegationStateCancelled = "cancelled" // DelegationStateRejected is a DelegationStatusPayload-only state (it is // NEVER persisted into PersistedDelegationLink.State — no link is ever // created for a rejected start). It reports that a user-initiated // start_delegation was refused by the daemon BEFORE any delegate session was // spawned (delegation disabled / killswitch off, admission-depth-cycle-writer // reject, unknown engine, source-not-found, quiescence failure). The frame is // keyed by SourceSID (the would-be source session, NOT a delegate — no // DelegateSID exists yet) and carries a redacted Error string the PWA // reconciles onto its per-source delegationStartErrors cell. This closes the // silent-failure gap where a rejected hand-off produced no negative frame and // the StartDelegationSheet had already closed optimistically. DelegationStateRejected = "rejected" // DelegationStateCancelling reports that a cancel request was received and // graceful teardown is in progress (emitted alongside MsgDelegationCancelAck). DelegationStateCancelling = "cancelling" // DelegationStateCancelStalled reports that graceful teardown exceeded the // bounded grace window; the PWA surfaces the force-abort escape hatch. DelegationStateCancelStalled = "cancel_stalled" // DelegationStateForceKilled reports that a force-abort hard-stopped the // delegate. The terminal delegation_result{status:"cancelled"} still follows. DelegationStateForceKilled = "force_killed" )
Link lifecycle states carried in DelegationStatusPayload.State and the durable PersistedDelegationLink.State.
const ( DelegationResultCompleted = "completed" DelegationResultError = "error" DelegationResultCancelled = "cancelled" )
Terminal statuses carried in DelegationResultPayload.Status.
const ( DelegationPassFailPass = "pass" DelegationPassFailFail = "fail" )
Pass/fail classification carried in DelegationResultPayload.PassFail.
const ( DelegationTriggeredByUser = "user" DelegationTriggeredByAuto = "auto" DelegationTriggeredBySystem = "system" )
Triggers carried in DelegationLinkPayload.TriggeredBy and PersistedDelegationLink.TriggeredBy — who initiated the delegation.
const ( DelegationDeliveryStatePending = "pending" DelegationDeliveryStateDelivered = "delivered" DelegationDeliveryStateFailed = "failed" )
Durable handoff first-message delivery states carried in the scalar audit field PersistedDelegationLink.DeliveryState. Empty (absent) means legacy/not-tracked. These are stable wire strings — changing any of them is a breaking change for any consumer that reads the persisted delivery_state audit field.
const ( DelegationValidationStateAwaiting = "awaiting_validation" DelegationValidationStatePassed = "passed" DelegationValidationStateFailed = "failed" )
Durable expected_output validation states carried in the scalar audit field PersistedDelegationLink.ValidationState (task #58 Phase C). Empty (absent) means validation was never engaged (the advisory default, max_validation_retries == 0). These are stable wire strings — changing any of them is a breaking change for any consumer that reads the persisted validation_state audit field.
- "awaiting_validation": a turn-end result did not match expected_output and the daemon issued a bounded re-prompt; a crash in this window recovers as a status-only result (the captured partial rides the encrypted blob, never here).
- "passed": the (re-prompted) result matched the requested shape.
- "failed": the retry budget was exhausted with the result still mismatching; the last captured result is returned advisory-style.
const ( GitDiffStatusModified string = "modified" GitDiffStatusAdded string = "added" GitDiffStatusDeleted string = "deleted" GitDiffStatusRenamed string = "renamed" GitDiffStatusConflict string = "conflict" GitDiffStatusRemoved string = "removed" )
GitDiffStatus enum values for GitDiffResponse.Status.
const ( GitNotAvailableReasonNotARepo string = "not_a_git_repo" GitNotAvailableReasonGitMissing string = "git_binary_missing" GitNotAvailableReasonWorkDirInvalid string = "work_dir_invalid" )
GitNotAvailableReason enum values for GitNotAvailablePayload.Reason.
const ( MsgGitBranchList = "git_branch_list" MsgGitBranchListResponse = "git_branch_list_response" MsgGitBranchSwitch = "git_branch_switch" MsgGitBranchSwitchResponse = "git_branch_switch_response" MsgGitFetch = "git_fetch" MsgGitFetchResponse = "git_fetch_response" MsgGitPull = "git_pull" MsgGitPullResponse = "git_pull_response" MsgGitPush = "git_push" MsgGitPushResponse = "git_push_response" MsgGitSyncProgress = "git_sync_progress" MsgGitSyncCancel = "git_sync_cancel" MsgGitSyncCancelResponse = "git_sync_cancel_response" MsgGitStashList = "git_stash_list" MsgGitStashListResponse = "git_stash_list_response" MsgGitStashPush = "git_stash_push" MsgGitStashPushResponse = "git_stash_push_response" MsgGitStashApply = "git_stash_apply" MsgGitStashApplyResponse = "git_stash_apply_response" MsgGitStashPop = "git_stash_pop" MsgGitStashPopResponse = "git_stash_pop_response" MsgGitStashDrop = "git_stash_drop" MsgGitStashDropResponse = "git_stash_drop_response" )
Message-type constants — DAEMON-side source of truth. Mirror MUST exist in agentd/internal/session/wsserver_gitsync.go with an init() panic cross-check that the two blocks agree at daemon startup.
const ( GitSyncErrAuthFailed = "auth_failed" GitSyncErrSSHPromptHang = "ssh_prompt_hang" GitSyncErrNonFastForward = "non_fast_forward" GitSyncErrMergeConflict = "merge_conflict" GitSyncErrDirtyWorkTree = "dirty_work_tree" GitSyncErrNoUpstream = "no_upstream" GitSyncErrNotAGitRepo = "not_a_git_repo" GitSyncErrNetwork = "network" GitSyncErrCanceled = "canceled" GitSyncErrTimeout = "timeout" GitSyncErrLockedIndex = "locked_index" GitSyncErrNotFound = "not_found" GitSyncErrInternal = "internal" )
Classified error codes. Every GitSync*Response.ErrorCode field holds one of these values (or the empty string when OK is true). The PWA maps each code to a user-facing ErrorBanner headline + suggested-action chips.
const ( // MsgSessionHead is a daemon->PWA announcement of the current durable // per-session head sequence. MsgSessionHead = "session_head" // MsgHistoryPageRequest is a PWA->daemon request for older durable // transcript messages before a sequence boundary. MsgHistoryPageRequest = "history_page_request" // MsgHistoryPage is the daemon->PWA response containing a backward history // page from durable storage. MsgHistoryPage = "history_page" )
Message-type constants for daemon-owned transcript history recovery.
const ( // MsgCommandReceipt is the AgentMessage control type carrying a // CommandReceiptPayload from daemon to PWA. MsgCommandReceipt = "command_receipt" CommandReceiptSchemaVersion = "agentd.command_receipt.v1" )
const ( // MsgSessionFeatureStatus is the AgentMessage type for per-session optional // feature lifecycle updates. MsgSessionFeatureStatus = "session_feature_status" SessionFeatureStatusSchemaVersion = 1 )
const ( SupportBundleSchemaVersion = "agentd.support_bundle.v1" SupportBundleEventLimit = 50 SupportBundleMaxEventLimit = 200 )
const ( // ProtocolV1 names the existing AgentD transport contract before the v2 // JSON-RPC command plane and typed event stream are selected. ProtocolV1 = "agentd.v1" // ProtocolV2 names the dual-stack protocol negotiated between PWA and daemon. ProtocolV2 = "agentd.v2" // AgentDEventProtocolV2 identifies typed streaming event frames. These are // intentionally not JSON-RPC notifications; history pages and session output // need a durable event contract with ordering metadata. AgentDEventProtocolV2 = "agentd.event.v2" JSONRPCVersion = "2.0" )
const ( CapabilityJSONRPCCommands = "jsonrpc.commands" CapabilityTypedEvents = "typed.events" CapabilityTransportPing = "transport.ping" CapabilitySupportBundle = "support.bundle" CapabilitySessionList = "session.list" CapabilitySessionFeatureStatus = "session.feature_status" CapabilityRelayOpaque = "relay.opaque" CapabilityCommandReceipts = "command.receipts" )
const ( JSONRPCParseError = -32700 JSONRPCInvalidRequest = -32600 JSONRPCMethodNotFound = -32601 JSONRPCInvalidParams = -32602 JSONRPCInternalError = -32603 JSONRPCServerBusy = -32000 )
const ( MsgGitWorktreeList = "git_worktree_list" MsgGitWorktreeListResponse = "git_worktree_list_response" MsgGitWorktreeAdd = "git_worktree_add" MsgGitWorktreeAddResponse = "git_worktree_add_response" MsgGitWorktreeAdded = "git_worktree_added" MsgGitWorktreeRemove = "git_worktree_remove" MsgGitWorktreeRemoveResponse = "git_worktree_remove_response" MsgGitWorktreeRemoved = "git_worktree_removed" MsgGitWorktreeLock = "git_worktree_lock" MsgGitWorktreeLockResponse = "git_worktree_lock_response" MsgGitWorktreeUnlock = "git_worktree_unlock" MsgGitWorktreeUnlockResponse = "git_worktree_unlock_response" MsgGitWorktreeUpdated = "git_worktree_updated" MsgGitWorktreePrune = "git_worktree_prune" MsgGitWorktreePruneResponse = "git_worktree_prune_response" MsgGitWorktreeProgress = "git_worktree_progress" MsgSessionWorktreeSwitch = "session_worktree_switch" MsgSessionWorktreeSwitchResponse = "session_worktree_switch_response" MsgSessionWorktreeChanged = "session_worktree_changed" )
Message-type constants — DAEMON-side source of truth. Feature 173.
Mirror MUST exist in agentd/internal/session/wsserver_worktrees.go with an init() panic cross-check that the two blocks agree at daemon startup.
const ( // GitWorktreeErrPathExists — target directory already exists. GitWorktreeErrPathExists = "worktree_path_exists" // GitWorktreeErrPathInvalid — validateWorktreePath rejected the path // (contains forbidden chars, escapes the allowlist, not absolute, etc). GitWorktreeErrPathInvalid = "worktree_path_invalid" // GitWorktreeErrBranchCheckedOut — requested base branch is already // checked out in another worktree. GitWorktreeErrBranchCheckedOut = "worktree_branch_checked_out" // GitWorktreeErrInUse — worktree path is the active workDir for one // or more live sessions; remove is refused to prevent orphaning them. GitWorktreeErrInUse = "worktree_in_use" // GitWorktreeErrPrimary — attempted to remove/switch-to the primary // worktree; primary cannot be removed and cannot be switched away // from via the same code path. GitWorktreeErrPrimary = "worktree_primary" // GitWorktreeErrDirty — worktree has uncommitted changes and the // request did not opt into --force. GitWorktreeErrDirty = "worktree_dirty" // GitWorktreeErrMissing — requested worktree path does not exist in // `git worktree list` output. GitWorktreeErrMissing = "worktree_missing" // GitWorktreeErrBranchInvalid — the requested new-branch name failed // gitops's branch-name validation (contains forbidden chars, starts // with `-`, too long, etc). GitWorktreeErrBranchInvalid = "worktree_branch_invalid" // GitWorktreesDisabled — operator disabled the worktree feature via // gitops.worktrees_enabled=false in daemon config. GitWorktreesDisabled = "worktrees_disabled" )
Classified error codes for worktree operations. The PWA maps each code to a user-facing ErrorBanner headline + suggested-action chips. Feature 173. These codes extend the GitSyncErr* family from gitsync.go but stay scoped to worktree-specific failure modes so the PWA can render tailored messages (e.g., "This branch is already checked out in another worktree").
const MsgInteractivePromptResolved = "interactive_prompt_resolved"
MsgInteractivePromptResolved is the daemon->PWA tombstone broadcast after an interactive prompt answer is accepted by the daemon-side agent adapter.
const MsgRateLimitsUpdated = "rate_limits_updated"
MsgRateLimitsUpdated is the wire-type discriminator for RateLimitsUpdatedPayload. Emitted by the daemon on each AccountRateLimitsUpdated SDK event. Old PWA clients that do not handle the type drop the message silently — graceful degradation.
const ProviderCapabilityContractSchemaVersion = 1
Variables ¶
var ( // ErrInvalidName indicates a server Name failed the name regex or a // reserved-name check. ErrInvalidName = errors.New("mcp: invalid server name") // ErrInvalidTransport indicates Transport is not stdio/sse/http. ErrInvalidTransport = errors.New("mcp: invalid transport") // ErrInvalidScope indicates Scope is not project/user. ErrInvalidScope = errors.New("mcp: invalid scope") // ErrInvalidCommand indicates a stdio Command is empty, too long, or // contains shell metacharacters. ErrInvalidCommand = errors.New("mcp: invalid command") // ErrInvalidArgs indicates stdio Args exceed count or length limits. ErrInvalidArgs = errors.New("mcp: invalid args") // ErrInvalidEnv indicates stdio Env has too many keys, or a key/value // that fails validation. ErrInvalidEnv = errors.New("mcp: invalid env") // ErrInvalidURL indicates sse/http URL is missing, unparseable, too long, // or uses a disallowed scheme. ErrInvalidURL = errors.New("mcp: invalid url") // ErrInvalidHeaders indicates sse/http Headers has too many keys or a // malformed key/value. ErrInvalidHeaders = errors.New("mcp: invalid headers") // ErrInvalidTransportFields indicates transport-exclusive fields are // populated for the wrong transport (e.g., URL set on stdio, Command set // on sse). ErrInvalidTransportFields = errors.New("mcp: transport-exclusive fields mismatched") )
Validation sentinel errors. Use errors.Is to check for a specific class; the wrapper error from Validate contains additional context.
Functions ¶
func IsJSONRPCRequest ¶ added in v0.1.1
func IsKnownCodexSandboxMode ¶ added in v0.1.1
func IsKnownCodexSandboxMode(mode CodexSandboxMode) bool
IsKnownCodexSandboxMode reports whether mode is a valid wire literal.
func IsKnownCommandReceiptReasonCode ¶ added in v0.1.1
func IsKnownCommandReceiptReasonCode(code CommandReceiptReasonCode) bool
func IsKnownCommandReceiptStage ¶ added in v0.1.1
func IsKnownCommandReceiptStage(stage CommandReceiptStage) bool
func IsKnownEngine ¶ added in v0.1.6
IsKnownEngine reports whether engine is one of the recognized delegation engine wire strings (EngineClaude | EngineCodex). It is the shared, cross-module allow-list check: internal/delegation's validateInput and the daemon's session.IsKnownEngine both resolve through this one function so a typo'd or hostile to_engine is rejected identically on every path, closing the silent-drift risk of three independent hardcoded {claude,codex} switches.
func IsKnownSessionFeatureReasonCode ¶ added in v0.1.1
func IsKnownSessionFeatureReasonCode(code SessionFeatureReasonCode) bool
func IsKnownSessionFeatureState ¶ added in v0.1.1
func IsKnownSessionFeatureState(state SessionFeatureState) bool
func KnownEngines ¶ added in v0.1.6
func KnownEngines() []string
KnownEngines returns a freshly allocated copy of the canonical engine allow-list. Callers receive their own slice so the package-level source of truth cannot be mutated. The daemon's session package drift-guards its engineAgentPairs bijection against this set.
func NewSupportBundleID ¶ added in v0.1.1
func NewTraceID ¶
func NewTraceID() string
NewTraceID generates a random W3C-compatible trace ID (32 lowercase hex chars).
Panics on crypto/rand failure. This is an accepted deviation from the "no panic in library code" rule: crypto/rand failure indicates a catastrophic OS-level entropy issue where no cryptographic operation in the system can be trusted (AES-GCM encryption, key generation, token signing). Crashing immediately is safer than continuing with broken cryptography.
func StartDelegationAwaitOrDefault ¶ added in v0.1.6
func StartDelegationAwaitOrDefault(raw json.RawMessage) bool
StartDelegationAwaitOrDefault resolves the governed await semantics for a start_delegation frame from the RAW JSON bytes, applying the absent⇒true rule that the plain-bool StartDelegationPayload.Await field cannot express on its own (omitempty drops an explicit false, so an absent field and an explicit false are indistinguishable after decoding into the struct).
This is the start_delegation analog of delegation.DelegateInput.AwaitOrDefault for the MCP path: it is the SINGLE place the absent⇒true rule is applied for the user-initiated trigger, so both daemon dispatch handlers (local WS and relay) resolve await identically (pattern-consistency dual-path) and a future non-PWA producer that omits await still gets the safe parked default rather than the dangerous fire-and-forget false.
Resolution:
- the "await" key is ABSENT, JSON null, or the bytes do not decode ⇒ true
- the "await" key is present with an explicit boolean (true|false) ⇒ that value
A malformed frame is treated as absent (⇒ true): the safe default is to park, and the caller has already validated the frame's required fields separately.
func ValidTraceID ¶
ValidTraceID returns true if s is a valid W3C trace ID (32 lowercase hex chars, non-zero).
func Validate ¶
func Validate(cfg *MCPServerConfig) error
Validate runs the full validation suite for an MCPServerConfig and returns the first sentinel-wrapped error it finds. Callers should use errors.Is to match the specific ErrInvalidXxx class.
func ValidateCommandReceipt ¶ added in v0.1.1
func ValidateCommandReceipt(r CommandReceiptPayload) error
ValidateCommandReceipt verifies the non-sensitive receipt invariants shared across daemon, PWA fixtures, and production synthetic checks.
func ValidateName ¶
ValidateName checks that name matches the MCP server name rules: byte length ≤64, matches ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$, is not a reserved filename, and contains no path separators or leading dot.
func ValidateRemote ¶
func ValidateRemote(cfg *MCPServerConfig) error
ValidateRemote checks the sse/http-transport fields of cfg: URL must be non-empty, ≤2048 bytes, parseable via net/url.Parse, and either use scheme=https OR have a loopback host (localhost/127.0.0.1/::1) with any scheme. Headers must respect count, RFC 7230 token syntax for keys, and length limits for values. Command/Args/Env must be empty.
func ValidateScope ¶
func ValidateScope(scope MCPServerScope) error
ValidateScope checks that scope is exactly project or user. The CLI's third scope (`local`) is not supported by feature 169.
func ValidateStdio ¶
func ValidateStdio(cfg *MCPServerConfig) error
ValidateStdio checks the stdio-transport fields of cfg: Command must be non-empty, ≤2048 bytes, and contain no shell metacharacters; Args must respect count and length limits; Env keys must match ^[A-Z_][A-Z0-9_]*$ and values must be ≤4096 bytes; there must be no URL or Headers set.
func ValidateTransport ¶
ValidateTransport checks that transport is exactly stdio, sse, or http. The Claude Code CLI also supports an in-process `sdk` transport, which is explicitly out of scope for user-manageable MCP servers — see spec Non-Goals.
Types ¶
type AckPayload ¶
type AckPayload struct {
SessionID string `json:"sid"`
ClientID string `json:"client_id,omitempty"`
}
AckPayload is the relay's acknowledgement of a successful registration or join.
type AgentCapability ¶
type AgentCapability struct {
// Deprecated: As of feature 186 (codex-remaining-gaps), consumers
// should read AnswerQuestionFreeText instead. This field is retained
// verbatim for one release so older PWAs that predate 186 continue to
// render the free-text reply row under the original semantics. The
// PWA consumer chain is `answer_question_free_text ?? answer_question
// ?? true` — new field wins, legacy field is the fallback, default
// favors claude-style rendering. See
// specs/186-codex-remaining-gaps/contracts/answer-question-free-text-capability.md
// for the full two-release deprecation plan.
AnswerQuestion bool `json:"answer_question"`
SendToolResult bool `json:"send_tool_result"`
RewindFiles bool `json:"rewind_files"`
MCPHotApply bool `json:"mcp_hot_apply"`
MCPReconnect bool `json:"mcp_reconnect"`
MCPLiveStatusLimited bool `json:"mcp_live_status_limited"`
SessionScopedApproval bool `json:"session_scoped_approval"`
AnswerQuestionFreeText bool `json:"answer_question_free_text"`
SupportsBypassPermissions bool `json:"supports_bypass_permissions"`
SupportsRuntimeFullAccess bool `json:"supports_runtime_full_access"`
// SupportsDelegation declares whether the daemon will honor a user-initiated
// cross-agent hand-off (start_delegation) for this session. It is a
// DAEMON-WIDE capability (true iff the daemon was started with
// delegation.enabled=true), NOT a per-agent CLI feature, so the Manager
// stamps it from the wired delegation coordinator rather than the per-agent
// adapter's Capabilities() method. The PWA gates the hand-off START affordance
// (SessionCard canStartHandoff) on this flag so a PWA pointed at an
// older / killswitch-off daemon does not render a button that does nothing
// over the relay (Finding #18). Older daemons that predate this field emit it
// absent → the zero value false → the PWA hides the affordance (fail-safe:
// never advertise a hand-off the daemon will silently drop). Default-false is
// the deliberate fallback for an unset capability.
SupportsDelegation bool `json:"supports_delegation"`
}
AgentCapability declares which interactive PWA controls the current agent supports. Older daemons that do not populate this struct will emit it as the zero value (all false) when embedded by pointer with omitempty — PWA falls back to capability-specific defaults when the field is absent.
Feature 186 (codex-remaining-gaps) adds two fields:
- SessionScopedApproval — enables 3rd "Allow for session" ApprovalGate button for agents whose runtime supports session-scoped permission grants (Codex: true; Claude: false). See specs/186-codex-remaining-gaps/contracts/session-scoped-approval-capability.md.
- AnswerQuestionFreeText — whether the free-text reply box applies to agent-initiated AskUserQuestion prompts. Replaces the semantics of AnswerQuestion over a two-release deprecation window. Claude: true; Codex: false (Codex uses structured ElicitationResponse, not free text). See specs/186-codex-remaining-gaps/contracts/answer-question-free-text-capability.md.
The pre-existing AnswerQuestion field is retained verbatim for back-compat per FR-017 deprecation plan.
Feature 188 (MCP parity) adds two more fields:
- MCPReconnect — whether the agent exposes a real reconnect operation for a single MCP server. Claude: true; Codex: false.
- MCPLiveStatusLimited — whether MCP status is inventory-derived / limited rather than a full live-health report. Claude: false; Codex: true.
Feature 195 (bypass-mode-optin) adds one field:
- SupportsBypassPermissions — whether the agent supports runtime switching to "bypass" approval mode. For Claude Code, true iff the daemon was configured with `agents.claude_code.allow_bypass_permissions: true`, which causes the CLI subprocess to launch with `--allow-dangerously-skip-permissions`. Codex: false unconditionally (Codex has its own approval semantics). The PWA reads this flag to decide whether to include "bypass" in the approval-mode cycle. See specs/195-bypass-mode-optin/contracts/agent-capability-bypass.md for the canonical contract.
Feature 229 (codex-runtime-full-access) adds one field:
- SupportsRuntimeFullAccess — whether the live session supports the Codex-only runtime transition to approval_policy=never plus sandbox=danger-full-access. This is true only when the daemon was configured with `agents.codex.allow_runtime_full_access_mode: true`. Claude remains false.
type AgentDErrorData ¶ added in v0.1.1
type AgentDErrorData struct {
AgentDCode string `json:"agentd_code,omitempty"`
Retryable bool `json:"retryable"`
Details json.RawMessage `json:"details,omitempty"`
}
type AgentDEventEnvelope ¶ added in v0.1.1
type AgentDEventEnvelope struct {
Protocol string `json:"protocol"`
ID string `json:"id"`
Type EventType `json:"type"`
Seq uint64 `json:"seq,omitempty"`
SessionID string `json:"session_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
Time time.Time `json:"time"`
Payload json.RawMessage `json:"payload"`
}
AgentDEventEnvelope is the typed v2 streaming envelope used for session output, approvals, prompts, and transport events.
type AgentExtensionDef ¶ added in v0.1.2
type AgentExtensionDef struct {
ID string `json:"id"`
RefID string `json:"ref_id,omitempty"`
Kind AgentExtensionKind `json:"kind"`
Invocation AgentExtensionInvocation `json:"invocation"`
Scope AgentExtensionScope `json:"scope,omitempty"`
Name string `json:"name"`
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
ShortDescription string `json:"short_description,omitempty"`
AcceptsArguments bool `json:"accepts_arguments,omitempty"`
ArgumentHint string `json:"argument_hint,omitempty"`
DefaultPrompt string `json:"default_prompt,omitempty"`
DependencyCount int `json:"dependency_count,omitempty"`
}
AgentExtensionDef is additive UI metadata for a session extension. IDs and RefID are opaque; local provider paths must never be placed on this wire type.
type AgentExtensionInvocation ¶ added in v0.1.2
type AgentExtensionInvocation string
AgentExtensionInvocation describes how a selected extension is invoked.
const ( AgentExtensionInvocationSlashText AgentExtensionInvocation = "slash_text" AgentExtensionInvocationSkillID AgentExtensionInvocation = "skill_id" )
type AgentExtensionKind ¶ added in v0.1.2
type AgentExtensionKind string
AgentExtensionKind classifies one provider-exposed extension surface.
const ( AgentExtensionKindSlashCommand AgentExtensionKind = "slash_command" AgentExtensionKindSkill AgentExtensionKind = "skill" )
type AgentExtensionScope ¶ added in v0.1.2
type AgentExtensionScope string
AgentExtensionScope is the display scope used by operator consoles.
const ( AgentExtensionScopeProject AgentExtensionScope = "project" AgentExtensionScopeGlobal AgentExtensionScope = "global" AgentExtensionScopeBuiltIn AgentExtensionScope = "built_in" AgentExtensionScopeInternal AgentExtensionScope = "internal" )
type ApprovalAttribution ¶ added in v0.1.6
type ApprovalAttribution struct {
SourceSID string `json:"source_sid,omitempty"` // session ID of the source agent that triggered the approval
SourceEngine string `json:"source_engine,omitempty"` // EngineClaude | EngineCodex
// InheritedApprovalMode / InheritedSandboxMode disclose, on a delegate-SPAWN
// approval card, the elevated posture a delegate WILL inherit from its source
// when the operator-enabled, per-call opt-in fires (agentd config
// delegation.inherit_source_approval_mode + the delegate tool's inherit_approval
// arg). They let the human approving the spawn see that the delegate will run
// with permission prompts disabled before granting it. Both omitempty: a spawn
// approval that does not inherit marshals to exactly the bytes it did before
// this feature shipped. Populated by the daemon on the source-session spawn
// approval only — distinct from SourceSID/SourceEngine above, which the daemon
// stamps on approvals raised BY a delegate. Values are agentd approval-mode /
// Codex sandbox-mode strings; this module stays dependency-free and does not
// validate them.
InheritedApprovalMode string `json:"inherited_approval_mode,omitempty"`
InheritedSandboxMode string `json:"inherited_sandbox_mode,omitempty"`
}
ApprovalAttribution pins the additive attribution fields that the daemon embeds into its ApprovalPayload (defined in agentd/internal/session/types.go) so a delegated approval can be traced back to the source agent that triggered it. Both fields use omitempty: an approval emitted without attribution marshals to exactly the bytes it did before this feature shipped, so old PWAs and old daemons remain fully compatible.
The daemon does NOT use this struct by value on the wire; it embeds the same two JSON fields directly into its richer ApprovalPayload (Phase 3). This pin keeps the field names and omitempty contract authoritative in the shared module — the same cross-repo additive-field pattern as StatusPayload / SessionRecoveryInfo in session_recovery.go.
type ApprovalResolvedPayload ¶
type ApprovalResolvedPayload struct {
ApprovalID string `json:"approval_id"`
SessionID string `json:"session_id"`
Decision string `json:"decision"`
ResolvedAt int64 `json:"resolved_at"`
}
ApprovalResolvedPayload is the daemon→PWA tombstone payload broadcast on every approval terminal state. Carried inside an AgentMessage envelope with Type=MsgApprovalResolved.
The PWA matches the payload's ApprovalID against its queued pendingApprovals[sessionId] entries and clears only that approval_id. Idempotent — receiving the same tombstone twice is a no-op on the consumer.
SessionID is required so the PWA can scope the clear to the correct session entry without an additional lookup.
Decision is one of the ApprovalDecision* constants above. PWA logs unknown values at warn level and does NOT clear the modal (defense in depth — better to show stale modal than dismiss on bad signal).
ResolvedAt is a unix-millisecond timestamp captured at the daemon when the resolution occurred. PWA does not act on this field beyond storage/audit.
type AuditEntryPayload ¶
type AuditEntryPayload struct {
Timestamp time.Time `json:"ts"`
SessionID string `json:"session_id"`
DeveloperID string `json:"developer_id"`
AgentType string `json:"agent"`
EventType string `json:"event"`
Tool string `json:"tool,omitempty"`
InputHash string `json:"input_hash,omitempty"`
Decision string `json:"decision,omitempty"`
PolicyName string `json:"policy,omitempty"`
Reason string `json:"reason,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
}
AuditEntryPayload carries a single audit event from daemon to relay. InputHash is sha256hex of raw tool_input JSON bytes — NOT plaintext.
type ClientConnectedPayload ¶
type ClientConnectedPayload struct {
SessionID string `json:"session_id"`
ClientID string `json:"client_id"`
}
ClientConnectedPayload is sent by the relay to the daemon when a PWA client connects or reconnects. ClientID is the relay-assigned connection identity used for targeted bootstrap and history responses; current daemons reject client_connected controls that omit it.
type ClientCountPayload ¶
ClientCountPayload is sent by the relay to the daemon after every client join and disconnect. Informs the daemon of the current connected client count for status and pressure decisions.
type CodexSandboxMode ¶ added in v0.1.1
type CodexSandboxMode string
CodexSandboxMode is the cross-repo wire enum for Codex per-session sandbox startup controls. Values intentionally match the Codex SDK thread/start sandbox literals.
const ( CodexSandboxReadOnly CodexSandboxMode = "read-only" CodexSandboxWorkspaceWrite CodexSandboxMode = "workspace-write" CodexSandboxDangerFullAccess CodexSandboxMode = "danger-full-access" )
func KnownCodexSandboxModes ¶ added in v0.1.1
func KnownCodexSandboxModes() []CodexSandboxMode
KnownCodexSandboxModes returns the daemon/PWA-supported sandbox modes in UI order from safest to most permissive.
type CommandReceiptPayload ¶ added in v0.1.1
type CommandReceiptPayload struct {
SchemaVersion string `json:"schema_version"`
ReceiptID string `json:"receipt_id"`
CommandID string `json:"command_id"`
CommandType string `json:"command_type"`
SessionID string `json:"session_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
Stage CommandReceiptStage `json:"stage"`
Terminal bool `json:"terminal"`
Retryable bool `json:"retryable"`
ReasonCode CommandReceiptReasonCode `json:"reason_code,omitempty"`
ObservedAtUnixMS int64 `json:"observed_at_unix_ms"`
}
CommandReceiptPayload is the redacted daemon-to-PWA receipt for a PWA-originated command. It intentionally contains only stable identifiers, low-cardinality state, and redacted failure classification.
type CommandReceiptReasonCode ¶ added in v0.1.1
type CommandReceiptReasonCode string
const ( CommandReceiptReasonTransportSendFailed CommandReceiptReasonCode = "transport_send_failed" CommandReceiptReasonRelayRouteFailed CommandReceiptReasonCode = "relay_route_failed" CommandReceiptReasonInvalidPayload CommandReceiptReasonCode = "invalid_payload" CommandReceiptReasonSessionNotFound CommandReceiptReasonCode = "session_not_found" CommandReceiptReasonSessionNotActive CommandReceiptReasonCode = "session_not_active" CommandReceiptReasonQueueFull CommandReceiptReasonCode = "queue_full" CommandReceiptReasonProviderNotReady CommandReceiptReasonCode = "provider_not_ready" CommandReceiptReasonProviderSendFailed CommandReceiptReasonCode = "provider_send_failed" CommandReceiptReasonHandlerFailed CommandReceiptReasonCode = "handler_failed" CommandReceiptReasonTimeoutNoDaemonReceipt CommandReceiptReasonCode = "timeout_no_daemon_receipt" )
type CommandReceiptStage ¶ added in v0.1.1
type CommandReceiptStage string
const ( CommandReceiptStageDaemonReceived CommandReceiptStage = "daemon_received" CommandReceiptStageDaemonAccepted CommandReceiptStage = "daemon_accepted" CommandReceiptStageQueued CommandReceiptStage = "queued" CommandReceiptStageDispatched CommandReceiptStage = "dispatched" CommandReceiptStageProviderAccepted CommandReceiptStage = "provider_accepted" CommandReceiptStageResponseStarted CommandReceiptStage = "response_started" CommandReceiptStageCompleted CommandReceiptStage = "completed" CommandReceiptStageFailed CommandReceiptStage = "failed" )
type ConnectionPhase ¶ added in v0.1.1
type ConnectionPhase string
const ( ConnectionPhaseDisconnected ConnectionPhase = "disconnected" ConnectionPhaseConnecting ConnectionPhase = "connecting" ConnectionPhaseNegotiating ConnectionPhase = "negotiating" ConnectionPhaseConnected ConnectionPhase = "connected" ConnectionPhaseStale ConnectionPhase = "stale" ConnectionPhaseReconnecting ConnectionPhase = "reconnecting" )
type ControlMessage ¶
type ControlMessage struct {
Type ControlType `json:"type"`
Payload json.RawMessage `json:"payload"`
}
ControlMessage is the wire format for relay control protocol messages.
type ControlType ¶
type ControlType string
ControlType discriminates control messages in the relay protocol.
const ( CtrlRegister ControlType = "register" CtrlJoin ControlType = "join" CtrlHeartbeat ControlType = "heartbeat" CtrlAck ControlType = "ack" CtrlError ControlType = "error" CtrlSyncPolicies ControlType = "sync_policies" CtrlStatusUpdate ControlType = "status_update" CtrlAuditEntry ControlType = "audit_entry" CtrlDeactivateDeveloper ControlType = "deactivate_developer" CtrlClientConnected ControlType = "client_connected" CtrlClientCount ControlType = "client_count" CtrlKeyRotate ControlType = "key_rotate" CtrlEntitlementUpdate ControlType = "entitlement_update" CtrlEntitlementViolation ControlType = "entitlement_violation" CtrlPushNotify ControlType = "push_notify" CtrlPushNotifyResult ControlType = "push_notify_result" CtrlTerminateSession ControlType = "terminate_session" CtrlTerminateSessionAck ControlType = "terminate_session_ack" CtrlRouteReceipt ControlType = "route_receipt" )
Control message types for the relay protocol.
type CostPayload ¶ added in v0.1.1
type CostPayload struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TurnCostUSD float64 `json:"turn_cost_usd"`
SessionTotal float64 `json:"session_total_usd"`
BudgetLimit float64 `json:"budget_limit_usd"` // 0 = no limit
BudgetRemain float64 `json:"budget_remain_usd"` // 0 = no limit
CachedInputTokens int `json:"cached_input_tokens,omitempty"`
ReasoningOutputTokens int `json:"reasoning_output_tokens,omitempty"`
PricingModel string `json:"pricing_model,omitempty"`
PricingAvailable bool `json:"pricing_available,omitempty"`
TurnCredits float64 `json:"turn_credits,omitempty"`
SessionTotalCredits float64 `json:"session_total_credits,omitempty"`
}
CostPayload is carried by AgentD "cost" messages. The first six fields are the historical wire contract. Later fields are additive and optional so older clients and daemons continue to interoperate.
type DeactivateDeveloperPayload ¶
type DeactivateDeveloperPayload struct {
DeveloperID string `json:"developer_id"`
}
DeactivateDeveloperPayload is sent by the relay to the daemon when a developer is deactivated via SCIM.
type DelegationCancelAckPayload ¶ added in v0.1.9
type DelegationCancelAckPayload struct {
DelegateSID string `json:"delegate_sid"` // delegate agent session ID being cancelled
RequestID string `json:"request_id,omitempty"` // echoes DelegationCancelPayload.RequestID for idempotent client reconcile
Accepted bool `json:"accepted"` // true = teardown started OR already terminal (idempotent); false = could not start
Error string `json:"error,omitempty"` // redacted, client-safe reason when Accepted=false
}
DelegationCancelAckPayload acknowledges a MsgDelegationCancel. Carried inside an AgentMessage envelope with Type=MsgDelegationCancelAck.
This is the ack half of the ack→terminal split modeled on GitSyncCancelResponse (gitsync.go): Accepted=true means the daemon found the link and began graceful teardown (the source delegation moves to DelegationStateCancelling); the canonical terminal delegation_result{status:"cancelled"} follows shortly. Accepted=false with a redacted Error means the cancel could not be started. An already-terminal link is acknowledged Accepted=true (idempotent no-op) so a duplicate or late cancel converges rather than erroring.
SECURITY (no-content-on-wire): carries ONLY session IDs + the request ID + accepted + a redacted reason — never delegate output, inherited context, diffs, or any other content.
type DelegationCancelPayload ¶ added in v0.1.6
type DelegationCancelPayload struct {
DelegateSID string `json:"delegate_sid"` // delegate agent session ID
Reason string `json:"reason,omitempty"` // optional cancellation reason
// RequestID is an at-least-once idempotency key. The daemon de-dupes repeat
// cancels by (delegate_sid, request_id) so a re-sent cancel after a lost ack
// converges rather than double-tearing-down, and echoes it back on the
// MsgDelegationCancelAck so the PWA can reconcile the ack to its in-flight
// request. omitempty keeps a pre-feature cancel frame byte-identical; an
// absent request_id is treated by the daemon as a fresh (non-idempotent) cancel.
RequestID string `json:"request_id,omitempty"`
}
DelegationCancelPayload requests termination of an active link. Carried inside an AgentMessage envelope with Type=MsgDelegationCancel.
type DelegationForceAbortPayload ¶ added in v0.1.9
type DelegationForceAbortPayload struct {
DelegateSID string `json:"delegate_sid"` // delegate agent session ID to hard-stop
RequestID string `json:"request_id,omitempty"` // idempotency key, paired with the originating cancel
}
DelegationForceAbortPayload escalates a stalled cancel to a hard stop. Carried inside an AgentMessage envelope with Type=MsgDelegationForceAbort.
The PWA sends this only after a DelegationStateCancelStalled state (the named escape hatch); the daemon hard-stops the delegate (DelegationStateForceKilled) and emits the canonical terminal delegation_result{status:"cancelled"}. Idempotent: a force-abort on an already-terminal delegate is a benign no-op.
SECURITY (no-content-on-wire): carries ONLY the delegate session ID + the request ID — no content.
type DelegationLinkPayload ¶ added in v0.1.6
type DelegationLinkPayload struct {
SourceSID string `json:"source_sid"` // source agent session ID
SourceEngine string `json:"source_engine"` // EngineClaude | EngineCodex
DelegateSID string `json:"delegate_sid"` // delegate agent session ID
DelegateEngine string `json:"delegate_engine"` // EngineClaude | EngineCodex
WorkDir string `json:"work_dir,omitempty"` // working directory scope for the delegation
TriggeredBy string `json:"triggered_by,omitempty"` // DelegationTriggeredBy* — user | auto | system
CreatedAt int64 `json:"created_at"` // unix milliseconds
// Parked discriminates an await=true delegation (the source agent is PARKED —
// entry.delegating=true — and receives the delegate result as a synthetic
// follow-up turn) from an await=false fire-and-forget delegation (the source is
// NEVER parked and runs concurrently). The PWA derives isParkedSource /
// deleteSuppressed / delegate-list-hiding from this discriminator.
//
// THREE-STATE *bool (Finding #1): a plain bool+omitempty cannot satisfy the two
// back-compat goals simultaneously — Go's json.Marshal drops a false bool, so an
// await=false link and an OLD daemon that never set the field would BOTH serialize
// without a "parked" key (false and absent collapse to identical wire bytes), and
// the PWA's `parked !== false` rule would mislabel a concurrent await=false
// delegation as parked. The field is therefore a *bool (mirroring
// PersistedDelegationLink.Await / StartDelegationPayload.Await):
// - &true (await=true) ⇒ `"parked":true` — source is parked.
// - &false (await=false) ⇒ `"parked":false` — fire-and-forget, NOT parked.
// - nil (legacy/old daemon) ⇒ key omitted — PWA's `parked !== false` reads
// absent⇒undefined⇒true, preserving the pre-field assume-parked default.
// A daemon that DOES set the field always sends the truthful await value, so the
// PWA can distinguish all three states.
Parked *bool `json:"parked,omitempty"`
// InheritedStateSummary is a disclosure-only, compact, human-readable summary of
// the benign source state inherited by the delegate (e.g. "branch X @ <head>,
// model/effort"). It is NOT machine-parsed and carries no inherited context
// content — only a glanceable description for the human and for link history.
// Empty when no inheritance occurred (the default); omitempty keeps the wire
// byte-identical to a pre-feature producer. This follows the same disclosure
// pattern as ApprovalAttribution.InheritedApprovalMode / InheritedSandboxMode and
// the "all optional fields use omitempty" contract at the top of this file.
InheritedStateSummary string `json:"inherited_state_summary,omitempty"`
}
DelegationLinkPayload initiates a delegation from the source agent to the delegate agent. Carried inside an AgentMessage envelope with Type=MsgDelegationLink.
type DelegationResultPayload ¶ added in v0.1.6
type DelegationResultPayload struct {
DelegateSID string `json:"delegate_sid"` // delegate agent session ID
Status string `json:"status"` // DelegationResult* — completed | error | cancelled
Summary string `json:"summary"` // human-readable result summary
DiffSummary string `json:"diff_summary,omitempty"` // final changeset summary
PassFail string `json:"pass_fail,omitempty"` // DelegationPassFail* — pass | fail completion classification
}
DelegationResultPayload terminates a delegation with its final status. Carried inside an AgentMessage envelope with Type=MsgDelegationResult.
type DelegationStatusPayload ¶ added in v0.1.6
type DelegationStatusPayload struct {
DelegateSID string `json:"delegate_sid"` // delegate agent session ID (EMPTY on a rejection frame)
State string `json:"state"` // DelegationState* — pending | active | completed | cancelled | rejected
DiffSummary string `json:"diff_summary,omitempty"` // optional human-readable summary of changes so far
UpdatedAt int64 `json:"updated_at,omitempty"` // unix milliseconds
// SourceSID is populated ONLY on a DelegationStateRejected frame to key the
// rejection to the would-be source session (a normal live-status frame leaves
// it empty; omitempty drops it so the wire bytes are unchanged for the live
// path). The PWA reconciles a rejection onto delegationStartErrors[source_sid].
SourceSID string `json:"source_sid,omitempty"`
// Error is the redacted, human-readable rejection reason surfaced on the
// source SessionCard. Populated ONLY on a DelegationStateRejected frame;
// omitempty drops it for the live-status path. It MUST be a safe,
// client-appropriate string (no internal paths / state) per the
// redact-before-PWA error-handling rule.
Error string `json:"error,omitempty"`
}
DelegationStatusPayload reports a link state change from the delegate back to the source. Carried inside an AgentMessage envelope with Type=MsgDelegationStatus.
Two usage shapes share this struct:
- Live link status (the original shape): keyed by DelegateSID, State is one of pending | active | completed | cancelled.
- Daemon rejection of a user-initiated start_delegation (additive, backward compatible): State=DelegationStateRejected, SourceSID identifies the would-be source session, Error carries a redacted human-readable reason, and DelegateSID is EMPTY (no delegate was ever spawned). SourceSID and Error are both omitempty, so every pre-existing live-status emit marshals to exactly the bytes it did before this field pair was added — old daemons and old PWAs stay byte-compatible.
type EntitlementUpdatePayload ¶ added in v0.1.1
type EntitlementUpdatePayload struct {
Plan string `json:"plan"`
BillingStatus string `json:"billing_status"`
ActiveSessionLimit int `json:"active_session_limit"`
CurrentActiveSessions int `json:"current_active_sessions"`
BufferTTLSeconds int `json:"buffer_ttl_seconds"`
BlockedReason string `json:"blocked_reason,omitempty"`
UpdatedAt int64 `json:"updated_at"`
}
EntitlementUpdatePayload is sent by hosted relay to daemon after registration and when hosted entitlement state changes. It is daemon-only and never sent to PWA clients.
type EntitlementViolationPayload ¶ added in v0.1.1
type EntitlementViolationPayload struct {
AgentSessionID string `json:"agent_session_id"`
Reason string `json:"reason"`
Plan string `json:"plan"`
ActiveSessionLimit int `json:"active_session_limit"`
CurrentActiveSessions int `json:"current_active_sessions"`
Message string `json:"message,omitempty"`
OccurredAt int64 `json:"occurred_at"`
}
EntitlementViolationPayload is sent by hosted relay to daemon when one active hosted agent session is rejected by the account entitlement limit.
type ErrorPayload ¶
type ErrorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable,omitempty"`
Terminal bool `json:"terminal,omitempty"`
RetryAfterMS int `json:"retry_after_ms,omitempty"`
}
ErrorPayload is the relay's error response to a failed control operation.
type EventType ¶ added in v0.1.1
type EventType string
const ( EventTransportConnected EventType = "transport.connected" EventTransportDisconnected EventType = "transport.disconnected" EventTransportPong EventType = "transport.pong" EventSessionListUpdated EventType = "session.list.updated" EventSessionFeatureStatus EventType = "session.feature_status" EventSessionOutputDelta EventType = "session.output.delta" EventThinkingDelta EventType = "session.thinking.delta" EventApprovalRequested EventType = "approval.requested" EventApprovalResolved EventType = "approval.resolved" EventPromptRequested EventType = "prompt.requested" EventCommandReceipt EventType = "command.receipt" EventError EventType = "error" )
type GitBranch ¶
type GitBranch struct {
Name string `json:"name"`
IsCurrent bool `json:"is_current"`
Upstream string `json:"upstream,omitempty"`
Ahead int `json:"ahead"`
Behind int `json:"behind"`
LastCommitAt int64 `json:"last_commit_at"`
LastCommitSha string `json:"last_commit_sha,omitempty"`
}
GitBranch is a single row in the branch switcher. Transient per request. Sorted by LastCommitAt descending for MRU behavior in the UI.
type GitBranchListRequest ¶
type GitBranchListRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
}
GitBranchListRequest — PWA → daemon.
type GitBranchListResponse ¶
type GitBranchListResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
CurrentBranch string `json:"current_branch,omitempty"`
Branches []GitBranch `json:"branches,omitempty"`
}
GitBranchListResponse — daemon → PWA. Echoes RequestID.
type GitBranchSwitchRequest ¶
type GitBranchSwitchRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Branch string `json:"branch"`
StashDirty bool `json:"stash_dirty"`
}
GitBranchSwitchRequest — PWA → daemon. First request always has StashDirty=false; on DirtyRequired=true response, the PWA opens the ConfirmRail and retries with StashDirty=true.
type GitBranchSwitchResponse ¶
type GitBranchSwitchResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
NewBranch string `json:"new_branch,omitempty"`
StashRef string `json:"stash_ref,omitempty"`
DirtyRequired bool `json:"dirty_required,omitempty"`
}
GitBranchSwitchResponse — daemon → PWA.
type GitDiffRequest ¶
type GitDiffRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Path string `json:"path"`
}
GitDiffRequest is the PWA → daemon request for one file's unified diff. Path must be repo-root-relative and must not escape the repo root.
type GitDiffResponse ¶
type GitDiffResponse struct {
RequestID string `json:"request_id"`
Path string `json:"path"`
Status string `json:"status"`
IsBinary bool `json:"is_binary"`
IsRedacted bool `json:"is_redacted"`
IsTruncated bool `json:"is_truncated"`
DiffText string `json:"diff_text"`
SizeBytes int64 `json:"size_bytes"`
Insertions int `json:"insertions"`
Deletions int `json:"deletions"`
}
GitDiffResponse is the daemon → PWA response carrying one file's diff (or a safe placeholder state). DiffText is raw unified diff and is empty when IsBinary, IsRedacted, or Status is "removed".
type GitFetchRequest ¶
type GitFetchRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Remote string `json:"remote,omitempty"`
Prune bool `json:"prune,omitempty"`
}
GitFetchRequest — PWA → daemon. Empty Remote triggers git-native default resolution (upstream-tracking → origin → fail). See FR-003a in spec.md.
type GitFetchResponse ¶
type GitFetchResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
FetchedAt int64 `json:"fetched_at"`
}
GitFetchResponse — daemon → PWA.
type GitFileStatus ¶
type GitFileStatus struct {
Path string `json:"path"`
OrigPath string `json:"orig_path,omitempty"`
XY string `json:"xy"`
IsStaged bool `json:"is_staged"`
IsUntracked bool `json:"is_untracked"`
IsConflict bool `json:"is_conflict"`
IsRename bool `json:"is_rename"`
Insertions int `json:"insertions"`
Deletions int `json:"deletions"`
IsBinary bool `json:"is_binary"`
IsRedacted bool `json:"is_redacted"`
SizeBytes int64 `json:"size_bytes"`
}
GitFileStatus describes one dirty file reported by `git status --porcelain=v2`. Shipped inside GitStatusPayload.Files. Paths are repo-root-relative and never absolute.
type GitNotAvailablePayload ¶
GitNotAvailablePayload is a one-shot notice emitted when gitwatch cannot observe a session (WorkDir is not a git repo, or git binary missing).
type GitPullRequest ¶
type GitPullRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Rebase bool `json:"rebase,omitempty"`
}
GitPullRequest — PWA → daemon. Rebase=false (default) → --ff-only.
type GitPullResponse ¶
type GitPullResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
NewHead string `json:"new_head,omitempty"`
FilesChanged int `json:"files_changed,omitempty"`
}
GitPullResponse — daemon → PWA.
type GitPushRequest ¶
type GitPushRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Remote string `json:"remote,omitempty"`
ForceWithLease bool `json:"force_with_lease,omitempty"`
Force bool `json:"force,omitempty"`
SetUpstream bool `json:"set_upstream,omitempty"`
}
GitPushRequest — PWA → daemon. Force semantics:
ForceWithLease=true, Force=false → --force-with-lease (safe) Force=true, ForceWithLease=false → raw --force (unsafe, advanced UI) both false → plain push both true → daemon rejects with GitSyncErrInternal (ambiguous)
type GitPushResponse ¶
type GitPushResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
PushedRef string `json:"pushed_ref,omitempty"`
}
GitPushResponse — daemon → PWA.
type GitStashApplyRequest ¶ added in v0.1.1
type GitStashApplyRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Ref string `json:"ref"`
AllowDirty bool `json:"allow_dirty,omitempty"`
}
GitStashApplyRequest — PWA → daemon.
type GitStashApplyResponse ¶ added in v0.1.1
type GitStashApplyResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
StashRef string `json:"stash_ref,omitempty"`
}
GitStashApplyResponse — daemon → PWA.
type GitStashDropRequest ¶ added in v0.1.1
type GitStashDropRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Ref string `json:"ref"`
}
GitStashDropRequest — PWA → daemon.
type GitStashDropResponse ¶ added in v0.1.1
type GitStashDropResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
StashRef string `json:"stash_ref,omitempty"`
Removed bool `json:"removed"`
}
GitStashDropResponse — daemon → PWA.
type GitStashEntry ¶ added in v0.1.1
type GitStashEntry struct {
Ref string `json:"ref"`
Index int `json:"index"`
CommitSHA string `json:"commit_sha"`
CreatedAt int64 `json:"created_at"`
Subject string `json:"subject"`
Branch string `json:"branch,omitempty"`
}
GitStashEntry is one row from Git's stash stack for the current repository. Ref is the only action key; CommitSHA and Branch are display-only.
type GitStashListRequest ¶ added in v0.1.1
type GitStashListRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
}
GitStashListRequest — PWA → daemon.
type GitStashListResponse ¶ added in v0.1.1
type GitStashListResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stashes []GitStashEntry `json:"stashes,omitempty"`
}
GitStashListResponse — daemon → PWA. Echoes RequestID.
type GitStashPopRequest ¶ added in v0.1.1
type GitStashPopRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Ref string `json:"ref"`
}
GitStashPopRequest — PWA → daemon.
type GitStashPopResponse ¶ added in v0.1.1
type GitStashPopResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
StashRef string `json:"stash_ref,omitempty"`
Removed bool `json:"removed"`
}
GitStashPopResponse — daemon → PWA.
type GitStashPushRequest ¶ added in v0.1.1
type GitStashPushRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
}
GitStashPushRequest — PWA → daemon.
type GitStashPushResponse ¶ added in v0.1.1
type GitStashPushResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
Stashed bool `json:"stashed"`
StashRef string `json:"stash_ref,omitempty"`
}
GitStashPushResponse — daemon → PWA.
type GitStatusPayload ¶
type GitStatusPayload struct {
RepoRoot string `json:"repo_root"`
Files []GitFileStatus `json:"files"`
TotalInsertions int `json:"total_insertions"`
TotalDeletions int `json:"total_deletions"`
GeneratedAt int64 `json:"generated_at"`
// Feature 172 additive fields — all omitempty for backward compat.
Branch string `json:"branch,omitempty"`
Upstream string `json:"upstream,omitempty"`
Ahead int `json:"ahead,omitempty"`
Behind int `json:"behind,omitempty"`
LastFetchedAt int64 `json:"last_fetched_at,omitempty"`
}
GitStatusPayload is the full per-session status snapshot returned by GetGitStatus and carried in MsgGitStatusUpdate pushes. Files is sorted ascending by path and capped at 500 entries.
Feature 172 extended this struct with five omitempty fields (Branch, Upstream, Ahead, Behind, LastFetchedAt) so the PWA's BranchChip and FreshnessPill can render current-branch context alongside the existing file-level status. All new fields are omitempty — older daemons emit the original 5-field shape and older PWAs ignore the new fields.
type GitStatusRequest ¶
type GitStatusRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
}
GitStatusRequest is the PWA → daemon request to fetch the current status snapshot for a session. The response body is a GitStatusPayload.
type GitSyncCancelRequest ¶
type GitSyncCancelRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
TargetID string `json:"target_id"`
}
GitSyncCancelRequest — PWA → daemon.
type GitSyncCancelResponse ¶
type GitSyncCancelResponse struct {
RequestID string `json:"request_id"`
TargetID string `json:"target_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
}
GitSyncCancelResponse — daemon → PWA. OK=true means the target's context.CancelFunc was found and invoked; the target op will emit its own terminal response shortly after with ErrorCode=canceled.
type GitSyncProgressPayload ¶
type GitSyncProgressPayload struct {
RequestID string `json:"request_id"`
Op string `json:"op"`
Stage string `json:"stage"`
Percent int `json:"percent,omitempty"`
Line string `json:"line,omitempty"`
}
GitSyncProgressPayload is a streaming daemon → PWA event emitted during long-running fetch/pull/push/switch operations. Lossy on the daemon side (buffered channel with drop-oldest on full). The terminal response is always delivered.
type GitWorktreeAddRequest ¶
type GitWorktreeAddRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Path string `json:"path"`
BaseRef string `json:"base_ref"`
NewBranchName string `json:"new_branch_name,omitempty"`
LockImmediately bool `json:"lock_immediately,omitempty"`
}
GitWorktreeAddRequest — PWA → daemon. NewBranchName non-empty triggers `-b <new>` so git creates a new branch at the target path. LockImmediately triggers a follow-up `git worktree lock` after the add succeeds.
type GitWorktreeAddResponse ¶
type GitWorktreeAddResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
Worktree *Worktree `json:"worktree,omitempty"`
}
GitWorktreeAddResponse — daemon → PWA (requestor only). On success, Worktree is populated with the created row.
type GitWorktreeAddedPayload ¶
type GitWorktreeAddedPayload struct {
SessionID string `json:"session_id"`
Worktree Worktree `json:"worktree"`
}
GitWorktreeAddedPayload — broadcast to all clients attached to the session on successful add (dual-fanout local WS + relay).
type GitWorktreeListRequest ¶
type GitWorktreeListRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
}
GitWorktreeListRequest — PWA → daemon. Asks for the worktree list of the repo containing the session's workDir.
type GitWorktreeListResponse ¶
type GitWorktreeListResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Worktrees []Worktree `json:"worktrees,omitempty"`
}
GitWorktreeListResponse — daemon → PWA. Echoes RequestID.
type GitWorktreeLockRequest ¶
type GitWorktreeLockRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Path string `json:"path"`
Reason string `json:"reason,omitempty"`
}
GitWorktreeLockRequest — PWA → daemon. Reason is redacted server-side before logging and truncated to 512 bytes before being passed to git.
type GitWorktreeLockResponse ¶
type GitWorktreeLockResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
Worktree *Worktree `json:"worktree,omitempty"`
}
GitWorktreeLockResponse — daemon → PWA.
type GitWorktreeProgressPayload ¶
type GitWorktreeProgressPayload struct {
RequestID string `json:"request_id"`
Op string `json:"op"`
Stage string `json:"stage"`
Percent int `json:"percent,omitempty"`
Line string `json:"line,omitempty"`
}
GitWorktreeProgressPayload is a streaming daemon → PWA event emitted during long-running `git worktree add --progress` operations. Lossy on the daemon side (buffered channel with drop-oldest on full). The terminal GitWorktreeAddResponse is always delivered.
Op is always "add" in v1 since `git worktree add` is currently the only long-running worktree operation; reserved for future extension to "switch" or "prune".
type GitWorktreePruneRequest ¶
type GitWorktreePruneRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
DryRun bool `json:"dry_run,omitempty"`
}
GitWorktreePruneRequest — PWA → daemon. DryRun=true runs `git worktree prune --dry-run -v` for a preview; the PWA then renders a ConfirmRail before sending the non-dry-run follow-up.
type GitWorktreePruneResponse ¶
type GitWorktreePruneResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
DryRun bool `json:"dry_run"`
RemovedPaths []string `json:"removed_paths,omitempty"`
RemovedCount int `json:"removed_count,omitempty"`
}
GitWorktreePruneResponse — daemon → PWA. RemovedPaths lists the .git/worktrees/<name> entries that were (or would be) removed.
type GitWorktreeRemoveRequest ¶
type GitWorktreeRemoveRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Path string `json:"path"`
Force bool `json:"force,omitempty"`
}
GitWorktreeRemoveRequest — PWA → daemon. Force maps to git's --force flag; gated by advanced-disclosure ConfirmRail in the UI.
type GitWorktreeRemoveResponse ¶
type GitWorktreeRemoveResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
Users []string `json:"users,omitempty"`
}
GitWorktreeRemoveResponse — daemon → PWA. On worktree_in_use, Users lists the session IDs currently attached to the path so the PWA can surface "session-abc is attached — detach first".
type GitWorktreeRemovedPayload ¶
type GitWorktreeRemovedPayload struct {
SessionID string `json:"session_id"`
Path string `json:"path"`
}
GitWorktreeRemovedPayload — broadcast on successful removal.
type GitWorktreeUnlockRequest ¶
type GitWorktreeUnlockRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Path string `json:"path"`
}
GitWorktreeUnlockRequest — PWA → daemon.
type GitWorktreeUnlockResponse ¶
type GitWorktreeUnlockResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
Worktree *Worktree `json:"worktree,omitempty"`
}
GitWorktreeUnlockResponse — daemon → PWA.
type GitWorktreeUpdatedPayload ¶
type GitWorktreeUpdatedPayload struct {
SessionID string `json:"session_id"`
Worktree Worktree `json:"worktree"`
}
GitWorktreeUpdatedPayload — broadcast on either lock or unlock success (same payload used for any non-structural worktree row update).
type HistoryPagePayload ¶ added in v0.1.1
type HistoryPagePayload struct {
SessionID string `json:"session_id"`
Messages []json.RawMessage `json:"messages"`
OldestSeq uint64 `json:"oldest_seq"`
HasMore bool `json:"has_more"`
RequestID string `json:"request_id"`
Error string `json:"error,omitempty"`
Trimmed bool `json:"trimmed,omitempty"`
RetainedOldestSeq uint64 `json:"retained_oldest_seq,omitempty"`
}
HistoryPagePayload is carried in an AgentMessage with Type MsgHistoryPage.
type HistoryPageRequest ¶ added in v0.1.1
type HistoryPageRequest struct {
Type string `json:"type"`
SessionID string `json:"session_id"`
BeforeSeq uint64 `json:"before_seq"`
Limit int `json:"limit,omitempty"`
RequestID string `json:"request_id"`
}
HistoryPageRequest is sent by the PWA when the user scrolls back before the currently loaded transcript window.
type InteractivePromptResolvedPayload ¶ added in v0.1.1
type InteractivePromptResolvedPayload struct {
QuestionID string `json:"question_id"`
SessionID string `json:"session_id"`
Reason string `json:"reason"`
ResolvedAt int64 `json:"resolved_at"`
}
InteractivePromptResolvedPayload is carried by MsgInteractivePromptResolved. The PWA records QuestionID as resolved for SessionID and clears only matching pending/in-flight prompt UI state. Reason is a stable, human-readable machine string such as "answered".
type JSONRPCError ¶ added in v0.1.1
type JSONRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data *AgentDErrorData `json:"data,omitempty"`
}
type JSONRPCID ¶ added in v0.1.1
type JSONRPCID []byte
JSONRPCID preserves a JSON-RPC request id in its original JSON form so responses can echo string, numeric, or null ids exactly as received.
func NewJSONRPCStringID ¶ added in v0.1.1
func NullJSONRPCID ¶ added in v0.1.1
func NullJSONRPCID() JSONRPCID
func (JSONRPCID) MarshalJSON ¶ added in v0.1.1
func (*JSONRPCID) UnmarshalJSON ¶ added in v0.1.1
type JSONRPCRequest ¶ added in v0.1.1
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID JSONRPCID `json:"id,omitempty"`
Method Method `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
TraceID string `json:"trace_id,omitempty"`
}
JSONRPCRequest is AgentD's command-plane request envelope.
TraceID is an AgentD extension to the JSON-RPC object. It is correlation metadata only and never authorizes a request.
func DecodeJSONRPCRequest ¶ added in v0.1.1
func DecodeJSONRPCRequest(data []byte) (JSONRPCRequest, error)
type JSONRPCResponse ¶ added in v0.1.1
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID JSONRPCID `json:"id"`
Result json.RawMessage `json:"result,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
TraceID string `json:"trace_id,omitempty"`
}
JSONRPCResponse is AgentD's command-plane response envelope. Exactly one of Result or Error is populated.
func NewJSONRPCError ¶ added in v0.1.1
func NewJSONRPCError(id JSONRPCID, traceID string, code int, message string, data *AgentDErrorData) JSONRPCResponse
func NewJSONRPCResult ¶ added in v0.1.1
func NewJSONRPCResult(id JSONRPCID, traceID string, result any) (JSONRPCResponse, error)
type JoinPayload ¶
type JoinPayload struct {
SessionID string `json:"sid"`
JWT string `json:"jwt"`
ClientID string `json:"client_id,omitempty"`
}
JoinPayload is sent by the mobile client to join a session. JWT carries the clientToken from QRPayload.token.
type KeyRotatePayload ¶
type KeyRotatePayload struct {
NewKeyHMAC string `json:"new_key_hmac"`
PrevKeyHMAC string `json:"prev_key_hmac"`
PrevExpiresAt int64 `json:"prev_expires_at"`
Epoch uint64 `json:"epoch"`
}
KeyRotatePayload is sent by the daemon to the relay to update the session's auth KeyHMAC during automatic key rotation. The relay retains the previous HMAC until PrevExpiresAt so in-flight client tokens pass validation during the grace window. Fields are NOT omitempty because the relay needs all four.
type MCPListPayload ¶
type MCPListPayload struct {
RequestID string `json:"request_id,omitempty"`
Scope MCPServerScope `json:"scope,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
MCPListPayload is the PWA → daemon request for the merged MCP server list. Empty Scope means both scopes; SessionID is required for project-scope resolution. RequestID is an opaque client-generated identifier echoed back in the response so the PWA can match replies to in-flight requests (feature 170).
type MCPListResponse ¶
type MCPListResponse struct {
RequestID string `json:"request_id,omitempty"`
Servers []MCPServerConfig `json:"servers"`
Status []MCPServerStatusEntry `json:"status,omitempty"`
ProjectWorkdir string `json:"project_workdir,omitempty"`
}
MCPListResponse is the daemon → PWA response to mcp_list_servers. Servers is ordered deterministically: user scope first, then project, sorted by name within each scope. Status is empty when no session is active. RequestID echoes the originating request's request_id so the PWA can route the response to the right in-flight callback (feature 170).
type MCPMutationPayload ¶
type MCPMutationPayload struct {
RequestID string `json:"request_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Server MCPServerConfig `json:"server"`
}
MCPMutationPayload is the PWA → daemon request for add/update operations. SessionID is required for project-scope mutations so the daemon can resolve the target workdir; user-scope mutations may omit it. RequestID is echoed back in the response (feature 170).
type MCPMutationResponse ¶
type MCPMutationResponse struct {
RequestID string `json:"request_id,omitempty"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
AppliedToLive bool `json:"applied_to_live"`
LiveStatus []MCPServerStatusEntry `json:"live_status,omitempty"`
Server *MCPServerConfig `json:"server,omitempty"`
}
MCPMutationResponse is the daemon → PWA response for add/update/remove/ toggle/reconnect operations. AppliedToLive is true when the SDK's SetMCPServers call succeeded against a live session; false for user-scope mutations without an active session, or when the session ended mid-op. RequestID echoes the originating request's request_id (feature 170).
type MCPReconnectPayload ¶
type MCPReconnectPayload struct {
RequestID string `json:"request_id,omitempty"`
SessionID string `json:"session_id"`
Name string `json:"name"`
}
MCPReconnectPayload is the PWA → daemon request to force a reconnect of a named MCP server on a live session. SessionID is required — reconnect is session-scoped. Shares MCPMutationResponse for the reply. RequestID is echoed back (feature 170).
type MCPRemovePayload ¶
type MCPRemovePayload struct {
RequestID string `json:"request_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Scope MCPServerScope `json:"scope"`
Name string `json:"name"`
}
MCPRemovePayload is the PWA → daemon request to delete a server from a given scope. Shares MCPMutationResponse for the reply. RequestID is echoed back (feature 170).
type MCPServerConfig ¶
type MCPServerConfig struct {
Name string `json:"name"`
Scope MCPServerScope `json:"scope"`
Transport string `json:"transport"`
Enabled bool `json:"enabled"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
URL string `json:"url,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
}
MCPServerConfig is the canonical representation of a single MCP server configuration. Field set depends on Transport:
- transport=stdio : Command (required), Args (optional), Env (optional)
- transport=sse : URL (required), Headers (optional)
- transport=http : URL (required), Headers (optional)
Env and Headers values are secrets — never log them.
type MCPServerScope ¶
type MCPServerScope string
MCPServerScope identifies where an MCP server configuration is persisted. `project` entries live in `<workdir>/.mcp.json`; `user` entries live in `~/.claude.json`. Claude Code CLI's third scope (`local`) is explicitly out of scope for feature 169 — see spec.md Non-Goals.
const ( // MCPScopeProject persists the server in <workdir>/.mcp.json. MCPScopeProject MCPServerScope = "project" // MCPScopeUser persists the server in ~/.claude.json. MCPScopeUser MCPServerScope = "user" )
MCPServerScope values.
type MCPServerStatusEntry ¶
type MCPServerStatusEntry struct {
Name string `json:"name"`
Status string `json:"status"`
Message string `json:"message,omitempty"`
ToolCount int `json:"tool_count,omitempty"`
ShadowedBy MCPServerScope `json:"shadowed_by,omitempty"`
}
MCPServerStatusEntry is the live connection state for a single MCP server as reported by the Go SDK's client.MCPServerStatus(). Not persisted — the daemon computes it on demand. `disabled` is synthesized locally when a config entry has Enabled=false (the SDK has no entry for those servers).
type MCPServersChangedPayload ¶
type MCPServersChangedPayload struct {
Scope MCPServerScope `json:"scope"`
SessionID string `json:"session_id,omitempty"`
Action string `json:"action"`
ServerName string `json:"server_name"`
}
MCPServersChangedPayload is the daemon → PWA broadcast emitted after every successful mutation. Clients re-dispatch mcp_list_servers to refresh their view. Action is diagnostic only (add|update|remove|toggle|reconnect).
type MCPTogglePayload ¶
type MCPTogglePayload struct {
RequestID string `json:"request_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Scope MCPServerScope `json:"scope"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
}
MCPTogglePayload is the PWA → daemon request to enable/disable a server without rewriting its full config. Shares MCPMutationResponse for the reply. RequestID is echoed back (feature 170).
type Method ¶ added in v0.1.1
type Method string
const ( MethodProtocolHello Method = "protocol.hello" MethodTransportPing Method = "transport.ping" MethodSupportBundle Method = "support.bundle" MethodSessionList Method = "session.list" MethodSessionStart Method = "session.start" MethodSessionStop Method = "session.stop" MethodSessionInterrupt Method = "session.interrupt" MethodSessionResume Method = "session.resume" MethodSessionDelete Method = "session.delete" MethodSessionRename Method = "session.rename" MethodSessionFork Method = "session.fork" MethodApprovalDecide Method = "approval.decide" MethodApprovalSetMode Method = "approval.setMode" MethodPromptAnswer Method = "prompt.answer" MethodBudgetExtend Method = "budget.extend" MethodModelsList Method = "models.list" MethodProvidersList Method = "providers.list" )
type NormalizedSupportBundleParams ¶ added in v0.1.1
func NormalizeSupportBundleParams ¶ added in v0.1.1
func NormalizeSupportBundleParams(params SupportBundleParams) (NormalizedSupportBundleParams, error)
type PersistedDelegationLink ¶ added in v0.1.6
type PersistedDelegationLink struct {
SourceSID string `json:"source_sid"` // source agent session ID
SourceEngine string `json:"source_engine"` // EngineClaude | EngineCodex
DelegateSID string `json:"delegate_sid"` // delegate agent session ID
DelegateEngine string `json:"delegate_engine"` // EngineClaude | EngineCodex
WorkDir string `json:"work_dir,omitempty"` // working directory scope for the delegation
TriggeredBy string `json:"triggered_by,omitempty"` // DelegationTriggeredBy* — user | auto | system
State string `json:"state,omitempty"` // DelegationState* — pending | active | completed | cancelled
CreatedAt int64 `json:"created_at"` // unix milliseconds
UpdatedAt int64 `json:"updated_at,omitempty"` // unix milliseconds
// Await is the governed delegation lifecycle flag persisted so restart recovery
// can distinguish an await=true (parked source, returns result) delegation from
// an await=false (fire-and-forget, source never parked) one. It is a *bool with
// the same absent⇒true idiom as StartDelegationPayload.Await /
// StartDelegationAwaitOrDefault: a NIL (absent) value resolves to true on
// recovery, so a journal written before this field existed recovers as the safe
// parked default. omitempty drops a nil pointer entirely, so old daemons and old
// journals stay byte-compatible. Without this field, recovery hardcoded
// await=true and re-parked a fire-and-forget source — its turns would queue, the
// quiescence clamp would fire, and an unwanted synthetic result would be injected.
Await *bool `json:"await,omitempty"`
// InheritedApprovalMode / InheritedSandboxMode record the elevated posture a
// delegate inherited from its source at spawn (empty when no inheritance
// occurred — the default), persisted so an operator can audit which delegates
// ran with an inherited, permission-prompt-disabled posture after the fact.
// Companion to the daemon's INFO spawn log. omitempty keeps pre-feature
// journals byte-identical; an absent value recovers as "no inheritance".
InheritedApprovalMode string `json:"inherited_approval_mode,omitempty"`
InheritedSandboxMode string `json:"inherited_sandbox_mode,omitempty"`
// DeliveryState records the durable handoff first-message delivery state, one of
// DelegationDeliveryState* — "pending" | "delivered" | "failed". Empty (absent)
// means legacy/not-tracked. omitempty keeps pre-feature journals byte-identical.
// This is a SCALAR audit field ONLY — it records WHETHER the inherited handoff
// first message reached the delegate, NEVER the inherited context content itself.
DeliveryState string `json:"delivery_state,omitempty"`
// ValidationState records the durable expected_output enforcement state, one of
// DelegationValidationState* — "awaiting_validation" | "passed" | "failed". Empty
// (absent) means validation was never engaged (max_validation_retries == 0, the
// advisory default). omitempty keeps pre-feature journals byte-identical. Like
// DeliveryState this is a SCALAR audit field ONLY — it records the validation
// PHASE, NEVER the result content or the requested shape (the captured partial
// rides the separate ENCRYPTED handoff blob store, never this plaintext link).
ValidationState string `json:"validation_state,omitempty"`
}
PersistedDelegationLink is the minimal durable representation of a source↔delegate link. The daemon persists this and replays it on restart so it can reconstruct the parked-source / live-delegate relationship (Phase 3 recovery, C3); a reloaded PWA renders it in link history (Phase 4, C7).
Timestamps are unix milliseconds (int64) — matching the existing module convention (ApprovalResolvedPayload.ResolvedAt, DelegationLinkPayload.CreatedAt) and avoiding the time.Time monotonic-clock roundtrip trap. All optional fields use omitempty for forward/backward compatibility across daemon restarts.
Phase 3 (daemon repo, NOT here): the daemon's internal persisted struct in agentd/internal/session/persistence.go adds daemon-specific fields that are NOT part of this shared schema — e.g. CancelledAt, CancelReason, FinalStatus, and retry bookkeeping. Only the wire/shared portion lives in agentd-protocol.
type PolicyJSON ¶
type PolicyJSON struct {
Name string `json:"name"`
Match PolicyMatchJSON `json:"match"`
Action string `json:"action"`
Approvers []string `json:"approvers,omitempty"`
TimeoutS int `json:"timeout_s,omitempty"`
Reason string `json:"reason,omitempty"`
}
PolicyJSON represents a single policy rule in the relay wire format.
type PolicyMatchJSON ¶
type PolicyMatchJSON struct {
Tool []string `json:"tool,omitempty"`
FilePattern string `json:"file_pattern,omitempty"`
Branch string `json:"branch,omitempty"`
Command string `json:"command,omitempty"`
RiskLevel []string `json:"risk_level,omitempty"`
}
PolicyMatchJSON represents the match criteria for a policy rule.
type ProtocolHelloOffer ¶ added in v0.1.1
type ProtocolHelloOffer struct {
SupportedProtocols []string
CapabilitiesByProtocol map[string][]string
}
func FullProtocolHelloOffer ¶ added in v0.1.1
func FullProtocolHelloOffer() ProtocolHelloOffer
type ProtocolHelloParams ¶ added in v0.1.1
type ProtocolHelloParams struct {
Client string `json:"client,omitempty"`
SupportedProtocols []string `json:"supported_protocols,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
ProtocolHelloParams is sent by clients before opting into v2 behavior.
type ProtocolHelloResult ¶ added in v0.1.1
type ProtocolHelloResult struct {
Protocol string `json:"protocol"`
SelectedProtocol string `json:"selected_protocol"`
SupportedProtocols []string `json:"supported_protocols"`
Capabilities []string `json:"capabilities"`
}
func NegotiateProtocolHello ¶ added in v0.1.1
func NegotiateProtocolHello(params ProtocolHelloParams) (ProtocolHelloResult, error)
func NegotiateProtocolHelloForOffer ¶ added in v0.1.1
func NegotiateProtocolHelloForOffer(params ProtocolHelloParams, offer ProtocolHelloOffer) (ProtocolHelloResult, error)
func NewProtocolHelloResult ¶ added in v0.1.1
func NewProtocolHelloResult() ProtocolHelloResult
type ProviderCapabilityContract ¶ added in v0.1.2
type ProviderCapabilityContract struct {
SchemaVersion int `json:"schema_version"`
Commands []ProviderCommandDescriptor `json:"commands,omitempty"`
Approval []ProviderFeatureDescriptor `json:"approval,omitempty"`
Sandbox []ProviderFeatureDescriptor `json:"sandbox,omitempty"`
MCP []ProviderFeatureDescriptor `json:"mcp,omitempty"`
Interactive []ProviderFeatureDescriptor `json:"interactive,omitempty"`
Skills []ProviderFeatureDescriptor `json:"skills,omitempty"`
Model []ProviderFeatureDescriptor `json:"model,omitempty"`
}
ProviderCapabilityContract is the additive v1 provider capability contract emitted on SessionInfo.provider_contract. It describes provider facts that legacy booleans and UI copy can derive from without changing old fields.
type ProviderCapabilitySource ¶ added in v0.1.2
type ProviderCapabilitySource string
const ( ProviderCapabilitySourceSDKRPC ProviderCapabilitySource = "sdk_rpc" ProviderCapabilitySourceSDKInit ProviderCapabilitySource = "sdk_init" ProviderCapabilitySourceCLIDocumented ProviderCapabilitySource = "cli_documented" ProviderCapabilitySourceDaemonCurated ProviderCapabilitySource = "daemon_curated" ProviderCapabilitySourceDaemonConfig ProviderCapabilitySource = "daemon_config" ProviderCapabilitySourcePromptComposed ProviderCapabilitySource = "prompt_composed" ProviderCapabilitySourcePWAClient ProviderCapabilitySource = "pwa_client" )
type ProviderCapabilitySupport ¶ added in v0.1.2
type ProviderCapabilitySupport string
const ( ProviderCapabilitySupported ProviderCapabilitySupport = "supported" ProviderCapabilityLimited ProviderCapabilitySupport = "limited" ProviderCapabilityUnsupported ProviderCapabilitySupport = "unsupported" )
type ProviderCommandArgumentRequirement ¶ added in v0.1.2
type ProviderCommandArgumentRequirement string
const ( ProviderCommandArgumentNone ProviderCommandArgumentRequirement = "none" ProviderCommandArgumentOptional ProviderCommandArgumentRequirement = "optional" ProviderCommandArgumentRequired ProviderCommandArgumentRequirement = "required" )
type ProviderCommandDescriptor ¶ added in v0.1.2
type ProviderCommandDescriptor struct {
Name string `json:"name"`
ArgumentRequirement ProviderCommandArgumentRequirement `json:"argument_requirement"`
Lifecycle ProviderCommandLifecycle `json:"lifecycle"`
StatusAfterDispatch ProviderCommandStatusAfterDispatch `json:"status_after_dispatch"`
Source ProviderCapabilitySource `json:"source"`
Support ProviderCapabilitySupport `json:"support"`
UserDescription string `json:"user_description"`
Limitations []string `json:"limitations,omitempty"`
}
type ProviderCommandLifecycle ¶ added in v0.1.2
type ProviderCommandLifecycle string
const ( ProviderCommandLifecycleProviderTurn ProviderCommandLifecycle = "provider_turn" ProviderCommandLifecycleProviderControl ProviderCommandLifecycle = "provider_control" ProviderCommandLifecycleDaemonControl ProviderCommandLifecycle = "daemon_control" ProviderCommandLifecycleClientLocal ProviderCommandLifecycle = "client_local" ProviderCommandLifecycleNoop ProviderCommandLifecycle = "noop" )
type ProviderCommandStatusAfterDispatch ¶ added in v0.1.2
type ProviderCommandStatusAfterDispatch string
const ( ProviderCommandStatusRunning ProviderCommandStatusAfterDispatch = "running" ProviderCommandStatusWaiting ProviderCommandStatusAfterDispatch = "waiting" ProviderCommandStatusUnchanged ProviderCommandStatusAfterDispatch = "unchanged" )
type ProviderFeatureDescriptor ¶ added in v0.1.2
type ProviderFeatureDescriptor struct {
ID string `json:"id"`
Support ProviderCapabilitySupport `json:"support"`
Source ProviderCapabilitySource `json:"source"`
UserLabel string `json:"user_label"`
UserDescription string `json:"user_description"`
Limitations []string `json:"limitations,omitempty"`
}
type PushNotifyPayload ¶ added in v0.1.1
type PushNotifyPayload struct {
Type string `json:"type"`
Summary string `json:"summary"`
ApprovalID string `json:"approval_id,omitempty"`
NotificationID string `json:"notification_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
CreatedAtUnixMS int64 `json:"created_at_unix_ms,omitempty"`
Attempt int `json:"attempt,omitempty"`
}
PushNotifyPayload is sent by a daemon to the relay over its authenticated websocket to trigger a Web Push notification. It intentionally does not carry the relay session ID; the relay derives that from the registered daemon connection to prevent session spoofing.
type PushNotifyResultPayload ¶ added in v0.1.1
type PushNotifyResultPayload struct {
NotificationID string `json:"notification_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
Type string `json:"type"`
Status string `json:"status"`
Reason string `json:"reason,omitempty"`
ProviderStatusCode int `json:"provider_status_code,omitempty"`
DeliveredAtUnixMS int64 `json:"delivered_at_unix_ms,omitempty"`
}
PushNotifyResultPayload is sent by the relay to the daemon after a daemon-originated push notification request reaches the relay. It reports the relay/provider result so the daemon can stop or retry tracked attempts.
type RateLimitBucket ¶
type RateLimitBucket struct {
UsedPercent float64 `json:"used_percent"`
WindowStart string `json:"window_start,omitempty"`
WindowEnd string `json:"window_end,omitempty"`
ResetsInSeconds int64 `json:"resets_in_seconds,omitempty"`
LabelID string `json:"label_id,omitempty"`
}
RateLimitBucket is one window of rate-limit usage. The underlying values come from the Codex SDK's typed RateLimits struct (codex-agent-sdk-go/types/account.go). UsedPercent is clamped to [0, 100] defensively before emission.
type RateLimitsUpdatedPayload ¶
type RateLimitsUpdatedPayload struct {
PrimaryWindow *RateLimitBucket `json:"primary_window,omitempty"`
SecondaryWindow *RateLimitBucket `json:"secondary_window,omitempty"`
ByLimitID map[string]*RateLimitBucket `json:"by_limit_id,omitempty"`
SessionID string `json:"session_id"`
ReceivedAtMillis int64 `json:"received_at_ms"`
PlanType string `json:"plan_type,omitempty"`
CreditsBalance string `json:"credits_balance,omitempty"`
CreditsHasCredits *bool `json:"credits_has_credits,omitempty"`
CreditsUnlimited *bool `json:"credits_unlimited,omitempty"`
}
RateLimitsUpdatedPayload is the structured snapshot of the account's rate-limit state at the time of emission. PrimaryWindow / SecondaryWindow cover the SDK's two-window model; ByLimitID exposes the richer per-limit-ID view when the SDK provides it. SessionID + ReceivedAtMillis are required so the PWA can correlate and order snapshots across reconnects.
On SDK parse failure, the daemon falls back to emitting only the back-compat MsgOutput text "rate limits updated" (preserves feature 185 behavior) and logs `codex_rate_limits_parse_failed` at warn level.
type RegisterPayload ¶
type RegisterPayload struct {
SessionID string `json:"sid"`
KeyHMAC string `json:"key_hmac"`
RelayAuth string `json:"relay_auth,omitempty"`
AgentType string `json:"agent"`
ProjectName string `json:"project"`
DisplayName string `json:"display"`
DeveloperID string `json:"dev_id,omitempty"`
}
RegisterPayload is sent by the daemon to register a session on the relay.
type RelayEnvelope ¶
type RelayEnvelope struct {
SessionID string `json:"sid"`
Seq uint64 `json:"seq"`
Encrypted []byte `json:"enc"`
TraceID string `json:"tid,omitempty"` // W3C trace-id (32 hex chars); optional for backward compat
EnvelopeID string `json:"eid,omitempty"` // opaque sender-selected id for route acknowledgement; relay never inspects Encrypted
TargetClientID string `json:"client_id,omitempty"` // daemon->client only; empty means fan out to all clients
Reliable bool `json:"rel,omitempty"` // targeted bootstrap/catch-up delivery must commit only after the client write succeeds
}
RelayEnvelope is the wire format for encrypted session messages routed between daemon and PWA via the relay. The relay routes by SessionID and NEVER inspects the Encrypted payload.
type RouteReceiptPayload ¶ added in v0.1.1
type RouteReceiptPayload struct {
EnvelopeID string `json:"eid"`
SessionID string `json:"sid,omitempty"`
TraceID string `json:"tid,omitempty"`
Routed bool `json:"routed"`
ReasonCode string `json:"reason_code,omitempty"`
ObservedAtUnixMs int64 `json:"observed_at_unix_ms"`
}
RouteReceiptPayload acknowledges relay routing for an encrypted envelope. It is transport metadata only: the relay never decrypts or classifies the business command carried inside RelayEnvelope.Encrypted.
type SessionFeature ¶ added in v0.1.1
type SessionFeature string
const ( SessionFeatureGitWatch SessionFeature = "git.watch" SessionFeatureMCPSync SessionFeature = "mcp.sync" SessionFeatureBudgetVirtualKey SessionFeature = "budget.virtual_key" SessionFeatureCodexModels SessionFeature = "codex.models" SessionFeatureCodexSkills SessionFeature = "codex.skills" )
type SessionFeatureReasonCode ¶ added in v0.1.1
type SessionFeatureReasonCode string
const ( SessionFeatureReasonQueueFull SessionFeatureReasonCode = "queue_full" SessionFeatureReasonTimeout SessionFeatureReasonCode = "timeout" SessionFeatureReasonHandlerFailed SessionFeatureReasonCode = "handler_failed" SessionFeatureReasonCanceled SessionFeatureReasonCode = "canceled" SessionFeatureReasonNotAGitRepo SessionFeatureReasonCode = "not_a_git_repo" SessionFeatureReasonGitBinaryMissing SessionFeatureReasonCode = "git_binary_missing" SessionFeatureReasonWorkDirInvalid SessionFeatureReasonCode = "work_dir_invalid" SessionFeatureReasonMCPStoreFailed SessionFeatureReasonCode = "mcp_store_failed" SessionFeatureReasonMCPApplyFailed SessionFeatureReasonCode = "mcp_apply_failed" SessionFeatureReasonBudgetKeyFailed SessionFeatureReasonCode = "budget_key_failed" )
type SessionFeatureState ¶ added in v0.1.1
type SessionFeatureState string
const ( SessionFeatureStatePending SessionFeatureState = "pending" SessionFeatureStateStarting SessionFeatureState = "starting" SessionFeatureStateReady SessionFeatureState = "ready" SessionFeatureStateDegraded SessionFeatureState = "degraded" SessionFeatureStateFailed SessionFeatureState = "failed" SessionFeatureStateCanceled SessionFeatureState = "canceled" )
type SessionFeatureStatusPayload ¶ added in v0.1.1
type SessionFeatureStatusPayload struct {
SchemaVersion int `json:"schema_version"`
SessionID string `json:"session_id"`
Feature SessionFeature `json:"feature"`
State SessionFeatureState `json:"state"`
ReasonCode SessionFeatureReasonCode `json:"reason_code,omitempty"`
Message string `json:"message,omitempty"`
ObservedAtUnixMS int64 `json:"observed_at_unix_ms"`
Attempt int `json:"attempt,omitempty"`
}
SessionFeatureStatusPayload is carried by MsgSessionFeatureStatus and EventSessionFeatureStatus. It reports the daemon-owned lifecycle of optional startup/runtime features independently from provider startup.
func (*SessionFeatureStatusPayload) UnmarshalJSON ¶ added in v0.1.1
func (p *SessionFeatureStatusPayload) UnmarshalJSON(data []byte) error
func (SessionFeatureStatusPayload) Validate ¶ added in v0.1.1
func (p SessionFeatureStatusPayload) Validate() error
type SessionHeadPayload ¶ added in v0.1.1
type SessionHeadPayload struct {
SessionID string `json:"session_id"`
HeadSeq uint64 `json:"head_seq"`
RetainedOldestSeq uint64 `json:"retained_oldest_seq,omitempty"`
}
SessionHeadPayload is carried in an AgentMessage with Type MsgSessionHead.
type SessionInfo ¶ added in v0.1.1
type SessionInfo struct {
FeatureStatuses []SessionFeatureStatusPayload `json:"feature_statuses,omitempty"`
ProviderContract *ProviderCapabilityContract `json:"provider_contract,omitempty"`
Recovery *SessionRecoveryInfo `json:"recovery,omitempty"`
}
SessionInfo pins the cross-repo feature_statuses field. Repos with richer session summaries embed the same JSON field in their local SessionInfo type.
type SessionRecoveryAction ¶ added in v0.1.2
type SessionRecoveryAction string
SessionRecoveryAction is the user-visible repair action for a recoverable paused session.
const ( SessionRecoveryActionResume SessionRecoveryAction = "resume" SessionRecoveryActionRetry SessionRecoveryAction = "retry" SessionRecoveryActionLoginThenRetry SessionRecoveryAction = "login_then_retry" SessionRecoveryActionRestorePath SessionRecoveryAction = "restore_path" )
type SessionRecoveryInfo ¶ added in v0.1.2
type SessionRecoveryInfo struct {
Recoverable bool `json:"recoverable"`
Reason SessionRecoveryReason `json:"reason,omitempty"`
Action SessionRecoveryAction `json:"action,omitempty"`
UserMessage string `json:"user_message,omitempty"`
Provider string `json:"provider,omitempty"`
}
SessionRecoveryInfo is the structured recovery metadata on SessionInfo and StatusPayload.
type SessionRecoveryReason ¶ added in v0.1.2
type SessionRecoveryReason string
SessionRecoveryReason is the daemon-classified reason a session can be repaired without losing its AgentD session identity or transcript.
const ( SessionRecoveryReasonDaemonRestarted SessionRecoveryReason = "daemon_restarted" SessionRecoveryReasonProviderExited SessionRecoveryReason = "provider_exited" SessionRecoveryReasonAuthRequired SessionRecoveryReason = "auth_required" SessionRecoveryReasonProviderStartFailed SessionRecoveryReason = "provider_start_failed" SessionRecoveryReasonWorkdirMissing SessionRecoveryReason = "workdir_missing" )
type SessionWorktreeChangedPayload ¶
type SessionWorktreeChangedPayload struct {
SessionID string `json:"session_id"`
OldWorkDir string `json:"old_work_dir"`
NewWorkDir string `json:"new_work_dir"`
NewBranch string `json:"new_branch,omitempty"`
RestartedAt int64 `json:"restarted_at"`
}
SessionWorktreeChangedPayload — server-push event broadcast to all clients attached to the session on a successful worktree switch (dual-fanout local WS + relay).
type SessionWorktreeSwitchRequest ¶
type SessionWorktreeSwitchRequest struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Path string `json:"path"`
}
SessionWorktreeSwitchRequest — PWA → daemon. Path is the target worktree's absolute path (must be one returned by GitWorktreeList for the session's current repo).
type SessionWorktreeSwitchResponse ¶
type SessionWorktreeSwitchResponse struct {
RequestID string `json:"request_id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Stderr string `json:"stderr,omitempty"`
NewWorkDir string `json:"new_work_dir,omitempty"`
NewBranch string `json:"new_branch,omitempty"`
RestartedAt int64 `json:"restarted_at,omitempty"`
}
SessionWorktreeSwitchResponse — daemon → PWA (requestor only). On success, NewWorkDir echoes the target path, NewBranch is the branch at the target (may be empty for detached HEAD), and RestartedAt is the Unix-millis timestamp of the completed subprocess restart.
type StartDelegationPayload ¶ added in v0.1.6
type StartDelegationPayload struct {
SourceSID string `json:"source_sid"` // source session to park + delegate from
ToEngine string `json:"to_engine"` // EngineClaude | EngineCodex — the delegate engine
Prompt string `json:"prompt"` // task prompt delivered to the delegate as its first message
Await bool `json:"await,omitempty"` // park source + return result to source agent; daemon defaults absent⇒true
}
StartDelegationPayload is the PWA→daemon command that USER-initiates a delegation. Carried inside an AgentMessage envelope with Type=MsgStartDelegation. The daemon resolves the source session, parks it (when Await), and spawns a delegate of ToEngine in the source's working directory with Prompt as the delegate's first task.
Await default note: the JSON bool zero-value is false, but the governed product default is await=TRUE when the field is ABSENT. omitempty drops an explicit false, so an absent field and an explicit false are indistinguishable on the wire. The PWA start-delegation UI ALWAYS sends await explicitly (Completion 2), so the daemon's start_delegation decoder treats the PWA as always-explicit. The daemon-side handler resolves the absent⇒true default by decoding into a *bool / inspecting the raw JSON, NOT by reading this struct's Go zero value. If a future non-PWA producer needs absent⇒true, switch this field to *bool then; keep omitempty so old consumers stay byte-compatible.
type StatusPayload ¶ added in v0.1.2
type StatusPayload struct {
Recovery *SessionRecoveryInfo `json:"recovery,omitempty"`
}
StatusPayload pins the cross-repo additive recovery field for daemon status updates. Repos with richer status payloads embed the same JSON field in their local StatusPayload type.
type StatusUpdatePayload ¶
type StatusUpdatePayload struct {
SessionID string `json:"sid"`
State string `json:"state"`
CostUSD float64 `json:"cost_usd,omitempty"`
Project string `json:"project,omitempty"`
AgentType string `json:"agent,omitempty"`
DeveloperID string `json:"dev_id,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
}
StatusUpdatePayload is sent by the daemon to the relay every 30s with current session state. The relay intercepts this and updates its in-memory state; it is never forwarded to clients.
type SupportBundle ¶ added in v0.1.1
type SupportBundle struct {
SchemaVersion string `json:"schema_version"`
GeneratedAtUnixMS int64 `json:"generated_at_unix_ms"`
BundleID string `json:"bundle_id"`
Client *SupportBundleClient `json:"client,omitempty"`
Daemon *SupportBundleDaemon `json:"daemon,omitempty"`
Transport SupportBundleTransport `json:"transport"`
RecentEvents []SupportEventEntry `json:"recent_events"`
LastErrors []SupportErrorRef `json:"last_errors"`
Redaction SupportRedaction `json:"redaction"`
Partial bool `json:"partial"`
PartialReasons []SupportPartialReason `json:"partial_reasons,omitempty"`
}
func (SupportBundle) MarshalJSON ¶ added in v0.1.1
func (b SupportBundle) MarshalJSON() ([]byte, error)
type SupportBundleClient ¶ added in v0.1.1
type SupportBundleContext ¶ added in v0.1.1
type SupportBundleContext struct {
TransportKind TransportKind
Connected bool
Stale bool
SelectedProtocol string
Capabilities []string
ActiveSessionID string
ActiveSessionState string
ActiveSessionStartupPhase string
HistoryHydrationState SupportHistoryHydrationState
LastRelayControlError string
LastInboundAgeMS *int64
LastPongAgeMS *int64
PendingJSONRPCRequestCount int
ClientDiagnostics *SupportClientDiagnostics
}
type SupportBundleDaemon ¶ added in v0.1.1
type SupportBundleDaemon struct {
Version string `json:"version"`
ProtocolVersion string `json:"protocol_version"`
AdvertisedCapabilities []string `json:"advertised_capabilities"`
ConfigSource SupportConfigSourceSummary `json:"config_source"`
RelayURLCategory SupportRelayURLCategory `json:"relay_url_category"`
}
type SupportBundleParams ¶ added in v0.1.1
type SupportBundleParams struct {
EventLimit *int `json:"event_limit,omitempty"`
IncludeRecentEvents *bool `json:"include_recent_events,omitempty"`
ClientTransport *SupportBundleTransport `json:"client_transport,omitempty"`
}
type SupportBundleTransport ¶ added in v0.1.1
type SupportBundleTransport struct {
ActiveMode string `json:"active_mode"`
Connected bool `json:"connected"`
Stale bool `json:"stale"`
SelectedProtocol string `json:"selected_protocol,omitempty"`
RelayURLCategory SupportRelayURLCategory `json:"relay_url_category,omitempty"`
ActiveSessionID string `json:"active_session_id,omitempty"`
ActiveSessionState string `json:"active_session_state,omitempty"`
ActiveSessionStartupPhase string `json:"active_session_startup_phase,omitempty"`
HistoryHydrationState SupportHistoryHydrationState `json:"history_hydration_state,omitempty"`
LastRelayControlError string `json:"last_relay_control_error,omitempty"`
RelayDiagnostics *SupportRelayDiagnostics `json:"relay_diagnostics,omitempty"`
ClientDiagnostics *SupportClientDiagnostics `json:"client_diagnostics,omitempty"`
LastInboundAgeMS *int64 `json:"last_inbound_age_ms,omitempty"`
LastPongAgeMS *int64 `json:"last_pong_age_ms,omitempty"`
PendingJSONRPCRequest int `json:"pending_jsonrpc_request_count,omitempty"`
}
type SupportClientDiagnostics ¶ added in v0.1.2
type SupportClientDiagnostics struct {
OutboundCommandCounts map[string]uint64 `json:"outbound_command_counts,omitempty"`
ChatViewRenderCount uint64 `json:"chat_view_render_count,omitempty"`
TranscriptScrollLoadCount uint64 `json:"transcript_scroll_load_count,omitempty"`
HistoryPageRequestsInFlight uint64 `json:"history_page_requests_in_flight,omitempty"`
WebSocketBufferedAmount uint64 `json:"websocket_buffered_amount,omitempty"`
}
type SupportConfigSourceKind ¶ added in v0.1.1
type SupportConfigSourceKind string
const ( SupportConfigSourceFile SupportConfigSourceKind = "file" SupportConfigSourceDefaultsEnv SupportConfigSourceKind = "defaults_env" SupportConfigSourceUnknown SupportConfigSourceKind = "unknown" )
type SupportConfigSourceSummary ¶ added in v0.1.1
type SupportConfigSourceSummary struct {
Kind SupportConfigSourceKind `json:"kind"`
Basename string `json:"basename,omitempty"`
PathHash string `json:"path_hash,omitempty"`
UnknownKeyCount int `json:"unknown_key_count"`
UnknownKeys []string `json:"unknown_keys,omitempty"`
}
type SupportErrorRef ¶ added in v0.1.1
type SupportEventEntry ¶ added in v0.1.1
type SupportEventEntry struct {
TS int64 `json:"ts"`
Source string `json:"source"`
Event string `json:"event"`
Code string `json:"code,omitempty"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
EventID string `json:"event_id,omitempty"`
Retryable bool `json:"retryable,omitempty"`
}
type SupportHistoryHydrationState ¶ added in v0.1.2
type SupportHistoryHydrationState string
const ( SupportHistoryHydrationWaitingTransport SupportHistoryHydrationState = "waiting_transport" SupportHistoryHydrationWaitingHistory SupportHistoryHydrationState = "waiting_history" SupportHistoryHydrationRestored SupportHistoryHydrationState = "restored" SupportHistoryHydrationIncomplete SupportHistoryHydrationState = "incomplete_retryable" SupportHistoryHydrationFailed SupportHistoryHydrationState = "failed" )
type SupportPartialReason ¶ added in v0.1.1
type SupportRedaction ¶ added in v0.1.1
type SupportRelayDiagnostics ¶ added in v0.1.2
type SupportRelayDiagnostics struct {
RelaySessionIDFingerprint string `json:"relay_session_id_fingerprint,omitempty"`
RegistrationGeneration uint64 `json:"registration_generation,omitempty"`
ReconnectCount uint64 `json:"reconnect_count,omitempty"`
LastControlCode string `json:"last_control_code,omitempty"`
ActiveBootstrapDrains uint64 `json:"active_bootstrap_drains,omitempty"`
RelayClientCount uint64 `json:"relay_client_count,omitempty"`
QueueRejections uint64 `json:"queue_rejections,omitempty"`
SerializerDrops uint64 `json:"serializer_drops,omitempty"`
}
type SupportRelayURLCategory ¶ added in v0.1.1
type SupportRelayURLCategory string
const ( SupportRelayURLNone SupportRelayURLCategory = "none" SupportRelayURLLocalhost SupportRelayURLCategory = "localhost" SupportRelayURLPrivateNetwork SupportRelayURLCategory = "private_network" SupportRelayURLHostedAgentD SupportRelayURLCategory = "hosted_agentd" SupportRelayURLCustomDomain SupportRelayURLCategory = "custom_domain" SupportRelayURLInvalid SupportRelayURLCategory = "invalid" )
type SyncPoliciesPayload ¶
type SyncPoliciesPayload struct {
Policies []PolicyJSON `json:"policies"`
}
SyncPoliciesPayload is sent by relay to daemon after CtrlAck. Carries the current org/team policy set.
type TerminateSessionAckPayload ¶ added in v0.1.1
type TerminateSessionAckPayload struct {
SessionID string `json:"session_id"`
Stopped int `json:"stopped,omitempty"`
}
TerminateSessionAckPayload is sent by the daemon after it has accepted a terminate_session control message. The relay treats it as observability; the durable termination tombstone is the reconnect-blocking authority.
type TerminateSessionPayload ¶ added in v0.1.1
type TerminateSessionPayload struct {
SessionID string `json:"session_id"`
Reason string `json:"reason,omitempty"`
}
TerminateSessionPayload is sent by the relay to a daemon when an operator terminates a single relay session from the dashboard. Unlike developer deactivation, this is scoped to one relay session and should stop reconnects for that relay session identity.
type TransportKind ¶ added in v0.1.1
type TransportKind string
const ( TransportLocal TransportKind = "local" TransportRelay TransportKind = "relay" )
type TransportPingParams ¶ added in v0.1.1
type TransportPingParams struct {
SentAtUnixMS int64 `json:"sent_at_unix_ms,omitempty"`
}
type TransportPongResult ¶ added in v0.1.1
type TransportPongResult struct {
Type string `json:"type"`
ReceivedAt int64 `json:"received_at_unix_ms"`
SentAtUnixMS int64 `json:"sent_at_unix_ms,omitempty"`
}
func NewTransportPongResult ¶ added in v0.1.1
func NewTransportPongResult(sentAtUnixMS int64) TransportPongResult
type Worktree ¶
type Worktree struct {
Path string `json:"path"`
Branch string `json:"branch,omitempty"`
HeadSHA string `json:"head_sha,omitempty"`
Locked bool `json:"locked,omitempty"`
LockedReason string `json:"locked_reason,omitempty"`
Prunable bool `json:"prunable,omitempty"`
PrunableReason string `json:"prunable_reason,omitempty"`
IsPrimary bool `json:"is_primary,omitempty"`
Ahead int `json:"ahead,omitempty"`
Behind int `json:"behind,omitempty"`
Upstream string `json:"upstream,omitempty"`
}
Worktree is a single entry in `git worktree list --porcelain -z` output. Transient per request — the PWA renders a list of these in the WorktreePanel. IsPrimary=true marks the main working tree (cannot be removed). Feature 173.