Skip to content

An open-source, faster Devin alternative

TypeScript

agent, sdk, react: Linear agent and ask seam (work 037, Phase 0 step 7)

Igor Zalutski8bae68cb7a08
diff --git a/agent/src/index.test.ts b/agent/src/index.test.ts
index 958732be..221f0bb3 100644
--- a/agent/src/index.test.ts
+++ b/agent/src/index.test.ts
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
+ ASK_TOOL,
bearer,
defineConnection,
defineMemory,
@@ -8,6 +9,7 @@ import {
documentMemory,
githubApp,
httpMemory,
+ linearAgent,
useConnection,
useInput,
useMemory,
@@ -599,3 +601,27 @@ test("defineTool refuses a result tool that waits for approval", () => {
/waits for approval cannot be the result tool/,
);
});
+
+test("linearAgent defines a frozen connection to the agent's own Linear app", () => {
+ const connection = defineConnection({ id: "linear", provider: linearAgent() });
+ assert.deepEqual(JSON.parse(JSON.stringify(connection)), {
+ kind: "connection",
+ id: "linear",
+ provider: { kind: "linear-agent" },
+ });
+ assert.ok(Object.isFrozen(connection));
+ assert.ok(Object.isFrozen(connection.provider));
+});
+
+test("defineTool reserves the question tool's id", () => {
+ assert.equal(ASK_TOOL, "ask");
+ assert.throws(
+ () =>
+ defineTool({
+ name: "ask",
+ description: "Ask something.",
+ run: () => "asked",
+ }),
+ /platform's question tool/,
+ );
+});
diff --git a/agent/src/index.ts b/agent/src/index.ts
index cb600178..cf434942 100644
--- a/agent/src/index.ts
+++ b/agent/src/index.ts
@@ -94,9 +94,90 @@ export interface OutcomeEvent {
readonly result?: { readonly text: string; readonly truncated?: boolean };
}
+/** One choice of a question; a selection sends `value` back. Each 1–80 characters. */
+export interface QuestionOption {
+ readonly label: string;
+ readonly value: string;
+}
+
+/** How this input answered the session's open question. */
+export interface QuestionAnswer {
+ readonly questionId: string;
+ /** What the person wrote or selected. */
+ readonly text: string;
+ /** The chosen option's value, when the text matched an option by value or label. */
+ readonly value?: string;
+}
+
+/**
+ * An input that arrived while a question was open without answering it.
+ * Held inputs never run as turns of their own: they are delivered, in
+ * arrival order, with the answer.
+ */
+export interface HeldInput {
+ readonly text?: string;
+ readonly payload?: DataValue;
+ readonly channel?: Readonly<ChannelMessageContext>;
+ readonly receivedAt: string;
+ /** When the provider says it was written, when it says. */
+ readonly providerTime?: string;
+}
+
interface BasicAgentInput {
readonly text?: string;
readonly payload?: DataValue;
+ /**
+ * Present only when this input answers the question an earlier turn
+ * asked with `ask`. Anything else written meanwhile is in `steering`.
+ */
+ readonly answer?: Readonly<QuestionAnswer>;
+ /**
+ * Inputs written while the question was open that did not answer it, in
+ * order. Read them before acting on the answer: they may change what the
+ * answer should mean.
+ */
+ readonly steering?: readonly Readonly<HeldInput>[];
+}
+
+/**
+ * The `payload` of a turn started from Linear: `source: "channel"`,
+ * `channel.provider: "linear"`, `channel.conversationId` the Linear agent
+ * session, `channel.workspaceId` the Linear workspace. `text` is Linear's
+ * prompt context when the session began, then each message's body.
+ */
+export interface LinearInputPayload {
+ readonly action: "created" | "prompted";
+ /** The issue as this message carried it. */
+ readonly issue: {
+ readonly id: string;
+ readonly identifier: string;
+ readonly title: string;
+ readonly description?: string | null;
+ readonly url: string;
+ readonly team: { readonly id: string; readonly key: string; readonly name: string };
+ };
+ /**
+ * Read from Linear when the session started and fixed for its life: the
+ * issue's parent at that time, and whether this agent's own Linear app
+ * created the issue. What they mean is the agent's decision.
+ */
+ readonly origin: {
+ readonly parent?: { readonly id: string; readonly identifier: string };
+ readonly createdByAgent: boolean;
+ };
+ readonly session: {
+ readonly id: string;
+ readonly url?: string;
+ /** The person responsible for the session; absent when automation started it. */
+ readonly creator?: { readonly id: string; readonly name: string };
+ };
+ readonly promptContext?: string;
+ /** The thread's root comment, when the session is a comment thread. */
+ readonly comment?: { readonly id: string; readonly body: string };
+ /** Earlier comments of that thread, as Linear sent them. */
+ readonly previousComments?: DataValue;
+ /** Workspace and team guidance for agents, as Linear sent it. */
+ readonly guidance?: DataValue;
}
export type AgentInput =
@@ -195,6 +276,20 @@ export interface GitHubConnectionDefinition extends ConnectionReference {
readonly provider: GitHubAppProvider;
}
+export interface LinearAgentProvider {
+ readonly kind: "linear-agent";
+}
+
+/**
+ * Linear's GraphQL API as this agent's own Linear app: `POST /graphql` on
+ * `https://api.linear.app`, with the app's token attached on the way out.
+ * The token is the environment's Linear connection for this agent; the
+ * agent never sees it.
+ */
+export interface LinearConnectionDefinition extends ConnectionReference {
+ readonly provider: LinearAgentProvider;
+}
+
export interface McpServerDefinition extends ResourceReference {
readonly kind: "mcp";
readonly url: string;
@@ -676,6 +771,9 @@ function identifier(value: string, kind: string): string {
const OPENCOMPUTER_USER_AGENT =
"OpenComputer-Agent/1 (+https://opencomputer.dev)";
+/** The platform's question tool, selected with `useTool("ask")`. No defined tool may use the id. */
+export const ASK_TOOL = "ask";
+
export function useSecret(
name: string,
options: { scope?: SecretScope } = {},
@@ -743,6 +841,16 @@ export function githubApp(options: {
});
}
+/**
+ * The agent's own Linear app as a connection provider. Requests go to
+ * Linear's GraphQL API with the token of the Linear connection bound to this
+ * agent in the session's environment; with it the agent writes documents,
+ * sub-issues, comments and status changes as itself.
+ */
+export function linearAgent(): LinearAgentProvider {
+ return Object.freeze({ kind: "linear-agent" });
+}
+
/**
* A service the platform holds an OAuth credential for.
*
@@ -963,6 +1071,11 @@ interface GitHubConnectionInput {
provider: GitHubAppProvider;
}
+interface LinearConnectionInput {
+ id: string;
+ provider: LinearAgentProvider;
+}
+
export function defineConnection(
input: HttpConnectionInput,
): HttpConnectionDefinition;
@@ -970,14 +1083,25 @@ export function defineConnection(
input: GitHubConnectionInput,
): GitHubConnectionDefinition;
export function defineConnection(
- input: HttpConnectionInput | GitHubConnectionInput,
-): HttpConnectionDefinition | GitHubConnectionDefinition {
+ input: LinearConnectionInput,
+): LinearConnectionDefinition;
+export function defineConnection(
+ input: HttpConnectionInput | GitHubConnectionInput | LinearConnectionInput,
+):
+ | HttpConnectionDefinition
+ | GitHubConnectionDefinition
+ | LinearConnectionDefinition {
const id = identifier(input.id, "defineConnection");
if ("provider" in input) {
- if (input.provider?.kind !== "github-app") {
+ const kind = input.provider?.kind;
+ if (kind !== "github-app" && kind !== "linear-agent") {
throw new Error("defineConnection() received an unsupported provider");
}
- return Object.freeze({ kind: "connection", id, provider: input.provider });
+ return Object.freeze({
+ kind: "connection",
+ id,
+ provider: input.provider,
+ }) as GitHubConnectionDefinition | LinearConnectionDefinition;
}
const origin = new URL(input.origin);
if (origin.protocol !== "https:" || origin.pathname !== "/") {
@@ -1520,6 +1644,11 @@ export function defineTool<Output extends DataValue = DataValue>(
"Tool IDs may contain only letters, numbers, underscores, and hyphens",
);
}
+ if (id === ASK_TOOL) {
+ throw new Error(
+ `Tool id ${JSON.stringify(ASK_TOOL)} is the platform's question tool; select it with useTool("${ASK_TOOL}") and rename this tool`,
+ );
+ }
if (!input.description.trim()) {
throw new Error("defineTool requires a non-empty description");
}
@@ -1625,6 +1754,14 @@ export const useInput = (): Readonly<AgentInput> => hooks().useInput();
export const useCurrentInput = useInput;
export const useModel = (model: ModelSelection): void =>
hooks().useModel(model);
+/**
+ * Selects a tool for this render: a tool defined with `defineTool`, or
+ * `"ask"`, the platform's question tool. `ask` takes `{ text, options? }`
+ * (`text` 1–4000 characters; at most six `{ label, value }` options, each
+ * 1–80 characters) and ends the turn with that question open. The person's
+ * reply arrives as the next input with `answer` set; anything written
+ * meanwhile arrives with it as `steering`.
+ */
export const useTool = (tool: string | ResourceReference): void =>
hooks().useTool(tool);
export const useConnection = (connection: string | ResourceReference): void =>
diff --git a/react/src/events.test.ts b/react/src/events.test.ts
index 81334678..502a2660 100644
--- a/react/src/events.test.ts
+++ b/react/src/events.test.ts
@@ -264,3 +264,41 @@ test("a terminal turn event settles every tool row without a completion, and the
]);
assert.deepEqual(cancelled?.result, turn.result);
});
+
+test("a turn that asks completes with outcome question and opens the question until it is answered", () => {
+ const asked = applyEvents(emptyTimeline(), [
+ { seq: 1, turnId: "t1", type: "message.received", data: { input: "Fix the login page." } },
+ { seq: 2, turnId: "t1", type: "turn.started", data: {} },
+ {
+ seq: 3,
+ turnId: "t1",
+ type: "question.asked",
+ data: { questionId: "q1", text: "Plan first, or go?", options: [{ label: "Go", value: "go" }, { bad: true }] },
+ },
+ { seq: 4, turnId: "t1", type: "turn.completed", data: { outcome: "question", questionId: "q1" } },
+ ]);
+ assert.deepEqual(asked.question, {
+ id: "q1",
+ text: "Plan first, or go?",
+ options: [{ label: "Go", value: "go" }],
+ turnId: "t1",
+ });
+ assert.equal(asked.isRunning, false);
+ const [first] = turnsOf(asked);
+ assert.equal(first?.status, "completed");
+ assert.equal(first?.outcome, "question");
+
+ const unrelated = applyEvents(asked, [
+ { seq: 5, turnId: "t2", type: "question.answered", data: { questionId: "q0", answer: { questionId: "q0", text: "go" } } },
+ ]);
+ assert.equal(unrelated.question?.id, "q1");
+ const answered = applyEvents(unrelated, [
+ { seq: 6, turnId: "t2", type: "question.answered", data: { questionId: "q1", answer: { questionId: "q1", text: "go", value: "go" } } },
+ ]);
+ assert.equal(answered.question, null);
+
+ const closed = applyEvents(asked, [
+ { seq: 5, type: "question.closed", data: { questionId: "q1", reason: "stopped" } },
+ ]);
+ assert.equal(closed.question, null);
+});
diff --git a/react/src/events.ts b/react/src/events.ts
index 07ec6c91..cf52ec7f 100644
--- a/react/src/events.ts
+++ b/react/src/events.ts
@@ -70,6 +70,25 @@ export interface ToolCall {
status: ToolCallStatus;
}
+/** One choice of a question; a selection sends `value` back. */
+export interface QuestionOption {
+ label: string;
+ value: string;
+}
+
+/**
+ * The question the session is waiting on, from `question.asked`; cleared by
+ * `question.answered` or `question.closed` for the same id.
+ */
+export interface Question {
+ id: string;
+ text: string;
+ /** Empty when the answer is free text. */
+ options: QuestionOption[];
+ /** The turn that asked. */
+ turnId?: string;
+}
+
/** The public failure a `turn.failed` event carries. */
export interface TurnFailure {
code: string;
@@ -93,6 +112,8 @@ export interface Turn {
*/
result?: DataValue;
failure?: TurnFailure;
+ /** `"question"` when the turn completed by asking; the session's `question` holds what it asked. */
+ outcome?: "question";
}
/** What the timeline keeps per turn; `Turn` adds the messages. */
@@ -103,6 +124,7 @@ export interface TurnRecord {
toolCalls: ToolCall[];
result?: DataValue;
failure?: TurnFailure;
+ outcome?: "question";
/** The `seq` of the first event that named the turn; orders the turns. */
seq: number;
}
@@ -114,6 +136,8 @@ export interface SessionTimeline {
cursor: number;
/** Every turn the log has recorded, by id, as of the cursor. */
turns: Record<string, TurnRecord>;
+ /** The open question, or null. */
+ question: Question | null;
isRunning: boolean;
ended: boolean;
}
@@ -124,6 +148,7 @@ export function emptyTimeline(): SessionTimeline {
memorySaves: [],
cursor: 0,
turns: {},
+ question: null,
isRunning: false,
ended: false,
};
@@ -251,7 +276,12 @@ export function applyTurnEvent(
next = { ...current, status: "running" };
break;
case "turn.completed":
- next = { ...current, status: "completed", toolCalls: settleToolCalls(current.toolCalls, "completed") };
+ next = {
+ ...current,
+ status: "completed",
+ toolCalls: settleToolCalls(current.toolCalls, "completed"),
+ ...(fields.outcome === "question" ? { outcome: "question" as const } : {}),
+ };
break;
case "turn.failed":
next = {
@@ -377,6 +407,27 @@ export function applyEvent(
: message,
);
return next;
+ case "question.asked": {
+ const options = Array.isArray(fields.options)
+ ? fields.options.flatMap((option: unknown) => {
+ const entry = option as { label?: unknown; value?: unknown } | null;
+ return entry && typeof entry.label === "string" && typeof entry.value === "string"
+ ? [{ label: entry.label, value: entry.value }]
+ : [];
+ })
+ : [];
+ next.question = {
+ id: text(fields.questionId),
+ text: text(fields.text),
+ options,
+ ...(event.turnId ? { turnId: event.turnId } : {}),
+ };
+ return next;
+ }
+ case "question.answered":
+ case "question.closed":
+ if (timeline.question?.id === text(fields.questionId)) next.question = null;
+ return next;
case "memory.saved": {
const save = memorySaveFromEvent(event);
if (save) next.memorySaves = [...timeline.memorySaves, save];
diff --git a/react/src/index.ts b/react/src/index.ts
index f1abdb5a..2df12b36 100644
--- a/react/src/index.ts
+++ b/react/src/index.ts
@@ -13,6 +13,7 @@ import {
type AgentMessage,
type DataValue,
type MemorySave,
+ type Question,
type SessionTimeline,
type Turn,
type TurnStatus,
@@ -30,6 +31,8 @@ export {
type AgentMessage,
type DataValue,
type MemorySave,
+ type Question,
+ type QuestionOption,
type SessionTimeline,
type ToolCall,
type ToolCallStatus,
@@ -103,6 +106,11 @@ export interface SendOptions {
idempotencyKey?: string;
/** Structured input the agent reads as `useInput().payload`, beside the text. */
payload?: DataValue;
+ /**
+ * The id of the open question this input answers. `answer()` sets it.
+ * Naming a question that is no longer open is refused with `question_stale`.
+ */
+ answers?: string;
}
/**
@@ -147,6 +155,13 @@ export interface UseAgentResult {
* settlement, which arrives through `turns`.
*/
stop: () => Promise<void>;
+ /**
+ * The question the agent is waiting on, or null. While it is open, input
+ * sent with `send` is held and reaches the agent with the answer.
+ */
+ question: Question | null;
+ /** Answers the question with that id: `send(text, { answers: questionId })`. */
+ answer: (questionId: string, text: string, options?: Omit<SendOptions, "answers">) => Promise<SendReceipt>;
sessionId: string | undefined;
/** A turn is running in the log, or a locally admitted turn has not settled. Queued replay alone is false. */
isRunning: boolean;
@@ -375,6 +390,9 @@ export function useAgent(
...(sendOptions.payload !== undefined
? { payload: sendOptions.payload }
: {}),
+ ...(sendOptions.answers !== undefined
+ ? { answers: sendOptions.answers }
+ : {}),
}),
},
),
@@ -629,6 +647,12 @@ export function useAgent(
}
}, [request]);
+ const answer = useCallback(
+ (questionId: string, value: string, answerOptions: Omit<SendOptions, "answers"> = {}) =>
+ send(value, { ...answerOptions, answers: questionId }),
+ [send],
+ );
+
const turns = useMemo(() => turnsOf(timeline), [timeline]);
return {
@@ -636,6 +660,8 @@ export function useAgent(
turns,
send,
stop,
+ question: timeline.question,
+ answer,
sessionId,
isRunning: timeline.isRunning || admitted.length > 0,
isReplaying,
diff --git a/sdks/typescript/src/agents/client.test.ts b/sdks/typescript/src/agents/client.test.ts
index 6587b89d..7b387d29 100644
--- a/sdks/typescript/src/agents/client.test.ts
+++ b/sdks/typescript/src/agents/client.test.ts
@@ -190,6 +190,32 @@ describe("OpenComputer client", () => {
expect(api.last().body).toEqual({ input: "again", mode: "steer" });
});
+ it("answers the open question by naming it, and reads the question from the session", async () => {
+ const question = { id: "q_1", text: "Plan first, or go?", options: [{ label: "Go", value: "go" }], askedAt: "t" };
+ const api = fakeApi({
+ "GET /api/managed-agents/sessions/ses_1": () =>
+ Response.json({
+ id: "ses_1",
+ agentId: "worker",
+ deploymentId: "dep_1",
+ status: "idle",
+ source: "api",
+ turns: [{ id: "turn_1", input: "Fix it.", mode: "queue", status: "completed", outcome: "question", createdAt: "t", updatedAt: "t" }],
+ question,
+ createdAt: "t",
+ updatedAt: "t",
+ }),
+ "POST /api/managed-agents/sessions/ses_1/turns": () =>
+ Response.json({ turnId: "turn_2", status: "queued", duplicate: false }, { status: 202 }),
+ });
+ const client = oc(api);
+ const session = await client.sessions.get("ses_1");
+ expect(session.question).toEqual(question);
+ expect(session.turns[0]?.outcome).toBe("question");
+ await client.sessions.turns.send("ses_1", { input: "go", answers: "q_1" });
+ expect(api.last().body).toEqual({ input: "go", answers: "q_1" });
+ });
+
it("reads the event log from a cursor", async () => {
const events = [{ id: "e1", seq: 1, timestamp: "t", sessionId: "ses_1", type: "session.created", data: { agentId: "worker", deploymentId: "dep_1" } }];
const api = fakeApi({ "GET /api/managed-agents/sessions/ses_1/events": () => Response.json({ events }) });
diff --git a/sdks/typescript/src/agents/client.ts b/sdks/typescript/src/agents/client.ts
index 4e4a7361..050fec11 100644
--- a/sdks/typescript/src/agents/client.ts
+++ b/sdks/typescript/src/agents/client.ts
@@ -98,6 +98,7 @@ export class Turns {
const body: Record<string, unknown> = { input: params.input };
if (params.mode !== undefined) body.mode = params.mode;
if (params.payload !== undefined) body.payload = params.payload;
+ if (params.answers !== undefined) body.answers = params.answers;
const answer = await this.http.send("POST", `/sessions/${segment(sessionId)}/turns`, shapes.turnReceipt, {
body,
headers: params.idempotencyKey !== undefined ? { "idempotency-key": params.idempotencyKey } : undefined,
diff --git a/sdks/typescript/src/agents/shapes.ts b/sdks/typescript/src/agents/shapes.ts
index 3acc31f7..90976416 100644
--- a/sdks/typescript/src/agents/shapes.ts
+++ b/sdks/typescript/src/agents/shapes.ts
@@ -33,10 +33,12 @@ import type {
SessionCreated,
SessionEvent,
SessionPage,
+ SessionQuestion,
SessionResult,
SessionStatus,
SessionSummary,
Turn,
+ TurnOutcome,
TurnStatus,
Webhook,
WebhookRequest,
@@ -217,11 +219,19 @@ const turnOutcomeDelivery: Shape<TurnOutcomeDelivery> = object({
updatedAt: string,
});
+const sessionQuestion: Shape<SessionQuestion> = object({
+ id: string,
+ text: string,
+ options: array(object({ label: string, value: string })),
+ askedAt: string,
+});
+
export const turn: Shape<Turn> = object({
id: string,
input: string,
mode: oneOf("queue", "steer", "interrupt"),
status: stringAs<TurnStatus>(),
+ outcome: optional(stringAs<TurnOutcome>()),
payload: optional(jsonValue),
deliveries: optional(array(turnOutcomeDelivery)),
createdAt: string,
@@ -260,6 +270,7 @@ export const session: Shape<Session> = object({
externalReference: optional(string),
revision: optional(number),
result: optional(nullable(sessionResult)),
+ question: optional(nullable(sessionQuestion)),
createdAt: string,
updatedAt: string,
}) as Shape<Session>;
diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.ts
index 2ceb135b..ca407940 100644
--- a/sdks/typescript/src/agents/types.ts
+++ b/sdks/typescript/src/agents/types.ts
@@ -43,6 +43,34 @@ export type TurnMode = "queue" | "steer" | "interrupt";
export type TurnStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | (string & {});
+/** What a settled turn came to beyond its status. `question`: a completed turn that ended by asking. */
+export type TurnOutcome = "question" | (string & {});
+
+/** One choice of a question; a selection sends `value` back. */
+export interface QuestionOption {
+ label: string;
+ value: string;
+}
+
+/**
+ * The question a session is waiting on, asked by the agent with `ask`.
+ * Answer it with `turns.send(id, { input, answers: question.id })`.
+ */
+export interface SessionQuestion {
+ id: string;
+ text: string;
+ /** Empty when the question is free text. */
+ options: QuestionOption[];
+ askedAt: string;
+}
+
+/** How an input answered a question; `value` when the text matched an option by value or label. */
+export interface QuestionAnswer {
+ questionId: string;
+ text: string;
+ value?: string;
+}
+
/** One entry of a session's `turns`. */
export interface Turn {
id: string;
@@ -50,6 +78,8 @@ export interface Turn {
input: string;
mode: TurnMode;
status: TurnStatus;
+ /** `question` on a completed turn that ended by asking. */
+ outcome?: TurnOutcome;
/** The structured input sent with the turn. */
payload?: DataValue;
/** Present when an event subscription selected the turn's outcome. */
@@ -102,6 +132,8 @@ export interface Session {
revision?: number;
/** The latest committed output of the result tool, or `null` when none was committed. */
result?: SessionResult | null;
+ /** The question the session is waiting on, or `null`. Independent of `result`. */
+ question?: SessionQuestion | null;
createdAt: string;
updatedAt: string;
}
@@ -172,6 +204,13 @@ export interface SendTurnParams {
mode?: TurnMode;
/** Structured input the agent reads as `useInput().payload`; at most 32 KB of JSON. */
payload?: DataValue;
+ /**
+ * The id of the open question this input answers; the agent reads it as
+ * `useInput().answer`. Naming any other question is `409 question_stale`.
+ * Without it, input sent while a question is open is held and delivered
+ * with the answer, not run on its own.
+ */
+ answers?: string;
}
/** What a session's activity looks like from a list row. */
@@ -304,7 +343,14 @@ export type SessionEvent =
| (EventBase & { type: "turn.steered"; data: { activeTurnId: string } })
| (EventBase & { type: "turn.interrupted"; data: { interruptedTurnIds: string[] } })
| (EventBase & { type: "turn.started"; data: Record<string, never> })
- | (EventBase & { type: "turn.completed"; data: Record<string, never> })
+ | (EventBase & {
+ type: "turn.completed";
+ /** Empty, or `{ outcome: "question", questionId }` when the turn ended by asking. */
+ data: { outcome?: TurnOutcome; questionId?: string };
+ })
+ | (EventBase & { type: "question.asked"; data: { questionId: string; text: string; options: QuestionOption[] } })
+ | (EventBase & { type: "question.answered"; data: { questionId: string; answer: QuestionAnswer } })
+ | (EventBase & { type: "question.closed"; data: { questionId: string; reason: "stopped" | "replaced" | (string & {}) } })
| (EventBase & { type: "turn.failed"; data: Failure })
| (EventBase & {
type: "turn.cancelled";