The Open Framework for Building Agents
fix(eve): use native elicitations for the Linear channel (#1053)
OwenKepharte7e773a79f86
diff --git a/packages/eve/src/public/channels/linear/api.ts b/packages/eve/src/public/channels/linear/api.tsindex 66b5e5e08..45210a509 100644--- a/packages/eve/src/public/channels/linear/api.ts+++ b/packages/eve/src/public/channels/linear/api.ts@@ -88,6 +88,8 @@ export interface LinearAgentActivityRecord {__typename?: string;};id: string;+ signal?: string | null;+ signalMetadata?: JsonObject | null;updatedAt?: string;}@@ -306,6 +308,8 @@ export async function listLinearAgentSessionActivities(input: {activities(last: $last) {nodes {id+ signal+ signalMetadataupdatedAtcontent {__typename@@ -374,6 +378,11 @@ function normalizeAgentActivityRecord(value: unknown): LinearAgentActivityRecordcontent,id: value.id,};+ if (typeof value.signal === "string" || value.signal === null) record.signal = value.signal;+ if (isObject(value.signalMetadata)) {+ record.signalMetadata = parseJsonObject(value.signalMetadata);+ }+ if (value.signalMetadata === null) record.signalMetadata = null;if (typeof value.updatedAt === "string") record.updatedAt = value.updatedAt;return record;}diff --git a/packages/eve/src/public/channels/linear/defaults.ts b/packages/eve/src/public/channels/linear/defaults.tsindex d1de64634..cda371a1c 100644--- a/packages/eve/src/public/channels/linear/defaults.ts+++ b/packages/eve/src/public/channels/linear/defaults.ts@@ -3,7 +3,10 @@ import type { SessionAuthContext } from "#channel/types.js";import { extractErrorId, formatErrorHint } from "#internal/logging.js";import { createLinearAgentActivity, type LinearApiOptions } from "#public/channels/linear/api.js";import type { LinearChannelCredentials } from "#public/channels/linear/auth.js";-import { renderLinearInputRequests } from "#public/channels/linear/hitl.js";+import {+ linearInputRequestSignal,+ renderLinearInputRequests,+} from "#public/channels/linear/hitl.js";import type { LinearAgentSessionEvent, LinearUser } from "#public/channels/linear/inbound.js";import type {LinearChannelEvents,@@ -128,10 +131,16 @@ export function createDefaultEvents(options: LinearDefaultEventOptions = {}): Li},async "input.requested"(event, channel, _ctx) {- await postActivity(channel, options, {- body: renderLinearInputRequests(event.requests),- type: "elicitation",- });+ const signal = linearInputRequestSignal(event.requests);+ await postActivity(+ channel,+ options,+ {+ body: renderLinearInputRequests(event.requests),+ type: "elicitation",+ },+ signal,+ );},async "message.completed"(event, channel, _ctx) {@@ -185,6 +194,10 @@ function postActivity(content: Parameters<typeof createLinearAgentActivity>[0]["activity"]["content"],activityOptions: {readonly ephemeral?: boolean;+ readonly signal?: Parameters<typeof createLinearAgentActivity>[0]["activity"]["signal"];+ readonly signalMetadata?: Parameters<+ typeof createLinearAgentActivity+ >[0]["activity"]["signalMetadata"];} = {},): Promise<{ readonly id: string; readonly success: boolean }> {return createLinearAgentActivity({@@ -194,6 +207,8 @@ function postActivity(agentSessionId: requireAgentSessionId(channel.state.agentSessionId),content,ephemeral: activityOptions.ephemeral,+ signal: activityOptions.signal,+ signalMetadata: activityOptions.signalMetadata,},});}diff --git a/packages/eve/src/public/channels/linear/hitl.test.ts b/packages/eve/src/public/channels/linear/hitl.test.tsindex 4bb68039d..bf9e12e89 100644--- a/packages/eve/src/public/channels/linear/hitl.test.ts+++ b/packages/eve/src/public/channels/linear/hitl.test.ts@@ -1,9 +1,8 @@import { describe, expect, it } from "vitest";import {+ linearInputRequestSignal,renderLinearInputRequests,- resolveLinearPromptInputResponses,- stripLinearHitlMarker,} from "#public/channels/linear/hitl.js";import type { InputRequest } from "#runtime/input/types.js";@@ -17,7 +16,7 @@ function makeRequest(overrides: Partial<InputRequest> = {}): InputRequest {}describe("Linear HITL helpers", () => {- it("renders input requests with a hidden Linear marker", () => {+ it("renders only user-visible input request text", () => {const rendered = renderLinearInputRequests([makeRequest({options: [@@ -30,46 +29,33 @@ describe("Linear HITL helpers", () => {expect(rendered).toContain("Approve deployment?");expect(rendered).toContain("1. Approve");expect(rendered).toContain("2. Deny - Stop the deployment");- expect(rendered).toContain("<!-- eve-input:");- expect(stripLinearHitlMarker(rendered)).not.toContain("eve-input");+ expect(rendered).not.toContain("eve-input");+ expect(rendered).not.toContain("<!--");});- it("resolves Linear prompt text against the latest elicitation marker", () => {- const elicitation = renderLinearInputRequests([- makeRequest({- options: [- { id: "approve", label: "Approve" },- { id: "deny", label: "Deny" },- ],- }),- ]);-+ it("uses user-facing option IDs as native Linear select values", () => {expect(- resolveLinearPromptInputResponses({- activities: [- {- content: { body: elicitation, type: "elicitation" },- id: "activity_1",- },+ linearInputRequestSignal([+ makeRequest({+ allowFreeform: true,+ options: [+ { id: "approve", label: "Approve" },+ { id: "deny", label: "Deny" },+ ],+ }),+ ]),+ ).toEqual({+ signal: "select",+ signalMetadata: {+ options: [+ { label: "Approve", value: "approve" },+ { label: "Deny", value: "deny" },],- body: "approve",- }),- ).toEqual([{ optionId: "approve", requestId: "call_1" }]);+ },+ });});- it("supports freeform replies when the original request allowed them", () => {- const elicitation = renderLinearInputRequests([- makeRequest({- allowFreeform: true,- options: [{ id: "pick_later", label: "Pick later" }],- }),- ]);-- expect(- resolveLinearPromptInputResponses({- activities: [{ content: { body: elicitation, type: "elicitation" }, id: "activity_1" }],- body: "Ship it after 5pm",- }),- ).toEqual([{ requestId: "call_1", text: "Ship it after 5pm" }]);+ it("does not emit a select signal for requests without options", () => {+ expect(linearInputRequestSignal([makeRequest({ allowFreeform: true })])).toEqual({});});});diff --git a/packages/eve/src/public/channels/linear/hitl.ts b/packages/eve/src/public/channels/linear/hitl.tsindex 0650f6f37..d4c8a08de 100644--- a/packages/eve/src/public/channels/linear/hitl.ts+++ b/packages/eve/src/public/channels/linear/hitl.ts@@ -1,45 +1,28 @@-import { resolveTextToResponses } from "#channel/resolve-text.js";-import type { LinearAgentActivityRecord } from "#public/channels/linear/api.js";-import type { InputOption, InputRequest, InputResponse } from "#runtime/input/types.js";+import type { InputRequest } from "#runtime/input/types.js";+import type { JsonObject } from "#shared/json.js";-/** Hidden marker embedded in eve-created Linear elicitation bodies. */-export const LINEAR_HITL_MARKER_PREFIX = "<!-- eve-input:";-export const LINEAR_HITL_MARKER_SUFFIX = " -->";--interface LinearHitlMarkerPayload {- requests: readonly LinearStoredInputRequest[];-}--interface LinearStoredInputRequest {- allowFreeform?: boolean;- display?: InputRequest["display"];- options?: readonly InputOption[];- prompt: string;- requestId: string;-}--/** Renders eve input requests as one Linear elicitation body. */+/** Renders eve input requests as one user-visible Linear elicitation body. */export function renderLinearInputRequests(requests: readonly InputRequest[]): string {- const marker = encodeLinearHitlMarker(requests.map(storableRequest));- const rendered = requests.map(renderLinearInputRequest).join("\n\n");- return `${rendered}\n\n${marker}`;-}--/** Resolves a Linear user prompt against the latest eve-created elicitation marker. */-export function resolveLinearPromptInputResponses(input: {- readonly activities: readonly LinearAgentActivityRecord[];- readonly body: string;-}): readonly InputResponse[] {- const marker = findLatestLinearHitlMarker(input.activities);- if (marker === null) return [];- return resolveTextToResponses(input.body, marker.requests.map(toInputRequest));-}--/** Strips eve's hidden HITL marker from a body before user-facing assertions/logging. */-export function stripLinearHitlMarker(body: string): string {- const start = body.indexOf(LINEAR_HITL_MARKER_PREFIX);- if (start === -1) return body;- return body.slice(0, start).trimEnd();+ return requests.map(renderLinearInputRequest).join("\n\n");+}++/** Builds native Linear select metadata for a single input request with options. */+export function linearInputRequestSignal(requests: readonly InputRequest[]): {+ readonly signal?: "select";+ readonly signalMetadata?: JsonObject;+} {+ const request = requests.length === 1 ? requests[0] : undefined;+ if (request?.options === undefined || request.options.length === 0) return {};++ return {+ signal: "select",+ signalMetadata: {+ options: request.options.map((option) => ({+ label: option.label,+ value: option.id,+ })),+ },+ };}function renderLinearInputRequest(request: InputRequest): string {@@ -58,114 +41,3 @@ function renderLinearInputRequest(request: InputRequest): string {}return lines.join("\n");}--function storableRequest(request: InputRequest): LinearStoredInputRequest {- const stored: LinearStoredInputRequest = {- prompt: request.prompt,- requestId: request.requestId,- };- if (request.allowFreeform !== undefined) stored.allowFreeform = request.allowFreeform;- if (request.display !== undefined) stored.display = request.display;- if (request.options !== undefined) stored.options = request.options;- return stored;-}--function toInputRequest(request: LinearStoredInputRequest): InputRequest {- const inputRequest: InputRequest = {- action: {- callId: `linear-input:${request.requestId}`,- input: {},- kind: "tool-call",- toolName: "linear_input",- },- prompt: request.prompt,- requestId: request.requestId,- };- if (request.allowFreeform !== undefined) inputRequest.allowFreeform = request.allowFreeform;- if (request.display !== undefined) inputRequest.display = request.display;- if (request.options !== undefined) inputRequest.options = [...request.options];- return inputRequest;-}--function encodeLinearHitlMarker(requests: readonly LinearStoredInputRequest[]): string {- const encoded = Buffer.from(JSON.stringify({ requests }), "utf8").toString("base64url");- return `${LINEAR_HITL_MARKER_PREFIX}${encoded}${LINEAR_HITL_MARKER_SUFFIX}`;-}--function findLatestLinearHitlMarker(- activities: readonly LinearAgentActivityRecord[],-): LinearHitlMarkerPayload | null {- for (let index = activities.length - 1; index >= 0; index -= 1) {- const body = activities[index]?.content.body;- if (body === undefined) continue;- const marker = decodeLinearHitlMarker(body);- if (marker !== null) return marker;- }- return null;-}--function decodeLinearHitlMarker(body: string): LinearHitlMarkerPayload | null {- const start = body.lastIndexOf(LINEAR_HITL_MARKER_PREFIX);- if (start === -1) return null;- const payloadStart = start + LINEAR_HITL_MARKER_PREFIX.length;- const end = body.indexOf(LINEAR_HITL_MARKER_SUFFIX, payloadStart);- if (end === -1) return null;-- try {- const decoded = Buffer.from(body.slice(payloadStart, end), "base64url").toString("utf8");- const parsed = JSON.parse(decoded) as unknown;- if (!isMarkerPayload(parsed)) return null;- return parsed;- } catch {- return null;- }-}--function isMarkerPayload(value: unknown): value is LinearHitlMarkerPayload {- if (!value || typeof value !== "object" || !("requests" in value)) return false;- const requests = (value as { readonly requests?: unknown }).requests;- return Array.isArray(requests) && requests.every(isStoredRequest);-}--function isStoredRequest(value: unknown): value is LinearStoredInputRequest {- if (!value || typeof value !== "object") return false;- const request = value as {- readonly allowFreeform?: unknown;- readonly display?: unknown;- readonly options?: unknown;- readonly prompt?: unknown;- readonly requestId?: unknown;- };- if (typeof request.prompt !== "string" || typeof request.requestId !== "string") return false;- if (request.allowFreeform !== undefined && typeof request.allowFreeform !== "boolean") {- return false;- }- if (- request.display !== undefined &&- request.display !== "confirmation" &&- request.display !== "select" &&- request.display !== "text"- ) {- return false;- }- const options = request.options;- return options === undefined || (Array.isArray(options) && options.every(isStoredOption));-}--function isStoredOption(value: unknown): value is InputOption {- if (!value || typeof value !== "object") return false;- const option = value as {- readonly description?: unknown;- readonly id?: unknown;- readonly label?: unknown;- readonly style?: unknown;- };- if (typeof option.id !== "string" || typeof option.label !== "string") return false;- if (option.description !== undefined && typeof option.description !== "string") return false;- return (- option.style === undefined ||- option.style === "primary" ||- option.style === "danger" ||- option.style === "default"- );-}diff --git a/packages/eve/src/public/channels/linear/index.ts b/packages/eve/src/public/channels/linear/index.tsindex 35ea00ce3..e89382268 100644--- a/packages/eve/src/public/channels/linear/index.ts+++ b/packages/eve/src/public/channels/linear/index.ts@@ -24,10 +24,8 @@ export {export { LINEAR_CHANNEL_DEFAULT_ROUTE } from "#public/channels/linear/constants.js";export { defaultLinearAuth, defaultOnAgentSession } from "#public/channels/linear/defaults.js";export {- LINEAR_HITL_MARKER_PREFIX,+ linearInputRequestSignal,renderLinearInputRequests,- resolveLinearPromptInputResponses,- stripLinearHitlMarker,} from "#public/channels/linear/hitl.js";export {formatLinearContextBlock,diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.tsindex 6f8aa6fa9..ff519972a 100644--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts@@ -7,7 +7,6 @@ import { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";-import { renderLinearInputRequests } from "#public/channels/linear/hitl.js";import { linearChannel, type LinearChannelState } from "#public/channels/linear/linearChannel.js";import { signLinearWebhookBody } from "#public/channels/linear/verify.js";import type { InputRequest } from "#runtime/input/types.js";@@ -181,41 +180,8 @@ describe("linearChannel inbound Agent Session events", () => {});});- it("resolves prompted events into input responses when the latest elicitation has eve metadata", async () => {- const elicitation = renderLinearInputRequests([- makeRequest({- options: [- { id: "approve", label: "Approve" },- { id: "deny", label: "Deny" },- ],- }),- ]);- const fetchMock = vi.fn().mockResolvedValue(- jsonResponse({- data: {- agentSession: {- activities: {- nodes: [- {- content: {- __typename: "AgentActivityElicitationContent",- body: elicitation,- type: "elicitation",- },- id: "activity_1",- updatedAt: "2026-06-08T12:00:00.000Z",- },- ],- },- },- },- }),- );- const channel = linearChannel({- api: { apiBaseUrl: "https://linear.test/graphql", fetch: fetchMock },- credentials: { accessToken: "linear-token", webhookSecret: SECRET },- });-+ it("delivers prompted values as messages for the harness to resolve", async () => {+ const channel = linearChannel({ credentials: { webhookSecret: SECRET } });const { send } = await firePost(channel,signedRequest(@@ -233,7 +199,7 @@ describe("linearChannel inbound Agent Session events", () => {expect(send).toHaveBeenCalledTimes(1);const [payload] = send.mock.calls[0]!;- expect(payload.inputResponses).toEqual([{ optionId: "approve", requestId: "call_1" }]);+ expect(payload.inputResponses).toBeUndefined();expect(payload.message).toBe("approve");});@@ -264,6 +230,65 @@ describe("linearChannel inbound Agent Session events", () => {});describe("linearChannel default event handlers", () => {+ it("posts input requests with native Linear select metadata and no visible marker", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ jsonResponse({+ data: {+ agentActivityCreate: {+ agentActivity: { id: "activity_1" },+ success: true,+ },+ },+ }),+ );+ const adapter = withState(+ getAdapter(+ linearChannel({+ api: { apiBaseUrl: "https://linear.test/graphql", fetch: fetchMock },+ credentials: { accessToken: "linear-token", webhookSecret: SECRET },+ }),+ ),+ { agentSessionId: "agent_session_1" },+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());++ await callEvent(+ adapter,+ makeEvent("input.requested", {+ requests: [+ makeRequest({+ allowFreeform: true,+ options: [+ { id: "alpha", label: "Alpha" },+ { id: "beta", label: "Beta" },+ ],+ }),+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ const input = (requestBody(fetchMock.mock.calls[0]?.[1]).variables as any).input;+ expect(input).toMatchObject({+ agentSessionId: "agent_session_1",+ content: {+ body: "Approve deployment?\n\n1. Alpha\n2. Beta\n\nYou can also reply with a custom answer.",+ type: "elicitation",+ },+ signal: "select",+ signalMetadata: {+ options: [+ { label: "Alpha", value: "alpha" },+ { label: "Beta", value: "beta" },+ ],+ },+ });+ expect(input.content.body).not.toContain("eve-input");+ });+it("posts completed messages as Linear response activities", async () => {const fetchMock = vi.fn().mockResolvedValue(jsonResponse({diff --git a/packages/eve/src/public/channels/linear/linearChannel.ts b/packages/eve/src/public/channels/linear/linearChannel.tsindex 6cbc2d7a9..4539843a8 100644--- a/packages/eve/src/public/channels/linear/linearChannel.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.ts@@ -14,7 +14,6 @@ import {import type { LinearChannelCredentials } from "#public/channels/linear/auth.js";import { LINEAR_CHANNEL_DEFAULT_ROUTE } from "#public/channels/linear/constants.js";import { createDefaultEvents, defaultOnAgentSession } from "#public/channels/linear/defaults.js";-import { resolveLinearPromptInputResponses } from "#public/channels/linear/hitl.js";import {formatLinearContextBlock,linearContinuationToken,@@ -36,7 +35,6 @@ import {} from "#public/definitions/channel.js";import { isObject } from "#shared/guards.js";import type { JsonObject } from "#shared/json.js";-import type { InputResponse } from "#runtime/input/types.js";const log = createLogger("linear.channel");@@ -344,12 +342,6 @@ async function dispatchAgentSession(input: {const result = await input.onAgentSession(context, event);if (result === null) return;- const body = event.agentActivity?.body;- const inputResponses =- event.action === "prompted" && body !== undefined- ? await resolvePromptResponses({ body, config: input.config, event })- : [];-await input.send({context: [@@ -357,7 +349,6 @@ async function dispatchAgentSession(input: {...event.previousComments,...(result.context ?? []),],- inputResponses,message: messageFromLinearAgentSessionEvent(event),},{@@ -368,25 +359,6 @@ async function dispatchAgentSession(input: {);}-async function resolvePromptResponses(input: {- readonly body: string;- readonly config: LinearChannelConfig;- readonly event: LinearAgentSessionEvent;-}): Promise<readonly InputResponse[]> {- try {- const activities = await listLinearAgentSessionActivities({- api: input.config.api,- credentials: input.config.credentials,- agentSessionId: input.event.agentSession.id,- last: 20,- });- return resolveLinearPromptInputResponses({ activities, body: input.body });- } catch (error) {- log.warn("linear HITL activity lookup failed — treating prompt as a message", { error });- return [];- }-}-async function resolveReceiveSession(target: Record<string, unknown>,config: LinearChannelConfig,