An open-source, faster Devin alternative
TypeScript
cli: compile linearAgent() connections and reserve the ask tool id (work 037, S4)
Igor Zalutskic95b201de092
diff --git a/cli/src/api.ts b/cli/src/api.tsindex f6f31b86..2c64927f 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -1349,6 +1349,10 @@ export class OpenComputerClient {permissions: Record<string, "read" | "write">;};}>;+ linearConnections: Array<{+ id: string;+ provider: { kind: "linear-agent" };+ }>;memory: MemoryDeclaration[];models: Array<{ provider: string; model: string }>;projectDeployment?: {diff --git a/cli/src/dev.ts b/cli/src/dev.tsindex b3f0a331..4fa07133 100644--- a/cli/src/dev.ts+++ b/cli/src/dev.ts@@ -68,6 +68,7 @@ async function registerBuiltDeployment(connections: built.connections,httpConnections: built.httpConnections,githubConnections: built.githubConnections,+ linearConnections: built.linearConnections,memory: built.memory,models: built.models,...(projectDeployment ? { projectDeployment } : {}),diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex 21960b3a..40115bad 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -361,6 +361,7 @@ export default function Agent() {connections: string[];httpConnections: unknown[];githubConnections: unknown[];+ linearConnections: unknown[];mcpServers: string[];mcpServerDefinitions: Array<{id: string;@@ -380,6 +381,7 @@ export default function Agent() {connections: [],httpConnections: [],githubConnections: [],+ linearConnections: [],mcpServers: ["docs"],mcpServerDefinitions: [{ id: "docs", url: "https://mcp.example.com/" }],memory: [],@@ -1023,6 +1025,235 @@ export default defineConnection({}});+test("the compiler records a Linear agent connection and the ask tool", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-linear-agent-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await mkdir(resolve(initialized.agentRoot, "connections"), {+ recursive: true,+ });+ await writeFile(+ resolve(initialized.agentRoot, "connections", "linear.ts"),+ `import { defineConnection, linearAgent } from "@opencomputer/agent";++export const linear = defineConnection({+ id: "linear",+ provider: linearAgent(),+});+`,+ );+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useConnection, useInput, useTool } from "@opencomputer/agent";+import { linear } from "./connections/linear.js";++export default function Agent() {+ useConnection(linear);+ useTool("ask");+ return useInput().answer ? "Act on the answer." : "Ask before acting.";+}+`,+ );++ const built = await buildAgentArtifact(initialized.agentRoot);+ // The id counts as a declared connection, as a GitHub one does: the+ // backend admits a provider connection only when `connections` names it.+ assert.deepEqual(built.connections, ["linear"]);+ assert.deepEqual(built.httpConnections, []);+ assert.deepEqual(built.githubConnections, []);+ assert.deepEqual(built.linearConnections, [+ { id: "linear", provider: { kind: "linear-agent" } },+ ]);+ const runtimeRoot = await agentRuntimeDirectory(initialized.agentRoot);+ const manifest = JSON.parse(+ await readFile(+ resolve(runtimeRoot, ".opencomputer", "reactive.json"),+ "utf8",+ ),+ ) as { linearConnections: unknown[]; tools: string[] };+ assert.deepEqual(manifest.linearConnections, built.linearConnections);+ // `ask` has no defineTool(); the literal selection is what records it.+ assert.deepEqual(manifest.tools, ["ask"]);++ // The emitted shim is what the bundled agent imports at run time.+ const shim = (await import(+ `${pathToFileURL(resolve(runtimeRoot, "opencomputer-agent.js")).href}?test=${crypto.randomUUID()}`+ )) as {+ ASK_TOOL: string;+ linearAgent: () => { kind: string };+ defineConnection: (input: Record<string, unknown>) => {+ kind: string;+ id: string;+ provider: { kind: string };+ };+ };+ assert.equal(shim.ASK_TOOL, "ask");+ assert.deepEqual(+ shim.defineConnection({ id: "linear", provider: shim.linearAgent() }),+ { kind: "connection", id: "linear", provider: { kind: "linear-agent" } },+ );+ assert.throws(+ () => shim.defineConnection({ id: "x", provider: { kind: "jira" } }),+ /unsupported provider/,+ );++ // useTool(ASK_TOOL) selects the same tool as the literal.+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { ASK_TOOL, useConnection, useTool } from "@opencomputer/agent";+import { linear } from "./connections/linear.js";++export default function Agent() {+ useConnection(linear);+ useTool(ASK_TOOL);+ return "Ask before acting.";+}+`,+ );+ await buildAgentArtifact(initialized.agentRoot);+ assert.deepEqual(+ (+ JSON.parse(+ await readFile(+ resolve(+ await agentRuntimeDirectory(initialized.agentRoot),+ ".opencomputer",+ "reactive.json",+ ),+ "utf8",+ ),+ ) as { tools: string[] }+ ).tools,+ ["ask"],+ );+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("the compiler rejects Linear connections it cannot record as written", async () => {+ const parent = await mkdtemp(+ resolve(tmpdir(), "opencomputer-linear-invalid-"),+ );+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await mkdir(resolve(initialized.agentRoot, "connections"), {+ recursive: true,+ });+ const connection = resolve(+ initialized.agentRoot,+ "connections",+ "linear.ts",+ );+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import "./connections/linear.js";+export default function Agent() { return "Use Linear."; }+`,+ );+ const rejects = async (source: string, pattern: RegExp) => {+ await writeFile(connection, source);+ await assert.rejects(buildAgentArtifact(initialized.agentRoot), pattern);+ };+ await rejects(+ `import { defineConnection, linearAgent } from "@opencomputer/agent";+export default defineConnection({+ id: "linear",+ provider: linearAgent({ workspace: "acme" }),+});+`,+ /Connection linear linearAgent\(\) takes no options/,+ );+ await rejects(+ `import { defineConnection, linearAgent } from "@opencomputer/agent";+const provider = linearAgent();+export default defineConnection({ id: "linear", provider: provider });+`,+ /provider must be an inline githubApp\(\) or linearAgent\(\) call/,+ );+ await rejects(+ `import { defineConnection, linearAgent } from "@opencomputer/agent";+export default defineConnection({+ id: "linear",+ provider: linearAgent(),+ origin: "https://api.linear.app",+});+`,+ /Linear connection linear does not support the origin option/,+ );+ await rejects(+ `import { defineConnection, githubApp, linearAgent } from "@opencomputer/agent";+export const linear = defineConnection({ id: "work", provider: linearAgent() });+export const github = defineConnection({+ id: "work",+ provider: githubApp({ permissions: { contents: "read" } }),+});+`,+ /Connection id "work" is defined more than once/,+ );+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("the tool id ask is reserved for the platform's question tool", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-ask-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });+ await writeFile(+ resolve(initialized.agentRoot, "tools", "ask.ts"),+ `import { defineTool } from "@opencomputer/agent";++export const ask = defineTool({+ name: "ask",+ description: "Ask the user.",+ async run() {+ return "asked";+ },+});+`,+ );+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useTool } from "@opencomputer/agent";+import { ask } from "./tools/ask.js";++export default function Agent() {+ useTool(ask);+ return "Ask.";+}+`,+ );+ await assert.rejects(+ buildAgentArtifact(initialized.agentRoot),+ /tools\/ask\.ts defineTool\("ask"\): "ask" is the platform's question tool; select it with useTool\("ask"\)/,+ );++ // The runtime shim refuses it too, so a definition the compiler could+ // not read still fails at load.+ const path = resolve(parent, "shim.js");+ await writeFile(path, agentApiRuntimeSource());+ const shim = (await import(+ `${pathToFileURL(path).href}?test=${crypto.randomUUID()}`+ )) as { defineTool: (input: Record<string, unknown>) => unknown };+ assert.throws(+ () =>+ shim.defineTool({+ name: "ask",+ description: "Ask the user.",+ run: async () => "asked",+ }),+ /"ask" is the platform's question tool/,+ );+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});+test("the compiler records managed MCP server definitions", async () => {const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-mcp-"));const root = resolve(parent, "app");diff --git a/cli/src/project.ts b/cli/src/project.tsindex 34f7a3ab..39ab2846 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -41,6 +41,7 @@ export interface BuiltAgentArtifact {connections: string[];httpConnections: HttpConnectionManifest[];githubConnections: GitHubConnectionManifest[];+ linearConnections: LinearConnectionManifest[];memory: MemoryDeclaration[];models: Array<{ provider: string; model: string }>;body: Buffer;@@ -93,6 +94,19 @@ export interface GitHubConnectionManifest {};}+/**+ * `defineConnection({ id, provider: linearAgent() })`: Linear's GraphQL API as+ * the agent's own Linear app. The provider has no options; the token is the+ * environment's Linear connection bound to the agent, attached at egress.+ */+export interface LinearConnectionManifest {+ id: string;+ provider: { kind: "linear-agent" };+}++/** The platform's question tool. Selected with useTool("ask"); no defined tool may take the id. */+const ASK_TOOL = "ask";+export interface McpServerManifest {id: string;url: string;@@ -2647,12 +2661,22 @@ const GITHUB_APP_PERMISSION_KEYS = new Set(["pull_requests",]);-function definedGitHubConnections(+/**+ * Connections whose provider the platform holds the credential for:+ * `githubApp({ permissions })` and `linearAgent()`. Each must be written as+ * an inline call in the `defineConnection()` literal, so the deployment can+ * record the provider without running the module.+ */+function definedProviderConnections(source: string,path: string,-): GitHubConnectionManifest[] {+): {+ github: GitHubConnectionManifest[];+ linear: LinearConnectionManifest[];+} {const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);const definitions: GitHubConnectionManifest[] = [];+ const linear: LinearConnectionManifest[] = [];const visit = (node: ts.Node): void => {if (ts.isCallExpression(node) &&@@ -2672,6 +2696,23 @@ function definedGitHubConnections(objectProperty(input, "id"),"connection id",);+ const providerCall =+ ts.isCallExpression(providerExpression) &&+ ts.isIdentifier(providerExpression.expression)+ ? providerExpression+ : undefined;+ const providerName = providerCall+ ? (providerCall.expression as ts.Identifier).text+ : undefined;+ if (+ !providerCall ||+ (providerName !== "githubApp" && providerName !== "linearAgent")+ ) {+ throw new Error(+ `Connection ${id} provider must be an inline githubApp() or linearAgent() call`,+ );+ }+ const providerLabel = providerName === "githubApp" ? "GitHub" : "Linear";for (const property of input.properties) {if (!ts.isPropertyAssignment(property)) {throw new Error(@@ -2681,21 +2722,22 @@ function definedGitHubConnections(const name = staticPropertyName(property.name, `Connection ${id}`);if (name !== "id" && name !== "provider") {throw new Error(- `GitHub connection ${id} does not support the ${name} option`,+ `${providerLabel} connection ${id} does not support the ${name} option`,);}}- if (- !ts.isCallExpression(providerExpression) ||- !ts.isIdentifier(providerExpression.expression) ||- providerExpression.expression.text !== "githubApp"- ) {- throw new Error(- `Connection ${id} provider must be an inline githubApp() call`,- );+ if (providerName === "linearAgent") {+ // The provider has no options: the Linear workspace and app are the+ // environment's connection bound to the agent, never the source.+ if (providerCall.arguments.length > 0) {+ throw new Error(`Connection ${id} linearAgent() takes no options`);+ }+ linear.push({ id, provider: { kind: "linear-agent" } });+ ts.forEachChild(node, visit);+ return;}const options = literalCallArgument(- providerExpression,+ providerCall,`Connection ${id} githubApp()`,);if (!options) {@@ -2777,7 +2819,7 @@ function definedGitHubConnections(ts.forEachChild(node, visit);};visit(file);- return definitions;+ return { github: definitions, linear };}interface DefinedTool {@@ -3190,6 +3232,8 @@ export const githubApp = (options) => {}return Object.freeze({ kind: "github-app", permissions: Object.freeze(permissions) });};+export const linearAgent = () => Object.freeze({ kind: "linear-agent" });+export const ASK_TOOL = "ask";export const callService = async (request) => {const base = globalThis.process?.env?.OPENCOMPUTER_CONNECTIONS_URL;const token = globalThis.process?.env?.OPENCOMPUTER_CONNECTION_TOKEN;@@ -3246,7 +3290,7 @@ export const listServices = async (options = {}) => {export const defineConnection = (input) => {const connectionId = id(input.id, "defineConnection");if (input.provider) {- if (input.provider.kind !== "github-app") throw new Error("defineConnection() received an unsupported provider");+ if (input.provider.kind !== "github-app" && input.provider.kind !== "linear-agent") throw new Error("defineConnection() received an unsupported provider");return Object.freeze({ kind: "connection", id: connectionId, provider: input.provider });}const origin = new URL(input.origin);@@ -3300,6 +3344,7 @@ export const defineMcpServer = (input) => {export const defineTool = (input) => {const toolId = id(input.name, "defineTool");if (!/^[a-zA-Z0-9_-]+$/.test(toolId)) throw new Error("Invalid tool id " + JSON.stringify(toolId));+ if (toolId === ASK_TOOL) throw new Error("Tool id " + JSON.stringify(ASK_TOOL) + " is the platform's question tool; select it with useTool(" + JSON.stringify(ASK_TOOL) + ") and rename this tool");if (!String(input.description).trim()) throw new Error("defineTool requires a non-empty description");if (input.input && typeof input.input !== "object") throw new Error("defineTool input must be a JSON Schema object");if (input.output && typeof input.output !== "object") throw new Error("defineTool output must be a JSON Schema object");@@ -3663,6 +3708,14 @@ the product or support surface presented to users.candidate.path,sourceResolver,);+ // `ask` is the platform's question tool: the host registers it, and a+ // defined tool of the same id would leave the model two tools under one+ // name. defineTool() refuses it at load too; this fails the build first.+ if (defined.some((tool) => tool.id === ASK_TOOL)) {+ throw new Error(+ `${candidate.path} defineTool(${JSON.stringify(ASK_TOOL)}): ${JSON.stringify(ASK_TOOL)} is the platform's question tool; select it with useTool(${JSON.stringify(ASK_TOOL)}) and rename this tool`,+ );+ }if (defined.length > 0) {reactiveTools.push(...defined.map((tool) => tool.id));gatedTools.push(@@ -3720,10 +3773,20 @@ the product or support surface presented to users.const httpConnections = sourceModules.flatMap((module) =>definedHttpConnections(module.source, module.path),);- const githubConnections = sourceModules.flatMap((module) =>- definedGitHubConnections(module.source, module.path),+ const providerConnections = sourceModules.map((module) =>+ definedProviderConnections(module.source, module.path),);- const allConnections = [...httpConnections, ...githubConnections];+ const githubConnections = providerConnections.flatMap(+ (connections) => connections.github,+ );+ const linearConnections = providerConnections.flatMap(+ (connections) => connections.linear,+ );+ const allConnections = [+ ...httpConnections,+ ...githubConnections,+ ...linearConnections,+ ];const duplicateConnection = allConnections.find((connection, index) =>allConnections.findIndex(@@ -3772,7 +3835,13 @@ the product or support surface presented to users.);const declaredMemory = new Set(memory.map((declaration) => declaration.id));const tools = [- ...new Set([...reactiveTools, ...literalHookIds(agentSource, "useTool")]),+ ...new Set([+ ...reactiveTools,+ ...literalHookIds(agentSource, "useTool"),+ // useTool(ASK_TOOL), the exported constant, selects the same tool as+ // useTool("ask"); no defineTool() exists for it.+ ...(/\buseTool\(\s*ASK_TOOL\s*\)/.test(agentSource) ? [ASK_TOOL] : []),+ ]),].sort();for (const id of literalHookIds(agentSource, "useMemory")) {if (!declaredMemory.has(id)) {@@ -3816,6 +3885,7 @@ the product or support surface presented to users.].sort(),httpConnections,githubConnections,+ linearConnections,mcpServers: [...new Set([...mcpServerDefinitions.map((server) => server.id),@@ -3866,12 +3936,14 @@ export async function buildAgentArtifact(connections?: string[];httpConnections?: HttpConnectionManifest[];githubConnections?: GitHubConnectionManifest[];+ linearConnections?: LinearConnectionManifest[];memory?: MemoryDeclaration[];models?: Array<{ provider: string; model: string }>;};const connections = [...new Set(reactive.connections ?? [])].sort();const httpConnections = reactive.httpConnections ?? [];const githubConnections = reactive.githubConnections ?? [];+ const linearConnections = reactive.linearConnections ?? [];const memory = reactive.memory ?? [];const models = reactive.models ?? [];const body = Buffer.from(@@ -3888,6 +3960,7 @@ export async function buildAgentArtifact(connections,httpConnections,githubConnections,+ linearConnections,memory,models,body,diff --git a/cli/src/template.ts b/cli/src/template.tsindex 063a7185..94a4ff44 100644--- a/cli/src/template.ts+++ b/cli/src/template.ts@@ -7,6 +7,7 @@ import {readProjectResources,type GitHubConnectionManifest,type HttpConnectionManifest,+ type LinearConnectionManifest,type MemoryDeclaration,type ProjectResourceManifest,} from "./project.js";@@ -51,6 +52,7 @@ export interface TemplateBuildArtifact {connections: string[];httpConnections: HttpConnectionManifest[];githubConnections: GitHubConnectionManifest[];+ linearConnections: LinearConnectionManifest[];memory: MemoryDeclaration[];models: Array<{ provider: string; model: string }>;}@@ -330,6 +332,7 @@ export async function buildTemplateProject(connections: built.connections,httpConnections: built.httpConnections,githubConnections: built.githubConnections,+ linearConnections: built.linearConnections,memory: built.memory,models: built.models,});