Package linear (github.com/coder/chat/adapters/linear) is the Linear app-actor adapter for the chat runtime (root package github.com/coder/chat). The bot acts as a Linear app-owned actor on App-Actor Client Credentials. [doc.go:linear]
It supports two Linear interaction models, both reached through chat.Adapter and an opaque, versioned Thread ID: [doc.go:linear]
- Agent sessions. The bot receives
AgentSessionEventcreatedandpromptedwebhooks. It posts the five Linear agent activity types: thought, response, action, elicitation, and error. - Issue comments. The bot receives Linear
Commentwebhooks and posts ordinary issue comments.
The adapter runs in one of two modes. Single-install mode uses a static Options.WebhookSecret and Options.ClientCredentials for one organization. Multi-tenant mode uses Options.InstallStore (chat.InstallStore) and reads the webhook secret and credentials from the install record of each organization. [doc.go:linear], [linear.go:New]
The adapter owns its own rate-limit retry (RetryPolicy) and Linear-specific extras (agent activities, session updates, proactive sessions, repository suggestions, and a raw GraphQL escape hatch). Callers reach the extras through chat.AdapterAs. [doc.go:linear]
NewvalidatesOptions, sets defaults, and returns anAdapter. [linear.go:New]OptionsholdsWebhookSecret,ClientCredentials,InstallStore,APIBaseURL,Client,Now,SignatureTolerance,Logger,RetryPolicy, andObserver. [linear.go:Options]ClientCredentialsholdsClientID,ClientSecret, andScopes. [linear.go:ClientCredentials]LinearInstallis the install credential (WebhookSecret,ClientCredentials,AccessToken,BotUserID) carried onchat.Install.Credential. [linear.go:LinearInstall]Adapteris the Linear adapter. It implementschat.Adapterandchat.HistoryReader. [linear.go:Adapter], [history.go:HistoryReader assertion]RetryPolicysetsMaxAttempts,MaxElapsed,BaseDelay, andMaxDelay. [retry.go:RetryPolicy]RateLimitedis the error returned when throttling retry stops (Adapter,RetryAfter,Attempts,Raw,Err). [retry.go:RateLimited]
Adapter.Namereturns"linear". [linear.go:Name]Adapter.Initexchanges a token and fetches the viewer identity in single-install mode. It does nothing in multi-tenant mode. [linear.go:Init]Adapter.Shutdownreturns nil. [linear.go:Shutdown]Adapter.Webhookreturns thehttp.Handlerfor inbound Linear webhooks, for achat.DispatchFunc. [linear.go:Webhook]Adapter.ValidateThreadIDdecodes a Thread ID into achat.ThreadRef. [linear.go:ValidateThreadID]Adapter.PostMessageposts an issue comment on a comment thread, or a response activity on an agent-session thread. [linear.go:PostMessage]Adapter.BotActorreturns the bot as achat.Actor. [linear.go:BotActor]Adapter.ReadHistoryreads agent activities or comment replies, newest first. [history.go:ReadHistory]
Adapter.PostThoughtposts an ephemeral thought activity. [linear.go:PostThought]Adapter.CreateAgentActivityposts any agent activity from anAgentActivityInput. [activity.go:CreateAgentActivity,AgentActivityInput]Adapter.PostActionposts an action activity from anActionInput. [activity.go:PostAction,ActionInput]Adapter.PostElicitationposts an elicitation activity from anElicitationInput. [activity.go:PostElicitation,ElicitationInput]Adapter.PostErrorposts an error activity from anErrorInput. [activity.go:PostError,ErrorInput]AuthSignalMetadata,SelectSignalMetadata, andSelectOptionare elicitation signal metadata types. [activity.go:AuthSignalMetadata,SelectSignalMetadata,SelectOption]
Adapter.UpdateSessionsets external URLs and the plan from anAgentSessionUpdateInput. [session.go:UpdateSession,AgentSessionUpdateInput]ExternalURLandPlanStepare session update types. [session.go:ExternalURL,PlanStep]Adapter.CreateSessionOnIssueandAdapter.CreateSessionOnIssueForTenantcreate a proactive session on an issue. [session.go:CreateSessionOnIssue,CreateSessionOnIssueForTenant]Adapter.CreateSessionOnCommentandAdapter.CreateSessionOnCommentForTenantcreate a proactive session on a comment. [session.go:CreateSessionOnComment,CreateSessionOnCommentForTenant]CreateSessionOnIssueInput,CreateSessionOnCommentInput, andCreatedAgentSessionare the proactive session types. [session.go:CreateSessionOnIssueInput,CreateSessionOnCommentInput,CreatedAgentSession]Adapter.SuggestRepositoriesranksCandidateRepositoryvalues intoRepositorySuggestionvalues for a thread's issue. [suggestions.go:SuggestRepositories,CandidateRepository,RepositorySuggestion]Adapter.GraphQLandAdapter.GraphQLForTenantsend a raw GraphQL request. [session.go:GraphQL,GraphQLForTenant]
RawMessageis the Linear payload onchat.Message.Raw. [raw.go:RawMessage]RawMessageFromextracts a*RawMessagefrom achat.Message. [raw.go:RawMessageFrom]RawMessage.StopRequestedreports the human-to-agentstopsignal. It is nil-safe. [raw.go:RawMessage.StopRequested]RawAgentSessionholds session context.FirstThoughtDeadlineholds the first-thought timing. [raw.go:RawAgentSession,FirstThoughtDeadline]
- Multi-tenant mode (
InstallStoreset) rejects a staticWebhookSecretorClientCredentials. [linear.go:New] - Single-install mode requires
WebhookSecret,ClientCredentials.ClientID, andClientCredentials.ClientSecret. [linear.go:New] Newrejects a negativeSignatureTolerance. Zero usesdefaultSignatureTolerance(1 minute). [linear.go:New,defaultSignatureTolerance]- Empty scopes default to
read,write,app:mentionable, andapp:assignable. [linear.go:New,defaultClientCredentialScopes] RetryPolicydefaults for zero fields:MaxAttempts3,MaxElapsed3s,BaseDelay200ms,MaxDelay1s.MaxAttempts1 turns retry off. [retry.go:RetryPolicy.withDefaults], [doc.go:linear]- Single-install
Initrequires a non-empty organization ID and app user ID from the viewer query. [linear.go:Init] Init,Webhook,PostThought,BotActor,ReadHistory, and the activity, session, suggestion, and GraphQL methods panic on a nil*AdapterthroughassertAdapter. [linear.go:assertAdapter,Init,Webhook,PostThought,BotActor], [history.go:ReadHistory], [activity.go:CreateAgentActivity], [session.go:GraphQL], [suggestions.go:SuggestRepositories]
Webhookaccepts only POST (else 405) and bodies up to 1 MiB (else 413). [linear.go:Webhook,maxWebhookBodyBytes]- An unreadable body returns 400
read body. After the signature check, a body that does not decode into the webhook envelope returns 400invalid linear payload. [linear.go:Webhook] - The
Linear-Signatureheader must be the hex HMAC-SHA256 of the raw body. The adapter checks it before it decodes the event envelope or dispatches (else 401). In multi-tenant mode, the unverified routing read in the next rule comes first. [linear.go:verifySignatureWithSecret,Webhook,resolveWebhookInstall] webhookTimestampmust be non-zero and within the signature tolerance (else 401). [linear.go:verifyTimestamp]- Multi-tenant mode reads
organizationIdfrom the unverified body for routing only. It then verifies the signature with the install record's webhook secret. [doc.go:linear], [linear.go:resolveWebhookInstall] - In multi-tenant mode, a body with no organization or a
chat.ErrInstallNotFoundlookup is an Ignored Event (200, not dispatched). Other lookup errors return 500. [linear.go:resolveWebhookInstall] chat.ErrAdmissionRejectedfrom dispatch returns 503, so Linear redelivers. Other dispatch errors return 500. [linear.go:Webhook]- An agent-session event needs an organization, a session ID, and an issue ID. A
promptedevent needsagentActivity. [linear.go:normalizeAgentSessionEvent] - The adapter drops agent-session and comment events whose organization or OAuth client ID conflicts with the resolved install. [linear.go:normalizeAgentSessionEvent], [comments.go:normalizeCommentEvent]
- A comment event needs a comment ID, an organization, an issue ID, and an author. [comments.go:normalizeCommentEvent]
- Multi-tenant mode drops events that the bot authored. [linear.go:normalizeAgentSessionEvent], [comments.go:normalizeCommentEvent]
- Event IDs have the form
linear:<org>:message:<sourceID>. [linear.go:normalizeAgentSessionEvent], [comments.go:normalizeCommentEvent]
- The adapter refreshes a token when it is empty or within 1 hour of expiry. [linear.go:ensureToken,tokenRefreshBuffer]
- A token response without a positive
expires_ingets Linear's documented 30-day lifetime, so the adapter refreshes it 1 hour before 30 days pass. This holds for the single-install token and for cached per-tenant tokens. The adapter does not refresh a token after a 401. [linear.go:exchangeClientCredentials,defaultTokenLifetime,ensureToken,tenantToken] - A client-credentials response must contain
access_tokenand grant every requested scope. [linear.go:exchangeClientCredentials,verifyGrantedScopes] - An install credential must be a
LinearInstallor a non-nil*LinearInstall. A multi-tenant install needs a webhook secret. A pre-suppliedAccessTokenis used as is. [linear.go:linearCredential,resolveWebhookInstall,tenantToken] GraphQL,CreateSessionOnIssue, andCreateSessionOnCommentfail in multi-tenant mode. Use theForTenantforms. [session.go:GraphQL,CreateSessionOnIssue,CreateSessionOnComment]GraphQLForTenantrequires a non-empty query and never returns the access token. [session.go:GraphQLForTenant]
- A Thread ID must start with
linear:v1:. Its payload needsorgandissue, plussessionfor agent-session threads orcommentfor comment threads. An empty kind means agent session. [linear.go:decodeThreadID,threadPayload.validate,threadPayload.kind] - Single-install mode rejects a Thread ID from another organization. [linear.go:validateThreadPayload]
- Agent activity operations fail on a non-agent-session thread. [linear.go:agentSessionPayload]
PostMessagerequires non-empty text andchat.MessageFormatTextorchat.MessageFormatMarkdown.PostThoughtrequires non-blank text. [linear.go:validatePostableMessage,PostThought]Ephemeralis valid only for thought and action activities. [linear.go:createAgentActivity]- An activity or comment mutation must report
successand a non-empty ID, else the call fails. [linear.go:createAgentActivity], [comments.go:createIssueComment] CreateAgentActivityrejects emptyContent.PostActionrejects a blankAction.PostElicitationandPostErrorreject a blankBody. [activity.go:CreateAgentActivity,PostAction,PostElicitation,PostError]UpdateSessionrejects an empty update. [session.go:UpdateSession]SuggestRepositoriesrequires at least one candidate, and each candidate needsHostnameandRepositoryFullName. [suggestions.go:SuggestRepositories]
ReadHistoryuses 50 whenLimit <= 0and capsLimitat 250. [history.go:ReadHistory,linearDefaultHistoryLimit,linearMaxHistoryLimit]ReadHistorydoes no storage, dedupe, or caching. [history.go:ReadHistory], [doc.go:linear]- A
Beforecursor resolves to acreatedAtfilter. An unresolved cursor is an error. [history.go:historyCursorFilter] - Retry runs on HTTP 429 or a throttling GraphQL error. It never sleeps past the request context deadline, and returns
*RateLimitedinstead. [retry.go:doJSONWithRetry,rateLimitedResponse] - Retry also returns
*RateLimitedafterMaxAttempts, or when the next delay would push the total pastMaxElapsed. A context cancelled during a backoff sleep returns the context error instead. Each delay is the exponential backoff, raised to the platform's Retry-After, then capped atMaxDelay. [retry.go:doJSONWithRetry], [internal/ratelimit/ratelimit.go:BackoffDelay] - The first-thought budget is 10 seconds from session creation. The adapter reports the deadline and runs no watchdog. [raw.go:firstThoughtBudget], [doc.go:linear]
- When the session timestamp does not parse,
newFirstThoughtDeadlineusesnow()as the creation time. Its doc comment says it returns nil in that case, so the doc comment and the code disagree. [raw.go:newFirstThoughtDeadline]
- The adapter POSTs to
{APIBaseURL}/oauth/token(defaulthttps://api.linear.app) for the client-credentials grant. [linear.go:exchangeClientCredentials,defaultAPIBaseURL] - All GraphQL calls POST to
{APIBaseURL}/graphqlwith a bearer token throughOptions.Client(defaulthttp.DefaultClient). [linear.go:callGraphQLWithToken,New] - GraphQL operations:
ViewerIdentityatInit,AgentActivityCreatefor activities,CommentCreatefor comments,AgentSessionUpdate,AgentSessionCreateOnIssue,AgentSessionCreateOnComment,IssueRepositorySuggestions, and history queries. [linear.go:fetchIdentity,createAgentActivity], [comments.go:createIssueComment], [session.go:UpdateSession,createSessionOnIssue,createSessionOnComment], [suggestions.go:SuggestRepositories], [history.go:readAgentSessionHistory,readCommentThreadHistory] - Multi-tenant mode calls
InstallStore.Lookupon every webhook whose body names an organization, and on every outbound token resolution. A body with no organization is ignored without a lookup. It does not cache install records. [linear.go:resolveWebhookInstall,resolveToken] - A mutex (
a.mu) guards the access token, expiry, organization, and bot identity. A second mutex guards the per-tenant token cache. [linear.go:Adapter,tenantToken] Webhookcalls the runtimechat.DispatchFuncfor each normalized event. [linear.go:Webhook]- Retry sleeps with
ratelimit.SleepCtxfrominternal/ratelimit, and resends a buffered copy of the request body. [retry.go:doJSONWithRetry] - The adapter emits
chat.ObsAdapterCallper attempt andchat.ObsRateLimitper throttle toOptions.Observer. [retry.go:doJSONWithRetry] - The adapter logs a
linear rate limitedwarning on throttles, warnings for dropped events, and debug records for ignored webhooks. [retry.go:logRetry], [linear.go:Webhook,normalizeAgentSessionEvent], [comments.go:normalizeCommentEvent]
- Run:
go test ./adapters/linear/... - The emulate.dev tier has no Linear tests yet, because emulate's Linear schema differs from Linear's. See "Emulator Tests" in
CONTRIBUTING.mdand issue #148.